parent
48d9f1dd5a
commit
9e02b7f3b3
196 changed files with 116992 additions and 29969 deletions
3
.gitignore
vendored
3
.gitignore
vendored
|
|
@ -10,5 +10,4 @@ CMakeUserPresets.json
|
|||
.idea/
|
||||
.claude/
|
||||
.tmp/
|
||||
AGENTS.md
|
||||
GEMINI.md
|
||||
.fetchcontent-cache/
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
cmake_minimum_required(VERSION 3.22)
|
||||
include(FetchContent)
|
||||
include(CMakeDependentOption)
|
||||
|
||||
project(box3d
|
||||
|
|
@ -9,6 +8,13 @@ project(box3d
|
|||
LANGUAGES C CXX
|
||||
)
|
||||
|
||||
# sokol's Metal backend is Objective-C; samples/host/sokol_app_impl.c and
|
||||
# samples/gfx/sokol_impl.c compile as OBJC on Apple. Enable the language here
|
||||
# so those source properties are honored.
|
||||
if(APPLE)
|
||||
enable_language(OBJC)
|
||||
endif()
|
||||
|
||||
# stuff to help debug cmake
|
||||
# message(STATUS "cmake tool chain: ${CMAKE_TOOLCHAIN_FILE}")
|
||||
# message(STATUS "cmake source dir: ${CMAKE_SOURCE_DIR}")
|
||||
|
|
@ -91,6 +97,15 @@ set(CMAKE_VERBOSE_MAKEFILE ON)
|
|||
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/bin")
|
||||
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/bin")
|
||||
|
||||
# Collect FetchContent downloads outside the build dir so a clean rebuild reuses them.
|
||||
# Must precede the first include(FetchContent)
|
||||
if(NOT FETCHCONTENT_BASE_DIR)
|
||||
set(FETCHCONTENT_BASE_DIR "${CMAKE_SOURCE_DIR}/.fetchcontent-cache"
|
||||
CACHE PATH "Shared FetchContent populate cache")
|
||||
endif()
|
||||
|
||||
include(FetchContent)
|
||||
|
||||
add_subdirectory(src)
|
||||
|
||||
# This hides samples, test, and doxygen from apps that use box3d via FetchContent
|
||||
|
|
@ -102,6 +117,10 @@ if(PROJECT_IS_TOP_LEVEL)
|
|||
option(BOX3D_VALIDATE "Enable heavy validation" ON)
|
||||
option(BOX3D_UNIT_TESTS "Build the Box3D unit tests" ON)
|
||||
|
||||
# Enable this for shader development using sokol-shdc.
|
||||
# This can be a large download, so this is disabled by default.
|
||||
option(BOX3D_BUILD_SHADERS "Recompile shaders with sokol-shdc" OFF)
|
||||
|
||||
if(BOX3D_UNIT_TESTS OR BOX3D_SAMPLES OR BOX3D_BENCHMARKS)
|
||||
|
||||
# Emscripten pthread support
|
||||
|
|
|
|||
Binary file not shown.
311
extern/glad/include/KHR/khrplatform.h
vendored
311
extern/glad/include/KHR/khrplatform.h
vendored
|
|
@ -1,311 +0,0 @@
|
|||
#ifndef __khrplatform_h_
|
||||
#define __khrplatform_h_
|
||||
|
||||
/*
|
||||
** Copyright (c) 2008-2018 The Khronos Group Inc.
|
||||
**
|
||||
** Permission is hereby granted, free of charge, to any person obtaining a
|
||||
** copy of this software and/or associated documentation files (the
|
||||
** "Materials"), to deal in the Materials without restriction, including
|
||||
** without limitation the rights to use, copy, modify, merge, publish,
|
||||
** distribute, sublicense, and/or sell copies of the Materials, and to
|
||||
** permit persons to whom the Materials are furnished to do so, subject to
|
||||
** the following conditions:
|
||||
**
|
||||
** The above copyright notice and this permission notice shall be included
|
||||
** in all copies or substantial portions of the Materials.
|
||||
**
|
||||
** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
||||
** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
|
||||
*/
|
||||
|
||||
/* Khronos platform-specific types and definitions.
|
||||
*
|
||||
* The master copy of khrplatform.h is maintained in the Khronos EGL
|
||||
* Registry repository at https://github.com/KhronosGroup/EGL-Registry
|
||||
* The last semantic modification to khrplatform.h was at commit ID:
|
||||
* 67a3e0864c2d75ea5287b9f3d2eb74a745936692
|
||||
*
|
||||
* Adopters may modify this file to suit their platform. Adopters are
|
||||
* encouraged to submit platform specific modifications to the Khronos
|
||||
* group so that they can be included in future versions of this file.
|
||||
* Please submit changes by filing pull requests or issues on
|
||||
* the EGL Registry repository linked above.
|
||||
*
|
||||
*
|
||||
* See the Implementer's Guidelines for information about where this file
|
||||
* should be located on your system and for more details of its use:
|
||||
* http://www.khronos.org/registry/implementers_guide.pdf
|
||||
*
|
||||
* This file should be included as
|
||||
* #include <KHR/khrplatform.h>
|
||||
* by Khronos client API header files that use its types and defines.
|
||||
*
|
||||
* The types in khrplatform.h should only be used to define API-specific types.
|
||||
*
|
||||
* Types defined in khrplatform.h:
|
||||
* khronos_int8_t signed 8 bit
|
||||
* khronos_uint8_t unsigned 8 bit
|
||||
* khronos_int16_t signed 16 bit
|
||||
* khronos_uint16_t unsigned 16 bit
|
||||
* khronos_int32_t signed 32 bit
|
||||
* khronos_uint32_t unsigned 32 bit
|
||||
* khronos_int64_t signed 64 bit
|
||||
* khronos_uint64_t unsigned 64 bit
|
||||
* khronos_intptr_t signed same number of bits as a pointer
|
||||
* khronos_uintptr_t unsigned same number of bits as a pointer
|
||||
* khronos_ssize_t signed size
|
||||
* khronos_usize_t unsigned size
|
||||
* khronos_float_t signed 32 bit floating point
|
||||
* khronos_time_ns_t unsigned 64 bit time in nanoseconds
|
||||
* khronos_utime_nanoseconds_t unsigned time interval or absolute time in
|
||||
* nanoseconds
|
||||
* khronos_stime_nanoseconds_t signed time interval in nanoseconds
|
||||
* khronos_boolean_enum_t enumerated boolean type. This should
|
||||
* only be used as a base type when a client API's boolean type is
|
||||
* an enum. Client APIs which use an integer or other type for
|
||||
* booleans cannot use this as the base type for their boolean.
|
||||
*
|
||||
* Tokens defined in khrplatform.h:
|
||||
*
|
||||
* KHRONOS_FALSE, KHRONOS_TRUE Enumerated boolean false/true values.
|
||||
*
|
||||
* KHRONOS_SUPPORT_INT64 is 1 if 64 bit integers are supported; otherwise 0.
|
||||
* KHRONOS_SUPPORT_FLOAT is 1 if floats are supported; otherwise 0.
|
||||
*
|
||||
* Calling convention macros defined in this file:
|
||||
* KHRONOS_APICALL
|
||||
* KHRONOS_APIENTRY
|
||||
* KHRONOS_APIATTRIBUTES
|
||||
*
|
||||
* These may be used in function prototypes as:
|
||||
*
|
||||
* KHRONOS_APICALL void KHRONOS_APIENTRY funcname(
|
||||
* int arg1,
|
||||
* int arg2) KHRONOS_APIATTRIBUTES;
|
||||
*/
|
||||
|
||||
#if defined(__SCITECH_SNAP__) && !defined(KHRONOS_STATIC)
|
||||
# define KHRONOS_STATIC 1
|
||||
#endif
|
||||
|
||||
/*-------------------------------------------------------------------------
|
||||
* Definition of KHRONOS_APICALL
|
||||
*-------------------------------------------------------------------------
|
||||
* This precedes the return type of the function in the function prototype.
|
||||
*/
|
||||
#if defined(KHRONOS_STATIC)
|
||||
/* If the preprocessor constant KHRONOS_STATIC is defined, make the
|
||||
* header compatible with static linking. */
|
||||
# define KHRONOS_APICALL
|
||||
#elif defined(_WIN32)
|
||||
# define KHRONOS_APICALL __declspec(dllimport)
|
||||
#elif defined (__SYMBIAN32__)
|
||||
# define KHRONOS_APICALL IMPORT_C
|
||||
#elif defined(__ANDROID__)
|
||||
# define KHRONOS_APICALL __attribute__((visibility("default")))
|
||||
#else
|
||||
# define KHRONOS_APICALL
|
||||
#endif
|
||||
|
||||
/*-------------------------------------------------------------------------
|
||||
* Definition of KHRONOS_APIENTRY
|
||||
*-------------------------------------------------------------------------
|
||||
* This follows the return type of the function and precedes the function
|
||||
* name in the function prototype.
|
||||
*/
|
||||
#if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(__SCITECH_SNAP__)
|
||||
/* Win32 but not WinCE */
|
||||
# define KHRONOS_APIENTRY __stdcall
|
||||
#else
|
||||
# define KHRONOS_APIENTRY
|
||||
#endif
|
||||
|
||||
/*-------------------------------------------------------------------------
|
||||
* Definition of KHRONOS_APIATTRIBUTES
|
||||
*-------------------------------------------------------------------------
|
||||
* This follows the closing parenthesis of the function prototype arguments.
|
||||
*/
|
||||
#if defined (__ARMCC_2__)
|
||||
#define KHRONOS_APIATTRIBUTES __softfp
|
||||
#else
|
||||
#define KHRONOS_APIATTRIBUTES
|
||||
#endif
|
||||
|
||||
/*-------------------------------------------------------------------------
|
||||
* basic type definitions
|
||||
*-----------------------------------------------------------------------*/
|
||||
#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__GNUC__) || defined(__SCO__) || defined(__USLC__)
|
||||
|
||||
|
||||
/*
|
||||
* Using <stdint.h>
|
||||
*/
|
||||
#include <stdint.h>
|
||||
typedef int32_t khronos_int32_t;
|
||||
typedef uint32_t khronos_uint32_t;
|
||||
typedef int64_t khronos_int64_t;
|
||||
typedef uint64_t khronos_uint64_t;
|
||||
#define KHRONOS_SUPPORT_INT64 1
|
||||
#define KHRONOS_SUPPORT_FLOAT 1
|
||||
/*
|
||||
* To support platform where unsigned long cannot be used interchangeably with
|
||||
* inptr_t (e.g. CHERI-extended ISAs), we can use the stdint.h intptr_t.
|
||||
* Ideally, we could just use (u)intptr_t everywhere, but this could result in
|
||||
* ABI breakage if khronos_uintptr_t is changed from unsigned long to
|
||||
* unsigned long long or similar (this results in different C++ name mangling).
|
||||
* To avoid changes for existing platforms, we restrict usage of intptr_t to
|
||||
* platforms where the size of a pointer is larger than the size of long.
|
||||
*/
|
||||
#if defined(__SIZEOF_LONG__) && defined(__SIZEOF_POINTER__)
|
||||
#if __SIZEOF_POINTER__ > __SIZEOF_LONG__
|
||||
#define KHRONOS_USE_INTPTR_T
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#elif defined(__VMS ) || defined(__sgi)
|
||||
|
||||
/*
|
||||
* Using <inttypes.h>
|
||||
*/
|
||||
#include <inttypes.h>
|
||||
typedef int32_t khronos_int32_t;
|
||||
typedef uint32_t khronos_uint32_t;
|
||||
typedef int64_t khronos_int64_t;
|
||||
typedef uint64_t khronos_uint64_t;
|
||||
#define KHRONOS_SUPPORT_INT64 1
|
||||
#define KHRONOS_SUPPORT_FLOAT 1
|
||||
|
||||
#elif defined(_WIN32) && !defined(__SCITECH_SNAP__)
|
||||
|
||||
/*
|
||||
* Win32
|
||||
*/
|
||||
typedef __int32 khronos_int32_t;
|
||||
typedef unsigned __int32 khronos_uint32_t;
|
||||
typedef __int64 khronos_int64_t;
|
||||
typedef unsigned __int64 khronos_uint64_t;
|
||||
#define KHRONOS_SUPPORT_INT64 1
|
||||
#define KHRONOS_SUPPORT_FLOAT 1
|
||||
|
||||
#elif defined(__sun__) || defined(__digital__)
|
||||
|
||||
/*
|
||||
* Sun or Digital
|
||||
*/
|
||||
typedef int khronos_int32_t;
|
||||
typedef unsigned int khronos_uint32_t;
|
||||
#if defined(__arch64__) || defined(_LP64)
|
||||
typedef long int khronos_int64_t;
|
||||
typedef unsigned long int khronos_uint64_t;
|
||||
#else
|
||||
typedef long long int khronos_int64_t;
|
||||
typedef unsigned long long int khronos_uint64_t;
|
||||
#endif /* __arch64__ */
|
||||
#define KHRONOS_SUPPORT_INT64 1
|
||||
#define KHRONOS_SUPPORT_FLOAT 1
|
||||
|
||||
#elif 0
|
||||
|
||||
/*
|
||||
* Hypothetical platform with no float or int64 support
|
||||
*/
|
||||
typedef int khronos_int32_t;
|
||||
typedef unsigned int khronos_uint32_t;
|
||||
#define KHRONOS_SUPPORT_INT64 0
|
||||
#define KHRONOS_SUPPORT_FLOAT 0
|
||||
|
||||
#else
|
||||
|
||||
/*
|
||||
* Generic fallback
|
||||
*/
|
||||
#include <stdint.h>
|
||||
typedef int32_t khronos_int32_t;
|
||||
typedef uint32_t khronos_uint32_t;
|
||||
typedef int64_t khronos_int64_t;
|
||||
typedef uint64_t khronos_uint64_t;
|
||||
#define KHRONOS_SUPPORT_INT64 1
|
||||
#define KHRONOS_SUPPORT_FLOAT 1
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
/*
|
||||
* Types that are (so far) the same on all platforms
|
||||
*/
|
||||
typedef signed char khronos_int8_t;
|
||||
typedef unsigned char khronos_uint8_t;
|
||||
typedef signed short int khronos_int16_t;
|
||||
typedef unsigned short int khronos_uint16_t;
|
||||
|
||||
/*
|
||||
* Types that differ between LLP64 and LP64 architectures - in LLP64,
|
||||
* pointers are 64 bits, but 'long' is still 32 bits. Win64 appears
|
||||
* to be the only LLP64 architecture in current use.
|
||||
*/
|
||||
#ifdef KHRONOS_USE_INTPTR_T
|
||||
typedef intptr_t khronos_intptr_t;
|
||||
typedef uintptr_t khronos_uintptr_t;
|
||||
#elif defined(_WIN64)
|
||||
typedef signed long long int khronos_intptr_t;
|
||||
typedef unsigned long long int khronos_uintptr_t;
|
||||
#else
|
||||
typedef signed long int khronos_intptr_t;
|
||||
typedef unsigned long int khronos_uintptr_t;
|
||||
#endif
|
||||
|
||||
#if defined(_WIN64)
|
||||
typedef signed long long int khronos_ssize_t;
|
||||
typedef unsigned long long int khronos_usize_t;
|
||||
#else
|
||||
typedef signed long int khronos_ssize_t;
|
||||
typedef unsigned long int khronos_usize_t;
|
||||
#endif
|
||||
|
||||
#if KHRONOS_SUPPORT_FLOAT
|
||||
/*
|
||||
* Float type
|
||||
*/
|
||||
typedef float khronos_float_t;
|
||||
#endif
|
||||
|
||||
#if KHRONOS_SUPPORT_INT64
|
||||
/* Time types
|
||||
*
|
||||
* These types can be used to represent a time interval in nanoseconds or
|
||||
* an absolute Unadjusted System Time. Unadjusted System Time is the number
|
||||
* of nanoseconds since some arbitrary system event (e.g. since the last
|
||||
* time the system booted). The Unadjusted System Time is an unsigned
|
||||
* 64 bit value that wraps back to 0 every 584 years. Time intervals
|
||||
* may be either signed or unsigned.
|
||||
*/
|
||||
typedef khronos_uint64_t khronos_utime_nanoseconds_t;
|
||||
typedef khronos_int64_t khronos_stime_nanoseconds_t;
|
||||
#endif
|
||||
|
||||
/*
|
||||
* Dummy value used to pad enum types to 32 bits.
|
||||
*/
|
||||
#ifndef KHRONOS_MAX_ENUM
|
||||
#define KHRONOS_MAX_ENUM 0x7FFFFFFF
|
||||
#endif
|
||||
|
||||
/*
|
||||
* Enumerated boolean type
|
||||
*
|
||||
* Values other than zero should be considered to be true. Therefore
|
||||
* comparisons should not be made against KHRONOS_TRUE.
|
||||
*/
|
||||
typedef enum {
|
||||
KHRONOS_FALSE = 0,
|
||||
KHRONOS_TRUE = 1,
|
||||
KHRONOS_BOOLEAN_ENUM_FORCE_SIZE = KHRONOS_MAX_ENUM
|
||||
} khronos_boolean_enum_t;
|
||||
|
||||
#endif /* __khrplatform_h_ */
|
||||
4133
extern/glad/include/glad/glad.h
vendored
4133
extern/glad/include/glad/glad.h
vendored
File diff suppressed because it is too large
Load diff
2121
extern/glad/src/glad.c
vendored
2121
extern/glad/src/glad.c
vendored
File diff suppressed because it is too large
Load diff
22
extern/sokol/LICENSE
vendored
Normal file
22
extern/sokol/LICENSE
vendored
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
zlib/libpng license
|
||||
|
||||
Copyright (c) 2018 Andre Weissflog
|
||||
|
||||
This software is provided 'as-is', without any express or implied warranty.
|
||||
In no event will the authors be held liable for any damages arising from the
|
||||
use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software in a
|
||||
product, an acknowledgment in the product documentation would be
|
||||
appreciated but is not required.
|
||||
|
||||
2. Altered source versions must be plainly marked as such, and must not
|
||||
be misrepresented as being the original software.
|
||||
|
||||
3. This notice may not be removed or altered from any source
|
||||
distribution.
|
||||
62
extern/sokol/README.md
vendored
Normal file
62
extern/sokol/README.md
vendored
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
# Vendored sokol headers
|
||||
|
||||
Upstream: <https://github.com/floooh/sokol>
|
||||
Pinned commit: `b210caee10d6834081cb46c617c3ff715a92be26`
|
||||
License: zlib (see `LICENSE`)
|
||||
|
||||
These are the only sokol headers render3d actually `#include`s:
|
||||
|
||||
| File | Upstream path | Used for |
|
||||
| ----------------- | ------------------------- | ----------------------------------------- |
|
||||
| `sokol_gfx.h` | `sokol_gfx.h` | Graphics backend (D3D11 / Metal / GL 4.3) |
|
||||
| `sokol_app.h` | `sokol_app.h` | Windowing and input |
|
||||
| `sokol_glue.h` | `sokol_glue.h` | Bridges sokol_app and sokol_gfx |
|
||||
| `sokol_log.h` | `sokol_log.h` | Default logger callback |
|
||||
| `sokol_imgui.h` | `util/sokol_imgui.h` | Dear ImGui renderer/event handler |
|
||||
|
||||
## Local patches
|
||||
|
||||
`sokol_gfx.h` carries a local patch (search the file for `Local patch:`) wiring
|
||||
`sg_push_debug_group` / `sg_pop_debug_group` on the D3D11 backend to
|
||||
`ID3DUserDefinedAnnotation::BeginEvent` / `EndEvent`. Upstream sokol_gfx
|
||||
silently no-ops these on every backend except Metal, so D3D11 captures in
|
||||
RenderDoc / PIX / Nsight had no hierarchical event regions. The patch:
|
||||
|
||||
- includes `<d3d11_1.h>`,
|
||||
- adds `ID3DUserDefinedAnnotation* annotation` to `_sg_d3d11_backend_t`,
|
||||
- QueryInterfaces it in `_sg_d3d11_setup_backend`, releases in
|
||||
`_sg_d3d11_discard_backend`,
|
||||
- implements `_sg_d3d11_push_debug_group` / `_sg_d3d11_pop_debug_group`
|
||||
(UTF-8 -> UTF-16 conversion, stack buffer, 256 char cap),
|
||||
- routes the public `_sg_push_debug_group` / `_sg_pop_debug_group`
|
||||
dispatcher to them under `SOKOL_D3D11`.
|
||||
|
||||
`sokol_app.h` carries a local patch (search the file for `Local patch:`) in
|
||||
`_sapp_win32_create_window` that changes how `desc.width` / `desc.height`
|
||||
are interpreted on Win32 when `desc.high_dpi == true`. Upstream always
|
||||
multiplies the requested size by the monitor's `window_scale`, treating
|
||||
`desc.width` as 100%-DPI logical pixels — so callers that want a specific
|
||||
framebuffer size on a high-DPI display have to pre-divide by the DPI scale
|
||||
themselves. The patch makes the high-DPI path interpret `desc.width` /
|
||||
`desc.height` as physical/framebuffer pixels directly; the `high_dpi=false`
|
||||
branch keeps upstream behavior so DPI-unaware apps are unaffected.
|
||||
|
||||
When bumping either header, re-apply the patch and rebuild. Each patch is
|
||||
small enough to re-do by hand each time; if either grows, consider
|
||||
upstreaming.
|
||||
|
||||
## Bumping
|
||||
|
||||
1. Pull the new headers from upstream at the desired commit:
|
||||
|
||||
```
|
||||
git clone --depth 1 https://github.com/floooh/sokol /tmp/sokol-src
|
||||
(cd /tmp/sokol-src && git fetch --depth 1 origin <sha> && git checkout <sha>)
|
||||
cp /tmp/sokol-src/sokol_{gfx,app,glue,log}.h extern/sokol/
|
||||
cp /tmp/sokol-src/util/sokol_imgui.h extern/sokol/
|
||||
cp /tmp/sokol-src/LICENSE extern/sokol/
|
||||
```
|
||||
|
||||
2. Update the pinned commit at the top of this file.
|
||||
3. Rebuild + run the smoke test on all three OSes.
|
||||
4. Commit as `deps: bump sokol to <sha> (<reason>)`.
|
||||
14500
extern/sokol/sokol_app.h
vendored
Normal file
14500
extern/sokol/sokol_app.h
vendored
Normal file
File diff suppressed because it is too large
Load diff
26841
extern/sokol/sokol_gfx.h
vendored
Normal file
26841
extern/sokol/sokol_gfx.h
vendored
Normal file
File diff suppressed because it is too large
Load diff
207
extern/sokol/sokol_glue.h
vendored
Normal file
207
extern/sokol/sokol_glue.h
vendored
Normal file
|
|
@ -0,0 +1,207 @@
|
|||
#if defined(SOKOL_IMPL) && !defined(SOKOL_GLUE_IMPL)
|
||||
#define SOKOL_GLUE_IMPL
|
||||
#endif
|
||||
#ifndef SOKOL_GLUE_INCLUDED
|
||||
/*
|
||||
sokol_glue.h -- glue helper functions for sokol headers
|
||||
|
||||
Project URL: https://github.com/floooh/sokol
|
||||
|
||||
Do this:
|
||||
#define SOKOL_IMPL or
|
||||
#define SOKOL_GLUE_IMPL
|
||||
before you include this file in *one* C or C++ file to create the
|
||||
implementation.
|
||||
|
||||
...optionally provide the following macros to override defaults:
|
||||
|
||||
SOKOL_ASSERT(c) - your own assert macro (default: assert(c))
|
||||
SOKOL_GLUE_API_DECL - public function declaration prefix (default: extern)
|
||||
SOKOL_API_DECL - same as SOKOL_GLUE_API_DECL
|
||||
SOKOL_API_IMPL - public function implementation prefix (default: -)
|
||||
|
||||
If sokol_glue.h is compiled as a DLL, define the following before
|
||||
including the declaration or implementation:
|
||||
|
||||
SOKOL_DLL
|
||||
|
||||
On Windows, SOKOL_DLL will define SOKOL_GLUE_API_DECL as __declspec(dllexport)
|
||||
or __declspec(dllimport) as needed.
|
||||
|
||||
OVERVIEW
|
||||
========
|
||||
sokol_glue.h provides glue helper functions between sokol_gfx.h and sokol_app.h,
|
||||
so that sokol_gfx.h doesn't need to depend on sokol_app.h but can be
|
||||
used with different window system glue libraries.
|
||||
|
||||
PROVIDED FUNCTIONS
|
||||
==================
|
||||
|
||||
sg_environment sglue_environment(void)
|
||||
|
||||
Returns an sg_environment struct initialized by calling sokol_app.h
|
||||
functions. Use this in the sg_setup() call like this:
|
||||
|
||||
sg_setup(&(sg_desc){
|
||||
.environment = sglue_environment(),
|
||||
...
|
||||
});
|
||||
|
||||
sg_swapchain sglue_swapchain(void)
|
||||
|
||||
Returns an sg_swapchain struct initialized by calling sokol_app.h
|
||||
functions. Use this in sg_begin_pass() for a 'swapchain pass' like
|
||||
this:
|
||||
|
||||
sg_begin_pass(&(sg_pass){ .swapchain = sglue_swapchain(), ... });
|
||||
|
||||
LICENSE
|
||||
=======
|
||||
zlib/libpng license
|
||||
|
||||
Copyright (c) 2018 Andre Weissflog
|
||||
|
||||
This software is provided 'as-is', without any express or implied warranty.
|
||||
In no event will the authors be held liable for any damages arising from the
|
||||
use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software in a
|
||||
product, an acknowledgment in the product documentation would be
|
||||
appreciated but is not required.
|
||||
|
||||
2. Altered source versions must be plainly marked as such, and must not
|
||||
be misrepresented as being the original software.
|
||||
|
||||
3. This notice may not be removed or altered from any source
|
||||
distribution.
|
||||
*/
|
||||
#define SOKOL_GLUE_INCLUDED
|
||||
|
||||
#if defined(SOKOL_API_DECL) && !defined(SOKOL_GLUE_API_DECL)
|
||||
#define SOKOL_GLUE_API_DECL SOKOL_API_DECL
|
||||
#endif
|
||||
#ifndef SOKOL_GLUE_API_DECL
|
||||
#if defined(_WIN32) && defined(SOKOL_DLL) && defined(SOKOL_GLUE_IMPL)
|
||||
#define SOKOL_GLUE_API_DECL __declspec(dllexport)
|
||||
#elif defined(_WIN32) && defined(SOKOL_DLL)
|
||||
#define SOKOL_GLUE_API_DECL __declspec(dllimport)
|
||||
#else
|
||||
#define SOKOL_GLUE_API_DECL extern
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifndef SOKOL_GFX_INCLUDED
|
||||
#error "Please include sokol_gfx.h before sokol_glue.h"
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
SOKOL_GLUE_API_DECL sg_environment sglue_environment(void);
|
||||
SOKOL_GLUE_API_DECL sg_swapchain sglue_swapchain(void);
|
||||
|
||||
#ifdef __cplusplus
|
||||
} /* extern "C" */
|
||||
#endif
|
||||
#endif /* SOKOL_GLUE_INCLUDED */
|
||||
|
||||
/*-- IMPLEMENTATION ----------------------------------------------------------*/
|
||||
#ifdef SOKOL_GLUE_IMPL
|
||||
#define SOKOL_GLUE_IMPL_INCLUDED (1)
|
||||
#include <string.h> /* memset */
|
||||
|
||||
#ifndef SOKOL_APP_INCLUDED
|
||||
#error "Please include sokol_app.h before the sokol_glue.h implementation"
|
||||
#endif
|
||||
|
||||
#ifndef SOKOL_API_IMPL
|
||||
#define SOKOL_API_IMPL
|
||||
#endif
|
||||
|
||||
#ifndef _SOKOL_PRIVATE
|
||||
#if defined(__GNUC__) || defined(__clang__)
|
||||
#define _SOKOL_PRIVATE __attribute__((unused)) static
|
||||
#else
|
||||
#define _SOKOL_PRIVATE static
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifndef SOKOL_ASSERT
|
||||
#include <assert.h>
|
||||
#define SOKOL_ASSERT(c) assert(c)
|
||||
#endif
|
||||
#ifndef SOKOL_UNREACHABLE
|
||||
#define SOKOL_UNREACHABLE SOKOL_ASSERT(false)
|
||||
#endif
|
||||
|
||||
_SOKOL_PRIVATE sg_pixel_format _sglue_to_sgpixelformat(sapp_pixel_format fmt) {
|
||||
switch (fmt) {
|
||||
case SAPP_PIXELFORMAT_NONE: return SG_PIXELFORMAT_NONE;
|
||||
case SAPP_PIXELFORMAT_RGBA8: return SG_PIXELFORMAT_RGBA8;
|
||||
case SAPP_PIXELFORMAT_SRGB8A8: return SG_PIXELFORMAT_SRGB8A8;
|
||||
case SAPP_PIXELFORMAT_BGRA8: return SG_PIXELFORMAT_BGRA8;
|
||||
case SAPP_PIXELFORMAT_DEPTH_STENCIL: return SG_PIXELFORMAT_DEPTH_STENCIL;
|
||||
case SAPP_PIXELFORMAT_DEPTH: return SG_PIXELFORMAT_DEPTH;
|
||||
case SAPP_PIXELFORMAT_SBGRA8: // FIXME!
|
||||
default:
|
||||
SOKOL_UNREACHABLE;
|
||||
return SG_PIXELFORMAT_NONE;
|
||||
}
|
||||
}
|
||||
|
||||
SOKOL_API_IMPL sg_environment sglue_environment(void) {
|
||||
sg_environment res;
|
||||
memset(&res, 0, sizeof(res));
|
||||
const sapp_environment env = sapp_get_environment();
|
||||
res.defaults.color_format = _sglue_to_sgpixelformat(env.defaults.color_format);
|
||||
res.defaults.depth_format = _sglue_to_sgpixelformat(env.defaults.depth_format);
|
||||
res.defaults.sample_count = env.defaults.sample_count;
|
||||
res.metal.device = env.metal.device;
|
||||
res.d3d11.device = env.d3d11.device;
|
||||
res.d3d11.device_context = env.d3d11.device_context;
|
||||
res.wgpu.device = env.wgpu.device;
|
||||
res.vulkan.instance = env.vulkan.instance;
|
||||
res.vulkan.physical_device = env.vulkan.physical_device;
|
||||
res.vulkan.device = env.vulkan.device;
|
||||
res.vulkan.queue = env.vulkan.queue;
|
||||
res.vulkan.queue_family_index = env.vulkan.queue_family_index;
|
||||
return res;
|
||||
}
|
||||
|
||||
SOKOL_API_IMPL sg_swapchain sglue_swapchain(void) {
|
||||
sg_swapchain res;
|
||||
memset(&res, 0, sizeof(res));
|
||||
const sapp_swapchain sc = sapp_get_swapchain();
|
||||
res.width = sc.width;
|
||||
res.height = sc.height;
|
||||
res.sample_count = sc.sample_count;
|
||||
res.color_format = _sglue_to_sgpixelformat(sc.color_format);
|
||||
res.depth_format = _sglue_to_sgpixelformat(sc.depth_format);
|
||||
res.metal.current_drawable = sc.metal.current_drawable;
|
||||
res.metal.depth_stencil_texture = sc.metal.depth_stencil_texture;
|
||||
res.metal.msaa_color_texture = sc.metal.msaa_color_texture;
|
||||
res.d3d11.render_view = sc.d3d11.render_view;
|
||||
res.d3d11.resolve_view = sc.d3d11.resolve_view;
|
||||
res.d3d11.depth_stencil_view = sc.d3d11.depth_stencil_view;
|
||||
res.wgpu.render_view = sc.wgpu.render_view;
|
||||
res.wgpu.resolve_view = sc.wgpu.resolve_view;
|
||||
res.wgpu.depth_stencil_view = sc.wgpu.depth_stencil_view;
|
||||
res.vulkan.render_image = sc.vulkan.render_image;
|
||||
res.vulkan.render_view = sc.vulkan.render_view;
|
||||
res.vulkan.resolve_image = sc.vulkan.resolve_image;
|
||||
res.vulkan.resolve_view = sc.vulkan.resolve_view;
|
||||
res.vulkan.depth_stencil_image = sc.vulkan.depth_stencil_image;
|
||||
res.vulkan.depth_stencil_view = sc.vulkan.depth_stencil_view;
|
||||
res.vulkan.render_finished_semaphore = sc.vulkan.render_finished_semaphore;
|
||||
res.vulkan.present_complete_semaphore = sc.vulkan.present_complete_semaphore;
|
||||
res.gl.framebuffer = sc.gl.framebuffer;
|
||||
return res;
|
||||
}
|
||||
|
||||
#endif /* SOKOL_GLUE_IMPL */
|
||||
3171
extern/sokol/sokol_imgui.h
vendored
Normal file
3171
extern/sokol/sokol_imgui.h
vendored
Normal file
File diff suppressed because it is too large
Load diff
334
extern/sokol/sokol_log.h
vendored
Normal file
334
extern/sokol/sokol_log.h
vendored
Normal file
|
|
@ -0,0 +1,334 @@
|
|||
#if defined(SOKOL_IMPL) && !defined(SOKOL_LOG_IMPL)
|
||||
#define SOKOL_LOG_IMPL
|
||||
#endif
|
||||
#ifndef SOKOL_LOG_INCLUDED
|
||||
/*
|
||||
sokol_log.h -- common logging callback for sokol headers
|
||||
|
||||
Project URL: https://github.com/floooh/sokol
|
||||
|
||||
Example code: https://github.com/floooh/sokol-samples
|
||||
|
||||
Do this:
|
||||
#define SOKOL_IMPL or
|
||||
#define SOKOL_LOG_IMPL
|
||||
before you include this file in *one* C or C++ file to create the
|
||||
implementation.
|
||||
|
||||
Optionally provide the following defines when building the implementation:
|
||||
|
||||
SOKOL_ASSERT(c) - your own assert macro (default: assert(c))
|
||||
SOKOL_UNREACHABLE() - a guard macro for unreachable code (default: assert(false))
|
||||
SOKOL_LOG_API_DECL - public function declaration prefix (default: extern)
|
||||
SOKOL_API_DECL - same as SOKOL_GFX_API_DECL
|
||||
SOKOL_API_IMPL - public function implementation prefix (default: -)
|
||||
|
||||
Optionally define the following for verbose output:
|
||||
|
||||
SOKOL_DEBUG - by default this is defined if NDEBUG is not defined
|
||||
|
||||
|
||||
OVERVIEW
|
||||
========
|
||||
sokol_log.h provides a default logging callback for other sokol headers.
|
||||
|
||||
To use the default log callback, just include sokol_log.h and provide
|
||||
a function pointer to the 'slog_func' function when setting up the
|
||||
sokol library:
|
||||
|
||||
For instance with sokol_audio.h:
|
||||
|
||||
#include "sokol_log.h"
|
||||
...
|
||||
saudio_setup(&(saudio_desc){ .logger.func = slog_func });
|
||||
|
||||
Logging output goes to stderr and/or a platform specific logging subsystem
|
||||
(which means that in some scenarios you might see logging messages duplicated):
|
||||
|
||||
- Windows: stderr + OutputDebugStringA()
|
||||
- macOS/iOS/Linux: stderr + syslog()
|
||||
- Emscripten: console.info()/warn()/error()
|
||||
- Android: __android_log_write()
|
||||
|
||||
On Windows with sokol_app.h also note the runtime config items to make
|
||||
stdout/stderr output visible on the console for WinMain() applications
|
||||
via sapp_desc.win32.console_attach or sapp_desc.win32.console_create,
|
||||
however when running in a debugger on Windows, the logging output should
|
||||
show up on the debug output UI panel.
|
||||
|
||||
In debug mode, a log message might look like this:
|
||||
|
||||
[sspine][error][id:12] /Users/floh/projects/sokol/util/sokol_spine.h:3472:0:
|
||||
SKELETON_DESC_NO_ATLAS: no atlas object provided in sspine_skeleton_desc.atlas
|
||||
|
||||
The source path and line number is formatted like compiler errors, in some IDEs (like VSCode)
|
||||
such error messages are clickable.
|
||||
|
||||
In release mode, logging is less verbose as to not bloat the executable with string data, but you still get
|
||||
enough information to identify the type and location of an error:
|
||||
|
||||
[sspine][error][id:12][line:3472]
|
||||
|
||||
RULES FOR WRITING YOUR OWN LOGGING FUNCTION
|
||||
===========================================
|
||||
- must be re-entrant because it might be called from different threads
|
||||
- must treat **all** provided string pointers as optional (can be null)
|
||||
- don't store the string pointers, copy the string data instead
|
||||
- must not return for log level panic
|
||||
|
||||
LICENSE
|
||||
=======
|
||||
zlib/libpng license
|
||||
|
||||
Copyright (c) 2023 Andre Weissflog
|
||||
|
||||
This software is provided 'as-is', without any express or implied warranty.
|
||||
In no event will the authors be held liable for any damages arising from the
|
||||
use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software in a
|
||||
product, an acknowledgment in the product documentation would be
|
||||
appreciated but is not required.
|
||||
|
||||
2. Altered source versions must be plainly marked as such, and must not
|
||||
be misrepresented as being the original software.
|
||||
|
||||
3. This notice may not be removed or altered from any source
|
||||
distribution.
|
||||
*/
|
||||
#define SOKOL_LOG_INCLUDED (1)
|
||||
#include <stdint.h>
|
||||
|
||||
#if defined(SOKOL_API_DECL) && !defined(SOKOL_LOG_API_DECL)
|
||||
#define SOKOL_LOG_API_DECL SOKOL_API_DECL
|
||||
#endif
|
||||
#ifndef SOKOL_LOG_API_DECL
|
||||
#if defined(_WIN32) && defined(SOKOL_DLL) && defined(SOKOL_LOG_IMPL)
|
||||
#define SOKOL_LOG_API_DECL __declspec(dllexport)
|
||||
#elif defined(_WIN32) && defined(SOKOL_DLL)
|
||||
#define SOKOL_LOG_API_DECL __declspec(dllimport)
|
||||
#else
|
||||
#define SOKOL_LOG_API_DECL extern
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/*
|
||||
Plug this function into the 'logger.func' struct item when initializing any of the sokol
|
||||
headers. For instance for sokol_audio.h it would look like this:
|
||||
|
||||
saudio_setup(&(saudio_desc){
|
||||
.logger = {
|
||||
.func = slog_func
|
||||
}
|
||||
});
|
||||
*/
|
||||
SOKOL_LOG_API_DECL void slog_func(const char* tag, uint32_t log_level, uint32_t log_item, const char* message, uint32_t line_nr, const char* filename, void* user_data);
|
||||
|
||||
#ifdef __cplusplus
|
||||
} // extern "C"
|
||||
#endif
|
||||
#endif // SOKOL_LOG_INCLUDED
|
||||
|
||||
// ██ ███ ███ ██████ ██ ███████ ███ ███ ███████ ███ ██ ████████ █████ ████████ ██ ██████ ███ ██
|
||||
// ██ ████ ████ ██ ██ ██ ██ ████ ████ ██ ████ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██
|
||||
// ██ ██ ████ ██ ██████ ██ █████ ██ ████ ██ █████ ██ ██ ██ ██ ███████ ██ ██ ██ ██ ██ ██ ██
|
||||
// ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
|
||||
// ██ ██ ██ ██ ███████ ███████ ██ ██ ███████ ██ ████ ██ ██ ██ ██ ██ ██████ ██ ████
|
||||
//
|
||||
// >>implementation
|
||||
#ifdef SOKOL_LOG_IMPL
|
||||
#define SOKOL_LOG_IMPL_INCLUDED (1)
|
||||
|
||||
#ifndef SOKOL_API_IMPL
|
||||
#define SOKOL_API_IMPL
|
||||
#endif
|
||||
#ifndef SOKOL_DEBUG
|
||||
#ifndef NDEBUG
|
||||
#define SOKOL_DEBUG
|
||||
#endif
|
||||
#endif
|
||||
#ifndef SOKOL_ASSERT
|
||||
#include <assert.h>
|
||||
#define SOKOL_ASSERT(c) assert(c)
|
||||
#endif
|
||||
|
||||
#ifndef _SOKOL_PRIVATE
|
||||
#if defined(__GNUC__) || defined(__clang__)
|
||||
#define _SOKOL_PRIVATE __attribute__((unused)) static
|
||||
#else
|
||||
#define _SOKOL_PRIVATE static
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifndef _SOKOL_UNUSED
|
||||
#define _SOKOL_UNUSED(x) (void)(x)
|
||||
#endif
|
||||
|
||||
// platform detection
|
||||
#if defined(__APPLE__)
|
||||
#define _SLOG_APPLE (1)
|
||||
#elif defined(__EMSCRIPTEN__)
|
||||
#define _SLOG_EMSCRIPTEN (1)
|
||||
#elif defined(_WIN32)
|
||||
#define _SLOG_WINDOWS (1)
|
||||
#elif defined(__ANDROID__)
|
||||
#define _SLOG_ANDROID (1)
|
||||
#elif defined(__linux__) || defined(__unix__)
|
||||
#define _SLOG_LINUX (1)
|
||||
#else
|
||||
#error "sokol_log.h: unknown platform"
|
||||
#endif
|
||||
|
||||
#include <stdlib.h> // abort
|
||||
#include <stdio.h> // fputs
|
||||
#include <stddef.h> // size_t
|
||||
|
||||
#if defined(_SLOG_EMSCRIPTEN)
|
||||
#include <emscripten/emscripten.h>
|
||||
#elif defined(_SLOG_WINDOWS)
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
#include <windows.h>
|
||||
#elif defined(_SLOG_ANDROID)
|
||||
#include <android/log.h>
|
||||
#elif defined(_SLOG_LINUX) || defined(_SLOG_APPLE)
|
||||
#include <syslog.h>
|
||||
#endif
|
||||
|
||||
// size of line buffer (on stack!) in bytes including terminating zero
|
||||
#define _SLOG_LINE_LENGTH (512)
|
||||
|
||||
_SOKOL_PRIVATE char* _slog_append(const char* str, char* dst, char* end) {
|
||||
if (str) {
|
||||
char c;
|
||||
while (((c = *str++) != 0) && (dst < (end - 1))) {
|
||||
*dst++ = c;
|
||||
}
|
||||
}
|
||||
*dst = 0;
|
||||
return dst;
|
||||
}
|
||||
|
||||
_SOKOL_PRIVATE char* _slog_itoa(uint32_t x, char* buf, size_t buf_size) {
|
||||
const size_t max_digits_and_null = 11;
|
||||
if (buf_size < max_digits_and_null) {
|
||||
return 0;
|
||||
}
|
||||
char* p = buf + max_digits_and_null;
|
||||
*--p = 0;
|
||||
do {
|
||||
*--p = '0' + (x % 10);
|
||||
x /= 10;
|
||||
} while (x != 0);
|
||||
return p;
|
||||
}
|
||||
|
||||
#if defined(_SLOG_EMSCRIPTEN)
|
||||
EM_JS(void, slog_js_log, (uint32_t level, const char* c_str), {
|
||||
const str = UTF8ToString(c_str);
|
||||
switch (level) {
|
||||
case 0: console.error(str); break;
|
||||
case 1: console.error(str); break;
|
||||
case 2: console.warn(str); break;
|
||||
default: console.info(str); break;
|
||||
}
|
||||
})
|
||||
#endif
|
||||
|
||||
SOKOL_API_IMPL void slog_func(const char* tag, uint32_t log_level, uint32_t log_item, const char* message, uint32_t line_nr, const char* filename, void* user_data) {
|
||||
_SOKOL_UNUSED(user_data);
|
||||
|
||||
const char* log_level_str;
|
||||
switch (log_level) {
|
||||
case 0: log_level_str = "panic"; break;
|
||||
case 1: log_level_str = "error"; break;
|
||||
case 2: log_level_str = "warning"; break;
|
||||
default: log_level_str = "info"; break;
|
||||
}
|
||||
|
||||
// build log output line
|
||||
char line_buf[_SLOG_LINE_LENGTH];
|
||||
char* str = line_buf;
|
||||
char* end = line_buf + sizeof(line_buf);
|
||||
char num_buf[32];
|
||||
if (tag) {
|
||||
str = _slog_append("[", str, end);
|
||||
str = _slog_append(tag, str, end);
|
||||
str = _slog_append("]", str, end);
|
||||
}
|
||||
str = _slog_append("[", str, end);
|
||||
str = _slog_append(log_level_str, str, end);
|
||||
str = _slog_append("]", str, end);
|
||||
str = _slog_append("[id:", str, end);
|
||||
str = _slog_append(_slog_itoa(log_item, num_buf, sizeof(num_buf)), str, end);
|
||||
str = _slog_append("]", str, end);
|
||||
// if a filename is provided, build a clickable log message that's compatible with compiler error messages
|
||||
if (filename) {
|
||||
str = _slog_append(" ", str, end);
|
||||
#if defined(_MSC_VER)
|
||||
// MSVC compiler error format
|
||||
str = _slog_append(filename, str, end);
|
||||
str = _slog_append("(", str, end);
|
||||
str = _slog_append(_slog_itoa(line_nr, num_buf, sizeof(num_buf)), str, end);
|
||||
str = _slog_append("): ", str, end);
|
||||
#else
|
||||
// gcc/clang compiler error format
|
||||
str = _slog_append(filename, str, end);
|
||||
str = _slog_append(":", str, end);
|
||||
str = _slog_append(_slog_itoa(line_nr, num_buf, sizeof(num_buf)), str, end);
|
||||
str = _slog_append(":0: ", str, end);
|
||||
#endif
|
||||
}
|
||||
else {
|
||||
str = _slog_append("[line:", str, end);
|
||||
str = _slog_append(_slog_itoa(line_nr, num_buf, sizeof(num_buf)), str, end);
|
||||
str = _slog_append("] ", str, end);
|
||||
}
|
||||
if (message) {
|
||||
str = _slog_append("\n\t", str, end);
|
||||
str = _slog_append(message, str, end);
|
||||
}
|
||||
str = _slog_append("\n\n", str, end);
|
||||
if (0 == log_level) {
|
||||
str = _slog_append("ABORTING because of [panic]\n", str, end);
|
||||
(void)str;
|
||||
}
|
||||
|
||||
// print to stderr?
|
||||
#if defined(_SLOG_LINUX) || defined(_SLOG_WINDOWS) || defined(_SLOG_APPLE)
|
||||
fputs(line_buf, stderr);
|
||||
#endif
|
||||
|
||||
// platform specific logging calls
|
||||
#if defined(_SLOG_WINDOWS)
|
||||
OutputDebugStringA(line_buf);
|
||||
#elif defined(_SLOG_ANDROID)
|
||||
int prio;
|
||||
switch (log_level) {
|
||||
case 0: prio = ANDROID_LOG_FATAL; break;
|
||||
case 1: prio = ANDROID_LOG_ERROR; break;
|
||||
case 2: prio = ANDROID_LOG_WARN; break;
|
||||
default: prio = ANDROID_LOG_INFO; break;
|
||||
}
|
||||
__android_log_write(prio, "SOKOL", line_buf);
|
||||
#elif defined(_SLOG_EMSCRIPTEN)
|
||||
slog_js_log(log_level, line_buf);
|
||||
#endif
|
||||
if (0 == log_level) {
|
||||
abort();
|
||||
}
|
||||
}
|
||||
#endif // SOKOL_LOG_IMPL
|
||||
7987
extern/stb/stb_image.h
vendored
7987
extern/stb/stb_image.h
vendored
File diff suppressed because it is too large
Load diff
|
|
@ -158,6 +158,9 @@ B3_API float b3GetMillisecondsAndReset( uint64_t* ticks );
|
|||
/// Yield to be used in a busy loop.
|
||||
B3_API void b3Yield( void );
|
||||
|
||||
/// Sleep the current thread for a number of milliseconds.
|
||||
B3_API void b3Sleep( int milliseconds );
|
||||
|
||||
// Simple djb2 hash function for determinism testing
|
||||
#define B3_HASH_INIT 5381
|
||||
B3_API uint32_t b3Hash( uint32_t hash, const uint8_t* data, int count );
|
||||
|
|
|
|||
|
|
@ -31,7 +31,8 @@ typedef struct b3SurfaceMaterial
|
|||
/// combining functions. It is not used internally.
|
||||
uint64_t userMaterialId;
|
||||
|
||||
/// Custom debug draw color. Ignored if 0.
|
||||
/// Custom debug draw color. Ignored if 0. The low 24 bits are RGB. The high byte may
|
||||
/// carry a b3DebugMaterial preset, see b3MakeDebugColor.
|
||||
/// @see b3HexColor
|
||||
uint32_t customColor;
|
||||
} b3SurfaceMaterial;
|
||||
|
|
|
|||
|
|
@ -1457,6 +1457,27 @@ typedef enum b3HexColor
|
|||
b3_colorBox2DYellow = 0xFFEE8C
|
||||
} b3HexColor;
|
||||
|
||||
/// Debug draw material preset. Optionally packed into the unused high byte of a
|
||||
/// b3HexColor (or b3SurfaceMaterial::customColor) to drive the renderer's PBR
|
||||
/// roughness and metalness. The low 24 bits stay RGB, so a plain 0xRRGGBB color
|
||||
/// reads as b3_debugMaterialDefault and keeps the renderer's per-body-type look.
|
||||
typedef enum b3DebugMaterial
|
||||
{
|
||||
b3_debugMaterialDefault = 0,
|
||||
b3_debugMaterialMatte,
|
||||
b3_debugMaterialSoft,
|
||||
b3_debugMaterialDead,
|
||||
b3_debugMaterialGlossy,
|
||||
b3_debugMaterialMetallic
|
||||
} b3DebugMaterial;
|
||||
|
||||
/// Pack an RGB color with a material preset for debug draw. The preset rides in
|
||||
/// the high byte where the color converters ignore it.
|
||||
B3_INLINE uint32_t b3MakeDebugColor( b3HexColor rgb, b3DebugMaterial material )
|
||||
{
|
||||
return ( (uint32_t)rgb & 0x00FFFFFFu ) | ( (uint32_t)material << 24 );
|
||||
}
|
||||
|
||||
/// Get the visualization color assigned to a constraint graph color slot. The last index
|
||||
/// (B3_GRAPH_COLOR_COUNT - 1) is the overflow color.
|
||||
B3_API b3HexColor b3GetGraphColor( int index );
|
||||
|
|
|
|||
|
|
@ -1,149 +1,191 @@
|
|||
# Samples app
|
||||
# Box3D samples
|
||||
|
||||
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
|
||||
FetchContent_Declare(imgui
|
||||
GIT_REPOSITORY https://github.com/ocornut/imgui.git
|
||||
GIT_TAG v1.92.7
|
||||
GIT_SHALLOW TRUE
|
||||
GIT_PROGRESS TRUE
|
||||
)
|
||||
target_include_directories(glad PUBLIC ${GLAD_DIR}/include)
|
||||
FetchContent_MakeAvailable(imgui)
|
||||
|
||||
# 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
|
||||
FetchContent_Declare(implot
|
||||
GIT_REPOSITORY https://github.com/epezent/implot.git
|
||||
GIT_TAG v0.17
|
||||
GIT_SHALLOW TRUE
|
||||
GIT_PROGRESS TRUE
|
||||
GIT_TAG v0.17
|
||||
GIT_SHALLOW TRUE
|
||||
GIT_PROGRESS TRUE
|
||||
)
|
||||
FetchContent_MakeAvailable(implot)
|
||||
|
||||
# The shader compiler is only needed when recompiling shaders. A fresh clone
|
||||
# with BOX3D_BUILD_SHADERS=OFF builds from the committed headers and skips this.
|
||||
if(BOX3D_BUILD_SHADERS)
|
||||
FetchContent_Declare(sokol_tools_bin
|
||||
GIT_REPOSITORY https://github.com/floooh/sokol-tools-bin.git
|
||||
GIT_TAG 1a9a4e54090fec42c5d13169b638f09f25474953
|
||||
# unfortunately cannot be shallow when using a SHA
|
||||
# GIT_SHALLOW TRUE
|
||||
GIT_PROGRESS TRUE
|
||||
)
|
||||
FetchContent_MakeAvailable(sokol_tools_bin)
|
||||
endif()
|
||||
|
||||
# imgui static lib: the five core sources. sokol_imgui is the backend (no
|
||||
# glfw/opengl3 backend sources), so it is not listed here.
|
||||
add_library(imgui STATIC
|
||||
"${imgui_SOURCE_DIR}/imgui.cpp"
|
||||
"${imgui_SOURCE_DIR}/imgui_draw.cpp"
|
||||
"${imgui_SOURCE_DIR}/imgui_tables.cpp"
|
||||
"${imgui_SOURCE_DIR}/imgui_widgets.cpp"
|
||||
"${imgui_SOURCE_DIR}/imgui_demo.cpp"
|
||||
)
|
||||
target_include_directories(imgui SYSTEM PUBLIC "${imgui_SOURCE_DIR}")
|
||||
set_target_properties(imgui PROPERTIES
|
||||
CXX_STANDARD 20
|
||||
CXX_STANDARD_REQUIRED ON
|
||||
CXX_EXTENSIONS OFF
|
||||
POSITION_INDEPENDENT_CODE ON
|
||||
)
|
||||
|
||||
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
|
||||
"${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
|
||||
target_include_directories(implot SYSTEM PUBLIC "${implot_SOURCE_DIR}")
|
||||
set_target_properties(implot PROPERTIES
|
||||
CXX_STANDARD 20
|
||||
CXX_STANDARD_REQUIRED ON
|
||||
CXX_EXTENSIONS OFF
|
||||
POSITION_INDEPENDENT_CODE ON
|
||||
)
|
||||
|
||||
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)
|
||||
# --- sokol: vendored headers INTERFACE target + per-platform backend. --------
|
||||
set(sokol_SOURCE_DIR "${CMAKE_SOURCE_DIR}/extern/sokol")
|
||||
add_library(sokol INTERFACE)
|
||||
target_include_directories(sokol SYSTEM INTERFACE "${sokol_SOURCE_DIR}")
|
||||
if(WIN32)
|
||||
target_compile_definitions(sokol INTERFACE SOKOL_D3D11)
|
||||
target_link_libraries(sokol INTERFACE
|
||||
d3d11 dxgi dxguid
|
||||
user32 gdi32 shell32 ole32)
|
||||
elseif(APPLE)
|
||||
target_compile_definitions(sokol INTERFACE SOKOL_METAL)
|
||||
target_link_libraries(sokol INTERFACE
|
||||
"-framework Foundation"
|
||||
"-framework Cocoa"
|
||||
"-framework QuartzCore"
|
||||
"-framework Metal"
|
||||
"-framework MetalKit")
|
||||
elseif(UNIX)
|
||||
target_compile_definitions(sokol INTERFACE SOKOL_GLCORE)
|
||||
find_package(OpenGL REQUIRED)
|
||||
find_package(Threads REQUIRED)
|
||||
find_package(X11 REQUIRED)
|
||||
if(NOT X11_Xi_FOUND OR NOT X11_Xcursor_FOUND)
|
||||
message(FATAL_ERROR
|
||||
"sokol_app needs Xi and Xcursor; install libxi-dev and libxcursor-dev.")
|
||||
endif()
|
||||
target_link_libraries(sokol INTERFACE
|
||||
OpenGL::GL Threads::Threads ${CMAKE_DL_LIBS} m
|
||||
X11::X11 X11::Xi X11::Xcursor)
|
||||
else()
|
||||
message(FATAL_ERROR "Unsupported platform for sokol backend selection.")
|
||||
endif()
|
||||
|
||||
# sokol-shdc executable path, consumed by shaders/CMakeLists.txt.
|
||||
if(BOX3D_BUILD_SHADERS)
|
||||
if(WIN32)
|
||||
set(_shdc_subdir win32)
|
||||
set(_shdc_exe sokol-shdc.exe)
|
||||
elseif(APPLE)
|
||||
if(CMAKE_SYSTEM_PROCESSOR MATCHES "arm64|aarch64")
|
||||
set(_shdc_subdir osx_arm64)
|
||||
else()
|
||||
set(_shdc_subdir osx)
|
||||
endif()
|
||||
set(_shdc_exe sokol-shdc)
|
||||
else()
|
||||
set(_shdc_subdir linux)
|
||||
set(_shdc_exe sokol-shdc)
|
||||
endif()
|
||||
set(SOKOL_SHDC_EXECUTABLE
|
||||
"${sokol_tools_bin_SOURCE_DIR}/bin/${_shdc_subdir}/${_shdc_exe}"
|
||||
CACHE FILEPATH "Path to sokol-shdc binary")
|
||||
unset(_shdc_subdir)
|
||||
unset(_shdc_exe)
|
||||
endif()
|
||||
|
||||
# --- Renderer + shaders (ported verbatim from render3d). ---------------------
|
||||
add_subdirectory(shaders)
|
||||
add_subdirectory(gfx)
|
||||
|
||||
set(SAMPLE_FILES
|
||||
main.cpp
|
||||
|
||||
# Host glue (ported from render3d's app/).
|
||||
host/camera.cpp
|
||||
host/camera.h
|
||||
host/gui.cpp
|
||||
host/gui.h
|
||||
host/imgui_impl.cpp
|
||||
host/sokol_app_impl.c
|
||||
|
||||
sample.cpp
|
||||
sample.h
|
||||
mesh_loader.cpp
|
||||
mesh_loader.h
|
||||
jsmn.h
|
||||
tiny_obj_loader.h
|
||||
earcut.h
|
||||
|
||||
# Samples
|
||||
sample_stacking.cpp
|
||||
sample_character.cpp
|
||||
sample_collision.cpp
|
||||
sample_determinism.cpp
|
||||
sample_robustness.cpp
|
||||
sample_benchmark.cpp
|
||||
sample_ragdoll.cpp
|
||||
sample_geometry.cpp
|
||||
sample_issues.cpp
|
||||
sample_shapes.cpp
|
||||
sample_tree.cpp
|
||||
sample_mesh.cpp
|
||||
sample_compound.cpp
|
||||
sample_events.cpp
|
||||
sample_bodies.cpp
|
||||
sample_manifold.cpp
|
||||
sample_continuous.cpp
|
||||
sample_joint.cpp
|
||||
)
|
||||
|
||||
add_executable(samples ${SAMPLE_FILES})
|
||||
|
||||
if(APPLE)
|
||||
# sokol_app's Cocoa backend is Objective-C; compile its impl TU as OBJC
|
||||
# with ARC, matching render3d's app/CMakeLists.
|
||||
set_source_files_properties(host/sokol_app_impl.c PROPERTIES LANGUAGE OBJC)
|
||||
set_source_files_properties(host/sokol_app_impl.c PROPERTIES COMPILE_OPTIONS "-fobjc-arc")
|
||||
endif()
|
||||
|
||||
# Include root is the samples dir so "gfx/..." and "host/..." prefixes resolve.
|
||||
# The data dir is on the path too so samples can #include recorded dumps
|
||||
# (sample_issues pulls dumps/.../box3d_dump.inl at compile time).
|
||||
target_include_directories(samples PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/../data")
|
||||
|
||||
# gfx: the renderer + Draw*/adapter. shared: human, utils (Random*), the
|
||||
# benchmark/determinism helpers the samples lean on.
|
||||
target_link_libraries(samples PRIVATE gfx shared imgui implot sokol)
|
||||
|
||||
set_target_properties(samples PROPERTIES
|
||||
CMAKE_COMPILE_WARNING_AS_ERROR ON
|
||||
CXX_STANDARD 20
|
||||
CXX_STANDARD_REQUIRED YES
|
||||
CXX_EXTENSIONS NO
|
||||
CXX_STANDARD 20
|
||||
CXX_STANDARD_REQUIRED ON
|
||||
CXX_EXTENSIONS OFF
|
||||
)
|
||||
|
||||
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}")
|
||||
source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${SAMPLE_FILES})
|
||||
|
|
|
|||
|
|
@ -1,332 +0,0 @@
|
|||
// 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 InvertOrthonormal( 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 };
|
||||
|
||||
// todo just transpose in place into out matrix
|
||||
b3Matrix3 invR = b3Transpose(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 = InvertOrthonormal(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;
|
||||
}
|
||||
|
|
@ -1,85 +0,0 @@
|
|||
// 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;
|
||||
};
|
||||
276
samples/font.cpp
276
samples/font.cpp
|
|
@ -1,276 +0,0 @@
|
|||
// 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;
|
||||
}
|
||||
|
|
@ -1,51 +0,0 @@
|
|||
// 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;
|
||||
};
|
||||
|
|
@ -1,150 +0,0 @@
|
|||
// 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;
|
||||
}
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
// 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);
|
||||
63
samples/gfx/CMakeLists.txt
Normal file
63
samples/gfx/CMakeLists.txt
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
set(GFX_FILES
|
||||
arena.c
|
||||
arena.h
|
||||
debug_adapter.c
|
||||
debug_adapter.h
|
||||
debug_shapes.c
|
||||
debug_shapes.h
|
||||
draw_overlay.h
|
||||
draw.c
|
||||
draw.h
|
||||
edges.c
|
||||
edges.h
|
||||
geometry_registry.c
|
||||
geometry_registry.h
|
||||
gtao.c
|
||||
gtao.h
|
||||
highlight_mask.c
|
||||
highlight_mask.h
|
||||
highlight_outline.c
|
||||
highlight_outline.h
|
||||
highlight_target.c
|
||||
highlight_target.h
|
||||
ibl.c
|
||||
ibl.h
|
||||
overlay.c
|
||||
overlay.h
|
||||
picking.h
|
||||
projection.h
|
||||
qsort.h
|
||||
renderer.c
|
||||
renderer.h
|
||||
scene_target.c
|
||||
scene_target.h
|
||||
shadow.c
|
||||
shadow.h
|
||||
sky.c
|
||||
sky.h
|
||||
sokol_impl.c
|
||||
text.c
|
||||
text.h
|
||||
tone_map.c
|
||||
tone_map.h
|
||||
utility.h
|
||||
)
|
||||
|
||||
add_library(gfx STATIC ${GFX_FILES})
|
||||
|
||||
if(APPLE)
|
||||
set_source_files_properties(
|
||||
sokol_impl.c
|
||||
PROPERTIES LANGUAGE OBJC)
|
||||
target_compile_options(gfx PRIVATE -fobjc-arc)
|
||||
endif()
|
||||
|
||||
# Include root is the samples dir so "gfx/foo.h" / "host/foo.h" prefixes
|
||||
# resolve (render3d used its repo root; here gfx lives under samples/).
|
||||
target_include_directories(gfx PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/..")
|
||||
target_link_libraries(gfx
|
||||
PUBLIC sokol box3d
|
||||
PRIVATE shader_gen
|
||||
)
|
||||
|
||||
source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${GFX_FILES})
|
||||
62
samples/gfx/arena.c
Normal file
62
samples/gfx/arena.c
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "gfx/arena.h"
|
||||
|
||||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
int ArenaInit( Arena* a, size_t capacity )
|
||||
{
|
||||
assert( a );
|
||||
assert( capacity > 0 );
|
||||
a->base = (uint8_t*)malloc( capacity );
|
||||
if ( !a->base )
|
||||
{
|
||||
a->capacity = 0;
|
||||
a->used = 0;
|
||||
return -1;
|
||||
}
|
||||
a->capacity = capacity;
|
||||
a->used = 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
void ArenaShutdown( Arena* a )
|
||||
{
|
||||
if ( !a )
|
||||
{
|
||||
return;
|
||||
}
|
||||
free( a->base );
|
||||
a->base = NULL;
|
||||
a->capacity = 0;
|
||||
a->used = 0;
|
||||
}
|
||||
|
||||
void* ArenaAlloc( Arena* a, size_t size, size_t align )
|
||||
{
|
||||
assert( a );
|
||||
assert( align > 0 && ( align & ( align - 1 ) ) == 0 ); // power of two
|
||||
// Align the absolute address, malloc's base is only guaranteed to be
|
||||
// alignof(max_align_t)-aligned (16 on x64 MSVC), so aligning the offset
|
||||
// alone breaks for align > 16.
|
||||
const uintptr_t mask = (uintptr_t)align - 1;
|
||||
const uintptr_t cur = (uintptr_t)a->base + a->used;
|
||||
const uintptr_t aligned = ( cur + mask ) & ~mask;
|
||||
const size_t alignedUsed = (size_t)( aligned - (uintptr_t)a->base );
|
||||
if ( alignedUsed > a->capacity || size > a->capacity - alignedUsed )
|
||||
{
|
||||
fprintf( stderr, "[arena/error] out of space: used=%zu cap=%zu req=%zu align=%zu\n", a->used, a->capacity, size, align );
|
||||
return NULL;
|
||||
}
|
||||
a->used = alignedUsed + size;
|
||||
return (void*)aligned;
|
||||
}
|
||||
|
||||
void ArenaReset( Arena* a )
|
||||
{
|
||||
assert( a );
|
||||
a->used = 0;
|
||||
}
|
||||
37
samples/gfx/arena.h
Normal file
37
samples/gfx/arena.h
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"
|
||||
{
|
||||
#endif
|
||||
|
||||
typedef struct Arena
|
||||
{
|
||||
uint8_t* base; // owned heap allocation, capacity bytes
|
||||
size_t capacity;
|
||||
size_t used;
|
||||
} Arena;
|
||||
|
||||
// Returns 0 on success, -1 on allocation failure. capacity must be > 0.
|
||||
int ArenaInit( Arena* a, size_t capacity );
|
||||
|
||||
// Free backing storage. Safe on a zero-initialized arena.
|
||||
void ArenaShutdown( Arena* a );
|
||||
|
||||
// Bump-allocate `size` bytes with `align` alignment (must be power-of-two).
|
||||
// Returns NULL if the request would overflow the arena, logs to stderr.
|
||||
void* ArenaAlloc( Arena* a, size_t size, size_t align );
|
||||
|
||||
// Reset to empty without freeing backing storage. Invalidates all
|
||||
// pointers handed out before the reset.
|
||||
void ArenaReset( Arena* a );
|
||||
|
||||
#ifdef __cplusplus
|
||||
} // extern "C"
|
||||
#endif
|
||||
916
samples/gfx/debug_adapter.c
Normal file
916
samples/gfx/debug_adapter.c
Normal file
|
|
@ -0,0 +1,916 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "gfx/debug_adapter.h"
|
||||
|
||||
#include "box3d/box3d.h"
|
||||
#include "gfx/debug_shapes.h"
|
||||
#include "gfx/draw.h"
|
||||
#include "gfx/geometry_registry.h"
|
||||
#include "gfx/highlight_mask.h"
|
||||
#include "gfx/overlay.h"
|
||||
#include "gfx/renderer.h"
|
||||
#include "gfx/text.h"
|
||||
|
||||
#include <assert.h>
|
||||
#include <math.h>
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#define BOX3D_USER_SHAPE_CAPACITY 65536
|
||||
#define BOX3D_FREELIST_END ( -1 )
|
||||
#define BOX3D_MATERIAL_OVERRIDE_CAPACITY 256
|
||||
|
||||
typedef enum
|
||||
{
|
||||
Box3DUS_Free = 0,
|
||||
Box3DUS_Sphere,
|
||||
Box3DUS_Capsule,
|
||||
Box3DUS_Hull,
|
||||
Box3DUS_Mesh,
|
||||
Box3DUS_HeightField,
|
||||
Box3DUS_Compound,
|
||||
} DebugShapeKind;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
b3Vec3 center;
|
||||
float radius;
|
||||
} DebugSphere;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
b3Transform localFrame;
|
||||
float halfLength;
|
||||
float radius;
|
||||
} DebugCapsule;
|
||||
|
||||
// Hull/mesh/heightfield. Scale only for mesh.
|
||||
typedef struct
|
||||
{
|
||||
MeshHandle handle;
|
||||
b3Vec3 scale;
|
||||
} DebugMesh;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
DebugShapeKind kind;
|
||||
// valid only when kind == Box3DUS_Free
|
||||
int nextFree;
|
||||
b3BodyType bodyType;
|
||||
bool isGround;
|
||||
b3ShapeId shapeId;
|
||||
b3BodyId bodyId;
|
||||
bool hasMaterial;
|
||||
Vec4 color;
|
||||
float metallic;
|
||||
float roughness;
|
||||
|
||||
// Compound children are flattened into their own pool slots. A child links
|
||||
// to its sibling through nextChild and is placed by childTransform under the
|
||||
// owning body transform. Identity transform and no sibling for top-level shapes.
|
||||
int nextChild;
|
||||
b3Transform childTransform;
|
||||
union
|
||||
{
|
||||
DebugSphere sphere;
|
||||
DebugCapsule capsule;
|
||||
DebugMesh geom;
|
||||
struct
|
||||
{
|
||||
int firstChild;
|
||||
} compound;
|
||||
};
|
||||
} DebugShape;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
b3ShapeId shapeId;
|
||||
Vec4 color;
|
||||
float metallic;
|
||||
float roughness;
|
||||
} MaterialOverride;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
DebugShape pool[BOX3D_USER_SHAPE_CAPACITY];
|
||||
int firstFree;
|
||||
int allocCount;
|
||||
|
||||
// For the ground grid
|
||||
b3ShapeId groundShapeId;
|
||||
|
||||
// Per-shape PBR overrides
|
||||
MaterialOverride materialOverrides[BOX3D_MATERIAL_OVERRIDE_CAPACITY];
|
||||
int materialOverrideCount;
|
||||
|
||||
b3BodyId hoveredBodyId;
|
||||
b3BodyId selectedBodyId;
|
||||
|
||||
// Function pointers, drawingBounds, and context inside this struct are NOT used.
|
||||
// Only used for settings
|
||||
b3DebugDraw guiDraw;
|
||||
|
||||
bool transparentDynamic;
|
||||
} AdapterState;
|
||||
|
||||
static AdapterState s_adapter;
|
||||
|
||||
// Per-bodyType PBR material defaults. Indexed by b3BodyType
|
||||
// (b3_staticBody = 0, b3_kinematicBody = 1, b3_dynamicBody = 2).
|
||||
static const float kBodyTypeMetallic[3] = { 0.0f, 0.0f, 0.0f };
|
||||
static const float kBodyTypeRoughness[3] = { 0.70f, 0.55f, 0.40f };
|
||||
|
||||
// PBR presets packed into the debug color high byte. Indexed by b3DebugMaterial.
|
||||
// Default (0) is unused here, the caller falls back to the per-bodyType table.
|
||||
// default matte soft dead glossy metal
|
||||
static const float kDebugMaterialMetallic[6] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.85f };
|
||||
static const float kDebugMaterialRoughness[6] = { 0.50f, 0.85f, 0.65f, 0.95f, 0.30f, 0.35f };
|
||||
|
||||
void InitAdapter( void )
|
||||
{
|
||||
for ( int i = 0; i < BOX3D_USER_SHAPE_CAPACITY; ++i )
|
||||
{
|
||||
s_adapter.pool[i].kind = Box3DUS_Free;
|
||||
s_adapter.pool[i].nextFree = ( i + 1 < BOX3D_USER_SHAPE_CAPACITY ) ? ( i + 1 ) : BOX3D_FREELIST_END;
|
||||
}
|
||||
s_adapter.firstFree = 0;
|
||||
s_adapter.allocCount = 0;
|
||||
s_adapter.groundShapeId = b3_nullShapeId;
|
||||
s_adapter.materialOverrideCount = 0;
|
||||
s_adapter.hoveredBodyId = b3_nullBodyId;
|
||||
s_adapter.selectedBodyId = b3_nullBodyId;
|
||||
s_adapter.transparentDynamic = false;
|
||||
|
||||
s_adapter.guiDraw = b3DefaultDebugDraw();
|
||||
s_adapter.guiDraw.drawShapes = true;
|
||||
}
|
||||
|
||||
void ResetAdapterPool( void )
|
||||
{
|
||||
// Release GPU mesh refs still held by live geom shapes, then rebuild the
|
||||
// free list from scratch. Mirrors InitAdapter's pool setup. The O(capacity)
|
||||
// sweep is cheap and guarantees a clean slate even if a shape leaked a ref.
|
||||
for ( int i = 0; i < BOX3D_USER_SHAPE_CAPACITY; ++i )
|
||||
{
|
||||
DebugShape* us = &s_adapter.pool[i];
|
||||
if ( us->kind == Box3DUS_Hull || us->kind == Box3DUS_Mesh || us->kind == Box3DUS_HeightField )
|
||||
{
|
||||
ReleaseMeshReference( us->geom.handle );
|
||||
}
|
||||
us->kind = Box3DUS_Free;
|
||||
us->nextFree = ( i + 1 < BOX3D_USER_SHAPE_CAPACITY ) ? ( i + 1 ) : BOX3D_FREELIST_END;
|
||||
}
|
||||
s_adapter.firstFree = 0;
|
||||
s_adapter.allocCount = 0;
|
||||
|
||||
s_adapter.groundShapeId = b3_nullShapeId;
|
||||
s_adapter.materialOverrideCount = 0;
|
||||
s_adapter.hoveredBodyId = b3_nullBodyId;
|
||||
s_adapter.selectedBodyId = b3_nullBodyId;
|
||||
s_adapter.transparentDynamic = false;
|
||||
}
|
||||
|
||||
b3DebugDraw* GetGuiDraw( void )
|
||||
{
|
||||
return &s_adapter.guiDraw;
|
||||
}
|
||||
|
||||
void ApplyGuiFlags( b3DebugDraw* out )
|
||||
{
|
||||
assert( out != NULL );
|
||||
out->forceScale = s_adapter.guiDraw.forceScale;
|
||||
out->jointScale = s_adapter.guiDraw.jointScale;
|
||||
out->drawShapes = s_adapter.guiDraw.drawShapes;
|
||||
out->drawJoints = s_adapter.guiDraw.drawJoints;
|
||||
out->drawJointExtras = s_adapter.guiDraw.drawJointExtras;
|
||||
out->drawBounds = s_adapter.guiDraw.drawBounds;
|
||||
out->drawMass = s_adapter.guiDraw.drawMass;
|
||||
out->drawBodyNames = s_adapter.guiDraw.drawBodyNames;
|
||||
out->drawContacts = s_adapter.guiDraw.drawContacts;
|
||||
out->drawAnchorA = s_adapter.guiDraw.drawAnchorA;
|
||||
out->drawGraphColors = s_adapter.guiDraw.drawGraphColors;
|
||||
out->drawContactFeatures = s_adapter.guiDraw.drawContactFeatures;
|
||||
out->drawContactNormals = s_adapter.guiDraw.drawContactNormals;
|
||||
out->drawContactForces = s_adapter.guiDraw.drawContactForces;
|
||||
out->drawFrictionForces = s_adapter.guiDraw.drawFrictionForces;
|
||||
out->drawIslands = s_adapter.guiDraw.drawIslands;
|
||||
}
|
||||
|
||||
void SetTransparentDynamic( bool enabled )
|
||||
{
|
||||
s_adapter.transparentDynamic = enabled;
|
||||
}
|
||||
|
||||
bool GetTransparentDynamic( void )
|
||||
{
|
||||
return s_adapter.transparentDynamic;
|
||||
}
|
||||
|
||||
void SetGroundShape( b3ShapeId shapeId )
|
||||
{
|
||||
s_adapter.groundShapeId = shapeId;
|
||||
}
|
||||
|
||||
void SetShapeMaterial( b3ShapeId shapeId, Vec4 color, float metallic, float roughness )
|
||||
{
|
||||
for ( int i = 0; i < s_adapter.materialOverrideCount; ++i )
|
||||
{
|
||||
if ( B3_ID_EQUALS( s_adapter.materialOverrides[i].shapeId, shapeId ) )
|
||||
{
|
||||
s_adapter.materialOverrides[i].color = color;
|
||||
s_adapter.materialOverrides[i].metallic = metallic;
|
||||
s_adapter.materialOverrides[i].roughness = roughness;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if ( s_adapter.materialOverrideCount >= BOX3D_MATERIAL_OVERRIDE_CAPACITY )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int index = s_adapter.materialOverrideCount++;
|
||||
s_adapter.materialOverrides[index].shapeId = shapeId;
|
||||
s_adapter.materialOverrides[index].color = color;
|
||||
s_adapter.materialOverrides[index].metallic = metallic;
|
||||
s_adapter.materialOverrides[index].roughness = roughness;
|
||||
}
|
||||
|
||||
int GetDebugShapeCount( void )
|
||||
{
|
||||
return s_adapter.allocCount;
|
||||
}
|
||||
|
||||
void SetHoveredBody( b3BodyId bodyId )
|
||||
{
|
||||
s_adapter.hoveredBodyId = b3Body_IsValid( bodyId ) ? bodyId : b3_nullBodyId;
|
||||
}
|
||||
|
||||
b3BodyId GetHoveredBody( void )
|
||||
{
|
||||
return s_adapter.hoveredBodyId;
|
||||
}
|
||||
|
||||
void SetSelectedBody( b3BodyId bodyId )
|
||||
{
|
||||
s_adapter.selectedBodyId = b3Body_IsValid( bodyId ) ? bodyId : b3_nullBodyId;
|
||||
}
|
||||
|
||||
void ClearSelection( void )
|
||||
{
|
||||
s_adapter.selectedBodyId = b3_nullBodyId;
|
||||
}
|
||||
|
||||
b3BodyId GetSelectedBody( void )
|
||||
{
|
||||
return s_adapter.selectedBodyId;
|
||||
}
|
||||
|
||||
bool IsBodySelected( b3BodyId bodyId )
|
||||
{
|
||||
if ( B3_IS_NULL( s_adapter.selectedBodyId ) )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return B3_ID_EQUALS( s_adapter.selectedBodyId, bodyId );
|
||||
}
|
||||
|
||||
static HighlightKind ResolveHighlightKind( b3BodyId bodyId )
|
||||
{
|
||||
if ( IsBodySelected( bodyId ) )
|
||||
{
|
||||
return HIGHLIGHT_KIND_SELECT;
|
||||
}
|
||||
|
||||
if ( B3_ID_EQUALS( bodyId, s_adapter.hoveredBodyId ) )
|
||||
{
|
||||
return HIGHLIGHT_KIND_HOVER;
|
||||
}
|
||||
|
||||
return HIGHLIGHT_KIND_NONE;
|
||||
}
|
||||
|
||||
static int AllocDebugShape( void )
|
||||
{
|
||||
if ( s_adapter.firstFree == BOX3D_FREELIST_END )
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
const int index = s_adapter.firstFree;
|
||||
s_adapter.firstFree = s_adapter.pool[index].nextFree;
|
||||
s_adapter.allocCount += 1;
|
||||
return index;
|
||||
}
|
||||
|
||||
static void FreeDebugShape( int index )
|
||||
{
|
||||
assert( index >= 0 && index < BOX3D_USER_SHAPE_CAPACITY );
|
||||
|
||||
// A sample switch cleans the pool twice: ResetAdapterPool sweeps it, then
|
||||
// b3DestroyWorld fires the destroy callback per shape. Relinking a slot
|
||||
// that is already free loops the free list, and a later alloc then hands
|
||||
// one slot to two shapes so the second overwrites the first.
|
||||
if ( s_adapter.pool[index].kind == Box3DUS_Free )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
s_adapter.pool[index].kind = Box3DUS_Free;
|
||||
s_adapter.pool[index].nextFree = s_adapter.firstFree;
|
||||
s_adapter.firstFree = index;
|
||||
s_adapter.allocCount -= 1;
|
||||
}
|
||||
|
||||
// Color + transform helpers
|
||||
|
||||
// b3HexColor is the SVG palette as 0xRRGGBB hex literals, sRGB-encoded,
|
||||
// like every CSS/SVG color.
|
||||
|
||||
// sRGB values used directly as linear albedo for overlays and in world text
|
||||
static Vec4 HexColorToVec4( b3HexColor color )
|
||||
{
|
||||
const uint32_t v = (uint32_t)color;
|
||||
const float r = (float)( ( v >> 16 ) & 0xFFu ) * ( 1.0f / 255.0f );
|
||||
const float g = (float)( ( v >> 8 ) & 0xFFu ) * ( 1.0f / 255.0f );
|
||||
const float b = (float)( v & 0xFFu ) * ( 1.0f / 255.0f );
|
||||
return MakeVec4( r, g, b, 1.0f );
|
||||
}
|
||||
|
||||
// sRGB EOTF, the standard piecewise curve (IEC 61966-2-1), one channel.
|
||||
static float SRGBToLinear( float c )
|
||||
{
|
||||
return ( c <= 0.04045f ) ? ( c * ( 1.0f / 12.92f ) ) : powf( ( c + 0.055f ) * ( 1.0f / 1.055f ), 2.4f );
|
||||
}
|
||||
|
||||
// sRGB 0xRRGGBB -> linear RGBA. Alpha carries no transfer function. Used
|
||||
// for lit shape base colors, see the hexColorToVec4 note above.
|
||||
static Vec4 HexColorToLinear( b3HexColor color )
|
||||
{
|
||||
const Vec4 s = HexColorToVec4( color );
|
||||
return MakeVec4( SRGBToLinear( s.x ), SRGBToLinear( s.y ), SRGBToLinear( s.z ), s.w );
|
||||
}
|
||||
|
||||
// Get a capsule transform to represent axial spin
|
||||
static b3Transform GetCapsuleLocalFrame( b3Vec3 c1, b3Vec3 c2, float* outHalfLength )
|
||||
{
|
||||
b3Vec3 d = b3Sub(c2, c1);
|
||||
float length = b3Length( d );
|
||||
*outHalfLength = 0.5f * length;
|
||||
|
||||
b3Transform t;
|
||||
t.q = b3Quat_identity;
|
||||
if ( length > 1.0e-6f )
|
||||
{
|
||||
b3Vec3 axis = b3MulSV( 1.0f / length, d );
|
||||
|
||||
// For rendering, the capsule axis is along x
|
||||
t.q = b3ComputeQuatBetweenUnitVectors( b3Vec3_axisX, axis );
|
||||
}
|
||||
t.p = b3Lerp( c1, c2, 0.5f );
|
||||
return t;
|
||||
}
|
||||
|
||||
static void RefreshMaterialFromOverride( DebugShape* us )
|
||||
{
|
||||
us->hasMaterial = false;
|
||||
for ( int i = 0; i < s_adapter.materialOverrideCount; ++i )
|
||||
{
|
||||
if ( B3_ID_EQUALS( s_adapter.materialOverrides[i].shapeId, us->shapeId ) )
|
||||
{
|
||||
us->hasMaterial = true;
|
||||
us->color = s_adapter.materialOverrides[i].color;
|
||||
us->metallic = s_adapter.materialOverrides[i].metallic;
|
||||
us->roughness = s_adapter.materialOverrides[i].roughness;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void PopulateCommonFields( DebugShape* us, const b3DebugShape* debugShape )
|
||||
{
|
||||
const b3BodyId bodyId = b3Shape_GetBody( debugShape->shapeId );
|
||||
us->bodyType = b3Body_GetType( bodyId );
|
||||
us->isGround = B3_ID_EQUALS( debugShape->shapeId, s_adapter.groundShapeId );
|
||||
us->shapeId = debugShape->shapeId;
|
||||
us->bodyId = bodyId;
|
||||
RefreshMaterialFromOverride( us );
|
||||
}
|
||||
|
||||
// Resolve one compound child into its own pool slot, mirroring the top-level
|
||||
// create path. Hull and mesh children take a mesh reference released on destroy.
|
||||
// Common fields are inherited from the parent so material and highlight stay
|
||||
// keyed to the compound's single shape. Returns the pool index, or -1 if the
|
||||
// pool is full or the geometry could not be registered.
|
||||
static int CreateCompoundChild( const b3ChildShape* child, const DebugShape* parent )
|
||||
{
|
||||
const bool needsHandle = ( child->type == b3_hullShape || child->type == b3_meshShape );
|
||||
MeshHandle handle = InvalidMeshHandle();
|
||||
if ( child->type == b3_hullShape )
|
||||
{
|
||||
handle = FindOrAddHull( child->hull );
|
||||
}
|
||||
else if ( child->type == b3_meshShape )
|
||||
{
|
||||
handle = FindOrAddMesh( child->mesh.data );
|
||||
}
|
||||
if ( needsHandle && !IsMeshHandleValid( handle ) )
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
const int index = AllocDebugShape();
|
||||
if ( index < 0 )
|
||||
{
|
||||
if ( needsHandle )
|
||||
{
|
||||
ReleaseMeshReference( handle );
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
DebugShape* us = &s_adapter.pool[index];
|
||||
us->bodyType = parent->bodyType;
|
||||
us->isGround = parent->isGround;
|
||||
us->shapeId = parent->shapeId;
|
||||
us->bodyId = parent->bodyId;
|
||||
us->hasMaterial = parent->hasMaterial;
|
||||
us->color = parent->color;
|
||||
us->metallic = parent->metallic;
|
||||
us->roughness = parent->roughness;
|
||||
|
||||
switch ( child->type )
|
||||
{
|
||||
case b3_sphereShape:
|
||||
us->kind = Box3DUS_Sphere;
|
||||
us->sphere.center = child->sphere.center;
|
||||
us->sphere.radius = child->sphere.radius;
|
||||
break;
|
||||
case b3_capsuleShape:
|
||||
us->kind = Box3DUS_Capsule;
|
||||
us->capsule.localFrame =
|
||||
GetCapsuleLocalFrame( child->capsule.center1, child->capsule.center2, &us->capsule.halfLength );
|
||||
us->capsule.radius = child->capsule.radius;
|
||||
break;
|
||||
case b3_hullShape:
|
||||
us->kind = Box3DUS_Hull;
|
||||
us->geom.handle = handle;
|
||||
us->geom.scale = b3Vec3_one;
|
||||
break;
|
||||
case b3_meshShape:
|
||||
us->kind = Box3DUS_Mesh;
|
||||
us->geom.handle = handle;
|
||||
us->geom.scale = (b3Vec3){ child->mesh.scale.x, child->mesh.scale.y, child->mesh.scale.z };
|
||||
break;
|
||||
default:
|
||||
assert( false );
|
||||
break;
|
||||
}
|
||||
|
||||
us->childTransform = child->transform;
|
||||
us->nextChild = -1;
|
||||
return index;
|
||||
}
|
||||
|
||||
static void* AdapterCreateDebugShape( const b3DebugShape* debugShape, void* context )
|
||||
{
|
||||
(void)context;
|
||||
assert( debugShape != NULL );
|
||||
|
||||
if ( debugShape->type == b3_sphereShape )
|
||||
{
|
||||
int index = AllocDebugShape();
|
||||
if ( index < 0 )
|
||||
{
|
||||
return NULL; // pool exhausted, Box3D treats NULL as "skip draw"
|
||||
}
|
||||
DebugShape* us = &s_adapter.pool[index];
|
||||
us->kind = Box3DUS_Sphere;
|
||||
PopulateCommonFields( us, debugShape );
|
||||
us->sphere.center = debugShape->sphere->center;
|
||||
us->sphere.radius = debugShape->sphere->radius;
|
||||
return us;
|
||||
}
|
||||
|
||||
if ( debugShape->type == b3_capsuleShape )
|
||||
{
|
||||
int index = AllocDebugShape();
|
||||
if ( index < 0 )
|
||||
{
|
||||
return NULL;
|
||||
}
|
||||
const b3Capsule* cap = debugShape->capsule;
|
||||
DebugShape* us = &s_adapter.pool[index];
|
||||
us->kind = Box3DUS_Capsule;
|
||||
PopulateCommonFields( us, debugShape );
|
||||
us->capsule.localFrame = GetCapsuleLocalFrame( cap->center1, cap->center2, &us->capsule.halfLength );
|
||||
us->capsule.radius = cap->radius;
|
||||
return us;
|
||||
}
|
||||
|
||||
if ( debugShape->type == b3_hullShape )
|
||||
{
|
||||
const b3Hull* hull = debugShape->hull;
|
||||
MeshHandle handle = FindOrAddHull( hull );
|
||||
if ( !IsMeshHandleValid( handle ) )
|
||||
{
|
||||
return NULL;
|
||||
}
|
||||
int index = AllocDebugShape();
|
||||
if ( index < 0 )
|
||||
{
|
||||
ReleaseMeshReference( handle );
|
||||
return NULL;
|
||||
}
|
||||
DebugShape* us = &s_adapter.pool[index];
|
||||
us->kind = Box3DUS_Hull;
|
||||
PopulateCommonFields( us, debugShape );
|
||||
us->geom.handle = handle;
|
||||
us->geom.scale = b3Vec3_one;
|
||||
return us;
|
||||
}
|
||||
|
||||
if ( debugShape->type == b3_meshShape )
|
||||
{
|
||||
const b3Mesh* mesh = debugShape->mesh;
|
||||
MeshHandle handle = FindOrAddMesh( mesh->data );
|
||||
if ( !IsMeshHandleValid( handle ) )
|
||||
{
|
||||
return NULL;
|
||||
}
|
||||
int index = AllocDebugShape();
|
||||
if ( index < 0 )
|
||||
{
|
||||
ReleaseMeshReference( handle );
|
||||
return NULL;
|
||||
}
|
||||
DebugShape* us = &s_adapter.pool[index];
|
||||
us->kind = Box3DUS_Mesh;
|
||||
PopulateCommonFields( us, debugShape );
|
||||
us->geom.handle = handle;
|
||||
us->geom.scale = (b3Vec3){ mesh->scale.x, mesh->scale.y, mesh->scale.z };
|
||||
return us;
|
||||
}
|
||||
|
||||
if ( debugShape->type == b3_heightShape )
|
||||
{
|
||||
const b3HeightField* hf = debugShape->heightField;
|
||||
const MeshHandle handle = FindOrAddHeightField( hf );
|
||||
if ( !IsMeshHandleValid( handle ) )
|
||||
{
|
||||
return NULL;
|
||||
}
|
||||
const int index = AllocDebugShape();
|
||||
if ( index < 0 )
|
||||
{
|
||||
ReleaseMeshReference( handle );
|
||||
return NULL;
|
||||
}
|
||||
DebugShape* us = &s_adapter.pool[index];
|
||||
us->kind = Box3DUS_HeightField;
|
||||
PopulateCommonFields( us, debugShape );
|
||||
us->geom.handle = handle;
|
||||
us->geom.scale = b3Vec3_one;
|
||||
return us;
|
||||
}
|
||||
|
||||
if ( debugShape->type == b3_compoundShape )
|
||||
{
|
||||
const int index = AllocDebugShape();
|
||||
if ( index < 0 )
|
||||
{
|
||||
return NULL;
|
||||
}
|
||||
DebugShape* us = &s_adapter.pool[index];
|
||||
us->kind = Box3DUS_Compound;
|
||||
PopulateCommonFields( us, debugShape );
|
||||
us->compound.firstChild = -1;
|
||||
|
||||
// Flatten the children once. The fixed pool never relocates, so the
|
||||
// parent pointer stays valid while children are allocated.
|
||||
const b3Compound* compound = debugShape->compound;
|
||||
const int total = compound->capsuleCount + compound->hullCount + compound->meshCount + compound->sphereCount;
|
||||
int prev = -1;
|
||||
for ( int i = 0; i < total; ++i )
|
||||
{
|
||||
b3ChildShape child = b3GetCompoundChild( compound, i );
|
||||
const int childIndex = CreateCompoundChild( &child, us );
|
||||
if ( childIndex < 0 )
|
||||
{
|
||||
continue; // skip a child we couldn't register, keep the rest
|
||||
}
|
||||
if ( prev < 0 )
|
||||
{
|
||||
us->compound.firstChild = childIndex;
|
||||
}
|
||||
else
|
||||
{
|
||||
s_adapter.pool[prev].nextChild = childIndex;
|
||||
}
|
||||
prev = childIndex;
|
||||
}
|
||||
return us;
|
||||
}
|
||||
|
||||
// Unknown shape type. Return NULL so Box3D skips drawing it.
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void DestroyDebugShape( void* userShape, void* context )
|
||||
{
|
||||
(void)context;
|
||||
if ( userShape == NULL )
|
||||
{
|
||||
return;
|
||||
}
|
||||
DebugShape* us = (DebugShape*)userShape;
|
||||
|
||||
if ( us->kind == Box3DUS_Compound )
|
||||
{
|
||||
int ci = us->compound.firstChild;
|
||||
while ( ci != -1 )
|
||||
{
|
||||
DebugShape* child = &s_adapter.pool[ci];
|
||||
const int next = child->nextChild;
|
||||
if ( child->kind == Box3DUS_Hull || child->kind == Box3DUS_Mesh || child->kind == Box3DUS_HeightField )
|
||||
{
|
||||
ReleaseMeshReference( child->geom.handle );
|
||||
}
|
||||
FreeDebugShape( ci );
|
||||
ci = next;
|
||||
}
|
||||
}
|
||||
else if ( us->kind == Box3DUS_Hull || us->kind == Box3DUS_Mesh || us->kind == Box3DUS_HeightField )
|
||||
{
|
||||
ReleaseMeshReference( us->geom.handle );
|
||||
}
|
||||
|
||||
const int index = (int)( us - s_adapter.pool );
|
||||
FreeDebugShape( index );
|
||||
}
|
||||
|
||||
// World-space cell size for the procedural ground grid (meters per minor
|
||||
// cell, major lines fire every 10 cells inside the shader).
|
||||
#define BOX3D_GROUND_GRID_CELL_SIZE 1.0f
|
||||
|
||||
// Alpha applied to non-static shapes when box3dAdapterSetTransparentDynamic is on.
|
||||
#define BOX3D_TRANSPARENT_DYNAMIC_ALPHA 0.5f
|
||||
|
||||
// Emit one resolved primitive at baseTransform. The per-kind offset (sphere
|
||||
// center, capsule frame) layers on top of baseTransform, so the same path
|
||||
// serves a top-level shape (base = body transform) and a compound child
|
||||
// (base = body transform composed with the child transform).
|
||||
static void AppendResolvedShape( const DebugShape* us, b3Transform baseTransform, Vec4 c, float metallic, float roughness,
|
||||
TransparentShadowCast shadowCast, HighlightKind hk )
|
||||
{
|
||||
if ( us->kind == Box3DUS_Sphere )
|
||||
{
|
||||
b3Transform transform = { b3TransformPoint( baseTransform, us->sphere.center ), baseTransform.q };
|
||||
AppendSphere( transform, us->sphere.radius, c, metallic, roughness, shadowCast );
|
||||
if ( hk != HIGHLIGHT_KIND_NONE )
|
||||
{
|
||||
AppendHighlightSphere( transform, us->sphere.radius, hk );
|
||||
}
|
||||
}
|
||||
else if ( us->kind == Box3DUS_Capsule )
|
||||
{
|
||||
b3Transform transform = b3MulTransforms( baseTransform, us->capsule.localFrame );
|
||||
AppendCapsule( transform, us->capsule.halfLength, us->capsule.radius, c, metallic, roughness, shadowCast );
|
||||
if ( hk != HIGHLIGHT_KIND_NONE )
|
||||
{
|
||||
AppendHighlightCapsule( transform, us->capsule.halfLength, us->capsule.radius, hk );
|
||||
}
|
||||
}
|
||||
else if ( us->kind == Box3DUS_Hull || us->kind == Box3DUS_Mesh || us->kind == Box3DUS_HeightField )
|
||||
{
|
||||
MeshMaterialMode mode = us->isGround ? MESH_MATERIAL_MODE_GROUND_GRID : MESH_MATERIAL_MODE_SOLID;
|
||||
float cell = us->isGround ? BOX3D_GROUND_GRID_CELL_SIZE : 0.0f;
|
||||
AppendMesh( us->geom.handle, baseTransform, us->geom.scale, c, metallic, roughness, mode, cell, shadowCast );
|
||||
if ( hk != HIGHLIGHT_KIND_NONE && us->kind == Box3DUS_Hull )
|
||||
{
|
||||
AppendHighlightHull( us->geom.handle, baseTransform, us->geom.scale, hk );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static bool DrawShape( void* userShape, b3Transform shapeTransform, b3HexColor color, void* context )
|
||||
{
|
||||
(void)context;
|
||||
if ( userShape == NULL )
|
||||
{
|
||||
return true; // unsupported shape type, skip and continue
|
||||
}
|
||||
|
||||
DebugShape* us = (DebugShape*)userShape;
|
||||
|
||||
RefreshMaterialFromOverride( us );
|
||||
|
||||
Vec4 c;
|
||||
float metallic;
|
||||
float roughness;
|
||||
if ( us->hasMaterial )
|
||||
{
|
||||
c = us->color;
|
||||
metallic = us->metallic;
|
||||
roughness = us->roughness;
|
||||
}
|
||||
else
|
||||
{
|
||||
c = HexColorToLinear( color );
|
||||
|
||||
// State-driven preset rides in the color high byte. Default falls back to
|
||||
// the per-bodyType material.
|
||||
b3DebugMaterial preset = (b3DebugMaterial)( ( (uint32_t)color >> 24 ) & 0xFFu );
|
||||
if ( preset > b3_debugMaterialDefault && preset <= b3_debugMaterialMetallic )
|
||||
{
|
||||
metallic = kDebugMaterialMetallic[preset];
|
||||
roughness = kDebugMaterialRoughness[preset];
|
||||
}
|
||||
else
|
||||
{
|
||||
int type = (int)us->bodyType;
|
||||
metallic = ( type >= 0 && type < 3 ) ? kBodyTypeMetallic[type] : 0.0f;
|
||||
roughness = ( type >= 0 && type < 3 ) ? kBodyTypeRoughness[type] : 0.5f;
|
||||
}
|
||||
}
|
||||
|
||||
if ( s_adapter.transparentDynamic && us->bodyType == b3_dynamicBody )
|
||||
{
|
||||
c.w = BOX3D_TRANSPARENT_DYNAMIC_ALPHA;
|
||||
}
|
||||
|
||||
TransparentShadowCast shadowCast = TRANSPARENT_SHADOW_NONE;
|
||||
|
||||
// Resolve hover/select state once. Body-keyed, so every supported shape on
|
||||
// a hovered/selected body outlines together, compound children included.
|
||||
HighlightKind hk = ResolveHighlightKind( us->bodyId );
|
||||
|
||||
if ( us->kind == Box3DUS_Compound )
|
||||
{
|
||||
for ( int ci = us->compound.firstChild; ci != -1; ci = s_adapter.pool[ci].nextChild )
|
||||
{
|
||||
b3Transform base = b3MulTransforms( shapeTransform, s_adapter.pool[ci].childTransform );
|
||||
AppendResolvedShape( &s_adapter.pool[ci], base, c, metallic, roughness, shadowCast, hk );
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
AppendResolvedShape( us, shapeTransform, c, metallic, roughness, shadowCast, hk );
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
#define BOX3D_LINE_THICKNESS_PX 2.5f
|
||||
#define BOX3D_TRANSFORM_LENGTH (0.25f * b3GetLengthUnitsPerMeter())
|
||||
|
||||
static void DrawSegmentFcn( b3Vec3 p1, b3Vec3 p2, b3HexColor color, void* context )
|
||||
{
|
||||
(void)context;
|
||||
OverlayAppendLine( p1, p2, HexColorToVec4( color ), BOX3D_LINE_THICKNESS_PX, OVERLAY_THICKNESS_PIXELS,
|
||||
OVERLAY_OCCLUSION_HIDE );
|
||||
}
|
||||
|
||||
static void DrawTransformFcn( b3Transform transform, void* context )
|
||||
{
|
||||
(void)context;
|
||||
b3Vec3 origin = transform.p;
|
||||
b3Matrix3 basis = b3MakeMatrixFromQuat( transform.q );
|
||||
float L = BOX3D_TRANSFORM_LENGTH;
|
||||
Vec4 red = MakeVec4( 1.0f, 0.0f, 0.0f, 1.0f );
|
||||
Vec4 green = MakeVec4( 0.0f, 1.0f, 0.0f, 1.0f );
|
||||
Vec4 blue = MakeVec4( 0.0f, 0.0f, 1.0f, 1.0f );
|
||||
OverlayAppendLine( origin, b3MulAdd( origin, L, basis.cx ), red, BOX3D_LINE_THICKNESS_PX, OVERLAY_THICKNESS_PIXELS,
|
||||
OVERLAY_OCCLUSION_HIDE );
|
||||
OverlayAppendLine( origin, b3MulAdd( origin, L, basis.cy ), green, BOX3D_LINE_THICKNESS_PX, OVERLAY_THICKNESS_PIXELS,
|
||||
OVERLAY_OCCLUSION_HIDE );
|
||||
OverlayAppendLine( origin, b3MulAdd( origin, L, basis.cz ), blue, BOX3D_LINE_THICKNESS_PX, OVERLAY_THICKNESS_PIXELS,
|
||||
OVERLAY_OCCLUSION_HIDE );
|
||||
}
|
||||
|
||||
static void DrawPointFcn( b3Vec3 p, float size, b3HexColor color, void* context )
|
||||
{
|
||||
(void)context;
|
||||
OverlayAppendPoint( p, HexColorToVec4( color ), size, OVERLAY_THICKNESS_PIXELS, OVERLAY_OCCLUSION_HIDE );
|
||||
}
|
||||
|
||||
static void DrawBoundsFcn( b3AABB aabb, b3HexColor color, void* context )
|
||||
{
|
||||
(void)context;
|
||||
|
||||
b3Vec3 lower = aabb.lowerBound;
|
||||
b3Vec3 upper = aabb.upperBound;
|
||||
Vec4 c = HexColorToVec4( color );
|
||||
|
||||
b3Vec3 c000 = { lower.x, lower.y, lower.z };
|
||||
b3Vec3 c100 = { upper.x, lower.y, lower.z };
|
||||
b3Vec3 c010 = { lower.x, upper.y, lower.z };
|
||||
b3Vec3 c110 = { upper.x, upper.y, lower.z };
|
||||
b3Vec3 c001 = { lower.x, lower.y, upper.z };
|
||||
b3Vec3 c101 = { upper.x, lower.y, upper.z };
|
||||
b3Vec3 c011 = { lower.x, upper.y, upper.z };
|
||||
b3Vec3 c111 = { upper.x, upper.y, upper.z };
|
||||
|
||||
float th = BOX3D_LINE_THICKNESS_PX;
|
||||
OverlayThicknessUnit u = OVERLAY_THICKNESS_PIXELS;
|
||||
OverlayOcclusionMode o = OVERLAY_OCCLUSION_HIDE;
|
||||
|
||||
// Bottom face
|
||||
OverlayAppendLine( c000, c100, c, th, u, o );
|
||||
OverlayAppendLine( c100, c101, c, th, u, o );
|
||||
OverlayAppendLine( c101, c001, c, th, u, o );
|
||||
OverlayAppendLine( c001, c000, c, th, u, o );
|
||||
|
||||
// Top face
|
||||
OverlayAppendLine( c010, c110, c, th, u, o );
|
||||
OverlayAppendLine( c110, c111, c, th, u, o );
|
||||
OverlayAppendLine( c111, c011, c, th, u, o );
|
||||
OverlayAppendLine( c011, c010, c, th, u, o );
|
||||
|
||||
// Vertical edges
|
||||
OverlayAppendLine( c000, c010, c, th, u, o );
|
||||
OverlayAppendLine( c100, c110, c, th, u, o );
|
||||
OverlayAppendLine( c101, c111, c, th, u, o );
|
||||
OverlayAppendLine( c001, c011, c, th, u, o );
|
||||
}
|
||||
|
||||
// Oriented box: 8 corners are transform * (+/-ex, +/-ey, +/-ez). 12 edges
|
||||
// connect adjacent corners along each axis.
|
||||
static void DrawBoxFcn( b3Vec3 extents, b3Transform transform, b3HexColor color, void* context )
|
||||
{
|
||||
(void)context;
|
||||
Vec4 c = HexColorToVec4( color );
|
||||
|
||||
// Local-space corners (8 = 2^3 sign combinations along each axis).
|
||||
float signs[2] = { -1.0f, 1.0f };
|
||||
b3Vec3 corners[8];
|
||||
for ( int xi = 0; xi < 2; ++xi )
|
||||
{
|
||||
for ( int yi = 0; yi < 2; ++yi )
|
||||
{
|
||||
for ( int zi = 0; zi < 2; ++zi )
|
||||
{
|
||||
float lx = signs[xi] * extents.x;
|
||||
float ly = signs[yi] * extents.y;
|
||||
float lz = signs[zi] * extents.z;
|
||||
corners[( xi << 2 ) | ( yi << 1 ) | zi] = b3TransformPoint( transform, (b3Vec3){ lx, ly, lz } );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Edges: bit-pattern walk where each edge connects two corner indices
|
||||
// that differ in exactly one axis bit.
|
||||
int edges[12][2] = {
|
||||
{ 0, 4 }, { 4, 5 }, { 5, 1 }, { 1, 0 }, // bottom face (yi = 0)
|
||||
{ 2, 6 }, { 6, 7 }, { 7, 3 }, { 3, 2 }, // top face (yi = 1)
|
||||
{ 0, 2 }, { 4, 6 }, { 5, 7 }, { 1, 3 }, // verticals (yi differs)
|
||||
};
|
||||
|
||||
float th = BOX3D_LINE_THICKNESS_PX;
|
||||
OverlayThicknessUnit u = OVERLAY_THICKNESS_PIXELS;
|
||||
OverlayOcclusionMode o = OVERLAY_OCCLUSION_HIDE;
|
||||
|
||||
for ( int i = 0; i < 12; ++i )
|
||||
{
|
||||
OverlayAppendLine( corners[edges[i][0]], corners[edges[i][1]], c, th, u, o );
|
||||
}
|
||||
}
|
||||
|
||||
static void DrawStringFcn( b3Vec3 p, const char* s, b3HexColor color, void* context )
|
||||
{
|
||||
(void)context;
|
||||
if ( s == NULL )
|
||||
{
|
||||
return;
|
||||
}
|
||||
DrawString( p, HexColorToVec4( color ), s );
|
||||
}
|
||||
|
||||
void AttachToWorldDef( b3WorldDef* def )
|
||||
{
|
||||
assert( def != NULL );
|
||||
def->createDebugShape = AdapterCreateDebugShape;
|
||||
def->destroyDebugShape = DestroyDebugShape;
|
||||
def->userDebugShapeContext = NULL;
|
||||
}
|
||||
|
||||
void MakeDebugDraw( b3DebugDraw* out )
|
||||
{
|
||||
assert( out != NULL );
|
||||
|
||||
*out = b3DefaultDebugDraw();
|
||||
|
||||
out->DrawShapeFcn = DrawShape;
|
||||
out->DrawSegmentFcn = DrawSegmentFcn;
|
||||
out->DrawTransformFcn = DrawTransformFcn;
|
||||
out->DrawPointFcn = DrawPointFcn;
|
||||
out->DrawBoundsFcn = DrawBoundsFcn;
|
||||
out->DrawBoxFcn = DrawBoxFcn;
|
||||
out->DrawStringFcn = DrawStringFcn;
|
||||
|
||||
// No context needed because globals are used
|
||||
out->context = NULL;
|
||||
}
|
||||
45
samples/gfx/debug_adapter.h
Normal file
45
samples/gfx/debug_adapter.h
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "box3d/types.h"
|
||||
#include "gfx/utility.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"
|
||||
{
|
||||
#endif
|
||||
|
||||
void InitAdapter( void );
|
||||
|
||||
// Unconditionally flush the debug-shape pool: release the GPU mesh references
|
||||
// held by live hull/mesh/heightfield shapes and rebuild the free list. Call
|
||||
// before b3DestroyWorld (or on scene switch). Defensive even when
|
||||
// destroyDebugShape already fired for every shape. After this,
|
||||
// GetDebugShapeCount() == 0 and the next world allocates from the pool bottom.
|
||||
void ResetAdapterPool( void );
|
||||
|
||||
void AttachToWorldDef( b3WorldDef* def );
|
||||
void MakeDebugDraw( b3DebugDraw* out );
|
||||
b3DebugDraw* GetGuiDraw( void );
|
||||
void ApplyGuiFlags( b3DebugDraw* out );
|
||||
int GetDebugShapeCount( void );
|
||||
|
||||
// Tag a Box3D shape so the renderer draws it with the procedural ground grid.
|
||||
void SetGroundShape( b3ShapeId shapeId );
|
||||
void SetShapeMaterial( b3ShapeId shapeId, Vec4 color, float metallic, float roughness );
|
||||
void SetTransparentDynamic( bool enabled );
|
||||
bool GetTransparentDynamic( void );
|
||||
|
||||
void SetHoveredBody( b3BodyId bodyId );
|
||||
b3BodyId GetHoveredBody( void );
|
||||
|
||||
void SetSelectedBody( b3BodyId bodyId );
|
||||
void ClearSelection( void );
|
||||
b3BodyId GetSelectedBody( void );
|
||||
bool IsBodySelected( b3BodyId bodyId );
|
||||
|
||||
#ifdef __cplusplus
|
||||
} // extern "C"
|
||||
#endif
|
||||
839
samples/gfx/debug_shapes.c
Normal file
839
samples/gfx/debug_shapes.c
Normal file
|
|
@ -0,0 +1,839 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "gfx/debug_shapes.h"
|
||||
|
||||
#include "gfx/qsort.h"
|
||||
|
||||
#include <assert.h>
|
||||
#include <math.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
// vertex/index buffer construction helpers
|
||||
|
||||
typedef struct BuildBuffer
|
||||
{
|
||||
MeshVertex* vertices;
|
||||
int vertexCount;
|
||||
int vertexCapacity;
|
||||
|
||||
uint32_t* indices;
|
||||
int indexCount;
|
||||
int indexCapacity;
|
||||
} BuildBuffer;
|
||||
|
||||
// Edge build record. Stored only on the CPU during shape acquire, sorted
|
||||
// and deduplicated in place, then expanded into EdgeVertex pairs at upload
|
||||
// time. `v0 < v1` after canonicalization so duplicate edges from adjacent
|
||||
// triangles compare equal regardless of which triangle emitted them.
|
||||
typedef struct EdgeRecord
|
||||
{
|
||||
uint32_t v0;
|
||||
uint32_t v1;
|
||||
uint32_t flags;
|
||||
} EdgeRecord;
|
||||
|
||||
typedef struct EdgeBuilder
|
||||
{
|
||||
EdgeRecord* edges;
|
||||
int count;
|
||||
int capacity;
|
||||
} EdgeBuilder;
|
||||
|
||||
// Render class carried in the edge flag. Convex must stay 1 so hull edges
|
||||
// (which emit 1u directly) keep their color. Concave stays 0 to match the
|
||||
// old binary flag value.
|
||||
typedef enum EdgeClass
|
||||
{
|
||||
EDGE_CONCAVE = 0,
|
||||
EDGE_CONVEX = 1,
|
||||
EDGE_FLAT = 2,
|
||||
} EdgeClass;
|
||||
|
||||
// Collapse Box3D's two-bit edge flags to a render class. Concave bit clear
|
||||
// means convex, a true convex edge or an open boundary with neither bit.
|
||||
// Both bits set means nearly coplanar.
|
||||
static uint32_t ClassifyEdge( uint8_t flags, uint8_t concaveBit, uint8_t inverseBit )
|
||||
{
|
||||
if ( flags & concaveBit )
|
||||
{
|
||||
return ( flags & inverseBit ) ? (uint32_t)EDGE_FLAT : (uint32_t)EDGE_CONCAVE;
|
||||
}
|
||||
return (uint32_t)EDGE_CONVEX;
|
||||
}
|
||||
|
||||
// Dedup priority when two adjacent triangles disagree on a shared edge. They
|
||||
// normally agree, this only matters at non-manifold joints. Convex wins as the
|
||||
// most prominent feature, then concave, then flat.
|
||||
static uint32_t EdgeClassRank( uint32_t c )
|
||||
{
|
||||
if ( c == EDGE_CONVEX )
|
||||
{
|
||||
return 2;
|
||||
}
|
||||
if ( c == EDGE_CONCAVE )
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static bool EdgeBuilderReserve( EdgeBuilder* b, int extra )
|
||||
{
|
||||
const int need = b->count + extra;
|
||||
if ( need <= b->capacity )
|
||||
{
|
||||
return true;
|
||||
}
|
||||
int newCap = b->capacity == 0 ? 64 : b->capacity;
|
||||
while ( newCap < need )
|
||||
{
|
||||
newCap *= 2;
|
||||
}
|
||||
EdgeRecord* grown = (EdgeRecord*)realloc( b->edges, (size_t)newCap * sizeof( EdgeRecord ) );
|
||||
if ( !grown )
|
||||
{
|
||||
fprintf( stderr, "error: edge buffer realloc failed (cap=%d)\n", newCap );
|
||||
return false;
|
||||
}
|
||||
b->edges = grown;
|
||||
b->capacity = newCap;
|
||||
return true;
|
||||
}
|
||||
|
||||
static void EdgeBuilderFree( EdgeBuilder* b )
|
||||
{
|
||||
free( b->edges );
|
||||
b->edges = NULL;
|
||||
b->count = 0;
|
||||
b->capacity = 0;
|
||||
}
|
||||
|
||||
// Push one canonicalized edge into the builder. Returns false on OOM.
|
||||
static bool EmitEdge( EdgeBuilder* b, uint32_t a, uint32_t c, uint32_t flag )
|
||||
{
|
||||
if ( !EdgeBuilderReserve( b, 1 ) )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
EdgeRecord* r = &b->edges[b->count++];
|
||||
if ( a <= c )
|
||||
{
|
||||
r->v0 = a;
|
||||
r->v1 = c;
|
||||
}
|
||||
else
|
||||
{
|
||||
r->v0 = c;
|
||||
r->v1 = a;
|
||||
}
|
||||
r->flags = flag;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Expand a sorted, deduplicated EdgeRecord array into the EdgeVertex pair
|
||||
// layout the geometry registry wants. Two consecutive EdgeVertex entries per
|
||||
// edge (the two endpoints), each carrying the same `flags`. Returns NULL on
|
||||
// OOM (caller treats as "no edges").
|
||||
static EdgeVertex* ExpandEdgesForUpload( const EdgeRecord* edges, int edgeCount, const b3Vec3* vertices )
|
||||
{
|
||||
if ( edgeCount == 0 )
|
||||
{
|
||||
return NULL;
|
||||
}
|
||||
|
||||
EdgeVertex* out = (EdgeVertex*)malloc( (size_t)( 2 * edgeCount ) * sizeof( EdgeVertex ) );
|
||||
if ( !out )
|
||||
{
|
||||
fprintf( stderr, "error: edge upload buffer alloc failed (edges=%d)\n", edgeCount );
|
||||
return NULL;
|
||||
}
|
||||
|
||||
for ( int i = 0; i < edgeCount; ++i )
|
||||
{
|
||||
const EdgeRecord r = edges[i];
|
||||
const b3Vec3 a = vertices[r.v0];
|
||||
const b3Vec3 c = vertices[r.v1];
|
||||
const float flagF = (float)r.flags;
|
||||
out[2 * i + 0].position[0] = a.x;
|
||||
out[2 * i + 0].position[1] = a.y;
|
||||
out[2 * i + 0].position[2] = a.z;
|
||||
out[2 * i + 0].flag = flagF;
|
||||
out[2 * i + 1].position[0] = c.x;
|
||||
out[2 * i + 1].position[1] = c.y;
|
||||
out[2 * i + 1].position[2] = c.z;
|
||||
out[2 * i + 1].flag = flagF;
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
static bool BufferReserveVertices( BuildBuffer* b, int extra )
|
||||
{
|
||||
const int need = b->vertexCount + extra;
|
||||
if ( need <= b->vertexCapacity )
|
||||
{
|
||||
return true;
|
||||
}
|
||||
int newCap = b->vertexCapacity == 0 ? 256 : b->vertexCapacity;
|
||||
while ( newCap < need )
|
||||
{
|
||||
newCap *= 2;
|
||||
}
|
||||
MeshVertex* grown = (MeshVertex*)realloc( b->vertices, (size_t)newCap * sizeof( MeshVertex ) );
|
||||
if ( !grown )
|
||||
{
|
||||
fprintf( stderr, "error: vertex buffer realloc failed (cap=%d)\n", newCap );
|
||||
return false;
|
||||
}
|
||||
b->vertices = grown;
|
||||
b->vertexCapacity = newCap;
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool BufferReserveIndices( BuildBuffer* b, int extra )
|
||||
{
|
||||
const int need = b->indexCount + extra;
|
||||
if ( need <= b->indexCapacity )
|
||||
{
|
||||
return true;
|
||||
}
|
||||
int newCap = b->indexCapacity == 0 ? 384 : b->indexCapacity;
|
||||
while ( newCap < need )
|
||||
{
|
||||
newCap *= 2;
|
||||
}
|
||||
uint32_t* grown = (uint32_t*)realloc( b->indices, (size_t)newCap * sizeof( uint32_t ) );
|
||||
if ( !grown )
|
||||
{
|
||||
fprintf( stderr, "error: index buffer realloc failed (cap=%d)\n", newCap );
|
||||
return false;
|
||||
}
|
||||
b->indices = grown;
|
||||
b->indexCapacity = newCap;
|
||||
return true;
|
||||
}
|
||||
|
||||
static void BufferFree( BuildBuffer* b )
|
||||
{
|
||||
free( b->vertices );
|
||||
free( b->indices );
|
||||
b->vertices = NULL;
|
||||
b->indices = NULL;
|
||||
b->vertexCount = 0;
|
||||
b->vertexCapacity = 0;
|
||||
b->indexCount = 0;
|
||||
b->indexCapacity = 0;
|
||||
}
|
||||
|
||||
// Append three vertices (one triangle) with a shared face normal and add
|
||||
// three consecutive indices that reference them. Returns false on OOM.
|
||||
static bool EmitFlatTriangle( BuildBuffer* b, b3Vec3 p0, b3Vec3 p1, b3Vec3 p2, b3Vec3 normal )
|
||||
{
|
||||
if ( !BufferReserveVertices( b, 3 ) || !BufferReserveIndices( b, 3 ) )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
MeshVertex* v = &b->vertices[b->vertexCount];
|
||||
v[0].position[0] = p0.x;
|
||||
v[0].position[1] = p0.y;
|
||||
v[0].position[2] = p0.z;
|
||||
v[0].normal[0] = normal.x;
|
||||
v[0].normal[1] = normal.y;
|
||||
v[0].normal[2] = normal.z;
|
||||
v[1].position[0] = p1.x;
|
||||
v[1].position[1] = p1.y;
|
||||
v[1].position[2] = p1.z;
|
||||
v[1].normal[0] = normal.x;
|
||||
v[1].normal[1] = normal.y;
|
||||
v[1].normal[2] = normal.z;
|
||||
v[2].position[0] = p2.x;
|
||||
v[2].position[1] = p2.y;
|
||||
v[2].position[2] = p2.z;
|
||||
v[2].normal[0] = normal.x;
|
||||
v[2].normal[1] = normal.y;
|
||||
v[2].normal[2] = normal.z;
|
||||
|
||||
const uint32_t base = (uint32_t)b->vertexCount;
|
||||
b->indices[b->indexCount + 0] = base + 0u;
|
||||
b->indices[b->indexCount + 1] = base + 1u;
|
||||
b->indices[b->indexCount + 2] = base + 2u;
|
||||
|
||||
b->vertexCount += 3;
|
||||
b->indexCount += 3;
|
||||
return true;
|
||||
}
|
||||
|
||||
static b3Vec3 TriangleNormal( b3Vec3 a, b3Vec3 b, b3Vec3 c )
|
||||
{
|
||||
const float ex = b.x - a.x, ey = b.y - a.y, ez = b.z - a.z;
|
||||
const float fx = c.x - a.x, fy = c.y - a.y, fz = c.z - a.z;
|
||||
b3Vec3 n;
|
||||
n.x = ey * fz - ez * fy;
|
||||
n.y = ez * fx - ex * fz;
|
||||
n.z = ex * fy - ey * fx;
|
||||
const float lenSq = n.x * n.x + n.y * n.y + n.z * n.z;
|
||||
if ( lenSq > 1.0e-20f )
|
||||
{
|
||||
const float inv = 1.0f / sqrtf( lenSq );
|
||||
n.x *= inv;
|
||||
n.y *= inv;
|
||||
n.z *= inv;
|
||||
}
|
||||
else
|
||||
{
|
||||
n.x = 0.0f;
|
||||
n.y = 1.0f;
|
||||
n.z = 0.0f;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
static MeshHandle BuildHull( const b3Hull* hull )
|
||||
{
|
||||
const b3Vec3* points = b3GetHullPoints( hull );
|
||||
const b3HullHalfEdge* edges = b3GetHullEdges( hull );
|
||||
const b3HullFace* faces = b3GetHullFaces( hull );
|
||||
const b3Plane* planes = b3GetHullPlanes( hull );
|
||||
if ( !points || !edges || !faces || !planes )
|
||||
{
|
||||
fprintf( stderr, "error: hull missing arrays (hash=0x%08x)\n", hull->hash );
|
||||
return InvalidMeshHandle();
|
||||
}
|
||||
|
||||
BuildBuffer buf = { 0 };
|
||||
EdgeBuilder eb = { 0 };
|
||||
|
||||
// Per-face fan triangulation. Each face's half-edges form a CCW loop
|
||||
// (viewed from outside, against the face's outward normal). The fan
|
||||
// pivot is the loop's first vertex, subsequent triangles are
|
||||
// (v0, v_i, v_{i+1}) for i from 1 to count-2. Plane normal carries
|
||||
// the outward direction.
|
||||
for ( int faceIdx = 0; faceIdx < hull->faceCount; ++faceIdx )
|
||||
{
|
||||
const b3HullFace face = faces[faceIdx];
|
||||
const b3Vec3 normal = planes[faceIdx].normal;
|
||||
const uint8_t startEdge = face.edge;
|
||||
|
||||
// First pass: count loop length so we know how to fan it. b3 hull
|
||||
// faces are bounded (max half-edge count fits a uint8_t) so this
|
||||
// terminates cleanly.
|
||||
uint8_t e = startEdge;
|
||||
int loopLen = 0;
|
||||
do
|
||||
{
|
||||
loopLen += 1;
|
||||
e = edges[e].next;
|
||||
if ( loopLen > 256 )
|
||||
{
|
||||
fprintf( stderr, "error: hull face loop runaway (hash=0x%08x)\n", hull->hash );
|
||||
BufferFree( &buf );
|
||||
return InvalidMeshHandle();
|
||||
}
|
||||
}
|
||||
while ( e != startEdge );
|
||||
|
||||
if ( loopLen < 3 )
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Second pass: emit fan. Collect the loop's vertex indices on the stack.
|
||||
// loopLen <= 256.
|
||||
uint8_t loop[256];
|
||||
e = startEdge;
|
||||
for ( int i = 0; i < loopLen; ++i )
|
||||
{
|
||||
loop[i] = edges[e].origin;
|
||||
e = edges[e].next;
|
||||
}
|
||||
|
||||
b3Vec3 p0 = points[loop[0]];
|
||||
for ( int i = 1; i < loopLen - 1; ++i )
|
||||
{
|
||||
b3Vec3 p1 = points[loop[i]];
|
||||
b3Vec3 p2 = points[loop[i + 1]];
|
||||
if ( !EmitFlatTriangle( &buf, p0, p1, p2, normal ) )
|
||||
{
|
||||
BufferFree( &buf );
|
||||
return InvalidMeshHandle();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ( buf.indexCount == 0 )
|
||||
{
|
||||
BufferFree( &buf );
|
||||
return InvalidMeshHandle();
|
||||
}
|
||||
|
||||
// Emit hull edges. This automatically prevents duplicates. No sorting needed.
|
||||
int pairCount = hull->edgeCount / 2;
|
||||
for ( int i = 0; i < pairCount; i += 1 )
|
||||
{
|
||||
uint8_t a = edges[2 * i + 0].origin;
|
||||
uint8_t c = edges[2 * i + 1].origin;
|
||||
|
||||
if ( !EmitEdge( &eb, (uint32_t)a, (uint32_t)c, 1u ) )
|
||||
{
|
||||
EdgeBuilderFree( &eb );
|
||||
BufferFree( &buf );
|
||||
return InvalidMeshHandle();
|
||||
}
|
||||
}
|
||||
|
||||
MeshHandle h = RegisterMesh( hull->hash, buf.vertices, buf.vertexCount, buf.indices, buf.indexCount, "geom_hull" );
|
||||
|
||||
if ( IsMeshHandleValid( h ) )
|
||||
{
|
||||
SetMeshKind( h, MESH_KIND_HULL );
|
||||
if ( eb.count > 0 )
|
||||
{
|
||||
EdgeVertex* upload = ExpandEdgesForUpload( eb.edges, eb.count, points );
|
||||
if ( upload )
|
||||
{
|
||||
RegisterMeshEdges( h, upload, eb.count, "geom_hull_edges" );
|
||||
free( upload );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
EdgeBuilderFree( &eb );
|
||||
BufferFree( &buf );
|
||||
return h;
|
||||
}
|
||||
|
||||
// Mesh edge sort/dedup. EdgeRecord is canonicalized (v0 <= v1) by emitEdge,
|
||||
// so a shared interior edge from two adjacent triangles compares equal and
|
||||
// the unique pass drops the duplicate. Sort key is (v0, v1) lex order.
|
||||
static inline int MeshEdgeLess( const EdgeRecord* a, const EdgeRecord* b )
|
||||
{
|
||||
if ( a->v0 != b->v0 )
|
||||
{
|
||||
return a->v0 < b->v0;
|
||||
}
|
||||
return a->v1 < b->v1;
|
||||
}
|
||||
|
||||
static MeshHandle BuildMeshData( const b3MeshData* meshData )
|
||||
{
|
||||
const b3Vec3* verts = b3GetMeshVertices( meshData );
|
||||
const b3MeshTriangle* tris = b3GetMeshTriangles( meshData );
|
||||
const uint8_t* flags = b3GetMeshFlags( meshData );
|
||||
if ( !verts || !tris || meshData->triangleCount <= 0 )
|
||||
{
|
||||
fprintf( stderr, "error: mesh missing arrays or empty (hash=0x%08x)\n", meshData->hash );
|
||||
return InvalidMeshHandle();
|
||||
}
|
||||
|
||||
BuildBuffer buf = { 0 };
|
||||
EdgeBuilder eb = { 0 };
|
||||
|
||||
for ( int t = 0; t < meshData->triangleCount; ++t )
|
||||
{
|
||||
const b3MeshTriangle tri = tris[t];
|
||||
const b3Vec3 a = verts[tri.index1];
|
||||
const b3Vec3 b = verts[tri.index2];
|
||||
const b3Vec3 c = verts[tri.index3];
|
||||
const b3Vec3 n = TriangleNormal( a, b, c );
|
||||
if ( !EmitFlatTriangle( &buf, a, b, c, n ) )
|
||||
{
|
||||
EdgeBuilderFree( &eb );
|
||||
BufferFree( &buf );
|
||||
return InvalidMeshHandle();
|
||||
}
|
||||
|
||||
// Emit all three edges, classified by convexity
|
||||
const uint8_t f = flags ? flags[t] : 0u;
|
||||
bool ok = EmitEdge( &eb, (uint32_t)tri.index1, (uint32_t)tri.index2,
|
||||
ClassifyEdge( f, b3_concaveEdge1, b3_inverseConcaveEdge1 ) );
|
||||
if ( ok )
|
||||
{
|
||||
ok = EmitEdge( &eb, (uint32_t)tri.index2, (uint32_t)tri.index3,
|
||||
ClassifyEdge( f, b3_concaveEdge2, b3_inverseConcaveEdge2 ) );
|
||||
}
|
||||
|
||||
if ( ok )
|
||||
{
|
||||
ok = EmitEdge( &eb, (uint32_t)tri.index3, (uint32_t)tri.index1,
|
||||
ClassifyEdge( f, b3_concaveEdge3, b3_inverseConcaveEdge3 ) );
|
||||
}
|
||||
|
||||
if ( !ok )
|
||||
{
|
||||
EdgeBuilderFree( &eb );
|
||||
BufferFree( &buf );
|
||||
return InvalidMeshHandle();
|
||||
}
|
||||
}
|
||||
|
||||
if ( buf.indexCount == 0 )
|
||||
{
|
||||
EdgeBuilderFree( &eb );
|
||||
BufferFree( &buf );
|
||||
return InvalidMeshHandle();
|
||||
}
|
||||
|
||||
// Sort + unique on the canonicalized (v0, v1) key. svpv/qsort macro
|
||||
// inlines the comparator and swap so this is fast even for very dense
|
||||
// meshes, runs once at acquire, not per frame.
|
||||
if ( eb.count > 1 )
|
||||
{
|
||||
#define LESS( i, j ) MeshEdgeLess( &eb.edges[(int)( i )], &eb.edges[(int)( j )] )
|
||||
#define SWAP( i, j ) \
|
||||
do \
|
||||
{ \
|
||||
EdgeRecord tmp_ = eb.edges[(int)( i )]; \
|
||||
eb.edges[(int)( i )] = eb.edges[(int)( j )]; \
|
||||
eb.edges[(int)( j )] = tmp_; \
|
||||
} \
|
||||
while ( 0 )
|
||||
|
||||
QSORT( eb.count, LESS, SWAP );
|
||||
#undef LESS
|
||||
#undef SWAP
|
||||
|
||||
// In-place unique. Two records compare equal when (v0, v1) match.
|
||||
// On a flag tie the higher-rank class wins so the overlay renders the
|
||||
// edge in the more prominent color when the two triangles' bits
|
||||
// disagree (rare but possible at non-manifold joints).
|
||||
int write = 0;
|
||||
for ( int read = 1; read < eb.count; ++read )
|
||||
{
|
||||
EdgeRecord* w = &eb.edges[write];
|
||||
EdgeRecord* r = &eb.edges[read];
|
||||
if ( w->v0 == r->v0 && w->v1 == r->v1 )
|
||||
{
|
||||
if ( EdgeClassRank( r->flags ) > EdgeClassRank( w->flags ) )
|
||||
{
|
||||
w->flags = r->flags;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
++write;
|
||||
eb.edges[write] = *r;
|
||||
}
|
||||
}
|
||||
eb.count = write + 1;
|
||||
}
|
||||
|
||||
const MeshHandle h = RegisterMesh( meshData->hash, buf.vertices, buf.vertexCount, buf.indices, buf.indexCount, "geom_mesh" );
|
||||
|
||||
if ( IsMeshHandleValid( h ) )
|
||||
{
|
||||
SetMeshKind( h, MESH_KIND_MESH );
|
||||
if ( eb.count > 0 )
|
||||
{
|
||||
EdgeVertex* upload = ExpandEdgesForUpload( eb.edges, eb.count, verts );
|
||||
if ( upload )
|
||||
{
|
||||
RegisterMeshEdges( h, upload, eb.count, "geom_mesh_edges" );
|
||||
free( upload );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
EdgeBuilderFree( &eb );
|
||||
BufferFree( &buf );
|
||||
return h;
|
||||
}
|
||||
|
||||
static b3Vec3 HeightFieldSample( const b3HeightField* hf, int row, int col )
|
||||
{
|
||||
int index = row * hf->columnCount + col;
|
||||
float decoded = hf->minHeight + hf->heightScale * (float)hf->compressedHeights[index];
|
||||
b3Vec3 scale = hf->scale;
|
||||
b3Vec3 v;
|
||||
v.x = scale.x * (float)col;
|
||||
v.y = scale.y * decoded;
|
||||
v.z = scale.z * (float)row;
|
||||
return v;
|
||||
}
|
||||
|
||||
static MeshHandle BuildHeightField( const b3HeightField* hf )
|
||||
{
|
||||
if ( hf->columnCount < 2 || hf->rowCount < 2 || !hf->compressedHeights )
|
||||
{
|
||||
fprintf( stderr, "error: heightfield degenerate (hash=0x%08x)\n", hf->hash );
|
||||
return InvalidMeshHandle();
|
||||
}
|
||||
|
||||
BuildBuffer buf = { 0 };
|
||||
EdgeBuilder eb = { 0 };
|
||||
|
||||
const int cols = hf->columnCount;
|
||||
const int rows = hf->rowCount;
|
||||
const uint8_t* materials = hf->materialIndices; // may be NULL if all solid
|
||||
const uint8_t* edgeFlags = hf->flags; // per-triangle concave bits
|
||||
const bool clockwise = hf->clockwise;
|
||||
|
||||
// Build a (rows x cols) grid vertex array up front. Triangle emission
|
||||
// stays per-cell with duplicated corners for flat shading, the edge
|
||||
// builder refers to grid indices, so it needs a contiguous grid array
|
||||
// to expand against at upload time.
|
||||
b3Vec3* gridVertices = (b3Vec3*)malloc( (size_t)( rows * cols ) * sizeof( b3Vec3 ) );
|
||||
if ( !gridVertices )
|
||||
{
|
||||
fprintf( stderr, "error: hf grid alloc failed (rows=%d cols=%d)\n", rows, cols );
|
||||
return InvalidMeshHandle();
|
||||
}
|
||||
for ( int row = 0; row < rows; ++row )
|
||||
{
|
||||
for ( int col = 0; col < cols; ++col )
|
||||
{
|
||||
gridVertices[row * cols + col] = HeightFieldSample( hf, row, col );
|
||||
}
|
||||
}
|
||||
|
||||
// Each cell (row, col) covers world rectangle:
|
||||
// x in [scale.x * col, scale.x * (col + 1)]
|
||||
// z in [scale.z * row, scale.z * (row + 1)]
|
||||
// with corner heights at the four grid corners. b3HeightField holds
|
||||
// per-cell material. B3_HEIGHT_FIELD_HOLE (0xFF) marks a hole, skip
|
||||
// both triangles for that cell. Triangulation matches Box3D's collision
|
||||
// triangulation (see height_field.c line 228+):
|
||||
//
|
||||
// tri0: (col, row), (col, row+1), (col+1, row)
|
||||
// tri1: (col+1, row+1), (col+1, row), (col, row+1)
|
||||
//
|
||||
// Box3D's `clockwise` flag flips the index order. The "clockwise"
|
||||
// terminology is the source-side winding seen from +Y above, the
|
||||
// renderer wants CCW-from-outside (which for an upward-facing
|
||||
// heightfield means CCW from +Y). When clockwise=true we mirror the
|
||||
// indices to flip the winding.
|
||||
for ( int row = 0; row < rows - 1; ++row )
|
||||
{
|
||||
for ( int col = 0; col < cols - 1; ++col )
|
||||
{
|
||||
const int cellIndex = row * ( cols - 1 ) + col;
|
||||
if ( materials && materials[cellIndex] == B3_HEIGHT_FIELD_HOLE )
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
const uint32_t i00 = (uint32_t)( row * cols + col );
|
||||
const uint32_t i10 = (uint32_t)( row * cols + col + 1 );
|
||||
const uint32_t i01 = (uint32_t)( ( row + 1 ) * cols + col );
|
||||
const uint32_t i11 = (uint32_t)( ( row + 1 ) * cols + col + 1 );
|
||||
|
||||
const b3Vec3 p00 = gridVertices[i00];
|
||||
const b3Vec3 p10 = gridVertices[i10];
|
||||
const b3Vec3 p01 = gridVertices[i01];
|
||||
const b3Vec3 p11 = gridVertices[i11];
|
||||
|
||||
b3Vec3 a0, b0, c0, a1, b1, c1;
|
||||
if ( clockwise )
|
||||
{
|
||||
a0 = p00;
|
||||
b0 = p10;
|
||||
c0 = p01;
|
||||
a1 = p11;
|
||||
b1 = p01;
|
||||
c1 = p10;
|
||||
}
|
||||
else
|
||||
{
|
||||
a0 = p00;
|
||||
b0 = p01;
|
||||
c0 = p10;
|
||||
a1 = p11;
|
||||
b1 = p10;
|
||||
c1 = p01;
|
||||
}
|
||||
|
||||
const b3Vec3 n0 = TriangleNormal( a0, b0, c0 );
|
||||
const b3Vec3 n1 = TriangleNormal( a1, b1, c1 );
|
||||
if ( !EmitFlatTriangle( &buf, a0, b0, c0, n0 ) || !EmitFlatTriangle( &buf, a1, b1, c1, n1 ) )
|
||||
{
|
||||
EdgeBuilderFree( &eb );
|
||||
BufferFree( &buf );
|
||||
free( gridVertices );
|
||||
return InvalidMeshHandle();
|
||||
}
|
||||
|
||||
// Diagonal edge (shared between tri0 and tri1), classified by
|
||||
// convexity. b3's flag interpretation is fixed to the
|
||||
// source-order triangulation, independent of our render-side
|
||||
// clockwise flip.
|
||||
const int tri0 = 2 * cellIndex;
|
||||
const uint8_t f0 = edgeFlags ? edgeFlags[tri0] : 0u;
|
||||
if ( !EmitEdge( &eb, i10, i01, ClassifyEdge( f0, b3_concaveEdge2, b3_inverseConcaveEdge2 ) ) )
|
||||
{
|
||||
EdgeBuilderFree( &eb );
|
||||
BufferFree( &buf );
|
||||
free( gridVertices );
|
||||
return InvalidMeshHandle();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ( buf.indexCount == 0 )
|
||||
{
|
||||
EdgeBuilderFree( &eb );
|
||||
BufferFree( &buf );
|
||||
free( gridVertices );
|
||||
return InvalidMeshHandle();
|
||||
}
|
||||
|
||||
// Row edges (horizontal, between (row, col) and (row, col+1)). Iterate
|
||||
// every grid row including the outer two. Flag from concaveEdge3 of the
|
||||
// adjacent tri0 (cell below the edge) or, on the boundary row, of the
|
||||
// adjacent tri1 (cell above). Skip edges whose only adjacent cell is a
|
||||
// hole.
|
||||
for ( int row = 0; row < rows; ++row )
|
||||
{
|
||||
for ( int col = 0; col < cols - 1; ++col )
|
||||
{
|
||||
int triangleIndex = -1;
|
||||
if ( row < rows - 1 )
|
||||
{
|
||||
const int cellIndex = row * ( cols - 1 ) + col;
|
||||
if ( !materials || materials[cellIndex] != B3_HEIGHT_FIELD_HOLE )
|
||||
{
|
||||
triangleIndex = 2 * cellIndex;
|
||||
}
|
||||
}
|
||||
if ( triangleIndex < 0 && row > 0 )
|
||||
{
|
||||
const int cellIndex = ( row - 1 ) * ( cols - 1 ) + col;
|
||||
if ( !materials || materials[cellIndex] != B3_HEIGHT_FIELD_HOLE )
|
||||
{
|
||||
triangleIndex = 2 * cellIndex + 1;
|
||||
}
|
||||
}
|
||||
if ( triangleIndex < 0 )
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
const uint8_t f = edgeFlags ? edgeFlags[triangleIndex] : 0u;
|
||||
const uint32_t i0 = (uint32_t)( row * cols + col );
|
||||
const uint32_t i1 = (uint32_t)( row * cols + col + 1 );
|
||||
if ( !EmitEdge( &eb, i0, i1, ClassifyEdge( f, b3_concaveEdge3, b3_inverseConcaveEdge3 ) ) )
|
||||
{
|
||||
EdgeBuilderFree( &eb );
|
||||
BufferFree( &buf );
|
||||
free( gridVertices );
|
||||
return InvalidMeshHandle();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Column edges (vertical, between (row, col) and (row+1, col)). Same
|
||||
// flag-sourcing logic, looking at the cell to the right (concaveEdge1
|
||||
// of its tri0) or, on the boundary column, the cell to the left
|
||||
// (concaveEdge1 of its tri1).
|
||||
for ( int col = 0; col < cols; ++col )
|
||||
{
|
||||
for ( int row = 0; row < rows - 1; ++row )
|
||||
{
|
||||
int triangleIndex = -1;
|
||||
if ( col < cols - 1 )
|
||||
{
|
||||
const int cellIndex = row * ( cols - 1 ) + col;
|
||||
if ( !materials || materials[cellIndex] != B3_HEIGHT_FIELD_HOLE )
|
||||
{
|
||||
triangleIndex = 2 * cellIndex;
|
||||
}
|
||||
}
|
||||
if ( triangleIndex < 0 && col > 0 )
|
||||
{
|
||||
const int cellIndex = row * ( cols - 1 ) + col - 1;
|
||||
if ( !materials || materials[cellIndex] != B3_HEIGHT_FIELD_HOLE )
|
||||
{
|
||||
triangleIndex = 2 * cellIndex + 1;
|
||||
}
|
||||
}
|
||||
if ( triangleIndex < 0 )
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
const uint8_t f = edgeFlags ? edgeFlags[triangleIndex] : 0u;
|
||||
const uint32_t i0 = (uint32_t)( row * cols + col );
|
||||
const uint32_t i1 = (uint32_t)( ( row + 1 ) * cols + col );
|
||||
if ( !EmitEdge( &eb, i0, i1, ClassifyEdge( f, b3_concaveEdge1, b3_inverseConcaveEdge1 ) ) )
|
||||
{
|
||||
EdgeBuilderFree( &eb );
|
||||
BufferFree( &buf );
|
||||
free( gridVertices );
|
||||
return InvalidMeshHandle();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const MeshHandle h = RegisterMesh( hf->hash, buf.vertices, buf.vertexCount, buf.indices, buf.indexCount, "geom_heightfield" );
|
||||
|
||||
if ( IsMeshHandleValid( h ) )
|
||||
{
|
||||
SetMeshKind( h, MESH_KIND_HEIGHTFIELD );
|
||||
if ( eb.count > 0 )
|
||||
{
|
||||
EdgeVertex* upload = ExpandEdgesForUpload( eb.edges, eb.count, gridVertices );
|
||||
if ( upload )
|
||||
{
|
||||
RegisterMeshEdges( h, upload, eb.count, "geom_heightfield_edges" );
|
||||
free( upload );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
EdgeBuilderFree( &eb );
|
||||
BufferFree( &buf );
|
||||
free( gridVertices );
|
||||
return h;
|
||||
}
|
||||
|
||||
MeshHandle FindOrAddHull( const b3Hull* hull )
|
||||
{
|
||||
if ( !hull || hull->hash == 0u )
|
||||
{
|
||||
return InvalidMeshHandle();
|
||||
}
|
||||
|
||||
MeshHandle existing = FindMesh( hull->hash );
|
||||
if ( IsMeshHandleValid( existing ) )
|
||||
{
|
||||
AddMeshReference( existing );
|
||||
return existing;
|
||||
}
|
||||
|
||||
return BuildHull( hull );
|
||||
}
|
||||
|
||||
MeshHandle FindOrAddMesh( const b3MeshData* meshData )
|
||||
{
|
||||
if ( !meshData || meshData->hash == 0u )
|
||||
{
|
||||
return InvalidMeshHandle();
|
||||
}
|
||||
|
||||
MeshHandle existing = FindMesh( meshData->hash );
|
||||
if ( IsMeshHandleValid( existing ) )
|
||||
{
|
||||
AddMeshReference( existing );
|
||||
return existing;
|
||||
}
|
||||
|
||||
return BuildMeshData( meshData );
|
||||
}
|
||||
|
||||
MeshHandle FindOrAddHeightField( const b3HeightField* heightField )
|
||||
{
|
||||
if ( !heightField || heightField->hash == 0u )
|
||||
{
|
||||
return InvalidMeshHandle();
|
||||
}
|
||||
MeshHandle existing = FindMesh( heightField->hash );
|
||||
if ( IsMeshHandleValid( existing ) )
|
||||
{
|
||||
AddMeshReference( existing );
|
||||
return existing;
|
||||
}
|
||||
return BuildHeightField( heightField );
|
||||
}
|
||||
50
samples/gfx/debug_shapes.h
Normal file
50
samples/gfx/debug_shapes.h
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Box3D -> gfx geometry-registry bridge for shapes with intrinsic
|
||||
// topology (hulls, triangle meshes, heightfields).
|
||||
//
|
||||
// Each Acquire* function checks the registry for an existing entry under
|
||||
// the Box3D struct's `hash` field (computed by Box3D at construction) and,
|
||||
// on miss, builds a flat-shaded triangle list and registers it. On hit
|
||||
// the existing entry's refcount is bumped. Symmetric Release* via the
|
||||
// returned MeshHandle goes through ReleaseMeshReference directly.
|
||||
//
|
||||
// All three builders emit duplicated vertices (one per triangle corner)
|
||||
// so the per-vertex normal is the face normal, flat shading falls out
|
||||
// of the rasterizer without any extra shader logic. This costs ~3x the
|
||||
// vertex memory of a deduplicated mesh, acceptable at this scale.
|
||||
//
|
||||
// Builders run from createDebugShape callbacks (Box3D path). They are NOT hot-path,
|
||||
// running once per distinct geometry per renderer session, so transient build
|
||||
// buffers use malloc/free rather than the frame arena.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "box3d/collision.h"
|
||||
#include "gfx/geometry_registry.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"
|
||||
{
|
||||
#endif
|
||||
|
||||
// Acquire a registry handle for the given Box3D hull. Returns an invalid
|
||||
// handle on registry-full or zero hash. The caller owns one refcount. Pair
|
||||
// each Acquire with a single ReleaseMeshReference when the consumer goes away.
|
||||
MeshHandle FindOrAddHull( const b3Hull* hull );
|
||||
|
||||
// Acquire for b3MeshData. The b3Mesh struct's per-instance `scale` is NOT
|
||||
// part of the geometry, callers pass it as the per-instance scale at
|
||||
// draw time. Two b3Mesh sharing the same b3MeshData share one entry.
|
||||
MeshHandle FindOrAddMesh( const b3MeshData* meshData );
|
||||
|
||||
// Acquire for b3HeightField. The `scale` vector is part of the height
|
||||
// field's hash (folded into construction), so two heightfields with
|
||||
// different scales hash to different entries, per-instance scale stays
|
||||
// at (1, 1, 1) for heightfield draws.
|
||||
MeshHandle FindOrAddHeightField( const b3HeightField* heightField );
|
||||
|
||||
#ifdef __cplusplus
|
||||
} // extern "C"
|
||||
#endif
|
||||
370
samples/gfx/draw.c
Normal file
370
samples/gfx/draw.c
Normal file
|
|
@ -0,0 +1,370 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "gfx/draw.h"
|
||||
|
||||
#include "gfx/overlay.h"
|
||||
#include "gfx/renderer.h"
|
||||
#include "gfx/text.h"
|
||||
|
||||
#include <stdarg.h>
|
||||
#include <stdio.h>
|
||||
|
||||
void DrawCubeEx( b3Transform transform, b3Vec3 scale, Vec4 baseColor, float metallic, float roughness,
|
||||
TransparentShadowCast shadowCast )
|
||||
{
|
||||
AppendCube( transform, scale, baseColor, metallic, roughness, shadowCast );
|
||||
}
|
||||
|
||||
void DrawCube( b3Transform transform, b3Vec3 scale, Vec4 baseColor )
|
||||
{
|
||||
DrawCubeEx( transform, scale, baseColor, DEFAULT_METALLIC, DEFAULT_ROUGHNESS, TRANSPARENT_SHADOW_FULL );
|
||||
}
|
||||
|
||||
void DrawSphereEx( b3Transform transform, float radius, Vec4 baseColor, float metallic, float roughness,
|
||||
TransparentShadowCast shadowCast )
|
||||
{
|
||||
AppendSphere( transform, radius, baseColor, metallic, roughness, shadowCast );
|
||||
}
|
||||
|
||||
void DrawSphere( b3Transform transform, float radius, Vec4 baseColor )
|
||||
{
|
||||
DrawSphereEx( transform, radius, baseColor, DEFAULT_METALLIC, DEFAULT_ROUGHNESS, TRANSPARENT_SHADOW_FULL );
|
||||
}
|
||||
|
||||
void DrawCapsuleEx( b3Transform transform, float halfLength, float radius, Vec4 baseColor, float metallic, float roughness,
|
||||
TransparentShadowCast shadowCast )
|
||||
{
|
||||
AppendCapsule( transform, halfLength, radius, baseColor, metallic, roughness, shadowCast );
|
||||
}
|
||||
|
||||
void DrawCapsule( b3Transform transform, float halfLength, float radius, Vec4 baseColor )
|
||||
{
|
||||
DrawCapsuleEx( transform, halfLength, radius, baseColor, DEFAULT_METALLIC, DEFAULT_ROUGHNESS, TRANSPARENT_SHADOW_FULL );
|
||||
}
|
||||
|
||||
void DrawSolidSphere( b3Transform transform, b3Sphere sphere, Vec4 color )
|
||||
{
|
||||
b3Transform world = { b3TransformPoint( transform, sphere.center ), transform.q };
|
||||
DrawSphere( world, sphere.radius, color );
|
||||
}
|
||||
|
||||
void DrawSolidCapsule( b3Transform transform, b3Capsule capsule, Vec4 color )
|
||||
{
|
||||
b3Vec3 c1 = b3TransformPoint( transform, capsule.center1 );
|
||||
b3Vec3 c2 = b3TransformPoint( transform, capsule.center2 );
|
||||
b3Vec3 axis = b3Sub( c2, c1 );
|
||||
float length = b3Length( axis );
|
||||
|
||||
// Impostor cylinder runs along local +X, so align +X with the capsule axis.
|
||||
b3Quat q = transform.q;
|
||||
if ( length > 1e-6f )
|
||||
{
|
||||
q = b3ComputeQuatBetweenUnitVectors( b3Vec3_axisX, b3MulSV( 1.0f / length, axis ) );
|
||||
}
|
||||
|
||||
b3Transform world = { b3MulSV( 0.5f, b3Add( c1, c2 ) ), q };
|
||||
DrawCapsule( world, 0.5f * length, capsule.radius, color );
|
||||
}
|
||||
|
||||
void DrawHull( b3Transform transform, const b3Hull* hull, Vec4 color )
|
||||
{
|
||||
const b3Vec3* points = b3GetHullPoints( hull );
|
||||
const b3HullHalfEdge* edges = b3GetHullEdges( hull );
|
||||
|
||||
// Half-edges come in twin pairs, so draw each undirected edge once.
|
||||
for ( int i = 0; i < hull->edgeCount; ++i )
|
||||
{
|
||||
if ( i >= edges[i].twin )
|
||||
{
|
||||
continue;
|
||||
}
|
||||
b3Vec3 p1 = b3TransformPoint( transform, points[edges[i].origin] );
|
||||
b3Vec3 p2 = b3TransformPoint( transform, points[edges[edges[i].twin].origin] );
|
||||
DrawLine( p1, p2, color );
|
||||
}
|
||||
}
|
||||
|
||||
void DrawPlane( b3Vec3 normal, b3Vec3 point, Vec4 color )
|
||||
{
|
||||
b3Vec3 perp1 = b3Perp( normal );
|
||||
b3Vec3 perp2 = b3Cross( perp1, normal );
|
||||
b3Vec3 p1 = b3Add( point, b3Add( perp1, perp2 ) );
|
||||
b3Vec3 p2 = b3Add( point, b3Sub( perp2, perp1 ) );
|
||||
b3Vec3 p3 = b3Sub( point, b3Add( perp1, perp2 ) );
|
||||
b3Vec3 p4 = b3Add( point, b3Sub( perp1, perp2 ) );
|
||||
DrawLine( p1, p2, color );
|
||||
DrawLine( p2, p3, color );
|
||||
DrawLine( p3, p4, color );
|
||||
DrawLine( p4, p1, color );
|
||||
DrawLine( point, b3Add( point, b3MulSV( 0.5f, normal ) ), color );
|
||||
DrawPoint( point, 10.0f, color );
|
||||
}
|
||||
|
||||
void DrawLineEx( b3Vec3 a, b3Vec3 b, Vec4 color, float thickness, OverlayThicknessUnit thicknessUnit,
|
||||
OverlayOcclusionMode occlusionMode )
|
||||
{
|
||||
OverlayAppendLine( a, b, color, thickness, thicknessUnit, occlusionMode );
|
||||
}
|
||||
|
||||
void DrawLine( b3Vec3 a, b3Vec3 b, Vec4 color )
|
||||
{
|
||||
DrawLineEx( a, b, color, DEFAULT_LINE_THICKNESS_PX, OVERLAY_THICKNESS_PIXELS, OVERLAY_OCCLUSION_HIDE );
|
||||
}
|
||||
|
||||
void DrawPointEx( b3Vec3 p, Vec4 color, float size, OverlayThicknessUnit sizeUnit, OverlayOcclusionMode occlusionMode )
|
||||
{
|
||||
OverlayAppendPoint( p, color, size, sizeUnit, occlusionMode );
|
||||
}
|
||||
|
||||
void DrawPoint( b3Vec3 p, float size, Vec4 color )
|
||||
{
|
||||
DrawPointEx( p, color, size, OVERLAY_THICKNESS_PIXELS, OVERLAY_OCCLUSION_DIM );
|
||||
}
|
||||
|
||||
void DrawArrowEx( b3Vec3 a, b3Vec3 b, Vec4 color, float thickness, OverlayThicknessUnit thicknessUnit,
|
||||
OverlayOcclusionMode occlusionMode, float headLengthFrac )
|
||||
{
|
||||
DrawLineEx( a, b, color, thickness, thicknessUnit, occlusionMode );
|
||||
|
||||
b3Vec3 shaft = b3Sub( b, a );
|
||||
float shaftLen = b3Length( shaft );
|
||||
if ( shaftLen < 1e-6f )
|
||||
{
|
||||
return;
|
||||
}
|
||||
b3Vec3 dir = { shaft.x / shaftLen, shaft.y / shaftLen, shaft.z / shaftLen };
|
||||
b3Vec3 perp = b3Perp( dir );
|
||||
float headLen = shaftLen * headLengthFrac;
|
||||
|
||||
b3Vec3 backFromTip = b3MulSV( -headLen, dir );
|
||||
b3Vec3 sideStep = b3MulSV( headLen * 0.5f, perp );
|
||||
b3Vec3 tip1 = b3Add( b, b3Add( backFromTip, sideStep ) );
|
||||
b3Vec3 tip2 = b3Add( b, b3Sub( backFromTip, sideStep ) );
|
||||
DrawLineEx( b, tip1, color, thickness, thicknessUnit, occlusionMode );
|
||||
DrawLineEx( b, tip2, color, thickness, thicknessUnit, occlusionMode );
|
||||
}
|
||||
|
||||
void DrawArrow( b3Vec3 a, b3Vec3 b, Vec4 color )
|
||||
{
|
||||
DrawArrowEx( a, b, color, DEFAULT_LINE_THICKNESS_PX, OVERLAY_THICKNESS_PIXELS, OVERLAY_OCCLUSION_HIDE,
|
||||
DEFAULT_ARROW_HEAD_FRAC );
|
||||
}
|
||||
|
||||
void DrawCrossEx( b3Vec3 center, float size, Vec4 color, float thickness, OverlayThicknessUnit thicknessUnit,
|
||||
OverlayOcclusionMode occlusionMode )
|
||||
{
|
||||
float h = size * 0.5f;
|
||||
DrawLineEx( (b3Vec3){ center.x - h, center.y, center.z }, (b3Vec3){ center.x + h, center.y, center.z }, color, thickness,
|
||||
thicknessUnit, occlusionMode );
|
||||
DrawLineEx( (b3Vec3){ center.x, center.y - h, center.z }, (b3Vec3){ center.x, center.y + h, center.z }, color, thickness,
|
||||
thicknessUnit, occlusionMode );
|
||||
DrawLineEx( (b3Vec3){ center.x, center.y, center.z - h }, (b3Vec3){ center.x, center.y, center.z + h }, color, thickness,
|
||||
thicknessUnit, occlusionMode );
|
||||
}
|
||||
|
||||
void DrawCross( b3Vec3 center, float size, Vec4 color )
|
||||
{
|
||||
DrawCrossEx( center, size, color, DEFAULT_LINE_THICKNESS_PX, OVERLAY_THICKNESS_PIXELS, OVERLAY_OCCLUSION_HIDE );
|
||||
}
|
||||
|
||||
void DrawAabbEx( b3Vec3 mn, b3Vec3 mx, Vec4 color, float thickness, OverlayThicknessUnit thicknessUnit,
|
||||
OverlayOcclusionMode occlusionMode )
|
||||
{
|
||||
// 8 corners of the box.
|
||||
b3Vec3 c000 = { mn.x, mn.y, mn.z };
|
||||
b3Vec3 c100 = { mx.x, mn.y, mn.z };
|
||||
b3Vec3 c010 = { mn.x, mx.y, mn.z };
|
||||
b3Vec3 c110 = { mx.x, mx.y, mn.z };
|
||||
b3Vec3 c001 = { mn.x, mn.y, mx.z };
|
||||
b3Vec3 c101 = { mx.x, mn.y, mx.z };
|
||||
b3Vec3 c011 = { mn.x, mx.y, mx.z };
|
||||
b3Vec3 c111 = { mx.x, mx.y, mx.z };
|
||||
|
||||
// 4 bottom edges (y = mn.y).
|
||||
DrawLineEx( c000, c100, color, thickness, thicknessUnit, occlusionMode );
|
||||
DrawLineEx( c100, c101, color, thickness, thicknessUnit, occlusionMode );
|
||||
DrawLineEx( c101, c001, color, thickness, thicknessUnit, occlusionMode );
|
||||
DrawLineEx( c001, c000, color, thickness, thicknessUnit, occlusionMode );
|
||||
// 4 top edges (y = mx.y).
|
||||
DrawLineEx( c010, c110, color, thickness, thicknessUnit, occlusionMode );
|
||||
DrawLineEx( c110, c111, color, thickness, thicknessUnit, occlusionMode );
|
||||
DrawLineEx( c111, c011, color, thickness, thicknessUnit, occlusionMode );
|
||||
DrawLineEx( c011, c010, color, thickness, thicknessUnit, occlusionMode );
|
||||
// 4 vertical edges.
|
||||
DrawLineEx( c000, c010, color, thickness, thicknessUnit, occlusionMode );
|
||||
DrawLineEx( c100, c110, color, thickness, thicknessUnit, occlusionMode );
|
||||
DrawLineEx( c101, c111, color, thickness, thicknessUnit, occlusionMode );
|
||||
DrawLineEx( c001, c011, color, thickness, thicknessUnit, occlusionMode );
|
||||
}
|
||||
|
||||
void DrawAabb( b3Vec3 mn, b3Vec3 mx, Vec4 color )
|
||||
{
|
||||
DrawAabbEx( mn, mx, color, DEFAULT_LINE_THICKNESS_PX, OVERLAY_THICKNESS_PIXELS, OVERLAY_OCCLUSION_HIDE );
|
||||
}
|
||||
|
||||
void DrawBounds( b3AABB bounds, float extension, Vec4 color )
|
||||
{
|
||||
b3Vec3 e = { extension, extension, extension };
|
||||
DrawAabb( b3Sub( bounds.lowerBound, e ), b3Add( bounds.upperBound, e ), color );
|
||||
}
|
||||
|
||||
void DrawAxesEx( b3Transform transform, float size, float thickness, OverlayThicknessUnit thicknessUnit,
|
||||
OverlayOcclusionMode occlusionMode )
|
||||
{
|
||||
b3Vec3 origin = transform.p;
|
||||
b3Matrix3 basis = b3MakeMatrixFromQuat( transform.q );
|
||||
DrawLineEx( origin, b3MulAdd( origin, size, basis.cx ), MakeVec4( 1.0f, 0.0f, 0.0f, 1.0f ), thickness, thicknessUnit,
|
||||
occlusionMode );
|
||||
DrawLineEx( origin, b3MulAdd( origin, size, basis.cy ), MakeVec4( 0.0f, 1.0f, 0.0f, 1.0f ), thickness, thicknessUnit,
|
||||
occlusionMode );
|
||||
DrawLineEx( origin, b3MulAdd( origin, size, basis.cz ), MakeVec4( 0.0f, 0.0f, 1.0f, 1.0f ), thickness, thicknessUnit,
|
||||
occlusionMode );
|
||||
}
|
||||
|
||||
void DrawAxes( b3Transform transform, float size )
|
||||
{
|
||||
DrawAxesEx( transform, size, DEFAULT_LINE_THICKNESS_PX, OVERLAY_THICKNESS_PIXELS, OVERLAY_OCCLUSION_HIDE );
|
||||
}
|
||||
|
||||
void DrawGrid( b3Vec3 center, b3Vec3 normal, float halfExtent, int divisions, Vec4 color )
|
||||
{
|
||||
if ( divisions < 1 || halfExtent <= 0.0f )
|
||||
{
|
||||
return;
|
||||
}
|
||||
// Orthonormal in-plane axes from the normal.
|
||||
b3Vec3 n = b3Normalize( normal );
|
||||
b3Vec3 u = b3Normalize( b3Perp( n ) );
|
||||
b3Vec3 v = b3Cross( n, u );
|
||||
|
||||
const float step = ( 2.0f * halfExtent ) / (float)divisions;
|
||||
for ( int i = 0; i <= divisions; ++i )
|
||||
{
|
||||
const float o = -halfExtent + (float)i * step;
|
||||
// Line spanning u at this offset along v.
|
||||
b3Vec3 ua = b3Add( center, b3Add( b3MulSV( -halfExtent, u ), b3MulSV( o, v ) ) );
|
||||
b3Vec3 ub = b3Add( center, b3Add( b3MulSV( halfExtent, u ), b3MulSV( o, v ) ) );
|
||||
DrawLineEx( ua, ub, color, DEFAULT_LINE_THICKNESS_PX, OVERLAY_THICKNESS_PIXELS, OVERLAY_OCCLUSION_HIDE );
|
||||
// Line spanning v at this offset along u.
|
||||
b3Vec3 va = b3Add( center, b3Add( b3MulSV( o, u ), b3MulSV( -halfExtent, v ) ) );
|
||||
b3Vec3 vb = b3Add( center, b3Add( b3MulSV( o, u ), b3MulSV( halfExtent, v ) ) );
|
||||
DrawLineEx( va, vb, color, DEFAULT_LINE_THICKNESS_PX, OVERLAY_THICKNESS_PIXELS, OVERLAY_OCCLUSION_HIDE );
|
||||
}
|
||||
}
|
||||
|
||||
void DrawGroundGrid( int size )
|
||||
{
|
||||
Vec4 color = MakeVec4( 0.3f, 0.3f, 0.3f, 1.0f );
|
||||
DrawGrid( b3Vec3_zero, b3Vec3_axisY, (float)size, size, color );
|
||||
}
|
||||
|
||||
void DrawTriangle( b3Vec3 a, b3Vec3 b, b3Vec3 c, Vec4 color )
|
||||
{
|
||||
DrawLineEx( a, b, color, DEFAULT_LINE_THICKNESS_PX, OVERLAY_THICKNESS_PIXELS, OVERLAY_OCCLUSION_HIDE );
|
||||
DrawLineEx( b, c, color, DEFAULT_LINE_THICKNESS_PX, OVERLAY_THICKNESS_PIXELS, OVERLAY_OCCLUSION_HIDE );
|
||||
DrawLineEx( c, a, color, DEFAULT_LINE_THICKNESS_PX, OVERLAY_THICKNESS_PIXELS, OVERLAY_OCCLUSION_HIDE );
|
||||
}
|
||||
|
||||
static void DrawDisc( b3Vec3 center, b3Vec3 normal, float radius, int segments, Vec4 color )
|
||||
{
|
||||
b3Vec3 tangent1 = b3Perp( normal );
|
||||
b3Vec3 tangent2 = b3Cross( normal, tangent1 );
|
||||
|
||||
float delta = 2.0f * B3_PI / segments;
|
||||
float cosine = cosf( delta );
|
||||
float sine = sinf( delta );
|
||||
|
||||
float x1 = radius, y1 = 0.0f;
|
||||
b3Vec3 vertex1 = b3Add( center, b3Blend2( x1, tangent1, y1, tangent2 ) );
|
||||
|
||||
for ( int i = 0; i < segments; ++i )
|
||||
{
|
||||
float x2 = cosine * x1 - sine * y1;
|
||||
float y2 = sine * x1 + cosine * y1;
|
||||
b3Vec3 vertex2 = b3Add( center, b3Blend2( x2, tangent1, y2, tangent2 ) );
|
||||
|
||||
DrawLineEx( vertex1, vertex2, color, 2.0f, OVERLAY_THICKNESS_PIXELS, OVERLAY_OCCLUSION_DIM );
|
||||
|
||||
x1 = x2;
|
||||
y1 = y2;
|
||||
vertex1 = vertex2;
|
||||
}
|
||||
}
|
||||
|
||||
static void DrawArc( b3Vec3 center, b3Vec3 normal, float radius, b3Vec3 start, float maxDegrees, int segments, Vec4 color )
|
||||
{
|
||||
b3Vec3 tangent1 = b3Normalize( start );
|
||||
b3Vec3 tangent2 = b3Cross( normal, tangent1 );
|
||||
|
||||
float deltaDegrees = maxDegrees / segments;
|
||||
b3CosSin cs = b3ComputeCosSin( B3_DEG_TO_RAD * deltaDegrees );
|
||||
float x1 = radius, y1 = 0.0f;
|
||||
|
||||
b3Vec3 vertex1 = b3Add( center, b3Blend2( x1, tangent1, y1, tangent2 ) );
|
||||
|
||||
for ( float angle = 0.0f; angle < maxDegrees - 0.001f; angle += deltaDegrees )
|
||||
{
|
||||
float x2 = cs.cosine * x1 - cs.sine * y1;
|
||||
float y2 = cs.sine * x1 + cs.cosine * y1;
|
||||
b3Vec3 vertex2 = b3Add( center, b3Blend2( x2, tangent1, y2, tangent2 ) );
|
||||
|
||||
DrawLineEx( vertex1, vertex2, color, 2.0f, OVERLAY_THICKNESS_PIXELS, OVERLAY_OCCLUSION_DASHED );
|
||||
|
||||
x1 = x2;
|
||||
y1 = y2;
|
||||
vertex1 = vertex2;
|
||||
}
|
||||
}
|
||||
|
||||
void DrawWireSphere( b3Transform transform, const b3Sphere* sphere, int segments, Vec4 color )
|
||||
{
|
||||
b3Vec3 center = b3TransformPoint( transform, sphere->center );
|
||||
float radius = sphere->radius;
|
||||
|
||||
b3Vec3 axisX = b3RotateVector( transform.q, (b3Vec3){ 1.0f, 0.0f, 0.0f } );
|
||||
b3Vec3 axisY = b3RotateVector( transform.q, (b3Vec3){ 0.0f, 1.0f, 0.0f } );
|
||||
b3Vec3 axisZ = b3RotateVector( transform.q, (b3Vec3){ 0.0f, 0.0f, 1.0f } );
|
||||
|
||||
DrawDisc( center, axisX, radius, segments, color );
|
||||
DrawDisc( center, axisY, radius, segments, color );
|
||||
DrawDisc( center, axisZ, radius, segments, color );
|
||||
}
|
||||
|
||||
void DrawWireCapsule( b3Transform transform, const b3Capsule* capsule, int segments, Vec4 color )
|
||||
{
|
||||
b3Vec3 center1 = b3TransformPoint( transform, capsule->center1 );
|
||||
b3Vec3 center2 = b3TransformPoint( transform, capsule->center2 );
|
||||
float radius = capsule->radius;
|
||||
|
||||
b3Vec3 normal = b3Normalize( b3Sub( center2, center1 ) );
|
||||
b3Vec3 tangent1 = b3Perp( normal );
|
||||
b3Vec3 tangent2 = b3Cross( normal, tangent1 );
|
||||
|
||||
DrawLineEx( b3MulAdd( center1, radius, tangent1 ), b3MulAdd( center2, radius, tangent1 ), color, 2.0f,
|
||||
OVERLAY_THICKNESS_PIXELS, OVERLAY_OCCLUSION_DASHED );
|
||||
DrawLineEx( b3MulAdd( center1, radius, tangent2 ), b3MulAdd( center2, radius, tangent2 ), color, 2.0f,
|
||||
OVERLAY_THICKNESS_PIXELS, OVERLAY_OCCLUSION_DASHED );
|
||||
DrawLineEx( b3MulSub( center1, radius, tangent1 ), b3MulSub( center2, radius, tangent1 ), color, 2.0f,
|
||||
OVERLAY_THICKNESS_PIXELS, OVERLAY_OCCLUSION_DASHED );
|
||||
DrawLineEx( b3MulSub( center1, radius, tangent2 ), b3MulSub( center2, radius, tangent2 ), color, 2.0f,
|
||||
OVERLAY_THICKNESS_PIXELS, OVERLAY_OCCLUSION_DASHED );
|
||||
|
||||
DrawArc( center1, b3Neg( tangent1 ), radius, tangent2, 180.0f, segments / 2, color );
|
||||
DrawArc( center1, tangent2, radius, tangent1, 180.0f, segments / 2, color );
|
||||
DrawArc( center2, tangent1, radius, tangent2, 180.0f, segments / 2, color );
|
||||
DrawArc( center2, b3Neg( tangent2 ), radius, tangent1, 180.0f, segments / 2, color );
|
||||
|
||||
DrawDisc( center1, normal, radius, segments, color );
|
||||
DrawDisc( center2, normal, radius, segments, color );
|
||||
}
|
||||
|
||||
void DrawWorldString( b3Vec3 point, Vec4 color, const char* format, ... )
|
||||
{
|
||||
va_list args;
|
||||
va_start( args, format );
|
||||
char buffer[256];
|
||||
vsnprintf( buffer, sizeof( buffer ), format, args );
|
||||
va_end( args );
|
||||
DrawString( point, color, buffer );
|
||||
}
|
||||
117
samples/gfx/draw.h
Normal file
117
samples/gfx/draw.h
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "gfx/draw_overlay.h"
|
||||
#include "gfx/utility.h"
|
||||
|
||||
#include "box3d/collision.h"
|
||||
|
||||
// Neutral-dielectric material defaults for the short-form shape calls.
|
||||
#define DEFAULT_METALLIC 0.0f
|
||||
#define DEFAULT_ROUGHNESS 0.5f
|
||||
|
||||
// Thickness/size defaults for the short-form overlay calls
|
||||
#define DEFAULT_LINE_THICKNESS_PX 1.5f
|
||||
#define DEFAULT_POINT_SIZE_PX 4.0f
|
||||
|
||||
// Arrow head length as a fraction of the shaft length
|
||||
#define DEFAULT_ARROW_HEAD_FRAC 0.15f
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"
|
||||
{
|
||||
#endif
|
||||
|
||||
// Cube. transform places and orients the cube. scale is the cube's full side
|
||||
// lengths (it multiplies the unit cube proxy, which spans [-0.5, 0.5]).
|
||||
void DrawCube( b3Transform transform, b3Vec3 scale, Vec4 baseColor );
|
||||
void DrawCubeEx( b3Transform transform, b3Vec3 scale, Vec4 baseColor, float metallic, float roughness,
|
||||
TransparentShadowCast shadowCast );
|
||||
|
||||
// Sphere impostor. transform supplies the orientation (rotation drives the
|
||||
// surface pattern so spin is visible) and the center (translation).
|
||||
void DrawSphere( b3Transform transform, float radius, Vec4 baseColor );
|
||||
void DrawSphereEx( b3Transform transform, float radius, Vec4 baseColor, float metallic, float roughness,
|
||||
TransparentShadowCast shadowCast );
|
||||
|
||||
// Capsule impostor. transform supplies the orientation (the capsule's local +X
|
||||
// axis becomes the world long axis, rotation about local +X drives the
|
||||
// cylinder/cap surface pattern so roll is visible) and the center
|
||||
// (translation). halfLength is the distance from center to either cap
|
||||
// center along local +X. radius is the cap radius.
|
||||
void DrawCapsule( b3Transform transform, float halfLength, float radius, Vec4 baseColor );
|
||||
void DrawCapsuleEx( b3Transform transform, float halfLength, float radius, Vec4 baseColor, float metallic, float roughness,
|
||||
TransparentShadowCast shadowCast );
|
||||
|
||||
// Solid shape wrappers over the impostor primitives. They take Box3D shape
|
||||
// types and fold the shape-local frame into the transform, so samples draw
|
||||
// straight from collision data.
|
||||
void DrawSolidSphere( b3Transform transform, b3Sphere sphere, Vec4 color );
|
||||
void DrawSolidCapsule( b3Transform transform, b3Capsule capsule, Vec4 color );
|
||||
|
||||
// Convex hull wireframe. Each undirected edge once, in world space.
|
||||
void DrawHull( b3Transform transform, const b3Hull* hull, Vec4 color );
|
||||
|
||||
// Plane as a unit wireframe quad through the point, plus a short normal and a dot.
|
||||
void DrawPlane( b3Vec3 normal, b3Vec3 point, Vec4 color );
|
||||
|
||||
// All overlay submissions land in the renderer's per-frame overlay arenas
|
||||
// and are drawn into the MSAA HDR scene target after opaque + sky, before
|
||||
// the AgX tone map pass. Colors are straight (non-premultiplied) linear RGBA.
|
||||
|
||||
void DrawLine( b3Vec3 a, b3Vec3 b, Vec4 color );
|
||||
void DrawLineEx( b3Vec3 a, b3Vec3 b, Vec4 color, float thickness, OverlayThicknessUnit thicknessUnit,
|
||||
OverlayOcclusionMode occlusionMode );
|
||||
|
||||
// Debug point, size in pixels. Dimmed rather than hidden when occluded so
|
||||
// contact and witness points stay visible through geometry.
|
||||
void DrawPoint( b3Vec3 p, float size, Vec4 color );
|
||||
void DrawPointEx( b3Vec3 p, Vec4 color, float size, OverlayThicknessUnit sizeUnit, OverlayOcclusionMode occlusionMode );
|
||||
|
||||
// Single-arrow shaft from a to b with two short angled head segments at b.
|
||||
// headLengthFrac is the head length as a fraction of the shaft length
|
||||
void DrawArrow( b3Vec3 a, b3Vec3 b, Vec4 color );
|
||||
void DrawArrowEx( b3Vec3 a, b3Vec3 b, Vec4 color, float thickness, OverlayThicknessUnit thicknessUnit,
|
||||
OverlayOcclusionMode occlusionMode, float headLengthFrac );
|
||||
|
||||
// Three orthogonal lines through center, total length size per axis, uniform color.
|
||||
void DrawCross( b3Vec3 center, float size, Vec4 color );
|
||||
void DrawCrossEx( b3Vec3 center, float size, Vec4 color, float thickness, OverlayThicknessUnit thicknessUnit,
|
||||
OverlayOcclusionMode occlusionMode );
|
||||
|
||||
// Wireframe AABB (12 edges) between world-space min and max corners.
|
||||
void DrawAabb( b3Vec3 min, b3Vec3 max, Vec4 color );
|
||||
void DrawAabbEx( b3Vec3 min, b3Vec3 max, Vec4 color, float thickness, OverlayThicknessUnit thicknessUnit,
|
||||
OverlayOcclusionMode occlusionMode );
|
||||
|
||||
// AABB wireframe expanded outward by `extension` on every side.
|
||||
void DrawBounds( b3AABB bounds, float extension, Vec4 color );
|
||||
|
||||
// Draw RGB axes
|
||||
void DrawAxes( b3Transform transform, float size );
|
||||
void DrawAxesEx( b3Transform transform, float size, float thickness, OverlayThicknessUnit thicknessUnit,
|
||||
OverlayOcclusionMode occlusionMode );
|
||||
|
||||
// Planar overlay grid centered at `center`, lying in the plane defined by
|
||||
// `normal`. `halfExtent` is the half-width per in-plane axis, `divisions` the
|
||||
// cell count per axis. Emits 2 * (divisions + 1) lines along an orthonormal
|
||||
// basis derived from the normal, so it is not pinned to a Y-up ground plane.
|
||||
void DrawGrid( b3Vec3 center, b3Vec3 normal, float halfExtent, int divisions, Vec4 color );
|
||||
|
||||
// Gray ground grid in the XZ plane, `size` meters half-extent with 1 m cells.
|
||||
void DrawGroundGrid( int size );
|
||||
|
||||
// Wireframe triangle: three overlay lines a -> b -> c -> a.
|
||||
void DrawTriangle( b3Vec3 a, b3Vec3 b, b3Vec3 c, Vec4 color );
|
||||
|
||||
void DrawWireSphere( b3Transform transform, const b3Sphere* sphere, int segments, Vec4 color );
|
||||
void DrawWireCapsule( b3Transform transform, const b3Capsule* capsule, int segments, Vec4 color );
|
||||
|
||||
// printf-style world-space text label. The renderer projects with its latched camera.
|
||||
void DrawWorldString( b3Vec3 point, Vec4 color, const char* format, ... );
|
||||
|
||||
#ifdef __cplusplus
|
||||
} // extern "C"
|
||||
#endif
|
||||
37
samples/gfx/draw_overlay.h
Normal file
37
samples/gfx/draw_overlay.h
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#pragma once
|
||||
|
||||
// How a line or point reacts when scene geometry sits in front of it.
|
||||
typedef enum OverlayOcclusionMode
|
||||
{
|
||||
// depth tested
|
||||
OVERLAY_OCCLUSION_HIDE = 0,
|
||||
|
||||
// reduced alpha
|
||||
OVERLAY_OCCLUSION_DIM = 1,
|
||||
|
||||
// screen-space dash pattern
|
||||
OVERLAY_OCCLUSION_DASHED = 2,
|
||||
} OverlayOcclusionMode;
|
||||
|
||||
// How to interpret the `thickness` (lines) or `size` (points) argument
|
||||
typedef enum OverlayThicknessUnit
|
||||
{
|
||||
// screen-space pixels
|
||||
OVERLAY_THICKNESS_PIXELS = 0,
|
||||
|
||||
// world-space meters
|
||||
OVERLAY_THICKNESS_WORLD = 1,
|
||||
} OverlayThicknessUnit;
|
||||
|
||||
// Whether a shape draw call participates in the shadow caster pass.
|
||||
typedef enum TransparentShadowCast
|
||||
{
|
||||
// regular shadow
|
||||
TRANSPARENT_SHADOW_FULL = 0,
|
||||
|
||||
// disable shadow
|
||||
TRANSPARENT_SHADOW_NONE = 1,
|
||||
} TransparentShadowCast;
|
||||
349
samples/gfx/edges.c
Normal file
349
samples/gfx/edges.c
Normal file
|
|
@ -0,0 +1,349 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "gfx/edges.h"
|
||||
|
||||
#include "edge.glsl.h"
|
||||
#include "box3d/types.h"
|
||||
#include "gfx/geometry_registry.h"
|
||||
#include "gfx/scene_target.h"
|
||||
|
||||
// Two pipelines off the same shader:
|
||||
|
||||
// pipelineMsaa: sample_count=SCENE_SAMPLE_COUNT, scene_target color+depth,
|
||||
// for the opaque path (drawn inside the open MSAA scene pass).
|
||||
|
||||
// pipelineTransparent: sample_count=1, RGBA16F + SG_PIXELFORMAT_DEPTH, for
|
||||
// the transparent path (own pass against resolve + GTAO prepass depth).
|
||||
// Note: the edges are not transparent, they are being drawn after transparent
|
||||
// shapes, which looks good on transparent hulls.
|
||||
|
||||
// Both share blend (premultiplied alpha) and depth state (GREATER_EQUAL,
|
||||
// no write, reverse-Z, the VS adds zBias toward camera).
|
||||
static struct
|
||||
{
|
||||
sg_shader shader;
|
||||
sg_pipeline pipelineMsaa;
|
||||
sg_pipeline pipelineTransparent;
|
||||
bool ready;
|
||||
} s_edges;
|
||||
|
||||
EdgeOverlayParams GetDefaultEdgeParams( void )
|
||||
{
|
||||
EdgeOverlayParams p;
|
||||
p.enabled = true;
|
||||
p.showHulls = true;
|
||||
p.showMeshes = true;
|
||||
p.showHeightfields = true;
|
||||
p.showEdgeConvexity = false;
|
||||
p.thicknessPx = 1.5f;
|
||||
p.zBias = 1.0e-6f;
|
||||
p.convexColor = MakeVec4( 0.1f, 0.8f, 0.1f, 0.75f );
|
||||
p.concaveColor = MakeVec4( 0.8f, 0.10f, 0.10f, 0.75f );
|
||||
p.flatColor = MakeVec4( 0.6f, 0.6f, 0.6f, 0.5f );
|
||||
return p;
|
||||
}
|
||||
|
||||
static void ApplyCommonPipelineState( sg_pipeline_desc* p )
|
||||
{
|
||||
p->shader = s_edges.shader;
|
||||
p->index_type = SG_INDEXTYPE_NONE;
|
||||
p->cull_mode = SG_CULLMODE_NONE;
|
||||
p->colors[0].pixel_format = SG_PIXELFORMAT_RGBA16F;
|
||||
p->color_count = 1;
|
||||
p->colors[0].blend.enabled = true;
|
||||
p->colors[0].blend.src_factor_rgb = SG_BLENDFACTOR_ONE;
|
||||
p->colors[0].blend.dst_factor_rgb = SG_BLENDFACTOR_ONE_MINUS_SRC_ALPHA;
|
||||
p->colors[0].blend.op_rgb = SG_BLENDOP_ADD;
|
||||
p->colors[0].blend.src_factor_alpha = SG_BLENDFACTOR_ONE;
|
||||
p->colors[0].blend.dst_factor_alpha = SG_BLENDFACTOR_ONE_MINUS_SRC_ALPHA;
|
||||
p->colors[0].blend.op_alpha = SG_BLENDOP_ADD;
|
||||
p->depth.compare = SG_COMPAREFUNC_GREATER_EQUAL;
|
||||
p->depth.write_enabled = false;
|
||||
}
|
||||
|
||||
void InitEdges( void )
|
||||
{
|
||||
if ( s_edges.ready )
|
||||
{
|
||||
return;
|
||||
}
|
||||
s_edges.shader = sg_make_shader( edge_edge_overlay_shader_desc( sg_query_backend() ) );
|
||||
|
||||
// MSAA pipeline, depth format mirrors the scene target's MSAA depth
|
||||
// attachment (env.defaults.depth_format).
|
||||
sg_pipeline_desc msaaPdesc = { 0 };
|
||||
ApplyCommonPipelineState( &msaaPdesc );
|
||||
msaaPdesc.depth.pixel_format = GetSceneTargetDepthFormat();
|
||||
msaaPdesc.sample_count = SCENE_SAMPLE_COUNT;
|
||||
msaaPdesc.label = "edge_overlay_pipeline_msaa";
|
||||
s_edges.pipelineMsaa = sg_make_pipeline( &msaaPdesc );
|
||||
|
||||
// Transparent pipeline, single-sample, depth matches the GTAO prepass attachment
|
||||
// (SG_PIXELFORMAT_DEPTH) that the post-resolve pass binds.
|
||||
sg_pipeline_desc xpPdesc = { 0 };
|
||||
ApplyCommonPipelineState( &xpPdesc );
|
||||
xpPdesc.depth.pixel_format = SG_PIXELFORMAT_DEPTH;
|
||||
xpPdesc.sample_count = 1;
|
||||
xpPdesc.label = "edge_overlay_pipeline_transparent";
|
||||
s_edges.pipelineTransparent = sg_make_pipeline( &xpPdesc );
|
||||
|
||||
s_edges.ready = true;
|
||||
}
|
||||
|
||||
void ShutdownEdges( void )
|
||||
{
|
||||
if ( !s_edges.ready )
|
||||
{
|
||||
return;
|
||||
}
|
||||
sg_destroy_pipeline( s_edges.pipelineTransparent );
|
||||
s_edges.pipelineTransparent.id = 0;
|
||||
sg_destroy_pipeline( s_edges.pipelineMsaa );
|
||||
s_edges.pipelineMsaa.id = 0;
|
||||
sg_destroy_shader( s_edges.shader );
|
||||
s_edges.shader.id = 0;
|
||||
s_edges.ready = false;
|
||||
}
|
||||
|
||||
static inline Vec4 Premultiply( Vec4 c )
|
||||
{
|
||||
return MakeVec4( c.x * c.w, c.y * c.w, c.z * c.w, c.w );
|
||||
}
|
||||
|
||||
// Per-batch policy: does the toggle want this batch drawn at all?
|
||||
static bool IsBatchEnabled( const MeshEdgeBatch* b, const EdgeOverlayParams* p )
|
||||
{
|
||||
switch ( b->kind )
|
||||
{
|
||||
case MESH_KIND_HULL:
|
||||
// Hull edges on every hull, opaque and transparent. Opaque hulls
|
||||
// pick up MSAA in the scene pass, transparent ones draw post-resolve.
|
||||
return p->showHulls;
|
||||
case MESH_KIND_MESH:
|
||||
return p->showMeshes;
|
||||
case MESH_KIND_HEIGHTFIELD:
|
||||
return p->showHeightfields;
|
||||
case MESH_KIND_UNKNOWN:
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Pack ub_frame + ub_pass + select pipeline + iterate batches. When
|
||||
// `ArenaFilter` is ARENA_FILTER_BOTH, iterates every surviving batch
|
||||
// and picks the matching instance view per batch (used by the MSAA path
|
||||
// during the "transparent edges in MSAA pass" experiment). Otherwise restricts to
|
||||
// the matching arena.
|
||||
typedef enum ArenaFilter
|
||||
{
|
||||
ARENA_FILTER_OPAQUE_ONLY = 0,
|
||||
ARENA_FILTER_TRANSPARENT_ONLY,
|
||||
ARENA_FILTER_BOTH,
|
||||
} ArenaFilter;
|
||||
|
||||
static void SubmitBatches( int width, int height, const Mat4* view, const Mat4* proj, sg_pipeline pip, sg_view opaqueInstanceView,
|
||||
sg_view transparentInstanceView, ArenaFilter arenaFilter, const EdgeOverlayParams* params )
|
||||
{
|
||||
sg_apply_pipeline( pip );
|
||||
|
||||
edge_ub_frame_t uf = { 0 };
|
||||
uf.view_proj = MulMM4( *proj, *view );
|
||||
uf.viewport =
|
||||
MakeVec4( (float)width, (float)height, width > 0 ? 1.0f / (float)width : 0.0f, height > 0 ? 1.0f / (float)height : 0.0f );
|
||||
sg_apply_uniforms( UB_edge_ub_frame, &SG_RANGE( uf ) );
|
||||
|
||||
// Mesh and heightfield edges color by convexity (or collapse to flat when
|
||||
// convexity coloring is off). Hull edges ignore convexity and always draw
|
||||
// in the hard-coded hull color, so every class maps to it. Pass colors are
|
||||
// shared across a draw, so select per batch kind inside the loop.
|
||||
edge_ub_pass_t passMesh = { 0 };
|
||||
if ( params->showEdgeConvexity )
|
||||
{
|
||||
passMesh.convex_color = Premultiply( params->convexColor );
|
||||
passMesh.concave_color = Premultiply( params->concaveColor );
|
||||
passMesh.flat_color = Premultiply( params->flatColor );
|
||||
}
|
||||
else
|
||||
{
|
||||
Vec4 flat = Premultiply( params->flatColor );
|
||||
passMesh.convex_color = flat;
|
||||
passMesh.concave_color = flat;
|
||||
passMesh.flat_color = flat;
|
||||
}
|
||||
|
||||
edge_ub_pass_t passHull = { 0 };
|
||||
|
||||
Vec4 hullEdgeColor = { 0.5f, 0.5f, 0.5f, 0.5f };
|
||||
Vec4 hull = Premultiply( hullEdgeColor );
|
||||
passHull.convex_color = hull;
|
||||
passHull.concave_color = hull;
|
||||
passHull.flat_color = hull;
|
||||
|
||||
sg_view currentEdgeView = { SG_INVALID_ID };
|
||||
sg_view currentInstView = { SG_INVALID_ID };
|
||||
int currentPassKind = -1; // -1 none, 0 mesh colors, 1 hull color
|
||||
|
||||
int batchCount = GetMeshEdgeBatchCount();
|
||||
for ( int i = 0; i < batchCount; ++i )
|
||||
{
|
||||
MeshEdgeBatch b = GetMeshEdgeBatch( i );
|
||||
if ( arenaFilter == ARENA_FILTER_OPAQUE_ONLY && b.isTransparent )
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if ( arenaFilter == ARENA_FILTER_TRANSPARENT_ONLY && b.isTransparent == false )
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if ( b.instanceCount <= 0 )
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if ( b.edgeCount <= 0 )
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if ( IsBatchEnabled( &b, params ) == false )
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
int passKind = ( b.kind == MESH_KIND_HULL ) ? 1 : 0;
|
||||
if ( passKind != currentPassKind )
|
||||
{
|
||||
if ( passKind == 1 )
|
||||
{
|
||||
sg_apply_uniforms( UB_edge_ub_pass, &SG_RANGE( passHull ) );
|
||||
}
|
||||
else
|
||||
{
|
||||
sg_apply_uniforms( UB_edge_ub_pass, &SG_RANGE( passMesh ) );
|
||||
}
|
||||
currentPassKind = passKind;
|
||||
}
|
||||
|
||||
sg_view instView = b.isTransparent ? transparentInstanceView : opaqueInstanceView;
|
||||
if ( instView.id != currentInstView.id || b.edgeStorageView.id != currentEdgeView.id )
|
||||
{
|
||||
sg_bindings bnd = { 0 };
|
||||
bnd.views[VIEW_edge_geom_instances] = instView;
|
||||
bnd.views[VIEW_edge_edge_endpoints] = b.edgeStorageView;
|
||||
sg_apply_bindings( &bnd );
|
||||
currentInstView = instView;
|
||||
currentEdgeView = b.edgeStorageView;
|
||||
}
|
||||
|
||||
edge_ub_draw_t ud = { 0 };
|
||||
ud.inst_base[0] = b.firstInstance;
|
||||
ud.edge_params = MakeVec4( params->thicknessPx, params->zBias, 0.0f, 0.0f );
|
||||
sg_apply_uniforms( UB_edge_ub_draw, &SG_RANGE( ud ) );
|
||||
|
||||
sg_draw( 0, 6 * b.edgeCount, b.instanceCount );
|
||||
}
|
||||
}
|
||||
|
||||
// Cheap pre-walk to avoid issuing pipeline / bindings / uniforms when no
|
||||
// batch survives the filter.
|
||||
static bool DoesAnyBatchSurvive( ArenaFilter arenaFilter, const EdgeOverlayParams* params )
|
||||
{
|
||||
const int batchCount = GetMeshEdgeBatchCount();
|
||||
for ( int i = 0; i < batchCount; ++i )
|
||||
{
|
||||
const MeshEdgeBatch b = GetMeshEdgeBatch( i );
|
||||
if ( arenaFilter == ARENA_FILTER_OPAQUE_ONLY && b.isTransparent )
|
||||
continue;
|
||||
if ( arenaFilter == ARENA_FILTER_TRANSPARENT_ONLY && !b.isTransparent )
|
||||
continue;
|
||||
if ( b.instanceCount <= 0 )
|
||||
continue;
|
||||
if ( b.edgeCount <= 0 )
|
||||
continue;
|
||||
if ( IsBatchEnabled( &b, params ) )
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// When true, the MSAA path draws BOTH opaque AND transparent edge batches, so
|
||||
// transparent-hull edges also pick up 4x MSAA at the cost of the translucent body
|
||||
// blending over them post-resolve.
|
||||
// Result: rendering transparent hulls after their edges yields jaggies
|
||||
#define EDGES_MSAA_INCLUDES_TRANSPARENT 0
|
||||
|
||||
// Mirror experiment: route ALL edge batches (opaque-arena meshes /
|
||||
// heightfields as well as the transparent-arena hulls) through the
|
||||
// post-resolve transparent path and skip the MSAA submission entirely.
|
||||
// Edges lose 4x MSAA (they fall back to fwidth-based fragment AA) but
|
||||
// they're guaranteed crisp on top of everything, including transparent
|
||||
// hulls.
|
||||
// Result: rendering edges for opaque meshes after MSAA resolve yields jaggies
|
||||
// probably due to inconsistent AA on the edges and the MSAA opaque geometry.
|
||||
#define EDGES_TRANSPARENT_INCLUDES_OPAQUE 0
|
||||
|
||||
// Conclusion: the split edge rendering is worth it. Must keep.
|
||||
|
||||
#if EDGES_MSAA_INCLUDES_TRANSPARENT && EDGES_TRANSPARENT_INCLUDES_OPAQUE
|
||||
#error "EDGES_MSAA_INCLUDES_TRANSPARENT and EDGES_TRANSPARENT_INCLUDES_OPAQUE are mutually exclusive"
|
||||
#endif
|
||||
|
||||
void RenderEdgesInMSAA( int width, int height, const Mat4* view, const Mat4* proj, sg_view opaqueInstanceView,
|
||||
sg_view transparentInstanceView, const EdgeOverlayParams* params )
|
||||
{
|
||||
if ( !s_edges.ready || !params || !params->enabled )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Experiment drawing all edges after transparent shapes with no MSAA
|
||||
if ( EDGES_TRANSPARENT_INCLUDES_OPAQUE )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
const ArenaFilter filter = EDGES_MSAA_INCLUDES_TRANSPARENT ? ARENA_FILTER_BOTH : ARENA_FILTER_OPAQUE_ONLY;
|
||||
if ( !DoesAnyBatchSurvive( filter, params ) )
|
||||
{
|
||||
return;
|
||||
}
|
||||
SubmitBatches( width, height, view, proj, s_edges.pipelineMsaa, opaqueInstanceView, transparentInstanceView, filter, params );
|
||||
}
|
||||
|
||||
void RenderEdgesPostTransparent( int width, int height, const Mat4* view, const Mat4* proj, sg_view colorAttachView,
|
||||
sg_view depthAttachView, sg_view opaqueInstanceView, sg_view transparentInstanceView,
|
||||
const EdgeOverlayParams* params )
|
||||
{
|
||||
if ( !s_edges.ready || !params || !params->enabled )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Experiment drawing all edges in the MSAA scene, even for edges on transparent hulls.
|
||||
if ( EDGES_MSAA_INCLUDES_TRANSPARENT )
|
||||
{
|
||||
return;
|
||||
}
|
||||
const ArenaFilter filter = EDGES_TRANSPARENT_INCLUDES_OPAQUE ? ARENA_FILTER_BOTH : ARENA_FILTER_TRANSPARENT_ONLY;
|
||||
if ( !DoesAnyBatchSurvive( filter, params ) )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
sg_pass pass = { 0 };
|
||||
pass.action.colors[0].load_action = SG_LOADACTION_LOAD;
|
||||
pass.action.colors[0].store_action = SG_STOREACTION_STORE;
|
||||
pass.action.depth.load_action = SG_LOADACTION_LOAD;
|
||||
pass.action.depth.store_action = SG_STOREACTION_DONTCARE;
|
||||
pass.attachments.colors[0] = colorAttachView;
|
||||
pass.attachments.depth_stencil = depthAttachView;
|
||||
pass.label = "edge_overlay_pass_transparent";
|
||||
sg_push_debug_group( "edges_transparent" );
|
||||
sg_begin_pass( &pass );
|
||||
sg_apply_viewport( 0, 0, width, height, true );
|
||||
|
||||
SubmitBatches( width, height, view, proj, s_edges.pipelineTransparent, opaqueInstanceView, transparentInstanceView, filter,
|
||||
params );
|
||||
|
||||
sg_end_pass();
|
||||
sg_pop_debug_group();
|
||||
}
|
||||
71
samples/gfx/edges.h
Normal file
71
samples/gfx/edges.h
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Renders per-shape edges for hulls, meshes, and heightfields registered in
|
||||
// the geometry registry. Same shader / batching for both arenas. Split
|
||||
// into two submission paths to match the silhouette quality of the
|
||||
// rest of the scene:
|
||||
//
|
||||
// Opaque path (RenderEdgesInMSAA): opaque-arena batches (meshes,
|
||||
// heightfields, opaque hulls if policy 1b is ever relaxed). Draws
|
||||
// inside the caller's currently-open MSAA scene pass, picking up the
|
||||
// same 4x MSAA as the opaque shapes. Pipeline tracks scene_target's
|
||||
// color/depth formats and sample_count.
|
||||
//
|
||||
// Transparent path (RenderEdgesPostTransparent): transparent-arena batches
|
||||
// (hulls per policy 1b). Opens its own single-sample pass against the
|
||||
// resolved scene color + GTAO prepass depth, so edges sit on top of the
|
||||
// transparent draws that have already blended into the resolve. MSAA
|
||||
// isn't available here (the resolve already happened), the FS's
|
||||
// fwidth-based AA does what it can.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "gfx/utility.h"
|
||||
#include "sokol_gfx.h"
|
||||
|
||||
#include <stdbool.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"
|
||||
{
|
||||
#endif
|
||||
|
||||
typedef struct EdgeOverlayParams
|
||||
{
|
||||
bool enabled;
|
||||
bool showHulls;
|
||||
bool showMeshes;
|
||||
bool showHeightfields;
|
||||
bool showEdgeConvexity;
|
||||
float thicknessPx;
|
||||
float zBias; // reverse-Z nudge toward camera, ~5e-5 is a good start
|
||||
Vec4 convexColor; // straight (non-premultiplied) linear RGBA, premultiplied inside
|
||||
Vec4 concaveColor;
|
||||
Vec4 flatColor;
|
||||
} EdgeOverlayParams;
|
||||
|
||||
EdgeOverlayParams GetDefaultEdgeParams( void );
|
||||
|
||||
void InitEdges( void );
|
||||
void ShutdownEdges( void );
|
||||
|
||||
// Draw edge batches into the caller's currently-open render pass. The pass
|
||||
// must be the MSAA scene pass (sceneTargetAttachments), the pipeline
|
||||
// matches its color format (RGBA16F), depth format (sceneTargetDepthFormat),
|
||||
// and sample_count (4).
|
||||
void RenderEdgesInMSAA( int width, int height, const Mat4* view, const Mat4* proj, sg_view opaqueInstanceView,
|
||||
sg_view transparentInstanceView, const EdgeOverlayParams* params );
|
||||
|
||||
// Open a single-sample render pass against (colorAttachView, depthAttachView)
|
||||
// and draw transparent-arena edge batches. When the
|
||||
// EDGES_TRANSPARENT_INCLUDES_OPAQUE experiment is enabled, opaque-arena
|
||||
// batches are also drawn here (and the MSAA path becomes a no-op), so the
|
||||
// caller must pass a valid opaqueInstanceView too.
|
||||
void RenderEdgesPostTransparent( int width, int height, const Mat4* view, const Mat4* proj, sg_view colorAttachView,
|
||||
sg_view depthAttachView, sg_view opaqueInstanceView, sg_view transparentInstanceView,
|
||||
const EdgeOverlayParams* params );
|
||||
|
||||
#ifdef __cplusplus
|
||||
} // extern "C"
|
||||
#endif
|
||||
770
samples/gfx/geometry_registry.c
Normal file
770
samples/gfx/geometry_registry.c
Normal file
|
|
@ -0,0 +1,770 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "gfx/geometry_registry.h"
|
||||
|
||||
#include "geom.glsl.h"
|
||||
|
||||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define MAX_REGISTRY_ENTRIES 256
|
||||
#define MAX_GEOM_INSTANCES_GLOBAL 65536
|
||||
#define INITIAL_PER_ENTRY_CAPACITY 8
|
||||
|
||||
typedef struct Entry
|
||||
{
|
||||
uint32_t hash;
|
||||
int refCount; // 0 means free
|
||||
sg_buffer vbo;
|
||||
sg_buffer ibo;
|
||||
int indexCount;
|
||||
MeshKind kind; // shape-kind tag, default UNKNOWN
|
||||
|
||||
// edge overlay data. edgeCount == 0 and edgeBuf.id == SG_INVALID_ID
|
||||
// means "no edges registered", HasEdges returns false. Otherwise
|
||||
// edgeBuf is a storage-buffer-usage GPU buffer of 2*edgeCount EdgeVertex
|
||||
// entries (two endpoints per edge), accessed via edgeStorageView.
|
||||
sg_buffer edgeBuf;
|
||||
sg_view edgeStorageView;
|
||||
int edgeCount;
|
||||
|
||||
// per-entry xp-arena first instance offset, captured during the
|
||||
// xp upload loop. Valid for the rest of the frame when xpCount > 0.
|
||||
int xpFirstInstance;
|
||||
|
||||
// Per-frame CPU staging for the opaque path. instances grows on demand
|
||||
// (doubling) so the first frame for a given geometry may allocate,
|
||||
// later frames reuse the buffer.
|
||||
geom_instance_t* instances;
|
||||
int count;
|
||||
int capacity;
|
||||
|
||||
// Set during UploadMeshInstances. Valid for the rest of the frame.
|
||||
int firstInstance;
|
||||
|
||||
// transparent path. Parallel arena per entry, packed into the
|
||||
// shared xp instance GPU buffer at upload time.
|
||||
geom_instance_t* xpInstances;
|
||||
int xpCount;
|
||||
int xpCapacity;
|
||||
} Entry;
|
||||
|
||||
static struct
|
||||
{
|
||||
Entry entries[MAX_REGISTRY_ENTRIES];
|
||||
int entryCount; // high-water mark, freed slots are reused
|
||||
|
||||
// Shared GPU storage buffer for instance data across all entries.
|
||||
sg_buffer instBuf;
|
||||
sg_view instView;
|
||||
|
||||
// Packing scratch: rebuilt every frame by UploadMeshInstances.
|
||||
geom_instance_t* uploadScratch;
|
||||
int uploadScratchCap;
|
||||
|
||||
// Draw spans for the frame. Rebuilt by UploadMeshInstances. drawSpans
|
||||
// holds positive-determinant runs (back-culled), mirrorDrawSpans holds
|
||||
// negative-determinant runs (front-culled). A mesh entry with a mix of
|
||||
// both contributes one span to each, so each list caps at one per entry.
|
||||
MeshDrawSpan drawSpans[MAX_REGISTRY_ENTRIES];
|
||||
int drawSpanCount;
|
||||
MeshDrawSpan mirrorDrawSpans[MAX_REGISTRY_ENTRIES];
|
||||
int mirrorDrawSpanCount;
|
||||
|
||||
// transparent path. xpInstBuf holds at most
|
||||
// MAX_GEOM_XP_INSTANCES_GLOBAL instances, xpDraws[] is the per-
|
||||
// instance draw list the renderer's back-to-front sort consumes.
|
||||
sg_buffer xpInstBuf;
|
||||
sg_view xpInstView;
|
||||
geom_instance_t* xpUploadScratch;
|
||||
int xpUploadScratchCap;
|
||||
MeshXpInstance xpDraws[MAX_GEOM_XP_INSTANCES_GLOBAL];
|
||||
int xpDrawCount;
|
||||
|
||||
// per-entry edge batches, rebuilt by UploadMeshInstances.
|
||||
// Two slots per entry (opaque + xp) so the cap is 2 x MAX_REGISTRY.
|
||||
MeshEdgeBatch edgeBatches[2 * MAX_REGISTRY_ENTRIES];
|
||||
int edgeBatchCount;
|
||||
} s_geom;
|
||||
|
||||
void CreateMeshRegistry( void )
|
||||
{
|
||||
sg_buffer_desc bdesc = { 0 };
|
||||
bdesc.usage.storage_buffer = true;
|
||||
bdesc.usage.stream_update = true;
|
||||
bdesc.size = (size_t)MAX_GEOM_INSTANCES_GLOBAL * sizeof( geom_instance_t );
|
||||
bdesc.label = "geom_instances";
|
||||
s_geom.instBuf = sg_make_buffer( &bdesc );
|
||||
|
||||
sg_view_desc vdesc = { 0 };
|
||||
vdesc.storage_buffer.buffer = s_geom.instBuf;
|
||||
vdesc.label = "geom_instances_view";
|
||||
s_geom.instView = sg_make_view( &vdesc );
|
||||
|
||||
sg_buffer_desc xpbdesc = { 0 };
|
||||
xpbdesc.usage.storage_buffer = true;
|
||||
xpbdesc.usage.stream_update = true;
|
||||
xpbdesc.size = (size_t)MAX_GEOM_XP_INSTANCES_GLOBAL * sizeof( geom_instance_t );
|
||||
xpbdesc.label = "geom_instances_xp";
|
||||
s_geom.xpInstBuf = sg_make_buffer( &xpbdesc );
|
||||
|
||||
sg_view_desc xpvdesc = { 0 };
|
||||
xpvdesc.storage_buffer.buffer = s_geom.xpInstBuf;
|
||||
xpvdesc.label = "geom_instances_xp_view";
|
||||
s_geom.xpInstView = sg_make_view( &xpvdesc );
|
||||
|
||||
s_geom.uploadScratch = NULL;
|
||||
s_geom.uploadScratchCap = 0;
|
||||
s_geom.xpUploadScratch = NULL;
|
||||
s_geom.xpUploadScratchCap = 0;
|
||||
s_geom.entryCount = 0;
|
||||
s_geom.drawSpanCount = 0;
|
||||
s_geom.mirrorDrawSpanCount = 0;
|
||||
s_geom.xpDrawCount = 0;
|
||||
s_geom.edgeBatchCount = 0;
|
||||
}
|
||||
|
||||
void DestroyMeshRegistry( void )
|
||||
{
|
||||
for ( int i = 0; i < s_geom.entryCount; ++i )
|
||||
{
|
||||
Entry* e = &s_geom.entries[i];
|
||||
if ( e->refCount > 0 )
|
||||
{
|
||||
sg_destroy_buffer( e->ibo );
|
||||
sg_destroy_buffer( e->vbo );
|
||||
if ( e->edgeCount > 0 )
|
||||
{
|
||||
sg_destroy_view( e->edgeStorageView );
|
||||
sg_destroy_buffer( e->edgeBuf );
|
||||
}
|
||||
}
|
||||
free( e->instances );
|
||||
e->instances = NULL;
|
||||
e->capacity = 0;
|
||||
free( e->xpInstances );
|
||||
e->xpInstances = NULL;
|
||||
e->xpCapacity = 0;
|
||||
}
|
||||
s_geom.entryCount = 0;
|
||||
|
||||
free( s_geom.uploadScratch );
|
||||
s_geom.uploadScratch = NULL;
|
||||
s_geom.uploadScratchCap = 0;
|
||||
free( s_geom.xpUploadScratch );
|
||||
s_geom.xpUploadScratch = NULL;
|
||||
s_geom.xpUploadScratchCap = 0;
|
||||
|
||||
sg_destroy_view( s_geom.xpInstView );
|
||||
sg_destroy_buffer( s_geom.xpInstBuf );
|
||||
sg_destroy_view( s_geom.instView );
|
||||
sg_destroy_buffer( s_geom.instBuf );
|
||||
}
|
||||
|
||||
MeshHandle FindMesh( uint32_t hash )
|
||||
{
|
||||
if ( hash == 0u )
|
||||
{
|
||||
return InvalidMeshHandle();
|
||||
}
|
||||
|
||||
for ( int i = 0; i < s_geom.entryCount; ++i )
|
||||
{
|
||||
const Entry* e = &s_geom.entries[i];
|
||||
if ( e->refCount > 0 && e->hash == hash )
|
||||
{
|
||||
MeshHandle h = { i, hash };
|
||||
return h;
|
||||
}
|
||||
}
|
||||
|
||||
return InvalidMeshHandle();
|
||||
}
|
||||
|
||||
static int FindFreeSlot( void )
|
||||
{
|
||||
for ( int i = 0; i < s_geom.entryCount; ++i )
|
||||
{
|
||||
if ( s_geom.entries[i].refCount == 0 )
|
||||
{
|
||||
return i;
|
||||
}
|
||||
}
|
||||
if ( s_geom.entryCount >= MAX_REGISTRY_ENTRIES )
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
return s_geom.entryCount++;
|
||||
}
|
||||
|
||||
MeshHandle RegisterMesh( uint32_t hash, const MeshVertex* vertices, int vertexCount, const uint32_t* indices,
|
||||
int indexCount, const char* debugLabel )
|
||||
{
|
||||
assert( hash != 0u );
|
||||
assert( vertexCount > 0 );
|
||||
assert( indexCount > 0 );
|
||||
|
||||
const int slot = FindFreeSlot();
|
||||
if ( slot < 0 )
|
||||
{
|
||||
fprintf( stderr, "error: registry full (cap=%d), dropping geometry\n", MAX_REGISTRY_ENTRIES );
|
||||
return InvalidMeshHandle();
|
||||
}
|
||||
|
||||
Entry* e = &s_geom.entries[slot];
|
||||
|
||||
sg_buffer_desc vbDesc = { 0 };
|
||||
vbDesc.usage.vertex_buffer = true;
|
||||
vbDesc.usage.immutable = true;
|
||||
vbDesc.data.ptr = vertices;
|
||||
vbDesc.data.size = (size_t)vertexCount * sizeof( MeshVertex );
|
||||
vbDesc.label = debugLabel ? debugLabel : "geom_vbo";
|
||||
e->vbo = sg_make_buffer( &vbDesc );
|
||||
|
||||
sg_buffer_desc ibDesc = { 0 };
|
||||
ibDesc.usage.index_buffer = true;
|
||||
ibDesc.usage.immutable = true;
|
||||
ibDesc.data.ptr = indices;
|
||||
ibDesc.data.size = (size_t)indexCount * sizeof( uint32_t );
|
||||
ibDesc.label = debugLabel ? debugLabel : "geom_ibo";
|
||||
e->ibo = sg_make_buffer( &ibDesc );
|
||||
|
||||
e->hash = hash;
|
||||
e->refCount = 1;
|
||||
e->indexCount = indexCount;
|
||||
e->kind = MESH_KIND_UNKNOWN;
|
||||
e->edgeBuf.id = SG_INVALID_ID;
|
||||
e->edgeStorageView.id = SG_INVALID_ID;
|
||||
e->edgeCount = 0;
|
||||
e->xpFirstInstance = 0;
|
||||
e->count = 0;
|
||||
e->xpCount = 0;
|
||||
// instances/xpInstances/capacities persist across re-registration in
|
||||
// the same slot.
|
||||
|
||||
MeshHandle h = { slot, hash };
|
||||
return h;
|
||||
}
|
||||
|
||||
void RegisterMeshEdges( MeshHandle h, const EdgeVertex* edges, int edgeCount, const char* debugLabel )
|
||||
{
|
||||
if ( !IsMeshHandleValid( h ) )
|
||||
{
|
||||
return;
|
||||
}
|
||||
if ( edges == NULL || edgeCount <= 0 )
|
||||
{
|
||||
return;
|
||||
}
|
||||
Entry* e = &s_geom.entries[h.index];
|
||||
if ( e->refCount == 0 || e->hash != h.hash )
|
||||
{
|
||||
return;
|
||||
}
|
||||
assert( e->edgeCount == 0 && "RegisterMeshEdges already called for this entry" );
|
||||
|
||||
sg_buffer_desc bdesc = { 0 };
|
||||
bdesc.usage.storage_buffer = true;
|
||||
bdesc.usage.immutable = true;
|
||||
bdesc.data.ptr = edges;
|
||||
bdesc.data.size = (size_t)( 2 * edgeCount ) * sizeof( EdgeVertex );
|
||||
bdesc.label = debugLabel ? debugLabel : "geom_edges";
|
||||
e->edgeBuf = sg_make_buffer( &bdesc );
|
||||
|
||||
sg_view_desc vdesc = { 0 };
|
||||
vdesc.storage_buffer.buffer = e->edgeBuf;
|
||||
vdesc.label = debugLabel ? debugLabel : "geom_edges_view";
|
||||
e->edgeStorageView = sg_make_view( &vdesc );
|
||||
|
||||
e->edgeCount = edgeCount;
|
||||
}
|
||||
|
||||
bool HasEdges( MeshHandle h )
|
||||
{
|
||||
if ( !IsMeshHandleValid( h ) )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
const Entry* e = &s_geom.entries[h.index];
|
||||
if ( e->refCount == 0 || e->hash != h.hash )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return e->edgeCount > 0;
|
||||
}
|
||||
|
||||
int GetEdgeCount( MeshHandle h )
|
||||
{
|
||||
if ( !IsMeshHandleValid( h ) )
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
const Entry* e = &s_geom.entries[h.index];
|
||||
if ( e->refCount == 0 || e->hash != h.hash )
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
return e->edgeCount;
|
||||
}
|
||||
|
||||
sg_view GetEdgeStorageView( MeshHandle h )
|
||||
{
|
||||
sg_view invalid = { SG_INVALID_ID };
|
||||
if ( !IsMeshHandleValid( h ) )
|
||||
{
|
||||
return invalid;
|
||||
}
|
||||
const Entry* e = &s_geom.entries[h.index];
|
||||
if ( e->refCount == 0 || e->hash != h.hash || e->edgeCount == 0 )
|
||||
{
|
||||
return invalid;
|
||||
}
|
||||
return e->edgeStorageView;
|
||||
}
|
||||
|
||||
void SetMeshKind( MeshHandle h, MeshKind kind )
|
||||
{
|
||||
if ( !IsMeshHandleValid( h ) )
|
||||
{
|
||||
return;
|
||||
}
|
||||
Entry* e = &s_geom.entries[h.index];
|
||||
if ( e->refCount == 0 || e->hash != h.hash )
|
||||
{
|
||||
return;
|
||||
}
|
||||
e->kind = kind;
|
||||
}
|
||||
|
||||
MeshKind GetMeshKind( MeshHandle h )
|
||||
{
|
||||
if ( !IsMeshHandleValid( h ) )
|
||||
{
|
||||
return MESH_KIND_UNKNOWN;
|
||||
}
|
||||
const Entry* e = &s_geom.entries[h.index];
|
||||
if ( e->refCount == 0 || e->hash != h.hash )
|
||||
{
|
||||
return MESH_KIND_UNKNOWN;
|
||||
}
|
||||
return e->kind;
|
||||
}
|
||||
|
||||
bool GetMeshBuffers( MeshHandle h, MeshBuffers* out )
|
||||
{
|
||||
if ( !IsMeshHandleValid( h ) || !out )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
const Entry* e = &s_geom.entries[h.index];
|
||||
if ( e->refCount == 0 || e->hash != h.hash )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
out->vbo = e->vbo;
|
||||
out->ibo = e->ibo;
|
||||
out->indexCount = e->indexCount;
|
||||
return true;
|
||||
}
|
||||
|
||||
void AddMeshReference( MeshHandle h )
|
||||
{
|
||||
if ( !IsMeshHandleValid( h ) )
|
||||
{
|
||||
return;
|
||||
}
|
||||
Entry* e = &s_geom.entries[h.index];
|
||||
assert( e->refCount > 0 && e->hash == h.hash );
|
||||
e->refCount += 1;
|
||||
}
|
||||
|
||||
void ReleaseMeshReference( MeshHandle h )
|
||||
{
|
||||
if ( !IsMeshHandleValid( h ) )
|
||||
{
|
||||
return;
|
||||
}
|
||||
Entry* e = &s_geom.entries[h.index];
|
||||
assert( e->refCount > 0 && e->hash == h.hash );
|
||||
e->refCount -= 1;
|
||||
if ( e->refCount == 0 )
|
||||
{
|
||||
sg_destroy_buffer( e->ibo );
|
||||
sg_destroy_buffer( e->vbo );
|
||||
if ( e->edgeCount > 0 )
|
||||
{
|
||||
sg_destroy_view( e->edgeStorageView );
|
||||
sg_destroy_buffer( e->edgeBuf );
|
||||
}
|
||||
e->hash = 0u;
|
||||
e->indexCount = 0;
|
||||
e->edgeBuf.id = SG_INVALID_ID;
|
||||
e->edgeStorageView.id = SG_INVALID_ID;
|
||||
e->edgeCount = 0;
|
||||
e->count = 0;
|
||||
e->xpCount = 0;
|
||||
// Keep instances/xpInstances/capacities for the slot's next tenant.
|
||||
}
|
||||
}
|
||||
|
||||
void ResetFrameForMeshes( void )
|
||||
{
|
||||
for ( int i = 0; i < s_geom.entryCount; ++i )
|
||||
{
|
||||
s_geom.entries[i].count = 0;
|
||||
s_geom.entries[i].xpCount = 0;
|
||||
}
|
||||
s_geom.drawSpanCount = 0;
|
||||
s_geom.mirrorDrawSpanCount = 0;
|
||||
s_geom.xpDrawCount = 0;
|
||||
s_geom.edgeBatchCount = 0;
|
||||
}
|
||||
|
||||
static void PackMat4ToInstance( const Mat4* transform, b3Vec3 scale, Vec4 baseColor, float metallic, float roughness,
|
||||
MeshMaterialMode materialMode, float gridCellSize, TransparentShadowCast shadowCast,
|
||||
geom_instance_t* inst )
|
||||
{
|
||||
// 3x4 affine pack identical to PackXformRows in renderer.c. Rotation
|
||||
// rows in .xyz, translation column in .w of each row.
|
||||
inst->xform_row0.x = transform->cx.x;
|
||||
inst->xform_row0.y = transform->cy.x;
|
||||
inst->xform_row0.z = transform->cz.x;
|
||||
inst->xform_row0.w = transform->cw.x;
|
||||
inst->xform_row1.x = transform->cx.y;
|
||||
inst->xform_row1.y = transform->cy.y;
|
||||
inst->xform_row1.z = transform->cz.y;
|
||||
inst->xform_row1.w = transform->cw.y;
|
||||
inst->xform_row2.x = transform->cx.z;
|
||||
inst->xform_row2.y = transform->cy.z;
|
||||
inst->xform_row2.z = transform->cz.z;
|
||||
inst->xform_row2.w = transform->cw.z;
|
||||
|
||||
inst->base_color = baseColor;
|
||||
|
||||
inst->scale.x = scale.x;
|
||||
inst->scale.y = scale.y;
|
||||
inst->scale.z = scale.z;
|
||||
inst->scale.w = 0.0f;
|
||||
|
||||
// overload material.w with the shadow-cast bit for SOLID shapes.
|
||||
// GROUND_GRID's gridCellSize stays put, the geom FS reads material.w
|
||||
// only inside the GROUND_GRID branch (`v_material.z > 0.5`), so SOLID
|
||||
// shapes can repurpose the slot. Ground shapes are always opaque +
|
||||
// FULL by usage, the dual use is safe by construction. Renderer-side
|
||||
// shadow-cast queries go through MeshXpInstance.shadowCast, not
|
||||
// material.w, so this packing is purely about keeping the GPU
|
||||
// instance-struct stride unchanged.
|
||||
const bool isGround = ( materialMode == MESH_MATERIAL_MODE_GROUND_GRID );
|
||||
inst->material.x = metallic;
|
||||
inst->material.y = roughness;
|
||||
inst->material.z = (float)materialMode;
|
||||
inst->material.w = isGround ? gridCellSize : ( ( shadowCast == TRANSPARENT_SHADOW_FULL ) ? 1.0f : 0.0f );
|
||||
}
|
||||
|
||||
static b3Vec3 GetOriginFromInstance( const geom_instance_t* inst )
|
||||
{
|
||||
return (b3Vec3){ inst->xform_row0.w, inst->xform_row1.w, inst->xform_row2.w };
|
||||
}
|
||||
|
||||
void AppendMesh( MeshHandle h, b3Transform transform, b3Vec3 scale, Vec4 baseColor, float metallic, float roughness,
|
||||
MeshMaterialMode materialMode, float gridCellSize, TransparentShadowCast shadowCast )
|
||||
{
|
||||
if ( !IsMeshHandleValid( h ) )
|
||||
{
|
||||
return;
|
||||
}
|
||||
Entry* e = &s_geom.entries[h.index];
|
||||
if ( e->refCount == 0 || e->hash != h.hash )
|
||||
{
|
||||
// Stale handle, slot got reused. Caller messed up retain/release.
|
||||
return;
|
||||
}
|
||||
|
||||
const bool xp = baseColor.w < 1.0f;
|
||||
geom_instance_t** arr = xp ? &e->xpInstances : &e->instances;
|
||||
int* cnt = xp ? &e->xpCount : &e->count;
|
||||
int* cap = xp ? &e->xpCapacity : &e->capacity;
|
||||
|
||||
if ( *cnt >= *cap )
|
||||
{
|
||||
const int newCap = *cap == 0 ? INITIAL_PER_ENTRY_CAPACITY : *cap * 2;
|
||||
geom_instance_t* grown = (geom_instance_t*)realloc( *arr, (size_t)newCap * sizeof( geom_instance_t ) );
|
||||
if ( !grown )
|
||||
{
|
||||
fprintf( stderr, "error: per-entry%s grow failed (newCap=%d)\n", xp ? "(xp)" : "", newCap );
|
||||
return;
|
||||
}
|
||||
*arr = grown;
|
||||
*cap = newCap;
|
||||
}
|
||||
Mat4 m = MakeMat4FromTransform( transform, b3Vec3_one );
|
||||
PackMat4ToInstance( &m, scale, baseColor, metallic, roughness, materialMode, gridCellSize, shadowCast,
|
||||
&( *arr )[( *cnt )++] );
|
||||
}
|
||||
|
||||
int UploadMeshInstances( void )
|
||||
{
|
||||
// Opaque pack
|
||||
int total = 0;
|
||||
for ( int i = 0; i < s_geom.entryCount; ++i )
|
||||
{
|
||||
total += s_geom.entries[i].count;
|
||||
}
|
||||
s_geom.drawSpanCount = 0;
|
||||
if ( total > MAX_GEOM_INSTANCES_GLOBAL )
|
||||
{
|
||||
fprintf( stderr, "error: %d opaque instances exceeds global cap %d\n", total, MAX_GEOM_INSTANCES_GLOBAL );
|
||||
total = MAX_GEOM_INSTANCES_GLOBAL;
|
||||
}
|
||||
int opaqueCursor = 0;
|
||||
if ( total > 0 )
|
||||
{
|
||||
if ( total > s_geom.uploadScratchCap )
|
||||
{
|
||||
geom_instance_t* grown = (geom_instance_t*)realloc( s_geom.uploadScratch, (size_t)total * sizeof( geom_instance_t ) );
|
||||
if ( !grown )
|
||||
{
|
||||
fprintf( stderr, "error: upload scratch grow failed\n" );
|
||||
return 0;
|
||||
}
|
||||
s_geom.uploadScratch = grown;
|
||||
s_geom.uploadScratchCap = total;
|
||||
}
|
||||
|
||||
for ( int i = 0; i < s_geom.entryCount && opaqueCursor < total; ++i )
|
||||
{
|
||||
Entry* e = &s_geom.entries[i];
|
||||
if ( e->refCount == 0 || e->count == 0 )
|
||||
{
|
||||
continue;
|
||||
}
|
||||
int take = e->count;
|
||||
if ( opaqueCursor + take > total )
|
||||
{
|
||||
take = total - opaqueCursor;
|
||||
}
|
||||
|
||||
// Stable-partition the run, positive-determinant instances first
|
||||
// then mirror-scaled ones. Rotation is proper so sign(scale.x*y*z)
|
||||
// is the winding sign. The two sub-runs stay contiguous, the
|
||||
// renderer draws the front part back-culled and the tail (mirror)
|
||||
// front-culled.
|
||||
geom_instance_t* dst = &s_geom.uploadScratch[opaqueCursor];
|
||||
int posCount = 0;
|
||||
for ( int k = 0; k < take; ++k )
|
||||
{
|
||||
const geom_instance_t* inst = &e->instances[k];
|
||||
if ( inst->scale.x * inst->scale.y * inst->scale.z >= 0.0f )
|
||||
{
|
||||
dst[posCount++] = *inst;
|
||||
}
|
||||
}
|
||||
int negCount = 0;
|
||||
for ( int k = 0; k < take; ++k )
|
||||
{
|
||||
const geom_instance_t* inst = &e->instances[k];
|
||||
if ( inst->scale.x * inst->scale.y * inst->scale.z < 0.0f )
|
||||
{
|
||||
dst[posCount + negCount++] = *inst;
|
||||
}
|
||||
}
|
||||
e->firstInstance = opaqueCursor;
|
||||
|
||||
if ( posCount > 0 )
|
||||
{
|
||||
MeshDrawSpan span;
|
||||
span.vbo = e->vbo;
|
||||
span.ibo = e->ibo;
|
||||
span.indexCount = e->indexCount;
|
||||
span.firstInstance = opaqueCursor;
|
||||
span.instanceCount = posCount;
|
||||
s_geom.drawSpans[s_geom.drawSpanCount++] = span;
|
||||
}
|
||||
if ( negCount > 0 )
|
||||
{
|
||||
MeshDrawSpan span;
|
||||
span.vbo = e->vbo;
|
||||
span.ibo = e->ibo;
|
||||
span.indexCount = e->indexCount;
|
||||
span.firstInstance = opaqueCursor + posCount;
|
||||
span.instanceCount = negCount;
|
||||
s_geom.mirrorDrawSpans[s_geom.mirrorDrawSpanCount++] = span;
|
||||
}
|
||||
|
||||
// Edge batch covers the whole run, partition order is irrelevant
|
||||
// to the edge pass (each instance draws via firstInstance + index).
|
||||
if ( e->edgeCount > 0 )
|
||||
{
|
||||
MeshEdgeBatch eb;
|
||||
eb.kind = e->kind;
|
||||
eb.edgeStorageView = e->edgeStorageView;
|
||||
eb.edgeCount = e->edgeCount;
|
||||
eb.firstInstance = opaqueCursor;
|
||||
eb.instanceCount = take;
|
||||
eb.isTransparent = false;
|
||||
s_geom.edgeBatches[s_geom.edgeBatchCount++] = eb;
|
||||
}
|
||||
|
||||
opaqueCursor += take;
|
||||
}
|
||||
|
||||
sg_range r;
|
||||
r.ptr = s_geom.uploadScratch;
|
||||
r.size = (size_t)opaqueCursor * sizeof( geom_instance_t );
|
||||
sg_update_buffer( s_geom.instBuf, &r );
|
||||
}
|
||||
|
||||
// Transparent pack
|
||||
int xpTotal = 0;
|
||||
for ( int i = 0; i < s_geom.entryCount; ++i )
|
||||
{
|
||||
xpTotal += s_geom.entries[i].xpCount;
|
||||
}
|
||||
s_geom.xpDrawCount = 0;
|
||||
if ( xpTotal > MAX_GEOM_XP_INSTANCES_GLOBAL )
|
||||
{
|
||||
fprintf( stderr, "error: %d transparent instances exceeds cap %d\n", xpTotal, MAX_GEOM_XP_INSTANCES_GLOBAL );
|
||||
xpTotal = MAX_GEOM_XP_INSTANCES_GLOBAL;
|
||||
}
|
||||
int xpCursor = 0;
|
||||
if ( xpTotal > 0 )
|
||||
{
|
||||
if ( xpTotal > s_geom.xpUploadScratchCap )
|
||||
{
|
||||
geom_instance_t* grown =
|
||||
(geom_instance_t*)realloc( s_geom.xpUploadScratch, (size_t)xpTotal * sizeof( geom_instance_t ) );
|
||||
if ( !grown )
|
||||
{
|
||||
fprintf( stderr, "error: xp upload scratch grow failed\n" );
|
||||
return opaqueCursor;
|
||||
}
|
||||
s_geom.xpUploadScratch = grown;
|
||||
s_geom.xpUploadScratchCap = xpTotal;
|
||||
}
|
||||
|
||||
// Walk each entry's xpInstances and emit one xpDraws entry per
|
||||
// instance. The xp draw list is a flat per-instance enumeration,
|
||||
// the renderer's back-to-front sort consumes individual entries,
|
||||
// not per-entry spans (transparent draws can't share a single
|
||||
// sg_draw across entries with different vbo/ibo).
|
||||
for ( int i = 0; i < s_geom.entryCount && xpCursor < xpTotal; ++i )
|
||||
{
|
||||
Entry* e = &s_geom.entries[i];
|
||||
if ( e->refCount == 0 || e->xpCount == 0 )
|
||||
{
|
||||
continue;
|
||||
}
|
||||
int take = e->xpCount;
|
||||
if ( xpCursor + take > xpTotal )
|
||||
{
|
||||
take = xpTotal - xpCursor;
|
||||
}
|
||||
memcpy( &s_geom.xpUploadScratch[xpCursor], e->xpInstances, (size_t)take * sizeof( geom_instance_t ) );
|
||||
e->xpFirstInstance = xpCursor;
|
||||
for ( int k = 0; k < take && s_geom.xpDrawCount < MAX_GEOM_XP_INSTANCES_GLOBAL; ++k )
|
||||
{
|
||||
const geom_instance_t* src = &e->xpInstances[k];
|
||||
MeshXpInstance d;
|
||||
d.vbo = e->vbo;
|
||||
d.ibo = e->ibo;
|
||||
d.indexCount = e->indexCount;
|
||||
d.firstInstance = xpCursor + k;
|
||||
d.origin = GetOriginFromInstance( src );
|
||||
// shadowCast is packed into material.w for SOLID shapes,
|
||||
// GROUND_GRID can't be transparent in practice (ground
|
||||
// shapes are submitted opaque), so reading material.w as
|
||||
// the cast bit is safe for everything that lands here.
|
||||
d.shadowCast = src->material.w;
|
||||
s_geom.xpDraws[s_geom.xpDrawCount++] = d;
|
||||
}
|
||||
|
||||
// Edge batch for this entry's xp run. The edge pass draws all
|
||||
// xp instances of an entry in a single sg_draw, it doesn't
|
||||
// need per-instance back-to-front ordering (depth test handles
|
||||
// occlusion against opaque scene, edges over transparent
|
||||
// shapes blend additively without ordering concerns).
|
||||
if ( e->edgeCount > 0 )
|
||||
{
|
||||
MeshEdgeBatch eb;
|
||||
eb.kind = e->kind;
|
||||
eb.edgeStorageView = e->edgeStorageView;
|
||||
eb.edgeCount = e->edgeCount;
|
||||
eb.firstInstance = xpCursor;
|
||||
eb.instanceCount = take;
|
||||
eb.isTransparent = true;
|
||||
s_geom.edgeBatches[s_geom.edgeBatchCount++] = eb;
|
||||
}
|
||||
|
||||
xpCursor += take;
|
||||
}
|
||||
|
||||
sg_range xr;
|
||||
xr.ptr = s_geom.xpUploadScratch;
|
||||
xr.size = (size_t)xpCursor * sizeof( geom_instance_t );
|
||||
sg_update_buffer( s_geom.xpInstBuf, &xr );
|
||||
}
|
||||
|
||||
return opaqueCursor + xpCursor;
|
||||
}
|
||||
|
||||
int GetMeshDrawSpanCount( void )
|
||||
{
|
||||
return s_geom.drawSpanCount;
|
||||
}
|
||||
|
||||
MeshDrawSpan GetMeshDrawSpan( int i )
|
||||
{
|
||||
assert( i >= 0 && i < s_geom.drawSpanCount );
|
||||
return s_geom.drawSpans[i];
|
||||
}
|
||||
|
||||
int GetMeshMirrorDrawSpanCount( void )
|
||||
{
|
||||
return s_geom.mirrorDrawSpanCount;
|
||||
}
|
||||
|
||||
MeshDrawSpan GetMeshMirrorDrawSpan( int i )
|
||||
{
|
||||
assert( i >= 0 && i < s_geom.mirrorDrawSpanCount );
|
||||
return s_geom.mirrorDrawSpans[i];
|
||||
}
|
||||
|
||||
sg_view GetMeshInstanceView( void )
|
||||
{
|
||||
return s_geom.instView;
|
||||
}
|
||||
|
||||
int GetTransparentMeshInstanceCount( void )
|
||||
{
|
||||
return s_geom.xpDrawCount;
|
||||
}
|
||||
|
||||
MeshXpInstance GetTransparentMeshInstance( int i )
|
||||
{
|
||||
assert( i >= 0 && i < s_geom.xpDrawCount );
|
||||
return s_geom.xpDraws[i];
|
||||
}
|
||||
|
||||
sg_view GetTransparentMeshInstanceView( void )
|
||||
{
|
||||
return s_geom.xpInstView;
|
||||
}
|
||||
|
||||
int GetMeshEntryCount( void )
|
||||
{
|
||||
return s_geom.entryCount;
|
||||
}
|
||||
|
||||
int GetMeshEdgeBatchCount( void )
|
||||
{
|
||||
return s_geom.edgeBatchCount;
|
||||
}
|
||||
|
||||
MeshEdgeBatch GetMeshEdgeBatch( int i )
|
||||
{
|
||||
assert( i >= 0 && i < s_geom.edgeBatchCount );
|
||||
return s_geom.edgeBatches[i];
|
||||
}
|
||||
243
samples/gfx/geometry_registry.h
Normal file
243
samples/gfx/geometry_registry.h
Normal file
|
|
@ -0,0 +1,243 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Ref-counted GPU buffer store for triangle geometries (convex hulls,
|
||||
// triangle meshes, heightfields). Owned by the renderer
|
||||
// Keyed by uint32_t content hash for Box3D shapes we
|
||||
// pass through b3Hull.hash / b3MeshData.hash / b3HeightField.hash
|
||||
//
|
||||
// Lifecycle:
|
||||
//
|
||||
// handle = FindMesh(hash)
|
||||
// if (!IsMeshHandleValid(handle)) {
|
||||
// // Build CPU verts + indices, then:
|
||||
// handle = RegisterMesh(hash, verts, vc, index, ic, "label");
|
||||
// } else {
|
||||
// AddMeshReference(handle);
|
||||
// }
|
||||
// // ...later, when the owning shape is destroyed:
|
||||
// ReleaseMeshReference(handle);
|
||||
//
|
||||
// Per-frame:
|
||||
//
|
||||
// ResetFrameForMeshes(); // reset all entry counts
|
||||
// AppendMesh(handle, &transform, scale, color); // many times, across handles
|
||||
//
|
||||
// Renderer drains via GetMeshDrawSpanCount + GetMeshDrawSpan.
|
||||
//
|
||||
// All instances across all entries land in one shared GPU storage buffer.
|
||||
// Each draw call rebinds the entry's vbo/ibo and sets `inst_base` (the
|
||||
// offset into the global instance array) via ub_draw so the shader can
|
||||
// index correctly. sokol_gfx's sg_draw has no first_instance parameter,
|
||||
// so the offset is plumbed as a per-draw uniform.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "gfx/draw_overlay.h"
|
||||
#include "gfx/utility.h"
|
||||
#include "sokol_gfx.h"
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"
|
||||
{
|
||||
#endif
|
||||
|
||||
// Upper bound on transparent mesh instances drained in a frame. Shared so the
|
||||
// renderer can size its sort scratch to match the registry cap.
|
||||
#define MAX_GEOM_XP_INSTANCES_GLOBAL ( 16 * 1024 )
|
||||
|
||||
typedef struct MeshHandle
|
||||
{
|
||||
int index; // -1 means invalid
|
||||
uint32_t hash; // for cheap validation against index reuse
|
||||
} MeshHandle;
|
||||
|
||||
static inline MeshHandle InvalidMeshHandle( void )
|
||||
{
|
||||
MeshHandle h = { -1, 0u };
|
||||
return h;
|
||||
}
|
||||
|
||||
static inline bool IsMeshHandleValid( MeshHandle h )
|
||||
{
|
||||
return h.index >= 0;
|
||||
}
|
||||
|
||||
// Per-vertex data uploaded to the GPU.
|
||||
typedef struct MeshVertex
|
||||
{
|
||||
float position[3];
|
||||
float normal[3];
|
||||
} MeshVertex;
|
||||
|
||||
// Per-edge-endpoint data for the edge overlay. Two consecutive entries
|
||||
// per edge (the two endpoints). `flag` carries the Box3D edge classification
|
||||
// as 0.0 = concave, 1.0 = convex/face boundary, 2.0 = flat (coplanar), used
|
||||
// by the FS to pick between the concave/convex/flat color uniforms. Stored as
|
||||
// a float (not uint) so the shader struct can be a flat vec4, sidesteps
|
||||
// std430 vec3+uint padding ambiguity across GLSL/HLSL/MSL cross-compilers.
|
||||
typedef struct EdgeVertex
|
||||
{
|
||||
float position[3];
|
||||
float flag;
|
||||
} EdgeVertex;
|
||||
|
||||
// One draw span returned by the registry to the renderer. Spans are
|
||||
// produced in registry-entry order. The renderer iterates and issues one
|
||||
// sg_draw per span.
|
||||
typedef struct MeshDrawSpan
|
||||
{
|
||||
sg_buffer vbo;
|
||||
sg_buffer ibo;
|
||||
int indexCount;
|
||||
int firstInstance;
|
||||
int instanceCount;
|
||||
} MeshDrawSpan;
|
||||
|
||||
// Shape kind tag carried by a registry entry
|
||||
typedef enum MeshKind
|
||||
{
|
||||
MESH_KIND_UNKNOWN = 0,
|
||||
MESH_KIND_HULL,
|
||||
MESH_KIND_MESH,
|
||||
MESH_KIND_HEIGHTFIELD,
|
||||
} MeshKind;
|
||||
|
||||
// Per-entry edge-draw batch produced by UploadMeshInstances. One batch
|
||||
// per (entry x arena) with non-empty instance count and registered edges:
|
||||
// up to two batches per entry (opaque + transparent). `firstInstance`
|
||||
// indexes the opaque buffer when `isXp == false`, the xp buffer otherwise,
|
||||
// the edge pass picks the matching storage view via
|
||||
// GetMeshInstanceView / GetTransparentMeshInstanceView.
|
||||
typedef struct MeshEdgeBatch
|
||||
{
|
||||
MeshKind kind;
|
||||
sg_view edgeStorageView;
|
||||
int edgeCount;
|
||||
int firstInstance;
|
||||
int instanceCount;
|
||||
bool isTransparent;
|
||||
} MeshEdgeBatch;
|
||||
|
||||
// One transparent geom instance, ready to feed into the back-to-front
|
||||
// sort and a per-instance draw. `firstInstance` indexes the shared
|
||||
// transparent geom buffer (bound via GetTransparentMeshInstanceView). `origin` is
|
||||
// the world-space position of the instance, recovered from xform_row*.w.
|
||||
// The renderer uses it as the back-to-front sort key. `shadowCast` is 1.0
|
||||
// when SHADOW_FULL, 0.0 otherwise (packed from the instance's material.z
|
||||
// so the renderer doesn't have to repeat the unpack).
|
||||
typedef struct MeshXpInstance
|
||||
{
|
||||
sg_buffer vbo;
|
||||
sg_buffer ibo;
|
||||
int indexCount;
|
||||
int firstInstance;
|
||||
b3Vec3 origin;
|
||||
float shadowCast;
|
||||
} MeshXpInstance;
|
||||
|
||||
void CreateMeshRegistry( void );
|
||||
void DestroyMeshRegistry( void );
|
||||
|
||||
MeshHandle FindMesh( uint32_t hash );
|
||||
|
||||
MeshHandle RegisterMesh( uint32_t hash, const MeshVertex* vertices, int vertexCount, const uint32_t* indices,
|
||||
int indexCount, const char* debugLabel );
|
||||
|
||||
// Optional: register an edge list for a geometry already registered via
|
||||
// RegisterMesh. Must be called at most once per registration (i.e. between
|
||||
// RegisterMesh and the matching ReleaseMeshReference that drops refCount to 0).
|
||||
// `edges` points to `2 * edgeCount` EdgeVertex entries (two endpoints per
|
||||
// edge, consecutive). Storage-buffer-backed and immutable on the GPU. Caller
|
||||
// is free to free the input array after this returns. Safe no-op if `h` is
|
||||
// invalid.
|
||||
void RegisterMeshEdges( MeshHandle h, const EdgeVertex* edges, int edgeCount, const char* debugLabel );
|
||||
|
||||
// Edge data queries used by the edge overlay pass.
|
||||
bool HasEdges( MeshHandle h );
|
||||
int GetEdgeCount( MeshHandle h );
|
||||
sg_view GetEdgeStorageView( MeshHandle h );
|
||||
|
||||
// Shape-kind tag, see MeshKind enum above. Safe no-op on invalid handle.
|
||||
void SetMeshKind( MeshHandle h, MeshKind kind );
|
||||
MeshKind GetMeshKind( MeshHandle h );
|
||||
|
||||
// Direct GPU buffer accessor, used by passes that need to draw a single
|
||||
// registered geometry by handle (e.g. highlight mask issues one draw
|
||||
// per selected hull, bypassing the per-frame instance arenas). Writes
|
||||
// (vbo, ibo, indexCount) into *out and returns true. Returns false +
|
||||
// leaves *out untouched if the handle is invalid.
|
||||
typedef struct MeshBuffers
|
||||
{
|
||||
sg_buffer vbo;
|
||||
sg_buffer ibo;
|
||||
int indexCount;
|
||||
} MeshBuffers;
|
||||
|
||||
bool GetMeshBuffers( MeshHandle h, MeshBuffers* out );
|
||||
|
||||
void AddMeshReference( MeshHandle h );
|
||||
void ReleaseMeshReference( MeshHandle h );
|
||||
|
||||
void ResetFrameForMeshes( void );
|
||||
|
||||
// Material modes packed into the instance buffer's material.z slot. The
|
||||
// fragment shader branches on this to either feed baseColor straight into
|
||||
// the BRDF or run a procedural-grid shader first (used for ground planes
|
||||
// tagged via the Box3D adapter).
|
||||
typedef enum MeshMaterialMode
|
||||
{
|
||||
MESH_MATERIAL_MODE_SOLID = 0,
|
||||
MESH_MATERIAL_MODE_GROUND_GRID = 1,
|
||||
} MeshMaterialMode;
|
||||
|
||||
void AppendMesh( MeshHandle h, b3Transform transform, b3Vec3 scale, Vec4 baseColor, float metallic, float roughness,
|
||||
MeshMaterialMode materialMode, float gridCellSize, TransparentShadowCast shadowCast );
|
||||
|
||||
// Pack per-entry instances into the global GPU buffer. Called once per
|
||||
// frame by the renderer before draw. Returns the total instance count
|
||||
// (opaque + transparent combined, transparent instances live in a
|
||||
// separate GPU buffer accessed through GetTransparentMeshInstanceView).
|
||||
int UploadMeshInstances( void );
|
||||
|
||||
int GetMeshDrawSpanCount( void );
|
||||
|
||||
MeshDrawSpan GetMeshDrawSpan( int i );
|
||||
|
||||
// Mirror spans carry negative-determinant (mirror-scaled) instances. Their
|
||||
// flipped winding needs the opposite cull face, so the renderer draws them
|
||||
// with a front-cull pipeline after the back-cull pass over the normal spans.
|
||||
// Usually empty, only a few sample scenes mirror a mesh.
|
||||
int GetMeshMirrorDrawSpanCount( void );
|
||||
|
||||
MeshDrawSpan GetMeshMirrorDrawSpan( int i );
|
||||
|
||||
// Bound to the geom pipeline by the renderer. Exposed so renderer.c can
|
||||
// bind a single view across all draws without recreating it per span.
|
||||
sg_view GetMeshInstanceView( void );
|
||||
|
||||
// Transparent geom queries. Returns the count of transparent geom
|
||||
// instances submitted this frame (after UploadMeshInstances) and the
|
||||
// per-instance metadata for each. The renderer mixes these with cube/
|
||||
// sphere/capsule transparent instances in its back-to-front sort, then
|
||||
// issues one sg_draw per entry using inst_base = firstInstance.
|
||||
int GetTransparentMeshInstanceCount( void );
|
||||
MeshXpInstance GetTransparentMeshInstance( int i );
|
||||
sg_view GetTransparentMeshInstanceView( void );
|
||||
|
||||
// Per-entry edge-draw batches built during UploadMeshInstances.
|
||||
// Up to two batches per entry (opaque + xp) when both arenas are non-empty
|
||||
// and the entry has edges registered. The edge pass iterates these in
|
||||
// arbitrary order, depth-test handles occlusion.
|
||||
int GetMeshEdgeBatchCount( void );
|
||||
MeshEdgeBatch GetMeshEdgeBatch( int i );
|
||||
|
||||
// Total registry entry count for diagnostics.
|
||||
int GetMeshEntryCount( void );
|
||||
|
||||
#ifdef __cplusplus
|
||||
} // extern "C"
|
||||
#endif
|
||||
890
samples/gfx/gtao.c
Normal file
890
samples/gfx/gtao.c
Normal file
|
|
@ -0,0 +1,890 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "gfx/gtao.h"
|
||||
|
||||
#include "gtao_denoise.glsl.h"
|
||||
#include "gtao_main_pass.glsl.h"
|
||||
#include "gtao_prefilter_depth.glsl.h"
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
// Owned targets for the GTAO pipeline:
|
||||
//
|
||||
// * Depth pre-pass D32F image (`prepassDepthImage`), rasterizer /
|
||||
// early-Z attachment, never sampled as a texture but re-attached as
|
||||
// the depth_stencil of the transparent pass (LOAD + GREATER test,
|
||||
// no depth write). Lives alongside the R32F color attachment to give
|
||||
// the rasterizer a proper depth buffer for closest-fragment selection,
|
||||
// the GTAO trace itself reads linear view-z out of the color
|
||||
// attachment, not this.
|
||||
// * Linear-depth R32F image (`linearDepthImage`), color attachment +
|
||||
// sample. Filled by the depth_only_* pipelines with positive linear
|
||||
// view-space depth. Source for the prefiltered-depth chain and
|
||||
// MainPass's in-place normal reconstruction taps (which read raw
|
||||
// depth, not the prefiltered chain, mirrors MainPass.esf:122).
|
||||
// * Prefiltered-depth R32F mip chain (`prefilterDepthImage`, 5 mips,
|
||||
// storage_image), populated by `PrefilterDepth`. Each mip has
|
||||
// its own writeonly storage_image view, a single full-chain texture
|
||||
// view feeds the MainPass trace samples (textureLod at a computed
|
||||
// mip per sample).
|
||||
// * Edges R32F image (`edgesImage`, storage_image), written by
|
||||
// MainPass alongside the noisy AO. Carries 4 packed edge gradients
|
||||
// per pixel consumed by every Denoise dispatch.
|
||||
// * Two ping-pong R32F AO targets (`noisy0Image`, `noisy1Image`,
|
||||
// storage_image + texture). MainPass writes the raw noisy term into
|
||||
// `noisy0`. Denoise pass 0 reads `noisy0`, writes `noisy1`. Denoise
|
||||
// pass 1 reads `noisy1`, writes `noisy0`. The final Denoise
|
||||
// dispatch reads `noisy0` and writes `result` with the
|
||||
// XE_GTAO_OCCLUSION_TERM_SCALE (1.5) rescale applied on store.
|
||||
// * `result` R32F image, full-res AO output sampled by lit shaders.
|
||||
// Has BOTH color_attachment (for the clear-to-1.0 fallback path) and
|
||||
// storage_image (so the Denoise final apply can imageStore into it).
|
||||
//
|
||||
// All targets are single-sample. MSAA-resolved depth would be per-pixel
|
||||
// filtered and break the GTAO trace's expectation of analytic surface
|
||||
// samples at each pixel, re-rendering the depth pre-pass single-sample
|
||||
// costs one extra vertex pass which is acceptable for a debug renderer.
|
||||
|
||||
#define GTAO_PREFILTER_MIP_COUNT 5
|
||||
|
||||
static struct
|
||||
{
|
||||
int width;
|
||||
int height;
|
||||
|
||||
sg_image prepassDepthImage;
|
||||
sg_view prepassDepthAttachView;
|
||||
|
||||
sg_image linearDepthImage;
|
||||
sg_view linearDepthAttachView;
|
||||
sg_view linearDepthSampleView;
|
||||
|
||||
sg_image prefilterDepthImage; // R32F, 5 mips, storage_image
|
||||
sg_view prefilterMipStorageView[GTAO_PREFILTER_MIP_COUNT];
|
||||
sg_view prefilterChainSampleView;
|
||||
|
||||
sg_image edgesImage; // R32F, storage_image
|
||||
sg_view edgesStorageView;
|
||||
sg_view edgesSampleView;
|
||||
|
||||
// Ping-pong noisy AO targets. R32F + storage_image + texture.
|
||||
// MainPass writes noisy0 directly. Denoise then bounces noisy0 <-> noisy1
|
||||
// and the final apply lands in result.
|
||||
sg_image noisy0Image;
|
||||
sg_view noisy0StorageView;
|
||||
sg_view noisy0SampleView;
|
||||
sg_image noisy1Image;
|
||||
sg_view noisy1StorageView;
|
||||
sg_view noisy1SampleView;
|
||||
|
||||
sg_image resultImage; // R32F
|
||||
sg_view resultAttachView; // color attach (clear-to-1 fallback)
|
||||
sg_view resultStorageView; // storage_image (Denoise final apply writes via imageStore)
|
||||
sg_view resultSampleView;
|
||||
|
||||
sg_sampler linearSampler; // linear-filter, clamp, lit shaders sample tex_ao with this
|
||||
sg_sampler pointSampler; // point-clamp, bound by every GTAO compute (texelFetch doesn't filter, textureLod on the prefilter
|
||||
// chain needs point so neighbouring mip texels don't bilerp)
|
||||
|
||||
sg_shader prefilterShader;
|
||||
sg_pipeline prefilterPipeline;
|
||||
|
||||
sg_shader mainPassShader;
|
||||
sg_pipeline mainPassPipeline;
|
||||
|
||||
sg_shader denoiseShader;
|
||||
sg_pipeline denoisePipeline;
|
||||
|
||||
GtaoTraceParams params; // XeGTAO trace knobs
|
||||
} s_gtao;
|
||||
|
||||
// XeGTAO continuous-knob defaults from XeGTAO_Types.esh:107-114, mirrored
|
||||
// here so a "reset" button in the panel can restore them without
|
||||
// recompiling. Quality defaults to High (3 x 3 slices/steps), not XeGTAO's
|
||||
// Ultra (9 x 3), High is the ship default. Ultra is one combo step away.
|
||||
static const GtaoTraceParams k_gtao_default_params = {
|
||||
.radius = 0.5f,
|
||||
.falloff = 0.615f,
|
||||
.radiusMul = 1.457f,
|
||||
.finalValuePow = 2.2f,
|
||||
.denoiseBlurBeta = 1.2f,
|
||||
.sampleDistPow = 2.0f,
|
||||
.thinOcclComp = 0.0f,
|
||||
.depthMipSampOffset = 3.30f,
|
||||
.quality = AO_QUALITY_HIGH,
|
||||
.denoisePassCount = 3,
|
||||
};
|
||||
|
||||
// Slice and step counts per quality tier. Internal, the public knob is quality.
|
||||
static void GtaoQualityToCounts( AmbientOcclusionQuality quality, int* sliceCount, int* stepsPerSlice )
|
||||
{
|
||||
switch ( quality )
|
||||
{
|
||||
case AO_QUALITY_MEDIUM:
|
||||
*sliceCount = 2;
|
||||
*stepsPerSlice = 2;
|
||||
break;
|
||||
case AO_QUALITY_ULTRA:
|
||||
*sliceCount = 9;
|
||||
*stepsPerSlice = 3;
|
||||
break;
|
||||
case AO_QUALITY_HIGH:
|
||||
default:
|
||||
*sliceCount = 3;
|
||||
*stepsPerSlice = 3;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void InitAmbientOcclusion( void )
|
||||
{
|
||||
s_gtao.width = 0;
|
||||
s_gtao.height = 0;
|
||||
s_gtao.params = k_gtao_default_params;
|
||||
|
||||
sg_sampler_desc linDesc = { 0 };
|
||||
linDesc.min_filter = SG_FILTER_LINEAR;
|
||||
linDesc.mag_filter = SG_FILTER_LINEAR;
|
||||
linDesc.mipmap_filter = SG_FILTER_NEAREST;
|
||||
linDesc.wrap_u = SG_WRAP_CLAMP_TO_EDGE;
|
||||
linDesc.wrap_v = SG_WRAP_CLAMP_TO_EDGE;
|
||||
linDesc.wrap_w = SG_WRAP_CLAMP_TO_EDGE;
|
||||
linDesc.label = "gtao_linear_sampler";
|
||||
s_gtao.linearSampler = sg_make_sampler( &linDesc );
|
||||
|
||||
// Point-clamp sampler bound by the prefilter compute. The shader
|
||||
// only ever reads via texelFetch (which ignores the sampler's
|
||||
// filter mode), but sokol-gfx requires a sampler binding for every
|
||||
// texture binding, point/clamp is the safe default.
|
||||
sg_sampler_desc pointDesc = { 0 };
|
||||
pointDesc.min_filter = SG_FILTER_NEAREST;
|
||||
pointDesc.mag_filter = SG_FILTER_NEAREST;
|
||||
pointDesc.mipmap_filter = SG_FILTER_NEAREST;
|
||||
pointDesc.wrap_u = SG_WRAP_CLAMP_TO_EDGE;
|
||||
pointDesc.wrap_v = SG_WRAP_CLAMP_TO_EDGE;
|
||||
pointDesc.wrap_w = SG_WRAP_CLAMP_TO_EDGE;
|
||||
pointDesc.label = "gtao_point_sampler";
|
||||
s_gtao.pointSampler = sg_make_sampler( &pointDesc );
|
||||
|
||||
// PrefilterDepth compute pipeline. Built once at init, its bindings
|
||||
// are all view-driven and resize without needing a new shader/pipeline.
|
||||
s_gtao.prefilterShader = sg_make_shader( gtao_prefilter_depth_prog_shader_desc( sg_query_backend() ) );
|
||||
|
||||
sg_pipeline_desc ppdesc = { 0 };
|
||||
ppdesc.compute = true;
|
||||
ppdesc.shader = s_gtao.prefilterShader;
|
||||
ppdesc.label = "gtao_prefilter_pipeline";
|
||||
s_gtao.prefilterPipeline = sg_make_pipeline( &ppdesc );
|
||||
|
||||
// MainPass compute pipeline. Same view-driven bindings idiom.
|
||||
s_gtao.mainPassShader = sg_make_shader( gtao_main_pass_prog_shader_desc( sg_query_backend() ) );
|
||||
|
||||
sg_pipeline_desc mpdesc = { 0 };
|
||||
mpdesc.compute = true;
|
||||
mpdesc.shader = s_gtao.mainPassShader;
|
||||
mpdesc.label = "gtao_main_pass_pipeline";
|
||||
s_gtao.mainPassPipeline = sg_make_pipeline( &mpdesc );
|
||||
|
||||
// Denoise compute pipeline. One pipeline drives all three
|
||||
// dispatches, the per-dispatch finalApply flag is delivered through
|
||||
// the dedicated ub_denoise UBO (binding=1). Source/destination images
|
||||
// are swapped between dispatches via sg_apply_bindings.
|
||||
s_gtao.denoiseShader = sg_make_shader( gtao_denoise_prog_shader_desc( sg_query_backend() ) );
|
||||
|
||||
sg_pipeline_desc dndesc = { 0 };
|
||||
dndesc.compute = true;
|
||||
dndesc.shader = s_gtao.denoiseShader;
|
||||
dndesc.label = "gtao_denoise_pipeline";
|
||||
s_gtao.denoisePipeline = sg_make_pipeline( &dndesc );
|
||||
}
|
||||
|
||||
static void destroyTargets( void )
|
||||
{
|
||||
if ( s_gtao.resultSampleView.id )
|
||||
{
|
||||
sg_destroy_view( s_gtao.resultSampleView );
|
||||
s_gtao.resultSampleView.id = 0;
|
||||
}
|
||||
if ( s_gtao.resultStorageView.id )
|
||||
{
|
||||
sg_destroy_view( s_gtao.resultStorageView );
|
||||
s_gtao.resultStorageView.id = 0;
|
||||
}
|
||||
if ( s_gtao.resultAttachView.id )
|
||||
{
|
||||
sg_destroy_view( s_gtao.resultAttachView );
|
||||
s_gtao.resultAttachView.id = 0;
|
||||
}
|
||||
if ( s_gtao.resultImage.id )
|
||||
{
|
||||
sg_destroy_image( s_gtao.resultImage );
|
||||
s_gtao.resultImage.id = 0;
|
||||
}
|
||||
if ( s_gtao.noisy1SampleView.id )
|
||||
{
|
||||
sg_destroy_view( s_gtao.noisy1SampleView );
|
||||
s_gtao.noisy1SampleView.id = 0;
|
||||
}
|
||||
if ( s_gtao.noisy1StorageView.id )
|
||||
{
|
||||
sg_destroy_view( s_gtao.noisy1StorageView );
|
||||
s_gtao.noisy1StorageView.id = 0;
|
||||
}
|
||||
if ( s_gtao.noisy1Image.id )
|
||||
{
|
||||
sg_destroy_image( s_gtao.noisy1Image );
|
||||
s_gtao.noisy1Image.id = 0;
|
||||
}
|
||||
if ( s_gtao.noisy0SampleView.id )
|
||||
{
|
||||
sg_destroy_view( s_gtao.noisy0SampleView );
|
||||
s_gtao.noisy0SampleView.id = 0;
|
||||
}
|
||||
if ( s_gtao.noisy0StorageView.id )
|
||||
{
|
||||
sg_destroy_view( s_gtao.noisy0StorageView );
|
||||
s_gtao.noisy0StorageView.id = 0;
|
||||
}
|
||||
if ( s_gtao.noisy0Image.id )
|
||||
{
|
||||
sg_destroy_image( s_gtao.noisy0Image );
|
||||
s_gtao.noisy0Image.id = 0;
|
||||
}
|
||||
if ( s_gtao.edgesSampleView.id )
|
||||
{
|
||||
sg_destroy_view( s_gtao.edgesSampleView );
|
||||
s_gtao.edgesSampleView.id = 0;
|
||||
}
|
||||
if ( s_gtao.edgesStorageView.id )
|
||||
{
|
||||
sg_destroy_view( s_gtao.edgesStorageView );
|
||||
s_gtao.edgesStorageView.id = 0;
|
||||
}
|
||||
if ( s_gtao.edgesImage.id )
|
||||
{
|
||||
sg_destroy_image( s_gtao.edgesImage );
|
||||
s_gtao.edgesImage.id = 0;
|
||||
}
|
||||
if ( s_gtao.prefilterChainSampleView.id )
|
||||
{
|
||||
sg_destroy_view( s_gtao.prefilterChainSampleView );
|
||||
s_gtao.prefilterChainSampleView.id = 0;
|
||||
}
|
||||
for ( int i = 0; i < GTAO_PREFILTER_MIP_COUNT; ++i )
|
||||
{
|
||||
if ( s_gtao.prefilterMipStorageView[i].id )
|
||||
{
|
||||
sg_destroy_view( s_gtao.prefilterMipStorageView[i] );
|
||||
s_gtao.prefilterMipStorageView[i].id = 0;
|
||||
}
|
||||
}
|
||||
if ( s_gtao.prefilterDepthImage.id )
|
||||
{
|
||||
sg_destroy_image( s_gtao.prefilterDepthImage );
|
||||
s_gtao.prefilterDepthImage.id = 0;
|
||||
}
|
||||
if ( s_gtao.linearDepthSampleView.id )
|
||||
{
|
||||
sg_destroy_view( s_gtao.linearDepthSampleView );
|
||||
s_gtao.linearDepthSampleView.id = 0;
|
||||
}
|
||||
if ( s_gtao.linearDepthAttachView.id )
|
||||
{
|
||||
sg_destroy_view( s_gtao.linearDepthAttachView );
|
||||
s_gtao.linearDepthAttachView.id = 0;
|
||||
}
|
||||
if ( s_gtao.linearDepthImage.id )
|
||||
{
|
||||
sg_destroy_image( s_gtao.linearDepthImage );
|
||||
s_gtao.linearDepthImage.id = 0;
|
||||
}
|
||||
if ( s_gtao.prepassDepthAttachView.id )
|
||||
{
|
||||
sg_destroy_view( s_gtao.prepassDepthAttachView );
|
||||
s_gtao.prepassDepthAttachView.id = 0;
|
||||
}
|
||||
if ( s_gtao.prepassDepthImage.id )
|
||||
{
|
||||
sg_destroy_image( s_gtao.prepassDepthImage );
|
||||
s_gtao.prepassDepthImage.id = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void ShutdownAmbientOcclusion( void )
|
||||
{
|
||||
destroyTargets();
|
||||
if ( s_gtao.denoisePipeline.id )
|
||||
{
|
||||
sg_destroy_pipeline( s_gtao.denoisePipeline );
|
||||
s_gtao.denoisePipeline.id = 0;
|
||||
}
|
||||
if ( s_gtao.denoiseShader.id )
|
||||
{
|
||||
sg_destroy_shader( s_gtao.denoiseShader );
|
||||
s_gtao.denoiseShader.id = 0;
|
||||
}
|
||||
if ( s_gtao.mainPassPipeline.id )
|
||||
{
|
||||
sg_destroy_pipeline( s_gtao.mainPassPipeline );
|
||||
s_gtao.mainPassPipeline.id = 0;
|
||||
}
|
||||
if ( s_gtao.mainPassShader.id )
|
||||
{
|
||||
sg_destroy_shader( s_gtao.mainPassShader );
|
||||
s_gtao.mainPassShader.id = 0;
|
||||
}
|
||||
if ( s_gtao.prefilterPipeline.id )
|
||||
{
|
||||
sg_destroy_pipeline( s_gtao.prefilterPipeline );
|
||||
s_gtao.prefilterPipeline.id = 0;
|
||||
}
|
||||
if ( s_gtao.prefilterShader.id )
|
||||
{
|
||||
sg_destroy_shader( s_gtao.prefilterShader );
|
||||
s_gtao.prefilterShader.id = 0;
|
||||
}
|
||||
if ( s_gtao.pointSampler.id )
|
||||
{
|
||||
sg_destroy_sampler( s_gtao.pointSampler );
|
||||
s_gtao.pointSampler.id = 0;
|
||||
}
|
||||
if ( s_gtao.linearSampler.id )
|
||||
{
|
||||
sg_destroy_sampler( s_gtao.linearSampler );
|
||||
s_gtao.linearSampler.id = 0;
|
||||
}
|
||||
s_gtao.width = 0;
|
||||
s_gtao.height = 0;
|
||||
}
|
||||
|
||||
void ResizeGTAO( int width, int height )
|
||||
{
|
||||
if ( width <= 0 || height <= 0 )
|
||||
{
|
||||
return;
|
||||
}
|
||||
if ( width == s_gtao.width && height == s_gtao.height && s_gtao.linearDepthImage.id )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
destroyTargets();
|
||||
|
||||
s_gtao.width = width;
|
||||
s_gtao.height = height;
|
||||
|
||||
// Transient D32F depth-stencil attachment (rasterizer-only)
|
||||
sg_image_desc didesc = { 0 };
|
||||
didesc.usage.depth_stencil_attachment = true;
|
||||
didesc.width = width;
|
||||
didesc.height = height;
|
||||
didesc.pixel_format = SG_PIXELFORMAT_DEPTH;
|
||||
didesc.sample_count = 1;
|
||||
didesc.label = "gtao_prepass_depth";
|
||||
s_gtao.prepassDepthImage = sg_make_image( &didesc );
|
||||
|
||||
sg_view_desc davdesc = { 0 };
|
||||
davdesc.depth_stencil_attachment.image = s_gtao.prepassDepthImage;
|
||||
davdesc.label = "gtao_prepass_depth_attach";
|
||||
s_gtao.prepassDepthAttachView = sg_make_view( &davdesc );
|
||||
|
||||
// R32F linear-depth color attachment
|
||||
sg_image_desc ldesc = { 0 };
|
||||
ldesc.usage.color_attachment = true;
|
||||
ldesc.width = width;
|
||||
ldesc.height = height;
|
||||
ldesc.pixel_format = SG_PIXELFORMAT_R32F;
|
||||
ldesc.sample_count = 1;
|
||||
ldesc.label = "gtao_linear_depth";
|
||||
s_gtao.linearDepthImage = sg_make_image( &ldesc );
|
||||
|
||||
sg_view_desc lavdesc = { 0 };
|
||||
lavdesc.color_attachment.image = s_gtao.linearDepthImage;
|
||||
lavdesc.label = "gtao_linear_depth_attach";
|
||||
s_gtao.linearDepthAttachView = sg_make_view( &lavdesc );
|
||||
|
||||
sg_view_desc lsvdesc = { 0 };
|
||||
lsvdesc.texture.image = s_gtao.linearDepthImage;
|
||||
lsvdesc.label = "gtao_linear_depth_sample";
|
||||
s_gtao.linearDepthSampleView = sg_make_view( &lsvdesc );
|
||||
|
||||
// R32F prefiltered linear-depth chain (5 mips, storage_image)
|
||||
// The chain dimensions cover only the in-bounds region: mip N is
|
||||
// `max(1, w >> N)` x `max(1, h >> N)`. The shader's per-thread early-
|
||||
// out skips writes past the viewport bound, so mips don't need
|
||||
// padding to a multiple of 16 for correctness, sokol-gfx sizes the
|
||||
// sub-mips itself from num_mipmaps.
|
||||
sg_image_desc pdesc = { 0 };
|
||||
pdesc.usage.storage_image = true;
|
||||
pdesc.width = width;
|
||||
pdesc.height = height;
|
||||
pdesc.num_mipmaps = GTAO_PREFILTER_MIP_COUNT;
|
||||
pdesc.pixel_format = SG_PIXELFORMAT_R32F;
|
||||
pdesc.sample_count = 1;
|
||||
pdesc.label = "gtao_prefilter_depth";
|
||||
s_gtao.prefilterDepthImage = sg_make_image( &pdesc );
|
||||
|
||||
for ( int i = 0; i < GTAO_PREFILTER_MIP_COUNT; ++i )
|
||||
{
|
||||
sg_view_desc msvdesc = { 0 };
|
||||
msvdesc.storage_image.image = s_gtao.prefilterDepthImage;
|
||||
msvdesc.storage_image.mip_level = i;
|
||||
msvdesc.label = "gtao_prefilter_mip_storage";
|
||||
s_gtao.prefilterMipStorageView[i] = sg_make_view( &msvdesc );
|
||||
}
|
||||
|
||||
sg_view_desc pcsvdesc = { 0 };
|
||||
pcsvdesc.texture.image = s_gtao.prefilterDepthImage;
|
||||
|
||||
// mip_levels.count == 0 means "all remaining mips" (sokol-gfx
|
||||
// convention), leaving the rest zero-initialized gives a view over
|
||||
// the full chain that MainPass can textureLod into.
|
||||
pcsvdesc.label = "gtao_prefilter_chain_sample";
|
||||
s_gtao.prefilterChainSampleView = sg_make_view( &pcsvdesc );
|
||||
|
||||
// R32F edges target
|
||||
// storage_image so MainPass can imageStore the packed edge gradients
|
||||
// per pixel, texture sample view alone is the eventual Denoise read
|
||||
// path. Allocated now even though the sample view goes
|
||||
// unused for one commit cycle. The alternative is conditioning
|
||||
// MainPass's edges output, and that's worse than the storage cost.
|
||||
//
|
||||
// Format deviation from Esoterica's R8 UNORM: sokol-shdc / SPIRV-
|
||||
// Cross only allow r32f/r32i/r32ui plus rgba/rg{32,16} variants for
|
||||
// storage_image access formats (D3D11 typed-UAV constraint). R32F
|
||||
// is the cheapest single-channel fp format that survives cross-
|
||||
// compilation, the packed-edges value range stays in [0,1] so
|
||||
// XeGTAO_UnpackEdges is unchanged.
|
||||
sg_image_desc edesc = { 0 };
|
||||
edesc.usage.storage_image = true;
|
||||
edesc.width = width;
|
||||
edesc.height = height;
|
||||
edesc.pixel_format = SG_PIXELFORMAT_R32F;
|
||||
edesc.sample_count = 1;
|
||||
edesc.label = "gtao_edges";
|
||||
s_gtao.edgesImage = sg_make_image( &edesc );
|
||||
|
||||
sg_view_desc esvdesc = { 0 };
|
||||
esvdesc.storage_image.image = s_gtao.edgesImage;
|
||||
esvdesc.label = "gtao_edges_storage";
|
||||
s_gtao.edgesStorageView = sg_make_view( &esvdesc );
|
||||
|
||||
sg_view_desc etxvdesc = { 0 };
|
||||
etxvdesc.texture.image = s_gtao.edgesImage;
|
||||
etxvdesc.label = "gtao_edges_sample";
|
||||
s_gtao.edgesSampleView = sg_make_view( &etxvdesc );
|
||||
|
||||
// R32F noisy AO ping-pong targets
|
||||
// Two textures with identical descriptors. MainPass writes noisy0,
|
||||
// the three Denoise dispatches bounce noisy0 -> noisy1 -> noisy0
|
||||
// and then noisy0 -> result. Format deviation same rationale as
|
||||
// edges + result above (sokol-shdc storage_image access-format
|
||||
// restriction).
|
||||
sg_image_desc ndesc = { 0 };
|
||||
ndesc.usage.storage_image = true;
|
||||
ndesc.width = width;
|
||||
ndesc.height = height;
|
||||
ndesc.pixel_format = SG_PIXELFORMAT_R32F;
|
||||
ndesc.sample_count = 1;
|
||||
|
||||
ndesc.label = "gtao_noisy0";
|
||||
s_gtao.noisy0Image = sg_make_image( &ndesc );
|
||||
ndesc.label = "gtao_noisy1";
|
||||
s_gtao.noisy1Image = sg_make_image( &ndesc );
|
||||
|
||||
sg_view_desc n0stvdesc = { 0 };
|
||||
n0stvdesc.storage_image.image = s_gtao.noisy0Image;
|
||||
n0stvdesc.label = "gtao_noisy0_storage";
|
||||
s_gtao.noisy0StorageView = sg_make_view( &n0stvdesc );
|
||||
|
||||
sg_view_desc n0txvdesc = { 0 };
|
||||
n0txvdesc.texture.image = s_gtao.noisy0Image;
|
||||
n0txvdesc.label = "gtao_noisy0_sample";
|
||||
s_gtao.noisy0SampleView = sg_make_view( &n0txvdesc );
|
||||
|
||||
sg_view_desc n1stvdesc = { 0 };
|
||||
n1stvdesc.storage_image.image = s_gtao.noisy1Image;
|
||||
n1stvdesc.label = "gtao_noisy1_storage";
|
||||
s_gtao.noisy1StorageView = sg_make_view( &n1stvdesc );
|
||||
|
||||
sg_view_desc n1txvdesc = { 0 };
|
||||
n1txvdesc.texture.image = s_gtao.noisy1Image;
|
||||
n1txvdesc.label = "gtao_noisy1_sample";
|
||||
s_gtao.noisy1SampleView = sg_make_view( &n1txvdesc );
|
||||
|
||||
// R32F `result` AO target
|
||||
// Dual usage: color_attachment for the ClearAmbientOcclusion path
|
||||
// (sg_begin_pass with SG_LOADACTION_CLEAR), storage_image for
|
||||
// MainPass's imageStore output. sokol-gfx is OK with both flags on
|
||||
// the same image, each consumer binds via its own sg_view.
|
||||
//
|
||||
// Format deviation from Esoterica's R16F: same sokol-shdc storage_
|
||||
// image access-format restriction as `edges` above (D3D11 typed-UAV
|
||||
// constraint). R32F doubles the storage cost but is a transparent
|
||||
// drop-in for the float visibility term. Lit shaders sampling
|
||||
// tex_ao read .x as a float either way.
|
||||
sg_image_desc rdesc = { 0 };
|
||||
rdesc.usage.color_attachment = true;
|
||||
rdesc.usage.storage_image = true;
|
||||
rdesc.width = width;
|
||||
rdesc.height = height;
|
||||
rdesc.pixel_format = SG_PIXELFORMAT_R32F;
|
||||
rdesc.sample_count = 1;
|
||||
rdesc.label = "gtao_result";
|
||||
s_gtao.resultImage = sg_make_image( &rdesc );
|
||||
|
||||
sg_view_desc ravdesc = { 0 };
|
||||
ravdesc.color_attachment.image = s_gtao.resultImage;
|
||||
ravdesc.label = "gtao_result_attach";
|
||||
s_gtao.resultAttachView = sg_make_view( &ravdesc );
|
||||
|
||||
sg_view_desc rstvdesc = { 0 };
|
||||
rstvdesc.storage_image.image = s_gtao.resultImage;
|
||||
rstvdesc.label = "gtao_result_storage";
|
||||
s_gtao.resultStorageView = sg_make_view( &rstvdesc );
|
||||
|
||||
sg_view_desc rsvdesc = { 0 };
|
||||
rsvdesc.texture.image = s_gtao.resultImage;
|
||||
rsvdesc.label = "gtao_result_sample";
|
||||
s_gtao.resultSampleView = sg_make_view( &rsvdesc );
|
||||
}
|
||||
|
||||
sg_view GetLinearDepthAttachmentView( void )
|
||||
{
|
||||
return s_gtao.linearDepthAttachView;
|
||||
}
|
||||
|
||||
sg_view GetPrepassDepthAttachmentView( void )
|
||||
{
|
||||
return s_gtao.prepassDepthAttachView;
|
||||
}
|
||||
|
||||
sg_view GetLinearDepthSampleView( void )
|
||||
{
|
||||
return s_gtao.linearDepthSampleView;
|
||||
}
|
||||
|
||||
sg_view GetPrefilterDepthSampleView( void )
|
||||
{
|
||||
return s_gtao.prefilterChainSampleView;
|
||||
}
|
||||
|
||||
sg_view GetAOResultSampleView( void )
|
||||
{
|
||||
return s_gtao.resultSampleView;
|
||||
}
|
||||
|
||||
sg_sampler GetAOLinearSampler( void )
|
||||
{
|
||||
return s_gtao.linearSampler;
|
||||
}
|
||||
|
||||
void ClearAmbientOcclusion( void )
|
||||
{
|
||||
if ( !s_gtao.resultImage.id )
|
||||
{
|
||||
fprintf( stderr, "[gtao/error] ClearAmbientOcclusion called before ResizeGTAO succeeded\n" );
|
||||
return;
|
||||
}
|
||||
sg_pass pass = { 0 };
|
||||
pass.action.colors[0].load_action = SG_LOADACTION_CLEAR;
|
||||
pass.action.colors[0].clear_value.r = 1.0f;
|
||||
pass.action.colors[0].clear_value.g = 1.0f;
|
||||
pass.action.colors[0].clear_value.b = 1.0f;
|
||||
pass.action.colors[0].clear_value.a = 1.0f;
|
||||
pass.action.colors[0].store_action = SG_STOREACTION_STORE;
|
||||
pass.attachments.colors[0] = s_gtao.resultAttachView;
|
||||
sg_push_debug_group( "gtao_clear_white" );
|
||||
sg_begin_pass( &pass );
|
||||
sg_end_pass();
|
||||
sg_pop_debug_group();
|
||||
}
|
||||
|
||||
// Derived inputs that all three GTAO shaders' UBOs are projections of.
|
||||
// Computed once per dispatch from the camera + current trace params,
|
||||
// each per-shader builder picks the subset it needs.
|
||||
//
|
||||
// NoiseIndex deliberately absent, the main pass hardcodes 0 at the
|
||||
// SpatioTemporalNoise call site (no TAA). Same goes for
|
||||
// DepthUnpackConsts and CameraTanHalfFOV: our source depth is already
|
||||
// positive linear view-Z so XeGTAO_ScreenSpaceToViewSpaceDepth is the
|
||||
// identity and none of the consumed helpers ever touch them.
|
||||
typedef struct
|
||||
{
|
||||
int viewportWidth;
|
||||
int viewportHeight;
|
||||
b3Vec2 viewportPixelSize;
|
||||
b3Vec2 ndcToViewMul;
|
||||
b3Vec2 ndcToViewAdd;
|
||||
b3Vec2 ndcToViewMul_x_PixelSize;
|
||||
GtaoTraceParams params;
|
||||
} GtaoUboInputs;
|
||||
|
||||
// `proj` is column-major (Mat4 cx/cy/cz/cw), cx.x = 1/tanHalfFOVX and
|
||||
// cy.y = 1/tanHalfFOVY for a standard reverse-Z perspective matrix as
|
||||
// produced by Camera::Proj. The NDC-to-view factors are Esoterica's
|
||||
// post-fix form (no spurious double-0.5, see the plan note on Known
|
||||
// Esoterica bugs we deliberately fix).
|
||||
static GtaoUboInputs ComputeUboInputs( const Mat4* proj, int viewportWidth, int viewportHeight )
|
||||
{
|
||||
GtaoUboInputs in;
|
||||
in.viewportWidth = viewportWidth;
|
||||
in.viewportHeight = viewportHeight;
|
||||
in.viewportPixelSize = (b3Vec2){ 1.0f / (float)viewportWidth, 1.0f / (float)viewportHeight };
|
||||
|
||||
const float tanHalfFOVY = 1.0f / proj->cy.y;
|
||||
const float tanHalfFOVX = 1.0f / proj->cx.x;
|
||||
in.ndcToViewMul = (b3Vec2){ tanHalfFOVX * 2.0f, tanHalfFOVY * -2.0f };
|
||||
in.ndcToViewAdd = (b3Vec2){ tanHalfFOVX * -1.0f, tanHalfFOVY * 1.0f };
|
||||
in.ndcToViewMul_x_PixelSize = (b3Vec2){
|
||||
in.ndcToViewMul.x * in.viewportPixelSize.x,
|
||||
in.ndcToViewMul.y * in.viewportPixelSize.y,
|
||||
};
|
||||
|
||||
in.params = s_gtao.params;
|
||||
return in;
|
||||
}
|
||||
|
||||
static gtao_prefilter_depth_ub_gtao_t buildPrefilterUbo( const GtaoUboInputs* in )
|
||||
{
|
||||
gtao_prefilter_depth_ub_gtao_t c = { 0 };
|
||||
c.ViewportSize[0] = in->viewportWidth;
|
||||
c.ViewportSize[1] = in->viewportHeight;
|
||||
c.EffectRadius = in->params.radius;
|
||||
c.EffectFalloffRange = in->params.falloff;
|
||||
c.RadiusMultiplier = in->params.radiusMul;
|
||||
return c;
|
||||
}
|
||||
|
||||
static gtao_main_pass_ub_gtao_t MakeMainPassUbo( const GtaoUboInputs* in )
|
||||
{
|
||||
gtao_main_pass_ub_gtao_t c = { 0 };
|
||||
c.ViewportSize[0] = in->viewportWidth;
|
||||
c.ViewportSize[1] = in->viewportHeight;
|
||||
c.ViewportPixelSize = in->viewportPixelSize;
|
||||
c.NDCToViewMul = in->ndcToViewMul;
|
||||
c.NDCToViewAdd = in->ndcToViewAdd;
|
||||
c.NDCToViewMul_x_PixelSize = in->ndcToViewMul_x_PixelSize;
|
||||
c.EffectRadius = in->params.radius;
|
||||
c.EffectFalloffRange = in->params.falloff;
|
||||
c.RadiusMultiplier = in->params.radiusMul;
|
||||
c.FinalValuePower = in->params.finalValuePow;
|
||||
c.SampleDistributionPower = in->params.sampleDistPow;
|
||||
c.ThinOccluderCompensation = in->params.thinOcclComp;
|
||||
c.DepthMIPSamplingOffset = in->params.depthMipSampOffset;
|
||||
int sliceCount, stepsPerSlice;
|
||||
GtaoQualityToCounts( in->params.quality, &sliceCount, &stepsPerSlice );
|
||||
c.SliceCount = (float)sliceCount;
|
||||
c.StepsPerSlice = (float)stepsPerSlice;
|
||||
return c;
|
||||
}
|
||||
|
||||
static gtao_denoise_ub_gtao_t MakeDenoiseUbo( const GtaoUboInputs* in )
|
||||
{
|
||||
gtao_denoise_ub_gtao_t c = { 0 };
|
||||
c.ViewportSize[0] = in->viewportWidth;
|
||||
c.ViewportSize[1] = in->viewportHeight;
|
||||
c.DenoiseBlurBeta = in->params.denoiseBlurBeta;
|
||||
return c;
|
||||
}
|
||||
|
||||
GtaoTraceParams GetGtaoTraceParams( void )
|
||||
{
|
||||
return s_gtao.params;
|
||||
}
|
||||
void SetGtaoTraceParams( GtaoTraceParams p )
|
||||
{
|
||||
if ( p.denoisePassCount < 1 )
|
||||
{
|
||||
p.denoisePassCount = 1;
|
||||
}
|
||||
if ( p.denoisePassCount > GTAO_MAX_DENOISE_PASSES )
|
||||
{
|
||||
p.denoisePassCount = GTAO_MAX_DENOISE_PASSES;
|
||||
}
|
||||
s_gtao.params = p;
|
||||
}
|
||||
|
||||
GtaoTraceParams GetDefaultGtaoTraceParams( void )
|
||||
{
|
||||
return k_gtao_default_params;
|
||||
}
|
||||
|
||||
AmbientOcclusionQuality GetAOQualityForPixelScale( float dpiScale )
|
||||
{
|
||||
// Retina-class panels (DPI scale ~2x) render densely enough that High's
|
||||
// per-pixel sample noise stays sub-perceptual.
|
||||
const float highMinDpiScale = 2.0f;
|
||||
return ( dpiScale >= highMinDpiScale ) ? AO_QUALITY_HIGH : AO_QUALITY_ULTRA;
|
||||
}
|
||||
|
||||
void PrefilterDepth( const Mat4* proj, int viewportWidth, int viewportHeight )
|
||||
{
|
||||
if ( !s_gtao.prefilterDepthImage.id )
|
||||
{
|
||||
fprintf( stderr, "[gtao/error] PrefilterDepth called before ResizeGTAO succeeded\n" );
|
||||
return;
|
||||
}
|
||||
|
||||
GtaoUboInputs inputs = ComputeUboInputs( proj, viewportWidth, viewportHeight );
|
||||
gtao_prefilter_depth_ub_gtao_t consts = buildPrefilterUbo( &inputs );
|
||||
|
||||
sg_pass pass = { 0 };
|
||||
pass.compute = true;
|
||||
pass.label = "gtao_prefilter_depth";
|
||||
sg_push_debug_group( "gtao_prefilter_depth" );
|
||||
sg_begin_pass( &pass );
|
||||
|
||||
sg_apply_pipeline( s_gtao.prefilterPipeline );
|
||||
|
||||
sg_bindings bindings = { 0 };
|
||||
bindings.views[VIEW_gtao_prefilter_depth_out_depth0] = s_gtao.prefilterMipStorageView[0];
|
||||
bindings.views[VIEW_gtao_prefilter_depth_out_depth1] = s_gtao.prefilterMipStorageView[1];
|
||||
bindings.views[VIEW_gtao_prefilter_depth_out_depth2] = s_gtao.prefilterMipStorageView[2];
|
||||
bindings.views[VIEW_gtao_prefilter_depth_out_depth3] = s_gtao.prefilterMipStorageView[3];
|
||||
bindings.views[VIEW_gtao_prefilter_depth_out_depth4] = s_gtao.prefilterMipStorageView[4];
|
||||
bindings.views[VIEW_gtao_prefilter_depth_tex_src_depth] = s_gtao.linearDepthSampleView;
|
||||
bindings.samplers[SMP_gtao_prefilter_depth_smp_src_depth] = s_gtao.pointSampler;
|
||||
sg_apply_bindings( &bindings );
|
||||
|
||||
sg_apply_uniforms( UB_gtao_prefilter_depth_ub_gtao, &SG_RANGE( consts ) );
|
||||
|
||||
// 16x16 destination pixels per workgroup (8x8 threads x 2x2 per
|
||||
// thread). Round up so partially-covered groups still execute.
|
||||
const int groupsX = ( viewportWidth + 15 ) / 16;
|
||||
const int groupsY = ( viewportHeight + 15 ) / 16;
|
||||
sg_dispatch( groupsX, groupsY, 1 );
|
||||
|
||||
sg_end_pass();
|
||||
sg_pop_debug_group();
|
||||
}
|
||||
|
||||
void ComputeNoisyResult( const Mat4* proj, int viewportWidth, int viewportHeight )
|
||||
{
|
||||
if ( !s_gtao.noisy0Image.id || !s_gtao.edgesImage.id || !s_gtao.prefilterDepthImage.id )
|
||||
{
|
||||
fprintf( stderr, "[gtao/error] ComputeNoisyResult called before ResizeGTAO succeeded\n" );
|
||||
return;
|
||||
}
|
||||
|
||||
GtaoUboInputs inputs = ComputeUboInputs( proj, viewportWidth, viewportHeight );
|
||||
gtao_main_pass_ub_gtao_t consts = MakeMainPassUbo( &inputs );
|
||||
|
||||
sg_pass pass = { 0 };
|
||||
pass.compute = true;
|
||||
pass.label = "gtao_main_pass";
|
||||
sg_push_debug_group( "gtao_main_pass" );
|
||||
sg_begin_pass( &pass );
|
||||
|
||||
sg_apply_pipeline( s_gtao.mainPassPipeline );
|
||||
|
||||
sg_bindings bindings = { 0 };
|
||||
// MainPass writes the raw noisy term into noisy0 (the first ping-pong
|
||||
// target). The Denoise dispatches that follow chain noisy0 -> noisy1
|
||||
// -> noisy0 -> result. tex_raw_depth is the full-res linearDepth.
|
||||
bindings.views[VIEW_gtao_main_pass_out_noisy_ao] = s_gtao.noisy0StorageView;
|
||||
bindings.views[VIEW_gtao_main_pass_out_edges] = s_gtao.edgesStorageView;
|
||||
bindings.views[VIEW_gtao_main_pass_tex_raw_depth] = s_gtao.linearDepthSampleView;
|
||||
bindings.views[VIEW_gtao_main_pass_tex_prefilter_depth] = s_gtao.prefilterChainSampleView;
|
||||
bindings.samplers[SMP_gtao_main_pass_smp_point_clamp] = s_gtao.pointSampler;
|
||||
sg_apply_bindings( &bindings );
|
||||
|
||||
sg_apply_uniforms( UB_gtao_main_pass_ub_gtao, &SG_RANGE( consts ) );
|
||||
|
||||
// 8x8 numthreads, 1 destination pixel per thread. Round up so the
|
||||
// partially-covered groups still execute, the shader's
|
||||
// bounds-guarded early-out skips OOB threads.
|
||||
const int groupsX = ( viewportWidth + 7 ) / 8;
|
||||
const int groupsY = ( viewportHeight + 7 ) / 8;
|
||||
sg_dispatch( groupsX, groupsY, 1 );
|
||||
|
||||
sg_end_pass();
|
||||
sg_pop_debug_group();
|
||||
}
|
||||
|
||||
// Helper for Denoise, one of three near-identical dispatches.
|
||||
// `srcSample` is the texture view of the noisy AO source, `dstStorage`
|
||||
// is the storage_image view of the destination. `finalApply` controls
|
||||
// the XE_GTAO_OCCLUSION_TERM_SCALE rescale on store. Each dispatch
|
||||
// opens its own compute pass so sokol can insert the
|
||||
// storage_image -> sampled-texture barrier between adjacent passes.
|
||||
static void runDenoiseDispatch( const gtao_denoise_ub_gtao_t* consts, sg_view srcSample, sg_view dstStorage, bool finalApply,
|
||||
const char* label )
|
||||
{
|
||||
sg_pass pass = { 0 };
|
||||
pass.compute = true;
|
||||
pass.label = label;
|
||||
sg_push_debug_group( label );
|
||||
sg_begin_pass( &pass );
|
||||
|
||||
sg_apply_pipeline( s_gtao.denoisePipeline );
|
||||
|
||||
sg_bindings bindings = { 0 };
|
||||
bindings.views[VIEW_gtao_denoise_out_ao] = dstStorage;
|
||||
bindings.views[VIEW_gtao_denoise_tex_edges] = s_gtao.edgesSampleView;
|
||||
bindings.views[VIEW_gtao_denoise_tex_noisy_ao] = srcSample;
|
||||
bindings.samplers[SMP_gtao_denoise_smp_point_clamp] = s_gtao.pointSampler;
|
||||
sg_apply_bindings( &bindings );
|
||||
|
||||
sg_apply_uniforms( UB_gtao_denoise_ub_gtao, &SG_RANGE( *consts ) );
|
||||
|
||||
gtao_denoise_ub_denoise_t apply = { finalApply ? 1 : 0, 0, 0, 0 };
|
||||
sg_apply_uniforms( UB_gtao_denoise_ub_denoise, &SG_RANGE( apply ) );
|
||||
|
||||
// 8x8 numthreads, 2 horizontal pixels per thread -> 16x8 destination
|
||||
// pixels per workgroup. Deviates from Esoterica's (W+7)/8 dispatch
|
||||
// sizing (which over-covers by 2x, the surplus threads write OOB,
|
||||
// silent no-op in D3D11/Vulkan/Metal compute). The visible output
|
||||
// is the same.
|
||||
const int groupsX = ( s_gtao.width + 15 ) / 16;
|
||||
const int groupsY = ( s_gtao.height + 7 ) / 8;
|
||||
sg_dispatch( groupsX, groupsY, 1 );
|
||||
|
||||
sg_end_pass();
|
||||
sg_pop_debug_group();
|
||||
}
|
||||
|
||||
void Denoise( const Mat4* proj, int viewportWidth, int viewportHeight )
|
||||
{
|
||||
if ( !s_gtao.noisy0Image.id || !s_gtao.noisy1Image.id || !s_gtao.resultImage.id || !s_gtao.edgesImage.id )
|
||||
{
|
||||
fprintf( stderr, "[gtao/error] Denoise called before ResizeGTAO succeeded\n" );
|
||||
return;
|
||||
}
|
||||
|
||||
GtaoUboInputs inputs = ComputeUboInputs( proj, viewportWidth, viewportHeight );
|
||||
gtao_denoise_ub_gtao_t consts = MakeDenoiseUbo( &inputs );
|
||||
|
||||
int passCount = s_gtao.params.denoisePassCount;
|
||||
if ( passCount < 1 )
|
||||
{
|
||||
passCount = 1;
|
||||
}
|
||||
if ( passCount > GTAO_MAX_DENOISE_PASSES )
|
||||
{
|
||||
passCount = GTAO_MAX_DENOISE_PASSES;
|
||||
}
|
||||
|
||||
static const char* k_intermediateLabels[GTAO_MAX_DENOISE_PASSES] = {
|
||||
"gtao_denoise_pass0", "gtao_denoise_pass1", "gtao_denoise_pass2",
|
||||
"gtao_denoise_pass3", "gtao_denoise_pass4",
|
||||
};
|
||||
|
||||
sg_view src = s_gtao.noisy0SampleView;
|
||||
sg_view dst = s_gtao.noisy1StorageView;
|
||||
sg_view srcAlt = s_gtao.noisy1SampleView;
|
||||
sg_view dstAlt = s_gtao.noisy0StorageView;
|
||||
|
||||
for ( int i = 0; i < passCount - 1; ++i )
|
||||
{
|
||||
runDenoiseDispatch( &consts, src, dst, false, k_intermediateLabels[i] );
|
||||
sg_view tmpS = src;
|
||||
src = srcAlt;
|
||||
srcAlt = tmpS;
|
||||
sg_view tmpD = dst;
|
||||
dst = dstAlt;
|
||||
dstAlt = tmpD;
|
||||
}
|
||||
runDenoiseDispatch( &consts, src, s_gtao.resultStorageView, true, "gtao_denoise_final" );
|
||||
}
|
||||
164
samples/gfx/gtao.h
Normal file
164
samples/gfx/gtao.h
Normal file
|
|
@ -0,0 +1,164 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// GTAO (ground truth ambient occlusion):
|
||||
// * A full-res depth-only pre-pass color attachment carrying positive
|
||||
// linear view-space depth (R32F). Shapes rasterize their analytic
|
||||
// surface depth into it, the GTAO compute pipeline samples this as
|
||||
// the source for its prefiltered depth chain and for the MainPass
|
||||
// normal reconstruction taps.
|
||||
// * A D32F depth-stencil attachment that runs alongside the R32F color
|
||||
// attachment for early-Z and correct closest-fragment selection. Never
|
||||
// sampled, without it, overlapping primitives produce "whoever drew
|
||||
// last wins" in the R32F color, which is wrong. Also re-attached as
|
||||
// the depth_stencil of the transparent pass (LOAD + GREATER, no
|
||||
// depth write).
|
||||
// * A 5-mip R32F prefiltered linear-depth chain populated by a compute
|
||||
// dispatch over the depth pre-pass. Mip 0 is a verbatim copy of the
|
||||
// source, mips 1-4 use the XeGTAO depth-MIP filter (weighted average
|
||||
// that biases toward the closer of each 2x2 footprint). Consumed by
|
||||
// MainPass for the trace samples.
|
||||
// * An R32F `edges` texture written by MainPass alongside the noisy AO
|
||||
// term. Encodes 4 packed edge gradients per pixel consumed by the
|
||||
// Denoise step. R32F (not Esoterica's R8 UNORM) because sokol-shdc /
|
||||
// SPIRV-Cross only allows r32f / r32i / r32ui plus rgba/rg{32,16}
|
||||
// variants as storage_image access formats.
|
||||
// * Two R32F ping-pong AO targets `noisy0` / `noisy1`. MainPass writes
|
||||
// the raw noisy term into `noisy0`. Denoise pass 0 reads `noisy0`,
|
||||
// writes `noisy1`. Denoise pass 1 reads `noisy1`, writes `noisy0`.
|
||||
// Denoise final pass reads `noisy0` and writes `result` with the
|
||||
// XE_GTAO_OCCLUSION_TERM_SCALE rescale.
|
||||
// * A full-res R32F `result` AO texture sampled by lit shape shaders
|
||||
// via `tex_ao`. Cleared to 1.0 when GTAO is disabled at runtime,
|
||||
// written by Denoise final apply.
|
||||
//
|
||||
// Sizing: targets follow the main pass's width/height. ResizeGTAO is
|
||||
// called once per frame with the swapchain or offscreen attachment size,
|
||||
// reallocates only on actual changes.
|
||||
|
||||
// Must of the code and shaders for XeGTAO are ported from Esoterica Engine
|
||||
// https://github.com/BobbyAnguelov/Esoterica
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "gfx/utility.h"
|
||||
#include "sokol_gfx.h"
|
||||
|
||||
#include <stdbool.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"
|
||||
{
|
||||
#endif
|
||||
|
||||
void InitAmbientOcclusion( void );
|
||||
void ShutdownAmbientOcclusion( void );
|
||||
|
||||
// Selects the slice count and steps-per-slice
|
||||
typedef enum AmbientOcclusionQuality
|
||||
{
|
||||
// 2 slices and 2 steps
|
||||
AO_QUALITY_MEDIUM = 0,
|
||||
|
||||
// 3 slices and 3 steps
|
||||
AO_QUALITY_HIGH = 1,
|
||||
|
||||
// 9 slices and 3 steps
|
||||
AO_QUALITY_ULTRA = 2,
|
||||
} AmbientOcclusionQuality;
|
||||
|
||||
// 3 to 4 is the sweet spot
|
||||
#define GTAO_MAX_DENOISE_PASSES 5
|
||||
|
||||
typedef struct GtaoTraceParams
|
||||
{
|
||||
float radius; // EffectRadius, world-space sample radius
|
||||
float falloff; // EffectFalloffRange, fraction of radius over which the weight tapers
|
||||
float radiusMul; // RadiusMultiplier, per-MIP scale
|
||||
float finalValuePow; // FinalValuePower, non-linear contrast on the final term
|
||||
float denoiseBlurBeta; // DenoiseBlurBeta, bilateral blur strength
|
||||
float sampleDistPow; // SampleDistributionPower, exponent on the slice-sampling distribution
|
||||
float thinOcclComp; // ThinOccluderCompensation, extra weight for thin features
|
||||
float depthMipSampOffset; // DepthMIPSamplingOffset, bias on the prefilter MIP selection
|
||||
AmbientOcclusionQuality quality; // Trace quality tier, picks the slice and step counts internally
|
||||
int denoisePassCount; // Total denoise dispatches, >=1 (final apply), clamped to GTAO_MAX_DENOISE_PASSES
|
||||
} GtaoTraceParams;
|
||||
|
||||
GtaoTraceParams GetGtaoTraceParams( void );
|
||||
void SetGtaoTraceParams( GtaoTraceParams p );
|
||||
GtaoTraceParams GetDefaultGtaoTraceParams( void );
|
||||
|
||||
AmbientOcclusionQuality GetAOQualityForPixelScale( float dpiScale );
|
||||
|
||||
// Ensure the owned targets are sized to match (width, height). No-op if
|
||||
// the size hasn't changed, destroys + recreates on resize. Must be called
|
||||
// before any gtao*View accessor each frame.
|
||||
void ResizeGTAO( int width, int height );
|
||||
|
||||
// Depth pre-pass attachment views. Bind as pass.attachments.colors[0]
|
||||
// (linear-depth R32F) and pass.attachments.depth_stencil (transient D32F,
|
||||
// rasterizer-only). The renderer's DepthPrepass writes both.
|
||||
sg_view GetLinearDepthAttachmentView( void );
|
||||
sg_view GetPrepassDepthAttachmentView( void );
|
||||
|
||||
// Texture view of the R32F linear-depth target. Consumed by the GTAO
|
||||
// PrefilterDepth compute.
|
||||
sg_view GetLinearDepthSampleView( void );
|
||||
|
||||
// Dispatch the PrefilterDepth compute. Builds GTAOConstants
|
||||
// from `proj` + viewport dims, then runs one ceil(w/16) x ceil(h/16)
|
||||
// workgroup over the linear-depth target to populate all 5 mips of the
|
||||
// prefiltered chain. Must be called after the depth pre-pass has
|
||||
// written `linearDepthImage` and before MainPass tries to read
|
||||
// the prefiltered chain.
|
||||
void PrefilterDepth( const Mat4* proj, int viewportWidth, int viewportHeight );
|
||||
|
||||
// Texture view of the full prefiltered linear-depth mip chain (R32F,
|
||||
// 5 mips). Consumed by MainPass. The chain view samples every mip, the
|
||||
// bound shader picks a mip via textureLod at trace time.
|
||||
sg_view GetPrefilterDepthSampleView( void );
|
||||
|
||||
// Dispatch the MainPass compute. Per-pixel: reconstructs the
|
||||
// view-space normal in-place from depth derivatives, generates Hilbert
|
||||
// + R2 spatial noise (NoiseIndex = 0, no TAA), runs the XeGTAO Ultra-
|
||||
// tier slice trace (9 slices x 3 steps) against the prefiltered depth
|
||||
// chain. Writes the noisy AO term (divided by 1.5 per
|
||||
// XeGTAO_OutputWorkingTerm) to `noisy0Image` and the packed edges to
|
||||
// `edgesImage`. Must be called after PrefilterDepth has populated
|
||||
// the prefiltered chain.
|
||||
//
|
||||
// `noisy0` is fed into Denoise next, lit shaders sample `result`
|
||||
// which only receives a write on the denoise final-apply dispatch.
|
||||
void ComputeNoisyResult( const Mat4* proj, int viewportWidth, int viewportHeight );
|
||||
|
||||
// Dispatch the cross-bilateral denoise. Runs N = params.denoisePassCount
|
||||
// dispatches total: (N - 1) intermediates that ping-pong noisy0 <-> noisy1
|
||||
// with finalApply = 0, then one final dispatch with finalApply = 1 that
|
||||
// rescales by XE_GTAO_OCCLUSION_TERM_SCALE (1.5) and writes `result`. At
|
||||
// N = 1 only the final dispatch runs and reads noisy0 directly.
|
||||
//
|
||||
// Each dispatch is a 8x8 num threads compute over ceil(W/16) x ceil(H/8)
|
||||
// workgroups (each thread handles 2 horizontal pixels). The edge texture
|
||||
// written by MainPass is bound on every dispatch.
|
||||
//
|
||||
// Must be called after ComputeNoisyResult(). This is the last GTAO
|
||||
// dispatch and lit shaders can sample `result` via GetAOResultSampleView
|
||||
// right after.
|
||||
void Denoise( const Mat4* proj, int viewportWidth, int viewportHeight );
|
||||
|
||||
// Clear the full-res `result` AO target to 1.0 (no occlusion). Used when
|
||||
// GTAO is disabled at runtime (FrameInput.disable_gtao = true), lit
|
||||
// shaders (which always sample tex_ao) see a fully-lit ambient.
|
||||
void ClearAmbientOcclusion( void );
|
||||
|
||||
// Texture view of the full-res `result` AO output (R32F). Lit shape
|
||||
// shaders bind this and sample at gl_FragCoord.xy * viewport.zw to look
|
||||
// up their per-pixel AO term. After the Denoise final apply this is the
|
||||
// rescaled [0, 1.5] visibility term (XE_GTAO_OCCLUSION_TERM_SCALE).
|
||||
sg_view GetAOResultSampleView( void );
|
||||
|
||||
sg_sampler GetAOLinearSampler( void );
|
||||
|
||||
#ifdef __cplusplus
|
||||
} // extern "C"
|
||||
#endif
|
||||
413
samples/gfx/highlight_mask.c
Normal file
413
samples/gfx/highlight_mask.c
Normal file
|
|
@ -0,0 +1,413 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "gfx/highlight_mask.h"
|
||||
|
||||
#include "gfx/renderer.h"
|
||||
#include "mask_capsule.glsl.h"
|
||||
#include "mask_hull.glsl.h"
|
||||
#include "mask_sphere.glsl.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#define MAX_HIGHLIGHTS_PER_KIND 64
|
||||
|
||||
// Mirrors of the shader-side instance structs. sokol-shdc generates these
|
||||
// as mask_*_instance_t in the per-shader header. The CPU staging arrays
|
||||
// upload directly into the per-pipeline storage buffers without an extra
|
||||
// pack step.
|
||||
|
||||
static struct
|
||||
{
|
||||
sg_shader shader;
|
||||
sg_pipeline pipeline;
|
||||
sg_buffer instBuf;
|
||||
sg_view instView;
|
||||
mask_sphere_instance_t cpu[MAX_HIGHLIGHTS_PER_KIND];
|
||||
int count;
|
||||
} s_sphere;
|
||||
|
||||
static struct
|
||||
{
|
||||
sg_shader shader;
|
||||
sg_pipeline pipeline;
|
||||
sg_buffer instBuf;
|
||||
sg_view instView;
|
||||
mask_capsule_instance_t cpu[MAX_HIGHLIGHTS_PER_KIND];
|
||||
int count;
|
||||
} s_capsule;
|
||||
|
||||
// Hulls draw one-by-one (each with its own vbo/ibo binding). The CPU staging
|
||||
// holds the instance struct array. The per-frame draw list holds the
|
||||
// matching geometry buffers + indexCount.
|
||||
typedef struct HullDraw
|
||||
{
|
||||
sg_buffer vbo;
|
||||
sg_buffer ibo;
|
||||
int indexCount;
|
||||
} HullDraw;
|
||||
|
||||
static struct
|
||||
{
|
||||
sg_shader shader;
|
||||
sg_pipeline pipeline;
|
||||
sg_buffer instBuf;
|
||||
sg_view instView;
|
||||
mask_hull_instance_t cpu[MAX_HIGHLIGHTS_PER_KIND];
|
||||
HullDraw draws[MAX_HIGHLIGHTS_PER_KIND];
|
||||
int count;
|
||||
} s_hull;
|
||||
|
||||
static bool s_uiInitialized = false;
|
||||
|
||||
// Init / shutdown
|
||||
|
||||
void HighlightMaskInit( void )
|
||||
{
|
||||
if ( s_uiInitialized )
|
||||
return;
|
||||
|
||||
// Sphere mask pipeline
|
||||
s_sphere.shader = sg_make_shader( mask_sphere_prog_shader_desc( sg_query_backend() ) );
|
||||
|
||||
sg_buffer_desc sphBufDesc = { 0 };
|
||||
sphBufDesc.usage.storage_buffer = true;
|
||||
sphBufDesc.usage.stream_update = true;
|
||||
sphBufDesc.size = sizeof( s_sphere.cpu );
|
||||
sphBufDesc.label = "highlight_sphere_instances";
|
||||
s_sphere.instBuf = sg_make_buffer( &sphBufDesc );
|
||||
|
||||
sg_view_desc sphViewDesc = { 0 };
|
||||
sphViewDesc.storage_buffer.buffer = s_sphere.instBuf;
|
||||
sphViewDesc.label = "highlight_sphere_instances_view";
|
||||
s_sphere.instView = sg_make_view( &sphViewDesc );
|
||||
|
||||
sg_pipeline_desc sphPdesc = { 0 };
|
||||
sphPdesc.shader = s_sphere.shader;
|
||||
sphPdesc.layout.buffers[0].stride = sizeof( float ) * 3;
|
||||
sphPdesc.layout.attrs[ATTR_mask_sphere_prog_in_pos].format = SG_VERTEXFORMAT_FLOAT3;
|
||||
sphPdesc.layout.attrs[ATTR_mask_sphere_prog_in_pos].buffer_index = 0;
|
||||
sphPdesc.index_type = SG_INDEXTYPE_UINT16;
|
||||
sphPdesc.colors[0].pixel_format = SG_PIXELFORMAT_R8;
|
||||
sphPdesc.color_count = 1;
|
||||
sphPdesc.depth.pixel_format = SG_PIXELFORMAT_DEPTH;
|
||||
sphPdesc.depth.compare = SG_COMPAREFUNC_GREATER_EQUAL;
|
||||
sphPdesc.depth.write_enabled = false;
|
||||
// Impostor convention: front-face cull on the proxy box, so the
|
||||
// analytic intersection is rasterized from the back faces and remains
|
||||
// visible when the camera sits inside the proxy AABB but outside the
|
||||
// analytic sphere.
|
||||
sphPdesc.cull_mode = SG_CULLMODE_FRONT;
|
||||
sphPdesc.face_winding = SG_FACEWINDING_CCW;
|
||||
sphPdesc.sample_count = 1;
|
||||
sphPdesc.label = "highlight_sphere_pipeline";
|
||||
s_sphere.pipeline = sg_make_pipeline( &sphPdesc );
|
||||
|
||||
// Capsule mask pipeline
|
||||
s_capsule.shader = sg_make_shader( mask_capsule_prog_shader_desc( sg_query_backend() ) );
|
||||
|
||||
sg_buffer_desc capBufDesc = { 0 };
|
||||
capBufDesc.usage.storage_buffer = true;
|
||||
capBufDesc.usage.stream_update = true;
|
||||
capBufDesc.size = sizeof( s_capsule.cpu );
|
||||
capBufDesc.label = "highlight_capsule_instances";
|
||||
s_capsule.instBuf = sg_make_buffer( &capBufDesc );
|
||||
|
||||
sg_view_desc capViewDesc = { 0 };
|
||||
capViewDesc.storage_buffer.buffer = s_capsule.instBuf;
|
||||
capViewDesc.label = "highlight_capsule_instances_view";
|
||||
s_capsule.instView = sg_make_view( &capViewDesc );
|
||||
|
||||
sg_pipeline_desc capPdesc = { 0 };
|
||||
capPdesc.shader = s_capsule.shader;
|
||||
capPdesc.layout.buffers[0].stride = sizeof( float ) * 3;
|
||||
capPdesc.layout.attrs[ATTR_mask_capsule_prog_in_pos].format = SG_VERTEXFORMAT_FLOAT3;
|
||||
capPdesc.layout.attrs[ATTR_mask_capsule_prog_in_pos].buffer_index = 0;
|
||||
capPdesc.index_type = SG_INDEXTYPE_UINT16;
|
||||
capPdesc.colors[0].pixel_format = SG_PIXELFORMAT_R8;
|
||||
capPdesc.color_count = 1;
|
||||
capPdesc.depth.pixel_format = SG_PIXELFORMAT_DEPTH;
|
||||
capPdesc.depth.compare = SG_COMPAREFUNC_GREATER_EQUAL;
|
||||
capPdesc.depth.write_enabled = false;
|
||||
capPdesc.cull_mode = SG_CULLMODE_FRONT;
|
||||
capPdesc.face_winding = SG_FACEWINDING_CCW;
|
||||
capPdesc.sample_count = 1;
|
||||
capPdesc.label = "highlight_capsule_pipeline";
|
||||
s_capsule.pipeline = sg_make_pipeline( &capPdesc );
|
||||
|
||||
// Hull mask pipeline
|
||||
s_hull.shader = sg_make_shader( mask_hull_prog_shader_desc( sg_query_backend() ) );
|
||||
|
||||
sg_buffer_desc hullBufDesc = { 0 };
|
||||
hullBufDesc.usage.storage_buffer = true;
|
||||
hullBufDesc.usage.stream_update = true;
|
||||
hullBufDesc.size = sizeof( s_hull.cpu );
|
||||
hullBufDesc.label = "highlight_hull_instances";
|
||||
s_hull.instBuf = sg_make_buffer( &hullBufDesc );
|
||||
|
||||
sg_view_desc hullViewDesc = { 0 };
|
||||
hullViewDesc.storage_buffer.buffer = s_hull.instBuf;
|
||||
hullViewDesc.label = "highlight_hull_instances_view";
|
||||
s_hull.instView = sg_make_view( &hullViewDesc );
|
||||
|
||||
sg_pipeline_desc hullPdesc = { 0 };
|
||||
hullPdesc.shader = s_hull.shader;
|
||||
// Geometry registry vbo is interleaved {position(3), normal(3)}, keep
|
||||
// the stride matching the lit geom vbo so this pipeline can share it.
|
||||
// in_normal is declared by the lit shader at offset 12 but unused here.
|
||||
// The shader doesn't declare it so the binding is skipped to match.
|
||||
hullPdesc.layout.buffers[0].stride = sizeof( float ) * 6;
|
||||
hullPdesc.layout.attrs[ATTR_mask_hull_prog_in_pos].format = SG_VERTEXFORMAT_FLOAT3;
|
||||
hullPdesc.layout.attrs[ATTR_mask_hull_prog_in_pos].buffer_index = 0;
|
||||
hullPdesc.layout.attrs[ATTR_mask_hull_prog_in_pos].offset = 0;
|
||||
hullPdesc.index_type = SG_INDEXTYPE_UINT32;
|
||||
hullPdesc.colors[0].pixel_format = SG_PIXELFORMAT_R8;
|
||||
hullPdesc.color_count = 1;
|
||||
hullPdesc.depth.pixel_format = SG_PIXELFORMAT_DEPTH;
|
||||
hullPdesc.depth.compare = SG_COMPAREFUNC_GREATER_EQUAL;
|
||||
hullPdesc.depth.write_enabled = false;
|
||||
hullPdesc.cull_mode = SG_CULLMODE_BACK;
|
||||
hullPdesc.face_winding = SG_FACEWINDING_CCW;
|
||||
hullPdesc.sample_count = 1;
|
||||
hullPdesc.label = "highlight_hull_pipeline";
|
||||
s_hull.pipeline = sg_make_pipeline( &hullPdesc );
|
||||
|
||||
s_uiInitialized = true;
|
||||
}
|
||||
|
||||
void HighlightMaskShutdown( void )
|
||||
{
|
||||
if ( !s_uiInitialized )
|
||||
return;
|
||||
|
||||
sg_destroy_pipeline( s_hull.pipeline );
|
||||
s_hull.pipeline.id = 0;
|
||||
sg_destroy_view( s_hull.instView );
|
||||
s_hull.instView.id = 0;
|
||||
sg_destroy_buffer( s_hull.instBuf );
|
||||
s_hull.instBuf.id = 0;
|
||||
sg_destroy_shader( s_hull.shader );
|
||||
s_hull.shader.id = 0;
|
||||
|
||||
sg_destroy_pipeline( s_capsule.pipeline );
|
||||
s_capsule.pipeline.id = 0;
|
||||
sg_destroy_view( s_capsule.instView );
|
||||
s_capsule.instView.id = 0;
|
||||
sg_destroy_buffer( s_capsule.instBuf );
|
||||
s_capsule.instBuf.id = 0;
|
||||
sg_destroy_shader( s_capsule.shader );
|
||||
s_capsule.shader.id = 0;
|
||||
|
||||
sg_destroy_pipeline( s_sphere.pipeline );
|
||||
s_sphere.pipeline.id = 0;
|
||||
sg_destroy_view( s_sphere.instView );
|
||||
s_sphere.instView.id = 0;
|
||||
sg_destroy_buffer( s_sphere.instBuf );
|
||||
s_sphere.instBuf.id = 0;
|
||||
sg_destroy_shader( s_sphere.shader );
|
||||
s_sphere.shader.id = 0;
|
||||
|
||||
s_uiInitialized = false;
|
||||
}
|
||||
|
||||
void HighlightMaskBeginFrame( void )
|
||||
{
|
||||
s_sphere.count = 0;
|
||||
s_capsule.count = 0;
|
||||
s_hull.count = 0;
|
||||
}
|
||||
|
||||
bool HasHighlightMaskContent( void )
|
||||
{
|
||||
return ( s_sphere.count + s_capsule.count + s_hull.count ) > 0;
|
||||
}
|
||||
|
||||
// Append API
|
||||
|
||||
void AppendHighlightSphere( b3Transform transform, float radius, HighlightKind kind )
|
||||
{
|
||||
if ( kind == HIGHLIGHT_KIND_NONE )
|
||||
return;
|
||||
if ( s_sphere.count >= MAX_HIGHLIGHTS_PER_KIND )
|
||||
{
|
||||
fprintf( stderr, "[highlight/error] sphere overflow: dropping (cap=%d)\n", MAX_HIGHLIGHTS_PER_KIND );
|
||||
return;
|
||||
}
|
||||
mask_sphere_instance_t* inst = &s_sphere.cpu[s_sphere.count++];
|
||||
// transform's translation is the world-space center.
|
||||
inst->center_radius = MakeVec4( transform.p.x, transform.p.y, transform.p.z, radius );
|
||||
inst->kind = MakeVec4( (float)kind, 0.0f, 0.0f, 0.0f );
|
||||
}
|
||||
|
||||
void AppendHighlightCapsule( b3Transform transform, float halfLength, float radius, HighlightKind kind )
|
||||
{
|
||||
if ( kind == HIGHLIGHT_KIND_NONE )
|
||||
return;
|
||||
if ( s_capsule.count >= MAX_HIGHLIGHTS_PER_KIND )
|
||||
{
|
||||
fprintf( stderr, "[highlight/error] capsule overflow: dropping (cap=%d)\n", MAX_HIGHLIGHTS_PER_KIND );
|
||||
return;
|
||||
}
|
||||
mask_capsule_instance_t* inst = &s_capsule.cpu[s_capsule.count++];
|
||||
// 3x4 affine row layout: row i = (R_i0, R_i1, R_i2, t_i).
|
||||
Mat4 m = MakeMat4FromTransform( transform, b3Vec3_one );
|
||||
inst->xform_row0 = MakeVec4( m.cx.x, m.cy.x, m.cz.x, m.cw.x );
|
||||
inst->xform_row1 = MakeVec4( m.cx.y, m.cy.y, m.cz.y, m.cw.y );
|
||||
inst->xform_row2 = MakeVec4( m.cx.z, m.cy.z, m.cz.z, m.cw.z );
|
||||
inst->params = MakeVec4( halfLength, radius, (float)kind, 0.0f );
|
||||
}
|
||||
|
||||
void AppendHighlightHull( MeshHandle handle, b3Transform transform, b3Vec3 scale, HighlightKind kind )
|
||||
{
|
||||
if ( kind == HIGHLIGHT_KIND_NONE )
|
||||
return;
|
||||
if ( s_hull.count >= MAX_HIGHLIGHTS_PER_KIND )
|
||||
{
|
||||
fprintf( stderr, "[highlight/error] hull overflow: dropping (cap=%d)\n", MAX_HIGHLIGHTS_PER_KIND );
|
||||
return;
|
||||
}
|
||||
MeshBuffers gb = { 0 };
|
||||
if ( !GetMeshBuffers( handle, &gb ) )
|
||||
{
|
||||
return; // stale or invalid handle, skip silently
|
||||
}
|
||||
const int index = s_hull.count++;
|
||||
mask_hull_instance_t* inst = &s_hull.cpu[index];
|
||||
Mat4 m = MakeMat4FromTransform( transform, b3Vec3_one );
|
||||
inst->xform_row0 = MakeVec4( m.cx.x, m.cy.x, m.cz.x, m.cw.x );
|
||||
inst->xform_row1 = MakeVec4( m.cx.y, m.cy.y, m.cz.y, m.cw.y );
|
||||
inst->xform_row2 = MakeVec4( m.cx.z, m.cy.z, m.cz.z, m.cw.z );
|
||||
inst->scale_kind = MakeVec4( scale.x, scale.y, scale.z, (float)kind );
|
||||
s_hull.draws[index].vbo = gb.vbo;
|
||||
s_hull.draws[index].ibo = gb.ibo;
|
||||
s_hull.draws[index].indexCount = gb.indexCount;
|
||||
}
|
||||
|
||||
// Submit
|
||||
|
||||
void SubmitHighlightMask( int width, int height, const Mat4* viewProj, b3Vec3 cameraPosWorld, sg_view maskAttachView,
|
||||
sg_view depthAttachView )
|
||||
{
|
||||
if ( !s_uiInitialized )
|
||||
return;
|
||||
if ( !HasHighlightMaskContent() )
|
||||
return;
|
||||
|
||||
sg_pass pass = { 0 };
|
||||
pass.action.colors[0].load_action = SG_LOADACTION_CLEAR;
|
||||
pass.action.colors[0].clear_value.r = 0.0f;
|
||||
pass.action.colors[0].clear_value.g = 0.0f;
|
||||
pass.action.colors[0].clear_value.b = 0.0f;
|
||||
pass.action.colors[0].clear_value.a = 0.0f;
|
||||
pass.action.colors[0].store_action = SG_STOREACTION_STORE;
|
||||
pass.action.depth.load_action = SG_LOADACTION_LOAD;
|
||||
pass.action.depth.store_action = SG_STOREACTION_DONTCARE;
|
||||
pass.attachments.colors[0] = maskAttachView;
|
||||
pass.attachments.depth_stencil = depthAttachView;
|
||||
pass.label = "highlight_mask_pass";
|
||||
sg_push_debug_group( "highlight_mask" );
|
||||
sg_begin_pass( &pass );
|
||||
sg_apply_viewport( 0, 0, width, height, true );
|
||||
|
||||
const sg_buffer cubeVbuf = GetCubeProxyVertexBuffer();
|
||||
const sg_buffer cubeIbuf = GetCubeProxyIndexBuffer();
|
||||
const int cubeCount = GetCubeProxyIndexCount();
|
||||
|
||||
// Spheres
|
||||
if ( s_sphere.count > 0 )
|
||||
{
|
||||
sg_range upload;
|
||||
upload.ptr = s_sphere.cpu;
|
||||
upload.size = (size_t)s_sphere.count * sizeof( mask_sphere_instance_t );
|
||||
sg_update_buffer( s_sphere.instBuf, &upload );
|
||||
|
||||
sg_apply_pipeline( s_sphere.pipeline );
|
||||
|
||||
sg_bindings b = { 0 };
|
||||
b.vertex_buffers[0] = cubeVbuf;
|
||||
b.index_buffer = cubeIbuf;
|
||||
b.views[VIEW_mask_sphere_instances] = s_sphere.instView;
|
||||
sg_apply_bindings( &b );
|
||||
|
||||
mask_sphere_ub_frame_t uf = { 0 };
|
||||
uf.view_proj = *viewProj;
|
||||
sg_apply_uniforms( UB_mask_sphere_ub_frame, &SG_RANGE( uf ) );
|
||||
|
||||
mask_sphere_ub_pass_t up = { 0 };
|
||||
up.view_proj = *viewProj;
|
||||
up.camera_pos = MakeVec4( cameraPosWorld.x, cameraPosWorld.y, cameraPosWorld.z, 0.0f );
|
||||
sg_apply_uniforms( UB_mask_sphere_ub_pass, &SG_RANGE( up ) );
|
||||
|
||||
sg_draw( 0, cubeCount, s_sphere.count );
|
||||
}
|
||||
|
||||
// Capsules
|
||||
if ( s_capsule.count > 0 )
|
||||
{
|
||||
sg_range upload;
|
||||
upload.ptr = s_capsule.cpu;
|
||||
upload.size = (size_t)s_capsule.count * sizeof( mask_capsule_instance_t );
|
||||
sg_update_buffer( s_capsule.instBuf, &upload );
|
||||
|
||||
sg_apply_pipeline( s_capsule.pipeline );
|
||||
|
||||
sg_bindings b = { 0 };
|
||||
b.vertex_buffers[0] = cubeVbuf;
|
||||
b.index_buffer = cubeIbuf;
|
||||
b.views[VIEW_mask_capsule_instances] = s_capsule.instView;
|
||||
sg_apply_bindings( &b );
|
||||
|
||||
mask_capsule_ub_frame_t uf = { 0 };
|
||||
uf.view_proj = *viewProj;
|
||||
sg_apply_uniforms( UB_mask_capsule_ub_frame, &SG_RANGE( uf ) );
|
||||
|
||||
mask_capsule_ub_pass_t up = { 0 };
|
||||
up.view_proj = *viewProj;
|
||||
up.camera_pos = MakeVec4( cameraPosWorld.x, cameraPosWorld.y, cameraPosWorld.z, 0.0f );
|
||||
sg_apply_uniforms( UB_mask_capsule_ub_pass, &SG_RANGE( up ) );
|
||||
|
||||
sg_draw( 0, cubeCount, s_capsule.count );
|
||||
}
|
||||
|
||||
// Hulls
|
||||
if ( s_hull.count > 0 )
|
||||
{
|
||||
sg_range upload;
|
||||
upload.ptr = s_hull.cpu;
|
||||
upload.size = (size_t)s_hull.count * sizeof( mask_hull_instance_t );
|
||||
sg_update_buffer( s_hull.instBuf, &upload );
|
||||
|
||||
sg_apply_pipeline( s_hull.pipeline );
|
||||
|
||||
mask_hull_ub_frame_t uf = { 0 };
|
||||
uf.view_proj = *viewProj;
|
||||
sg_apply_uniforms( UB_mask_hull_ub_frame, &SG_RANGE( uf ) );
|
||||
|
||||
// One draw per hull, each binds its own (vbo, ibo) but shares the
|
||||
// mask hull instance storage view. inst_base picks the slot.
|
||||
sg_buffer currentVbo = { 0 };
|
||||
sg_buffer currentIbo = { 0 };
|
||||
for ( int i = 0; i < s_hull.count; ++i )
|
||||
{
|
||||
const HullDraw d = s_hull.draws[i];
|
||||
if ( d.vbo.id != currentVbo.id || d.ibo.id != currentIbo.id )
|
||||
{
|
||||
sg_bindings b = { 0 };
|
||||
b.vertex_buffers[0] = d.vbo;
|
||||
b.index_buffer = d.ibo;
|
||||
b.views[VIEW_mask_hull_instances] = s_hull.instView;
|
||||
sg_apply_bindings( &b );
|
||||
currentVbo = d.vbo;
|
||||
currentIbo = d.ibo;
|
||||
}
|
||||
mask_hull_ub_draw_t ud = { 0 };
|
||||
ud.inst_base[0] = i;
|
||||
sg_apply_uniforms( UB_mask_hull_ub_draw, &SG_RANGE( ud ) );
|
||||
sg_draw( 0, d.indexCount, 1 );
|
||||
}
|
||||
}
|
||||
|
||||
sg_end_pass();
|
||||
sg_pop_debug_group();
|
||||
}
|
||||
74
samples/gfx/highlight_mask.h
Normal file
74
samples/gfx/highlight_mask.h
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Per-frame append API + the render pass that rasterizes a small set
|
||||
// "highlighted" shapes into the renderer-owned R8 mask target. The pass
|
||||
// runs once per frame, after the GTAO depth prepass, before tonemap, the
|
||||
// outline post-pass then reads the mask and composites silhouette colors
|
||||
// over the resolved scene.
|
||||
//
|
||||
// Restricted to spheres, capsules, and hulls by design, meshes and
|
||||
// heightfields look poor outlined and aren't worth the pipeline weight.
|
||||
//
|
||||
// Encodes one of three states per pixel as the kind value passed in:
|
||||
// 1 = hover -> R8 UNORM 0.5
|
||||
// 2 = select -> R8 UNORM 1.0
|
||||
// 0 -> unhighlighted, never written
|
||||
//
|
||||
// Single-threaded, render-thread only. Submission counts capped per
|
||||
// shape class, overflows log and drop.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "gfx/geometry_registry.h"
|
||||
#include "gfx/utility.h"
|
||||
#include "sokol_gfx.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"
|
||||
{
|
||||
#endif
|
||||
|
||||
typedef enum HighlightKind
|
||||
{
|
||||
HIGHLIGHT_KIND_NONE = 0,
|
||||
HIGHLIGHT_KIND_HOVER = 1,
|
||||
HIGHLIGHT_KIND_SELECT = 2,
|
||||
} HighlightKind;
|
||||
|
||||
void HighlightMaskInit( void );
|
||||
void HighlightMaskShutdown( void );
|
||||
|
||||
// Reset per-frame counts. Called from ResetFrameArena.
|
||||
void HighlightMaskBeginFrame( void );
|
||||
|
||||
// Append a highlighted sphere. transform supplies the world-space center via
|
||||
// its translation, rotation is ignored (a sphere is rotationally invariant
|
||||
// for silhouette purposes). Logs + drops on overflow.
|
||||
void AppendHighlightSphere( b3Transform transform, float radius, HighlightKind kind );
|
||||
|
||||
// Append a highlighted capsule. transform follows the same convention as
|
||||
// AppendCapsule (rotation places local +X along the long axis,
|
||||
// translation is the capsule center). halfLength and radius are
|
||||
// world-space scalars. Logs + drops on overflow.
|
||||
void AppendHighlightCapsule( b3Transform transform, float halfLength, float radius, HighlightKind kind );
|
||||
|
||||
// Append a highlighted hull. handle resolves to a registered geometry
|
||||
// (vbo/ibo). transform + scale match AppendMesh, rotation matters because
|
||||
// hulls aren't rotationally symmetric. Logs + drops on overflow.
|
||||
void AppendHighlightHull( MeshHandle handle, b3Transform transform, b3Vec3 scale, HighlightKind kind );
|
||||
|
||||
// True when at least one shape was submitted this frame. Lets the caller
|
||||
// skip mask + outline passes entirely on the common empty case.
|
||||
bool HasHighlightMaskContent( void );
|
||||
|
||||
// Open a single-sample render pass against (maskAttachView,
|
||||
// depthAttachView), clear the mask to 0, and rasterize all submitted
|
||||
// highlights. Depth-tests GREATER_EQUAL against the supplied prepass depth
|
||||
// (no write). No-op when no highlights were submitted.
|
||||
void SubmitHighlightMask( int width, int height, const Mat4* viewProj, b3Vec3 cameraPosWorld, sg_view maskAttachView,
|
||||
sg_view depthAttachView );
|
||||
|
||||
#ifdef __cplusplus
|
||||
} // extern "C"
|
||||
#endif
|
||||
155
samples/gfx/highlight_outline.c
Normal file
155
samples/gfx/highlight_outline.c
Normal file
|
|
@ -0,0 +1,155 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "gfx/highlight_outline.h"
|
||||
|
||||
#include "highlight_outline.glsl.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#define HIGHLIGHT_OUTLINE_MAX_PIPELINES 2
|
||||
|
||||
static struct
|
||||
{
|
||||
sg_shader shader;
|
||||
sg_sampler sampler;
|
||||
struct
|
||||
{
|
||||
sg_pixel_format colorFormat;
|
||||
sg_pixel_format depthFormat;
|
||||
sg_pipeline pipeline;
|
||||
} pipelines[HIGHLIGHT_OUTLINE_MAX_PIPELINES];
|
||||
int pipelineCount;
|
||||
bool ready;
|
||||
} s_ho;
|
||||
|
||||
HighlightParams GetDefaultHighlightParams( void )
|
||||
{
|
||||
HighlightParams p;
|
||||
p.enabled = true;
|
||||
p.hoverThicknessPx = 1.0f;
|
||||
p.selectThicknessPx = 2.0f;
|
||||
// Cool cyan for hover at moderate alpha. Warm orange-yellow for select
|
||||
// at full alpha. Authored as straight RGBA. Premultiplied in the
|
||||
// submit step.
|
||||
p.hoverColor = MakeVec4( 0.35f, 0.85f, 1.0f, 0.75f );
|
||||
p.selectColor = MakeVec4( 1.0f, 0.78f, 0.20f, 1.0f );
|
||||
return p;
|
||||
}
|
||||
|
||||
static sg_pipeline ensurePipeline( sg_pixel_format colorFormat, sg_pixel_format depthFormat )
|
||||
{
|
||||
for ( int i = 0; i < s_ho.pipelineCount; ++i )
|
||||
{
|
||||
if ( s_ho.pipelines[i].colorFormat == colorFormat && s_ho.pipelines[i].depthFormat == depthFormat )
|
||||
{
|
||||
return s_ho.pipelines[i].pipeline;
|
||||
}
|
||||
}
|
||||
if ( s_ho.pipelineCount >= HIGHLIGHT_OUTLINE_MAX_PIPELINES )
|
||||
{
|
||||
fprintf( stderr, "highlight_outline: pipeline cache exhausted (max %d format pairs)\n", HIGHLIGHT_OUTLINE_MAX_PIPELINES );
|
||||
sg_pipeline empty = { 0 };
|
||||
return empty;
|
||||
}
|
||||
|
||||
sg_pipeline_desc pdesc = { 0 };
|
||||
pdesc.shader = s_ho.shader;
|
||||
pdesc.colors[0].pixel_format = colorFormat;
|
||||
pdesc.color_count = 1;
|
||||
// Premultiplied-alpha blend over the resolved scene color. ub_pass
|
||||
// colors are premultiplied by the C side.
|
||||
pdesc.colors[0].blend.enabled = true;
|
||||
pdesc.colors[0].blend.src_factor_rgb = SG_BLENDFACTOR_ONE;
|
||||
pdesc.colors[0].blend.dst_factor_rgb = SG_BLENDFACTOR_ONE_MINUS_SRC_ALPHA;
|
||||
pdesc.colors[0].blend.op_rgb = SG_BLENDOP_ADD;
|
||||
pdesc.colors[0].blend.src_factor_alpha = SG_BLENDFACTOR_ONE;
|
||||
pdesc.colors[0].blend.dst_factor_alpha = SG_BLENDFACTOR_ONE_MINUS_SRC_ALPHA;
|
||||
pdesc.colors[0].blend.op_alpha = SG_BLENDOP_ADD;
|
||||
pdesc.depth.pixel_format = depthFormat;
|
||||
pdesc.depth.write_enabled = false;
|
||||
pdesc.depth.compare = SG_COMPAREFUNC_ALWAYS;
|
||||
pdesc.cull_mode = SG_CULLMODE_NONE;
|
||||
pdesc.face_winding = SG_FACEWINDING_CCW;
|
||||
pdesc.sample_count = 1;
|
||||
pdesc.label = "highlight_outline_pipeline";
|
||||
|
||||
const sg_pipeline pip = sg_make_pipeline( &pdesc );
|
||||
s_ho.pipelines[s_ho.pipelineCount].colorFormat = colorFormat;
|
||||
s_ho.pipelines[s_ho.pipelineCount].depthFormat = depthFormat;
|
||||
s_ho.pipelines[s_ho.pipelineCount].pipeline = pip;
|
||||
++s_ho.pipelineCount;
|
||||
return pip;
|
||||
}
|
||||
|
||||
void InitHighlightOutline( void )
|
||||
{
|
||||
if ( s_ho.ready )
|
||||
return;
|
||||
s_ho.shader = sg_make_shader( highlight_outline_prog_shader_desc( sg_query_backend() ) );
|
||||
|
||||
// texelFetch reads ignore sampler state, but sokol-gfx still requires a
|
||||
// sampler binding for any texture binding. Nearest + clamp. Nothing
|
||||
// exotic.
|
||||
sg_sampler_desc sdesc = { 0 };
|
||||
sdesc.min_filter = SG_FILTER_NEAREST;
|
||||
sdesc.mag_filter = SG_FILTER_NEAREST;
|
||||
sdesc.mipmap_filter = SG_FILTER_NEAREST;
|
||||
sdesc.wrap_u = SG_WRAP_CLAMP_TO_EDGE;
|
||||
sdesc.wrap_v = SG_WRAP_CLAMP_TO_EDGE;
|
||||
sdesc.label = "highlight_outline_sampler";
|
||||
s_ho.sampler = sg_make_sampler( &sdesc );
|
||||
|
||||
s_ho.ready = true;
|
||||
}
|
||||
|
||||
void ShutdownHighlightOutline( void )
|
||||
{
|
||||
if ( !s_ho.ready )
|
||||
return;
|
||||
for ( int i = 0; i < s_ho.pipelineCount; ++i )
|
||||
{
|
||||
sg_destroy_pipeline( s_ho.pipelines[i].pipeline );
|
||||
s_ho.pipelines[i].pipeline.id = 0;
|
||||
s_ho.pipelines[i].colorFormat = SG_PIXELFORMAT_NONE;
|
||||
s_ho.pipelines[i].depthFormat = SG_PIXELFORMAT_NONE;
|
||||
}
|
||||
s_ho.pipelineCount = 0;
|
||||
sg_destroy_sampler( s_ho.sampler );
|
||||
s_ho.sampler.id = 0;
|
||||
sg_destroy_shader( s_ho.shader );
|
||||
s_ho.shader.id = 0;
|
||||
s_ho.ready = false;
|
||||
}
|
||||
|
||||
static inline Vec4 Premultiply( Vec4 c )
|
||||
{
|
||||
return MakeVec4( c.x * c.w, c.y * c.w, c.z * c.w, c.w );
|
||||
}
|
||||
|
||||
void SubmitHighlightOutline( sg_view maskSampleView, sg_pixel_format colorFormat, sg_pixel_format depthFormat,
|
||||
const HighlightParams* params )
|
||||
{
|
||||
if ( !s_ho.ready || !params || !params->enabled )
|
||||
return;
|
||||
|
||||
const sg_pipeline pip = ensurePipeline( colorFormat, depthFormat );
|
||||
if ( pip.id == 0 )
|
||||
return;
|
||||
|
||||
sg_apply_pipeline( pip );
|
||||
|
||||
sg_bindings b = { 0 };
|
||||
b.views[VIEW_highlight_outline_tex_mask] = maskSampleView;
|
||||
b.samplers[SMP_highlight_outline_smp_mask] = s_ho.sampler;
|
||||
sg_apply_bindings( &b );
|
||||
|
||||
highlight_outline_ub_pass_t up = { 0 };
|
||||
up.hover_color = Premultiply( params->hoverColor );
|
||||
up.select_color = Premultiply( params->selectColor );
|
||||
up.thickness_px = MakeVec4( params->hoverThicknessPx, params->selectThicknessPx, 0.0f, 0.0f );
|
||||
sg_apply_uniforms( UB_highlight_outline_ub_pass, &SG_RANGE( up ) );
|
||||
|
||||
sg_draw( 0, 3, 1 );
|
||||
}
|
||||
57
samples/gfx/highlight_outline.h
Normal file
57
samples/gfx/highlight_outline.h
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Fullscreen pass that reads the R8 highlight mask (filled by the
|
||||
// highlight_mask pass) and composites silhouette outline colors onto the
|
||||
// already-tone-mapped scene image. Runs against the same swap chain /
|
||||
// offscreen attachment the tone-map pass wrote to, with LOAD on color and
|
||||
// no depth.
|
||||
//
|
||||
// Two outline styles, both authored in linear premultiplied alpha space:
|
||||
// hover, typically thinner, more subtle (default 1 px, cool color)
|
||||
// select, wider and more saturated (default 2 px, warm color).
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "gfx/utility.h"
|
||||
#include "sokol_gfx.h"
|
||||
|
||||
#include <stdbool.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"
|
||||
{
|
||||
#endif
|
||||
|
||||
typedef struct HighlightParams
|
||||
{
|
||||
bool enabled;
|
||||
float hoverThicknessPx;
|
||||
float selectThicknessPx;
|
||||
// straight (non-premultiplied) linear RGBA, premultiplied inside
|
||||
Vec4 hoverColor;
|
||||
Vec4 selectColor;
|
||||
} HighlightParams;
|
||||
|
||||
HighlightParams GetDefaultHighlightParams( void );
|
||||
|
||||
void InitHighlightOutline( void );
|
||||
void ShutdownHighlightOutline( void );
|
||||
|
||||
// Submit the outline post-pass against the currently-open render pass.
|
||||
// The caller is responsible for having opened a pass against the desired
|
||||
// destination (the swap-chain after tone map, or the offscreen tone map target)
|
||||
// with LOAD action on color. The pass's color attachment format must match
|
||||
// colorFormat and its depth format must match depthFormat (depth is not
|
||||
// read or written by this pass, but the pipeline declaration needs the
|
||||
// formats to match for sokol-gfx validation).
|
||||
//
|
||||
// maskSampleView is the texture-sample view over the R8 mask image. The
|
||||
// pipeline is cached per (colorFormat, depthFormat) pair so repeat calls
|
||||
// from RenderFrame / RenderFrameOffscreen reuse one pipeline each.
|
||||
void SubmitHighlightOutline( sg_view maskSampleView, sg_pixel_format colorFormat, sg_pixel_format depthFormat,
|
||||
const HighlightParams* params );
|
||||
|
||||
#ifdef __cplusplus
|
||||
} // extern "C"
|
||||
#endif
|
||||
90
samples/gfx/highlight_target.c
Normal file
90
samples/gfx/highlight_target.c
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "gfx/highlight_target.h"
|
||||
|
||||
static struct
|
||||
{
|
||||
int width;
|
||||
int height;
|
||||
sg_image image;
|
||||
sg_view attachView;
|
||||
sg_view sampleView;
|
||||
bool ready;
|
||||
} s_ht;
|
||||
|
||||
static void destroyTargets( void )
|
||||
{
|
||||
if ( s_ht.sampleView.id )
|
||||
{
|
||||
sg_destroy_view( s_ht.sampleView );
|
||||
s_ht.sampleView.id = 0;
|
||||
}
|
||||
if ( s_ht.attachView.id )
|
||||
{
|
||||
sg_destroy_view( s_ht.attachView );
|
||||
s_ht.attachView.id = 0;
|
||||
}
|
||||
if ( s_ht.image.id )
|
||||
{
|
||||
sg_destroy_image( s_ht.image );
|
||||
s_ht.image.id = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void InitHighlightTarget( void )
|
||||
{
|
||||
s_ht.width = 0;
|
||||
s_ht.height = 0;
|
||||
s_ht.ready = true;
|
||||
}
|
||||
|
||||
void ShutdownHighlightTarget( void )
|
||||
{
|
||||
if ( !s_ht.ready )
|
||||
return;
|
||||
destroyTargets();
|
||||
s_ht.width = 0;
|
||||
s_ht.height = 0;
|
||||
s_ht.ready = false;
|
||||
}
|
||||
|
||||
void ResizeHighlightTarget( int width, int height )
|
||||
{
|
||||
if ( !s_ht.ready || width <= 0 || height <= 0 )
|
||||
return;
|
||||
if ( width == s_ht.width && height == s_ht.height && s_ht.image.id )
|
||||
return;
|
||||
|
||||
destroyTargets();
|
||||
s_ht.width = width;
|
||||
s_ht.height = height;
|
||||
|
||||
sg_image_desc idesc = { 0 };
|
||||
idesc.usage.color_attachment = true;
|
||||
idesc.width = width;
|
||||
idesc.height = height;
|
||||
idesc.pixel_format = SG_PIXELFORMAT_R8;
|
||||
idesc.sample_count = 1;
|
||||
idesc.label = "highlight_mask";
|
||||
s_ht.image = sg_make_image( &idesc );
|
||||
|
||||
sg_view_desc avdesc = { 0 };
|
||||
avdesc.color_attachment.image = s_ht.image;
|
||||
avdesc.label = "highlight_mask_attach";
|
||||
s_ht.attachView = sg_make_view( &avdesc );
|
||||
|
||||
sg_view_desc svdesc = { 0 };
|
||||
svdesc.texture.image = s_ht.image;
|
||||
svdesc.label = "highlight_mask_sample";
|
||||
s_ht.sampleView = sg_make_view( &svdesc );
|
||||
}
|
||||
|
||||
sg_view GetHighlightTargetMaskAttachView( void )
|
||||
{
|
||||
return s_ht.attachView;
|
||||
}
|
||||
sg_view GetHighlightTargetMaskSampleView( void )
|
||||
{
|
||||
return s_ht.sampleView;
|
||||
}
|
||||
44
samples/gfx/highlight_target.h
Normal file
44
samples/gfx/highlight_target.h
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Single-sample R8 UNORM image at scene resolution, written by the
|
||||
// highlight_mask pass and sampled by the highlight_outline post-pass. Sized
|
||||
// alongside the scene target, both resize when the framebuffer does.
|
||||
//
|
||||
// The mask encodes one of three states as a UNORM byte: 0.0 = no highlight,
|
||||
// 0.5 = hover, 1.0 = select. R8 UNORM (rather than R8_UINT) so the outline
|
||||
// shader can sample via the standard texture/sampler path, sokol-shdc's
|
||||
// integer-texture binding has cross-backend quirks we'd rather not eat for
|
||||
// a 3-value mask. Thresholds in the FS (>0.25, >0.75) recover the discrete
|
||||
// kinds.
|
||||
//
|
||||
// Single-sample (no MSAA), keeps the mask pipeline matched to the GTAO
|
||||
// prepass depth (also 1 sample) it depth-tests against. Silhouette softness
|
||||
// comes from the outline shader's tap pattern + alpha blend, not from MSAA
|
||||
// on the mask itself.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "sokol_gfx.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"
|
||||
{
|
||||
#endif
|
||||
|
||||
void InitHighlightTarget( void );
|
||||
void ShutdownHighlightTarget( void );
|
||||
|
||||
// Resize to (width, height) if changed. No-op when stable. Recreates the
|
||||
// image + views on size change.
|
||||
void ResizeHighlightTarget( int width, int height );
|
||||
|
||||
// Color-attachment view over the mask image. Bound by the highlight_mask pass.
|
||||
sg_view GetHighlightTargetMaskAttachView( void );
|
||||
|
||||
// Texture-sample view over the mask image. Bound by the highlight_outline pass.
|
||||
sg_view GetHighlightTargetMaskSampleView( void );
|
||||
|
||||
#ifdef __cplusplus
|
||||
} // extern "C"
|
||||
#endif
|
||||
667
samples/gfx/ibl.c
Normal file
667
samples/gfx/ibl.c
Normal file
|
|
@ -0,0 +1,667 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "gfx/ibl.h"
|
||||
|
||||
#include "brdf_lut.glsl.h"
|
||||
#include "gfx/sky.h"
|
||||
#include "prefilter.glsl.h"
|
||||
#include "sky_to_cube.glsl.h"
|
||||
|
||||
#include <math.h>
|
||||
|
||||
// Per-face basis vectors that map a fragment's v_uv in [0,1]^2 to a
|
||||
// world-space direction. Match the GL cubemap sampling convention (which
|
||||
// sokol abstracts uniformly across backends), so a direction d written
|
||||
// at (face F, uv) is recovered by sampling the cubemap with the same d.
|
||||
// Order: +X, -X, +Y, -Y, +Z, -Z.
|
||||
typedef struct
|
||||
{
|
||||
b3Vec3 right;
|
||||
b3Vec3 up;
|
||||
b3Vec3 forward;
|
||||
} CubeFaceBasis;
|
||||
|
||||
// SH projection grid resolution per face. 32 -> 6 * 32^2 = 6144 sample
|
||||
// evaluations per rebuild. Cheap on CPU and well above the SH order-2
|
||||
// Nyquist for the smooth Preetham function.
|
||||
#define IBL_SH_SAMPLES_PER_FACE 32
|
||||
|
||||
// Funk-Hecke / Ramamoorthi diffuse convolution weights, pre-multiplied
|
||||
// into the stored SH coefficients so the shader reads them as
|
||||
// E(N) = sum(coef[i] * basis_i(N)), L_diffuse = (albedo / pi) * E(N).
|
||||
// A_0 = pi, A_1 = 2pi/3, A_2 = pi/4 (Ramamoorthi & Hanrahan 2001, eq.5).
|
||||
#define SH_A0 ( 3.14159265358979323846f )
|
||||
#define SH_A1 ( 3.14159265358979323846f * 2.0f / 3.0f )
|
||||
#define SH_A2 ( 3.14159265358979323846f / 4.0f )
|
||||
|
||||
// SH-basis normalization constants (real spherical harmonics, l=0..2).
|
||||
// Order matches Sloan / Ramamoorthi: index 0 = (l=0,m=0), 1..3 = l=1
|
||||
// with m = -1,0,+1, 4..8 = l=2 with m = -2,-1,0,+1,+2.
|
||||
#define SH_Y00 0.282094791773878f // 0.5 / sqrt(pi)
|
||||
#define SH_Y1n1 0.488602511902919f // sqrt(3/(4pi))
|
||||
#define SH_Y10 0.488602511902919f
|
||||
#define SH_Y1p1 0.488602511902919f
|
||||
#define SH_Y2n2 1.092548430592079f // sqrt(15/(4pi))
|
||||
#define SH_Y2n1 1.092548430592079f
|
||||
#define SH_Y20 0.315391565252520f // sqrt(5/(16pi))
|
||||
#define SH_Y2p1 1.092548430592079f
|
||||
#define SH_Y2p2 0.546274215296039f // sqrt(15/(16pi)) = SH_Y2n2/2
|
||||
|
||||
static const CubeFaceBasis s_cubeFaceBasis[6] = {
|
||||
// +X
|
||||
{ { 0.0f, 0.0f, -1.0f }, { 0.0f, -1.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } },
|
||||
// -X
|
||||
{ { 0.0f, 0.0f, 1.0f }, { 0.0f, -1.0f, 0.0f }, { -1.0f, 0.0f, 0.0f } },
|
||||
// +Y
|
||||
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 1.0f }, { 0.0f, 1.0f, 0.0f } },
|
||||
// -Y
|
||||
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, -1.0f }, { 0.0f, -1.0f, 0.0f } },
|
||||
// +Z
|
||||
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, -1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } },
|
||||
// -Z
|
||||
{ { -1.0f, 0.0f, 0.0f }, { 0.0f, -1.0f, 0.0f }, { 0.0f, 0.0f, -1.0f } },
|
||||
};
|
||||
|
||||
static struct
|
||||
{
|
||||
// BRDF integration LUT (Karis split-sum). RG16F at GFX_IBL_LUT_SIZE^2.
|
||||
// Generated once at InitImageBasedLighting. Environment-independent so it never
|
||||
// needs to be rebuilt.
|
||||
sg_image brdfLut;
|
||||
sg_view brdfLutColorAttachmentView; // used during generation
|
||||
sg_view brdfLutSampleView; // bound by lit pipelines
|
||||
sg_sampler brdfLutSampler;
|
||||
sg_shader brdfLutShader;
|
||||
sg_pipeline brdfLutPipeline;
|
||||
|
||||
// Raw Preetham sky cube. 1 mip, 6 faces. Filled by sky_to_cube. Read
|
||||
// by the prefilter pass as the input cube. Not bound to lit pipelines.
|
||||
sg_image skyCubeRaw;
|
||||
sg_view skyCubeRawFaceAttachmentViews[6];
|
||||
sg_view skyCubeRawSampleView;
|
||||
sg_shader skyToCubeShader;
|
||||
sg_pipeline skyToCubePipeline;
|
||||
|
||||
// GGX-prefiltered sky cube. GFX_IBL_CUBE_MIPS mips x 6 faces. Mip 0
|
||||
// is the mirror (effectively a copy of skyCubeRaw). Deeper mips are
|
||||
// progressively rougher. This is what the lit pipelines sample.
|
||||
sg_image skyCube;
|
||||
sg_view skyCubeFaceMipAttachmentViews[6 * GFX_IBL_CUBE_MIPS];
|
||||
sg_view skyCubeSampleView;
|
||||
sg_sampler skyCubeSampler; // trilinear, clamp_to_edge
|
||||
sg_shader prefilterShader;
|
||||
sg_pipeline prefilterPipeline;
|
||||
|
||||
// SH cache. Filled by RebuildImageBasedLightingIfDirty.
|
||||
b3Vec3 shCoeffs[9];
|
||||
|
||||
// Dirty flag. Set true by MarkIblDirty + initial state. Cleared
|
||||
// by RebuildImageBasedLightingIfDirty after a successful rebuild.
|
||||
bool dirty;
|
||||
bool ready;
|
||||
} s_ibl;
|
||||
|
||||
// CPU Preetham (mirror of common/preetham.glsl)
|
||||
//
|
||||
// Keeps SH projection in lockstep with the GPU sky. The math is verbatim
|
||||
// from the shader. Comments are deliberately spare to avoid two sources
|
||||
// of truth, read preetham.glsl for the rationale.
|
||||
|
||||
static float PreethamPerezC( float cos_theta, float cos_gamma, float gamma, float A, float B, float C, float D, float E )
|
||||
{
|
||||
const float ct = ( cos_theta < 0.01f ) ? 0.01f : cos_theta;
|
||||
const float term1 = 1.0f + A * expf( B / ct );
|
||||
const float term2 = 1.0f + C * expf( D * gamma ) + E * cos_gamma * cos_gamma;
|
||||
return term1 * term2;
|
||||
}
|
||||
|
||||
static b3Vec3 PreethamSkyScaledC( b3Vec3 view_dir, b3Vec3 sun_dir, float turbidity, float fade )
|
||||
{
|
||||
const float PI = 3.14159265358979323846f;
|
||||
const float LUMINANCE_SCALE = 0.06f; // mirrors PREETHAM_LUMINANCE_SCALE
|
||||
|
||||
const float sun_y_clamped = ( sun_dir.y < 0.0f ) ? 0.0f : ( sun_dir.y > 1.0f ) ? 1.0f : sun_dir.y;
|
||||
|
||||
b3Vec3 view_clamped;
|
||||
view_clamped.x = view_dir.x;
|
||||
view_clamped.y = ( view_dir.y > 0.0f ? view_dir.y : 0.0f ) + 0.01f;
|
||||
view_clamped.z = view_dir.z;
|
||||
const float vlen =
|
||||
sqrtf( view_clamped.x * view_clamped.x + view_clamped.y * view_clamped.y + view_clamped.z * view_clamped.z );
|
||||
if ( vlen > 0.0f )
|
||||
{
|
||||
view_clamped.x /= vlen;
|
||||
view_clamped.y /= vlen;
|
||||
view_clamped.z /= vlen;
|
||||
}
|
||||
|
||||
const float cos_theta = ( view_clamped.y > 0.0f ) ? view_clamped.y : 0.0f;
|
||||
float cos_gamma = sun_dir.x * view_clamped.x + sun_dir.y * view_clamped.y + sun_dir.z * view_clamped.z;
|
||||
if ( cos_gamma < -1.0f )
|
||||
cos_gamma = -1.0f;
|
||||
if ( cos_gamma > 1.0f )
|
||||
cos_gamma = 1.0f;
|
||||
const float gamma = acosf( cos_gamma );
|
||||
const float sun_theta = acosf( sun_y_clamped );
|
||||
|
||||
const float T = ( turbidity < 1.0f ) ? 1.0f : turbidity;
|
||||
const float T2 = T * T;
|
||||
|
||||
const float A_Y = 0.1787f * T - 1.4630f;
|
||||
const float B_Y = -0.3554f * T + 0.4275f;
|
||||
const float C_Y = -0.0227f * T + 5.3251f;
|
||||
const float D_Y = 0.1206f * T - 2.5771f;
|
||||
const float E_Y = -0.0670f * T + 0.3703f;
|
||||
const float A_x = -0.0193f * T - 0.2592f;
|
||||
const float B_x = -0.0665f * T + 0.0008f;
|
||||
const float C_x = -0.0004f * T + 0.2125f;
|
||||
const float D_x = -0.0641f * T - 0.8989f;
|
||||
const float E_x = -0.0033f * T + 0.0452f;
|
||||
const float A_y = -0.0167f * T - 0.2608f;
|
||||
const float B_y = -0.0950f * T + 0.0092f;
|
||||
const float C_y = -0.0079f * T + 0.2102f;
|
||||
const float D_y = -0.0441f * T - 1.6537f;
|
||||
const float E_y = -0.0109f * T + 0.0529f;
|
||||
|
||||
const float ts = sun_theta;
|
||||
const float ts2 = ts * ts;
|
||||
const float ts3 = ts2 * ts;
|
||||
|
||||
const float x_z = ( 0.00166f * ts3 - 0.00375f * ts2 + 0.00209f * ts ) * T2 +
|
||||
( -0.02903f * ts3 + 0.06377f * ts2 - 0.03202f * ts + 0.00394f ) * T +
|
||||
( 0.11693f * ts3 - 0.21196f * ts2 + 0.06052f * ts + 0.25886f );
|
||||
const float y_z = ( 0.00275f * ts3 - 0.00610f * ts2 + 0.00317f * ts ) * T2 +
|
||||
( -0.04214f * ts3 + 0.08970f * ts2 - 0.04153f * ts + 0.00516f ) * T +
|
||||
( 0.15346f * ts3 - 0.26756f * ts2 + 0.06670f * ts + 0.26688f );
|
||||
|
||||
const float chi = ( 4.0f / 9.0f - T / 120.0f ) * ( PI - 2.0f * sun_theta );
|
||||
const float Y_z = ( 4.0453f * T - 4.9710f ) * tanf( chi ) - 0.2155f * T + 2.4192f;
|
||||
|
||||
const float cos_zen_gamma = sun_y_clamped;
|
||||
const float pY_v = PreethamPerezC( cos_theta, cos_gamma, gamma, A_Y, B_Y, C_Y, D_Y, E_Y );
|
||||
const float px_v = PreethamPerezC( cos_theta, cos_gamma, gamma, A_x, B_x, C_x, D_x, E_x );
|
||||
const float py_v = PreethamPerezC( cos_theta, cos_gamma, gamma, A_y, B_y, C_y, D_y, E_y );
|
||||
const float pY_z = PreethamPerezC( 1.0f, cos_zen_gamma, sun_theta, A_Y, B_Y, C_Y, D_Y, E_Y );
|
||||
const float px_z = PreethamPerezC( 1.0f, cos_zen_gamma, sun_theta, A_x, B_x, C_x, D_x, E_x );
|
||||
const float py_z = PreethamPerezC( 1.0f, cos_zen_gamma, sun_theta, A_y, B_y, C_y, D_y, E_y );
|
||||
|
||||
const float pY_z_safe = ( pY_z < 1.0e-5f ) ? 1.0e-5f : pY_z;
|
||||
const float px_z_safe = ( px_z < 1.0e-5f ) ? 1.0e-5f : px_z;
|
||||
const float py_z_safe = ( py_z < 1.0e-5f ) ? 1.0e-5f : py_z;
|
||||
|
||||
float Y = Y_z * pY_v / pY_z_safe;
|
||||
if ( Y < 0.0f )
|
||||
Y = 0.0f;
|
||||
const float x = x_z * px_v / px_z_safe;
|
||||
const float y = y_z * py_v / py_z_safe;
|
||||
|
||||
const float yy = ( y < 1.0e-5f ) ? 1.0e-5f : y;
|
||||
const float X_xyz = Y * x / yy;
|
||||
const float Y_xyz = Y;
|
||||
const float Z_xyz = Y * ( 1.0f - x - y ) / yy;
|
||||
|
||||
b3Vec3 rgb;
|
||||
rgb.x = ( X_xyz * 3.2404542f ) + ( Y_xyz * -1.5371385f ) + ( Z_xyz * -0.4985314f );
|
||||
rgb.y = ( X_xyz * -0.9692660f ) + ( Y_xyz * 1.8760108f ) + ( Z_xyz * 0.0415560f );
|
||||
rgb.z = ( X_xyz * 0.0556434f ) + ( Y_xyz * -0.2040259f ) + ( Z_xyz * 1.0572252f );
|
||||
if ( rgb.x < 0.0f )
|
||||
rgb.x = 0.0f;
|
||||
if ( rgb.y < 0.0f )
|
||||
rgb.y = 0.0f;
|
||||
if ( rgb.z < 0.0f )
|
||||
rgb.z = 0.0f;
|
||||
rgb.x *= LUMINANCE_SCALE * fade;
|
||||
rgb.y *= LUMINANCE_SCALE * fade;
|
||||
rgb.z *= LUMINANCE_SCALE * fade;
|
||||
return rgb;
|
||||
}
|
||||
|
||||
// Cube-texel solid-angle approximation. Closed form:
|
||||
// domega = 4 / ((u^2 + v^2 + 1)^1.5 * N^2)
|
||||
// where (u, v) in [-1, +1] is the texel-center face coordinate and N is
|
||||
// the face resolution. Sufficient at the 32^2 SH sampling grid.
|
||||
static float cubeTexelSolidAngle( float u, float v, int n )
|
||||
{
|
||||
const float d2 = u * u + v * v + 1.0f;
|
||||
const float denom = sqrtf( d2 * d2 * d2 ) * (float)n * (float)n;
|
||||
return 4.0f / denom;
|
||||
}
|
||||
|
||||
// Project the procedural sky into 9 RGB SH coefficients (band 0..2) by
|
||||
// evaluating closed-form Preetham at 32^2 stratified samples per face,
|
||||
// accumulating sum L(omega) * Y_i(omega) * domega, then multiplying by the Funk-Hecke
|
||||
// diffuse convolution weights so the shader's evaluation is a straight
|
||||
// dot product against the SH basis.
|
||||
static void ProjectSkyToSh( b3Vec3 dirToSun, float turbidity, float fade )
|
||||
{
|
||||
b3Vec3 coef[9];
|
||||
for ( int i = 0; i < 9; ++i )
|
||||
{
|
||||
coef[i] = b3Vec3_zero;
|
||||
}
|
||||
|
||||
const int N = IBL_SH_SAMPLES_PER_FACE;
|
||||
const float pixSize = 2.0f / (float)N;
|
||||
|
||||
for ( int face = 0; face < 6; ++face )
|
||||
{
|
||||
const CubeFaceBasis b = s_cubeFaceBasis[face];
|
||||
for ( int row = 0; row < N; ++row )
|
||||
{
|
||||
for ( int col = 0; col < N; ++col )
|
||||
{
|
||||
const float u = ( (float)col + 0.5f ) * pixSize - 1.0f;
|
||||
const float v = ( (float)row + 0.5f ) * pixSize - 1.0f;
|
||||
|
||||
b3Vec3 dir;
|
||||
dir.x = b.forward.x + u * b.right.x + v * b.up.x;
|
||||
dir.y = b.forward.y + u * b.right.y + v * b.up.y;
|
||||
dir.z = b.forward.z + u * b.right.z + v * b.up.z;
|
||||
const float dlen = sqrtf( dir.x * dir.x + dir.y * dir.y + dir.z * dir.z );
|
||||
if ( dlen > 0.0f )
|
||||
{
|
||||
dir.x /= dlen;
|
||||
dir.y /= dlen;
|
||||
dir.z /= dlen;
|
||||
}
|
||||
|
||||
const float dW = cubeTexelSolidAngle( u, v, N );
|
||||
const b3Vec3 L = PreethamSkyScaledC( dir, dirToSun, turbidity, fade );
|
||||
|
||||
const float x = dir.x;
|
||||
const float y = dir.y;
|
||||
const float z = dir.z;
|
||||
|
||||
const float basis[9] = {
|
||||
SH_Y00,
|
||||
-SH_Y1n1 * y,
|
||||
SH_Y10 * z,
|
||||
-SH_Y1p1 * x,
|
||||
SH_Y2n2 * x * y,
|
||||
-SH_Y2n1 * y * z,
|
||||
SH_Y20 * ( 3.0f * z * z - 1.0f ),
|
||||
-SH_Y2p1 * x * z,
|
||||
SH_Y2p2 * ( x * x - y * y ),
|
||||
};
|
||||
|
||||
for ( int i = 0; i < 9; ++i )
|
||||
{
|
||||
const float w = basis[i] * dW;
|
||||
coef[i].x += L.x * w;
|
||||
coef[i].y += L.y * w;
|
||||
coef[i].z += L.z * w;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Apply Funk-Hecke / Ramamoorthi convolution weights so the shader
|
||||
// can evaluate irradiance as a straight dot product.
|
||||
const float scale[9] = {
|
||||
SH_A0, SH_A1, SH_A1, SH_A1, SH_A2, SH_A2, SH_A2, SH_A2, SH_A2,
|
||||
};
|
||||
for ( int i = 0; i < 9; ++i )
|
||||
{
|
||||
s_ibl.shCoeffs[i].x = coef[i].x * scale[i];
|
||||
s_ibl.shCoeffs[i].y = coef[i].y * scale[i];
|
||||
s_ibl.shCoeffs[i].z = coef[i].z * scale[i];
|
||||
}
|
||||
}
|
||||
|
||||
static void GenerateBrdfLut( void )
|
||||
{
|
||||
// One-shot pass into the LUT's color attachment. Discard load (we
|
||||
// overwrite every pixel), no clear necessary.
|
||||
sg_pass pass = { 0 };
|
||||
pass.action.colors[0].load_action = SG_LOADACTION_DONTCARE;
|
||||
pass.action.colors[0].store_action = SG_STOREACTION_STORE;
|
||||
pass.attachments.colors[0] = s_ibl.brdfLutColorAttachmentView;
|
||||
|
||||
sg_push_debug_group( "ibl_brdf_lut" );
|
||||
sg_begin_pass( &pass );
|
||||
sg_apply_pipeline( s_ibl.brdfLutPipeline );
|
||||
// params.x: backend-conditional UV.y sign for the LUT's render-target
|
||||
// V orientation, see brdf_lut.glsl. +1 on GL (NDC.y=+1 stores at the
|
||||
// texel addressed by sampling V=1), -1 on D3D11/Metal/WGPU (NDC.y=+1
|
||||
// stores at the texel addressed by sampling V=0). Without this, the
|
||||
// lit shaders' sample at (n_dot_v, roughness) reads the LUT for
|
||||
// (n_dot_v, 1-roughness) on non-GL backends, metals look dark and
|
||||
// rough materials look mirror-smooth.
|
||||
const sg_backend backend = sg_query_backend();
|
||||
const float uvYSign = ( backend == SG_BACKEND_GLCORE || backend == SG_BACKEND_GLES3 ) ? 1.0f : -1.0f;
|
||||
brdf_lut_ub_brdf_t ub = { 0 };
|
||||
ub.params = MakeVec4( uvYSign, 0.0f, 0.0f, 0.0f );
|
||||
sg_apply_uniforms( UB_brdf_lut_ub_brdf, &SG_RANGE( ub ) );
|
||||
// No texture bindings, sokol's VALIDATE_ABND_EMPTY_BINDINGS rejects
|
||||
// an empty sg_apply_bindings call, so skip it entirely.
|
||||
sg_draw( 0, 3, 1 );
|
||||
sg_end_pass();
|
||||
sg_pop_debug_group();
|
||||
}
|
||||
|
||||
static void GenerateSkyCube( b3Vec3 dirToSun, float turbidity, float fade )
|
||||
{
|
||||
// Six passes, one per face. Each pass fills the raw cube's
|
||||
// corresponding face via a fullscreen-triangle Preetham eval.
|
||||
sg_push_debug_group( "ibl_sky_to_cube" );
|
||||
for ( int face = 0; face < 6; ++face )
|
||||
{
|
||||
sg_pass pass = { 0 };
|
||||
pass.action.colors[0].load_action = SG_LOADACTION_DONTCARE;
|
||||
pass.action.colors[0].store_action = SG_STOREACTION_STORE;
|
||||
pass.attachments.colors[0] = s_ibl.skyCubeRawFaceAttachmentViews[face];
|
||||
|
||||
sg_begin_pass( &pass );
|
||||
sg_apply_pipeline( s_ibl.skyToCubePipeline );
|
||||
|
||||
const CubeFaceBasis b = s_cubeFaceBasis[face];
|
||||
sky_to_cube_ub_face_t up = { 0 };
|
||||
up.face_right = MakeVec4( b.right.x, b.right.y, b.right.z, 0.0f );
|
||||
up.face_up = MakeVec4( b.up.x, b.up.y, b.up.z, 0.0f );
|
||||
up.face_forward = MakeVec4( b.forward.x, b.forward.y, b.forward.z, fade );
|
||||
up.sun_dir_world = MakeVec4( dirToSun.x, dirToSun.y, dirToSun.z, turbidity );
|
||||
sg_apply_uniforms( UB_sky_to_cube_ub_face, &SG_RANGE( up ) );
|
||||
|
||||
sg_draw( 0, 3, 1 );
|
||||
sg_end_pass();
|
||||
}
|
||||
sg_pop_debug_group();
|
||||
}
|
||||
|
||||
static void GeneratePrefilter( void )
|
||||
{
|
||||
// For each mip x face, importance-sample the raw cube into the
|
||||
// prefiltered cube's corresponding face slice. Roughness maps
|
||||
// linearly across mips: mip 0 = 0 (mirror), mip N-1 = 1 (max rough).
|
||||
sg_push_debug_group( "ibl_prefilter" );
|
||||
const float mipDenom = (float)( GFX_IBL_CUBE_MIPS - 1 );
|
||||
|
||||
for ( int mip = 0; mip < GFX_IBL_CUBE_MIPS; ++mip )
|
||||
{
|
||||
const float roughness = ( mipDenom > 0.0f ) ? ( (float)mip / mipDenom ) : 0.0f;
|
||||
for ( int face = 0; face < 6; ++face )
|
||||
{
|
||||
sg_pass pass = { 0 };
|
||||
pass.action.colors[0].load_action = SG_LOADACTION_DONTCARE;
|
||||
pass.action.colors[0].store_action = SG_STOREACTION_STORE;
|
||||
pass.attachments.colors[0] = s_ibl.skyCubeFaceMipAttachmentViews[face * GFX_IBL_CUBE_MIPS + mip];
|
||||
|
||||
sg_begin_pass( &pass );
|
||||
sg_apply_pipeline( s_ibl.prefilterPipeline );
|
||||
|
||||
sg_bindings bindings = { 0 };
|
||||
bindings.views[VIEW_prefilter_tex_sky] = s_ibl.skyCubeRawSampleView;
|
||||
bindings.samplers[SMP_prefilter_smp_sky] = s_ibl.skyCubeSampler;
|
||||
sg_apply_bindings( &bindings );
|
||||
|
||||
const CubeFaceBasis b = s_cubeFaceBasis[face];
|
||||
prefilter_ub_pass_t up = { 0 };
|
||||
up.face_right = MakeVec4( b.right.x, b.right.y, b.right.z, 0.0f );
|
||||
up.face_up = MakeVec4( b.up.x, b.up.y, b.up.z, 0.0f );
|
||||
up.face_forward = MakeVec4( b.forward.x, b.forward.y, b.forward.z, 0.0f );
|
||||
up.params = MakeVec4( roughness, 0.0f, 0.0f, 0.0f );
|
||||
sg_apply_uniforms( UB_prefilter_ub_pass, &SG_RANGE( up ) );
|
||||
|
||||
sg_draw( 0, 3, 1 );
|
||||
sg_end_pass();
|
||||
}
|
||||
}
|
||||
sg_pop_debug_group();
|
||||
}
|
||||
|
||||
void InitImageBasedLighting( const sg_environment* env )
|
||||
{
|
||||
(void)env;
|
||||
|
||||
// BRDF LUT image + views + sampler
|
||||
sg_image_desc lutDesc = { 0 };
|
||||
lutDesc.usage.color_attachment = true;
|
||||
lutDesc.width = GFX_IBL_LUT_SIZE;
|
||||
lutDesc.height = GFX_IBL_LUT_SIZE;
|
||||
lutDesc.pixel_format = SG_PIXELFORMAT_RG16F;
|
||||
lutDesc.sample_count = 1;
|
||||
lutDesc.label = "ibl_brdf_lut";
|
||||
s_ibl.brdfLut = sg_make_image( &lutDesc );
|
||||
|
||||
sg_view_desc lutAttachDesc = { 0 };
|
||||
lutAttachDesc.color_attachment.image = s_ibl.brdfLut;
|
||||
lutAttachDesc.label = "ibl_brdf_lut_attachment";
|
||||
s_ibl.brdfLutColorAttachmentView = sg_make_view( &lutAttachDesc );
|
||||
|
||||
sg_view_desc lutSampleDesc = { 0 };
|
||||
lutSampleDesc.texture.image = s_ibl.brdfLut;
|
||||
lutSampleDesc.label = "ibl_brdf_lut_sample";
|
||||
s_ibl.brdfLutSampleView = sg_make_view( &lutSampleDesc );
|
||||
|
||||
sg_sampler_desc lutSampDesc = { 0 };
|
||||
lutSampDesc.min_filter = SG_FILTER_LINEAR;
|
||||
lutSampDesc.mag_filter = SG_FILTER_LINEAR;
|
||||
lutSampDesc.mipmap_filter = SG_FILTER_NEAREST;
|
||||
lutSampDesc.wrap_u = SG_WRAP_CLAMP_TO_EDGE;
|
||||
lutSampDesc.wrap_v = SG_WRAP_CLAMP_TO_EDGE;
|
||||
lutSampDesc.wrap_w = SG_WRAP_CLAMP_TO_EDGE;
|
||||
lutSampDesc.label = "ibl_brdf_lut_sampler";
|
||||
s_ibl.brdfLutSampler = sg_make_sampler( &lutSampDesc );
|
||||
|
||||
s_ibl.brdfLutShader = sg_make_shader( brdf_lut_build_shader_desc( sg_query_backend() ) );
|
||||
|
||||
sg_pipeline_desc lutPipeDesc = { 0 };
|
||||
lutPipeDesc.shader = s_ibl.brdfLutShader;
|
||||
lutPipeDesc.colors[0].pixel_format = SG_PIXELFORMAT_RG16F;
|
||||
lutPipeDesc.color_count = 1;
|
||||
lutPipeDesc.depth.pixel_format = SG_PIXELFORMAT_NONE;
|
||||
lutPipeDesc.depth.write_enabled = false;
|
||||
lutPipeDesc.depth.compare = SG_COMPAREFUNC_ALWAYS;
|
||||
lutPipeDesc.cull_mode = SG_CULLMODE_NONE;
|
||||
lutPipeDesc.face_winding = SG_FACEWINDING_CCW;
|
||||
lutPipeDesc.sample_count = 1;
|
||||
lutPipeDesc.label = "ibl_brdf_lut_pipeline";
|
||||
s_ibl.brdfLutPipeline = sg_make_pipeline( &lutPipeDesc );
|
||||
|
||||
GenerateBrdfLut();
|
||||
|
||||
// Raw sky cube (sky_to_cube target / prefilter input)
|
||||
sg_image_desc rawDesc = { 0 };
|
||||
rawDesc.type = SG_IMAGETYPE_CUBE;
|
||||
rawDesc.usage.color_attachment = true;
|
||||
rawDesc.width = GFX_IBL_CUBE_SIZE;
|
||||
rawDesc.height = GFX_IBL_CUBE_SIZE;
|
||||
rawDesc.num_mipmaps = 1;
|
||||
rawDesc.pixel_format = SG_PIXELFORMAT_RGBA16F;
|
||||
rawDesc.sample_count = 1;
|
||||
rawDesc.label = "ibl_sky_cube_raw";
|
||||
s_ibl.skyCubeRaw = sg_make_image( &rawDesc );
|
||||
|
||||
for ( int face = 0; face < 6; ++face )
|
||||
{
|
||||
sg_view_desc fdesc = { 0 };
|
||||
fdesc.color_attachment.image = s_ibl.skyCubeRaw;
|
||||
fdesc.color_attachment.slice = face;
|
||||
fdesc.color_attachment.mip_level = 0;
|
||||
fdesc.label = "ibl_sky_cube_raw_face";
|
||||
s_ibl.skyCubeRawFaceAttachmentViews[face] = sg_make_view( &fdesc );
|
||||
}
|
||||
|
||||
sg_view_desc rawSampleDesc = { 0 };
|
||||
rawSampleDesc.texture.image = s_ibl.skyCubeRaw;
|
||||
rawSampleDesc.label = "ibl_sky_cube_raw_sample";
|
||||
s_ibl.skyCubeRawSampleView = sg_make_view( &rawSampleDesc );
|
||||
|
||||
// Prefiltered sky cube (lit-pipeline input)
|
||||
sg_image_desc cubeDesc = { 0 };
|
||||
cubeDesc.type = SG_IMAGETYPE_CUBE;
|
||||
cubeDesc.usage.color_attachment = true;
|
||||
cubeDesc.width = GFX_IBL_CUBE_SIZE;
|
||||
cubeDesc.height = GFX_IBL_CUBE_SIZE;
|
||||
cubeDesc.num_mipmaps = GFX_IBL_CUBE_MIPS;
|
||||
cubeDesc.pixel_format = SG_PIXELFORMAT_RGBA16F;
|
||||
cubeDesc.sample_count = 1;
|
||||
cubeDesc.label = "ibl_sky_cube";
|
||||
s_ibl.skyCube = sg_make_image( &cubeDesc );
|
||||
|
||||
for ( int face = 0; face < 6; ++face )
|
||||
{
|
||||
for ( int mip = 0; mip < GFX_IBL_CUBE_MIPS; ++mip )
|
||||
{
|
||||
sg_view_desc fdesc = { 0 };
|
||||
fdesc.color_attachment.image = s_ibl.skyCube;
|
||||
fdesc.color_attachment.slice = face;
|
||||
fdesc.color_attachment.mip_level = mip;
|
||||
fdesc.label = "ibl_sky_cube_face_mip";
|
||||
s_ibl.skyCubeFaceMipAttachmentViews[face * GFX_IBL_CUBE_MIPS + mip] = sg_make_view( &fdesc );
|
||||
}
|
||||
}
|
||||
|
||||
sg_view_desc cubeSampleDesc = { 0 };
|
||||
cubeSampleDesc.texture.image = s_ibl.skyCube;
|
||||
cubeSampleDesc.label = "ibl_sky_cube_sample";
|
||||
s_ibl.skyCubeSampleView = sg_make_view( &cubeSampleDesc );
|
||||
|
||||
sg_sampler_desc cubeSampDesc = { 0 };
|
||||
cubeSampDesc.min_filter = SG_FILTER_LINEAR;
|
||||
cubeSampDesc.mag_filter = SG_FILTER_LINEAR;
|
||||
cubeSampDesc.mipmap_filter = SG_FILTER_LINEAR;
|
||||
cubeSampDesc.wrap_u = SG_WRAP_CLAMP_TO_EDGE;
|
||||
cubeSampDesc.wrap_v = SG_WRAP_CLAMP_TO_EDGE;
|
||||
cubeSampDesc.wrap_w = SG_WRAP_CLAMP_TO_EDGE;
|
||||
cubeSampDesc.label = "ibl_sky_cube_sampler";
|
||||
s_ibl.skyCubeSampler = sg_make_sampler( &cubeSampDesc );
|
||||
|
||||
// sky_to_cube pipeline
|
||||
s_ibl.skyToCubeShader = sg_make_shader( sky_to_cube_build_shader_desc( sg_query_backend() ) );
|
||||
|
||||
sg_pipeline_desc skyPipeDesc = { 0 };
|
||||
skyPipeDesc.shader = s_ibl.skyToCubeShader;
|
||||
skyPipeDesc.colors[0].pixel_format = SG_PIXELFORMAT_RGBA16F;
|
||||
skyPipeDesc.color_count = 1;
|
||||
skyPipeDesc.depth.pixel_format = SG_PIXELFORMAT_NONE;
|
||||
skyPipeDesc.depth.write_enabled = false;
|
||||
skyPipeDesc.depth.compare = SG_COMPAREFUNC_ALWAYS;
|
||||
skyPipeDesc.cull_mode = SG_CULLMODE_NONE;
|
||||
skyPipeDesc.face_winding = SG_FACEWINDING_CCW;
|
||||
skyPipeDesc.sample_count = 1;
|
||||
skyPipeDesc.label = "ibl_sky_to_cube_pipeline";
|
||||
s_ibl.skyToCubePipeline = sg_make_pipeline( &skyPipeDesc );
|
||||
|
||||
// prefilter pipeline
|
||||
s_ibl.prefilterShader = sg_make_shader( prefilter_build_shader_desc( sg_query_backend() ) );
|
||||
|
||||
sg_pipeline_desc prePipeDesc = { 0 };
|
||||
prePipeDesc.shader = s_ibl.prefilterShader;
|
||||
prePipeDesc.colors[0].pixel_format = SG_PIXELFORMAT_RGBA16F;
|
||||
prePipeDesc.color_count = 1;
|
||||
prePipeDesc.depth.pixel_format = SG_PIXELFORMAT_NONE;
|
||||
prePipeDesc.depth.write_enabled = false;
|
||||
prePipeDesc.depth.compare = SG_COMPAREFUNC_ALWAYS;
|
||||
prePipeDesc.cull_mode = SG_CULLMODE_NONE;
|
||||
prePipeDesc.face_winding = SG_FACEWINDING_CCW;
|
||||
prePipeDesc.sample_count = 1;
|
||||
prePipeDesc.label = "ibl_prefilter_pipeline";
|
||||
s_ibl.prefilterPipeline = sg_make_pipeline( &prePipeDesc );
|
||||
|
||||
// SH cache starts zero, RebuildImageBasedLightingIfDirty fills it.
|
||||
for ( int i = 0; i < 9; ++i )
|
||||
{
|
||||
s_ibl.shCoeffs[i] = b3Vec3_zero;
|
||||
}
|
||||
s_ibl.dirty = true;
|
||||
s_ibl.ready = true;
|
||||
}
|
||||
|
||||
void ShutdownImageBasedLighting( void )
|
||||
{
|
||||
if ( !s_ibl.ready )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
sg_destroy_pipeline( s_ibl.prefilterPipeline );
|
||||
sg_destroy_shader( s_ibl.prefilterShader );
|
||||
sg_destroy_pipeline( s_ibl.skyToCubePipeline );
|
||||
sg_destroy_shader( s_ibl.skyToCubeShader );
|
||||
|
||||
sg_destroy_sampler( s_ibl.skyCubeSampler );
|
||||
sg_destroy_view( s_ibl.skyCubeSampleView );
|
||||
for ( int i = 0; i < 6 * GFX_IBL_CUBE_MIPS; ++i )
|
||||
{
|
||||
sg_destroy_view( s_ibl.skyCubeFaceMipAttachmentViews[i] );
|
||||
}
|
||||
sg_destroy_image( s_ibl.skyCube );
|
||||
|
||||
sg_destroy_view( s_ibl.skyCubeRawSampleView );
|
||||
for ( int face = 0; face < 6; ++face )
|
||||
{
|
||||
sg_destroy_view( s_ibl.skyCubeRawFaceAttachmentViews[face] );
|
||||
}
|
||||
sg_destroy_image( s_ibl.skyCubeRaw );
|
||||
|
||||
sg_destroy_pipeline( s_ibl.brdfLutPipeline );
|
||||
sg_destroy_shader( s_ibl.brdfLutShader );
|
||||
sg_destroy_sampler( s_ibl.brdfLutSampler );
|
||||
sg_destroy_view( s_ibl.brdfLutSampleView );
|
||||
sg_destroy_view( s_ibl.brdfLutColorAttachmentView );
|
||||
sg_destroy_image( s_ibl.brdfLut );
|
||||
s_ibl.ready = false;
|
||||
}
|
||||
|
||||
void MarkIblDirty( void )
|
||||
{
|
||||
s_ibl.dirty = true;
|
||||
}
|
||||
|
||||
void RebuildImageBasedLightingIfDirty( b3Vec3 dirToSun, float turbidity )
|
||||
{
|
||||
if ( s_ibl.dirty == false || s_ibl.ready == false )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Renormalize just in case to avoid NaNs
|
||||
float lenSq = dirToSun.x * dirToSun.x + dirToSun.y * dirToSun.y + dirToSun.z * dirToSun.z;
|
||||
b3Vec3 sun = ( lenSq > 0.0f ) ? b3Normalize( dirToSun ) : b3Vec3_axisY;
|
||||
float fade = SkySunFadeWeight( sun );
|
||||
|
||||
sg_push_debug_group( "ibl_rebuild" );
|
||||
|
||||
GenerateSkyCube( sun, turbidity, fade );
|
||||
GeneratePrefilter();
|
||||
ProjectSkyToSh( sun, turbidity, fade );
|
||||
|
||||
sg_pop_debug_group();
|
||||
|
||||
s_ibl.dirty = false;
|
||||
}
|
||||
|
||||
sg_view GetIblSpecularView( void )
|
||||
{
|
||||
return s_ibl.skyCubeSampleView;
|
||||
}
|
||||
|
||||
sg_sampler GetIblSpecularSampler( void )
|
||||
{
|
||||
return s_ibl.skyCubeSampler;
|
||||
}
|
||||
|
||||
float GetIblSpecularMaxLod( void )
|
||||
{
|
||||
return (float)( GFX_IBL_CUBE_MIPS - 1 );
|
||||
}
|
||||
|
||||
sg_view GetIblBrdfLutView( void )
|
||||
{
|
||||
return s_ibl.brdfLutSampleView;
|
||||
}
|
||||
|
||||
sg_sampler GetIblBrdfLutSampler( void )
|
||||
{
|
||||
return s_ibl.brdfLutSampler;
|
||||
}
|
||||
|
||||
void GetIblSphericalHarmonicCoefficients( b3Vec3 out[9] )
|
||||
{
|
||||
for ( int i = 0; i < 9; ++i )
|
||||
{
|
||||
out[i] = s_ibl.shCoeffs[i];
|
||||
}
|
||||
}
|
||||
75
samples/gfx/ibl.h
Normal file
75
samples/gfx/ibl.h
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Image-based lighting from the procedural sky.
|
||||
//
|
||||
// Owns three persistent GPU resources plus a CPU-side cache:
|
||||
// * BRDF integration LUT (Karis split-sum, RG16F 256^2), generated once
|
||||
// at boot. Environment-independent.
|
||||
// * Sky cubemap with full GGX-prefiltered mip chain (RGBA16F 6x256^2),
|
||||
// regenerated when the sun direction or turbidity changes.
|
||||
// * Diffuse irradiance, 9 spherical-harmonic coefficients per channel,
|
||||
// evaluated on the CPU from the closed-form Preetham model. Cached
|
||||
// and uploaded into the lit pipelines' ub_pass each frame.
|
||||
//
|
||||
// The lit pipelines consume IBL by:
|
||||
// 1. Calling GetIblSphericalHarmonicCoefficients to get the diffuse SH (copied into ub_pass).
|
||||
// 2. Binding GetIblSpecularView / GetIblSpecularSampler for the
|
||||
// prefiltered cubemap and GetIblBrdfLutView / GetIblBrdfLutSampler
|
||||
// for the LUT.
|
||||
// 3. Passing GetIblSpecularMaxLod so the shader can scale roughness
|
||||
// to a mip level.
|
||||
//
|
||||
// MarkIblDirty + RebuildImageBasedLightingIfDirty are the rebuild hook. The
|
||||
// renderer marks dirty when SetSun is called, then calls
|
||||
// RebuildImageBasedLightingIfDirty at the top of DrawScene, the rebuild is a no-op
|
||||
// when not dirty.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "gfx/utility.h"
|
||||
#include "sokol_gfx.h"
|
||||
|
||||
#include <stdbool.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"
|
||||
{
|
||||
#endif
|
||||
|
||||
// Cube faces are 256^2, small enough for cheap regeneration on sun
|
||||
// change, large enough that mid-roughness prefilter mips read clean.
|
||||
// 7 mip levels covers all roughness from 0 (mip 0) to 1 (mip 6 = 4^2).
|
||||
#define GFX_IBL_CUBE_SIZE 256
|
||||
#define GFX_IBL_CUBE_MIPS 7
|
||||
#define GFX_IBL_LUT_SIZE 256
|
||||
|
||||
void InitImageBasedLighting( const sg_environment* env );
|
||||
void ShutdownImageBasedLighting( void );
|
||||
|
||||
// Mark the cube map + SH as stale. Cheap, the actual GPU regen + CPU SH
|
||||
// projection happens on the next RebuildImageBasedLightingIfDirty call.
|
||||
void MarkIblDirty( void );
|
||||
|
||||
// If dirty, regenerate the prefiltered sky cube and recompute SH from
|
||||
// the current sun direction + turbidity. Idempotent when clean.
|
||||
void RebuildImageBasedLightingIfDirty( b3Vec3 dirToSun, float turbidity );
|
||||
|
||||
// Prefiltered sky cubemap (mip 0 = mirror, mip GFX_IBL_CUBE_MIPS-1 =
|
||||
// fully rough). Bind once per lit-pipeline draw.
|
||||
sg_view GetIblSpecularView( void );
|
||||
sg_sampler GetIblSpecularSampler( void );
|
||||
float GetIblSpecularMaxLod( void );
|
||||
|
||||
// BRDF integration LUT. Sample with (n_dot_v, roughness) UVs.
|
||||
sg_view GetIblBrdfLutView( void );
|
||||
sg_sampler GetIblBrdfLutSampler( void );
|
||||
|
||||
// Copy the 9 RGB SH coefficients (band 0 through band 2) into `out`.
|
||||
// Layout matches the lit shaders' ub_pass.sh[9] slot, each coefficient
|
||||
// is a vec3, written as 9 consecutive b3Vec3.
|
||||
void GetIblSphericalHarmonicCoefficients( b3Vec3 out[9] );
|
||||
|
||||
#ifdef __cplusplus
|
||||
} // extern "C"
|
||||
#endif
|
||||
55
samples/gfx/keycodes.h
Normal file
55
samples/gfx/keycodes.h
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Named key / modifier / mouse-button aliases over sokol_app's codes, so
|
||||
// host Sample code can read input without including sokol_app.h directly.
|
||||
// render3d's own code uses SAPP_* directly; this header is for the port-side
|
||||
// host shell. The aliases are the codes actually exercised by the samples
|
||||
// (character + joint movers, scene hotkeys, picking).
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "sokol_app.h"
|
||||
|
||||
#include <assert.h>
|
||||
|
||||
enum
|
||||
{
|
||||
KEY_A = SAPP_KEYCODE_A,
|
||||
KEY_B = SAPP_KEYCODE_B,
|
||||
KEY_D = SAPP_KEYCODE_D,
|
||||
KEY_F = SAPP_KEYCODE_F,
|
||||
KEY_L = SAPP_KEYCODE_L,
|
||||
KEY_M = SAPP_KEYCODE_M,
|
||||
KEY_O = SAPP_KEYCODE_O,
|
||||
KEY_P = SAPP_KEYCODE_P,
|
||||
KEY_R = SAPP_KEYCODE_R,
|
||||
KEY_S = SAPP_KEYCODE_S,
|
||||
KEY_T = SAPP_KEYCODE_T,
|
||||
KEY_V = SAPP_KEYCODE_V,
|
||||
KEY_W = SAPP_KEYCODE_W,
|
||||
KEY_SPACE = SAPP_KEYCODE_SPACE,
|
||||
KEY_ESCAPE = SAPP_KEYCODE_ESCAPE,
|
||||
KEY_TAB = SAPP_KEYCODE_TAB,
|
||||
KEY_HOME = SAPP_KEYCODE_HOME,
|
||||
KEY_LEFT_SHIFT = SAPP_KEYCODE_LEFT_SHIFT,
|
||||
KEY_LEFT_BRACKET = SAPP_KEYCODE_LEFT_BRACKET,
|
||||
KEY_RIGHT_BRACKET = SAPP_KEYCODE_RIGHT_BRACKET,
|
||||
|
||||
MOD_SHIFT = SAPP_MODIFIER_SHIFT,
|
||||
MOD_CTRL = SAPP_MODIFIER_CTRL,
|
||||
MOD_ALT = SAPP_MODIFIER_ALT,
|
||||
|
||||
MOUSE_LEFT = SAPP_MOUSEBUTTON_LEFT,
|
||||
MOUSE_RIGHT = SAPP_MOUSEBUTTON_RIGHT,
|
||||
MOUSE_MIDDLE = SAPP_MOUSEBUTTON_MIDDLE,
|
||||
};
|
||||
|
||||
// Spot-check that the aliases still track sokol_app at compile time. One per
|
||||
// enum source (keycode, modifier, mouse button) is enough to catch a drift.
|
||||
// Cast to int so the compare doesn't trip C++'s deprecated cross-enum-type
|
||||
// comparison warning under -Werror.
|
||||
static_assert( (int)KEY_W == (int)SAPP_KEYCODE_W, "keycode alias drift" );
|
||||
static_assert( (int)KEY_ESCAPE == (int)SAPP_KEYCODE_ESCAPE, "keycode alias drift" );
|
||||
static_assert( (int)MOD_SHIFT == (int)SAPP_MODIFIER_SHIFT, "modifier alias drift" );
|
||||
static_assert( (int)MOUSE_LEFT == (int)SAPP_MOUSEBUTTON_LEFT, "mouse button alias drift" );
|
||||
403
samples/gfx/overlay.c
Normal file
403
samples/gfx/overlay.c
Normal file
|
|
@ -0,0 +1,403 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "gfx/overlay.h"
|
||||
|
||||
#include "gfx/arena.h"
|
||||
#include "overlay_line.glsl.h"
|
||||
#include "overlay_point.glsl.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#define MAX_LINES 65536
|
||||
#define MAX_POINTS 65536
|
||||
|
||||
// The overlay draws into the post-tone map target (swap chain or the offscreen
|
||||
// test target). Two slots cover both. The swap chain (has a depth
|
||||
// attachment) and the color-only offscreen target. Mirrors tonemap.c's
|
||||
// cache. Hitting the cap means a third color/depth pair appeared.
|
||||
#define OVERLAY_MAX_PIPELINES 2
|
||||
|
||||
static struct
|
||||
{
|
||||
Arena lineArena;
|
||||
Arena pointArena;
|
||||
|
||||
overlay_line_line_instance_t* lineBase;
|
||||
overlay_point_point_instance_t* pointBase;
|
||||
int lineCount;
|
||||
int pointCount;
|
||||
|
||||
sg_shader lineShader;
|
||||
sg_shader pointShader;
|
||||
|
||||
// Pipelines are created lazily per (color, depth) output-format pair.
|
||||
// The post-tone map target's format isn't known at init time.
|
||||
struct
|
||||
{
|
||||
sg_pixel_format colorFormat;
|
||||
sg_pixel_format depthFormat;
|
||||
sg_pipeline linePipeline;
|
||||
sg_pipeline pointPipeline;
|
||||
} pipelines[OVERLAY_MAX_PIPELINES];
|
||||
int pipelineCount;
|
||||
|
||||
sg_buffer lineInstBuf;
|
||||
sg_buffer pointInstBuf;
|
||||
sg_view lineInstView;
|
||||
sg_view pointInstView;
|
||||
|
||||
bool ready;
|
||||
} s_overlay;
|
||||
|
||||
static uint32_t PackThicknessFlag( OverlayThicknessUnit unit )
|
||||
{
|
||||
return ( unit == OVERLAY_THICKNESS_WORLD ) ? 1u : 0u;
|
||||
}
|
||||
|
||||
static uint32_t PackOcclusionFlag( OverlayOcclusionMode mode )
|
||||
{
|
||||
switch ( mode )
|
||||
{
|
||||
case OVERLAY_OCCLUSION_DIM:
|
||||
return 1u;
|
||||
case OVERLAY_OCCLUSION_DASHED:
|
||||
return 2u;
|
||||
case OVERLAY_OCCLUSION_HIDE: /* fallthrough */
|
||||
default:
|
||||
return 0u;
|
||||
}
|
||||
}
|
||||
|
||||
static Vec4 Premultiply( Vec4 c )
|
||||
{
|
||||
return MakeVec4( c.x * c.w, c.y * c.w, c.z * c.w, c.w );
|
||||
}
|
||||
|
||||
// Lazily create (and cache) the line + point pipelines for one output
|
||||
// format pair. Mirrors tonemap.c::ensurePipeline. The overlay draws
|
||||
// post-tonemap into the swapchain or an offscreen test target, both
|
||||
// single-sample, so sample_count is fixed at 1. The line/point shaders
|
||||
// carry their own SDF coverage AA. Returns false (and logs) if the cache
|
||||
// is full.
|
||||
static bool EnsurePipelines( sg_pixel_format colorFormat, sg_pixel_format depthFormat, sg_pipeline* outLine,
|
||||
sg_pipeline* outPoint )
|
||||
{
|
||||
for ( int i = 0; i < s_overlay.pipelineCount; ++i )
|
||||
{
|
||||
if ( s_overlay.pipelines[i].colorFormat == colorFormat && s_overlay.pipelines[i].depthFormat == depthFormat )
|
||||
{
|
||||
*outLine = s_overlay.pipelines[i].linePipeline;
|
||||
*outPoint = s_overlay.pipelines[i].pointPipeline;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if ( s_overlay.pipelineCount >= OVERLAY_MAX_PIPELINES )
|
||||
{
|
||||
fprintf( stderr, "[overlay] pipeline cache exhausted (max %d format pairs)\n", OVERLAY_MAX_PIPELINES );
|
||||
return false;
|
||||
}
|
||||
|
||||
// Line pipeline
|
||||
sg_pipeline_desc linePdesc = { 0 };
|
||||
linePdesc.shader = s_overlay.lineShader;
|
||||
// No VBO / no IBO, VS expands six vertices per instance from
|
||||
// gl_VertexIndex. Default layout (no attrs declared) is correct.
|
||||
linePdesc.index_type = SG_INDEXTYPE_NONE;
|
||||
linePdesc.cull_mode = SG_CULLMODE_NONE;
|
||||
linePdesc.colors[0].pixel_format = colorFormat;
|
||||
linePdesc.color_count = 1;
|
||||
// Premultiplied-alpha blend. CPU side premultiplies color.rgb by .a.
|
||||
linePdesc.colors[0].blend.enabled = true;
|
||||
linePdesc.colors[0].blend.src_factor_rgb = SG_BLENDFACTOR_ONE;
|
||||
linePdesc.colors[0].blend.dst_factor_rgb = SG_BLENDFACTOR_ONE_MINUS_SRC_ALPHA;
|
||||
linePdesc.colors[0].blend.op_rgb = SG_BLENDOP_ADD;
|
||||
linePdesc.colors[0].blend.src_factor_alpha = SG_BLENDFACTOR_ONE;
|
||||
linePdesc.colors[0].blend.dst_factor_alpha = SG_BLENDFACTOR_ONE_MINUS_SRC_ALPHA;
|
||||
linePdesc.colors[0].blend.op_alpha = SG_BLENDOP_ADD;
|
||||
// Depth-blind: compare ALWAYS, write off. pixel_format still has to
|
||||
// match the target's depth attachment (or NONE) for sokol's validation.
|
||||
linePdesc.depth.pixel_format = depthFormat;
|
||||
linePdesc.depth.compare = SG_COMPAREFUNC_ALWAYS;
|
||||
linePdesc.depth.write_enabled = false;
|
||||
linePdesc.sample_count = 1;
|
||||
linePdesc.label = "overlay_line_pipeline";
|
||||
const sg_pipeline linePip = sg_make_pipeline( &linePdesc );
|
||||
|
||||
// Point pipeline
|
||||
sg_pipeline_desc pointPdesc = { 0 };
|
||||
pointPdesc.shader = s_overlay.pointShader;
|
||||
pointPdesc.index_type = SG_INDEXTYPE_NONE;
|
||||
pointPdesc.cull_mode = SG_CULLMODE_NONE;
|
||||
pointPdesc.colors[0].pixel_format = colorFormat;
|
||||
pointPdesc.color_count = 1;
|
||||
pointPdesc.colors[0].blend.enabled = true;
|
||||
pointPdesc.colors[0].blend.src_factor_rgb = SG_BLENDFACTOR_ONE;
|
||||
pointPdesc.colors[0].blend.dst_factor_rgb = SG_BLENDFACTOR_ONE_MINUS_SRC_ALPHA;
|
||||
pointPdesc.colors[0].blend.op_rgb = SG_BLENDOP_ADD;
|
||||
pointPdesc.colors[0].blend.src_factor_alpha = SG_BLENDFACTOR_ONE;
|
||||
pointPdesc.colors[0].blend.dst_factor_alpha = SG_BLENDFACTOR_ONE_MINUS_SRC_ALPHA;
|
||||
pointPdesc.colors[0].blend.op_alpha = SG_BLENDOP_ADD;
|
||||
pointPdesc.depth.pixel_format = depthFormat;
|
||||
pointPdesc.depth.compare = SG_COMPAREFUNC_ALWAYS;
|
||||
pointPdesc.depth.write_enabled = false;
|
||||
pointPdesc.sample_count = 1;
|
||||
pointPdesc.label = "overlay_point_pipeline";
|
||||
const sg_pipeline pointPip = sg_make_pipeline( &pointPdesc );
|
||||
|
||||
s_overlay.pipelines[s_overlay.pipelineCount].colorFormat = colorFormat;
|
||||
s_overlay.pipelines[s_overlay.pipelineCount].depthFormat = depthFormat;
|
||||
s_overlay.pipelines[s_overlay.pipelineCount].linePipeline = linePip;
|
||||
s_overlay.pipelines[s_overlay.pipelineCount].pointPipeline = pointPip;
|
||||
++s_overlay.pipelineCount;
|
||||
|
||||
*outLine = linePip;
|
||||
*outPoint = pointPip;
|
||||
return true;
|
||||
}
|
||||
|
||||
void OverlayInit( void )
|
||||
{
|
||||
if ( s_overlay.ready )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ArenaInit( &s_overlay.lineArena, (size_t)MAX_LINES * sizeof( overlay_line_line_instance_t ) ) != 0 )
|
||||
{
|
||||
fprintf( stderr, "[overlay] failed to init line arena\n" );
|
||||
return;
|
||||
}
|
||||
if ( ArenaInit( &s_overlay.pointArena, (size_t)MAX_POINTS * sizeof( overlay_point_point_instance_t ) ) != 0 )
|
||||
{
|
||||
fprintf( stderr, "[overlay] failed to init point arena\n" );
|
||||
ArenaShutdown( &s_overlay.lineArena );
|
||||
return;
|
||||
}
|
||||
|
||||
// Line instance buffer + shader
|
||||
sg_buffer_desc lineBufDesc = { 0 };
|
||||
lineBufDesc.usage.storage_buffer = true;
|
||||
lineBufDesc.usage.stream_update = true;
|
||||
lineBufDesc.size = (size_t)MAX_LINES * sizeof( overlay_line_line_instance_t );
|
||||
lineBufDesc.label = "overlay_line_instances";
|
||||
s_overlay.lineInstBuf = sg_make_buffer( &lineBufDesc );
|
||||
|
||||
sg_view_desc lineViewDesc = { 0 };
|
||||
lineViewDesc.storage_buffer.buffer = s_overlay.lineInstBuf;
|
||||
lineViewDesc.label = "overlay_line_instances_view";
|
||||
s_overlay.lineInstView = sg_make_view( &lineViewDesc );
|
||||
|
||||
s_overlay.lineShader = sg_make_shader( overlay_line_prog_shader_desc( sg_query_backend() ) );
|
||||
|
||||
// Point instance buffer + shader
|
||||
sg_buffer_desc pointBufDesc = { 0 };
|
||||
pointBufDesc.usage.storage_buffer = true;
|
||||
pointBufDesc.usage.stream_update = true;
|
||||
pointBufDesc.size = (size_t)MAX_POINTS * sizeof( overlay_point_point_instance_t );
|
||||
pointBufDesc.label = "overlay_point_instances";
|
||||
s_overlay.pointInstBuf = sg_make_buffer( &pointBufDesc );
|
||||
|
||||
sg_view_desc pointViewDesc = { 0 };
|
||||
pointViewDesc.storage_buffer.buffer = s_overlay.pointInstBuf;
|
||||
pointViewDesc.label = "overlay_point_instances_view";
|
||||
s_overlay.pointInstView = sg_make_view( &pointViewDesc );
|
||||
|
||||
s_overlay.pointShader = sg_make_shader( overlay_point_prog_shader_desc( sg_query_backend() ) );
|
||||
|
||||
s_overlay.ready = true;
|
||||
}
|
||||
|
||||
void OverlayShutdown( void )
|
||||
{
|
||||
if ( !s_overlay.ready )
|
||||
{
|
||||
return;
|
||||
}
|
||||
for ( int i = 0; i < s_overlay.pipelineCount; ++i )
|
||||
{
|
||||
sg_destroy_pipeline( s_overlay.pipelines[i].linePipeline );
|
||||
sg_destroy_pipeline( s_overlay.pipelines[i].pointPipeline );
|
||||
s_overlay.pipelines[i].linePipeline.id = 0;
|
||||
s_overlay.pipelines[i].pointPipeline.id = 0;
|
||||
s_overlay.pipelines[i].colorFormat = SG_PIXELFORMAT_NONE;
|
||||
s_overlay.pipelines[i].depthFormat = SG_PIXELFORMAT_NONE;
|
||||
}
|
||||
s_overlay.pipelineCount = 0;
|
||||
sg_destroy_shader( s_overlay.lineShader );
|
||||
s_overlay.lineShader.id = 0;
|
||||
sg_destroy_shader( s_overlay.pointShader );
|
||||
s_overlay.pointShader.id = 0;
|
||||
sg_destroy_view( s_overlay.lineInstView );
|
||||
s_overlay.lineInstView.id = 0;
|
||||
sg_destroy_view( s_overlay.pointInstView );
|
||||
s_overlay.pointInstView.id = 0;
|
||||
sg_destroy_buffer( s_overlay.lineInstBuf );
|
||||
s_overlay.lineInstBuf.id = 0;
|
||||
sg_destroy_buffer( s_overlay.pointInstBuf );
|
||||
s_overlay.pointInstBuf.id = 0;
|
||||
ArenaShutdown( &s_overlay.lineArena );
|
||||
ArenaShutdown( &s_overlay.pointArena );
|
||||
s_overlay.lineBase = NULL;
|
||||
s_overlay.pointBase = NULL;
|
||||
s_overlay.lineCount = 0;
|
||||
s_overlay.pointCount = 0;
|
||||
s_overlay.ready = false;
|
||||
}
|
||||
|
||||
void OverlayResetFrame( void )
|
||||
{
|
||||
ArenaReset( &s_overlay.lineArena );
|
||||
ArenaReset( &s_overlay.pointArena );
|
||||
s_overlay.lineBase = NULL;
|
||||
s_overlay.pointBase = NULL;
|
||||
s_overlay.lineCount = 0;
|
||||
s_overlay.pointCount = 0;
|
||||
}
|
||||
|
||||
int OverlayLineCount( void )
|
||||
{
|
||||
return s_overlay.lineCount;
|
||||
}
|
||||
int OverlayPointCount( void )
|
||||
{
|
||||
return s_overlay.pointCount;
|
||||
}
|
||||
|
||||
void OverlayAppendLine( b3Vec3 a, b3Vec3 b, Vec4 linearColor, float thickness, OverlayThicknessUnit thicknessUnit,
|
||||
OverlayOcclusionMode occlusionMode )
|
||||
{
|
||||
if ( s_overlay.lineCount >= MAX_LINES )
|
||||
{
|
||||
return;
|
||||
}
|
||||
overlay_line_line_instance_t* inst = (overlay_line_line_instance_t*)ArenaAlloc(
|
||||
&s_overlay.lineArena, sizeof( overlay_line_line_instance_t ), _Alignof( overlay_line_line_instance_t ) );
|
||||
if ( !inst )
|
||||
{
|
||||
return;
|
||||
}
|
||||
if ( s_overlay.lineCount == 0 )
|
||||
{
|
||||
s_overlay.lineBase = inst;
|
||||
}
|
||||
s_overlay.lineCount++;
|
||||
|
||||
const Vec4 cpremul = Premultiply( linearColor );
|
||||
inst->a = MakeVec4( a.x, a.y, a.z, thickness );
|
||||
inst->b = MakeVec4( b.x, b.y, b.z, 0.0f );
|
||||
inst->color = cpremul;
|
||||
inst->flags[0] = PackThicknessFlag( thicknessUnit );
|
||||
inst->flags[1] = PackOcclusionFlag( occlusionMode );
|
||||
inst->flags[2] = 0;
|
||||
inst->flags[3] = 0;
|
||||
}
|
||||
|
||||
void OverlayAppendPoint( b3Vec3 p, Vec4 linearColor, float size, OverlayThicknessUnit sizeUnit, OverlayOcclusionMode occlusionMode )
|
||||
{
|
||||
if ( s_overlay.pointCount >= MAX_POINTS )
|
||||
{
|
||||
return;
|
||||
}
|
||||
overlay_point_point_instance_t* inst = (overlay_point_point_instance_t*)ArenaAlloc(
|
||||
&s_overlay.pointArena, sizeof( overlay_point_point_instance_t ), _Alignof( overlay_point_point_instance_t ) );
|
||||
if ( !inst )
|
||||
{
|
||||
return;
|
||||
}
|
||||
if ( s_overlay.pointCount == 0 )
|
||||
{
|
||||
s_overlay.pointBase = inst;
|
||||
}
|
||||
s_overlay.pointCount++;
|
||||
|
||||
const Vec4 cpremul = Premultiply( linearColor );
|
||||
inst->p = MakeVec4( p.x, p.y, p.z, size );
|
||||
inst->color = cpremul;
|
||||
inst->flags[0] = PackThicknessFlag( sizeUnit );
|
||||
inst->flags[1] = PackOcclusionFlag( occlusionMode );
|
||||
inst->flags[2] = 0;
|
||||
inst->flags[3] = 0;
|
||||
}
|
||||
|
||||
void OverlaySubmit( int width, int height, const Mat4* view, const Mat4* viewInv, const Mat4* proj, const Mat4* projInv,
|
||||
b3Vec3 cameraPos, float time,
|
||||
sg_view linearDepthView, sg_sampler linearDepthSampler, sg_pixel_format colorFormat,
|
||||
sg_pixel_format depthFormat )
|
||||
{
|
||||
if ( !s_overlay.ready )
|
||||
{
|
||||
return;
|
||||
}
|
||||
if ( s_overlay.lineCount == 0 && s_overlay.pointCount == 0 )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
sg_pipeline linePipeline = { 0 };
|
||||
sg_pipeline pointPipeline = { 0 };
|
||||
if ( !EnsurePipelines( colorFormat, depthFormat, &linePipeline, &pointPipeline ) )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Build the shared ub_frame data. Both shaders' reflected ub_frame
|
||||
// structs have the same layout (declared identically in both .glsl),
|
||||
// so one struct populates both via sg_apply_uniforms.
|
||||
const Mat4 view_proj = MulMM4( *proj, *view );
|
||||
// inv(P*V) = inv(V)*inv(P). The camera builds both inverses from the
|
||||
// same parameters as the forward matrices, so this is a single multiply
|
||||
// instead of a general 4x4 inversion.
|
||||
const Mat4 inv_view_proj = MulMM4( *viewInv, *projInv );
|
||||
const float w = (float)width;
|
||||
const float h = (float)height;
|
||||
overlay_line_ub_frame_t ub = { 0 };
|
||||
ub.view = *view;
|
||||
ub.proj = *proj;
|
||||
ub.view_proj = view_proj;
|
||||
ub.inv_view_proj = inv_view_proj;
|
||||
ub.camera_pos = MakeVec4( cameraPos.x, cameraPos.y, cameraPos.z, time );
|
||||
ub.viewport = MakeVec4( w, h, w > 0.0f ? 1.0f / w : 0.0f, h > 0.0f ? 1.0f / h : 0.0f );
|
||||
|
||||
// Lines
|
||||
if ( s_overlay.lineCount > 0 )
|
||||
{
|
||||
sg_range r;
|
||||
r.ptr = s_overlay.lineBase;
|
||||
r.size = (size_t)s_overlay.lineCount * sizeof( overlay_line_line_instance_t );
|
||||
sg_update_buffer( s_overlay.lineInstBuf, &r );
|
||||
|
||||
sg_apply_pipeline( linePipeline );
|
||||
sg_bindings b = { 0 };
|
||||
b.views[VIEW_overlay_line_line_instances] = s_overlay.lineInstView;
|
||||
b.views[VIEW_overlay_line_tex_depth] = linearDepthView;
|
||||
b.samplers[SMP_overlay_line_smp_depth] = linearDepthSampler;
|
||||
sg_apply_bindings( &b );
|
||||
sg_apply_uniforms( UB_overlay_line_ub_frame, &SG_RANGE( ub ) );
|
||||
sg_draw( 0, 6, s_overlay.lineCount );
|
||||
}
|
||||
|
||||
// Points
|
||||
if ( s_overlay.pointCount > 0 )
|
||||
{
|
||||
sg_range r;
|
||||
r.ptr = s_overlay.pointBase;
|
||||
r.size = (size_t)s_overlay.pointCount * sizeof( overlay_point_point_instance_t );
|
||||
sg_update_buffer( s_overlay.pointInstBuf, &r );
|
||||
|
||||
// Same ub_frame data. The generated _t names differ but the layout
|
||||
// matches byte-for-byte (both glsl files declare identical ub_frame).
|
||||
overlay_point_ub_frame_t pub;
|
||||
memcpy( &pub, &ub, sizeof( pub ) );
|
||||
|
||||
sg_apply_pipeline( pointPipeline );
|
||||
sg_bindings b = { 0 };
|
||||
b.views[VIEW_overlay_point_point_instances] = s_overlay.pointInstView;
|
||||
b.views[VIEW_overlay_point_tex_depth] = linearDepthView;
|
||||
b.samplers[SMP_overlay_point_smp_depth] = linearDepthSampler;
|
||||
sg_apply_bindings( &b );
|
||||
sg_apply_uniforms( UB_overlay_point_ub_frame, &SG_RANGE( pub ) );
|
||||
sg_draw( 0, 6, s_overlay.pointCount );
|
||||
}
|
||||
}
|
||||
75
samples/gfx/overlay.h
Normal file
75
samples/gfx/overlay.h
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Overlay pipeline, lines and points.
|
||||
//
|
||||
// Owns two pipelines (overlay_line, overlay_point), two per-frame instance
|
||||
// arenas, and the upload-side storage buffers. The renderer wires the
|
||||
// per-frame reset and the draw call.
|
||||
//
|
||||
// Pass placement: the renderer calls OverlaySubmit in the post-tone map
|
||||
// pass, the same swap chain (or offscreen test) pass that AgX tone map and
|
||||
// the highlight outline write to, after both and before sg_end_pass. So
|
||||
// overlay fragments are display-referred: a submitted color reaches the
|
||||
// screen verbatim, NOT run through exposure + AgX. This keeps debug
|
||||
// overlays consistent with the ImGui text labels (also post-tone map) and
|
||||
// makes their colors WYSIWYG. The target is single-sample, the line/point
|
||||
// shaders carry their own SDF coverage AA, so MSAA isn't needed.
|
||||
//
|
||||
// Depth-test = ALWAYS (depth-write off), the fragment shader samples the
|
||||
// GTAO linear-depth pre-pass for the DIM / DASHED / HIDE occlusion-mode
|
||||
// branches. Pipelines are created lazily per output format pair (the
|
||||
// post-tone map target's format isn't known until submit).
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "gfx/draw_overlay.h"
|
||||
#include "gfx/utility.h"
|
||||
#include "sokol_gfx.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"
|
||||
{
|
||||
#endif
|
||||
|
||||
void OverlayInit( void );
|
||||
void OverlayShutdown( void );
|
||||
|
||||
// Reset both per-primitive instance arenas. Called from
|
||||
// ResetFrameArena once per frame before any append.
|
||||
void OverlayResetFrame( void );
|
||||
|
||||
// Append an overlay line. Dropped if the arena overflows.
|
||||
void OverlayAppendLine( b3Vec3 a, b3Vec3 b, Vec4 linearColor, float thickness, OverlayThicknessUnit thicknessUnit,
|
||||
OverlayOcclusionMode occlusionMode );
|
||||
|
||||
// Append an overlay point. Dropped if the arena overflows.
|
||||
void OverlayAppendPoint( b3Vec3 p, Vec4 linearColor, float size, OverlayThicknessUnit sizeUnit, OverlayOcclusionMode occlusionMode );
|
||||
|
||||
// Encode line + point draws into the currently-open render pass. The
|
||||
// renderer calls this once per frame in the post-tone map pass, after
|
||||
// tone map + the highlight outline. No-op if both arenas are empty.
|
||||
//
|
||||
// width, height: viewport size in pixels (for ub_frame.viewport).
|
||||
// view, viewInv, proj, projInv: camera matrices paired with their inverses
|
||||
// (produced by the camera alongside the forward matrices). The overlay
|
||||
// shaders read view_proj and inv_view_proj from ub_frame, inv_view_proj is
|
||||
// built here as viewInv * projInv, no matrix inversion at runtime.
|
||||
// cameraPos: world-space camera position
|
||||
// time: seconds since InitRenderer, packed into camera_pos.w.
|
||||
// linearDepthView: texture view over the R32F linear-depth pre-pass target.
|
||||
// linearDepthSampler: matching sampler (existing GetAOLinearSampler reused).
|
||||
// colorFormat: pixel format of the pass's color attachment.
|
||||
// depthFormat: pixel format of the pass's depth attachment, or
|
||||
// SG_PIXELFORMAT_NONE for a color-only target. Both select/build the cached pipeline pair.
|
||||
void OverlaySubmit( int width, int height, const Mat4* view, const Mat4* viewInv, const Mat4* proj, const Mat4* projInv,
|
||||
b3Vec3 cameraPos, float time, sg_view linearDepthView, sg_sampler linearDepthSampler, sg_pixel_format colorFormat,
|
||||
sg_pixel_format depthFormat );
|
||||
|
||||
// Per-frame primitive counts
|
||||
int OverlayLineCount( void );
|
||||
int OverlayPointCount( void );
|
||||
|
||||
#ifdef __cplusplus
|
||||
} // extern "C"
|
||||
#endif
|
||||
67
samples/gfx/picking.h
Normal file
67
samples/gfx/picking.h
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Pick-ray helper.
|
||||
//
|
||||
// Build a world-space ray from a screen-pixel coordinate using the latched
|
||||
// camera state set each frame by RenderFrame / RenderFrameOffscreen.
|
||||
// Pure-C / header-only so the demo app and the Box3D adapter share one
|
||||
// implementation without dragging the rest of the renderer in.
|
||||
//
|
||||
// Conventions match the rest of the renderer:
|
||||
// * Column-major matrices, multiplied as M * v
|
||||
// * Reverse-Z clip space (near maps to clip-Z = +w, far to 0)
|
||||
// * Mouse (x, y) in framebuffer pixels with origin at the top-left
|
||||
// (Y grows downward, matches ImGui and sokol_app)
|
||||
//
|
||||
// Output matches Box3D's `b3World_CastRayClosest(origin, translation, ...)`
|
||||
// convention: `*outOrigin` is the world point on the near plane along the
|
||||
// pick ray, and `*outTranslation` is the unnormalized vector pointing from
|
||||
// the near to the far plane along that ray. Pass them straight through.
|
||||
//
|
||||
// Returns false (and leaves outputs untouched) when the matrices are
|
||||
// degenerate or the camera state hasn't been initialized (viewportW/H 0).
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "gfx/renderer.h"
|
||||
#include "gfx/utility.h"
|
||||
|
||||
#include <stdbool.h>
|
||||
|
||||
static inline bool BuildPickRay( float mouseX, float mouseY, b3Vec3* outOrigin, b3Vec3* outTranslation )
|
||||
{
|
||||
CameraState s = GetCameraState();
|
||||
if ( s.viewportW <= 0 || s.viewportH <= 0 )
|
||||
return false;
|
||||
|
||||
// Pixel -> NDC. Origin top-left, Y down. NDC has Y up, X right.
|
||||
const float ndcX = ( 2.0f * mouseX / (float)s.viewportW ) - 1.0f;
|
||||
const float ndcY = 1.0f - ( 2.0f * mouseY / (float)s.viewportH );
|
||||
|
||||
// Reverse-Z: near plane z = 1, far plane z = 0 in NDC. We pick those
|
||||
// two clip-space points (w = 1) and run them through the inverse VP to
|
||||
// recover world-space. inv(P*V) = inv(V)*inv(P) = viewInv * projInv,
|
||||
// both produced by the camera alongside their forward matrices, no
|
||||
// runtime matrix inversion.
|
||||
const Mat4 invVP = MulMM4( s.viewInv, s.projInv );
|
||||
|
||||
const Vec4 clipN = MakeVec4( ndcX, ndcY, 1.0f, 1.0f );
|
||||
const Vec4 clipF = MakeVec4( ndcX, ndcY, 0.0f, 1.0f );
|
||||
|
||||
const Vec4 wN = MulMV4( invVP, clipN );
|
||||
const Vec4 wF = MulMV4( invVP, clipF );
|
||||
|
||||
if ( wN.w == 0.0f || wF.w == 0.0f )
|
||||
return false;
|
||||
|
||||
const float invWN = 1.0f / wN.w;
|
||||
const float invWF = 1.0f / wF.w;
|
||||
|
||||
b3Vec3 nearWorld = { wN.x * invWN, wN.y * invWN, wN.z * invWN };
|
||||
b3Vec3 farWorld = { wF.x * invWF, wF.y * invWF, wF.z * invWF };
|
||||
|
||||
*outOrigin = nearWorld;
|
||||
*outTranslation = b3Sub( farWorld, nearWorld );
|
||||
return true;
|
||||
}
|
||||
56
samples/gfx/projection.h
Normal file
56
samples/gfx/projection.h
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
// World-to-screen projection helper used by the in-world text overlay
|
||||
// and its unit test. Header-only / pure C so the unit test can pull it in
|
||||
// without dragging the rest of the renderer along.
|
||||
//
|
||||
// Convention matches the renderer: column-major matrices multiplied as
|
||||
// `M * v`, reverse-Z clip space (near maps to clip-Z = +w, far to 0), Y-up
|
||||
// view space. Screen pixels follow ImGui's origin convention: (0,0) at the
|
||||
// top-left of the viewport, Y growing downward.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "gfx/utility.h"
|
||||
|
||||
#include <stdbool.h>
|
||||
|
||||
// Project a world-space point through `view`/`proj` for a viewport of size
|
||||
// `viewportW` x `viewportH` pixels. Writes the screen-pixel position into
|
||||
// `*outScreenX`/`*outScreenY` and returns true when the point is visible
|
||||
// (in front of the near plane and inside the X/Y frustum). Returns false
|
||||
// without writing the outputs when the point is behind the camera (clip.w
|
||||
// non-positive) or outside the frustum in either axis.
|
||||
static inline bool ProjectWorldToScreen( Mat4 view, Mat4 proj, int viewportW, int viewportH, b3Vec3 worldPos, float* outScreenX,
|
||||
float* outScreenY )
|
||||
{
|
||||
Vec4 world = MakeVec4( worldPos.x, worldPos.y, worldPos.z, 1.0f );
|
||||
Vec4 viewP = MulMV4( view, world );
|
||||
Vec4 clip = MulMV4( proj, viewP );
|
||||
|
||||
// Reverse-Z still uses a positive w for "in front of camera", w is the
|
||||
// view-space depth before the proj divide. Reject behind-camera and
|
||||
// numerically degenerate cases together.
|
||||
if ( clip.w <= 1e-6f )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
const float invW = 1.0f / clip.w;
|
||||
const float ndcX = clip.x * invW;
|
||||
const float ndcY = clip.y * invW;
|
||||
|
||||
if ( ndcX < -1.0f || ndcX > 1.0f )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( ndcY < -1.0f || ndcY > 1.0f )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// NDC (-1..1, Y up) -> screen pixels (0..W, 0..H, Y down).
|
||||
*outScreenX = ( ndcX * 0.5f + 0.5f ) * (float)viewportW;
|
||||
*outScreenY = ( 1.0f - ( ndcY * 0.5f + 0.5f ) ) * (float)viewportH;
|
||||
|
||||
return true;
|
||||
}
|
||||
190
samples/gfx/qsort.h
Normal file
190
samples/gfx/qsort.h
Normal file
|
|
@ -0,0 +1,190 @@
|
|||
/*
|
||||
* Copyright (c) 2013, 2017 Alexey Tourbin
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
* SOFTWARE.
|
||||
*/
|
||||
|
||||
/*
|
||||
* Vendored from github.com/svpv/qsort (commit 32667a20d3725f62ab2c3def00fcaa96ce2a5508,
|
||||
* last upstream commit Jan 2019). Header-only inline-sort macro; small enough
|
||||
* and stable enough that paying for a FetchContent pin no longer earns its keep.
|
||||
*
|
||||
* This is a traditional Quicksort implementation which mostly follows
|
||||
* [Sedgewick 1978]. Sorting is performed entirely on array indices,
|
||||
* while actual access to the array elements is abstracted out with the
|
||||
* user-defined `LESS` and `SWAP` primitives.
|
||||
*
|
||||
* Synopsis:
|
||||
* QSORT(N, LESS, SWAP);
|
||||
* where
|
||||
* N - the number of elements in A[];
|
||||
* LESS(i, j) - compares A[i] to A[j];
|
||||
* SWAP(i, j) - exchanges A[i] with A[j].
|
||||
*/
|
||||
|
||||
#ifndef QSORT_H
|
||||
#define QSORT_H
|
||||
|
||||
/* Sort 3 elements. */
|
||||
#define Q_SORT3(q_a1, q_a2, q_a3, Q_LESS, Q_SWAP) \
|
||||
do { \
|
||||
if (Q_LESS(q_a2, q_a1)) { \
|
||||
if (Q_LESS(q_a3, q_a2)) \
|
||||
Q_SWAP(q_a1, q_a3); \
|
||||
else { \
|
||||
Q_SWAP(q_a1, q_a2); \
|
||||
if (Q_LESS(q_a3, q_a2)) \
|
||||
Q_SWAP(q_a2, q_a3); \
|
||||
} \
|
||||
} \
|
||||
else if (Q_LESS(q_a3, q_a2)) { \
|
||||
Q_SWAP(q_a2, q_a3); \
|
||||
if (Q_LESS(q_a2, q_a1)) \
|
||||
Q_SWAP(q_a1, q_a2); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
/* Partition [q_l,q_r] around a pivot. After partitioning,
|
||||
* [q_l,q_j] are the elements that are less than or equal to the pivot,
|
||||
* while [q_i,q_r] are the elements greater than or equal to the pivot. */
|
||||
#define Q_PARTITION(q_l, q_r, q_i, q_j, Q_UINT, Q_LESS, Q_SWAP) \
|
||||
do { \
|
||||
/* The middle element, not to be confused with the median. */ \
|
||||
Q_UINT q_m = q_l + ((q_r - q_l) >> 1); \
|
||||
/* Reorder the second, the middle, and the last items. \
|
||||
* As [Edelkamp Weiss 2016] explain, using the second element \
|
||||
* instead of the first one helps avoid bad behaviour for \
|
||||
* decreasingly sorted arrays. This method is used in recent \
|
||||
* versions of gcc's std::sort, see gcc bug 58437#c13, although \
|
||||
* the details are somewhat different (cf. #c14). */ \
|
||||
Q_SORT3(q_l + 1, q_m, q_r, Q_LESS, Q_SWAP); \
|
||||
/* Place the median at the beginning. */ \
|
||||
Q_SWAP(q_l, q_m); \
|
||||
/* Partition [q_l+2, q_r-1] around the median which is in q_l. \
|
||||
* q_i and q_j are initially off by one, they get decremented \
|
||||
* in the do-while loops. */ \
|
||||
q_i = q_l + 1; q_j = q_r; \
|
||||
while (1) { \
|
||||
do q_i++; while (Q_LESS(q_i, q_l)); \
|
||||
do q_j--; while (Q_LESS(q_l, q_j)); \
|
||||
if (q_i >= q_j) break; /* Sedgewick says "until j < i" */ \
|
||||
Q_SWAP(q_i, q_j); \
|
||||
} \
|
||||
/* Compensate for the i==j case. */ \
|
||||
q_i = q_j + 1; \
|
||||
/* Put the median to its final place. */ \
|
||||
Q_SWAP(q_l, q_j); \
|
||||
/* The median is not part of the left subfile. */ \
|
||||
q_j--; \
|
||||
} while (0)
|
||||
|
||||
/* Insertion sort is applied to small subfiles - this is contrary to
|
||||
* Sedgewick's suggestion to run a separate insertion sort pass after
|
||||
* the partitioning is done. The reason I don't like a separate pass
|
||||
* is that it triggers extra comparisons, because it can't see that the
|
||||
* medians are already in their final positions and need not be rechecked.
|
||||
* Since I do not assume that comparisons are cheap, I also do not try
|
||||
* to eliminate the (q_j > q_l) boundary check. */
|
||||
#define Q_INSERTION_SORT(q_l, q_r, Q_UINT, Q_LESS, Q_SWAP) \
|
||||
do { \
|
||||
Q_UINT q_i, q_j; \
|
||||
/* For each item starting with the second... */ \
|
||||
for (q_i = q_l + 1; q_i <= q_r; q_i++) \
|
||||
/* move it down the array so that the first part is sorted. */ \
|
||||
for (q_j = q_i; q_j > q_l && (Q_LESS(q_j, q_j - 1)); q_j--) \
|
||||
Q_SWAP(q_j, q_j - 1); \
|
||||
} while (0)
|
||||
|
||||
/* When the size of [q_l,q_r], i.e. q_r-q_l+1, is greater than or equal to
|
||||
* Q_THRESH, the algorithm performs recursive partitioning. When the size
|
||||
* drops below Q_THRESH, the algorithm switches to insertion sort.
|
||||
* The minimum valid value is probably 5 (with 5 items, the second and
|
||||
* the middle items, the middle itself being rounded down, are distinct). */
|
||||
#define Q_THRESH 16
|
||||
|
||||
/* The main loop. */
|
||||
#define Q_LOOP(Q_UINT, Q_N, Q_LESS, Q_SWAP) \
|
||||
do { \
|
||||
Q_UINT q_l = 0; \
|
||||
Q_UINT q_r = (Q_N) - 1; \
|
||||
Q_UINT q_sp = 0; /* the number of frames pushed to the stack */ \
|
||||
struct { Q_UINT q_l, q_r; } \
|
||||
/* On 32-bit platforms, to sort a "char[3GB+]" array, \
|
||||
* it may take full 32 stack frames. On 64-bit CPUs, \
|
||||
* though, the address space is limited to 48 bits. \
|
||||
* The usage is further reduced if Q_N has a 32-bit type. */ \
|
||||
q_st[sizeof(Q_UINT) > 4 && sizeof(Q_N) > 4 ? 48 : 32]; \
|
||||
while (1) { \
|
||||
if (q_r - q_l + 1 >= Q_THRESH) { \
|
||||
Q_UINT q_i, q_j; \
|
||||
Q_PARTITION(q_l, q_r, q_i, q_j, Q_UINT, Q_LESS, Q_SWAP); \
|
||||
/* Now have two subfiles: [q_l,q_j] and [q_i,q_r]. \
|
||||
* Dealing with them depends on which one is bigger. */ \
|
||||
if (q_j - q_l >= q_r - q_i) \
|
||||
Q_SUBFILES(q_l, q_j, q_i, q_r); \
|
||||
else \
|
||||
Q_SUBFILES(q_i, q_r, q_l, q_j); \
|
||||
} \
|
||||
else { \
|
||||
Q_INSERTION_SORT(q_l, q_r, Q_UINT, Q_LESS, Q_SWAP); \
|
||||
/* Pop subfiles from the stack, until it gets empty. */ \
|
||||
if (q_sp == 0) break; \
|
||||
q_sp--; \
|
||||
q_l = q_st[q_sp].q_l; \
|
||||
q_r = q_st[q_sp].q_r; \
|
||||
} \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
/* The missing part: dealing with subfiles.
|
||||
* Assumes that the first subfile is not smaller than the second. */
|
||||
#define Q_SUBFILES(q_l1, q_r1, q_l2, q_r2) \
|
||||
do { \
|
||||
/* If the second subfile is only a single element, it needs \
|
||||
* no further processing. The first subfile will be processed \
|
||||
* on the next iteration (both subfiles cannot be only a single \
|
||||
* element, due to Q_THRESH). */ \
|
||||
if (q_l2 == q_r2) { \
|
||||
q_l = q_l1; \
|
||||
q_r = q_r1; \
|
||||
} \
|
||||
else { \
|
||||
/* Otherwise, both subfiles need processing. \
|
||||
* Push the larger subfile onto the stack. */ \
|
||||
q_st[q_sp].q_l = q_l1; \
|
||||
q_st[q_sp].q_r = q_r1; \
|
||||
q_sp++; \
|
||||
/* Process the smaller subfile on the next iteration. */ \
|
||||
q_l = q_l2; \
|
||||
q_r = q_r2; \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
/* And now, ladies and gentlemen, may I proudly present to you... */
|
||||
#define QSORT(Q_N, Q_LESS, Q_SWAP) \
|
||||
do { \
|
||||
if ((Q_N) > 1) \
|
||||
/* We could check sizeof(Q_N) and use "unsigned", but at least \
|
||||
* on x86_64, this has the performance penalty of up to 5%. */ \
|
||||
Q_LOOP(unsigned long, Q_N, Q_LESS, Q_SWAP); \
|
||||
} while (0)
|
||||
|
||||
#endif
|
||||
|
||||
/* ex:set ts=8 sts=4 sw=4 noet: */
|
||||
3087
samples/gfx/renderer.c
Normal file
3087
samples/gfx/renderer.c
Normal file
File diff suppressed because it is too large
Load diff
179
samples/gfx/renderer.h
Normal file
179
samples/gfx/renderer.h
Normal file
|
|
@ -0,0 +1,179 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "gfx/draw_overlay.h"
|
||||
#include "gfx/edges.h"
|
||||
#include "gfx/highlight_outline.h"
|
||||
#include "gfx/utility.h"
|
||||
#include "sokol_gfx.h"
|
||||
|
||||
#include <stdbool.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"
|
||||
{
|
||||
#endif
|
||||
|
||||
typedef struct FrameInput
|
||||
{
|
||||
Mat4 view;
|
||||
Mat4 viewInv;
|
||||
Mat4 proj;
|
||||
Mat4 projInv;
|
||||
b3Vec3 cameraPosition;
|
||||
|
||||
// seconds since InitRenderer
|
||||
float time;
|
||||
|
||||
// 0 = lit, 1 = view-space depth grayscale, 2 = CSM cascade index,
|
||||
// 3 = view-space normal (RGB, [-1,1] mapped to [0,1]),
|
||||
// 4 = raw GTAO ambient-occlusion (grayscale, post-upsample).
|
||||
int debugMode;
|
||||
|
||||
// cascade passes still clear to depth=1.0
|
||||
bool disableShadows;
|
||||
|
||||
// depth pre-pass + trace + upsample skipped
|
||||
// the full-res AO target is cleared to 1.0 (no occlusion) instead
|
||||
bool disableAmbientOcclusion;
|
||||
} FrameInput;
|
||||
|
||||
// Directional light. The renderer owns one. Defaults are set in InitRenderer:
|
||||
// dirToSun normalized from (0.5, 0.8, 0.4), color (1.0, 0.95, 0.85),
|
||||
// ambient 0.10. Apps can override via SetSun before any draw call.
|
||||
// dirToSun is normalized internally, caller need not pre-normalize.
|
||||
typedef struct Sun
|
||||
{
|
||||
b3Vec3 dirToSun; // world-space direction TO the sun
|
||||
b3Vec3 color; // RGB intensity, multiplied by N.L for direct light
|
||||
float ambient; // ambient strength added to direct light (0..1 typical)
|
||||
float strength; // multiplies color [0,1]
|
||||
} Sun;
|
||||
|
||||
void InitRenderer( const sg_environment* env );
|
||||
|
||||
// Sun settings
|
||||
void SetSun( Sun sun );
|
||||
Sun GetSun( void );
|
||||
|
||||
// Exposure stop applied by the AgX tone map pass (final image multiplied
|
||||
// by pow(2, ev) before tone map).
|
||||
void SetExposure( float ev );
|
||||
float GetExposure( void );
|
||||
|
||||
// AgX-look saturation applied by the tone map pass after the AgX sigmoid.
|
||||
// 1.0 (default) is AgX's stock Standard look. >1.0 counteracts the
|
||||
// path-to-white desaturation for punchier debug colors, <1.0 mutes them.
|
||||
void SetToneMapSaturation( float saturation );
|
||||
float GetToneMapSaturation( void );
|
||||
|
||||
// Preetham turbidity, fed to both the sky pass and the IBL cube map rebuild.
|
||||
void SetSkyTurbidity( float t );
|
||||
float GetSkyTurbidity( void );
|
||||
|
||||
// Toggle image-based lighting (IBL). Ambient comes from the procedural sky
|
||||
// (diffuse SH + prefiltered specular). When disabled, lit shapes fall back
|
||||
// to flat ambient, base_color * sun.ambient. Does not affect the sky background.
|
||||
void SetIblEnabled( bool enabled );
|
||||
bool GetIblEnabled( void );
|
||||
|
||||
void SetEdgeOverlayParams( const EdgeOverlayParams* settings );
|
||||
EdgeOverlayParams GetEdgeOverlayParams( void );
|
||||
|
||||
// Body highlighting parameters
|
||||
void SetHighlightParams( const HighlightParams* params );
|
||||
HighlightParams GetHighlightParams( void );
|
||||
|
||||
typedef struct
|
||||
{
|
||||
int cubeCount;
|
||||
int sphereCount;
|
||||
int capsuleCount;
|
||||
int cubeCountXp;
|
||||
int sphereCountXp;
|
||||
int capsuleCountXp;
|
||||
int geomInstanceCount; // sum across all draw spans (opaque)
|
||||
int geomInstanceCountXp;
|
||||
int geomSpanCount;
|
||||
int lineCount;
|
||||
int pointCount;
|
||||
int drawCallCount; // approximate, one per non-empty shape stream + spans
|
||||
float frameTimeMs; // last RenderFrame cost
|
||||
} RenderStats;
|
||||
|
||||
RenderStats GetRenderStats( void );
|
||||
|
||||
// Last-frame camera latch. Populated at the top of RenderFrame /
|
||||
// RenderFrameOffscreen so post-scene consumers (e.g. the ImGui-backed
|
||||
// in-world text overlay) can project world positions to screen pixels using
|
||||
// the same matrices the scene was rasterized with. viewportW/H are in pixels,
|
||||
// matching the framebuffer the scene rendered to.
|
||||
typedef struct CameraState
|
||||
{
|
||||
Mat4 view;
|
||||
Mat4 viewInv;
|
||||
Mat4 proj;
|
||||
Mat4 projInv;
|
||||
int viewportW;
|
||||
int viewportH;
|
||||
} CameraState;
|
||||
CameraState GetCameraState( void );
|
||||
|
||||
// Cube proxy buffer shared by sphere and capsule impostors
|
||||
sg_buffer GetCubeProxyVertexBuffer( void );
|
||||
sg_buffer GetCubeProxyIndexBuffer( void );
|
||||
int GetCubeProxyIndexCount( void );
|
||||
|
||||
void RenderFrame( const sg_swapchain* swapChain, const FrameInput* frame );
|
||||
|
||||
// Render the scene into a caller-owned offscreen attachment set. The
|
||||
// renderer is host-agnostic. This is the entry point a non-sokol_app
|
||||
// host (e.g. a GLFW-based Box3D sample) would call. `attachments` describes
|
||||
// the tonemap output target (single-sample, sRGB-encoded BGRA8/RGBA8), the
|
||||
// renderer owns its own MSAA HDR scene target internally. `outputFormat` is
|
||||
// the color format of attachments.colors[0], used to key the tonemap pipeline
|
||||
// cache. width/height are the attachment image dimensions, fed into
|
||||
// ub_frame.viewport.
|
||||
void RenderFrameOffscreen( const sg_attachments* attachments, sg_pixel_format outputFormat, int width, int height,
|
||||
const FrameInput* frame );
|
||||
void ShutdownRenderer( void );
|
||||
|
||||
int GetRenderErrorCount( void );
|
||||
|
||||
// Reset the per-frame arena and clear all instance counts. Safe to call
|
||||
// every frame even if no submissions follow.
|
||||
void ResetFrameArena( void );
|
||||
|
||||
// Append one cube instance into the frame arena. transform places and orients
|
||||
// the cube. scale multiplies the unit cube proxy (which spans [-0.5, 0.5]), so
|
||||
// scale is the cube's full side lengths. baseColor is linear RGBA (alpha < 1.0
|
||||
// routes to the transparent arena, alpha == 1.0 to the opaque arena). metallic
|
||||
// and roughness feed the PBR BRDF (clamp to [0,1] at the call site). shadowCast
|
||||
// picks whether this instance contributes to the shadow caster pass. Logs and
|
||||
// drops on overflow.
|
||||
void AppendCube( b3Transform transform, b3Vec3 scale, Vec4 baseColor, float metallic, float roughness, TransparentShadowCast shadowCast );
|
||||
|
||||
// Append one sphere instance. transform's rotation drives the surface pattern
|
||||
// so spin is visible, its translation is the sphere center. radius is the only
|
||||
// scale, given separately so the bounding-cube proxy matches the analytic
|
||||
// silhouette. baseColor, metallic, roughness feed the PBR BRDF, the impostor
|
||||
// pattern modulates baseColor before lighting. shadowCast as in AppendCube.
|
||||
// Logs and drops on overflow.
|
||||
void AppendSphere( b3Transform transform, float radius, Vec4 baseColor, float metallic, float roughness,
|
||||
TransparentShadowCast shadowCast );
|
||||
|
||||
// Append one capsule instance. transform's rotation places the capsule's local
|
||||
// +X axis (the long axis) in world space and drives the surface pattern so
|
||||
// all three rotational axes are visible, its translation is the capsule
|
||||
// center. halfLength is the distance from center to either cap center along
|
||||
// local +X. radius is the cap radius. baseColor, metallic, roughness feed
|
||||
// the PBR BRDF, the impostor pattern modulates baseColor before lighting.
|
||||
// shadowCast as in AppendCube. Logs and drops on overflow.
|
||||
void AppendCapsule( b3Transform transform, float halfLength, float radius, Vec4 baseColor, float metallic, float roughness,
|
||||
TransparentShadowCast shadowCast );
|
||||
|
||||
#ifdef __cplusplus
|
||||
} // extern "C"
|
||||
#endif
|
||||
220
samples/gfx/scene_target.c
Normal file
220
samples/gfx/scene_target.c
Normal file
|
|
@ -0,0 +1,220 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "gfx/scene_target.h"
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
#define SCENE_COLOR_FORMAT SG_PIXELFORMAT_RGBA16F
|
||||
|
||||
// At SCENE_SAMPLE_COUNT > 1: colorMsaaImage holds the MSAA color, sokol_gfx
|
||||
// auto-resolves into colorResolveImage at end-of-pass, and the tone map +
|
||||
// transparent passes consume the resolve image.
|
||||
// At SCENE_SAMPLE_COUNT == 1: colorResolveImage is unused (id = 0). The
|
||||
// "MSAA" image is itself 1x and serves as both the scene_hdr color
|
||||
// attachment AND the sampled scene color for downstream passes. The
|
||||
// public sceneTargetResolve* accessors transparently point at it.
|
||||
static struct
|
||||
{
|
||||
sg_pixel_format depthFormat;
|
||||
int width;
|
||||
int height;
|
||||
|
||||
sg_image colorMsaaImage; // sample_count = SCENE_SAMPLE_COUNT
|
||||
sg_image depthMsaaImage; // sample_count = SCENE_SAMPLE_COUNT
|
||||
sg_image colorResolveImage; // sample_count = 1, unused when SCENE_SAMPLE_COUNT == 1
|
||||
|
||||
sg_view colorMsaaView; // color_attachment over colorMsaaImage
|
||||
sg_view depthMsaaView; // depth_stencil_attachment over depthMsaaImage
|
||||
sg_view colorResolveAttachView; // resolve_attachment, unused when SCENE_SAMPLE_COUNT == 1
|
||||
sg_view colorResolveColorAttachView; // color_attachment over resolved scene color (transparent pass)
|
||||
sg_view colorResolveSampleView; // texture view for sampling in tonemap
|
||||
|
||||
bool ready;
|
||||
} s_st;
|
||||
|
||||
static void destroyTargets( void )
|
||||
{
|
||||
if ( s_st.colorResolveSampleView.id )
|
||||
{
|
||||
sg_destroy_view( s_st.colorResolveSampleView );
|
||||
s_st.colorResolveSampleView.id = 0;
|
||||
}
|
||||
if ( s_st.colorResolveColorAttachView.id )
|
||||
{
|
||||
sg_destroy_view( s_st.colorResolveColorAttachView );
|
||||
s_st.colorResolveColorAttachView.id = 0;
|
||||
}
|
||||
if ( s_st.colorResolveAttachView.id )
|
||||
{
|
||||
sg_destroy_view( s_st.colorResolveAttachView );
|
||||
s_st.colorResolveAttachView.id = 0;
|
||||
}
|
||||
if ( s_st.depthMsaaView.id )
|
||||
{
|
||||
sg_destroy_view( s_st.depthMsaaView );
|
||||
s_st.depthMsaaView.id = 0;
|
||||
}
|
||||
if ( s_st.colorMsaaView.id )
|
||||
{
|
||||
sg_destroy_view( s_st.colorMsaaView );
|
||||
s_st.colorMsaaView.id = 0;
|
||||
}
|
||||
if ( s_st.colorResolveImage.id )
|
||||
{
|
||||
sg_destroy_image( s_st.colorResolveImage );
|
||||
s_st.colorResolveImage.id = 0;
|
||||
}
|
||||
if ( s_st.depthMsaaImage.id )
|
||||
{
|
||||
sg_destroy_image( s_st.depthMsaaImage );
|
||||
s_st.depthMsaaImage.id = 0;
|
||||
}
|
||||
if ( s_st.colorMsaaImage.id )
|
||||
{
|
||||
sg_destroy_image( s_st.colorMsaaImage );
|
||||
s_st.colorMsaaImage.id = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void InitSceneTarget( const sg_environment* env )
|
||||
{
|
||||
s_st.depthFormat = env->defaults.depth_format;
|
||||
s_st.width = 0;
|
||||
s_st.height = 0;
|
||||
s_st.ready = true;
|
||||
}
|
||||
|
||||
void ShutdownSceneTarget( void )
|
||||
{
|
||||
if ( !s_st.ready )
|
||||
{
|
||||
return;
|
||||
}
|
||||
destroyTargets();
|
||||
s_st.width = 0;
|
||||
s_st.height = 0;
|
||||
s_st.ready = false;
|
||||
}
|
||||
|
||||
void ResizeSceneTarget( int width, int height )
|
||||
{
|
||||
if ( !s_st.ready || width <= 0 || height <= 0 )
|
||||
{
|
||||
return;
|
||||
}
|
||||
if ( width == s_st.width && height == s_st.height && s_st.colorMsaaImage.id )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
destroyTargets();
|
||||
s_st.width = width;
|
||||
s_st.height = height;
|
||||
|
||||
sg_image_desc cdesc = { 0 };
|
||||
cdesc.usage.color_attachment = true;
|
||||
cdesc.width = width;
|
||||
cdesc.height = height;
|
||||
cdesc.pixel_format = SCENE_COLOR_FORMAT;
|
||||
cdesc.sample_count = SCENE_SAMPLE_COUNT;
|
||||
cdesc.label = "scene_color_msaa";
|
||||
s_st.colorMsaaImage = sg_make_image( &cdesc );
|
||||
|
||||
sg_image_desc ddesc = { 0 };
|
||||
ddesc.usage.depth_stencil_attachment = true;
|
||||
ddesc.width = width;
|
||||
ddesc.height = height;
|
||||
ddesc.pixel_format = s_st.depthFormat;
|
||||
ddesc.sample_count = SCENE_SAMPLE_COUNT;
|
||||
ddesc.label = "scene_depth_msaa";
|
||||
s_st.depthMsaaImage = sg_make_image( &ddesc );
|
||||
|
||||
if ( SCENE_SAMPLE_COUNT > 1 )
|
||||
{
|
||||
sg_image_desc rdesc = { 0 };
|
||||
rdesc.usage.resolve_attachment = true;
|
||||
// Also bind as a regular color_attachment for the transparent pass
|
||||
// that runs after the opaque MSAA pass has resolved.
|
||||
rdesc.usage.color_attachment = true;
|
||||
rdesc.width = width;
|
||||
rdesc.height = height;
|
||||
rdesc.pixel_format = SCENE_COLOR_FORMAT;
|
||||
rdesc.sample_count = 1;
|
||||
rdesc.label = "scene_color_resolve";
|
||||
s_st.colorResolveImage = sg_make_image( &rdesc );
|
||||
}
|
||||
|
||||
sg_view_desc cmvdesc = { 0 };
|
||||
cmvdesc.color_attachment.image = s_st.colorMsaaImage;
|
||||
cmvdesc.label = "scene_color_msaa_attach";
|
||||
s_st.colorMsaaView = sg_make_view( &cmvdesc );
|
||||
|
||||
sg_view_desc dmvdesc = { 0 };
|
||||
dmvdesc.depth_stencil_attachment.image = s_st.depthMsaaImage;
|
||||
dmvdesc.label = "scene_depth_msaa_attach";
|
||||
s_st.depthMsaaView = sg_make_view( &dmvdesc );
|
||||
|
||||
if ( SCENE_SAMPLE_COUNT > 1 )
|
||||
{
|
||||
sg_view_desc cravdesc = { 0 };
|
||||
cravdesc.resolve_attachment.image = s_st.colorResolveImage;
|
||||
cravdesc.label = "scene_color_resolve_attach";
|
||||
s_st.colorResolveAttachView = sg_make_view( &cravdesc );
|
||||
|
||||
sg_view_desc crcadesc = { 0 };
|
||||
crcadesc.color_attachment.image = s_st.colorResolveImage;
|
||||
crcadesc.label = "scene_color_resolve_color_attach";
|
||||
s_st.colorResolveColorAttachView = sg_make_view( &crcadesc );
|
||||
|
||||
sg_view_desc crsvdesc = { 0 };
|
||||
crsvdesc.texture.image = s_st.colorResolveImage;
|
||||
crsvdesc.label = "scene_color_resolve_sample";
|
||||
s_st.colorResolveSampleView = sg_make_view( &crsvdesc );
|
||||
}
|
||||
else
|
||||
{
|
||||
// 1x: there is no resolve. The scene color image IS the 1x image
|
||||
// the transparent pass and tonemap want. Reuse it via the same
|
||||
// public accessors so callers stay backend-agnostic.
|
||||
sg_view_desc crcadesc = { 0 };
|
||||
crcadesc.color_attachment.image = s_st.colorMsaaImage;
|
||||
crcadesc.label = "scene_color_attach_1x";
|
||||
s_st.colorResolveColorAttachView = sg_make_view( &crcadesc );
|
||||
|
||||
sg_view_desc crsvdesc = { 0 };
|
||||
crsvdesc.texture.image = s_st.colorMsaaImage;
|
||||
crsvdesc.label = "scene_color_sample_1x";
|
||||
s_st.colorResolveSampleView = sg_make_view( &crsvdesc );
|
||||
}
|
||||
}
|
||||
|
||||
sg_attachments GetSceneTargetAttachments( void )
|
||||
{
|
||||
sg_attachments a = { 0 };
|
||||
a.colors[0] = s_st.colorMsaaView;
|
||||
// resolves[0] paired with a 1x color attachment fails sokol_gfx
|
||||
// validation. At SCENE_SAMPLE_COUNT == 1 the colorMsaaView is itself
|
||||
// the single-sample target, no resolve step needed.
|
||||
if ( SCENE_SAMPLE_COUNT > 1 )
|
||||
{
|
||||
a.resolves[0] = s_st.colorResolveAttachView;
|
||||
}
|
||||
a.depth_stencil = s_st.depthMsaaView;
|
||||
return a;
|
||||
}
|
||||
|
||||
sg_view GetSceneTargetResolveSampleView( void )
|
||||
{
|
||||
return s_st.colorResolveSampleView;
|
||||
}
|
||||
|
||||
sg_view GetSceneTargetResolveColorAttachView( void )
|
||||
{
|
||||
return s_st.colorResolveColorAttachView;
|
||||
}
|
||||
|
||||
sg_pixel_format GetSceneTargetDepthFormat( void )
|
||||
{
|
||||
return s_st.depthFormat;
|
||||
}
|
||||
69
samples/gfx/scene_target.h
Normal file
69
samples/gfx/scene_target.h
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// HDR scene target.
|
||||
//
|
||||
// Renderer-owned 4x MSAA color + matching MSAA depth + single-sample
|
||||
// resolve color, all sized to the current frame's render width/height.
|
||||
// The opaque-scene pass writes into the MSAA color (with hardware resolve
|
||||
// into the resolve image at end-of-pass), the tonemap pass samples the
|
||||
// resolve image and writes the final swapchain/test target.
|
||||
//
|
||||
// Color format is fixed at RGBA16F across all backends, renderable +
|
||||
// filterable + MSAA-resolvable on D3D11, Metal, and GL 4.5 core. Alpha is
|
||||
// kept (vs. R11G11B10F) because the transparent pass uses it for
|
||||
// sorted-alpha transparency.
|
||||
//
|
||||
// Depth format mirrors env.defaults.depth_format so the shape pipelines
|
||||
// (depth.pixel_format = env->defaults.depth_format) remain compatible.
|
||||
//
|
||||
// Per-frame sizing: RenderFrame calls ResizeSceneTarget(W,H) before
|
||||
// opening the lit pass. Recreates on size change, no-op when stable.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "sokol_gfx.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"
|
||||
{
|
||||
#endif
|
||||
|
||||
// MSAA sample count for the scene_hdr pass. Every pipeline that targets
|
||||
// scene_hdr (lit shapes in renderer.c, sky in sky.c, MSAA edge overlay in
|
||||
// edges.c) must declare a matching pipeline sample_count, so they all
|
||||
// reference this constant. Valid values: 1, 2, 4, 8. At 1, the resolve
|
||||
// attachment is omitted (sokol_gfx rejects a resolve paired with a 1x
|
||||
// color attachment) and the scene color image is sampled directly by the
|
||||
// tone map pass, the transparent pass binds it as a regular color
|
||||
// attachment with LOAD. Change here, rebuild, re-run.
|
||||
#define SCENE_SAMPLE_COUNT 4
|
||||
|
||||
void InitSceneTarget( const sg_environment* env );
|
||||
void ShutdownSceneTarget( void );
|
||||
|
||||
void ResizeSceneTarget( int width, int height );
|
||||
|
||||
// Attachment set the opaque-scene pass binds: colors[0] = MSAA color view,
|
||||
// resolves[0] = single-sample resolve view, depth_stencil = MSAA depth view.
|
||||
sg_attachments GetSceneTargetAttachments( void );
|
||||
|
||||
// Texture-view over the single-sample resolved color image. The tone map
|
||||
// pass samples this.
|
||||
sg_view GetSceneTargetResolveSampleView( void );
|
||||
|
||||
// Color-attachment view over the single-sample resolved image, for the
|
||||
// transparent pass that runs after the opaque MSAA pass has resolved.
|
||||
// The transparent pass binds this with LOADACTION_LOAD so it blends over
|
||||
// the resolved opaque scene rather than overwriting it.
|
||||
sg_view GetSceneTargetResolveColorAttachView( void );
|
||||
|
||||
// MSAA depth-attachment format used by the scene target. Mirrors the
|
||||
// env.defaults.depth_format passed to sceneTargetInit, surfaced for pass
|
||||
// modules (e.g. the edge overlay) that want to add a pipeline state
|
||||
// matching the MSAA scene attachments without re-querying the env.
|
||||
sg_pixel_format GetSceneTargetDepthFormat( void );
|
||||
|
||||
#ifdef __cplusplus
|
||||
} // extern "C"
|
||||
#endif
|
||||
350
samples/gfx/shadow.c
Normal file
350
samples/gfx/shadow.c
Normal file
|
|
@ -0,0 +1,350 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "gfx/shadow.h"
|
||||
|
||||
#include <float.h>
|
||||
#include <math.h>
|
||||
#include <stdio.h>
|
||||
|
||||
// Cascade fitting parameters. SHADOW_SPLIT_NEAR and the default far
|
||||
// (SHADOW_SPLIT_FAR, in shadow.h) are *view-space* distances from the camera
|
||||
// (positive). CSM quality at distance falls off fast, so cascades focus on
|
||||
// near content.
|
||||
//
|
||||
// PSSM_LAMBDA blends the uniform split scheme (each cascade covers an
|
||||
// equal slice of view-space distance) and the logarithmic scheme (each
|
||||
// cascade covers an equal multiplicative range). 0 = pure uniform,
|
||||
// 1 = pure log. 0.5 is the sweet spot at the default range. The blend is
|
||||
// pushed toward log up to PSSM_LAMBDA_MAX as the range widens, otherwise a
|
||||
// large far would balloon the near cascade and coarsen close-up shadows.
|
||||
//
|
||||
// CASTER_MARGIN_M expands the orthographic light frustum's near edge
|
||||
// toward the sun so casters above the camera frustum slice (e.g. the
|
||||
// building roof at y=3 when the slice itself only reaches y=1) still cast
|
||||
// onto receivers inside the slice.
|
||||
#define SHADOW_SPLIT_NEAR 0.1f
|
||||
#define PSSM_LAMBDA 0.5f
|
||||
#define PSSM_LAMBDA_MAX 0.9f
|
||||
#define CASTER_MARGIN_M 50.0f
|
||||
|
||||
static struct
|
||||
{
|
||||
b3Vec3 sunDir; // world-space dir TO sun, normalized
|
||||
float splitNear; // PSSM split range near (positive view-Z)
|
||||
float splitFar; // PSSM split range far (positive view-Z)
|
||||
float splitLambda; // uniform/log split blend, widens with range
|
||||
sg_image depthArray; // D32F, cascade layers
|
||||
sg_view cascadeAttachmentViews[SHADOW_CASCADE_COUNT]; // depth-stencil view per cascade
|
||||
sg_view sampleView; // full-array texture-sample view
|
||||
sg_sampler sampler; // comparison sampler (LESS_EQUAL, linear PCF)
|
||||
Mat4 cascadeMatrices[SHADOW_CASCADE_COUNT]; // light-space view-proj per cascade
|
||||
float cascadeFarViewZ[SHADOW_CASCADE_COUNT]; // far end (positive view-Z) per cascade
|
||||
bool inPass; // safety against unbalanced begin/end
|
||||
} s_shadow;
|
||||
|
||||
// PSSM split scheme: blend uniform and logarithmic. Returns the *positive*
|
||||
// view-space distance at the boundary of cascade `i` (i in [0..N], where
|
||||
// split[0] = near and split[N] = far).
|
||||
static inline float ComputeSplitDistance( int i, int cascadeCount, float nearZ, float farZ )
|
||||
{
|
||||
const float fi = (float)i / (float)cascadeCount;
|
||||
const float u = nearZ + ( farZ - nearZ ) * fi;
|
||||
const float l = nearZ * powf( farZ / nearZ, fi );
|
||||
return s_shadow.splitLambda * l + ( 1.0f - s_shadow.splitLambda ) * u;
|
||||
}
|
||||
|
||||
// Push the uniform/log blend toward log as the split range widens, so the near
|
||||
// cascade stays tight when far is large. Anchored at the default range so the
|
||||
// reference scenes keep the 0.5 sweet spot.
|
||||
static inline float SplitLambdaForRange( float nearZ, float farZ )
|
||||
{
|
||||
float decades = log10f( ( farZ / nearZ ) / ( SHADOW_SPLIT_FAR / SHADOW_SPLIT_NEAR ) );
|
||||
return b3ClampFloat( PSSM_LAMBDA + 0.4f * decades, PSSM_LAMBDA, PSSM_LAMBDA_MAX );
|
||||
}
|
||||
|
||||
// Fill cornersOut with the 8 world-space corners of the camera frustum
|
||||
// slice between view-space distances nearZ and farZ (both positive, the
|
||||
// camera looks down its own -Z axis in view space).
|
||||
//
|
||||
// Camera basis comes straight from `viewInv` (the camera's world matrix
|
||||
// produced by mat4ViewAndInverse): column 0 is right, column 1 is up,
|
||||
// column 2 is back (i.e., -forward), column 3 is eye, no inversion.
|
||||
// FovY and aspect are read from the projection matrix: mat4Perspective
|
||||
// puts proj[1][1] = 1/tan(fovY/2) and proj[0][0] = proj[1][1] / aspect.
|
||||
static void FrustumSliceCornersWorld( const Mat4* viewInv, const Mat4* proj, float nearZ, float farZ, b3Vec3 cornersOut[8] )
|
||||
{
|
||||
const b3Vec3 eye = { viewInv->cw.x, viewInv->cw.y, viewInv->cw.z };
|
||||
const b3Vec3 right = { viewInv->cx.x, viewInv->cx.y, viewInv->cx.z };
|
||||
const b3Vec3 up = { viewInv->cy.x, viewInv->cy.y, viewInv->cy.z };
|
||||
const b3Vec3 forward = { -viewInv->cz.x, -viewInv->cz.y, -viewInv->cz.z };
|
||||
|
||||
const float tanHalfFovY = ( proj->cy.y != 0.0f ) ? ( 1.0f / proj->cy.y ) : 1.0f;
|
||||
const float aspect = ( proj->cx.x != 0.0f ) ? ( proj->cy.y / proj->cx.x ) : 1.0f;
|
||||
|
||||
const float distances[2] = { nearZ, farZ };
|
||||
for ( int s = 0; s < 2; ++s )
|
||||
{
|
||||
const float d = distances[s];
|
||||
const float h = d * tanHalfFovY;
|
||||
const float w = h * aspect;
|
||||
const b3Vec3 center = b3MulAdd( eye, d, forward );
|
||||
for ( int j = 0; j < 4; ++j )
|
||||
{
|
||||
const float sx = ( j & 1 ) ? +w : -w;
|
||||
const float sy = ( j & 2 ) ? +h : -h;
|
||||
b3Vec3 c = b3MulAdd( center, sx, right );
|
||||
c = b3MulAdd( c, sy, up );
|
||||
cornersOut[s * 4 + j] = c;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fit one cascade's light-space view-projection matrix to the camera
|
||||
// frustum slice [nearZ, farZ] for the configured sun direction.
|
||||
//
|
||||
// The slice is bounded by a *world-space sphere* (centroid + max radius
|
||||
// from centroid to any slice corner). The sphere is rotation-invariant.
|
||||
// Rotating the camera around its eye doesn't move it, which is the key
|
||||
// property that lets the texel-snap stabilization avoid swimming edges.
|
||||
//
|
||||
// Light view: orthonormal frame whose -Z axis points toward the sun.
|
||||
// Light proj: orthographic, sized to enclose the sphere. The near plane
|
||||
// is pushed back along +sun by CASTER_MARGIN_M so casters between the
|
||||
// slice and the sun are not clipped.
|
||||
//
|
||||
// Texel-snap: after the unsnapped lightVP is built, transform the slice
|
||||
// center through it to clip space, round the resulting clip-space xy to
|
||||
// the nearest texel grid step, and apply the rounding delta as a
|
||||
// post-translation. This pins the cascade to a fixed grid in light
|
||||
// space, small camera motions no longer cause the shadow texels to
|
||||
// drift relative to the casters.
|
||||
static Mat4 FitCascade( const Mat4* viewInv, const Mat4* proj, b3Vec3 dirToSun, float nearZ, float farZ )
|
||||
{
|
||||
b3Vec3 corners[8];
|
||||
FrustumSliceCornersWorld( viewInv, proj, nearZ, farZ, corners );
|
||||
|
||||
b3Vec3 center = b3Vec3_zero;
|
||||
for ( int i = 0; i < 8; ++i )
|
||||
{
|
||||
center = b3Add( center, corners[i] );
|
||||
}
|
||||
center = b3MulSV( 1.0f / 8.0f, center );
|
||||
|
||||
float radius = 0.0f;
|
||||
for ( int i = 0; i < 8; ++i )
|
||||
{
|
||||
const b3Vec3 d = b3Sub( corners[i], center );
|
||||
const float r = sqrtf( d.x * d.x + d.y * d.y + d.z * d.z );
|
||||
if ( r > radius )
|
||||
{
|
||||
radius = r;
|
||||
}
|
||||
}
|
||||
if ( radius < 0.01f )
|
||||
{
|
||||
radius = 0.01f;
|
||||
}
|
||||
|
||||
// Avoid a degenerate up vector when the sun is straight up/down.
|
||||
b3Vec3 up = b3Vec3_axisY;
|
||||
if ( fabsf( dirToSun.y ) > 0.999f )
|
||||
{
|
||||
up = b3Vec3_axisZ;
|
||||
}
|
||||
|
||||
// Place the light eye behind the sphere along +sun. Far clip extends
|
||||
// past the sphere's back face. Near clip pulls forward by
|
||||
// CASTER_MARGIN_M to admit casters above the slice.
|
||||
const b3Vec3 eyeWorld = b3MulAdd( center, radius + CASTER_MARGIN_M, dirToSun );
|
||||
const Mat4 lightView = MakeLookAt( eyeWorld, center, up );
|
||||
const Mat4 lightProj = MakeOrthographic( -radius, radius, -radius, radius, 0.0f, 2.0f * radius + CASTER_MARGIN_M );
|
||||
Mat4 lightVP = MulMM4( lightProj, lightView );
|
||||
|
||||
// Texel-snap stabilization. Transform the sphere center through the
|
||||
// unsnapped lightVP. Project to texel coords, round, convert the
|
||||
// delta back to clip space, and add as a post-translation.
|
||||
const Vec4 centerClip = MulMV4( lightVP, MakeVec4( center.x, center.y, center.z, 1.0f ) );
|
||||
const float halfRes = (float)SHADOW_RESOLUTION * 0.5f;
|
||||
const float texX = centerClip.x * halfRes;
|
||||
const float texY = centerClip.y * halfRes;
|
||||
const float dx = ( roundf( texX ) - texX ) / halfRes;
|
||||
const float dy = ( roundf( texY ) - texY ) / halfRes;
|
||||
|
||||
Mat4 snapMat = MakeIdentity();
|
||||
snapMat.cw.x = dx;
|
||||
snapMat.cw.y = dy;
|
||||
return MulMM4( snapMat, lightVP );
|
||||
}
|
||||
|
||||
void InitShadows( void )
|
||||
{
|
||||
s_shadow.sunDir = b3Normalize( (b3Vec3){ 0.5f, 0.8f, 0.4f } );
|
||||
s_shadow.splitNear = SHADOW_SPLIT_NEAR;
|
||||
s_shadow.splitFar = SHADOW_SPLIT_FAR;
|
||||
s_shadow.splitLambda = SplitLambdaForRange( s_shadow.splitNear, s_shadow.splitFar );
|
||||
|
||||
sg_image_desc desc = { 0 };
|
||||
desc.type = SG_IMAGETYPE_ARRAY;
|
||||
desc.usage.depth_stencil_attachment = true;
|
||||
desc.width = SHADOW_RESOLUTION;
|
||||
desc.height = SHADOW_RESOLUTION;
|
||||
desc.num_slices = SHADOW_CASCADE_COUNT;
|
||||
desc.pixel_format = SG_PIXELFORMAT_DEPTH;
|
||||
desc.sample_count = 1;
|
||||
desc.label = "shadow_depth_array";
|
||||
s_shadow.depthArray = sg_make_image( &desc );
|
||||
|
||||
// Per-cascade depth attachment view (slice = cascade index).
|
||||
for ( int i = 0; i < SHADOW_CASCADE_COUNT; ++i )
|
||||
{
|
||||
sg_view_desc vdesc = { 0 };
|
||||
vdesc.depth_stencil_attachment.image = s_shadow.depthArray;
|
||||
vdesc.depth_stencil_attachment.slice = i;
|
||||
vdesc.label = "shadow_cascade_attachment";
|
||||
s_shadow.cascadeAttachmentViews[i] = sg_make_view( &vdesc );
|
||||
}
|
||||
|
||||
// Whole-array texture sample view: layer index becomes the .z arg in
|
||||
// the shader's sampler2DArrayShadow lookup. Explicitly range over all
|
||||
// cascade slices so the view binds the full array
|
||||
// (careful: sokol's "count = 0 means all remaining" default).
|
||||
sg_view_desc svdesc = { 0 };
|
||||
svdesc.texture.image = s_shadow.depthArray;
|
||||
svdesc.texture.slices.base = 0;
|
||||
svdesc.texture.slices.count = SHADOW_CASCADE_COUNT;
|
||||
svdesc.label = "shadow_sample_view";
|
||||
s_shadow.sampleView = sg_make_view( &svdesc );
|
||||
|
||||
// Comparison sampler: LESS_EQUAL means the test returns 1.0 (lit) when
|
||||
// the receiver's reference depth is <= the stored depth, i.e., the
|
||||
// receiver is the closest surface to the light. Linear PCF: each
|
||||
// texture call returns a 2x2 weighted compare-result mix.
|
||||
sg_sampler_desc sdesc = { 0 };
|
||||
sdesc.min_filter = SG_FILTER_LINEAR;
|
||||
sdesc.mag_filter = SG_FILTER_LINEAR;
|
||||
sdesc.mipmap_filter = SG_FILTER_NEAREST;
|
||||
sdesc.wrap_u = SG_WRAP_CLAMP_TO_EDGE;
|
||||
sdesc.wrap_v = SG_WRAP_CLAMP_TO_EDGE;
|
||||
sdesc.wrap_w = SG_WRAP_CLAMP_TO_EDGE;
|
||||
sdesc.compare = SG_COMPAREFUNC_LESS_EQUAL;
|
||||
sdesc.label = "shadow_compare_sampler";
|
||||
s_shadow.sampler = sg_make_sampler( &sdesc );
|
||||
|
||||
s_shadow.inPass = false;
|
||||
}
|
||||
|
||||
void ShutdownShadows( void )
|
||||
{
|
||||
sg_destroy_sampler( s_shadow.sampler );
|
||||
sg_destroy_view( s_shadow.sampleView );
|
||||
for ( int i = 0; i < SHADOW_CASCADE_COUNT; ++i )
|
||||
{
|
||||
sg_destroy_view( s_shadow.cascadeAttachmentViews[i] );
|
||||
}
|
||||
sg_destroy_image( s_shadow.depthArray );
|
||||
}
|
||||
|
||||
void SetShadowSplits( float nearViewZ, float farViewZ )
|
||||
{
|
||||
if ( nearViewZ <= 0.0f || farViewZ <= nearViewZ )
|
||||
{
|
||||
// Restore defaults on (0, 0) or any nonsense input.
|
||||
nearViewZ = SHADOW_SPLIT_NEAR;
|
||||
farViewZ = SHADOW_SPLIT_FAR;
|
||||
}
|
||||
|
||||
s_shadow.splitNear = nearViewZ;
|
||||
s_shadow.splitFar = farViewZ;
|
||||
s_shadow.splitLambda = SplitLambdaForRange( nearViewZ, farViewZ );
|
||||
}
|
||||
|
||||
void SetShadowSplitFar( float farViewZ )
|
||||
{
|
||||
SetShadowSplits( s_shadow.splitNear, farViewZ );
|
||||
}
|
||||
|
||||
void SetShadowSunDir( b3Vec3 dirToSun )
|
||||
{
|
||||
const float lenSq = dirToSun.x * dirToSun.x + dirToSun.y * dirToSun.y + dirToSun.z * dirToSun.z;
|
||||
if ( lenSq > 0.0f )
|
||||
{
|
||||
s_shadow.sunDir = b3Normalize( dirToSun );
|
||||
}
|
||||
}
|
||||
|
||||
void FitShadows( const Mat4* viewInv, const Mat4* proj )
|
||||
{
|
||||
// PSSM splits across [splitNear, splitFar]. split[0] = near,
|
||||
// split[N] = far. Cascade i covers (split[i], split[i+1]].
|
||||
float splits[SHADOW_CASCADE_COUNT + 1];
|
||||
for ( int i = 0; i <= SHADOW_CASCADE_COUNT; ++i )
|
||||
{
|
||||
splits[i] = ComputeSplitDistance( i, SHADOW_CASCADE_COUNT, s_shadow.splitNear, s_shadow.splitFar );
|
||||
}
|
||||
|
||||
for ( int i = 0; i < SHADOW_CASCADE_COUNT; ++i )
|
||||
{
|
||||
s_shadow.cascadeMatrices[i] = FitCascade( viewInv, proj, s_shadow.sunDir, splits[i], splits[i + 1] );
|
||||
s_shadow.cascadeFarViewZ[i] = splits[i + 1];
|
||||
}
|
||||
}
|
||||
|
||||
void BeginShadowPass( int cascade )
|
||||
{
|
||||
if ( cascade < 0 || cascade >= SHADOW_CASCADE_COUNT )
|
||||
{
|
||||
fprintf( stderr, "cascade index out of range: %d\n", cascade );
|
||||
return;
|
||||
}
|
||||
sg_pass pass = { 0 };
|
||||
pass.action.depth.load_action = SG_LOADACTION_CLEAR;
|
||||
pass.action.depth.clear_value = 1.0f; // standard Z far
|
||||
pass.action.depth.store_action = SG_STOREACTION_STORE;
|
||||
pass.attachments.depth_stencil = s_shadow.cascadeAttachmentViews[cascade];
|
||||
sg_begin_pass( &pass );
|
||||
s_shadow.inPass = true;
|
||||
}
|
||||
|
||||
void EndShadowPass( void )
|
||||
{
|
||||
if ( !s_shadow.inPass )
|
||||
{
|
||||
return;
|
||||
}
|
||||
sg_end_pass();
|
||||
s_shadow.inPass = false;
|
||||
}
|
||||
|
||||
Mat4 GetCascadeMatrix( int cascade )
|
||||
{
|
||||
if ( cascade < 0 || cascade >= SHADOW_CASCADE_COUNT )
|
||||
{
|
||||
return MakeIdentity();
|
||||
}
|
||||
return s_shadow.cascadeMatrices[cascade];
|
||||
}
|
||||
|
||||
float GetCascadeFarViewZ( int cascade )
|
||||
{
|
||||
if ( cascade < 0 || cascade >= SHADOW_CASCADE_COUNT )
|
||||
{
|
||||
return 0.0f;
|
||||
}
|
||||
return s_shadow.cascadeFarViewZ[cascade];
|
||||
}
|
||||
|
||||
sg_view GetShadowSampleView( void )
|
||||
{
|
||||
return s_shadow.sampleView;
|
||||
}
|
||||
|
||||
sg_sampler GetShadowSampler( void )
|
||||
{
|
||||
return s_shadow.sampler;
|
||||
}
|
||||
|
||||
float GetShadowTexelSize( void )
|
||||
{
|
||||
return 1.0f / (float)SHADOW_RESOLUTION;
|
||||
}
|
||||
102
samples/gfx/shadow.h
Normal file
102
samples/gfx/shadow.h
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Cascaded-shadow-map infrastructure.
|
||||
//
|
||||
// One depth array texture (D32F) holds all cascades, each cascade gets its
|
||||
// own depth-only view used as the depth attachment for that cascade's
|
||||
// shadow pass. A single comparison sampler (LESS_EQUAL with linear PCF)
|
||||
// is shared by every lit shader that reads from the array.
|
||||
//
|
||||
// Light-space matrices and split distances are computed by FitShadows
|
||||
// each frame from the camera frustum and the sun direction.
|
||||
//
|
||||
// Coordinate convention inside shadow space:
|
||||
// - Standard Z (not reverse-Z): 0 at near, 1 at far. The shadow pass
|
||||
// clears depth to 1.0, fragments closer to the light overwrite with
|
||||
// smaller values, the sampler compares LESS_EQUAL to determine "this
|
||||
// fragment is the closest one, so lit".
|
||||
// - Right-handed orthographic projection, 0..1 clip-Z.
|
||||
//
|
||||
// Public surface:
|
||||
// InitShadows / ShutdownShadows, lifecycle.
|
||||
// SetShadowSunDir, store the direction the renderer will use when
|
||||
// fitting cascades.
|
||||
// FitShadows, recompute cascade matrices and split distances for a
|
||||
// given camera frustum.
|
||||
// BeginShadowPass / EndShadowPass, open/close the depth pass per cascade.
|
||||
// GetShadowSampleView / GetShadowSampler, for lit pipelines to
|
||||
// bind once and sample across all cascades.
|
||||
// GetCascadeMatrix / GetCascadeFarViewZ, for lit
|
||||
// shaders to transform world positions and select the right cascade.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "gfx/utility.h"
|
||||
#include "sokol_gfx.h"
|
||||
|
||||
#include <stdbool.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"
|
||||
{
|
||||
#endif
|
||||
|
||||
#define SHADOW_CASCADE_COUNT 3
|
||||
#define SHADOW_RESOLUTION 2048
|
||||
|
||||
// Default cascade far split, view-space distance from the camera. Scenes
|
||||
// smaller than this keep the default range, larger ones widen it.
|
||||
#define SHADOW_SPLIT_FAR 50.0f
|
||||
|
||||
void InitShadows( void );
|
||||
void ShutdownShadows( void );
|
||||
|
||||
// Set the world-space direction TO the sun
|
||||
void SetShadowSunDir( b3Vec3 dirToSun );
|
||||
|
||||
// Override the view-space distance range PSSM splits over. Defaults to
|
||||
// (0.1, SHADOW_SPLIT_FAR), sufficient for the reference scenes but too short
|
||||
// for larger ones. The split blend is derived from the range, so a wider far
|
||||
// keeps the near cascade tight. Pass (0, 0) to restore defaults.
|
||||
void SetShadowSplits( float nearViewZ, float farViewZ );
|
||||
|
||||
// Fit the cascade far split to a scene of this view-space depth, keeping the
|
||||
// current near and recomputing the split blend.
|
||||
void SetShadowSplitFar( float farViewZ );
|
||||
|
||||
// Recompute per-cascade light-space matrices and split distances for the
|
||||
// camera frustum described by viewInv + proj. viewInv (the camera's world
|
||||
// matrix) supplies eye + basis directly, so the slice-corner walk does no
|
||||
// matrix inversion. proj supplies fovY + aspect via proj[1][1] / proj[0][0].
|
||||
// Cascade slices are fit to the camera frustum and snapped to texel
|
||||
// boundaries to avoid swimming edges as the camera moves.
|
||||
void FitShadows( const Mat4* viewInv, const Mat4* proj );
|
||||
|
||||
// Begin / end the depth-only render pass for a cascade. Bind this as
|
||||
// the surrounding pass before issuing caster draws into the cascade.
|
||||
void BeginShadowPass( int cascade );
|
||||
void EndShadowPass( void );
|
||||
|
||||
// Light-space view-proj matrix for a cascade. Lit shaders multiply a
|
||||
// world-space position by this to get shadow-space coordinates.
|
||||
Mat4 GetCascadeMatrix( int cascade );
|
||||
|
||||
// Far view-space Z (positive value, distance from camera) for the end
|
||||
// cascade. Lit shaders compare a fragment's view-space depth against
|
||||
// these to pick which cascade to sample.
|
||||
float GetCascadeFarViewZ( int cascade );
|
||||
|
||||
// Bound by lit pipelines once for sampling across all cascades. The view
|
||||
// is the depth array's full-array sampling view. Per-cascade selection
|
||||
// happens inside the shader by passing `cascade` as the layer index.
|
||||
sg_view GetShadowSampleView( void );
|
||||
sg_sampler GetShadowSampler( void );
|
||||
|
||||
// One-texel size in shadow space (1 / SHADOW_RESOLUTION). Lit shaders
|
||||
// use this to size PCF taps and slope-scale bias.
|
||||
float GetShadowTexelSize( void );
|
||||
|
||||
#ifdef __cplusplus
|
||||
} // extern "C"
|
||||
#endif
|
||||
109
samples/gfx/sky.c
Normal file
109
samples/gfx/sky.c
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "gfx/sky.h"
|
||||
|
||||
#include "gfx/scene_target.h"
|
||||
#include "sky.glsl.h"
|
||||
|
||||
// Below-horizon fade: the renderer feeds the FS a [0,1] weight derived from
|
||||
// the sun's elevation, smoothly stepped between BELOW_HORIZON_FADE_START
|
||||
// (~2 deg) and BELOW_HORIZON_FADE_END (~5 deg). Preetham diverges at and below
|
||||
// the horizon, so we fade to zero there rather than render garbage. Values
|
||||
// in radians via sin so we can compare against dirToSun.y directly.
|
||||
#define BELOW_HORIZON_FADE_START_SIN 0.0349f // sin(2 deg)
|
||||
#define BELOW_HORIZON_FADE_END_SIN 0.0872f // sin(5 deg)
|
||||
|
||||
static struct
|
||||
{
|
||||
sg_shader shader;
|
||||
sg_pipeline pipeline;
|
||||
bool ready;
|
||||
} s_sky;
|
||||
|
||||
void InitSky( const sg_environment* env )
|
||||
{
|
||||
s_sky.shader = sg_make_shader( sky_shader_desc( sg_query_backend() ) );
|
||||
|
||||
sg_pipeline_desc pdesc = { 0 };
|
||||
pdesc.shader = s_sky.shader;
|
||||
// No vertex attributes, the VS pulls 3 fullscreen-triangle corners from
|
||||
// gl_VertexIndex. Leaving layout.attrs zeroed tells sokol the pipeline
|
||||
// has no input bindings (D3D11 builds an empty input layout).
|
||||
// Color attachment is the HDR scene target (RGBA16F MSAA).
|
||||
pdesc.colors[0].pixel_format = SG_PIXELFORMAT_RGBA16F;
|
||||
pdesc.depth.pixel_format = env->defaults.depth_format;
|
||||
// Reverse-Z: depth was cleared to 0 (far). Sky vertices sit at NDC z=0
|
||||
// (also far). GREATER_EQUAL passes against the cleared value on
|
||||
// untouched pixels and fails on opaque pixels (whose z > 0 means
|
||||
// they're closer than the far plane in reverse-Z).
|
||||
pdesc.depth.compare = SG_COMPAREFUNC_GREATER_EQUAL;
|
||||
pdesc.depth.write_enabled = false;
|
||||
// No back-face winding to enforce, but matching the rest of the
|
||||
// pipeline's CCW front face means the rasterizer's culling logic
|
||||
// never sees a back face on the fullscreen triangle.
|
||||
pdesc.cull_mode = SG_CULLMODE_NONE;
|
||||
pdesc.face_winding = SG_FACEWINDING_CCW;
|
||||
// Must match the scene_hdr MSAA color attachment's sample count.
|
||||
pdesc.sample_count = SCENE_SAMPLE_COUNT;
|
||||
pdesc.label = "sky_pipeline";
|
||||
s_sky.pipeline = sg_make_pipeline( &pdesc );
|
||||
|
||||
s_sky.ready = true;
|
||||
}
|
||||
|
||||
void ShutdownSky( void )
|
||||
{
|
||||
if ( !s_sky.ready )
|
||||
{
|
||||
return;
|
||||
}
|
||||
sg_destroy_pipeline( s_sky.pipeline );
|
||||
sg_destroy_shader( s_sky.shader );
|
||||
s_sky.ready = false;
|
||||
}
|
||||
|
||||
float SkySunFadeWeight( b3Vec3 dirToSun )
|
||||
{
|
||||
// dirToSun is assumed unit-length. The rendering side renormalizes
|
||||
// before calling. The fade reads dirToSun.y directly as sin(elevation).
|
||||
float t = ( dirToSun.y - BELOW_HORIZON_FADE_START_SIN ) / ( BELOW_HORIZON_FADE_END_SIN - BELOW_HORIZON_FADE_START_SIN );
|
||||
t = ( t < 0.0f ) ? 0.0f : ( t > 1.0f ? 1.0f : t );
|
||||
return t * t * ( 3.0f - 2.0f * t );
|
||||
}
|
||||
|
||||
void DrawSky( b3Vec3 dirToSun, float turbidity, b3Vec3 cameraPos, Mat4 invViewProj )
|
||||
{
|
||||
if ( !s_sky.ready )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Renormalize defensively. Caller is the renderer with sun.dirToSun
|
||||
// already normalized, but the FS reads sun_dir_world.xyz expecting unit
|
||||
// length and an undetected zero vector here would emit NaNs.
|
||||
const float lenSq = dirToSun.x * dirToSun.x + dirToSun.y * dirToSun.y + dirToSun.z * dirToSun.z;
|
||||
b3Vec3 sun = ( lenSq > 0.0f ) ? b3Normalize( dirToSun ) : b3Vec3_axisY;
|
||||
|
||||
const float fade = SkySunFadeWeight( sun );
|
||||
|
||||
sky_ub_frame_t ub = { 0 };
|
||||
ub.inv_view_proj = invViewProj;
|
||||
|
||||
sky_ub_pass_t up = { 0 };
|
||||
up.sun_dir_world = MakeVec4( sun.x, sun.y, sun.z, fade );
|
||||
up.sky_params = MakeVec4( turbidity, 0.0f, 0.0f, 0.0f );
|
||||
up.camera_pos = MakeVec4( cameraPos.x, cameraPos.y, cameraPos.z, 0.0f );
|
||||
|
||||
sg_apply_pipeline( s_sky.pipeline );
|
||||
|
||||
// Deliberately no sg_apply_bindings: the pipeline declares no vertex
|
||||
// buffers, no textures, and no storage views, so its required_bindings
|
||||
// mask is empty. Sokol's draw-time check is "applied == required". An
|
||||
// entirely-empty sg_bindings actually FAILS validation
|
||||
// (VALIDATE_ABND_EMPTY_BINDINGS, sokol_gfx.h:23591), so the only way
|
||||
// to draw a bindings-free pipeline is to skip the call.
|
||||
sg_apply_uniforms( UB_sky_ub_frame, &SG_RANGE( ub ) );
|
||||
sg_apply_uniforms( UB_sky_ub_pass, &SG_RANGE( up ) );
|
||||
sg_draw( 0, 3, 1 );
|
||||
}
|
||||
49
samples/gfx/sky.h
Normal file
49
samples/gfx/sky.h
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Procedural sky
|
||||
//
|
||||
// Renders a Preetham analytic daylight skybox into the main lit pass after
|
||||
// all opaque shapes. Uses a fullscreen triangle drawn at the reverse-Z far
|
||||
// plane (NDC z = 0) with depth test GREATER_EQUAL and depth-write off, so
|
||||
// pixels covered by opaque geometry pass through unchanged and untouched
|
||||
// pixels (still at the cleared depth of 0) receive the sky.
|
||||
//
|
||||
// The sun direction is the renderer's single source of truth, the shadow
|
||||
// caster, direct lighting, and sky all consume the same world-space vector
|
||||
// (set via SetSun). Below-horizon fade is computed C-side and passed in
|
||||
// alongside the direction so the FS doesn't need to know the threshold.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "gfx/utility.h"
|
||||
#include "sokol_gfx.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"
|
||||
{
|
||||
#endif
|
||||
|
||||
void InitSky( const sg_environment* env );
|
||||
void ShutdownSky( void );
|
||||
|
||||
// Below-horizon fade weight in [0, 1], 1 well above the horizon, 0
|
||||
// below it, smoothstep between sin(2 deg) and sin(5 deg). The IBL cubemap
|
||||
// renderer reads this so its sky matches the backdrop exactly when the
|
||||
// sun is near the horizon. dirToSun.y == sin(elevation) when normalized.
|
||||
float SkySunFadeWeight( b3Vec3 dirToSun );
|
||||
|
||||
// Issue the sky draw. Call inside the main lit pass after all opaque
|
||||
// shape draws. Parameters:
|
||||
// dirToSun world-space direction TO the sun, renormalized internally,
|
||||
// may be the same vector handed to SetSun.
|
||||
// turbidity Preetham T (project spec = 2.2).
|
||||
// cameraPos world-space camera position, the FS reconstructs view
|
||||
// direction as (world_far_point - cameraPos).
|
||||
// invViewProj inverse of proj * view for the current frame, the VS
|
||||
// unprojects NDC corners through this to get world rays.
|
||||
void DrawSky( b3Vec3 dirToSun, float turbidity, b3Vec3 cameraPos, Mat4 invViewProj );
|
||||
|
||||
#ifdef __cplusplus
|
||||
} // extern "C"
|
||||
#endif
|
||||
10
samples/gfx/sokol_impl.c
Normal file
10
samples/gfx/sokol_impl.c
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Single-translation-unit build of sokol_gfx's implementation.
|
||||
// Backend macro (SOKOL_D3D11 / SOKOL_METAL / SOKOL_GLCORE) is provided by
|
||||
// the `sokol` INTERFACE target. On macOS this file is compiled as
|
||||
// Objective-C with ARC.
|
||||
|
||||
#define SOKOL_IMPL
|
||||
#include "sokol_gfx.h"
|
||||
115
samples/gfx/text.c
Normal file
115
samples/gfx/text.c
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "gfx/text.h"
|
||||
|
||||
#include <assert.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
// Per-frame array of label entries. Cap and per-entry text length are sized
|
||||
// for the highest-density label scene we expect (Box3D's body names + joint
|
||||
// types + contact IDs on a busy demo). Bump if a real scene saturates. The
|
||||
// text fits inline so an entry stays small and we don't need a second arena
|
||||
// for the strings.
|
||||
#define TEXT_CAPACITY 1024
|
||||
#define TEXT_BUFFER_SIZE 64 // 63 chars + NUL
|
||||
|
||||
typedef struct TextSlot
|
||||
{
|
||||
TextSpace space;
|
||||
b3Vec3 worldPos;
|
||||
int screenX;
|
||||
int screenY;
|
||||
Vec4 color;
|
||||
char text[TEXT_BUFFER_SIZE];
|
||||
} TextSlot;
|
||||
|
||||
static TextSlot s_slots[TEXT_CAPACITY];
|
||||
static TextEntry s_entries[TEXT_CAPACITY];
|
||||
static int s_count;
|
||||
|
||||
void ResetTextArena( void )
|
||||
{
|
||||
s_count = 0;
|
||||
}
|
||||
|
||||
// Claim a slot and copy the text in, truncating at the cap boundary. Returns
|
||||
// the slot or NULL on overflow. Caller fills the space-specific fields.
|
||||
static TextSlot* AppendSlot( Vec4 color, const char* text )
|
||||
{
|
||||
if ( text == NULL )
|
||||
return NULL;
|
||||
if ( s_count >= TEXT_CAPACITY )
|
||||
return NULL;
|
||||
|
||||
TextSlot* slot = &s_slots[s_count];
|
||||
slot->color = color;
|
||||
// strncpy intentionally, we want explicit NUL-termination at the cap
|
||||
// boundary even if the source is longer. strncpy alone doesn't guarantee
|
||||
// the terminator on truncation. The explicit write below does.
|
||||
strncpy( slot->text, text, TEXT_BUFFER_SIZE - 1 );
|
||||
slot->text[TEXT_BUFFER_SIZE - 1] = '\0';
|
||||
return slot;
|
||||
}
|
||||
|
||||
static void PublishSlot( const TextSlot* slot )
|
||||
{
|
||||
s_entries[s_count].space = slot->space;
|
||||
s_entries[s_count].worldPos = slot->worldPos;
|
||||
s_entries[s_count].screenX = slot->screenX;
|
||||
s_entries[s_count].screenY = slot->screenY;
|
||||
s_entries[s_count].color = slot->color;
|
||||
s_entries[s_count].text = slot->text;
|
||||
s_count += 1;
|
||||
}
|
||||
|
||||
void DrawString( b3Vec3 worldPos, Vec4 color, const char* text )
|
||||
{
|
||||
TextSlot* slot = AppendSlot( color, text );
|
||||
if ( slot == NULL )
|
||||
return;
|
||||
slot->space = TEXT_SPACE_WORLD;
|
||||
slot->worldPos = worldPos;
|
||||
slot->screenX = 0;
|
||||
slot->screenY = 0;
|
||||
PublishSlot( slot );
|
||||
}
|
||||
|
||||
void DrawScreenString( int x, int y, Vec4 color, const char* text )
|
||||
{
|
||||
TextSlot* slot = AppendSlot( color, text );
|
||||
if ( slot == NULL )
|
||||
return;
|
||||
slot->space = TEXT_SPACE_SCREEN;
|
||||
slot->worldPos = b3Vec3_zero;
|
||||
slot->screenX = x;
|
||||
slot->screenY = y;
|
||||
PublishSlot( slot );
|
||||
}
|
||||
|
||||
void DrawScreenStringFormat( int x, int y, Vec4 color, const char* fmt, ... )
|
||||
{
|
||||
if ( fmt == NULL )
|
||||
return;
|
||||
char buffer[TEXT_BUFFER_SIZE];
|
||||
va_list args;
|
||||
va_start( args, fmt );
|
||||
vsnprintf( buffer, sizeof( buffer ), fmt, args );
|
||||
va_end( args );
|
||||
DrawScreenString( x, y, color, buffer );
|
||||
}
|
||||
|
||||
int GetTextCount( void )
|
||||
{
|
||||
return s_count;
|
||||
}
|
||||
|
||||
const TextEntry* GetTextAt( int i )
|
||||
{
|
||||
assert( i >= 0 && i < s_count );
|
||||
return &s_entries[i];
|
||||
}
|
||||
84
samples/gfx/text.h
Normal file
84
samples/gfx/text.h
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Text label storage, world space and screen space.
|
||||
//
|
||||
// Pure C so the box3d adapter (also C) can submit labels via DrawString, and
|
||||
// the unit test for the projection helper can pull this in without ImGui.
|
||||
// The renderer doesn't rasterize text itself: labels accumulate in a fixed
|
||||
// per-frame array, ResetTextArena clears the array at the start of each
|
||||
// frame (called from ResetFrameArena), and the GUI shell drains the
|
||||
// array after the scene renders. World entries project to screen pixels
|
||||
// with the last rendered camera, screen entries pass through their pixel
|
||||
// position as-is, both emit via ImGui's background draw list. That means
|
||||
// labels only appear when the app runs through StartUIFrame,
|
||||
// RenderFrameOffscreen alone is not a label-rendering path.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "gfx/projection.h"
|
||||
#include "gfx/utility.h"
|
||||
|
||||
#include <stdbool.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"
|
||||
{
|
||||
#endif
|
||||
|
||||
// Whether an entry carries a world position to project or a screen pixel to
|
||||
// use directly.
|
||||
typedef enum TextSpace
|
||||
{
|
||||
TEXT_SPACE_WORLD = 0,
|
||||
TEXT_SPACE_SCREEN = 1,
|
||||
} TextSpace;
|
||||
|
||||
typedef struct TextEntry
|
||||
{
|
||||
TextSpace space;
|
||||
b3Vec3 worldPos; // valid when space == TEXT_SPACE_WORLD
|
||||
int screenX; // framebuffer pixels, origin top-left, when space == TEXT_SPACE_SCREEN
|
||||
int screenY;
|
||||
Vec4 color; // linear RGBA, bytes pass through to ImGui as-is
|
||||
const char* text; // points into the per-frame text arena, NUL-terminated
|
||||
} TextEntry;
|
||||
|
||||
// Submit a UTF-8 string at a world-space position. Text is copied into the
|
||||
// per-frame text arena and truncated to fit (current cap: 63 chars + NUL).
|
||||
// Color is linear RGBA. Logs and drops on overflow.
|
||||
void DrawString( b3Vec3 worldPos, Vec4 color, const char* text );
|
||||
|
||||
// Submit a UTF-8 string at a screen-pixel position (origin top-left, Y down,
|
||||
// framebuffer pixels). Same copy/truncation/overflow rules as DrawString.
|
||||
void DrawScreenString( int x, int y, Vec4 color, const char* text );
|
||||
void DrawScreenStringFormat( int x, int y, Vec4 color, const char* fmt, ... );
|
||||
|
||||
// Iteration surface for the GUI shell. Pointers/strings are valid until
|
||||
// the next ResetTextArena (called by ResetFrameArena, which the GUI shell
|
||||
// invokes each frame). Caller is expected to honor 0 <= i < count.
|
||||
int GetTextCount( void );
|
||||
const TextEntry* GetTextAt( int i );
|
||||
|
||||
// Wipe the per-frame text array. Called from ResetFrameArena.
|
||||
void ResetTextArena( void );
|
||||
|
||||
// Resolve an entry to its screen-pixel position. Screen entries pass through;
|
||||
// world entries project through view/proj for the given viewport. Returns
|
||||
// false (leaving outputs untouched) when a world entry is off-frustum or
|
||||
// behind the camera, matching ProjectWorldToScreen.
|
||||
static inline bool ResolveTextScreenPos( const TextEntry* e, Mat4 view, Mat4 proj, int viewportW, int viewportH,
|
||||
float* outScreenX, float* outScreenY )
|
||||
{
|
||||
if ( e->space == TEXT_SPACE_SCREEN )
|
||||
{
|
||||
*outScreenX = (float)e->screenX;
|
||||
*outScreenY = (float)e->screenY;
|
||||
return true;
|
||||
}
|
||||
return ProjectWorldToScreen( view, proj, viewportW, viewportH, e->worldPos, outScreenX, outScreenY );
|
||||
}
|
||||
|
||||
#ifdef __cplusplus
|
||||
} // extern "C"
|
||||
#endif
|
||||
137
samples/gfx/tone_map.c
Normal file
137
samples/gfx/tone_map.c
Normal file
|
|
@ -0,0 +1,137 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "gfx/tone_map.h"
|
||||
|
||||
#include "gfx/utility.h"
|
||||
#include "tonemap.glsl.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
// Two slots cover the only realistic divergence, the swapchain target
|
||||
// (has depth attachment from sokol_app's default) and the offscreen test
|
||||
// target (color only, no depth). Hitting this cap means a third
|
||||
// color/depth pair showed up. Raise it (and probably ask why).
|
||||
#define TONEMAP_MAX_PIPELINES 2
|
||||
|
||||
static struct
|
||||
{
|
||||
sg_shader shader;
|
||||
sg_sampler sampler;
|
||||
struct
|
||||
{
|
||||
sg_pixel_format colorFormat;
|
||||
sg_pixel_format depthFormat;
|
||||
sg_pipeline pipeline;
|
||||
} pipelines[TONEMAP_MAX_PIPELINES];
|
||||
int pipelineCount;
|
||||
bool ready;
|
||||
} s_tm;
|
||||
|
||||
static sg_pipeline ensurePipeline( sg_pixel_format colorFormat, sg_pixel_format depthFormat )
|
||||
{
|
||||
for ( int i = 0; i < s_tm.pipelineCount; ++i )
|
||||
{
|
||||
if ( s_tm.pipelines[i].colorFormat == colorFormat && s_tm.pipelines[i].depthFormat == depthFormat )
|
||||
{
|
||||
return s_tm.pipelines[i].pipeline;
|
||||
}
|
||||
}
|
||||
if ( s_tm.pipelineCount >= TONEMAP_MAX_PIPELINES )
|
||||
{
|
||||
fprintf( stderr, "tonemap: pipeline cache exhausted (max %d format pairs)\n", TONEMAP_MAX_PIPELINES );
|
||||
sg_pipeline empty = { 0 };
|
||||
return empty;
|
||||
}
|
||||
|
||||
sg_pipeline_desc pdesc = { 0 };
|
||||
pdesc.shader = s_tm.shader;
|
||||
pdesc.colors[0].pixel_format = colorFormat;
|
||||
// color_count isn't inferred from a single non-NONE entry, has to be
|
||||
// explicit (cf. MEMORY note on MRT color_count gotcha).
|
||||
pdesc.color_count = 1;
|
||||
// Depth format mirrors the target's depth attachment (or NONE) so
|
||||
// sokol's pipeline-vs-attachment validation is happy. Write/compare
|
||||
// are off either way, the tonemap is depth-blind.
|
||||
pdesc.depth.pixel_format = depthFormat;
|
||||
pdesc.depth.write_enabled = false;
|
||||
pdesc.depth.compare = SG_COMPAREFUNC_ALWAYS;
|
||||
pdesc.cull_mode = SG_CULLMODE_NONE;
|
||||
pdesc.face_winding = SG_FACEWINDING_CCW;
|
||||
pdesc.sample_count = 1;
|
||||
pdesc.label = "tonemap_pipeline";
|
||||
|
||||
const sg_pipeline pip = sg_make_pipeline( &pdesc );
|
||||
s_tm.pipelines[s_tm.pipelineCount].colorFormat = colorFormat;
|
||||
s_tm.pipelines[s_tm.pipelineCount].depthFormat = depthFormat;
|
||||
s_tm.pipelines[s_tm.pipelineCount].pipeline = pip;
|
||||
++s_tm.pipelineCount;
|
||||
return pip;
|
||||
}
|
||||
|
||||
void InitToneMap( void )
|
||||
{
|
||||
s_tm.shader = sg_make_shader( tonemap_prog_shader_desc( sg_query_backend() ) );
|
||||
|
||||
sg_sampler_desc sdesc = { 0 };
|
||||
sdesc.min_filter = SG_FILTER_LINEAR;
|
||||
sdesc.mag_filter = SG_FILTER_LINEAR;
|
||||
sdesc.mipmap_filter = SG_FILTER_NEAREST;
|
||||
sdesc.wrap_u = SG_WRAP_CLAMP_TO_EDGE;
|
||||
sdesc.wrap_v = SG_WRAP_CLAMP_TO_EDGE;
|
||||
sdesc.wrap_w = SG_WRAP_CLAMP_TO_EDGE;
|
||||
sdesc.label = "tonemap_sampler";
|
||||
s_tm.sampler = sg_make_sampler( &sdesc );
|
||||
|
||||
s_tm.ready = true;
|
||||
}
|
||||
|
||||
void ShutdownToneMap( void )
|
||||
{
|
||||
if ( !s_tm.ready )
|
||||
{
|
||||
return;
|
||||
}
|
||||
for ( int i = 0; i < s_tm.pipelineCount; ++i )
|
||||
{
|
||||
sg_destroy_pipeline( s_tm.pipelines[i].pipeline );
|
||||
s_tm.pipelines[i].pipeline.id = 0;
|
||||
s_tm.pipelines[i].colorFormat = SG_PIXELFORMAT_NONE;
|
||||
s_tm.pipelines[i].depthFormat = SG_PIXELFORMAT_NONE;
|
||||
}
|
||||
s_tm.pipelineCount = 0;
|
||||
sg_destroy_sampler( s_tm.sampler );
|
||||
sg_destroy_shader( s_tm.shader );
|
||||
s_tm.ready = false;
|
||||
}
|
||||
|
||||
void SubmitToneMap( sg_view sceneColorView, sg_pixel_format outputColorFormat, sg_pixel_format outputDepthFormat, float ev,
|
||||
float saturation )
|
||||
{
|
||||
if ( !s_tm.ready )
|
||||
{
|
||||
return;
|
||||
}
|
||||
const sg_pipeline pip = ensurePipeline( outputColorFormat, outputDepthFormat );
|
||||
if ( pip.id == 0 )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
sg_apply_pipeline( pip );
|
||||
|
||||
sg_bindings bindings = { 0 };
|
||||
bindings.views[VIEW_tonemap_tex_scene] = sceneColorView;
|
||||
bindings.samplers[SMP_tonemap_smp_scene] = s_tm.sampler;
|
||||
sg_apply_bindings( &bindings );
|
||||
|
||||
const sg_backend backend = sg_query_backend();
|
||||
const float uvYSign = ( backend == SG_BACKEND_GLCORE || backend == SG_BACKEND_GLES3 ) ? 1.0f : -1.0f;
|
||||
|
||||
tonemap_ub_tonemap_t ub = { 0 };
|
||||
ub.params = MakeVec4( ev, uvYSign, saturation, 0.0f );
|
||||
sg_apply_uniforms( UB_tonemap_ub_tonemap, &SG_RANGE( ub ) );
|
||||
|
||||
sg_draw( 0, 3, 1 );
|
||||
}
|
||||
56
samples/gfx/tone_map.h
Normal file
56
samples/gfx/tone_map.h
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// AgX tonemap pass.
|
||||
//
|
||||
// Final post-process: reads the resolved HDR scene color (RGBA16F) and
|
||||
// writes display-encoded sRGB to a linear-format LDR target (swapchain
|
||||
// in the demo, caller-owned attachment via RenderFrameOffscreen). See
|
||||
// the shader at shaders/post/tonemap.glsl for the AgX implementation
|
||||
// and the rationale for skipping the trailing pow(2.2) EOTF.
|
||||
//
|
||||
// The pass owns its pipeline cache. The output color format isn't known at
|
||||
// init time, RenderFrame targets the swapchain format, while
|
||||
// RenderFrameOffscreen targets whatever the caller supplies. Currently
|
||||
// both resolve to env.defaults.color_format, but the cache covers a future
|
||||
// where they diverge (capacity = 2).
|
||||
//
|
||||
// Single-threaded, render-thread only.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "sokol_gfx.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"
|
||||
{
|
||||
#endif
|
||||
|
||||
void InitToneMap( void );
|
||||
void ShutdownToneMap( void );
|
||||
|
||||
// Encodes one fullscreen AgX pass into the currently-open render pass.
|
||||
// The caller is responsible for sg_begin_pass / sg_end_pass on the output
|
||||
// target, this function only binds + draws.
|
||||
//
|
||||
// sceneColorView: texture-view over the resolved (single-sample) HDR
|
||||
// scene color image.
|
||||
// outputColorFormat: pixel format of the color attachment in the open
|
||||
// pass. Pipeline cache key.
|
||||
// outputDepthFormat: pixel format of the depth attachment in the open
|
||||
// pass, or SG_PIXELFORMAT_NONE if the target has no
|
||||
// depth. The swapchain path supplies the env default,
|
||||
// offscreen tests pass NONE. Pipeline cache key,
|
||||
// sokol enforces a pipeline-vs-attachment match even
|
||||
// though the tonemap pipeline doesn't touch depth.
|
||||
// ev: exposure stops applied before AgX. -2.0 matches
|
||||
// the spec for Preetham at physical strength.
|
||||
// saturation: AgX-look saturation applied after the AgX sigmoid.
|
||||
// 1.0 is the stock Standard look. >1.0 counteracts
|
||||
// AgX's path-to-white desaturation.
|
||||
void SubmitToneMap( sg_view sceneColorView, sg_pixel_format outputColorFormat, sg_pixel_format outputDepthFormat, float ev,
|
||||
float saturation );
|
||||
|
||||
#ifdef __cplusplus
|
||||
} // extern "C"
|
||||
#endif
|
||||
228
samples/gfx/utility.h
Normal file
228
samples/gfx/utility.h
Normal file
|
|
@ -0,0 +1,228 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Math utilities: the 4-wide types Box3D does not provide.
|
||||
//
|
||||
// Vec4, linear-RGBA colors and matrix columns.
|
||||
// Mat4, camera-space matrices (view / proj / view-proj / shadow).
|
||||
//
|
||||
// Per-shape transforms use b3Transform directly. Mat4 only appears for
|
||||
// camera-space matrices. These two types may later move into Box3D, this
|
||||
// header is written to make that a clean cut-paste.
|
||||
//
|
||||
// Conventions match the renderer and Box3D:
|
||||
// * Column-major storage, multiplied as M * v.
|
||||
// * Right-handed, Y-up. The renderer drives reverse-Z by passing near/far
|
||||
// swapped into the perspective builder.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "box3d/math_functions.h"
|
||||
#include "box3d/types.h"
|
||||
|
||||
#include <math.h>
|
||||
|
||||
typedef struct Vec4
|
||||
{
|
||||
float x, y, z, w;
|
||||
} Vec4;
|
||||
|
||||
// Column-major 4x4. cx / cy / cz are the basis columns and cw the
|
||||
// translation column, matching b3Matrix3's cx / cy / cz naming.
|
||||
typedef struct Mat4
|
||||
{
|
||||
Vec4 cx, cy, cz, cw;
|
||||
} Mat4;
|
||||
|
||||
static inline Vec4 MakeVec4( float x, float y, float z, float w )
|
||||
{
|
||||
Vec4 v = { x, y, z, w };
|
||||
return v;
|
||||
}
|
||||
|
||||
static inline Mat4 MakeIdentity( void )
|
||||
{
|
||||
Mat4 m = {
|
||||
{ 1.0f, 0.0f, 0.0f, 0.0f },
|
||||
{ 0.0f, 1.0f, 0.0f, 0.0f },
|
||||
{ 0.0f, 0.0f, 1.0f, 0.0f },
|
||||
{ 0.0f, 0.0f, 0.0f, 1.0f },
|
||||
};
|
||||
return m;
|
||||
}
|
||||
|
||||
// Matrix times column-vector.
|
||||
static inline Vec4 MulMV4( Mat4 m, Vec4 v )
|
||||
{
|
||||
Vec4 r;
|
||||
r.x = m.cx.x * v.x + m.cy.x * v.y + m.cz.x * v.z + m.cw.x * v.w;
|
||||
r.y = m.cx.y * v.x + m.cy.y * v.y + m.cz.y * v.z + m.cw.y * v.w;
|
||||
r.z = m.cx.z * v.x + m.cy.z * v.y + m.cz.z * v.z + m.cw.z * v.w;
|
||||
r.w = m.cx.w * v.x + m.cy.w * v.y + m.cz.w * v.z + m.cw.w * v.w;
|
||||
return r;
|
||||
}
|
||||
|
||||
// Matrix product: applying the result is equivalent to applying b then a.
|
||||
static inline Mat4 MulMM4( Mat4 a, Mat4 b )
|
||||
{
|
||||
Mat4 r;
|
||||
r.cx = MulMV4( a, b.cx );
|
||||
r.cy = MulMV4( a, b.cy );
|
||||
r.cz = MulMV4( a, b.cz );
|
||||
r.cw = MulMV4( a, b.cw );
|
||||
return r;
|
||||
}
|
||||
|
||||
static inline Mat4 Transpose4( Mat4 m )
|
||||
{
|
||||
Mat4 r;
|
||||
r.cx = MakeVec4( m.cx.x, m.cy.x, m.cz.x, m.cw.x );
|
||||
r.cy = MakeVec4( m.cx.y, m.cy.y, m.cz.y, m.cw.y );
|
||||
r.cz = MakeVec4( m.cx.z, m.cy.z, m.cz.z, m.cw.z );
|
||||
r.cw = MakeVec4( m.cx.w, m.cy.w, m.cz.w, m.cw.w );
|
||||
return r;
|
||||
}
|
||||
|
||||
// Right-handed perspective with a 0..1 clip-Z. The renderer drives reverse-Z by passing
|
||||
// nearPlane / farPlane swapped, which puts clip-Z = 1 at the near plane and 0 at the far.
|
||||
//
|
||||
// This is the finite-far form. The infinite-far variant (set cz.z = 0,
|
||||
// cw.z = nearPlane in the reverse-Z arg order) would give strictly better
|
||||
// precision at distance and remove `far` from the matrix entirely, per
|
||||
// Upchurch & Desbrun's roundoff analysis.
|
||||
static inline Mat4 MakePerspective( float fovY, float aspect, float nearPlane, float farPlane )
|
||||
{
|
||||
Mat4 m = { { 0.0f, 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f, 0.0f } };
|
||||
|
||||
float cotangent = 1.0f / tanf( fovY / 2.0f );
|
||||
m.cx.x = cotangent / aspect;
|
||||
m.cy.y = cotangent;
|
||||
m.cz.w = -1.0f;
|
||||
m.cz.z = farPlane / ( nearPlane - farPlane );
|
||||
m.cw.z = ( nearPlane * farPlane ) / ( nearPlane - farPlane );
|
||||
return m;
|
||||
}
|
||||
|
||||
// Same perspective as MakePerspective, but also fills the closed-form
|
||||
// inverse from the same parameters. The general inverse of a perspective
|
||||
// matrix is lossy. Building it analytically here keeps the un-project path
|
||||
// more accurate.
|
||||
static inline void MakePerspectiveAndInverse( Mat4* outProj, Mat4* outProjInv, float fovY, float aspect, float nearPlane,
|
||||
float farPlane )
|
||||
{
|
||||
float tanHalf = tanf( fovY / 2.0f );
|
||||
float cotangent = 1.0f / tanHalf;
|
||||
|
||||
// c, d are the two non-trivial slots of the forward matrix.
|
||||
float c = farPlane / ( nearPlane - farPlane );
|
||||
float d = ( nearPlane * farPlane ) / ( nearPlane - farPlane );
|
||||
|
||||
Mat4 p = { { 0.0f, 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f, 0.0f } };
|
||||
p.cx.x = cotangent / aspect;
|
||||
p.cy.y = cotangent;
|
||||
p.cz.z = c;
|
||||
p.cz.w = -1.0f;
|
||||
p.cw.z = d;
|
||||
*outProj = p;
|
||||
|
||||
Mat4 pi = { { 0.0f, 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f, 0.0f } };
|
||||
pi.cx.x = aspect * tanHalf;
|
||||
pi.cy.y = tanHalf;
|
||||
pi.cz.w = 1.0f / d;
|
||||
pi.cw.z = -1.0f;
|
||||
pi.cw.w = c / d;
|
||||
*outProjInv = pi;
|
||||
}
|
||||
|
||||
// Right-handed orthographic projection with a 0..1 clip-Z. Used for the shadow cascade light matrices.
|
||||
static inline Mat4 MakeOrthographic( float left, float right, float bottom, float top, float nearPlane, float farPlane )
|
||||
{
|
||||
Mat4 m = { { 0.0f, 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f, 0.0f } };
|
||||
m.cx.x = 2.0f / ( right - left );
|
||||
m.cy.y = 2.0f / ( top - bottom );
|
||||
m.cz.z = 1.0f / ( nearPlane - farPlane );
|
||||
m.cw.w = 1.0f;
|
||||
m.cw.x = ( left + right ) / ( left - right );
|
||||
m.cw.y = ( bottom + top ) / ( bottom - top );
|
||||
m.cw.z = nearPlane / ( nearPlane - farPlane );
|
||||
return m;
|
||||
}
|
||||
|
||||
// Right-handed look-at.
|
||||
static inline Mat4 MakeLookAt( b3Vec3 eye, b3Vec3 center, b3Vec3 up )
|
||||
{
|
||||
b3Vec3 f = b3Normalize( b3Sub( center, eye ) );
|
||||
b3Vec3 s = b3Normalize( b3Cross( f, up ) );
|
||||
b3Vec3 u = b3Cross( s, f );
|
||||
|
||||
Mat4 m;
|
||||
m.cx = MakeVec4( s.x, u.x, -f.x, 0.0f );
|
||||
m.cy = MakeVec4( s.y, u.y, -f.y, 0.0f );
|
||||
m.cz = MakeVec4( s.z, u.z, -f.z, 0.0f );
|
||||
m.cw = MakeVec4( -b3Dot( s, eye ), -b3Dot( u, eye ), b3Dot( f, eye ), 1.0f );
|
||||
return m;
|
||||
}
|
||||
|
||||
// Build a view matrix and its inverse together from the camera basis. `right`,
|
||||
// `up` and `forward` are the world-space view-X / view-Y / view-Z directions:
|
||||
// forward is +view-Z (pivot -> eye), so
|
||||
// the camera looks down -forward. The basis must be orthonormal and right-
|
||||
// handed (right = cross(up, forward)), both outputs assume that.
|
||||
//
|
||||
// viewInv is the camera's "world matrix": columns are right / up / forward /
|
||||
// eye. view is its transpose-with-shifted-translation form. Neither requires
|
||||
// any inversion at runtime.
|
||||
static inline void MakeViewAndInverse( Mat4* outView, Mat4* outViewInv, b3Vec3 right, b3Vec3 up, b3Vec3 forward, b3Vec3 eye )
|
||||
{
|
||||
Mat4 v;
|
||||
v.cx = MakeVec4( right.x, up.x, forward.x, 0.0f );
|
||||
v.cy = MakeVec4( right.y, up.y, forward.y, 0.0f );
|
||||
v.cz = MakeVec4( right.z, up.z, forward.z, 0.0f );
|
||||
v.cw = MakeVec4( -b3Dot( right, eye ), -b3Dot( up, eye ), -b3Dot( forward, eye ), 1.0f );
|
||||
*outView = v;
|
||||
|
||||
Mat4 vi;
|
||||
vi.cx = MakeVec4( right.x, right.y, right.z, 0.0f );
|
||||
vi.cy = MakeVec4( up.x, up.y, up.z, 0.0f );
|
||||
vi.cz = MakeVec4( forward.x, forward.y, forward.z, 0.0f );
|
||||
vi.cw = MakeVec4( eye.x, eye.y, eye.z, 1.0f );
|
||||
*outViewInv = vi;
|
||||
}
|
||||
|
||||
// Build a 4x4 model matrix from a Box3D rigid transform plus a (possibly
|
||||
// non-uniform) scale.
|
||||
static inline Mat4 MakeMat4FromTransform( b3Transform t, b3Vec3 scale )
|
||||
{
|
||||
b3Matrix3 r = b3MakeMatrixFromQuat( t.q );
|
||||
Mat4 m;
|
||||
m.cx = MakeVec4( scale.x * r.cx.x, scale.x * r.cx.y, scale.x * r.cx.z, 0.0f );
|
||||
m.cy = MakeVec4( scale.y * r.cy.x, scale.y * r.cy.y, scale.y * r.cy.z, 0.0f );
|
||||
m.cz = MakeVec4( scale.z * r.cz.x, scale.z * r.cz.y, scale.z * r.cz.z, 0.0f );
|
||||
m.cw = MakeVec4( t.p.x, t.p.y, t.p.z, 1.0f );
|
||||
return m;
|
||||
}
|
||||
|
||||
static inline float SrgbToLinear( float c )
|
||||
{
|
||||
return c <= 0.04045f ? c / 12.92f : powf( ( c + 0.055f ) / 1.055f, 2.4f );
|
||||
}
|
||||
|
||||
static inline Vec4 MakeColor( b3HexColor hexColor )
|
||||
{
|
||||
uint32_t v = (uint32_t)hexColor;
|
||||
float k = 1.0f / 255.0f;
|
||||
float r = (float)( ( v >> 16 ) & 0xFFu ) * k;
|
||||
float g = (float)( ( v >> 8 ) & 0xFFu ) * k;
|
||||
float b = (float)( v & 0xFFu ) * k;
|
||||
return MakeVec4( SrgbToLinear( r ), SrgbToLinear( g ), SrgbToLinear( b ), 1.0f );
|
||||
}
|
||||
|
||||
static inline Vec4 MakeColorAlpha( b3HexColor hexColor, float alpha )
|
||||
{
|
||||
uint32_t v = (uint32_t)hexColor;
|
||||
float k = 1.0f / 255.0f;
|
||||
float r = (float)( ( v >> 16 ) & 0xFFu ) * k;
|
||||
float g = (float)( ( v >> 8 ) & 0xFFu ) * k;
|
||||
float b = (float)( v & 0xFFu ) * k;
|
||||
return MakeVec4( SrgbToLinear( r ), SrgbToLinear( g ), SrgbToLinear( b ), alpha );
|
||||
}
|
||||
449
samples/host/camera.cpp
Normal file
449
samples/host/camera.cpp
Normal file
|
|
@ -0,0 +1,449 @@
|
|||
#include "camera.h"
|
||||
|
||||
#include "gfx/picking.h"
|
||||
|
||||
#include "box3d/math_functions.h"
|
||||
#include "sokol_app.h"
|
||||
|
||||
#include <math.h>
|
||||
|
||||
static constexpr float HALF_PI = B3_PI * 0.5f;
|
||||
static constexpr float DEG_TO_RAD = B3_PI / 180.0f;
|
||||
static constexpr float ORBIT_SENS = 0.005f; // radians per pixel
|
||||
static constexpr float FLY_LOOK_SENS = 0.005f; // radians per pixel
|
||||
static constexpr float PAN_SENS = 0.005f; // meters per pixel per meter of radius
|
||||
static constexpr float RADIAL_ZOOM_SENS = 0.02f; // meters per pixel (alt+right-drag)
|
||||
static constexpr float FLY_SPEED_STEP = 1.0f; // m/s per scroll tick
|
||||
static constexpr float ZOOM_STEP = 0.9f; // multiplier per scroll tick
|
||||
static constexpr float MIN_DIST = 0.1f;
|
||||
static constexpr float MAX_DIST = 1000.0f;
|
||||
static constexpr float MIN_SPEED = 0.06f; // matches box3d's 0.001*60
|
||||
static constexpr float MAX_SPEED = 30000.0f; // matches box3d's 500*60
|
||||
static constexpr float PITCH_LIM = HALF_PI - 0.01f;
|
||||
static constexpr float THIRD_PERSON_MIN_RADIUS = 0.25f; // matches box3d
|
||||
|
||||
// Build a reverse-Z RH projection and its inverse together by swapping the
|
||||
// near/far args. mat4PerspectiveAndInverse normally puts ndc.z=0 at near, 1
|
||||
// at far; with the arguments swapped you get 1 at near, 0 at far - what the
|
||||
// project's pipeline expects (compare GREATER, far-clear 0). The inverse is
|
||||
// closed-form from the same params so the un-project path stays accurate.
|
||||
static void ReverseZPerspectiveAndInverse( Mat4* outProj, Mat4* outProjInv, float fov, float aspect, float n, float f )
|
||||
{
|
||||
MakePerspectiveAndInverse( outProj, outProjInv, fov, aspect, f, n );
|
||||
}
|
||||
|
||||
// Yaw/pitch -> the "+view-Z" direction (pivot -> camera), matching Box3D's
|
||||
// sample convention. The actual looking direction is -ForwardFromAngles.
|
||||
static b3Vec3 ForwardFromAngles( float yaw, float pitch )
|
||||
{
|
||||
const float cp = cosf( pitch );
|
||||
return b3Vec3{ sinf( yaw ) * cp, sinf( pitch ), cosf( yaw ) * cp };
|
||||
}
|
||||
|
||||
// Refresh the world-space basis and the view / viewInv pair from yaw / pitch /
|
||||
// pivot / radius. Called from every state mutator (SetOrbit, Frame, Update)
|
||||
// so consumers can read m_view / m_viewInv without an inversion step.
|
||||
static void RebuildBasisAndView( Camera& c )
|
||||
{
|
||||
const b3Vec3 forward = ForwardFromAngles( c.m_yaw, c.m_pitch );
|
||||
const b3Vec3 worldUp = { 0.0f, 1.0f, 0.0f };
|
||||
// up = worldUp re-orthogonalized against forward. right = up x forward.
|
||||
// Matches Box3D's UpdateTransform; produces a right-handed view basis.
|
||||
const b3Vec3 upUnnorm = b3Sub( worldUp, b3MulSV( b3Dot( worldUp, forward ), forward ) );
|
||||
const b3Vec3 up = b3Normalize( upUnnorm );
|
||||
const b3Vec3 right = b3Normalize( b3Cross( up, forward ) );
|
||||
const b3Vec3 position = { c.m_pivot.x + forward.x * c.m_radius, c.m_pivot.y + forward.y * c.m_radius,
|
||||
c.m_pivot.z + forward.z * c.m_radius };
|
||||
|
||||
c.m_position = position;
|
||||
c.m_right = right;
|
||||
c.m_up = up;
|
||||
c.m_forward = forward;
|
||||
MakeViewAndInverse( &c.m_view, &c.m_viewInv, right, up, forward, position );
|
||||
}
|
||||
|
||||
Camera::Camera()
|
||||
: m_pivot{ 0.0f, 0.0f, 0.0f }
|
||||
, m_yaw( 35.0f * DEG_TO_RAD )
|
||||
, m_pitch( -25.0f * DEG_TO_RAD )
|
||||
, m_radius( 25.0f )
|
||||
, m_fov( 60.0f * DEG_TO_RAD )
|
||||
, m_near( 0.1f )
|
||||
, m_far( 1000.0f )
|
||||
, m_speed( 10.0f )
|
||||
, m_width( 0 )
|
||||
, m_height( 0 )
|
||||
, m_thirdPerson( false )
|
||||
, m_position{ 0.0f, 0.0f, 0.0f }
|
||||
, m_right{ 1.0f, 0.0f, 0.0f }
|
||||
, m_up{ 0.0f, 1.0f, 0.0f }
|
||||
, m_forward{ 0.0f, 0.0f, 1.0f }
|
||||
, m_view( MakeIdentity() )
|
||||
, m_viewInv( MakeIdentity() )
|
||||
, m_proj( MakeIdentity() )
|
||||
, m_projInv( MakeIdentity() )
|
||||
{
|
||||
RebuildBasisAndView( *this );
|
||||
RebuildProj( 1.0f );
|
||||
}
|
||||
|
||||
void Camera::RebuildProj( float aspect )
|
||||
{
|
||||
if ( aspect <= 0.0f )
|
||||
aspect = 1.0f;
|
||||
ReverseZPerspectiveAndInverse( &m_proj, &m_projInv, m_fov, aspect, m_near, m_far );
|
||||
}
|
||||
|
||||
void Camera::Frame( b3AABB aabb, float aspect, float padding )
|
||||
{
|
||||
if ( !b3IsValidAABB( aabb ) )
|
||||
{
|
||||
return;
|
||||
}
|
||||
b3Vec3 center = b3AABB_Center( aabb );
|
||||
b3Vec3 ext = b3AABB_Extents( aabb ); // half-extents
|
||||
float r = sqrtf( ext.x * ext.x + ext.y * ext.y + ext.z * ext.z );
|
||||
m_pivot = center;
|
||||
if ( r < 1.0e-6f )
|
||||
{
|
||||
// Point-like; preserve current radius, just retarget. The cached
|
||||
// position/basis depend on m_pivot, so refresh them before returning.
|
||||
RebuildBasisAndView( *this );
|
||||
return;
|
||||
}
|
||||
if ( aspect <= 0.0f )
|
||||
{
|
||||
aspect = 1.0f;
|
||||
}
|
||||
float halfFovY = 0.5f * m_fov;
|
||||
float invTan = 1.0f / tanf( halfFovY );
|
||||
float distV = r * invTan;
|
||||
float distH = r * invTan / aspect;
|
||||
float d = ( distV > distH ) ? distV : distH;
|
||||
d *= padding;
|
||||
SetOrbit( m_yaw, m_pitch, d );
|
||||
}
|
||||
|
||||
void Camera::SetOrbit( float yawRadians, float pitchRadians, float radius )
|
||||
{
|
||||
m_yaw = yawRadians;
|
||||
if ( pitchRadians > PITCH_LIM )
|
||||
pitchRadians = PITCH_LIM;
|
||||
if ( pitchRadians < -PITCH_LIM )
|
||||
pitchRadians = -PITCH_LIM;
|
||||
m_pitch = pitchRadians;
|
||||
if ( radius < MIN_DIST )
|
||||
radius = MIN_DIST;
|
||||
if ( radius > MAX_DIST )
|
||||
radius = MAX_DIST;
|
||||
m_radius = radius;
|
||||
RebuildBasisAndView( *this );
|
||||
}
|
||||
|
||||
void Camera::SetView( float yawDegrees, float pitchDegrees, float radius, b3Vec3 pivot )
|
||||
{
|
||||
// Box3D feeds degrees; render3d stores radians. Pivot first so SetOrbit's
|
||||
// basis rebuild uses the new pivot.
|
||||
SetPivot( pivot );
|
||||
SetOrbit( yawDegrees * DEG_TO_RAD, pitchDegrees * DEG_TO_RAD, radius );
|
||||
}
|
||||
|
||||
void Camera::UpdateTransform()
|
||||
{
|
||||
RebuildBasisAndView( *this );
|
||||
}
|
||||
|
||||
b3Vec3 Camera::Position() const
|
||||
{
|
||||
return m_position;
|
||||
}
|
||||
|
||||
PickRay Camera::BuildPickRay( float x, float y ) const
|
||||
{
|
||||
PickRay ray;
|
||||
if ( !::BuildPickRay( x, y, &ray.origin, &ray.translation ) )
|
||||
{
|
||||
// Camera state not latched yet, or degenerate matrices: defined zero
|
||||
// ray so callers never read uninitialized values.
|
||||
ray.origin = m_position;
|
||||
ray.translation = b3Vec3_zero;
|
||||
}
|
||||
return ray;
|
||||
}
|
||||
|
||||
void Camera::OnEvent( const sapp_event* e )
|
||||
{
|
||||
uint32_t mods = e->modifiers & ( SAPP_MODIFIER_SHIFT | SAPP_MODIFIER_CTRL | SAPP_MODIFIER_ALT );
|
||||
const bool canOrbit = mods == SAPP_MODIFIER_ALT;
|
||||
|
||||
switch ( e->type )
|
||||
{
|
||||
case SAPP_EVENTTYPE_MOUSE_DOWN:
|
||||
if ( e->mouse_button == SAPP_MOUSEBUTTON_LEFT )
|
||||
m_leftDown = true;
|
||||
if ( e->mouse_button == SAPP_MOUSEBUTTON_RIGHT )
|
||||
m_rightDown = true;
|
||||
if ( e->mouse_button == SAPP_MOUSEBUTTON_MIDDLE )
|
||||
m_middleDown = true;
|
||||
break;
|
||||
case SAPP_EVENTTYPE_MOUSE_UP:
|
||||
if ( e->mouse_button == SAPP_MOUSEBUTTON_LEFT )
|
||||
m_leftDown = false;
|
||||
if ( e->mouse_button == SAPP_MOUSEBUTTON_RIGHT )
|
||||
m_rightDown = false;
|
||||
if ( e->mouse_button == SAPP_MOUSEBUTTON_MIDDLE )
|
||||
m_middleDown = false;
|
||||
break;
|
||||
case SAPP_EVENTTYPE_MOUSE_MOVE:
|
||||
if ( canOrbit && m_leftDown )
|
||||
{
|
||||
m_orbitDX += e->mouse_dx;
|
||||
m_orbitDY += e->mouse_dy;
|
||||
}
|
||||
else if ( canOrbit && m_middleDown )
|
||||
{
|
||||
m_panDX += e->mouse_dx;
|
||||
m_panDY += e->mouse_dy;
|
||||
}
|
||||
else if ( canOrbit && m_rightDown )
|
||||
{
|
||||
m_radialZoomDY += e->mouse_dy;
|
||||
}
|
||||
else if ( !canOrbit && m_rightDown )
|
||||
{
|
||||
// Fly-look: routed into the same orbit accumulators; Update
|
||||
// interprets them differently when m_rightDown && !m_altDown.
|
||||
m_orbitDX += e->mouse_dx;
|
||||
m_orbitDY += e->mouse_dy;
|
||||
}
|
||||
break;
|
||||
case SAPP_EVENTTYPE_MOUSE_SCROLL:
|
||||
if ( !canOrbit && m_rightDown )
|
||||
m_speedScrollAccum += e->scroll_y;
|
||||
else
|
||||
m_scrollAccum += e->scroll_y;
|
||||
break;
|
||||
case SAPP_EVENTTYPE_KEY_DOWN:
|
||||
switch ( e->key_code )
|
||||
{
|
||||
case SAPP_KEYCODE_W:
|
||||
m_wDown = true;
|
||||
break;
|
||||
case SAPP_KEYCODE_A:
|
||||
m_aDown = true;
|
||||
break;
|
||||
case SAPP_KEYCODE_S:
|
||||
m_sDown = true;
|
||||
break;
|
||||
case SAPP_KEYCODE_D:
|
||||
m_dDown = true;
|
||||
break;
|
||||
case SAPP_KEYCODE_LEFT_ALT:
|
||||
case SAPP_KEYCODE_RIGHT_ALT:
|
||||
m_altDown = true;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case SAPP_EVENTTYPE_KEY_UP:
|
||||
switch ( e->key_code )
|
||||
{
|
||||
case SAPP_KEYCODE_W:
|
||||
m_wDown = false;
|
||||
break;
|
||||
case SAPP_KEYCODE_A:
|
||||
m_aDown = false;
|
||||
break;
|
||||
case SAPP_KEYCODE_S:
|
||||
m_sDown = false;
|
||||
break;
|
||||
case SAPP_KEYCODE_D:
|
||||
m_dDown = false;
|
||||
break;
|
||||
case SAPP_KEYCODE_LEFT_ALT:
|
||||
case SAPP_KEYCODE_RIGHT_ALT:
|
||||
m_altDown = false;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case SAPP_EVENTTYPE_UNFOCUSED:
|
||||
// Drop every held input on focus loss. Otherwise a drag or a held WASD
|
||||
// key survives an alt-tab and the camera keeps moving.
|
||||
m_leftDown = false;
|
||||
m_rightDown = false;
|
||||
m_middleDown = false;
|
||||
m_wDown = false;
|
||||
m_aDown = false;
|
||||
m_sDown = false;
|
||||
m_dDown = false;
|
||||
m_altDown = false;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void Camera::Update( float dt, int width, int height )
|
||||
{
|
||||
m_width = width;
|
||||
m_height = height;
|
||||
const float aspect = ( height > 0 ) ? (float)width / (float)height : 1.0f;
|
||||
|
||||
if ( m_thirdPerson )
|
||||
{
|
||||
// Follow cam: the sample drives m_pivot to the tracked body and calls
|
||||
// UpdateTransform. The only camera input is wheel zoom on the radius.
|
||||
if ( m_scrollAccum != 0.0f )
|
||||
{
|
||||
m_radius -= m_scrollAccum;
|
||||
if ( m_radius < THIRD_PERSON_MIN_RADIUS )
|
||||
m_radius = THIRD_PERSON_MIN_RADIUS;
|
||||
}
|
||||
// Drop the other accumulators so a return to orbit/fly starts clean.
|
||||
m_orbitDX = 0.0f;
|
||||
m_orbitDY = 0.0f;
|
||||
m_panDX = 0.0f;
|
||||
m_panDY = 0.0f;
|
||||
m_radialZoomDY = 0.0f;
|
||||
m_scrollAccum = 0.0f;
|
||||
m_speedScrollAccum = 0.0f;
|
||||
RebuildBasisAndView( *this );
|
||||
RebuildProj( aspect );
|
||||
return;
|
||||
}
|
||||
|
||||
const bool flyMode = m_rightDown && !m_altDown;
|
||||
|
||||
if ( flyMode )
|
||||
{
|
||||
// Snapshot eye BEFORE rotating so yaw/pitch pivot around the eye
|
||||
// (FPS) instead of around m_pivot (orbit). After rotation we
|
||||
// back-derive m_pivot from this preserved eye so Position()
|
||||
// returns the same point regardless of look angle.
|
||||
const b3Vec3 eyeBefore = Position();
|
||||
|
||||
// FPS look: drag right -> yaw decreases (turn head right, scene
|
||||
// shifts left); drag down -> pitch increases (look down). Box3D's
|
||||
// signs - opposite of render3d's orbit pitch sign on purpose.
|
||||
if ( m_orbitDX != 0.0f || m_orbitDY != 0.0f )
|
||||
{
|
||||
m_yaw -= m_orbitDX * FLY_LOOK_SENS;
|
||||
m_pitch += m_orbitDY * FLY_LOOK_SENS;
|
||||
if ( m_pitch > PITCH_LIM )
|
||||
m_pitch = PITCH_LIM;
|
||||
if ( m_pitch < -PITCH_LIM )
|
||||
m_pitch = -PITCH_LIM;
|
||||
}
|
||||
|
||||
const b3Vec3 forward = ForwardFromAngles( m_yaw, m_pitch );
|
||||
|
||||
float wasdF = 0.0f; // +forward = backwards, since forward = pivot->eye
|
||||
float wasdR = 0.0f;
|
||||
if ( m_wDown )
|
||||
wasdF -= 1.0f;
|
||||
if ( m_sDown )
|
||||
wasdF += 1.0f;
|
||||
if ( m_dDown )
|
||||
wasdR += 1.0f;
|
||||
if ( m_aDown )
|
||||
wasdR -= 1.0f;
|
||||
|
||||
b3Vec3 eye = eyeBefore;
|
||||
if ( wasdF != 0.0f || wasdR != 0.0f )
|
||||
{
|
||||
// Right = normalize(worldUp x forward), matching Box3D's
|
||||
// UpdateTransform. worldUp = (0,1,0).
|
||||
const b3Vec3 worldUp = { 0.0f, 1.0f, 0.0f };
|
||||
b3Vec3 right = b3Cross( worldUp, forward );
|
||||
const float rlen = sqrtf( right.x * right.x + right.y * right.y + right.z * right.z );
|
||||
if ( rlen > 1.0e-6f )
|
||||
{
|
||||
right.x /= rlen;
|
||||
right.y /= rlen;
|
||||
right.z /= rlen;
|
||||
}
|
||||
const float step = m_speed * dt;
|
||||
eye.x += forward.x * wasdF * step + right.x * wasdR * step;
|
||||
eye.y += forward.y * wasdF * step + right.y * wasdR * step;
|
||||
eye.z += forward.z * wasdF * step + right.z * wasdR * step;
|
||||
}
|
||||
|
||||
// Back-derive the pivot so Position() stays consistent and a return
|
||||
// to orbit mode preserves the current look direction.
|
||||
m_pivot.x = eye.x - forward.x * m_radius;
|
||||
m_pivot.y = eye.y - forward.y * m_radius;
|
||||
m_pivot.z = eye.z - forward.z * m_radius;
|
||||
|
||||
if ( m_speedScrollAccum != 0.0f )
|
||||
{
|
||||
m_speed += m_speedScrollAccum * FLY_SPEED_STEP;
|
||||
if ( m_speed < MIN_SPEED )
|
||||
m_speed = MIN_SPEED;
|
||||
if ( m_speed > MAX_SPEED )
|
||||
m_speed = MAX_SPEED;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Orbit mode.
|
||||
if ( m_orbitDX != 0.0f || m_orbitDY != 0.0f )
|
||||
{
|
||||
m_yaw -= m_orbitDX * ORBIT_SENS;
|
||||
m_pitch -= m_orbitDY * ORBIT_SENS;
|
||||
if ( m_pitch > PITCH_LIM )
|
||||
m_pitch = PITCH_LIM;
|
||||
if ( m_pitch < -PITCH_LIM )
|
||||
m_pitch = -PITCH_LIM;
|
||||
}
|
||||
|
||||
if ( m_panDX != 0.0f || m_panDY != 0.0f )
|
||||
{
|
||||
// Move pivot along view-space right/up. m_right / m_up are still
|
||||
// last frame's values (orbit yaw/pitch haven't been rebuilt yet),
|
||||
// which matches the screen the user dragged against.
|
||||
const float panScale = PAN_SENS * m_radius;
|
||||
m_pivot.x -= m_right.x * m_panDX * panScale;
|
||||
m_pivot.y -= m_right.y * m_panDX * panScale;
|
||||
m_pivot.z -= m_right.z * m_panDX * panScale;
|
||||
m_pivot.x += m_up.x * m_panDY * panScale;
|
||||
m_pivot.y += m_up.y * m_panDY * panScale;
|
||||
m_pivot.z += m_up.z * m_panDY * panScale;
|
||||
}
|
||||
|
||||
if ( m_radialZoomDY != 0.0f )
|
||||
{
|
||||
// Drag down -> zoom in (radius shrinks). Matches Box3D.
|
||||
m_radius -= RADIAL_ZOOM_SENS * m_radialZoomDY;
|
||||
if ( m_radius < MIN_DIST )
|
||||
m_radius = MIN_DIST;
|
||||
if ( m_radius > MAX_DIST )
|
||||
m_radius = MAX_DIST;
|
||||
}
|
||||
|
||||
if ( m_scrollAccum != 0.0f )
|
||||
{
|
||||
m_radius *= powf( ZOOM_STEP, m_scrollAccum );
|
||||
if ( m_radius < MIN_DIST )
|
||||
m_radius = MIN_DIST;
|
||||
if ( m_radius > MAX_DIST )
|
||||
m_radius = MAX_DIST;
|
||||
}
|
||||
}
|
||||
|
||||
// Keep yaw bounded across long sessions. b3UnwindAngle wraps to (-pi, pi].
|
||||
m_yaw = b3UnwindAngle( m_yaw );
|
||||
|
||||
m_orbitDX = 0.0f;
|
||||
m_orbitDY = 0.0f;
|
||||
m_panDX = 0.0f;
|
||||
m_panDY = 0.0f;
|
||||
m_radialZoomDY = 0.0f;
|
||||
m_scrollAccum = 0.0f;
|
||||
m_speedScrollAccum = 0.0f;
|
||||
|
||||
RebuildBasisAndView( *this );
|
||||
RebuildProj( aspect );
|
||||
}
|
||||
198
samples/host/camera.h
Normal file
198
samples/host/camera.h
Normal file
|
|
@ -0,0 +1,198 @@
|
|||
// Orbit + fly camera, modeled after Box3D's sample camera.
|
||||
//
|
||||
// Two modes share one state. Sticky mouse-button + Alt-modifier flags
|
||||
// select which mode each gesture drives:
|
||||
//
|
||||
// ORBIT (Alt held)
|
||||
// Alt + left-drag : orbit (yaw/pitch around pivot)
|
||||
// Alt + middle-drag : pan pivot in view-space XY
|
||||
// Alt + right-drag-Y : radial zoom (adjust radius)
|
||||
//
|
||||
// FLY (right mouse held, no Alt)
|
||||
// right-drag : FPS look (yaw/pitch the view direction)
|
||||
// WASD : translate eye along view forward/right at m_speed
|
||||
// scroll : tune m_speed
|
||||
//
|
||||
// Always
|
||||
// bare scroll : multiplicative zoom on radius
|
||||
//
|
||||
// OnEvent accumulates input deltas; Update consumes them and folds them
|
||||
// into the camera state. View / Proj produce the matrices the renderer
|
||||
// consumes.
|
||||
//
|
||||
// m_pivot is the look-at pivot, m_radius the radial offset, m_yaw / m_pitch
|
||||
// the spherical angles in radians. In fly mode the eye is the primary anchor
|
||||
// and m_pivot is back-derived so re-entering orbit mode preserves the look
|
||||
// direction. Box3D's sample camera keeps yaw/pitch in degrees, so SetView
|
||||
// converts at the boundary.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "gfx/utility.h"
|
||||
|
||||
struct sapp_event;
|
||||
|
||||
// World-space ray from a screen pixel: origin sits on the near plane,
|
||||
// translation spans near -> far. Feeds straight into b3World_CastRay*.
|
||||
struct PickRay
|
||||
{
|
||||
b3Vec3 origin;
|
||||
b3Vec3 translation;
|
||||
};
|
||||
|
||||
class Camera
|
||||
{
|
||||
public:
|
||||
Camera();
|
||||
|
||||
// Feed each sokol_app event here. Safe to call from event_cb at any
|
||||
// time during the frame; deltas are summed and consumed by Update().
|
||||
void OnEvent( const sapp_event* e );
|
||||
|
||||
// Width/height are the latched framebuffer pixels; aspect derives from
|
||||
// them and they back BuildPickRay and ImGui bottom-anchored panels.
|
||||
void Update( float dt, int width, int height );
|
||||
|
||||
Mat4 View() const
|
||||
{
|
||||
return m_view;
|
||||
}
|
||||
Mat4 ViewInverse() const
|
||||
{
|
||||
return m_viewInv;
|
||||
}
|
||||
Mat4 Proj() const
|
||||
{
|
||||
return m_proj;
|
||||
}
|
||||
Mat4 ProjInverse() const
|
||||
{
|
||||
return m_projInv;
|
||||
}
|
||||
|
||||
b3Vec3 Position() const;
|
||||
|
||||
// Cached basis accessors (Box3D parity). Forward is +view-Z (pivot -> eye),
|
||||
// so the look direction is -GetForward().
|
||||
b3Vec3 GetPosition() const
|
||||
{
|
||||
return m_position;
|
||||
}
|
||||
b3Vec3 GetForward() const
|
||||
{
|
||||
return m_forward;
|
||||
}
|
||||
b3Vec3 GetRight() const
|
||||
{
|
||||
return m_right;
|
||||
}
|
||||
b3Vec3 GetUp() const
|
||||
{
|
||||
return m_up;
|
||||
}
|
||||
|
||||
// Snap to a fixed orientation; used by scene init paths that frame
|
||||
// the camera independently of mouse state.
|
||||
void SetOrbit( float yawRadians, float pitchRadians, float radius );
|
||||
|
||||
// Box3D's sample signature: angles in degrees, pivot folded in. Mirrors
|
||||
// the ~140 sample call sites exactly so they need no edits.
|
||||
void SetView( float yawDegrees, float pitchDegrees, float radius, b3Vec3 pivot = b3Vec3_zero );
|
||||
|
||||
void SetPivot( b3Vec3 pivot )
|
||||
{
|
||||
m_pivot = pivot;
|
||||
}
|
||||
// Forwarder for existing render3d call sites.
|
||||
void SetTarget( b3Vec3 target )
|
||||
{
|
||||
m_pivot = target;
|
||||
}
|
||||
|
||||
// Frame an AABB: keep current yaw/pitch, move pivot to the AABB center,
|
||||
// and refit radius so the AABB fits in view at the current FOV+aspect.
|
||||
// `padding` (>= 1) scales the fit radius (1.2 leaves a small margin).
|
||||
// A degenerate / invalid AABB is a no-op.
|
||||
void Frame( b3AABB aabb, float aspect, float padding );
|
||||
void SetFov( float fovRadians )
|
||||
{
|
||||
m_fov = fovRadians;
|
||||
}
|
||||
void SetClip( float near, float far )
|
||||
{
|
||||
m_near = near;
|
||||
m_far = far;
|
||||
}
|
||||
|
||||
// Recomputes the projection. Call after any SetFov / SetClip change, or
|
||||
// when the target framebuffer aspect changes outside Update().
|
||||
void RebuildProj( float aspect );
|
||||
|
||||
// Recompute the basis + view from yaw/pitch/pivot/radius. Public entry
|
||||
// point for sample code that mutates m_pivot directly (third-person follow).
|
||||
void UpdateTransform();
|
||||
|
||||
// World-space pick ray from a framebuffer-pixel coordinate, using the
|
||||
// latched camera state. Wraps the free function in gfx/picking.h; hands
|
||||
// back a zero-translation ray (origin at the eye) if that state is not
|
||||
// ready yet, so callers never read uninitialized values.
|
||||
PickRay BuildPickRay( float x, float y ) const;
|
||||
|
||||
b3Vec3 m_pivot;
|
||||
float m_yaw; // radians, around Y
|
||||
float m_pitch; // radians, around camera-frame X
|
||||
float m_radius; // meters from pivot
|
||||
|
||||
float m_fov; // radians, vertical
|
||||
float m_near;
|
||||
float m_far;
|
||||
|
||||
// Fly-mode translation speed, m/s. Scroll-tunable while right-mouse held.
|
||||
float m_speed;
|
||||
|
||||
// Latched framebuffer pixels, refreshed each Update. Sample UI anchors
|
||||
// panels relative to m_height.
|
||||
int m_width;
|
||||
int m_height;
|
||||
|
||||
// Locks input to wheel-zoom; the sample drives m_pivot to a followed body
|
||||
// and calls UpdateTransform. Eye placement stays the orbit formula.
|
||||
bool m_thirdPerson;
|
||||
|
||||
// Cached basis (Box3D-style: forward is +view-Z, i.e. pivot->eye), refreshed
|
||||
// alongside m_view / m_viewInv whenever yaw/pitch/pivot/radius change.
|
||||
// These let consumers (picking, shadow frustum) skip re-inverting m_view.
|
||||
b3Vec3 m_position;
|
||||
b3Vec3 m_right;
|
||||
b3Vec3 m_up;
|
||||
b3Vec3 m_forward;
|
||||
|
||||
// All four matrices are produced together — view / viewInv from the basis,
|
||||
// proj / projInv from fov/aspect/near/far — so the renderer never inverts
|
||||
// at runtime.
|
||||
Mat4 m_view;
|
||||
Mat4 m_viewInv;
|
||||
Mat4 m_proj;
|
||||
Mat4 m_projInv;
|
||||
|
||||
// Per-frame input deltas accumulated by OnEvent and zeroed by Update.
|
||||
// Routing into the right bucket happens in OnEvent based on which mouse
|
||||
// buttons + Alt are held when the event arrives.
|
||||
float m_orbitDX = 0.0f; // alt+left-drag, or right-drag (fly look)
|
||||
float m_orbitDY = 0.0f;
|
||||
float m_panDX = 0.0f; // alt+middle-drag
|
||||
float m_panDY = 0.0f;
|
||||
float m_radialZoomDY = 0.0f; // alt+right-drag, Y component
|
||||
float m_scrollAccum = 0.0f; // bare scroll: orbit zoom
|
||||
float m_speedScrollAccum = 0.0f; // scroll while right held (no alt): tune speed
|
||||
|
||||
// Sticky button/key state, toggled by MOUSE_DOWN/UP and KEY_DOWN/UP.
|
||||
bool m_leftDown = false;
|
||||
bool m_rightDown = false;
|
||||
bool m_middleDown = false;
|
||||
bool m_altDown = false;
|
||||
bool m_wDown = false;
|
||||
bool m_aDown = false;
|
||||
bool m_sDown = false;
|
||||
bool m_dDown = false;
|
||||
};
|
||||
402
samples/host/gui.cpp
Normal file
402
samples/host/gui.cpp
Normal file
|
|
@ -0,0 +1,402 @@
|
|||
// Dear ImGui shell - implementation.
|
||||
//
|
||||
// Owns the simgui setup and the ImGui pass, runs the app's UI draw callback
|
||||
// (the menu bar, panels, and diagnostics drawn by DrawUI), and
|
||||
// drains the in-world text overlay. Panels are anchored with BeginPanel /
|
||||
// EndPanel; the menu bar and drawer the app draws itself.
|
||||
//
|
||||
// Render path: ImGui draws on a NEW swapchain pass opened in RenderUI,
|
||||
// LOADed on top of the already-tonemapped swapchain image. The simgui
|
||||
// pipeline therefore inherits the swapchain's color + depth format and
|
||||
// sample_count=1.
|
||||
|
||||
#include "gui.h"
|
||||
|
||||
#include "gfx/draw.h"
|
||||
#include "gfx/projection.h"
|
||||
#include "gfx/renderer.h"
|
||||
#include "gfx/text.h"
|
||||
#include "imgui.h"
|
||||
#include "implot.h"
|
||||
#include "sokol_app.h"
|
||||
#include "sokol_imgui.h"
|
||||
#include "sokol_log.h"
|
||||
|
||||
#include <math.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdio.h>
|
||||
|
||||
static bool s_uiInitialized = false;
|
||||
|
||||
// Display scale (sapp_dpi_scale) latched once in InitUI. ImGui runs in
|
||||
// physical framebuffer pixels, so panel code multiplies explicit pixel sizes
|
||||
// by this; the font atlas and the rest of the style are pre-scaled by it too.
|
||||
static float s_uiScale = 1.0f;
|
||||
|
||||
static DrawUiFcn* s_uiCallback;
|
||||
|
||||
// Restyle Dear ImGui away from the stock dark theme: a desaturated steel-blue
|
||||
// accent over neutral charcoal, one consistent rounding system, and roomier
|
||||
// padding. Sets base (unscaled) metrics - InitUI runs ScaleAllSizes after
|
||||
// this on hi-DPI displays; colors are scale-independent so they need no pass.
|
||||
static void guiApplyStyle( void )
|
||||
{
|
||||
ImGuiStyle& style = ImGui::GetStyle();
|
||||
|
||||
// Metrics: containers round at 4px, controls at 3px - one deliberate
|
||||
// system instead of the stock mix. Padding gives rows room to breathe.
|
||||
style.WindowPadding = ImVec2( 10.0f, 10.0f );
|
||||
style.FramePadding = ImVec2( 8.0f, 4.0f );
|
||||
style.CellPadding = ImVec2( 6.0f, 4.0f );
|
||||
style.ItemSpacing = ImVec2( 8.0f, 7.0f );
|
||||
style.ItemInnerSpacing = ImVec2( 7.0f, 4.0f );
|
||||
style.IndentSpacing = 18.0f;
|
||||
style.ScrollbarSize = 12.0f;
|
||||
style.GrabMinSize = 10.0f;
|
||||
|
||||
style.WindowBorderSize = 1.0f;
|
||||
style.FrameBorderSize = 0.0f;
|
||||
style.PopupBorderSize = 1.0f;
|
||||
style.TabBorderSize = 0.0f;
|
||||
style.SeparatorTextBorderSize = 1.0f;
|
||||
|
||||
style.WindowRounding = 4.0f;
|
||||
style.ChildRounding = 4.0f;
|
||||
style.PopupRounding = 4.0f;
|
||||
style.FrameRounding = 3.0f;
|
||||
style.GrabRounding = 3.0f;
|
||||
style.ScrollbarRounding = 3.0f;
|
||||
style.TabRounding = 3.0f;
|
||||
|
||||
style.WindowTitleAlign = ImVec2( 0.0f, 0.5f );
|
||||
|
||||
// Palette: neutral charcoal surfaces, one steel-blue accent at three
|
||||
// brightnesses. Replaces stock ImGui's saturated cornflower blue.
|
||||
const ImVec4 accent = ImVec4( 0.28f, 0.48f, 0.66f, 1.00f );
|
||||
const ImVec4 accentHi = ImVec4( 0.38f, 0.60f, 0.80f, 1.00f );
|
||||
const ImVec4 accentLo = ImVec4( 0.22f, 0.36f, 0.50f, 1.00f );
|
||||
|
||||
ImVec4* c = style.Colors;
|
||||
c[ImGuiCol_Text] = ImVec4( 0.90f, 0.91f, 0.93f, 1.00f );
|
||||
c[ImGuiCol_TextDisabled] = ImVec4( 0.49f, 0.51f, 0.55f, 1.00f );
|
||||
c[ImGuiCol_WindowBg] = ImVec4( 0.110f, 0.115f, 0.125f, 0.97f );
|
||||
c[ImGuiCol_ChildBg] = ImVec4( 0.00f, 0.00f, 0.00f, 0.00f );
|
||||
c[ImGuiCol_PopupBg] = ImVec4( 0.100f, 0.105f, 0.115f, 0.98f );
|
||||
c[ImGuiCol_Border] = ImVec4( 0.00f, 0.00f, 0.00f, 0.45f );
|
||||
c[ImGuiCol_BorderShadow] = ImVec4( 0.00f, 0.00f, 0.00f, 0.00f );
|
||||
c[ImGuiCol_FrameBg] = ImVec4( 0.18f, 0.19f, 0.21f, 1.00f );
|
||||
c[ImGuiCol_FrameBgHovered] = ImVec4( 0.24f, 0.26f, 0.29f, 1.00f );
|
||||
c[ImGuiCol_FrameBgActive] = ImVec4( 0.29f, 0.32f, 0.36f, 1.00f );
|
||||
c[ImGuiCol_TitleBg] = ImVec4( 0.090f, 0.095f, 0.105f, 1.00f );
|
||||
c[ImGuiCol_TitleBgActive] = ImVec4( 0.14f, 0.16f, 0.19f, 1.00f );
|
||||
c[ImGuiCol_TitleBgCollapsed] = ImVec4( 0.090f, 0.095f, 0.105f, 0.75f );
|
||||
c[ImGuiCol_MenuBarBg] = ImVec4( 0.13f, 0.14f, 0.16f, 1.00f );
|
||||
c[ImGuiCol_ScrollbarBg] = ImVec4( 0.06f, 0.06f, 0.07f, 0.55f );
|
||||
c[ImGuiCol_ScrollbarGrab] = ImVec4( 0.28f, 0.30f, 0.33f, 1.00f );
|
||||
c[ImGuiCol_ScrollbarGrabHovered] = ImVec4( 0.36f, 0.39f, 0.43f, 1.00f );
|
||||
c[ImGuiCol_ScrollbarGrabActive] = accent;
|
||||
c[ImGuiCol_CheckMark] = accentHi;
|
||||
c[ImGuiCol_SliderGrab] = accent;
|
||||
c[ImGuiCol_SliderGrabActive] = accentHi;
|
||||
c[ImGuiCol_Button] = ImVec4( 0.22f, 0.24f, 0.27f, 1.00f );
|
||||
c[ImGuiCol_ButtonHovered] = accentLo;
|
||||
c[ImGuiCol_ButtonActive] = accent;
|
||||
c[ImGuiCol_Header] = ImVec4( 0.19f, 0.21f, 0.24f, 1.00f );
|
||||
c[ImGuiCol_HeaderHovered] = accentLo;
|
||||
c[ImGuiCol_HeaderActive] = accent;
|
||||
c[ImGuiCol_Separator] = ImVec4( 1.00f, 1.00f, 1.00f, 0.09f );
|
||||
c[ImGuiCol_SeparatorHovered] = accentLo;
|
||||
c[ImGuiCol_SeparatorActive] = accent;
|
||||
c[ImGuiCol_ResizeGrip] = ImVec4( 1.00f, 1.00f, 1.00f, 0.06f );
|
||||
c[ImGuiCol_ResizeGripHovered] = accentLo;
|
||||
c[ImGuiCol_ResizeGripActive] = accent;
|
||||
c[ImGuiCol_Tab] = ImVec4( 0.15f, 0.16f, 0.18f, 1.00f );
|
||||
c[ImGuiCol_TabHovered] = accentLo;
|
||||
c[ImGuiCol_TabSelected] = accent;
|
||||
c[ImGuiCol_TabSelectedOverline] = accentHi;
|
||||
c[ImGuiCol_TabDimmed] = ImVec4( 0.12f, 0.13f, 0.14f, 1.00f );
|
||||
c[ImGuiCol_TabDimmedSelected] = accentLo;
|
||||
c[ImGuiCol_TextSelectedBg] = ImVec4( accent.x, accent.y, accent.z, 0.40f );
|
||||
c[ImGuiCol_DragDropTarget] = accentHi;
|
||||
c[ImGuiCol_NavCursor] = accentHi;
|
||||
c[ImGuiCol_PlotLines] = ImVec4( 0.70f, 0.72f, 0.75f, 1.00f );
|
||||
c[ImGuiCol_PlotLinesHovered] = accentHi;
|
||||
c[ImGuiCol_PlotHistogram] = accent;
|
||||
c[ImGuiCol_PlotHistogramHovered] = accentHi;
|
||||
}
|
||||
|
||||
void InitUI( const sg_environment* env, DrawUiFcn* drawGuiFcn )
|
||||
{
|
||||
s_uiCallback = drawGuiFcn;
|
||||
|
||||
simgui_desc_t desc = {};
|
||||
desc.color_format = env->defaults.color_format;
|
||||
desc.depth_format = env->defaults.depth_format;
|
||||
desc.sample_count = env->defaults.sample_count;
|
||||
desc.ini_filename = "imgui.ini";
|
||||
desc.logger.func = slog_func;
|
||||
// Skip ImGui's auto-pick so we always get the vector font we add below.
|
||||
desc.no_default_font = true;
|
||||
simgui_setup( &desc );
|
||||
|
||||
// simgui_setup creates the ImGui context, so ImPlot has to come after it.
|
||||
ImPlot::CreateContext();
|
||||
|
||||
// DPI handling mirrors the Box2D sample app, which gets crisp text at
|
||||
// fractional Windows display scales. ImGui runs in physical framebuffer
|
||||
// pixels: StartUIFrame feeds simgui dpi_scale=1.0, so DisplaySize is the
|
||||
// framebuffer size and DisplayFramebufferScale is 1.0. The display scale
|
||||
// is then applied by hand - the font atlas is baked once at an integer
|
||||
// pixel size and ScaleAllSizes scales the rest of the style. Drawing
|
||||
// ImGui 1:1 against the framebuffer with an integer-sized atlas is what
|
||||
// keeps glyphs sharp; letting sokol_imgui scale a logical-pixel UI up by
|
||||
// a fractional factor instead leaves every glyph on a sub-pixel boundary.
|
||||
s_uiScale = sapp_dpi_scale();
|
||||
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
io.Fonts->Clear();
|
||||
|
||||
// Restyle before the hi-DPI branch: guiApplyStyle sets base metrics, then
|
||||
// ScaleAllSizes (below) multiplies them up. Colors are unscaled.
|
||||
guiApplyStyle();
|
||||
|
||||
io.Fonts->AddFontDefaultVector();
|
||||
|
||||
ImGuiStyle& style = ImGui::GetStyle();
|
||||
if ( s_uiScale != 1.0f )
|
||||
{
|
||||
style.ScaleAllSizes( s_uiScale );
|
||||
}
|
||||
|
||||
// 13px base for the proportional UI font, scaled to a whole physical
|
||||
// pixel. Rasterizer density is 1.0 (DisplayFramebufferScale 1.0), so the
|
||||
// atlas bakes at exactly this - floorf keeps it on a whole-pixel size.
|
||||
style.FontSizeBase = floorf( 13.0f * s_uiScale );
|
||||
|
||||
s_uiInitialized = true;
|
||||
}
|
||||
|
||||
void ShutdownUI( void )
|
||||
{
|
||||
if ( !s_uiInitialized )
|
||||
return;
|
||||
|
||||
ImPlot::DestroyContext();
|
||||
simgui_shutdown();
|
||||
s_uiInitialized = false;
|
||||
}
|
||||
|
||||
bool HandleEvent( const sapp_event* e )
|
||||
{
|
||||
if ( !s_uiInitialized )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
bool handled = simgui_handle_event( e );
|
||||
const ImGuiIO& io = ImGui::GetIO();
|
||||
|
||||
if ( handled )
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if ( e->type == SAPP_EVENTTYPE_KEY_DOWN || e->type == SAPP_EVENTTYPE_KEY_UP || e->type == SAPP_EVENTTYPE_CHAR )
|
||||
{
|
||||
return io.WantCaptureKeyboard;
|
||||
}
|
||||
|
||||
if ( e->type == SAPP_EVENTTYPE_MOUSE_DOWN || e->type == SAPP_EVENTTYPE_MOUSE_UP || e->type == SAPP_EVENTTYPE_MOUSE_MOVE ||
|
||||
e->type == SAPP_EVENTTYPE_MOUSE_SCROLL )
|
||||
{
|
||||
return io.WantCaptureMouse;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// Gap between a panel and the window edge
|
||||
static const float PANEL_GAP = 5.0f;
|
||||
|
||||
// Running top Y for the next panel on each side, indexed by GuiPanelAnchor.
|
||||
static float s_panelCursorY[2];
|
||||
// Side of the panel currently open between guiBeginPanel and guiEndPanel.
|
||||
static GuiPanelAnchor s_panelOpenSide;
|
||||
static bool s_panelOpen = false;
|
||||
|
||||
static void ResetUIPanelLayout( void )
|
||||
{
|
||||
const ImGuiViewport* vp = ImGui::GetMainViewport();
|
||||
// Clear the main menu bar. Without docking the bar does not shrink the
|
||||
// viewport work area, so panels would otherwise start under it.
|
||||
const float top = vp->WorkPos.y + ImGui::GetFrameHeight() + PANEL_GAP * s_uiScale;
|
||||
s_panelCursorY[GUI_ANCHOR_LEFT] = top;
|
||||
s_panelCursorY[GUI_ANCHOR_RIGHT] = top;
|
||||
s_panelOpen = false;
|
||||
}
|
||||
|
||||
bool BeginPanel( const char* name, GuiPanelAnchor anchor, float width )
|
||||
{
|
||||
ImGuiViewport* vp = ImGui::GetMainViewport();
|
||||
float gap = PANEL_GAP * s_uiScale;
|
||||
float w = width * s_uiScale;
|
||||
float cursorY = s_panelCursorY[anchor];
|
||||
|
||||
// Left panels pin their top-left corner to the left edge; right panels
|
||||
// pin their top-right corner to the right edge (pivot picks the corner).
|
||||
float anchorX;
|
||||
ImVec2 pivot;
|
||||
if ( anchor == GUI_ANCHOR_RIGHT )
|
||||
{
|
||||
anchorX = vp->WorkPos.x + vp->WorkSize.x - gap;
|
||||
pivot = ImVec2( 1.0f, 0.0f );
|
||||
}
|
||||
else
|
||||
{
|
||||
anchorX = vp->WorkPos.x + gap;
|
||||
pivot = ImVec2( 0.0f, 0.0f );
|
||||
}
|
||||
ImGui::SetNextWindowPos( ImVec2( anchorX, cursorY ), ImGuiCond_Always, pivot );
|
||||
|
||||
// SetNextWindowSize y=0 auto-fits height to content; the constraint caps
|
||||
// it so a tall panel can't run past the window's bottom edge (the panel
|
||||
// gains a scrollbar past the cap). Width is locked to w by both calls.
|
||||
float maxH = vp->WorkPos.y + vp->WorkSize.y - gap - cursorY;
|
||||
if ( maxH < ImGui::GetFrameHeight() )
|
||||
maxH = ImGui::GetFrameHeight();
|
||||
ImGui::SetNextWindowSizeConstraints( ImVec2( w, 0.0f ), ImVec2( w, maxH ) );
|
||||
ImGui::SetNextWindowSize( ImVec2( w, 0.0f ), ImGuiCond_Always );
|
||||
|
||||
s_panelOpenSide = anchor;
|
||||
s_panelOpen = true;
|
||||
return ImGui::Begin( name, nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize );
|
||||
}
|
||||
|
||||
void EndPanel( void )
|
||||
{
|
||||
// Advance this side's cursor past the panel just drawn so the next panel
|
||||
// stacks directly below it. GetWindowSize is valid here whether or not
|
||||
// Begin returned true - a collapsed panel reports its title-bar height,
|
||||
// so the next panel snugs up under the collapsed bar.
|
||||
if ( s_panelOpen )
|
||||
{
|
||||
s_panelCursorY[s_panelOpenSide] += ImGui::GetWindowSize().y + PANEL_GAP * s_uiScale;
|
||||
s_panelOpen = false;
|
||||
}
|
||||
ImGui::End();
|
||||
}
|
||||
|
||||
// Text overlay. Drain the per-frame label arena (filled by DrawString /
|
||||
// DrawScreenString and the Box3D adapter's DrawString callback). World
|
||||
// entries project to screen pixels with the last rendered camera, screen
|
||||
// entries pass through their pixel position, and both emit into ImGui's
|
||||
// background draw list - labels sit on the scene but under any ImGui
|
||||
// windows. The drain runs in StartUIFrame because the calling app
|
||||
// guarantees RenderFrame already ran this frame, so GetCameraState
|
||||
// returns the matrices the scene was actually rasterized with.
|
||||
static void RenderText()
|
||||
{
|
||||
const int n = GetTextCount();
|
||||
if ( n <= 0 )
|
||||
return;
|
||||
|
||||
const CameraState cam = GetCameraState();
|
||||
if ( cam.viewportW <= 0 || cam.viewportH <= 0 )
|
||||
return;
|
||||
|
||||
// ImGui runs in physical framebuffer pixels (see InitUI), so the main
|
||||
// viewport's Size matches cam.viewportW/H. Project against the viewport
|
||||
// Size and offset by vp->Pos so this stays correct even if ImGui's space
|
||||
// ever gains an origin offset. Aspect is encoded in cam.proj, so any
|
||||
// width/height with the scene's ratio yields identical NDC.
|
||||
ImGuiViewport* vp = ImGui::GetMainViewport();
|
||||
const int vpW = (int)vp->Size.x;
|
||||
const int vpH = (int)vp->Size.y;
|
||||
if ( vpW <= 0 || vpH <= 0 )
|
||||
return;
|
||||
ImDrawList* dl = ImGui::GetBackgroundDrawList();
|
||||
const ImVec2 origin = vp->Pos;
|
||||
|
||||
for ( int i = 0; i < n; ++i )
|
||||
{
|
||||
const TextEntry* e = GetTextAt( i );
|
||||
float sx, sy;
|
||||
if ( !ResolveTextScreenPos( e, cam.view, cam.proj, vpW, vpH, &sx, &sy ) )
|
||||
{
|
||||
continue;
|
||||
}
|
||||
// Linear-to-byte: pass straight through (no sRGB encode) - matches
|
||||
// how Box3D's b3HexColor literals reach the Draw* path, so a label
|
||||
// color reads the same as the SVG hex it came from.
|
||||
const auto byte = []( float v ) -> uint32_t {
|
||||
if ( v < 0.0f )
|
||||
v = 0.0f;
|
||||
if ( v > 1.0f )
|
||||
v = 1.0f;
|
||||
return (uint32_t)( v * 255.0f + 0.5f );
|
||||
};
|
||||
const uint32_t col = IM_COL32( byte( e->color.x ), byte( e->color.y ), byte( e->color.z ), byte( e->color.w ) );
|
||||
dl->AddText( nullptr, 0.0f, ImVec2( origin.x + sx, origin.y + sy ), col, e->text );
|
||||
}
|
||||
}
|
||||
|
||||
void StartUIFrame( float dtSec )
|
||||
{
|
||||
if ( !s_uiInitialized )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
simgui_frame_desc_t fd = {};
|
||||
fd.width = sapp_width();
|
||||
fd.height = sapp_height();
|
||||
|
||||
// Clamp the delta we hand to ImGui to at least ~1ms. With swap_interval=0
|
||||
// sokol_app can call OnFrame back-to-back fast enough that stm_laptime
|
||||
// returns sub-microsecond deltas, and once cast to float ImGui's g.Time
|
||||
// fails to advance. That breaks the per-frame reset of the BG/FG draw
|
||||
// lists (their reset gate is `(float)BgFgDrawListsLastTimeActive !=
|
||||
// (float)g.Time`), so subsequent AddText calls into the background draw
|
||||
// list pile on top of the prior frame's vertices instead of replacing
|
||||
// them - visible as in-world labels flickering bright/dim as overlapping
|
||||
// copies alpha-blend over each other.
|
||||
const float kMinDt = 1.0f / 1000.0f;
|
||||
fd.delta_time = ( dtSec >= kMinDt ) ? (double)dtSec : (double)kMinDt;
|
||||
|
||||
// dpi_scale 1.0 on purpose: it keeps ImGui in physical framebuffer pixels
|
||||
// (DisplaySize = framebuffer, DisplayFramebufferScale = 1.0). The display
|
||||
// scale is baked into the font and style in InitUI instead. See there.
|
||||
fd.dpi_scale = 1.0f;
|
||||
simgui_new_frame( &fd );
|
||||
|
||||
// Reset the edge-anchor cursors before any panel opens - they accumulate
|
||||
// per panel within this frame and must start fresh each frame.
|
||||
ResetUIPanelLayout();
|
||||
|
||||
// The callback runs every frame; it branches on the sample context's showUI
|
||||
// (full UI vs the minimal HUD) the way Box2D's DrawUI does.
|
||||
if ( s_uiCallback != nullptr )
|
||||
{
|
||||
s_uiCallback();
|
||||
}
|
||||
|
||||
RenderText();
|
||||
}
|
||||
|
||||
void RenderUI( const sg_swapchain* swapchain )
|
||||
{
|
||||
if ( !s_uiInitialized )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
sg_pass pass = {};
|
||||
pass.action.colors[0].load_action = SG_LOADACTION_LOAD; // sit on top of tonemap
|
||||
pass.action.depth.load_action = SG_LOADACTION_DONTCARE;
|
||||
pass.action.stencil.load_action = SG_LOADACTION_DONTCARE;
|
||||
pass.swapchain = *swapchain;
|
||||
pass.label = "imgui";
|
||||
sg_begin_pass( &pass );
|
||||
simgui_render();
|
||||
sg_end_pass();
|
||||
}
|
||||
56
samples/host/gui.h
Normal file
56
samples/host/gui.h
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
// Dear ImGui shell.
|
||||
//
|
||||
// Wraps sokol_imgui.h, runs the app's UI draw callback (the DrawUiFcn passed
|
||||
// to InitUI) on top of the live scene, and drains the in-world text overlay.
|
||||
// Used only by the renderer binary; the visual-test targets call
|
||||
// RenderFrameOffscreen directly and never instantiate ImGui.
|
||||
//
|
||||
// Lifecycle from main.cpp's sapp callbacks:
|
||||
//
|
||||
// OnInit: InitRenderer(&env); InitUI(&env, DrawUI);
|
||||
// OnEvent: if (HandleEvent(e)) return; // skip camera if ImGui ate it
|
||||
// OnFrame: ResetFrameArena();
|
||||
// scene draws...
|
||||
// RenderFrame(&sc, &frame);
|
||||
// StartUIFrame(dt); // runs the UI draw callback, drains in-world text
|
||||
// RenderUI(&sc); // separate pass on the swapchain
|
||||
// OnCleanup: ShutdownUI(); ShutdownRenderer();
|
||||
//
|
||||
// RenderUI opens its own swapchain pass with LOAD action so ImGui sits on
|
||||
// top of the tonemapped scene without disturbing it. Single-threaded;
|
||||
// render-thread only.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "sokol_app.h"
|
||||
#include "sokol_gfx.h"
|
||||
|
||||
// Screen edge a panel anchors to. Panels sharing a side stack top-down in
|
||||
// the order they call guiBeginPanel within a frame.
|
||||
typedef enum GuiPanelAnchor
|
||||
{
|
||||
GUI_ANCHOR_LEFT = 0,
|
||||
GUI_ANCHOR_RIGHT = 1,
|
||||
} GuiPanelAnchor;
|
||||
|
||||
typedef void DrawUiFcn( void );
|
||||
|
||||
void InitUI( const sg_environment* env, DrawUiFcn* drawGuiFcn );
|
||||
void ShutdownUI( void );
|
||||
|
||||
bool HandleEvent( const sapp_event* e );
|
||||
|
||||
void StartUIFrame( float dtSec );
|
||||
void RenderUI( const sg_swapchain* swapchain );
|
||||
|
||||
// Begin an edge-anchored panel. A thin wrapper over ImGui::Begin. Pins the
|
||||
// window flush against anchor's screen edge, stacked below any panel
|
||||
// already opened on that side this frame, and re-anchors it there every
|
||||
// frame so it tracks the edge when the window resizes (unlike a one-shot
|
||||
// ImGuiCond_FirstUseEver position, which drifts off a shrinking window).
|
||||
// width is in unscaled pixels. The UI DPI scale is applied internally.
|
||||
// Height auto-fits the content, capped to the remaining viewport height
|
||||
// (the panel gains a scrollbar past the cap). Returns ImGui::Begin's value;
|
||||
// pair every call with EndPanel, including when it returns false.
|
||||
bool BeginPanel( const char* name, GuiPanelAnchor anchor, float width );
|
||||
void EndPanel( void );
|
||||
17
samples/host/imgui_impl.cpp
Normal file
17
samples/host/imgui_impl.cpp
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
// Single translation unit for sokol_imgui.h's implementation.
|
||||
//
|
||||
// Built as C++ so it can call into the C++ Dear ImGui API directly (the C
|
||||
// path needs cimgui, which we don't pull in). Compiled as part of the
|
||||
// renderer binary; not linked into tests, which never instantiate the GUI.
|
||||
//
|
||||
// The sokol_app/glue/time *_IMPL macros live in src/app/sokol_app_impl.c and
|
||||
// sokol_gfx's SOKOL_IMPL lives in src/gfx/sokol_impl.c - we only enable
|
||||
// SOKOL_IMGUI_IMPL here.
|
||||
|
||||
#include "imgui.h"
|
||||
|
||||
#include "sokol_gfx.h"
|
||||
#include "sokol_app.h"
|
||||
|
||||
#define SOKOL_IMGUI_IMPL
|
||||
#include "sokol_imgui.h"
|
||||
29
samples/host/sokol_app_impl.c
Normal file
29
samples/host/sokol_app_impl.c
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
// Single-TU build of sokol_app + sokol_glue + sokol_time.
|
||||
//
|
||||
// sokol_gfx's implementation lives in src/gfx/sokol_impl.c. We only include
|
||||
// its header here (without SOKOL_IMPL) so that sokol_glue can see the
|
||||
// sg_environment / sg_swapchain declarations it translates into.
|
||||
//
|
||||
// Backend macro (SOKOL_D3D11 / SOKOL_METAL / SOKOL_GLCORE) comes from the
|
||||
// `sokol` INTERFACE target. On Apple this file is compiled as Objective-C
|
||||
// with ARC (see src/app/CMakeLists.txt) so sokol_app's Cocoa backend builds.
|
||||
//
|
||||
// SOKOL_WIN32_FORCE_MAIN: sokol_app defaults to WinMain (subsystem:windows)
|
||||
// on Windows. Our binaries are console-subsystem so the smoke test can
|
||||
// surface stderr to ctest, so force the int main variant.
|
||||
//
|
||||
// _POSIX_C_SOURCE: glibc gates clock_gettime / CLOCK_MONOTONIC behind a
|
||||
// POSIX feature-test macro under -std=c17. Define before any system headers.
|
||||
#if defined(__linux__) && !defined(_POSIX_C_SOURCE)
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#endif
|
||||
|
||||
#define SOKOL_APP_IMPL
|
||||
#define SOKOL_GLUE_IMPL
|
||||
#define SOKOL_LOG_IMPL
|
||||
#define SOKOL_WIN32_FORCE_MAIN
|
||||
|
||||
#include "sokol_gfx.h"
|
||||
#include "sokol_app.h"
|
||||
#include "sokol_glue.h"
|
||||
#include "sokol_log.h"
|
||||
|
|
@ -1,156 +0,0 @@
|
|||
//-----------------------------------------------------------------------------
|
||||
// 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);
|
||||
}
|
||||
*/
|
||||
644
samples/main.cpp
644
samples/main.cpp
|
|
@ -1,356 +1,410 @@
|
|||
// 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
|
||||
// Box3D samples host: a sokol_app shell driving render3d's renderer. The four
|
||||
// sokol_app callbacks own the window and input; everything below the entry
|
||||
// points (InitRenderer, RenderFrame, the Draw* API, the b3DebugDraw adapter) is
|
||||
// host-agnostic. See render3d's HOST_INTEGRATION.md for the contract this fills.
|
||||
//
|
||||
// OnInit: InitRenderer -> InitUI -> InitAdapter -> Load -> SelectSample
|
||||
// OnEvent: Esc quits; ImGui gate; else feed camera + dispatch to the sample
|
||||
// OnFrame: ResetFrameArena -> Step -> Render -> RenderFrame -> UI -> commit
|
||||
// OnCleanup: destroy sample + Save -> ShutdownUI -> ShutdownRenderer
|
||||
//
|
||||
// --frames N runs N frames then exits with status = sokol validation-error
|
||||
// count, the automated regression net for the port.
|
||||
|
||||
// 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 "gfx/debug_adapter.h"
|
||||
#include "gfx/keycodes.h"
|
||||
#include "gfx/renderer.h"
|
||||
#include "host/gui.h"
|
||||
#include "sample.h"
|
||||
#include "shader.h"
|
||||
#include "sokol_app.h"
|
||||
#include "sokol_glue.h"
|
||||
|
||||
#include "box3d/box3d.h"
|
||||
#include "box3d/math_functions.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <thread>
|
||||
|
||||
#ifdef TRACY_ENABLE
|
||||
#include <client/TracyProfiler.hpp>
|
||||
#if defined( _WIN32 )
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#define NOMINMAX
|
||||
// clang-format off
|
||||
#include <windows.h>
|
||||
#include <timeapi.h> // timeBeginPeriod for fine sleep granularity
|
||||
// clang-format on
|
||||
#pragma comment( lib, "winmm.lib" ) // MSVC auto-link
|
||||
#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
|
||||
static SampleContext s_context;
|
||||
static int s_frame = 0;
|
||||
static int s_frameLimit = -1;
|
||||
static int s_sampleOverride = -1;
|
||||
|
||||
inline bool IsPowerOfTwo( int32_t x )
|
||||
static int CompareSamples( const void* a, const void* b )
|
||||
{
|
||||
return ( x != 0 ) && ( ( x & ( x - 1 ) ) == 0 );
|
||||
SampleEntry* entryA = (SampleEntry*)a;
|
||||
SampleEntry* entryB = (SampleEntry*)b;
|
||||
|
||||
int result = strcmp( entryA->Category, entryB->Category );
|
||||
if ( result == 0 )
|
||||
{
|
||||
result = strcmp( entryA->Name, entryB->Name );
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
void* AllocFcn( int32_t size, int32_t alignment )
|
||||
static void SortSamples()
|
||||
{
|
||||
// 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 );
|
||||
qsort( g_sampleEntries, g_sampleCount, sizeof( SampleEntry ), CompareSamples );
|
||||
}
|
||||
|
||||
#if defined( _MSC_VER )
|
||||
void* ptr = _aligned_malloc( sizeAligned, alignment );
|
||||
#else
|
||||
void* ptr = aligned_alloc( alignment, sizeAligned );
|
||||
// Single host UI callback fired from inside StartUIFrame: menu bar, panels, and
|
||||
// the active sample's drawer.
|
||||
static void OnDrawUI( void )
|
||||
{
|
||||
DrawUI( &s_context );
|
||||
}
|
||||
|
||||
static void OnInit( void )
|
||||
{
|
||||
#if defined( _WIN32 )
|
||||
timeBeginPeriod( 1 );
|
||||
#endif
|
||||
assert( ptr != nullptr );
|
||||
return ptr;
|
||||
|
||||
const sg_environment env = sglue_environment();
|
||||
InitRenderer( &env );
|
||||
InitUI( &env, OnDrawUI );
|
||||
InitAdapter();
|
||||
|
||||
constexpr float DEG = 3.14159265358979323846f / 180.0f;
|
||||
s_context.camera.SetFov( 50.0f * DEG );
|
||||
s_context.camera.SetClip( 0.1f, 1000.0f );
|
||||
|
||||
s_context.Load();
|
||||
|
||||
int cores = (int)std::thread::hardware_concurrency();
|
||||
s_context.workerCount = b3ClampInt( cores / 2, 1, 8 );
|
||||
s_context.windowWidth = sapp_width();
|
||||
s_context.windowHeight = sapp_height();
|
||||
|
||||
SortSamples();
|
||||
|
||||
// --sample N selects a registered sample by sorted index, overriding the
|
||||
// persisted one. Lets a headless --frames run target a specific sample.
|
||||
int index = s_context.sampleIndex;
|
||||
if ( s_sampleOverride >= 0 && s_sampleOverride < g_sampleCount )
|
||||
{
|
||||
index = s_sampleOverride;
|
||||
}
|
||||
|
||||
SelectSample( &s_context, index, false );
|
||||
}
|
||||
|
||||
void FreeFcn( void* mem )
|
||||
static void OnEvent( const sapp_event* e )
|
||||
{
|
||||
#if defined( _MSC_VER )
|
||||
_aligned_free( mem );
|
||||
#else
|
||||
free( mem );
|
||||
#endif
|
||||
}
|
||||
// Esc quits even with ImGui focus so a text field can't trap the app.
|
||||
if ( e->type == SAPP_EVENTTYPE_KEY_DOWN && e->key_code == SAPP_KEYCODE_ESCAPE )
|
||||
{
|
||||
sapp_request_quit();
|
||||
return;
|
||||
}
|
||||
|
||||
static int AssertHandler( const char* cond, const char* file, int line )
|
||||
{
|
||||
printf( "Box3D Assert: %s, %s, line %d\n", cond, file, line );
|
||||
return 1;
|
||||
}
|
||||
const bool imguiCaptured = HandleEvent( e );
|
||||
|
||||
#define WINDOW_TITLE "Box3D v0.1.0"
|
||||
// The camera must always see button releases and focus loss, even when the UI
|
||||
// captures the event. Otherwise a release over an ImGui panel never clears the
|
||||
// drag flag and the camera keeps orbiting.
|
||||
const bool releaseOrUnfocus = e->type == SAPP_EVENTTYPE_MOUSE_UP || e->type == SAPP_EVENTTYPE_UNFOCUSED;
|
||||
if ( imguiCaptured == false || releaseOrUnfocus )
|
||||
{
|
||||
s_context.camera.OnEvent( e );
|
||||
}
|
||||
|
||||
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 )
|
||||
if ( imguiCaptured )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
s_manager.Keyboard( key, action, mods );
|
||||
}
|
||||
// Keep keyboard mods only. sokol packs the held mouse button into modifiers
|
||||
// (SAPP_MODIFIER_LMB == 0x100), which would defeat the sample's modifiers == 0 checks.
|
||||
const int mods = e->modifiers & ( SAPP_MODIFIER_SHIFT | SAPP_MODIFIER_CTRL | SAPP_MODIFIER_ALT | SAPP_MODIFIER_SUPER );
|
||||
|
||||
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 )
|
||||
switch ( e->type )
|
||||
{
|
||||
case SAPP_EVENTTYPE_KEY_DOWN:
|
||||
SetKeyDown( e->key_code, true );
|
||||
|
||||
// Global shortcuts on first press; repeats are ignored. The sokol
|
||||
// analog of Box2D's KeyCallback.
|
||||
if ( e->key_repeat == false )
|
||||
{
|
||||
switch ( e->key_code )
|
||||
{
|
||||
case KEY_TAB:
|
||||
s_context.showUI = !s_context.showUI;
|
||||
break;
|
||||
|
||||
case KEY_O:
|
||||
if ( mods & MOD_CTRL )
|
||||
{
|
||||
// Ctrl+O opens the fuzzy picker. Force the UI visible so it shows.
|
||||
s_context.showUI = true;
|
||||
s_context.openSamplePicker = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
s_context.singleStep += ( mods & MOD_SHIFT ) ? 5 : 1;
|
||||
}
|
||||
break;
|
||||
|
||||
case KEY_P:
|
||||
s_context.pause = !s_context.pause;
|
||||
break;
|
||||
|
||||
case KEY_M:
|
||||
s_context.showMetrics = !s_context.showMetrics;
|
||||
break;
|
||||
|
||||
case KEY_R:
|
||||
SelectSample( &s_context, s_context.sampleIndex, true );
|
||||
break;
|
||||
|
||||
case KEY_LEFT_BRACKET:
|
||||
SelectSample( &s_context, b3MaxInt( 0, s_context.sampleIndex - 1 ), false );
|
||||
break;
|
||||
|
||||
case KEY_RIGHT_BRACKET:
|
||||
SelectSample( &s_context, b3MinInt( g_sampleCount - 1, s_context.sampleIndex + 1 ), false );
|
||||
break;
|
||||
|
||||
case KEY_F:
|
||||
case KEY_HOME:
|
||||
{
|
||||
// Frame the selection, or the whole world when nothing is selected.
|
||||
b3BodyId bodyId = GetHoveredBody();
|
||||
b3AABB aabb;
|
||||
float padding;
|
||||
if ( B3_IS_NON_NULL( bodyId ) )
|
||||
{
|
||||
aabb = b3Body_ComputeAABB( bodyId );
|
||||
padding = 1.5f;
|
||||
}
|
||||
else
|
||||
{
|
||||
aabb = b3World_GetBounds( s_context.sample->m_worldId );
|
||||
padding = 0.75f;
|
||||
}
|
||||
|
||||
Camera& cam = s_context.camera;
|
||||
float aspect = cam.m_height > 0 ? (float)cam.m_width / (float)cam.m_height : 1.0f;
|
||||
cam.Frame( aabb, aspect, padding );
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
s_context.sample->Keyboard( e->key_code, ACTION_PRESS, mods );
|
||||
break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case SAPP_EVENTTYPE_KEY_UP:
|
||||
SetKeyDown( e->key_code, false );
|
||||
break;
|
||||
|
||||
case SAPP_EVENTTYPE_MOUSE_DOWN:
|
||||
s_context.mouseX = e->mouse_x;
|
||||
s_context.mouseY = e->mouse_y;
|
||||
s_context.sample->MouseDown( { e->mouse_x, e->mouse_y }, e->mouse_button, mods );
|
||||
break;
|
||||
|
||||
case SAPP_EVENTTYPE_MOUSE_UP:
|
||||
s_context.sample->MouseUp( { e->mouse_x, e->mouse_y }, e->mouse_button );
|
||||
break;
|
||||
|
||||
case SAPP_EVENTTYPE_MOUSE_MOVE:
|
||||
s_context.mouseX = e->mouse_x;
|
||||
s_context.mouseY = e->mouse_y;
|
||||
s_context.mouseDX = e->mouse_dx;
|
||||
s_context.mouseDY = e->mouse_dy;
|
||||
s_context.sample->MouseMove( { e->mouse_x, e->mouse_y } );
|
||||
break;
|
||||
|
||||
case SAPP_EVENTTYPE_RESIZED:
|
||||
{
|
||||
int w = sapp_width();
|
||||
int h = sapp_height();
|
||||
s_context.minimized = ( w == 0 || h == 0 );
|
||||
if ( s_context.minimized == false )
|
||||
{
|
||||
s_context.windowWidth = w;
|
||||
s_context.windowHeight = h;
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Pace the loop to 60 Hz so the fixed 1/60 physics step plays at real time on any
|
||||
// display. Sleep the bulk of the idle time, then spin the last bit since sleep wakes
|
||||
// are only accurate to about a millisecond.
|
||||
static void LimitFrameRate( uint64_t frameStart )
|
||||
{
|
||||
const float targetMs = 1000.0f / 60.0f;
|
||||
const float spinMs = 2.0f;
|
||||
|
||||
int sleepMs = (int)( targetMs - spinMs - b3GetMilliseconds( frameStart ) );
|
||||
if ( sleepMs > 0 )
|
||||
{
|
||||
b3Sleep( sleepMs );
|
||||
}
|
||||
|
||||
while ( b3GetMilliseconds( frameStart ) < targetMs )
|
||||
{
|
||||
b3Yield();
|
||||
}
|
||||
}
|
||||
|
||||
static void OnFrame( void )
|
||||
{
|
||||
if ( s_frameLimit >= 0 && s_frame >= s_frameLimit )
|
||||
{
|
||||
sapp_quit();
|
||||
return;
|
||||
}
|
||||
|
||||
double xd, yd;
|
||||
glfwGetCursorPos( window, &xd, &yd );
|
||||
const uint64_t frameStart = b3GetTicks();
|
||||
|
||||
b3Vec2 ps = { float( xd ), float( yd ) };
|
||||
|
||||
// Use the mouse to move things around.
|
||||
if ( button == GLFW_MOUSE_BUTTON_1 )
|
||||
// Nothing to draw while minimized. sapp reports a 0x0 framebuffer then, which
|
||||
// would drive the swapchain and every render target to zero size. Pace the
|
||||
// loop so it doesn't spin and bail.
|
||||
if ( s_context.minimized )
|
||||
{
|
||||
if ( action == GLFW_PRESS )
|
||||
if ( s_frameLimit < 0 )
|
||||
{
|
||||
s_manager.m_sample->MouseDown( ps, button, modifiers );
|
||||
}
|
||||
|
||||
if ( action == GLFW_RELEASE )
|
||||
{
|
||||
s_manager.m_sample->MouseUp( ps, button );
|
||||
LimitFrameRate( frameStart );
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
static void MouseMotionCallback( GLFWwindow* window, double x, double y )
|
||||
{
|
||||
b3Vec2 ps = { float( x ), float( y ) };
|
||||
const float dt = (float)sapp_frame_duration();
|
||||
const int W = sapp_width();
|
||||
const int H = sapp_height();
|
||||
|
||||
ImGui_ImplGlfw_CursorPosCallback( window, ps.x, ps.y );
|
||||
Camera& camera = s_context.camera;
|
||||
camera.Update( dt, W, H );
|
||||
|
||||
s_manager.m_sample->MouseMove( ps );
|
||||
}
|
||||
ResetFrameArena();
|
||||
|
||||
static void ScrollCallback( GLFWwindow* window, double deltaX, double deltaY )
|
||||
{
|
||||
ImGui_ImplGlfw_ScrollCallback( window, deltaX, deltaY );
|
||||
}
|
||||
// Apply the per-frame draw state the UI owns, then advance the sample. Step
|
||||
// queues the HUD text; Render fills the instance and overlay arenas via the
|
||||
// b3DebugDraw adapter and the sample's own Draw* calls.
|
||||
SetTransparentDynamic( s_context.transparentDynamic );
|
||||
s_context.sample->ResetText();
|
||||
|
||||
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 )
|
||||
// Pause banner only with the UI up, matching Box2D.
|
||||
if ( s_context.pause && s_context.showUI )
|
||||
{
|
||||
exit( EXIT_FAILURE );
|
||||
s_context.sample->DrawTextLine( "****PAUSED****" );
|
||||
s_context.sample->DrawTextLine( "" );
|
||||
}
|
||||
|
||||
IMGUI_CHECKVERSION();
|
||||
ImGui::CreateContext();
|
||||
ImPlot::CreateContext();
|
||||
s_context.sample->Step();
|
||||
s_context.sample->Render();
|
||||
|
||||
// Setup Platform/Renderer bindings
|
||||
ImGui_ImplGlfw_InitForOpenGL( window, false );
|
||||
ImGui_ImplOpenGL3_Init();
|
||||
FrameInput fi{};
|
||||
fi.view = camera.View();
|
||||
fi.viewInv = camera.ViewInverse();
|
||||
fi.proj = camera.Proj();
|
||||
fi.projInv = camera.ProjInverse();
|
||||
fi.cameraPosition = camera.Position();
|
||||
fi.time = (float)sapp_frame_count() / 60.0f;
|
||||
fi.debugMode = s_context.debugView;
|
||||
fi.disableShadows = !s_context.enableShadows;
|
||||
fi.disableAmbientOcclusion = !s_context.enableGtao;
|
||||
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
io.Fonts->AddFontFromFileTTF( "data/fonts/Roboto-Medium.ttf", 16.0f );
|
||||
const sg_swapchain sc = sglue_swapchain();
|
||||
RenderFrame( &sc, &fi );
|
||||
|
||||
// Initialize test manager
|
||||
s_manager.Startup( window, s_windowWidth, s_windowHeight, s_bufferWidth, s_bufferHeight );
|
||||
}
|
||||
// StartUIFrame runs after RenderFrame: it drains the text arena with the
|
||||
// camera state RenderFrame just latched and runs the UI draw callback.
|
||||
StartUIFrame( dt );
|
||||
|
||||
static void Render( GLFWwindow* window, float elapsedTime )
|
||||
{
|
||||
// Start the Dear ImGui frame
|
||||
ImGui_ImplOpenGL3_NewFrame();
|
||||
ImGui_ImplGlfw_NewFrame();
|
||||
RenderUI( &sc );
|
||||
sg_commit();
|
||||
++s_frame;
|
||||
|
||||
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 )
|
||||
if ( s_frameLimit < 0 )
|
||||
{
|
||||
s_font->Flush();
|
||||
LimitFrameRate( frameStart );
|
||||
}
|
||||
|
||||
//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 )
|
||||
static void OnCleanup( void )
|
||||
{
|
||||
// Shutdown test manager
|
||||
s_manager.Shutdown( window );
|
||||
// Destroy the sample first because it will destroy debug shapes.
|
||||
delete s_context.sample;
|
||||
s_context.sample = nullptr;
|
||||
s_context.Save();
|
||||
|
||||
ImGui_ImplOpenGL3_Shutdown();
|
||||
ImGui_ImplGlfw_Shutdown();
|
||||
ImPlot::DestroyContext();
|
||||
ImGui::DestroyContext();
|
||||
ShutdownUI();
|
||||
ShutdownRenderer();
|
||||
|
||||
delete s_font;
|
||||
s_font = nullptr;
|
||||
}
|
||||
const int errors = GetRenderErrorCount();
|
||||
fprintf( stderr, "samples: %d frames, %d sokol errors\n", s_frame, errors );
|
||||
|
||||
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);
|
||||
#if defined( _WIN32 )
|
||||
timeEndPeriod( 1 );
|
||||
#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;
|
||||
exit( errors == 0 ? 0 : 1 );
|
||||
}
|
||||
|
||||
sapp_desc sokol_main( int argc, char** argv )
|
||||
{
|
||||
for ( int i = 1; i < argc; ++i )
|
||||
{
|
||||
if ( strcmp( argv[i], "--frames" ) == 0 && i + 1 < argc )
|
||||
{
|
||||
s_frameLimit = atoi( argv[++i] );
|
||||
}
|
||||
else if ( strcmp( argv[i], "--sample" ) == 0 && i + 1 < argc )
|
||||
{
|
||||
s_sampleOverride = atoi( argv[++i] );
|
||||
}
|
||||
}
|
||||
|
||||
sapp_desc desc{};
|
||||
desc.init_cb = OnInit;
|
||||
desc.frame_cb = OnFrame;
|
||||
desc.event_cb = OnEvent;
|
||||
desc.cleanup_cb = OnCleanup;
|
||||
|
||||
// GL 4.5 for glClipControl (reverse-Z). Ignored on D3D11 / Metal.
|
||||
desc.gl.major_version = 4;
|
||||
desc.gl.minor_version = 5;
|
||||
|
||||
desc.width = 1920;
|
||||
desc.height = 1080;
|
||||
|
||||
// No swap-chain MSAA. The renderer runs MSAA in its own scene target.
|
||||
desc.sample_count = 1;
|
||||
|
||||
desc.window_title = "Box3D Samples";
|
||||
|
||||
// Vsync off: the software limiter in OnFrame owns the cadence. A hard 60 Hz
|
||||
// cap under vsync would beat against a non-60 display and pace to the wrong rate.
|
||||
desc.swap_interval = 0;
|
||||
desc.high_dpi = true;
|
||||
|
||||
return desc;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,746 +0,0 @@
|
|||
// 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 <stdio.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 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 );
|
||||
}
|
||||
|
|
@ -1,43 +0,0 @@
|
|||
// 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 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 );
|
||||
1577
samples/sample.cpp
1577
samples/sample.cpp
File diff suppressed because it is too large
Load diff
118
samples/sample.h
118
samples/sample.h
|
|
@ -3,28 +3,42 @@
|
|||
|
||||
#pragma once
|
||||
|
||||
#include "camera.h"
|
||||
#include "host/camera.h"
|
||||
|
||||
class Font;
|
||||
struct MouseEvent;
|
||||
struct MouseMoveEvent;
|
||||
struct MouseWheelEvent;
|
||||
struct Scene;
|
||||
struct GLFWwindow;
|
||||
#include "box3d/types.h"
|
||||
|
||||
// Polled key state for samples that need continuous input (character movers).
|
||||
// Fed from the host event loop; read with the KEY_* aliases in gfx/keycodes.h.
|
||||
bool IsKeyDown( int key );
|
||||
void SetKeyDown( int key, bool down );
|
||||
|
||||
// Key action passed to Keyboard, matching the old GLFW press/release values so
|
||||
// sample code reads naturally without leaking sokol_app event types.
|
||||
enum
|
||||
{
|
||||
ACTION_RELEASE = 0,
|
||||
ACTION_PRESS = 1,
|
||||
};
|
||||
|
||||
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;
|
||||
|
||||
// Latest cursor position in framebuffer pixels, fed from the host event
|
||||
// loop. Drives picking on the step that follows a mouse move.
|
||||
float mouseX = 0.0f;
|
||||
float mouseY = 0.0f;
|
||||
|
||||
// Relative cursor motion for the latest move, fed from the host. Used for
|
||||
// third-person look while the cursor is locked.
|
||||
float mouseDX = 0.0f;
|
||||
float mouseDY = 0.0f;
|
||||
|
||||
int windowWidth = 1920;
|
||||
int windowHeight = 1080;
|
||||
|
|
@ -37,9 +51,6 @@ struct SampleContext
|
|||
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;
|
||||
|
|
@ -48,6 +59,21 @@ struct SampleContext
|
|||
int singleStep = 0;
|
||||
bool restart = false;
|
||||
|
||||
// UI visibility (Tab / View > Hide UI). When hidden only the minimal HUD shows.
|
||||
bool showUI = true;
|
||||
|
||||
// Bottom diagnostics drawer (M), set by Ctrl+O for the fuzzy picker.
|
||||
bool showMetrics = false;
|
||||
bool openSamplePicker = false;
|
||||
|
||||
// Render toggles fed into FrameInput each frame. They live here, not in
|
||||
// main.cpp, so the Render menu and the frame loop share one source.
|
||||
bool enableShadows = true;
|
||||
bool enableGtao = true;
|
||||
|
||||
float sunStrength = 1.0f;
|
||||
int debugView = 0;
|
||||
|
||||
int sampleIndex = 0;
|
||||
};
|
||||
|
||||
|
|
@ -59,12 +85,30 @@ public:
|
|||
|
||||
void CreateWorld( b3Capacity* capacity );
|
||||
|
||||
// Position the first HUD text line below the menu bar, or near the top when
|
||||
// the UI is hidden. Mirrors Box2D ResetText.
|
||||
void ResetText();
|
||||
|
||||
// Update and render are split to support pausing the simulation
|
||||
virtual void Step();
|
||||
|
||||
virtual void Render();
|
||||
|
||||
virtual void UpdateUI();
|
||||
// Draw sample controls into the shared info panel. Return true if any widget
|
||||
// was drawn so the panel can add a separator.
|
||||
virtual bool DrawControls()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Let a debug sample hide the Solver section.
|
||||
virtual bool HasSolverControls() const
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
// Bottom diagnostics drawer (Profile / Counters / Renderer / Frame Time).
|
||||
void DrawMetrics();
|
||||
|
||||
virtual void Keyboard( int key, int action, int modifiers )
|
||||
{
|
||||
|
|
@ -78,6 +122,9 @@ public:
|
|||
void DrawTextLine( const char* text, ... );
|
||||
void ResetProfile();
|
||||
|
||||
// Static ground box at the origin, drawn with the procedural grid material
|
||||
b3BodyId AddGroundBox( float extent );
|
||||
|
||||
#if defined( NDEBUG )
|
||||
static constexpr bool m_isDebug = false;
|
||||
#else
|
||||
|
|
@ -89,8 +136,6 @@ public:
|
|||
static constexpr int m_profileCapacity = 512;
|
||||
|
||||
SampleContext* m_context;
|
||||
GLFWwindow* m_window;
|
||||
Scene* m_scene;
|
||||
Camera* m_camera;
|
||||
|
||||
b3WorldId m_worldId;
|
||||
|
|
@ -105,12 +150,12 @@ public:
|
|||
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;
|
||||
|
|
@ -129,31 +174,18 @@ struct SampleEntry
|
|||
SampleCreateFcn* CreateFcn;
|
||||
};
|
||||
|
||||
class SampleManager
|
||||
{
|
||||
public:
|
||||
static int Register( const char* category, const char* name, SampleCreateFcn* fcn );
|
||||
extern SampleEntry g_sampleEntries[MAX_SAMPLES];
|
||||
extern int g_sampleCount;
|
||||
|
||||
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 );
|
||||
int RegisterSample( const char* category, const char* name, SampleCreateFcn* fcn );
|
||||
|
||||
void Keyboard( int key, int action, int modifiers );
|
||||
// Destroy the active sample and build the selected one. restart keeps the camera
|
||||
// by leaving the restart flag set while the new sample constructs.
|
||||
void SelectSample( SampleContext* context, int selection, bool restart );
|
||||
|
||||
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;
|
||||
};
|
||||
// The single host UI callback: menu bar, sample picker, info panel, and the
|
||||
// bottom diagnostics drawer.
|
||||
void DrawUI( SampleContext* context );
|
||||
|
||||
struct CastClosestContext
|
||||
{
|
||||
|
|
@ -167,8 +199,8 @@ struct CastClosestContext
|
|||
bool hit;
|
||||
};
|
||||
|
||||
float CastClosestCallback( b3ShapeId shapeId, b3Vec3 point, b3Vec3 normal, float fraction, uint64_t materialId,
|
||||
int triangleIndex, int childIndex, void* context );
|
||||
float CastClosestCallback( b3ShapeId shapeId, b3Vec3 point, b3Vec3 normal, float fraction, uint64_t materialId, int triangleIndex,
|
||||
int childIndex, void* context );
|
||||
|
||||
struct MoverShapeUserData
|
||||
{
|
||||
|
|
|
|||
|
|
@ -2,11 +2,10 @@
|
|||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "benchmarks.h"
|
||||
#include "camera.h"
|
||||
#include "gfx/debug_adapter.h"
|
||||
#include "gfx/draw.h"
|
||||
#include "imgui.h"
|
||||
#include "renderer.h"
|
||||
#include "sample.h"
|
||||
#include "scene.h"
|
||||
#include "utils.h"
|
||||
|
||||
#include "box3d/box3d.h"
|
||||
|
|
@ -28,11 +27,12 @@ public:
|
|||
{
|
||||
if ( context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 0.0f, 5.0f, 80.0f, { 0.0f, 18.0f, 0.0f } );
|
||||
EnableGrid( m_scene, true );
|
||||
m_camera->SetView( 40.0f, -10.0f, 110.0f, { 0.0f, 40.0f, 0.0f } );
|
||||
}
|
||||
|
||||
CreateLargePyramid( m_worldId );
|
||||
|
||||
SetGroundShape( GetGroundShapeId() );
|
||||
}
|
||||
|
||||
static Sample* Create( SampleContext* context )
|
||||
|
|
@ -41,7 +41,7 @@ public:
|
|||
}
|
||||
};
|
||||
|
||||
static int sampleLargePyramid = SampleManager::Register( "Benchmark", "Large Pyramid", BenchmarkLargePyramid::Create );
|
||||
static int sampleLargePyramid = RegisterSample( "Benchmark", "Large Pyramid", BenchmarkLargePyramid::Create );
|
||||
|
||||
class BenchmarkWidePyramid : public Sample
|
||||
{
|
||||
|
|
@ -52,10 +52,11 @@ public:
|
|||
if ( context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 0.0f, 5.0f, 80.0f, { 0.0f, 18.0f, 0.0f } );
|
||||
EnableGrid( m_scene, true );
|
||||
}
|
||||
|
||||
CreateWidePyramid( m_worldId );
|
||||
|
||||
SetGroundShape( GetGroundShapeId() );
|
||||
}
|
||||
|
||||
static Sample* Create( SampleContext* context )
|
||||
|
|
@ -64,7 +65,7 @@ public:
|
|||
}
|
||||
};
|
||||
|
||||
static int sampleWidePyramid = SampleManager::Register( "Benchmark", "Wide Pyramid", BenchmarkWidePyramid::Create );
|
||||
static int sampleWidePyramid = RegisterSample( "Benchmark", "Wide Pyramid", BenchmarkWidePyramid::Create );
|
||||
|
||||
class BenchmarkManyPyramids : public Sample
|
||||
{
|
||||
|
|
@ -74,8 +75,7 @@ public:
|
|||
{
|
||||
if ( context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 0.0f, 5.0f, 80.0f, { 0.0f, 18.0f, 0.0f } );
|
||||
EnableGrid( m_scene, true );
|
||||
m_camera->SetView( -10.0f, 10.0f, 120.0f, { 0.0f, 5.0f, 0.0f } );
|
||||
}
|
||||
|
||||
CreateManyPyramids( m_worldId );
|
||||
|
|
@ -88,13 +88,8 @@ public:
|
|||
// Human human = {};
|
||||
// b3Vec3 position = m_isDebug ? b3Vec3{ 0.0f, 20.0f, 0.0f } : b3Vec3{ 5.0f, 20.0f, 53.0f };
|
||||
// CreateHuman( &human, m_worldId, position, frictionTorque, hertz, dampingRatio, 0, nullptr, colorize );
|
||||
}
|
||||
|
||||
void Render() override
|
||||
{
|
||||
Sample::Render();
|
||||
b3Transform transform = { { 0.0f, 0.1f, 0.0f }, b3Quat_identity };
|
||||
DrawTransform( m_scene, transform, 4.0f );
|
||||
SetGroundShape( GetGroundShapeId() );
|
||||
}
|
||||
|
||||
static Sample* Create( SampleContext* context )
|
||||
|
|
@ -103,7 +98,7 @@ public:
|
|||
}
|
||||
};
|
||||
|
||||
static int sampleManyPyramids = SampleManager::Register( "Benchmark", "Many Pyramids", BenchmarkManyPyramids::Create );
|
||||
static int sampleManyPyramids = RegisterSample( "Benchmark", "Many Pyramids", BenchmarkManyPyramids::Create );
|
||||
|
||||
class BenchmarkRain : public Sample
|
||||
{
|
||||
|
|
@ -113,8 +108,8 @@ public:
|
|||
{
|
||||
if ( context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 45.0f, 30.0f, 40.0f, b3Vec3_zero );
|
||||
context->debugDraw.drawJoints = false;
|
||||
m_camera->SetView( 25.0f, 10.0f, 70.0f, b3Vec3_zero );
|
||||
GetGuiDraw()->drawJoints = false;
|
||||
}
|
||||
|
||||
b3Capacity capacity = {};
|
||||
|
|
@ -147,7 +142,7 @@ public:
|
|||
{
|
||||
Sample::Render();
|
||||
b3Transform transform = { { 0.0f, 0.1f, 0.0f }, b3Quat_identity };
|
||||
DrawTransform( m_scene, transform, 2.0f );
|
||||
DrawAxes( transform, 2.0f );
|
||||
}
|
||||
|
||||
static Sample* Create( SampleContext* context )
|
||||
|
|
@ -156,7 +151,7 @@ public:
|
|||
}
|
||||
};
|
||||
|
||||
static int sampleRain = SampleManager::Register( "Benchmark", "Rain", BenchmarkRain::Create );
|
||||
static int sampleRain = RegisterSample( "Benchmark", "Rain", BenchmarkRain::Create );
|
||||
|
||||
#if 0
|
||||
class BenchmarkLargeWorld : public Sample
|
||||
|
|
@ -196,7 +191,7 @@ public:
|
|||
{
|
||||
Sample::Render();
|
||||
b3Transform transform = { { 0.0f, 0.1f, 0.0f }, b3Quat_identity };
|
||||
DrawTransform( m_scene, transform, 2.0f );
|
||||
DrawAxes( transform, 2.0f );
|
||||
}
|
||||
|
||||
static Sample* Create( SampleContext* context )
|
||||
|
|
@ -205,7 +200,7 @@ public:
|
|||
}
|
||||
};
|
||||
|
||||
static int sampleLargeWorld = SampleManager::Register( "Benchmark", "Large World", BenchmarkLargeWorld::Create );
|
||||
static int sampleLargeWorld = RegisterSample( "Benchmark", "Large World", BenchmarkLargeWorld::Create );
|
||||
#endif
|
||||
|
||||
class BenchmarkJointGrid : public Sample
|
||||
|
|
@ -226,7 +221,7 @@ public:
|
|||
{
|
||||
Sample::Render();
|
||||
b3Transform transform = { { 0.0f, 0.1f, 0.0f }, b3Quat_identity };
|
||||
DrawTransform( m_scene, transform, 4.0f );
|
||||
DrawAxes( transform, 4.0f );
|
||||
|
||||
// transform.p.y = 0.0f;
|
||||
// transform.p.z = -5.0f;
|
||||
|
|
@ -250,7 +245,7 @@ public:
|
|||
}
|
||||
};
|
||||
|
||||
static int sampleJointGrid = SampleManager::Register( "Benchmark", "Joint Grid", BenchmarkJointGrid::Create );
|
||||
static int sampleJointGrid = RegisterSample( "Benchmark", "Joint Grid", BenchmarkJointGrid::Create );
|
||||
|
||||
class FallingBoxes : public Sample
|
||||
{
|
||||
|
|
@ -260,27 +255,19 @@ public:
|
|||
{
|
||||
if ( context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 45.0f, 45.0f, 250.0f, b3Vec3_zero );
|
||||
EnableGrid( m_scene, true );
|
||||
m_camera->SetView( 45.0f, 10.0f, 80.0f, { 0.0f, 20.0f, 0.0f } );
|
||||
}
|
||||
|
||||
{
|
||||
b3BoxHull groundBox = b3MakeBoxHull( 250.0f, 1.0f, 250.0f );
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.position = { 0.0f, -1.0f, 0.0f };
|
||||
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef );
|
||||
b3CreateHullShape( groundId, &shapeDef, &groundBox.base );
|
||||
}
|
||||
AddGroundBox( 100.0f );
|
||||
|
||||
{
|
||||
constexpr int n = m_isDebug ? 4 : 50;
|
||||
float a = 0.5f;
|
||||
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.type = b3_dynamicBody;
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
b3BoxHull box = b3MakeBoxHull( 1.0f, 1.0f, 1.0f );
|
||||
b3BoxHull box = b3MakeCubeHull( a );
|
||||
|
||||
for ( int i = 0; i < n; ++i )
|
||||
{
|
||||
|
|
@ -288,7 +275,7 @@ public:
|
|||
{
|
||||
for ( int k = 0; k < 8; ++k )
|
||||
{
|
||||
bodyDef.position = { -16.0f + 4.0f * j, 4.0f * i + 5.0f, -16.0f + 4.0f * k };
|
||||
bodyDef.position = { -16.0f * a + 4.0f * a * j, 4.0f * a * i + 5.0f * a, -16.0f * a + 4.0f * a * k };
|
||||
b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef );
|
||||
b3CreateHullShape( bodyId, &shapeDef, &box.base );
|
||||
}
|
||||
|
|
@ -303,7 +290,7 @@ public:
|
|||
}
|
||||
};
|
||||
|
||||
static int sampleFallingBoxes = SampleManager::Register( "Benchmark", "Falling Boxes", FallingBoxes::Create );
|
||||
static int sampleFallingBoxes = RegisterSample( "Benchmark", "Falling Boxes", FallingBoxes::Create );
|
||||
|
||||
class CandyCups : public Sample
|
||||
{
|
||||
|
|
@ -313,19 +300,11 @@ public:
|
|||
{
|
||||
if ( context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 45.0f, 35.0f, 40.0f, b3Vec3_zero );
|
||||
EnableGrid( m_scene, true );
|
||||
float radius = m_isDebug ? 20.0f : 70.0f;
|
||||
m_camera->SetView( 45.0f, 20.0f, radius, b3Vec3_zero );
|
||||
}
|
||||
|
||||
{
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.position = { 0.0f, -1.0f, 0.0f };
|
||||
b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef );
|
||||
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
b3BoxHull groundBox = b3MakeBoxHull( 250.0f, 1.0f, 250.0f );
|
||||
b3CreateHullShape( groundId, &shapeDef, &groundBox.base );
|
||||
}
|
||||
AddGroundBox( 60.0f );
|
||||
|
||||
{
|
||||
constexpr int n = m_isDebug ? 4 : 16;
|
||||
|
|
@ -334,7 +313,7 @@ public:
|
|||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.type = b3_dynamicBody;
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
m_convex = CreateConvex( 0.6f, 0.0f, 0.95f, 1.0f, context->arena );
|
||||
m_convex = CreateConvex( 0.6f, 0.0f, 0.95f, 1.0f );
|
||||
for ( int i = 0; i < n; ++i )
|
||||
{
|
||||
for ( int j = 0; j < m; ++j )
|
||||
|
|
@ -355,13 +334,13 @@ public:
|
|||
b3DestroyHull( m_convex );
|
||||
}
|
||||
|
||||
b3Hull* CreateConvex( float radius1, float height1, float radius2, float height2, Arena arena ) const
|
||||
b3Hull* CreateConvex( float radius1, float height1, float radius2, float height2 ) const
|
||||
{
|
||||
const int sideCount = 8;
|
||||
constexpr int sideCount = 8;
|
||||
const float deltaAlpha = 2.0f * B3_PI / sideCount;
|
||||
|
||||
int vertexCount = 2 * sideCount;
|
||||
b3Vec3* vertexBase = static_cast<b3Vec3*>( arena.Allocate( vertexCount * sizeof( b3Vec3 ) ) );
|
||||
b3Vec3 vertexBase[2 * sideCount];
|
||||
|
||||
float alpha = 0.0f;
|
||||
for ( int sideIndex = 0; sideIndex < sideCount; ++sideIndex )
|
||||
|
|
@ -389,7 +368,7 @@ public:
|
|||
b3Hull* m_convex;
|
||||
};
|
||||
|
||||
static int sampleSmallConvexes = SampleManager::Register( "Benchmark", "Candy Cups", CandyCups::Create );
|
||||
static int sampleSmallConvexes = RegisterSample( "Benchmark", "Candy Cups", CandyCups::Create );
|
||||
|
||||
class BenchmarkExplosion : public Sample
|
||||
{
|
||||
|
|
@ -399,7 +378,8 @@ public:
|
|||
{
|
||||
if ( m_context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 0.0f, 40.0f, 10.0f, { 0.0f, 0.0f, 0.0f } );
|
||||
float radius = m_isDebug ? 15.0f : 30.0f;
|
||||
m_camera->SetView( 45.0f, 20.0f, radius, { 0.0f, 0.0f, 0.0f } );
|
||||
}
|
||||
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
|
|
@ -410,38 +390,40 @@ public:
|
|||
b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef );
|
||||
b3CreateMeshShape( groundId, &shapeDef, m_gridMesh, b3Vec3_one );
|
||||
|
||||
float hy = 1.0f;
|
||||
|
||||
{
|
||||
b3Transform transform;
|
||||
transform.p = { 0.0f, 5.0f, -20.0f };
|
||||
transform.p = { 0.0f, hy, -20.0f };
|
||||
transform.q = b3Quat_identity;
|
||||
b3BoxHull wallBox = b3MakeTransformedBoxHull( 20.0f, 5.0f, 0.1f, transform );
|
||||
b3BoxHull wallBox = b3MakeTransformedBoxHull( 20.0f, hy, 0.1f, transform );
|
||||
shapeDef.name = "wall1";
|
||||
b3CreateHullShape( groundId, &shapeDef, &wallBox.base );
|
||||
}
|
||||
|
||||
{
|
||||
b3Transform transform;
|
||||
transform.p = { 0.0f, 5.0f, 20.0f };
|
||||
transform.p = { 0.0f, hy, 20.0f };
|
||||
transform.q = b3Quat_identity;
|
||||
b3BoxHull wallBox = b3MakeTransformedBoxHull( 20.0f, 5.0f, 0.1f, transform );
|
||||
b3BoxHull wallBox = b3MakeTransformedBoxHull( 20.0f, hy, 0.1f, transform );
|
||||
shapeDef.name = "wall2";
|
||||
b3CreateHullShape( groundId, &shapeDef, &wallBox.base );
|
||||
}
|
||||
|
||||
{
|
||||
b3Transform transform;
|
||||
transform.p = { -20.0f, 5.0f, 0.0f };
|
||||
transform.p = { -20.0f, hy, 0.0f };
|
||||
transform.q = b3Quat_identity;
|
||||
b3BoxHull wallBox = b3MakeTransformedBoxHull( 0.1f, 5.0f, 20.0f, transform );
|
||||
b3BoxHull wallBox = b3MakeTransformedBoxHull( 0.1f, hy, 20.0f, transform );
|
||||
shapeDef.name = "wall3";
|
||||
b3CreateHullShape( groundId, &shapeDef, &wallBox.base );
|
||||
}
|
||||
|
||||
{
|
||||
b3Transform transform;
|
||||
transform.p = { 20.0f, 5.0f, 0.0f };
|
||||
transform.p = { 20.0f, hy, 0.0f };
|
||||
transform.q = b3Quat_identity;
|
||||
b3BoxHull wallBox = b3MakeTransformedBoxHull( 0.1f, 5.0f, 20.0f, transform );
|
||||
b3BoxHull wallBox = b3MakeTransformedBoxHull( 0.1f, hy, 20.0f, transform );
|
||||
shapeDef.name = "wall4";
|
||||
b3CreateHullShape( groundId, &shapeDef, &wallBox.base );
|
||||
}
|
||||
|
|
@ -486,32 +468,16 @@ public:
|
|||
b3World_Explode( m_worldId, &def );
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool DrawControls() override
|
||||
{
|
||||
Sample::UpdateUI();
|
||||
ImGui::SliderFloat( "Magnitude", &m_impulse, 0.0f, 2000.0f, "%.0f" );
|
||||
|
||||
float fontSize = ImGui::GetFontSize();
|
||||
float height = 10.0f * fontSize;
|
||||
ImGui::SetNextWindowPos( { 1.0f * fontSize, m_camera->m_height - height - 3.0f * fontSize }, ImGuiCond_Once );
|
||||
ImGui::SetNextWindowSize( { 20.0f * fontSize, height } );
|
||||
|
||||
ImGui::Begin( "Explosion", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize );
|
||||
|
||||
ImGui::SliderFloat( "impulse", &m_impulse, 0.0f, 2000.0f, "%.0f" );
|
||||
|
||||
if ( ImGui::Button( "explode" ) )
|
||||
if ( ImGui::Button( "Explode" ) )
|
||||
{
|
||||
Explode();
|
||||
}
|
||||
|
||||
ImGui::End();
|
||||
}
|
||||
|
||||
void Render() override
|
||||
{
|
||||
Sample::Render();
|
||||
b3Transform transform = { { 0.0f, 0.1f, 0.0f }, b3Quat_identity };
|
||||
DrawTransform( m_scene, transform, 4.0f );
|
||||
return true;
|
||||
}
|
||||
|
||||
static Sample* Create( SampleContext* context )
|
||||
|
|
@ -524,7 +490,7 @@ public:
|
|||
float m_impulse;
|
||||
};
|
||||
|
||||
static int sampleExplosion = SampleManager::Register( "Benchmark", "Explosion", BenchmarkExplosion::Create );
|
||||
static int sampleExplosion = RegisterSample( "Benchmark", "Explosion", BenchmarkExplosion::Create );
|
||||
|
||||
class BenchmarkHeightField : public Sample
|
||||
{
|
||||
|
|
@ -558,7 +524,7 @@ public:
|
|||
{
|
||||
if ( context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 45.0f, 30.0f, 20.0f );
|
||||
m_camera->SetView( 0.0f, 20.0f, 50.0f );
|
||||
}
|
||||
|
||||
m_columnCount = 50;
|
||||
|
|
@ -579,25 +545,19 @@ public:
|
|||
b3DestroyHeightField( m_heightField );
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool DrawControls() override
|
||||
{
|
||||
float fontSize = ImGui::GetFontSize();
|
||||
float height = 4.0f * fontSize;
|
||||
ImGui::SetNextWindowPos( { 1.0f * fontSize, m_camera->m_height - height - 3.0f * fontSize }, ImGuiCond_Once );
|
||||
ImGui::SetNextWindowSize( { 20.0f * fontSize, height } );
|
||||
|
||||
ImGui::Begin( "Height Field", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize );
|
||||
ImGui::SliderFloat( "radius", &m_radius, 0.0f, 1.0f, "%.1f" );
|
||||
ImGui::End();
|
||||
ImGui::SliderFloat( "Radius", &m_radius, 0.0f, 1.0f, "%.1f" );
|
||||
return true;
|
||||
}
|
||||
|
||||
void Render() override
|
||||
{
|
||||
Sample::Render();
|
||||
|
||||
DrawLine( m_scene, b3Vec3_zero, 0.4f * b3Vec3_axisX, b3_colorRed );
|
||||
DrawLine( m_scene, b3Vec3_zero, 0.4f * b3Vec3_axisY, b3_colorGreen );
|
||||
DrawLine( m_scene, b3Vec3_zero, 0.4f * b3Vec3_axisZ, b3_colorBlue );
|
||||
DrawLine( b3Vec3_zero, 0.4f * b3Vec3_axisX, MakeColor( b3_colorRed ) );
|
||||
DrawLine( b3Vec3_zero, 0.4f * b3Vec3_axisY, MakeColor( b3_colorGreen ) );
|
||||
DrawLine( b3Vec3_zero, 0.4f * b3Vec3_axisZ, MakeColor( b3_colorBlue ) );
|
||||
|
||||
int hitCount = 0;
|
||||
int iterationCount = 0;
|
||||
|
|
@ -650,28 +610,29 @@ public:
|
|||
if ( m_isDebug )
|
||||
{
|
||||
b3Vec3 point = result.point;
|
||||
DrawLine( m_scene, point, point + 0.5f * result.normal, b3_colorGreen );
|
||||
DrawPoint( m_scene, point, 10.0f, b3_colorGreen );
|
||||
DrawLine( point, point + 0.5f * result.normal, MakeColor( b3_colorGreen ) );
|
||||
DrawPoint( point, 10.0f, MakeColor( b3_colorGreen ) );
|
||||
|
||||
if ( m_radius > 0.0f )
|
||||
{
|
||||
b3Transform transform = b3Transform_identity;
|
||||
transform.p = rayOrigin + result.fraction * rayTranslation;
|
||||
DrawSphere( m_scene, transform, sphere, b3_colorPurple );
|
||||
DrawSphereEx( transform, m_radius, MakeColorAlpha( b3_colorPurple, 0.5f ), 0.0f, 0.5f,
|
||||
TRANSPARENT_SHADOW_NONE );
|
||||
}
|
||||
|
||||
b3Vec3 rayEnd = rayOrigin + result.fraction * rayTranslation;
|
||||
DrawLine( m_scene, rayOrigin, rayEnd, b3_colorYellow );
|
||||
DrawPoint( m_scene, rayOrigin, 2.0f, b3_colorRed );
|
||||
DrawPoint( m_scene, rayEnd, 2.0f, b3_colorRed );
|
||||
DrawLine( rayOrigin, rayEnd, MakeColor( b3_colorYellow ) );
|
||||
DrawPoint( rayOrigin, 2.0f, MakeColor( b3_colorRed ) );
|
||||
DrawPoint( rayEnd, 2.0f, MakeColor( b3_colorRed ) );
|
||||
}
|
||||
}
|
||||
else if ( m_isDebug )
|
||||
{
|
||||
b3Vec3 rayEnd = rayOrigin + rayTranslation;
|
||||
DrawLine( m_scene, rayOrigin, rayEnd, b3_colorYellow );
|
||||
DrawPoint( m_scene, rayOrigin, 2.0f, b3_colorRed );
|
||||
DrawPoint( m_scene, rayEnd, 2.0f, b3_colorRed );
|
||||
DrawLine( rayOrigin, rayEnd, MakeColor( b3_colorYellow ) );
|
||||
DrawPoint( rayOrigin, 2.0f, MakeColor( b3_colorRed ) );
|
||||
DrawPoint( rayEnd, 2.0f, MakeColor( b3_colorRed ) );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -700,7 +661,7 @@ public:
|
|||
float m_radius;
|
||||
};
|
||||
|
||||
static int sampleHeightFieldBenchmark = SampleManager::Register( "Benchmark", "Height Field", BenchmarkHeightField::Create );
|
||||
static int sampleHeightFieldBenchmark = RegisterSample( "Benchmark", "Height Field", BenchmarkHeightField::Create );
|
||||
|
||||
class BenchmarkFallingTrees : public Sample
|
||||
{
|
||||
|
|
@ -710,9 +671,7 @@ public:
|
|||
{
|
||||
if ( context->restart == false )
|
||||
{
|
||||
float distance = 220.0f;
|
||||
float height = 20.0f;
|
||||
m_camera->SetView( 25.0f, 10.0f, distance, { 0.0f, height, 0.0f } );
|
||||
m_camera->SetView( 20.0f, 0.0f, 140.0f, { 0.0f, 15.0f, 0.0f } );
|
||||
}
|
||||
|
||||
m_gridSize = 100;
|
||||
|
|
@ -746,17 +705,8 @@ public:
|
|||
}
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool DrawControls() override
|
||||
{
|
||||
Sample::UpdateUI();
|
||||
|
||||
float fontSize = ImGui::GetFontSize();
|
||||
float height = 10.0f * fontSize;
|
||||
ImGui::SetNextWindowPos( { 1.0f * fontSize, m_camera->m_height - height - 3.0f * fontSize }, ImGuiCond_Once );
|
||||
ImGui::SetNextWindowSize( { 20.0f * fontSize, height } );
|
||||
|
||||
ImGui::Begin( "Falling Trees", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize );
|
||||
|
||||
if ( ImGui::RadioButton( "100cm", &m_gridSize, 100 ) )
|
||||
{
|
||||
Generate();
|
||||
|
|
@ -772,7 +722,7 @@ public:
|
|||
Generate();
|
||||
}
|
||||
|
||||
ImGui::End();
|
||||
return true;
|
||||
}
|
||||
|
||||
static Sample* Create( SampleContext* context )
|
||||
|
|
@ -783,7 +733,7 @@ public:
|
|||
int m_gridSize;
|
||||
};
|
||||
|
||||
static int sampleFallingTrees = SampleManager::Register( "Benchmark", "Falling Trees", BenchmarkFallingTrees::Create );
|
||||
static int sampleFallingTrees = RegisterSample( "Benchmark", "Falling Trees", BenchmarkFallingTrees::Create );
|
||||
|
||||
struct ShapeUserData
|
||||
{
|
||||
|
|
@ -799,7 +749,7 @@ public:
|
|||
{
|
||||
if ( m_context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 5.0f, 18.0f, 180.0f, { 0.0f, 5.0f, 0.0f } );
|
||||
m_camera->SetView( 0.0f, 0.0f, 250.0f, { 0.0f, 110.0f, 0.0f } );
|
||||
}
|
||||
|
||||
b3World_SetCustomFilterCallback( m_worldId, FilterFcn, this );
|
||||
|
|
@ -807,61 +757,77 @@ public:
|
|||
m_activeSensor.row = 0;
|
||||
m_activeSensor.active = true;
|
||||
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef );
|
||||
|
||||
{
|
||||
float gridSize = 3.0f;
|
||||
|
||||
// These destroy anything they touch, including themselves.
|
||||
b3BoxHull box = b3MakeCubeHull( 0.48f * gridSize );
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
shapeDef.isSensor = true;
|
||||
shapeDef.enableSensorEvents = true;
|
||||
shapeDef.userData = &m_activeSensor;
|
||||
shapeDef.baseMaterial.customColor = b3MakeDebugColor( (b3HexColor)0x505050u, b3_debugMaterialMetallic );
|
||||
|
||||
float y = 0.0f;
|
||||
float x = -40.0f * gridSize;
|
||||
for ( int i = 0; i < 81; ++i )
|
||||
{
|
||||
b3Vec3 extents = { 0.5f * gridSize, 0.5f * gridSize, 0.5f * gridSize };
|
||||
b3Transform transform = { { x, y, 0.0f }, b3Quat_identity };
|
||||
b3BoxHull box = b3MakeTransformedBoxHull( extents.x, extents.y, extents.z, transform );
|
||||
bodyDef.position = { x, y, 0.0f };
|
||||
b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef );
|
||||
b3CreateHullShape( groundId, &shapeDef, &box.base );
|
||||
x += gridSize;
|
||||
}
|
||||
}
|
||||
|
||||
g_randomSeed = 42;
|
||||
|
||||
float shift = 5.0f;
|
||||
float xCenter = 0.5f * shift * m_columnCount;
|
||||
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
shapeDef.isSensor = true;
|
||||
shapeDef.enableSensorEvents = true;
|
||||
|
||||
float yStart = 10.0f;
|
||||
|
||||
for ( int j = 0; j < m_rowCount; ++j )
|
||||
{
|
||||
m_passiveSensors[j].row = j;
|
||||
m_passiveSensors[j].active = false;
|
||||
shapeDef.userData = m_passiveSensors + j;
|
||||
g_randomSeed = 42;
|
||||
|
||||
float y = j * shift + yStart;
|
||||
for ( int i = 0; i < m_columnCount; ++i )
|
||||
float shift = 5.0f;
|
||||
float xCenter = 0.5f * shift * m_columnCount;
|
||||
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
|
||||
b3BoxHull box = b3MakeCubeHull( 0.5f );
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
shapeDef.isSensor = true;
|
||||
shapeDef.enableSensorEvents = true;
|
||||
|
||||
float yStart = 10.0f;
|
||||
m_filterRow = m_rowCount >> 1;
|
||||
|
||||
for ( int j = 0; j < m_rowCount; ++j )
|
||||
{
|
||||
float x = i * shift - xCenter;
|
||||
b3Vec3 extents = { 0.5f, 0.5f, 0.5f };
|
||||
b3Transform transform = { { x, y, 0.0f }, b3Quat_identity };
|
||||
b3BoxHull box = b3MakeTransformedBoxHull( extents.x, extents.y, extents.z, transform );
|
||||
b3CreateHullShape( groundId, &shapeDef, &box.base );
|
||||
m_passiveSensors[j].row = j;
|
||||
m_passiveSensors[j].active = false;
|
||||
shapeDef.userData = m_passiveSensors + j;
|
||||
|
||||
if ( j == m_filterRow )
|
||||
{
|
||||
shapeDef.enableCustomFiltering = true;
|
||||
shapeDef.baseMaterial.customColor = b3_colorFuchsia;
|
||||
}
|
||||
else
|
||||
{
|
||||
shapeDef.enableCustomFiltering = false;
|
||||
shapeDef.baseMaterial.customColor = 0;
|
||||
}
|
||||
|
||||
float y = j * shift + yStart;
|
||||
for ( int i = 0; i < m_columnCount; ++i )
|
||||
{
|
||||
float x = i * shift - xCenter;
|
||||
bodyDef.position = { x, y, 0.0f };
|
||||
b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef );
|
||||
b3CreateHullShape( groundId, &shapeDef, &box.base );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
m_maxBeginCount = 0;
|
||||
m_maxEndCount = 0;
|
||||
m_lastStepCount = 0;
|
||||
m_filterRow = m_rowCount >> 1;
|
||||
}
|
||||
|
||||
void CreateRow( float y )
|
||||
|
|
@ -1000,7 +966,7 @@ public:
|
|||
int m_filterRow;
|
||||
};
|
||||
|
||||
static int benchmarkSensor = SampleManager::Register( "Benchmark", "Sensor", BenchmarkSensor::Create );
|
||||
static int benchmarkSensor = RegisterSample( "Benchmark", "Sensor", BenchmarkSensor::Create );
|
||||
|
||||
class BenchmarkWasher : public Sample
|
||||
{
|
||||
|
|
@ -1010,8 +976,7 @@ public:
|
|||
{
|
||||
if ( m_context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 0.0f, 20.0f, 60.0, { 0.0f, 15.0f, 0.0f } );
|
||||
EnableGrid( m_scene, true );
|
||||
m_camera->SetView( 15.0f, 20.0f, 60.0, { 0.0f, 15.0f, 0.0f } );
|
||||
}
|
||||
|
||||
b3Capacity capacity = {};
|
||||
|
|
@ -1019,6 +984,7 @@ public:
|
|||
CreateWorld( &capacity );
|
||||
|
||||
CreateWasher( m_worldId );
|
||||
SetGroundShape( GetGroundShapeId() );
|
||||
}
|
||||
|
||||
static Sample* Create( SampleContext* context )
|
||||
|
|
@ -1027,7 +993,7 @@ public:
|
|||
}
|
||||
};
|
||||
|
||||
static int benchmarkWasher = SampleManager::Register( "Benchmark", "Washer", BenchmarkWasher::Create );
|
||||
static int benchmarkWasher = RegisterSample( "Benchmark", "Washer", BenchmarkWasher::Create );
|
||||
|
||||
class BenchmarkLargeWorld : public Sample
|
||||
{
|
||||
|
|
@ -1037,8 +1003,7 @@ public:
|
|||
{
|
||||
if ( context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 0.0f, 60.0f, 80.0f, b3Vec3_zero );
|
||||
EnableGrid( m_scene, false );
|
||||
m_camera->SetView( 0.0f, 10.0f, 250.0f, b3Vec3_zero );
|
||||
}
|
||||
|
||||
b3Capacity capacity = {};
|
||||
|
|
@ -1060,7 +1025,7 @@ public:
|
|||
}
|
||||
};
|
||||
|
||||
static int sampleLargeWorld = SampleManager::Register( "Benchmark", "Large World", BenchmarkLargeWorld::Create );
|
||||
static int sampleLargeWorld = RegisterSample( "Benchmark", "Large World", BenchmarkLargeWorld::Create );
|
||||
|
||||
class BenchmarkHull : public Sample
|
||||
{
|
||||
|
|
@ -1097,8 +1062,8 @@ public:
|
|||
b3Transform transform1 = { { -2.0f, 0.0f, 0.0f }, b3Quat_identity };
|
||||
b3Transform transform2 = { { 2.0f, 0.0f, 0.0f }, b3Quat_identity };
|
||||
|
||||
DrawHull( m_scene, transform1, m_hull, b3_colorGreen, true );
|
||||
DrawHull( m_scene, transform2, m_transformedHull, b3_colorYellow, true );
|
||||
DrawHull( transform1, m_hull, MakeColor( b3_colorGreen ) );
|
||||
DrawHull( transform2, m_transformedHull, MakeColor( b3_colorYellow ) );
|
||||
|
||||
Sample::Render();
|
||||
}
|
||||
|
|
@ -1148,7 +1113,7 @@ public:
|
|||
int m_count;
|
||||
};
|
||||
|
||||
static int sampleBenchmarkHull = SampleManager::Register( "Benchmark", "Hull", BenchmarkHull::Create );
|
||||
static int sampleBenchmarkHull = RegisterSample( "Benchmark", "Hull", BenchmarkHull::Create );
|
||||
|
||||
class BenchmarkChains : public Sample
|
||||
{
|
||||
|
|
@ -1159,7 +1124,6 @@ public:
|
|||
if ( context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 0.0f, 15.0f, 50.0f, { 0.0f, 5.0f, 0.0f } );
|
||||
EnableGrid( context->scene, false );
|
||||
}
|
||||
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
|
|
@ -1261,7 +1225,7 @@ public:
|
|||
b3Vec3 m_noise;
|
||||
};
|
||||
|
||||
static int sampleBenchmarkChains = SampleManager::Register( "Benchmark", "Chains", BenchmarkChains::Create );
|
||||
static int sampleBenchmarkChains = RegisterSample( "Benchmark", "Chains", BenchmarkChains::Create );
|
||||
|
||||
class BenchmarkDestruction : public Sample
|
||||
{
|
||||
|
|
@ -1273,13 +1237,12 @@ public:
|
|||
{
|
||||
if ( m_small )
|
||||
{
|
||||
m_camera->SetView( 0.0f, 40.0f, 10.0f, { 0.0f, 0.0f, 0.0f } );
|
||||
m_camera->SetView( 0.0f, 40.0f, 20.0f, { 0.0f, 0.0f, 0.0f } );
|
||||
}
|
||||
else
|
||||
{
|
||||
m_camera->SetView( 0.0f, 40.0f, 30.0f, { 0.0f, 0.0f, 0.0f } );
|
||||
}
|
||||
EnableGrid( m_context->scene, false );
|
||||
}
|
||||
|
||||
int bodyCapacity = m_gridCount * m_gridCount * m_gridCount;
|
||||
|
|
@ -1298,6 +1261,7 @@ public:
|
|||
b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef );
|
||||
b3CreateMeshShape( groundId, &shapeDef, m_gridMesh, b3Vec3_one );
|
||||
|
||||
#if 0
|
||||
{
|
||||
b3Transform transform;
|
||||
transform.p = { 0.0f, 5.0f, -20.0f };
|
||||
|
|
@ -1333,6 +1297,7 @@ public:
|
|||
shapeDef.name = "wall4";
|
||||
b3CreateHullShape( groundId, &shapeDef, &wallBox.base );
|
||||
}
|
||||
#endif
|
||||
|
||||
m_bodyIds = (b3BodyId*)malloc( bodyCapacity * sizeof( b3BodyId ) );
|
||||
memset( m_bodyIds, 0, bodyCapacity * sizeof( b3BodyId ) );
|
||||
|
|
@ -1414,17 +1379,16 @@ public:
|
|||
{
|
||||
Sample::Render();
|
||||
|
||||
b3Transform transform = { { 0.0f, 0.1f, 0.0f }, b3Quat_identity };
|
||||
DrawTransform( m_scene, transform, 4.0f );
|
||||
|
||||
DrawTextLine( "spawn = %.2f ms", m_spawnMilliseconds );
|
||||
DrawTextLine( "destroy = %.2f ms", m_destroyMilliseconds );
|
||||
|
||||
float r = m_explosionDef.radius;
|
||||
DrawSphere( m_scene, b3Transform_identity, { m_explosionDef.position, r }, b3_colorAqua );
|
||||
b3Sphere sphere1 = { m_explosionDef.position, r };
|
||||
DrawWireSphere( b3Transform_identity, &sphere1, 24, MakeColor( b3_colorAqua ) );
|
||||
|
||||
float rf = r + m_explosionDef.falloff;
|
||||
DrawSphere( m_scene, b3Transform_identity, { m_explosionDef.position, rf }, b3_colorCornsilk );
|
||||
b3Sphere sphere2 = { m_explosionDef.position, rf };
|
||||
DrawWireSphere( b3Transform_identity, &sphere2, 24, MakeColor( b3_colorCornsilk ) );
|
||||
}
|
||||
|
||||
void Step() override
|
||||
|
|
@ -1456,7 +1420,7 @@ public:
|
|||
float m_destroyMilliseconds;
|
||||
};
|
||||
|
||||
static int sampleDestruction = SampleManager::Register( "Benchmark", "Destruction", BenchmarkDestruction::Create );
|
||||
static int sampleDestruction = RegisterSample( "Benchmark", "Destruction", BenchmarkDestruction::Create );
|
||||
|
||||
class BenchmarkJunkyard : public Sample
|
||||
{
|
||||
|
|
@ -1466,12 +1430,13 @@ public:
|
|||
{
|
||||
if ( context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 45.0f, 30.0f, 100.0f, b3Vec3_zero );
|
||||
context->debugDraw.drawJoints = false;
|
||||
EnableGrid( m_scene, true );
|
||||
m_camera->SetView( 45.0f, 30.0f, 125.0f, b3Vec3_zero );
|
||||
GetGuiDraw()->drawJoints = false;
|
||||
}
|
||||
|
||||
CreateJunkyard( m_worldId );
|
||||
|
||||
SetGroundShape( GetGroundShapeId() );
|
||||
}
|
||||
|
||||
void Step() override
|
||||
|
|
@ -1486,4 +1451,4 @@ public:
|
|||
}
|
||||
};
|
||||
|
||||
static int sampleJunkyard = SampleManager::Register( "Benchmark", "Junkyard", BenchmarkJunkyard::Create );
|
||||
static int sampleJunkyard = RegisterSample( "Benchmark", "Junkyard", BenchmarkJunkyard::Create );
|
||||
|
|
|
|||
|
|
@ -1,14 +1,13 @@
|
|||
// 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 "gfx/keycodes.h"
|
||||
|
||||
#include "box3d/box3d.h"
|
||||
#include "gfx/draw.h"
|
||||
|
||||
class BodyType : public Sample
|
||||
{
|
||||
|
|
@ -24,18 +23,7 @@ public:
|
|||
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 );
|
||||
}
|
||||
b3BodyId groundId = AddGroundBox( 20.0f );
|
||||
|
||||
// Define attachment
|
||||
{
|
||||
|
|
@ -188,14 +176,8 @@ public:
|
|||
}
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool DrawControls() 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;
|
||||
|
|
@ -248,7 +230,7 @@ public:
|
|||
}
|
||||
}
|
||||
|
||||
ImGui::End();
|
||||
return true;
|
||||
}
|
||||
|
||||
void Step() override
|
||||
|
|
@ -285,7 +267,7 @@ public:
|
|||
bool m_isEnabled;
|
||||
};
|
||||
|
||||
static int sampleBodyType = SampleManager::Register( "Bodies", "Body Type", BodyType::Create );
|
||||
static int sampleBodyType = RegisterSample( "Bodies", "Body Type", BodyType::Create );
|
||||
|
||||
class SpinningBooks : public Sample
|
||||
{
|
||||
|
|
@ -298,6 +280,8 @@ public:
|
|||
m_camera->SetView( 0.0f, 30.0f, 10.0f, { 0.0f, 1.0f, 0.0f } );
|
||||
}
|
||||
|
||||
AddGroundBox( 10.0f );
|
||||
|
||||
b3BoxHull box = b3MakeBoxHull( 0.35f, 0.08f, 0.5f );
|
||||
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
|
|
@ -325,19 +309,13 @@ public:
|
|||
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 );
|
||||
static int sampleBook = RegisterSample( "Bodies", "Spinning Book", SpinningBooks::Create );
|
||||
|
||||
// Dzhanibekov effect
|
||||
class GyroscopicTorque : public Sample
|
||||
|
|
@ -351,6 +329,8 @@ public:
|
|||
m_camera->SetView( 0.0f, 20.0f, 4.0f, { 0.0f, 2.0f, 0.0f } );
|
||||
}
|
||||
|
||||
AddGroundBox( 20.0f );
|
||||
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.type = b3_dynamicBody;
|
||||
bodyDef.position = { 0.0f, 2.0f, 0.0f };
|
||||
|
|
@ -368,28 +348,17 @@ public:
|
|||
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 );
|
||||
static int sampleGyroscopicTorque = RegisterSample( "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 )
|
||||
{
|
||||
|
|
@ -398,19 +367,15 @@ public:
|
|||
m_camera->SetView( 45.0f, 25.0f, 25.0f, b3Vec3_zero );
|
||||
}
|
||||
|
||||
AddGroundBox( 30.0f );
|
||||
|
||||
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 };
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
shapeDef.baseMaterial.rollingResistance = 0.1f;
|
||||
b3CreateCapsuleShape( m_weebleId, &shapeDef, &capsule );
|
||||
|
||||
|
|
@ -432,16 +397,11 @@ public:
|
|||
|
||||
m_explosionPosition = { 0.0f, -0.1f, 0.0f };
|
||||
m_explosionRadius = 8.0f;
|
||||
m_explosionMagnitude = 10000.0f;
|
||||
m_explosionMagnitude = 20000.0f;
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool DrawControls() 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 ) );
|
||||
|
|
@ -457,27 +417,20 @@ public:
|
|||
def.impulsePerArea = m_explosionMagnitude;
|
||||
b3World_Explode( m_worldId, &def );
|
||||
}
|
||||
ImGui::PushItemWidth( 100.0f );
|
||||
ImGui::PushItemWidth( 6.0f * ImGui::GetFontSize() );
|
||||
|
||||
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 );
|
||||
return true;
|
||||
}
|
||||
|
||||
void Step() override
|
||||
{
|
||||
Sample::Step();
|
||||
|
||||
b3Sphere sphere = { b3Vec3_zero, m_explosionRadius };
|
||||
DrawSphere( m_scene, { m_explosionPosition, b3Quat_identity }, sphere, b3_colorAzure );
|
||||
b3Sphere sphere = { m_explosionPosition, m_explosionRadius };
|
||||
DrawWireSphere(b3Transform_identity, &sphere, 64, MakeColor(b3_colorAzure) );
|
||||
|
||||
// This shows how to get the velocity of a point on a body
|
||||
b3Vec3 localPoint = { 0.0f, 2.0f, 0.0f };
|
||||
|
|
@ -487,8 +440,13 @@ public:
|
|||
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 );
|
||||
DrawLine( worldPoint, worldPoint + v1, MakeColor( b3_colorRed ) );
|
||||
DrawLine( worldPoint + offset, worldPoint + v2 + offset, MakeColor( b3_colorGreen ) );
|
||||
}
|
||||
|
||||
static Sample* Create( SampleContext* context )
|
||||
{
|
||||
return new Weeble( context );
|
||||
}
|
||||
|
||||
b3BodyId m_weebleId;
|
||||
|
|
@ -497,7 +455,7 @@ public:
|
|||
float m_explosionMagnitude;
|
||||
};
|
||||
|
||||
static int sampleWeeble = SampleManager::Register( "Bodies", "Weeble", Weeble::Create );
|
||||
static int sampleWeeble = RegisterSample( "Bodies", "Weeble", Weeble::Create );
|
||||
|
||||
class DisableBody : public Sample
|
||||
{
|
||||
|
|
@ -515,23 +473,19 @@ public:
|
|||
m_camera->SetView( 45.0f, 25.0f, 10.0f, b3Vec3_zero );
|
||||
}
|
||||
|
||||
AddGroundBox( 20.0f );
|
||||
|
||||
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 };
|
||||
b3Capsule capsule = { { 0.0f, 0.0f, 0.0f }, { 0.0f, -linkLength, 0.0f }, linkRadius };
|
||||
|
||||
b3BodyId parentId = {};
|
||||
for ( int link = 0; link < e_count; ++link )
|
||||
{
|
||||
bodyDef.position = { 0.0f, 0.8f * float( e_count ) * linkLength, link * linkLength };
|
||||
bodyDef.position = { 0.0f, (float( e_count ) - link) * linkLength + 1.0f, 0.0f };
|
||||
bodyDef.type = B3_IS_NULL( parentId ) ? b3_kinematicBody : b3_dynamicBody;
|
||||
b3BodyId childId = b3CreateBody( m_worldId, &bodyDef );
|
||||
b3CreateCapsuleShape( childId, &shapeDef, &capsule );
|
||||
|
|
@ -542,7 +496,7 @@ public:
|
|||
b3WeldJointDef jointDef = b3DefaultWeldJointDef();
|
||||
jointDef.base.bodyIdA = parentId;
|
||||
jointDef.base.bodyIdB = childId;
|
||||
jointDef.base.localFrameA.p = { 0.0f, 0.0f, linkLength };
|
||||
jointDef.base.localFrameA.p = { 0.0f, -linkLength, 0.0f };
|
||||
jointDef.angularHertz = 10.0f;
|
||||
jointDef.angularDampingRatio = 1.0f;
|
||||
b3CreateWeldJoint( m_worldId, &jointDef );
|
||||
|
|
@ -559,14 +513,8 @@ public:
|
|||
b3CreateSphereShape( m_ballId, &shapeDef, &sphere );
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool DrawControls() 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 ) )
|
||||
|
|
@ -597,7 +545,7 @@ public:
|
|||
}
|
||||
}
|
||||
|
||||
ImGui::End();
|
||||
return true;
|
||||
}
|
||||
|
||||
void Step() override
|
||||
|
|
@ -616,7 +564,7 @@ public:
|
|||
b3BodyId m_ballId;
|
||||
};
|
||||
|
||||
static int sampleDisable = SampleManager::Register( "Bodies", "Disable", DisableBody::Create );
|
||||
static int sampleDisable = RegisterSample( "Bodies", "Disable", DisableBody::Create );
|
||||
|
||||
class BodyCast : public Sample
|
||||
{
|
||||
|
|
@ -657,7 +605,7 @@ public:
|
|||
|
||||
void MouseDown( b3Vec2 p, int button, int modifiers ) override
|
||||
{
|
||||
if ( button == 0 && modifiers == GLFW_MOD_ALT )
|
||||
if ( button == 0 && modifiers == MOD_ALT )
|
||||
{
|
||||
PickRay pickRay = m_camera->BuildPickRay( p.x, p.y );
|
||||
m_origin = pickRay.origin + 10.0f * b3Normalize( pickRay.translation );
|
||||
|
|
@ -684,11 +632,11 @@ public:
|
|||
{
|
||||
Sample::Render();
|
||||
|
||||
DrawGrid( m_scene, 10 );
|
||||
DrawGroundGrid( 10 );
|
||||
b3Transform transform = { { 0.0f, 0.1f, 0.0f }, b3Quat_identity };
|
||||
DrawTransform( m_scene, transform, 4.0f );
|
||||
DrawAxes( transform, 4.0f );
|
||||
|
||||
DrawHull( m_scene, m_transform, m_cylinder, b3_colorBlue, false );
|
||||
DrawHull( m_transform, m_cylinder, MakeColor( b3_colorBlue ) );
|
||||
}
|
||||
|
||||
void Step() override
|
||||
|
|
@ -702,16 +650,16 @@ public:
|
|||
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 );
|
||||
DrawLine( input.origin, input.origin + input.maxFraction * input.translation, MakeColor( 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 );
|
||||
DrawLine( result.point, result.point + 0.2f * result.normal, MakeColor( b3_colorYellow ) );
|
||||
DrawPoint( result.point, 10.0f, MakeColor( b3_colorYellow ) );
|
||||
}
|
||||
|
||||
DrawPoint( m_scene, input.origin, 10.0f, b3_colorGreen );
|
||||
DrawPoint( m_scene, input.origin + input.translation, 10.0f, b3_colorRed );
|
||||
DrawPoint( input.origin, 10.0f, MakeColor( b3_colorGreen ) );
|
||||
DrawPoint( input.origin + input.translation, 10.0f, MakeColor( b3_colorRed ) );
|
||||
}
|
||||
|
||||
// Cast sphere
|
||||
|
|
@ -729,18 +677,18 @@ public:
|
|||
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 );
|
||||
DrawSolidSphere( transform, sphere, MakeColor( b3_colorGreen ) );
|
||||
DrawLine( result.point, result.point + 0.2f * result.normal, MakeColor( b3_colorYellow ) );
|
||||
}
|
||||
else
|
||||
{
|
||||
b3Transform transform = { input.maxFraction * input.translation, b3Quat_identity };
|
||||
DrawSphere( m_scene, transform, sphere, b3_colorWhite );
|
||||
DrawSolidSphere( transform, sphere, MakeColor( 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 );
|
||||
DrawLine( sphere.center, sphere.center + input.maxFraction * input.translation, MakeColor( b3_colorWhite ) );
|
||||
DrawPoint( sphere.center, 10.0f, MakeColor( b3_colorGreen ) );
|
||||
DrawPoint( sphere.center + input.maxFraction * input.translation, 10.0f, MakeColor( b3_colorRed ) );
|
||||
}
|
||||
|
||||
// Overlap capsule
|
||||
|
|
@ -751,11 +699,11 @@ public:
|
|||
|
||||
if ( overlaps )
|
||||
{
|
||||
DrawCapsule( m_scene, b3Transform_identity, capsule, b3_colorGreen );
|
||||
DrawSolidCapsule( b3Transform_identity, capsule, MakeColor( b3_colorGreen ) );
|
||||
}
|
||||
else
|
||||
{
|
||||
DrawCapsule( m_scene, b3Transform_identity, capsule, b3_colorGray );
|
||||
DrawSolidCapsule( b3Transform_identity, capsule, MakeColor( b3_colorGray ) );
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -764,12 +712,12 @@ public:
|
|||
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 );
|
||||
DrawSolidCapsule( b3Transform_identity, capsule, MakeColor( b3_colorPurple ) );
|
||||
|
||||
for ( int i = 0; i < count; ++i )
|
||||
{
|
||||
b3PlaneResult result = bodyPlanes[i].result;
|
||||
DrawPlane( m_scene, result.plane.normal, result.point, b3_colorOrange );
|
||||
DrawPlane( result.plane.normal, result.point, MakeColor( b3_colorOrange ) );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -790,7 +738,7 @@ public:
|
|||
bool m_tracking;
|
||||
};
|
||||
|
||||
static int sampleBodyCast = SampleManager::Register( "Bodies", "Cast", BodyCast::Create );
|
||||
static int sampleBodyCast = RegisterSample( "Bodies", "Cast", BodyCast::Create );
|
||||
|
||||
// This shows how to drive a kinematic body to reach a target
|
||||
class Kinematic : public Sample
|
||||
|
|
@ -803,6 +751,8 @@ public:
|
|||
{
|
||||
m_camera->SetView( 0.0f, 30.0f, 10.0f, { 0.0f, 1.5f, 0.0f } );
|
||||
}
|
||||
|
||||
AddGroundBox( 20.0f );
|
||||
|
||||
m_amplitude = 2.0f;
|
||||
|
||||
|
|
@ -810,7 +760,7 @@ public:
|
|||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.type = b3_kinematicBody;
|
||||
bodyDef.position.x = 2.0f * m_amplitude;
|
||||
bodyDef.position.y = m_amplitude;
|
||||
bodyDef.position.y = m_amplitude + 1.0f;
|
||||
|
||||
m_bodyId = b3CreateBody( m_worldId, &bodyDef );
|
||||
|
||||
|
|
@ -822,13 +772,6 @@ public:
|
|||
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;
|
||||
|
|
@ -845,13 +788,13 @@ public:
|
|||
|
||||
b3Vec3 point;
|
||||
point.x = 2.0f * m_amplitude * cosf( t );
|
||||
point.y = m_amplitude * ( sinf( 2.0f * t ) + 1.0f );
|
||||
point.y = m_amplitude * ( sinf( 2.0f * t ) + 1.0f ) + 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 );
|
||||
DrawLine( point - 0.5f * axis, point + 0.5f * axis, MakeColor( b3_colorPlum ) );
|
||||
DrawPoint( point, 10.0f, MakeColor( b3_colorPlum ) );
|
||||
|
||||
b3Body_SetTargetTransform( m_bodyId, { point, rotation }, timeStep, true );
|
||||
}
|
||||
|
|
@ -871,7 +814,7 @@ public:
|
|||
float m_time;
|
||||
};
|
||||
|
||||
static int sampleKinematic = SampleManager::Register( "Bodies", "Kinematic", Kinematic::Create );
|
||||
static int sampleKinematic = RegisterSample( "Bodies", "Kinematic", Kinematic::Create );
|
||||
|
||||
class LockMixing : public Sample
|
||||
{
|
||||
|
|
@ -884,16 +827,7 @@ public:
|
|||
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 );
|
||||
}
|
||||
AddGroundBox( 20.0f );
|
||||
|
||||
b3BoxHull cube = b3MakeBoxHull( 1.0f, 1.0f, 1.0f );
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
|
|
@ -962,7 +896,7 @@ public:
|
|||
}
|
||||
};
|
||||
|
||||
static int sampleLockMixing = SampleManager::Register( "Bodies", "Lock Mixing", LockMixing::Create );
|
||||
static int sampleLockMixing = RegisterSample( "Bodies", "Lock Mixing", LockMixing::Create );
|
||||
|
||||
// A fully rotation locked body uses a zero inverse inertia tensor
|
||||
class FixedRotation : public Sample
|
||||
|
|
@ -976,16 +910,7 @@ public:
|
|||
m_camera->SetView( 0.0f, 15.0f, 10.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 );
|
||||
}
|
||||
AddGroundBox( 20.0f );
|
||||
|
||||
b3Capsule capsule = { { 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 0.3f };
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
|
|
@ -1020,4 +945,4 @@ public:
|
|||
}
|
||||
};
|
||||
|
||||
static int sampleFixedRotation = SampleManager::Register( "Bodies", "Fixed Rotation", FixedRotation::Create );
|
||||
static int sampleFixedRotation = RegisterSample( "Bodies", "Fixed Rotation", FixedRotation::Create );
|
||||
|
|
|
|||
|
|
@ -1,17 +1,15 @@
|
|||
// 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 "mesh_loader.h"
|
||||
#include "gfx/draw.h"
|
||||
|
||||
#include "gfx/keycodes.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
|
||||
|
|
@ -59,24 +57,20 @@ public:
|
|||
{
|
||||
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 );
|
||||
DrawGroundGrid( 10 );
|
||||
DrawLine( b3Vec3_zero, 2.0f * b3Vec3_axisX, MakeColor( b3_colorRed ) );
|
||||
DrawLine( b3Vec3_zero, 2.0f * b3Vec3_axisY, MakeColor( b3_colorGreen ) );
|
||||
DrawLine( b3Vec3_zero, 2.0f * b3Vec3_axisZ, MakeColor( b3_colorBlue ) );
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool DrawControls() 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();
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool PlaneResultFcn( b3ShapeId shape, const b3PlaneResult* results, int planeCount, void* context )
|
||||
|
|
@ -92,7 +86,7 @@ public:
|
|||
|
||||
void MouseDown( b3Vec2 p, int button, int modifiers ) override
|
||||
{
|
||||
if ( button == 0 && ( modifiers & GLFW_MOD_ALT ) == 0 )
|
||||
if ( button == 0 && ( modifiers & MOD_ALT ) == 0 )
|
||||
{
|
||||
PickRay pickRay = m_camera->BuildPickRay( p.x, p.y );
|
||||
m_origin = pickRay.origin + 10.0f * b3Normalize( pickRay.translation );
|
||||
|
|
@ -120,7 +114,7 @@ public:
|
|||
{
|
||||
m_planeCount = 0;
|
||||
|
||||
DrawCapsule( m_scene, m_transform, m_capsule, b3_colorGreen );
|
||||
DrawSolidCapsule( m_transform, m_capsule, MakeColor( b3_colorGreen ) );
|
||||
b3QueryFilter filter = b3DefaultQueryFilter();
|
||||
|
||||
b3Capsule capsule = { m_capsule.center1 + m_transform.p, m_capsule.center2 + m_transform.p, m_capsule.radius };
|
||||
|
|
@ -131,8 +125,8 @@ public:
|
|||
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 );
|
||||
DrawPoint( p1, 5.0f, MakeColor( b3_colorYellow ) );
|
||||
DrawLine( p1, p2, MakeColor( b3_colorYellow ) );
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -150,7 +144,7 @@ public:
|
|||
bool m_tracking;
|
||||
};
|
||||
|
||||
static int sampleCapsulePlane = SampleManager::Register( "Character", "CapsulePlane", CapsulePlane::Create );
|
||||
static int sampleCapsulePlane = RegisterSample( "Character", "CapsulePlane", CapsulePlane::Create );
|
||||
|
||||
// Exercises the deep-overlap path of b3World_CollideMover against each primitive
|
||||
// shape type: drag the mover capsule (yellow) into the static sphere, capsule,
|
||||
|
|
@ -216,7 +210,7 @@ public:
|
|||
void Render() override
|
||||
{
|
||||
Sample::Render();
|
||||
DrawGrid( m_scene, 12 );
|
||||
DrawGroundGrid( 12 );
|
||||
}
|
||||
|
||||
static bool PlaneResultFcn( b3ShapeId /*shape*/, const b3PlaneResult* results, int planeCount, void* context )
|
||||
|
|
@ -232,7 +226,7 @@ public:
|
|||
|
||||
void MouseDown( b3Vec2 p, int button, int modifiers ) override
|
||||
{
|
||||
if ( button == 0 && ( modifiers & GLFW_MOD_ALT ) == 0 )
|
||||
if ( button == 0 && ( modifiers & MOD_ALT ) == 0 )
|
||||
{
|
||||
PickRay pickRay = m_camera->BuildPickRay( p.x, p.y );
|
||||
m_origin = pickRay.origin + 10.0f * b3Normalize( pickRay.translation );
|
||||
|
|
@ -267,7 +261,7 @@ public:
|
|||
b3World_CollideMover( m_worldId, &worldMover, filter, PlaneResultFcn, this );
|
||||
|
||||
// Mover at the queried position.
|
||||
DrawCapsule( m_scene, m_transform, m_capsule, b3_colorYellow );
|
||||
DrawSolidCapsule( m_transform, m_capsule, MakeColor( b3_colorYellow ) );
|
||||
|
||||
// One arrow per returned plane, drawn from the contact point along the
|
||||
// normal. A degenerate (zero) normal is drawn red to surface the bug.
|
||||
|
|
@ -277,8 +271,8 @@ public:
|
|||
b3PlaneResult r = m_results[i];
|
||||
bool valid = b3IsNormalized( r.plane.normal );
|
||||
b3HexColor color = valid ? b3_colorLimeGreen : b3_colorRed;
|
||||
DrawPoint( m_scene, r.point, 6.0f, color );
|
||||
DrawArrow( m_scene, r.point, r.point + 0.5f * r.plane.normal, 0.05f, color );
|
||||
DrawPoint( r.point, 6.0f, MakeColor( color ) );
|
||||
DrawArrow( r.point, r.point + 0.5f * r.plane.normal, MakeColor( color ) );
|
||||
if ( valid == false )
|
||||
{
|
||||
m_zeroNormalCount += 1;
|
||||
|
|
@ -289,22 +283,18 @@ public:
|
|||
// Solve the planes and show the pushed-out capsule pose.
|
||||
b3PlaneSolverResult solved = b3SolvePlanes( b3Vec3_zero, solverPlanes, m_planeCount );
|
||||
b3Transform pushed = { m_transform.p + solved.delta, m_transform.q };
|
||||
DrawCapsule( m_scene, pushed, m_capsule, b3_colorCyan );
|
||||
DrawSolidCapsule( pushed, m_capsule, MakeColor( b3_colorCyan ) );
|
||||
|
||||
DrawTextLine( "drag the capsule with the left mouse to push it into the shapes" );
|
||||
DrawTextLine( "yellow = queried pose, cyan = solved push-out, lime = valid plane normals" );
|
||||
DrawTextLine( "planes: %d degenerate normals: %d", m_planeCount, m_zeroNormalCount );
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool DrawControls() override
|
||||
{
|
||||
float fontSize = ImGui::GetFontSize();
|
||||
ImGui::SetNextWindowPos( ImVec2( 10.0f, 600.0f ), ImGuiCond_Once );
|
||||
ImGui::SetNextWindowSize( ImVec2( 18.0f * fontSize, 5.0f * fontSize ) );
|
||||
ImGui::Begin( "Mover Overlap", nullptr, ImGuiWindowFlags_NoResize );
|
||||
ImGui::Text( "planes: %d", m_planeCount );
|
||||
ImGui::Text( "degenerate normals: %d", m_zeroNormalCount );
|
||||
ImGui::End();
|
||||
return true;
|
||||
}
|
||||
|
||||
static constexpr int m_planeCapacity = 32;
|
||||
|
|
@ -320,7 +310,7 @@ public:
|
|||
bool m_tracking;
|
||||
};
|
||||
|
||||
static int sampleMoverOverlap = SampleManager::Register( "Character", "MoverOverlap", MoverOverlap::Create );
|
||||
static int sampleMoverOverlap = RegisterSample( "Character", "MoverOverlap", MoverOverlap::Create );
|
||||
|
||||
class BasicMover : public Sample
|
||||
{
|
||||
|
|
@ -527,9 +517,9 @@ public:
|
|||
// Body->AddSphere( &ShapeDef, Sphere );
|
||||
//}
|
||||
|
||||
m_camera->m_thirdPerson = true;
|
||||
m_camera->m_thirdPerson = false;
|
||||
m_clipVelocity = true;
|
||||
glfwSetInputMode( m_window, GLFW_CURSOR, GLFW_CURSOR_DISABLED );
|
||||
// sapp_lock_mouse( true );
|
||||
|
||||
//m_haveMouseLast = false;
|
||||
//m_mouseLast = { 0.0f, 0.0f };
|
||||
|
|
@ -539,7 +529,7 @@ public:
|
|||
~BasicMover() override
|
||||
{
|
||||
m_camera->m_thirdPerson = false;
|
||||
glfwSetInputMode( m_window, GLFW_CURSOR, GLFW_CURSOR_NORMAL );
|
||||
sapp_lock_mouse( false );
|
||||
b3DestroyMesh( m_levelMesh );
|
||||
b3DestroyMesh( m_stairs );
|
||||
b3DestroyMesh( m_torus );
|
||||
|
|
@ -549,32 +539,25 @@ public:
|
|||
void Render() override
|
||||
{
|
||||
Sample::Render();
|
||||
DrawTransform( m_scene, { { 0.0f, 0.0f, 0.02f }, b3Quat_identity }, 2.0f );
|
||||
DrawAxes( { { 0.0f, 0.0f, 0.02f }, b3Quat_identity }, 2.0f );
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool DrawControls() 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 ) )
|
||||
if ( ImGui::Checkbox( "Third Person (T)", &thirdPerson ) )
|
||||
{
|
||||
ToggleThirdPerson();
|
||||
}
|
||||
|
||||
ImGui::Checkbox( "Clip Velocity", &m_clipVelocity );
|
||||
|
||||
ImGui::End();
|
||||
return true;
|
||||
}
|
||||
|
||||
void Keyboard( int key, int action, int mods ) override
|
||||
{
|
||||
if ( key == GLFW_KEY_T && action == GLFW_PRESS )
|
||||
if ( key == KEY_T && action == ACTION_PRESS )
|
||||
{
|
||||
ToggleThirdPerson();
|
||||
}
|
||||
|
|
@ -605,7 +588,7 @@ public:
|
|||
bool m_clipVelocity;
|
||||
};
|
||||
|
||||
static int sampleMover = SampleManager::Register( "Character", "Mover", BasicMover::Create );
|
||||
static int sampleMover = RegisterSample( "Character", "Mover", BasicMover::Create );
|
||||
|
||||
struct ClosestShapeCastContext
|
||||
{
|
||||
|
|
@ -893,7 +876,6 @@ struct RigidbodyCharacter
|
|||
// --- CategorizeGround: s&box-style box cast with radius shrinking ---
|
||||
void CategorizeGround()
|
||||
{
|
||||
Scene* scene = m_sample->m_scene;
|
||||
b3Vec3 feet = GetFeetPosition();
|
||||
|
||||
// s&box: from = WorldPosition + Up*4, to = WorldPosition + Down*2 (Source units)
|
||||
|
|
@ -910,7 +892,7 @@ struct RigidbodyCharacter
|
|||
if ( radiusScale < 0.7f )
|
||||
{
|
||||
UpdateGround( false, b3Vec3_axisY );
|
||||
DrawLine( scene, from, to, b3_colorRed );
|
||||
DrawLine( from, to, MakeColor( b3_colorRed ) );
|
||||
return;
|
||||
}
|
||||
tr = TraceBody( from, to, radiusScale, 0.5f );
|
||||
|
|
@ -919,13 +901,13 @@ struct RigidbodyCharacter
|
|||
if ( !tr.startedSolid && tr.hit && IsStandableSurface( tr.normal ) && m_jumpCooldown <= 0.0f )
|
||||
{
|
||||
UpdateGround( true, tr.normal );
|
||||
DrawLine( scene, from, tr.hitPoint, b3_colorGreen );
|
||||
DrawPoint( scene, tr.hitPoint, 5.0f, b3_colorGreen );
|
||||
DrawLine( from, tr.hitPoint, MakeColor( b3_colorGreen ) );
|
||||
DrawPoint( tr.hitPoint, 5.0f, MakeColor( b3_colorGreen ) );
|
||||
}
|
||||
else
|
||||
{
|
||||
UpdateGround( false, b3Vec3_axisY );
|
||||
DrawLine( scene, from, to, b3_colorGray );
|
||||
DrawLine( from, to, MakeColor( b3_colorGray ) );
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -947,7 +929,6 @@ struct RigidbodyCharacter
|
|||
return;
|
||||
}
|
||||
|
||||
Scene* scene = m_sample->m_scene;
|
||||
b3Vec3 pos = b3Body_GetPosition( m_bodyId );
|
||||
|
||||
b3Vec3 from = { pos.x, pos.y + 0.05f, pos.z };
|
||||
|
|
@ -982,7 +963,7 @@ struct RigidbodyCharacter
|
|||
b3Body_SetLinearVelocity( m_bodyId, vel );
|
||||
}
|
||||
|
||||
DrawLine( scene, from, tr.endPosition, b3_colorCyan );
|
||||
DrawLine( from, tr.endPosition, MakeColor( b3_colorCyan ) );
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -990,7 +971,6 @@ struct RigidbodyCharacter
|
|||
// Returns true if a step was taken and m_stepPosition was set.
|
||||
bool TryStep( float maxStepHeight )
|
||||
{
|
||||
Scene* scene = m_sample->m_scene;
|
||||
b3Vec3 pos = b3Body_GetPosition( m_bodyId );
|
||||
b3Vec3 vel = b3Body_GetLinearVelocity( m_bodyId );
|
||||
|
||||
|
|
@ -1023,7 +1003,7 @@ struct RigidbodyCharacter
|
|||
radiusScale -= 0.1f;
|
||||
if ( radiusScale < 0.6f )
|
||||
{
|
||||
DrawLine( scene, forwardFrom, forwardTo, b3_colorRed );
|
||||
DrawLine( forwardFrom, forwardTo, MakeColor( b3_colorRed ) );
|
||||
return false;
|
||||
}
|
||||
trForward = TraceBody( forwardFrom, forwardTo, radiusScale );
|
||||
|
|
@ -1035,7 +1015,7 @@ struct RigidbodyCharacter
|
|||
return false;
|
||||
}
|
||||
|
||||
DrawLine( scene, forwardFrom, trForward.endPosition, b3_colorYellow );
|
||||
DrawLine( forwardFrom, trForward.endPosition, MakeColor( b3_colorYellow ) );
|
||||
|
||||
// Remaining velocity direction after hit
|
||||
b3Vec3 hitPos = trForward.endPosition;
|
||||
|
|
@ -1047,7 +1027,7 @@ struct RigidbodyCharacter
|
|||
|
||||
if ( trUp.startedSolid )
|
||||
{
|
||||
DrawLine( scene, upFrom, upTo, b3_colorRed );
|
||||
DrawLine( upFrom, upTo, MakeColor( b3_colorRed ) );
|
||||
return false;
|
||||
}
|
||||
|
||||
|
|
@ -1056,11 +1036,11 @@ struct RigidbodyCharacter
|
|||
if ( upDistance < 0.005f )
|
||||
{
|
||||
// Too tight to step up
|
||||
DrawLine( scene, upFrom, topPos, b3_colorRed );
|
||||
DrawLine( upFrom, topPos, MakeColor( b3_colorRed ) );
|
||||
return false;
|
||||
}
|
||||
|
||||
DrawLine( scene, upFrom, topPos, b3_colorYellow );
|
||||
DrawLine( upFrom, topPos, MakeColor( b3_colorYellow ) );
|
||||
|
||||
// Phase 3 — ACROSS: from top position, trace in move direction
|
||||
float acrossDist = forwardDist * ( 1.0f - trForward.fraction ) + m_bodyRadius * 0.5f;
|
||||
|
|
@ -1070,12 +1050,12 @@ struct RigidbodyCharacter
|
|||
|
||||
if ( trAcross.startedSolid )
|
||||
{
|
||||
DrawLine( scene, acrossFrom, acrossTo, b3_colorRed );
|
||||
DrawLine( acrossFrom, acrossTo, MakeColor( b3_colorRed ) );
|
||||
return false;
|
||||
}
|
||||
|
||||
b3Vec3 acrossPos = trAcross.hit ? trAcross.endPosition : acrossTo;
|
||||
DrawLine( scene, acrossFrom, acrossPos, b3_colorYellow );
|
||||
DrawLine( acrossFrom, acrossPos, MakeColor( b3_colorYellow ) );
|
||||
|
||||
// Phase 4 — DOWN: from across position, trace straight down
|
||||
b3Vec3 downFrom = acrossPos;
|
||||
|
|
@ -1084,13 +1064,13 @@ struct RigidbodyCharacter
|
|||
|
||||
if ( !trDown.hit )
|
||||
{
|
||||
DrawLine( scene, downFrom, downTo, b3_colorRed );
|
||||
DrawLine( downFrom, downTo, MakeColor( b3_colorRed ) );
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( !IsStandableSurface( trDown.normal ) )
|
||||
{
|
||||
DrawLine( scene, downFrom, trDown.endPosition, b3_colorRed );
|
||||
DrawLine( downFrom, trDown.endPosition, MakeColor( b3_colorRed ) );
|
||||
return false;
|
||||
}
|
||||
|
||||
|
|
@ -1101,8 +1081,8 @@ struct RigidbodyCharacter
|
|||
return false;
|
||||
}
|
||||
|
||||
DrawLine( scene, downFrom, trDown.endPosition, b3_colorYellow );
|
||||
DrawPoint( scene, trDown.endPosition, 8.0f, b3_colorYellow );
|
||||
DrawLine( downFrom, trDown.endPosition, MakeColor( b3_colorYellow ) );
|
||||
DrawPoint( trDown.endPosition, 8.0f, MakeColor( b3_colorYellow ) );
|
||||
|
||||
// Teleport body to step position
|
||||
b3Vec3 stepPos = { trDown.endPosition.x, trDown.endPosition.y + 0.01f, trDown.endPosition.z };
|
||||
|
|
@ -1316,24 +1296,23 @@ struct RigidbodyCharacter
|
|||
|
||||
void DrawDebug() const
|
||||
{
|
||||
Scene* scene = m_sample->m_scene;
|
||||
b3Vec3 pos = b3Body_GetPosition( m_bodyId );
|
||||
b3Vec3 vel = b3Body_GetLinearVelocity( m_bodyId );
|
||||
|
||||
// Draw velocity vector (purple)
|
||||
DrawLine( scene, pos, pos + vel, b3_colorPurple );
|
||||
DrawLine( pos, pos + vel, MakeColor( b3_colorPurple ) );
|
||||
|
||||
// Draw wish velocity (orange)
|
||||
DrawLine( scene, pos, pos + m_lastWishVelocity, b3_colorOrange );
|
||||
DrawLine( pos, pos + m_lastWishVelocity, MakeColor( b3_colorOrange ) );
|
||||
|
||||
// Draw mass center (yellow dot)
|
||||
DrawPoint( scene, m_massCenterWorld, 8.0f, b3_colorYellow );
|
||||
DrawPoint( m_massCenterWorld, 8.0f, MakeColor( b3_colorYellow ) );
|
||||
|
||||
// Draw ground indicator
|
||||
if ( m_onGround )
|
||||
{
|
||||
b3Vec3 bottom = { pos.x, pos.y - m_totalHeight * 0.5f, pos.z };
|
||||
DrawLine( scene, bottom, bottom + 0.3f * m_groundNormal, b3_colorGreen );
|
||||
DrawLine( bottom, bottom + 0.3f * m_groundNormal, MakeColor( b3_colorGreen ) );
|
||||
}
|
||||
}
|
||||
};
|
||||
|
|
@ -1514,13 +1493,13 @@ public:
|
|||
|
||||
m_camera->m_thirdPerson = true;
|
||||
m_showDebug = true;
|
||||
glfwSetInputMode( m_window, GLFW_CURSOR, GLFW_CURSOR_DISABLED );
|
||||
sapp_lock_mouse( true );
|
||||
}
|
||||
|
||||
~RigidBodyCharacter() override
|
||||
{
|
||||
m_camera->m_thirdPerson = false;
|
||||
glfwSetInputMode( m_window, GLFW_CURSOR, GLFW_CURSOR_NORMAL );
|
||||
sapp_lock_mouse( false );
|
||||
b3DestroyMesh( m_levelMesh );
|
||||
b3DestroyMesh( m_stairs );
|
||||
b3DestroyMesh( m_building );
|
||||
|
|
@ -1531,12 +1510,12 @@ public:
|
|||
|
||||
void Keyboard( int key, int action, int mods ) override
|
||||
{
|
||||
if ( key == GLFW_KEY_T && action == GLFW_PRESS )
|
||||
if ( key == KEY_T && action == ACTION_PRESS )
|
||||
{
|
||||
ToggleThirdPerson();
|
||||
}
|
||||
|
||||
if ( key == GLFW_KEY_V && action == GLFW_PRESS )
|
||||
if ( key == KEY_V && action == ACTION_PRESS )
|
||||
{
|
||||
m_showDebug = !m_showDebug;
|
||||
}
|
||||
|
|
@ -1562,29 +1541,29 @@ public:
|
|||
|
||||
if ( m_camera->m_thirdPerson )
|
||||
{
|
||||
if ( glfwGetKey( m_window, GLFW_KEY_W ) )
|
||||
if ( IsKeyDown( KEY_W ) )
|
||||
{
|
||||
throttle.x += 1.0f;
|
||||
}
|
||||
if ( glfwGetKey( m_window, GLFW_KEY_S ) )
|
||||
if ( IsKeyDown( KEY_S ) )
|
||||
{
|
||||
throttle.x -= 1.0f;
|
||||
}
|
||||
if ( glfwGetKey( m_window, GLFW_KEY_A ) )
|
||||
if ( IsKeyDown( KEY_A ) )
|
||||
{
|
||||
throttle.y -= 1.0f;
|
||||
}
|
||||
if ( glfwGetKey( m_window, GLFW_KEY_D ) )
|
||||
if ( IsKeyDown( KEY_D ) )
|
||||
{
|
||||
throttle.y += 1.0f;
|
||||
}
|
||||
|
||||
if ( glfwGetKey( m_window, GLFW_KEY_SPACE ) )
|
||||
if ( IsKeyDown( KEY_SPACE ) )
|
||||
{
|
||||
m_character.Jump();
|
||||
}
|
||||
|
||||
m_character.m_sprint = m_character.m_onGround && glfwGetKey( m_window, GLFW_KEY_LEFT_SHIFT ) != 0;
|
||||
m_character.m_sprint = m_character.m_onGround && IsKeyDown( KEY_LEFT_SHIFT );
|
||||
}
|
||||
|
||||
// Pre-step: manipulate velocity before physics
|
||||
|
|
@ -1654,25 +1633,18 @@ public:
|
|||
void Render() override
|
||||
{
|
||||
Sample::Render();
|
||||
DrawTransform( m_scene, { { 0.0f, 0.0f, 0.02f }, b3Quat_identity }, 2.0f );
|
||||
DrawAxes( { { 0.0f, 0.0f, 0.02f }, b3Quat_identity }, 2.0f );
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool DrawControls() 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( 22.0f * fontSize, height ) );
|
||||
|
||||
ImGui::Begin( "Rigidbody Character", nullptr, ImGuiWindowFlags_NoResize );
|
||||
|
||||
bool thirdPerson = m_camera->m_thirdPerson;
|
||||
if ( ImGui::Checkbox( "Third Person (Key: T)", &thirdPerson ) )
|
||||
if ( ImGui::Checkbox( "Third Person (T)", &thirdPerson ) )
|
||||
{
|
||||
ToggleThirdPerson();
|
||||
}
|
||||
|
||||
ImGui::Checkbox( "Debug Visualization (Key: V)", &m_showDebug );
|
||||
ImGui::Checkbox( "Debug (V)", &m_showDebug );
|
||||
|
||||
ImGui::Separator();
|
||||
ImGui::Text( "Ground: %s", m_character.m_onGround ? "YES" : "NO" );
|
||||
|
|
@ -1686,7 +1658,7 @@ public:
|
|||
b3Vec3 pos = b3Body_GetPosition( m_character.m_bodyId );
|
||||
ImGui::Text( "Mass center offset: %.2f", mc.y - pos.y );
|
||||
|
||||
ImGui::End();
|
||||
return true;
|
||||
}
|
||||
|
||||
static Sample* Create( SampleContext* context )
|
||||
|
|
@ -1704,4 +1676,4 @@ public:
|
|||
bool m_showDebug;
|
||||
};
|
||||
|
||||
static int sampleRBCharacter = SampleManager::Register( "Character", "Rigid Body", RigidBodyCharacter::Create );
|
||||
static int sampleRBCharacter = RegisterSample( "Character", "Rigid Body", RigidBodyCharacter::Create );
|
||||
|
|
|
|||
|
|
@ -1,12 +1,13 @@
|
|||
// SPDX-FileCopyrightText: 2025 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "GLFW/glfw3.h"
|
||||
#include "camera.h"
|
||||
#include "utils.h"
|
||||
#include "renderer.h"
|
||||
#include "sample.h"
|
||||
#include "scene.h"
|
||||
|
||||
#include "gfx/draw.h"
|
||||
#include "utils.h"
|
||||
|
||||
#include "gfx/debug_adapter.h"
|
||||
#include "gfx/keycodes.h"
|
||||
|
||||
#include "box3d/box3d.h"
|
||||
|
||||
|
|
@ -73,10 +74,10 @@ public:
|
|||
{
|
||||
Sample::Render();
|
||||
|
||||
DrawGrid( m_scene, 10 );
|
||||
DrawLine( m_scene, b3Vec3_zero, 0.4f * b3Vec3_axisX, b3_colorRed );
|
||||
DrawLine( m_scene, b3Vec3_zero, 0.4f * b3Vec3_axisY, b3_colorGreen );
|
||||
DrawLine( m_scene, b3Vec3_zero, 0.4f * b3Vec3_axisZ, b3_colorBlue );
|
||||
DrawGroundGrid( 10 );
|
||||
DrawLine( b3Vec3_zero, 0.4f * b3Vec3_axisX, MakeColor( b3_colorRed ) );
|
||||
DrawLine( b3Vec3_zero, 0.4f * b3Vec3_axisY, MakeColor( b3_colorGreen ) );
|
||||
DrawLine( b3Vec3_zero, 0.4f * b3Vec3_axisZ, MakeColor( b3_colorBlue ) );
|
||||
|
||||
for ( float x = -8.0f; x <= 8.0f; x += 0.1f )
|
||||
{
|
||||
|
|
@ -88,12 +89,12 @@ public:
|
|||
{
|
||||
b3Vec3 point = result.point;
|
||||
|
||||
DrawLine( m_scene, point, point + 0.5f * result.normal, b3_colorGreen );
|
||||
DrawLine( point, point + 0.5f * result.normal, MakeColor( b3_colorGreen ) );
|
||||
}
|
||||
|
||||
DrawPoint( m_scene, rayOrigin, 4.0f, b3_colorGreen );
|
||||
DrawPoint( m_scene, rayOrigin + rayTranslation, 4.0f, b3_colorRed );
|
||||
DrawLine( m_scene, rayOrigin, rayOrigin + rayTranslation, b3_colorYellow );
|
||||
DrawPoint( rayOrigin, 4.0f, MakeColor( b3_colorGreen ) );
|
||||
DrawPoint( rayOrigin + rayTranslation, 4.0f, MakeColor( b3_colorRed ) );
|
||||
DrawLine( rayOrigin, rayOrigin + rayTranslation, MakeColor( b3_colorYellow ) );
|
||||
}
|
||||
|
||||
if ( m_offset > 2.0f )
|
||||
|
|
@ -117,7 +118,7 @@ public:
|
|||
b3MeshData* m_mesh;
|
||||
};
|
||||
|
||||
static int sampleRayCurtain = SampleManager::Register( "Collision", "Ray Curtain", RayCurtain::Create );
|
||||
static int sampleRayCurtain = RegisterSample( "Collision", "Ray Curtain", RayCurtain::Create );
|
||||
|
||||
// Context for ray cast callbacks. Do what you want with this.
|
||||
struct CastContext
|
||||
|
|
@ -510,7 +511,7 @@ public:
|
|||
|
||||
void MouseDown( b3Vec2 p, int button, int modifiers ) override
|
||||
{
|
||||
if ( button == 0 && modifiers == GLFW_MOD_CONTROL )
|
||||
if ( button == 0 && modifiers == MOD_CTRL )
|
||||
{
|
||||
PickRay pickRay = m_camera->BuildPickRay( p.x, p.y );
|
||||
m_origin = pickRay.origin;
|
||||
|
|
@ -518,14 +519,13 @@ public:
|
|||
}
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool HasSolverControls() const override
|
||||
{
|
||||
float height = 360.0f;
|
||||
ImGui::SetNextWindowPos( ImVec2( 10.0f, m_camera->m_height - height - 50.0f ), ImGuiCond_Once );
|
||||
ImGui::SetNextWindowSize( ImVec2( 210.0f, height ) );
|
||||
|
||||
ImGui::Begin( "Options", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize );
|
||||
return false;
|
||||
}
|
||||
|
||||
bool DrawControls() override
|
||||
{
|
||||
const char* castTypes[] = { "Ray", "Sphere", "Capsule", "Box" };
|
||||
if ( ImGui::Combo( "Cast Type", &m_castType, castTypes, IM_ARRAYSIZE( castTypes ) ) )
|
||||
{
|
||||
|
|
@ -573,16 +573,7 @@ public:
|
|||
DestroyBody();
|
||||
}
|
||||
|
||||
ImGui::End();
|
||||
|
||||
for ( int i = 0; i < m_maxCount; ++i )
|
||||
{
|
||||
if ( ( i & m_ignoreBase ) == m_ignoreBase && B3_IS_NULL( m_bodies[i] ) == false )
|
||||
{
|
||||
b3AABB bounds = b3Body_ComputeAABB( m_bodies[i] );
|
||||
DrawBounds( m_scene, bounds, 0.0f, b3_colorYellow );
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void Render() override
|
||||
|
|
@ -590,6 +581,16 @@ public:
|
|||
DrawTextLine( "Ctrl + left mouse to cast through cursor" );
|
||||
DrawTextLine( "Shapes drawn in yellow boxes are ignored by the ray" );
|
||||
|
||||
// Outline the bodies the cast ignores
|
||||
for ( int i = 0; i < m_maxCount; ++i )
|
||||
{
|
||||
if ( ( i & m_ignoreBase ) == m_ignoreBase && B3_IS_NULL( m_bodies[i] ) == false )
|
||||
{
|
||||
b3AABB bounds = b3Body_ComputeAABB( m_bodies[i] );
|
||||
DrawBounds( bounds, 0.0f, MakeColor( b3_colorYellow ) );
|
||||
}
|
||||
}
|
||||
|
||||
switch ( m_mode )
|
||||
{
|
||||
case e_any:
|
||||
|
|
@ -618,8 +619,8 @@ public:
|
|||
DrawTextLine( "material = %d, triangle = %d", m_castContext.materialIds[i], m_castContext.triangleIndices[i] );
|
||||
}
|
||||
|
||||
DrawGrid( m_scene, 10 );
|
||||
DrawTransform( m_scene, b3Transform_identity, 1.0f );
|
||||
DrawGroundGrid( 10 );
|
||||
DrawAxes( b3Transform_identity, 1.0f );
|
||||
|
||||
Sample::Render();
|
||||
}
|
||||
|
|
@ -700,59 +701,59 @@ public:
|
|||
{
|
||||
assert( m_castContext.count <= 3 );
|
||||
b3HexColor colors[3] = { b3_colorRed, b3_colorGreen, b3_colorBlue };
|
||||
DrawLine( m_scene, m_origin, m_origin + m_translation, color2 );
|
||||
DrawLine( m_origin, m_origin + m_translation, MakeColor( color2 ) );
|
||||
|
||||
for ( int i = 0; i < m_castContext.count; ++i )
|
||||
{
|
||||
b3Vec3 point = m_castContext.points[i];
|
||||
b3Vec3 normal = m_castContext.normals[i];
|
||||
DrawPoint( m_scene, point, 10.0f, colors[i] );
|
||||
DrawPoint( point, 10.0f, MakeColor( colors[i] ) );
|
||||
b3Vec3 head = point + 0.5f * normal;
|
||||
|
||||
b3Transform transform = { m_castContext.fractions[i] * m_translation, b3Quat_identity };
|
||||
|
||||
if ( m_castType == e_rayCast )
|
||||
{
|
||||
DrawLine( m_scene, point, head, colors[i] );
|
||||
DrawLine( point, head, MakeColor( colors[i] ) );
|
||||
}
|
||||
else if ( m_castType == e_sphereCast )
|
||||
{
|
||||
DrawLine( m_scene, point, head, color1 );
|
||||
DrawSphere( m_scene, transform, sphere, colors[i] );
|
||||
DrawLine( point, head, MakeColor( color1 ) );
|
||||
DrawSolidSphere( transform, sphere, MakeColorAlpha( colors[i], 0.5f ) );
|
||||
}
|
||||
else if ( m_castType == e_capsuleCast )
|
||||
{
|
||||
DrawLine( m_scene, point, head, color1 );
|
||||
DrawCapsule( m_scene, transform, capsule, colors[i] );
|
||||
DrawLine( point, head, MakeColor( color1 ) );
|
||||
DrawSolidCapsule( transform, capsule, MakeColor( colors[i] ) );
|
||||
}
|
||||
else if ( m_castType == e_boxCast )
|
||||
{
|
||||
DrawLine( m_scene, point, head, color1 );
|
||||
DrawHull( m_scene, transform, &box.base, colors[i], false );
|
||||
DrawLine( point, head, MakeColor( color1 ) );
|
||||
DrawHull( transform, &box.base, MakeColor( colors[i] ) );
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
DrawLine( m_scene, m_origin, m_origin + m_translation, color2 );
|
||||
DrawLine( m_origin, m_origin + m_translation, MakeColor( color2 ) );
|
||||
|
||||
b3Transform transform = { m_translation, b3Quat_identity };
|
||||
|
||||
if ( m_castType == e_sphereCast )
|
||||
{
|
||||
DrawSphere( m_scene, transform, sphere, gray );
|
||||
DrawSolidSphere( transform, sphere, MakeColor( gray ) );
|
||||
}
|
||||
else if ( m_castType == e_capsuleCast )
|
||||
{
|
||||
DrawCapsule( m_scene, transform, capsule, gray );
|
||||
DrawSolidCapsule( transform, capsule, MakeColor( gray ) );
|
||||
}
|
||||
else if ( m_castType == e_boxCast )
|
||||
{
|
||||
DrawHull( m_scene, transform, &box.base, gray, false );
|
||||
DrawHull( transform, &box.base, MakeColor( gray ) );
|
||||
}
|
||||
}
|
||||
|
||||
DrawPoint( m_scene, m_origin, 2.0f, green );
|
||||
DrawPoint( m_origin, 10.0f, MakeColor( green ) );
|
||||
}
|
||||
|
||||
static constexpr int m_maxCount = 64;
|
||||
|
|
@ -777,7 +778,7 @@ public:
|
|||
CastContext m_castContext;
|
||||
};
|
||||
|
||||
static int sampleCastWorld = SampleManager::Register( "Collision", "Cast World", CastWorld::Create );
|
||||
static int sampleCastWorld = RegisterSample( "Collision", "Cast World", CastWorld::Create );
|
||||
|
||||
class MeshScale : public Sample
|
||||
{
|
||||
|
|
@ -812,14 +813,13 @@ public:
|
|||
b3DestroyMesh( m_mesh );
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool HasSolverControls() const override
|
||||
{
|
||||
float height = 200.0f;
|
||||
ImGui::SetNextWindowPos( ImVec2( 10.0f, m_camera->m_height - height - 50.0f ), ImGuiCond_Once );
|
||||
ImGui::SetNextWindowSize( ImVec2( 200.0f, height ) );
|
||||
|
||||
ImGui::Begin( "Mesh Scale", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize );
|
||||
return false;
|
||||
}
|
||||
|
||||
bool DrawControls() override
|
||||
{
|
||||
b3Vec3 scale = m_scale;
|
||||
bool changed = false;
|
||||
changed = changed || ImGui::SliderFloat( "Scale X", &scale.x, -2.0f, 2.0f, "%.1f" );
|
||||
|
|
@ -837,7 +837,7 @@ public:
|
|||
|
||||
ImGui::Checkbox( "sphere Cast", &m_sphereCast );
|
||||
|
||||
ImGui::End();
|
||||
return true;
|
||||
}
|
||||
|
||||
void Step() override
|
||||
|
|
@ -845,9 +845,9 @@ public:
|
|||
b3Vec3 rayOrigin = m_start;
|
||||
b3Vec3 rayTranslation = { 4.0f, 0.0f, 0.0f };
|
||||
|
||||
DrawPoint( m_scene, rayOrigin, 8.0f, b3_colorGreen );
|
||||
DrawPoint( m_scene, rayOrigin + rayTranslation, 8.0f, b3_colorRed );
|
||||
DrawLine( m_scene, rayOrigin, rayOrigin + rayTranslation, b3_colorWhite );
|
||||
DrawPoint( rayOrigin, 8.0f, MakeColor( b3_colorGreen ) );
|
||||
DrawPoint( rayOrigin + rayTranslation, 8.0f, MakeColor( b3_colorRed ) );
|
||||
DrawLine( rayOrigin, rayOrigin + rayTranslation, MakeColor( b3_colorWhite ) );
|
||||
|
||||
if ( m_sphereCast )
|
||||
{
|
||||
|
|
@ -860,16 +860,16 @@ public:
|
|||
if ( context.count > 0 )
|
||||
{
|
||||
b3Transform transform = { context.fractions[0] * rayTranslation, b3Quat_identity };
|
||||
DrawSphere( m_scene, transform, sphere, b3_colorYellow );
|
||||
DrawSolidSphere( transform, sphere, MakeColor( b3_colorYellow ) );
|
||||
|
||||
b3Vec3 point = context.points[0];
|
||||
DrawLine( m_scene, point, point + 0.5f * context.normals[0], b3_colorGreen );
|
||||
DrawPoint( m_scene, point, 5.0f, b3_colorYellow );
|
||||
DrawLine( point, point + 0.5f * context.normals[0], MakeColor( b3_colorGreen ) );
|
||||
DrawPoint( point, 5.0f, MakeColor( b3_colorYellow ) );
|
||||
}
|
||||
else
|
||||
{
|
||||
b3Transform transform = { rayTranslation, b3Quat_identity };
|
||||
DrawSphere( m_scene, transform, sphere, b3_colorGray );
|
||||
DrawSolidSphere( transform, sphere, MakeColor( b3_colorGray ) );
|
||||
}
|
||||
}
|
||||
else
|
||||
|
|
@ -878,8 +878,8 @@ public:
|
|||
if ( result.hit )
|
||||
{
|
||||
b3Vec3 point = result.point;
|
||||
DrawLine( m_scene, point, point + 0.5f * result.normal, b3_colorGreen );
|
||||
DrawPoint( m_scene, point, 5.0f, b3_colorYellow );
|
||||
DrawLine( point, point + 0.5f * result.normal, MakeColor( b3_colorGreen ) );
|
||||
DrawPoint( point, 5.0f, MakeColor( b3_colorYellow ) );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -892,7 +892,7 @@ public:
|
|||
bool m_sphereCast;
|
||||
};
|
||||
|
||||
static int sampleMeshScale = SampleManager::Register( "Collision", "Mesh Scale", MeshScale::Create );
|
||||
static int sampleMeshScale = RegisterSample( "Collision", "Mesh Scale", MeshScale::Create );
|
||||
|
||||
class ShapeCast : public Sample
|
||||
{
|
||||
|
|
@ -964,7 +964,7 @@ public:
|
|||
|
||||
b3World_CastShape( m_worldId, &proxy, translation, b3DefaultQueryFilter(), RayCastClosestCallback, &context );
|
||||
|
||||
DrawSphere( m_scene, b3Transform_identity, sphere, b3_colorGreen );
|
||||
DrawSolidSphere( b3Transform_identity, sphere, MakeColor( b3_colorGreen ) );
|
||||
|
||||
if ( context.count > 0 )
|
||||
{
|
||||
|
|
@ -973,14 +973,14 @@ public:
|
|||
float fraction = context.fractions[0];
|
||||
|
||||
// final position with overlap resolution
|
||||
DrawSphere( m_scene, { fraction * translation, b3Quat_identity }, sphere, b3_colorRed );
|
||||
DrawSolidSphere( { fraction * translation, b3Quat_identity }, sphere, MakeColor( b3_colorRed ) );
|
||||
|
||||
DrawPoint( m_scene, point, 2.0f, b3_colorRed );
|
||||
DrawLine( m_scene, point, point + 0.2f * normal, b3_colorYellow );
|
||||
DrawPoint( point, 2.0f, MakeColor( b3_colorRed ) );
|
||||
DrawLine( point, point + 0.2f * normal, MakeColor( b3_colorYellow ) );
|
||||
}
|
||||
else
|
||||
{
|
||||
DrawSphere( m_scene, { translation, b3Quat_identity }, sphere, b3_colorGray );
|
||||
DrawSolidSphere( { translation, b3Quat_identity }, sphere, MakeColor( b3_colorGray ) );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1001,7 +1001,7 @@ public:
|
|||
|
||||
b3World_CastShape( m_worldId, &proxy, translation, b3DefaultQueryFilter(), RayCastClosestCallback, &context );
|
||||
|
||||
DrawCapsule( m_scene, b3Transform_identity, capsule, b3_colorGreen );
|
||||
DrawSolidCapsule( b3Transform_identity, capsule, MakeColor( b3_colorGreen ) );
|
||||
|
||||
if ( context.count > 0 )
|
||||
{
|
||||
|
|
@ -1009,14 +1009,14 @@ public:
|
|||
b3Vec3 normal = context.normals[0];
|
||||
float fraction = context.fractions[0];
|
||||
|
||||
DrawCapsule( m_scene, { fraction * translation, b3Quat_identity }, capsule, b3_colorRed );
|
||||
DrawSolidCapsule( { fraction * translation, b3Quat_identity }, capsule, MakeColor( b3_colorRed ) );
|
||||
|
||||
DrawPoint( m_scene, point, 2.0f, b3_colorRed );
|
||||
DrawLine( m_scene, point, point + 0.2f * normal, b3_colorYellow );
|
||||
DrawPoint( point, 2.0f, MakeColor( b3_colorRed ) );
|
||||
DrawLine( point, point + 0.2f * normal, MakeColor( b3_colorYellow ) );
|
||||
}
|
||||
else
|
||||
{
|
||||
DrawCapsule( m_scene, { translation, b3Quat_identity }, capsule, b3_colorGray );
|
||||
DrawSolidCapsule( { translation, b3Quat_identity }, capsule, MakeColor( b3_colorGray ) );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1044,7 +1044,7 @@ public:
|
|||
|
||||
b3World_CastShape( m_worldId, &proxy, translation, b3DefaultQueryFilter(), RayCastClosestCallback, &context );
|
||||
|
||||
DrawHull( m_scene, b3Transform_identity, &box.base, b3_colorGreen, false );
|
||||
DrawHull( b3Transform_identity, &box.base, MakeColor( b3_colorGreen ) );
|
||||
|
||||
if ( context.count > 0 )
|
||||
{
|
||||
|
|
@ -1053,26 +1053,27 @@ public:
|
|||
float fraction = context.fractions[0];
|
||||
|
||||
// final position with overlap resolution
|
||||
DrawHull( m_scene, { fraction * translation, b3Quat_identity }, &box.base, b3_colorRed, false );
|
||||
DrawHull( { fraction * translation, b3Quat_identity }, &box.base, MakeColor( b3_colorRed ) );
|
||||
|
||||
DrawPoint( m_scene, point, 2.0f, b3_colorRed );
|
||||
DrawLine( m_scene, point, point + 0.2f * normal, b3_colorYellow );
|
||||
DrawPoint( point, 2.0f, MakeColor( b3_colorRed ) );
|
||||
DrawLine( point, point + 0.2f * normal, MakeColor( b3_colorYellow ) );
|
||||
}
|
||||
else
|
||||
{
|
||||
DrawHull( m_scene, { translation, b3Quat_identity }, &box.base, b3_colorGray, false );
|
||||
DrawHull( { translation, b3Quat_identity }, &box.base, MakeColor( b3_colorGray ) );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool HasSolverControls() const override
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
bool DrawControls() override
|
||||
{
|
||||
float height = 80.0f;
|
||||
ImGui::SetNextWindowPos( ImVec2( 10.0f, m_camera->m_height - height - 50.0f ), ImGuiCond_Once );
|
||||
ImGui::SetNextWindowSize( ImVec2( 210.0f, height ) );
|
||||
ImGui::Begin( "Shape Cast", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize );
|
||||
ImGui::Checkbox( "Initial Overlap", &m_initialOverlap );
|
||||
ImGui::End();
|
||||
return true;
|
||||
}
|
||||
|
||||
void Render() override
|
||||
|
|
@ -1081,20 +1082,20 @@ public:
|
|||
|
||||
DrawTextLine( "Shift + LMB and drag to shift start position" );
|
||||
|
||||
DrawGrid( m_scene, 10 );
|
||||
DrawTransform( m_scene, b3Transform_identity, 1.0f );
|
||||
DrawGroundGrid( 10 );
|
||||
DrawAxes( b3Transform_identity, 1.0f );
|
||||
}
|
||||
|
||||
void MouseDown( b3Vec2 p, int button, int modifiers ) override
|
||||
{
|
||||
if ( button == 0 )
|
||||
{
|
||||
if ( modifiers == GLFW_MOD_SHIFT )
|
||||
if ( modifiers == MOD_SHIFT )
|
||||
{
|
||||
m_trackingX = true;
|
||||
m_baseX = p.x;
|
||||
}
|
||||
else if ( modifiers == GLFW_MOD_CONTROL )
|
||||
else if ( modifiers == MOD_CTRL )
|
||||
{
|
||||
m_trackingY = true;
|
||||
m_baseY = p.y;
|
||||
|
|
@ -1145,7 +1146,7 @@ public:
|
|||
bool m_initialOverlap;
|
||||
};
|
||||
|
||||
static int sampleShapeCast = SampleManager::Register( "Collision", "Shape Cast", ShapeCast::Create );
|
||||
static int sampleShapeCast = RegisterSample( "Collision", "Shape Cast", ShapeCast::Create );
|
||||
|
||||
// Tests shape overlap versus world
|
||||
class OverlapWorld : public Sample
|
||||
|
|
@ -1246,7 +1247,7 @@ public:
|
|||
b3ShapeProxy proxy = { &sphere.center, 1, sphere.radius };
|
||||
b3HexColor color = b3_colorGreen;
|
||||
b3World_OverlapShape( m_worldId, &proxy, b3DefaultQueryFilter(), OverlapResultFcn, &color );
|
||||
DrawSphere( m_scene, b3Transform_identity, sphere, color );
|
||||
DrawSolidSphere( b3Transform_identity, sphere, MakeColor( color ) );
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1262,7 +1263,7 @@ public:
|
|||
b3ShapeProxy proxy = { &capsule.center1, 2, capsule.radius };
|
||||
b3HexColor color = b3_colorGreen;
|
||||
b3World_OverlapShape( m_worldId, &proxy, b3DefaultQueryFilter(), OverlapResultFcn, &color );
|
||||
DrawCapsule( m_scene, b3Transform_identity, capsule, color );
|
||||
DrawSolidCapsule( b3Transform_identity, capsule, MakeColor( color ) );
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1275,7 +1276,7 @@ public:
|
|||
b3ShapeProxy proxy = { box.boxPoints, box.base.vertexCount, 0.0f };
|
||||
b3HexColor color = b3_colorGreen;
|
||||
b3World_OverlapShape( m_worldId, &proxy, b3DefaultQueryFilter(), OverlapResultFcn, &color );
|
||||
DrawHull( m_scene, b3Transform_identity, &box.base, color, false );
|
||||
DrawHull( b3Transform_identity, &box.base, MakeColor( color ) );
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1285,17 +1286,17 @@ public:
|
|||
|
||||
DrawTextLine( "Shift + LMB and drag to move shapes" );
|
||||
|
||||
DrawGrid( m_scene, 10 );
|
||||
DrawLine( m_scene, b3Vec3_zero, 0.4f * b3Vec3_axisX, b3_colorRed );
|
||||
DrawLine( m_scene, b3Vec3_zero, 0.4f * b3Vec3_axisY, b3_colorGreen );
|
||||
DrawLine( m_scene, b3Vec3_zero, 0.4f * b3Vec3_axisZ, b3_colorBlue );
|
||||
DrawGroundGrid( 10 );
|
||||
DrawLine( b3Vec3_zero, 0.4f * b3Vec3_axisX, MakeColor( b3_colorRed ) );
|
||||
DrawLine( b3Vec3_zero, 0.4f * b3Vec3_axisY, MakeColor( b3_colorGreen ) );
|
||||
DrawLine( b3Vec3_zero, 0.4f * b3Vec3_axisZ, MakeColor( b3_colorBlue ) );
|
||||
}
|
||||
|
||||
void MouseDown( b3Vec2 p, int button, int modifiers ) override
|
||||
{
|
||||
if ( button == 0 )
|
||||
{
|
||||
if ( modifiers == GLFW_MOD_SHIFT )
|
||||
if ( modifiers == MOD_SHIFT )
|
||||
{
|
||||
m_tracking = true;
|
||||
m_baseX = p.x;
|
||||
|
|
@ -1334,7 +1335,7 @@ public:
|
|||
bool m_tracking;
|
||||
};
|
||||
|
||||
static int sampleOverlapWorld = SampleManager::Register( "Collision", "Overlap World", OverlapWorld::Create );
|
||||
static int sampleOverlapWorld = RegisterSample( "Collision", "Overlap World", OverlapWorld::Create );
|
||||
|
||||
class InitialOverlap : public Sample
|
||||
{
|
||||
|
|
@ -1381,17 +1382,18 @@ public:
|
|||
{
|
||||
Sample::Render();
|
||||
|
||||
DrawTransform( m_scene, b3Transform_identity, 1.0f );
|
||||
DrawAxes( b3Transform_identity, 1.0f );
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool HasSolverControls() const override
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
bool DrawControls() override
|
||||
{
|
||||
float height = 80.0f;
|
||||
ImGui::SetNextWindowPos( ImVec2( 10.0f, m_camera->m_height - height - 50.0f ), ImGuiCond_Once );
|
||||
ImGui::SetNextWindowSize( ImVec2( 200.0f, height ) );
|
||||
ImGui::Begin( "Initial Overlap", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize );
|
||||
ImGui::Checkbox( "initial overlap", &m_initialOverlap );
|
||||
ImGui::End();
|
||||
return true;
|
||||
}
|
||||
|
||||
void Step() override
|
||||
|
|
@ -1414,20 +1416,20 @@ public:
|
|||
|
||||
b3ShapeProxy proxy = { &capsule.center1, 2, capsule.radius };
|
||||
|
||||
DrawCapsule( m_scene, b3Transform_identity, capsule, b3_colorGreen );
|
||||
DrawSolidCapsule( b3Transform_identity, capsule, MakeColor( b3_colorGreen ) );
|
||||
|
||||
b3World_CastShape( m_worldId, &proxy, translation, b3DefaultQueryFilter(), RayCastClosestCallback, &context );
|
||||
|
||||
float fraction = context.count > 0 ? context.fractions[0] : 1.0f;
|
||||
b3Transform shapeEnd = { fraction * translation, b3Quat_identity };
|
||||
DrawCapsule( m_scene, shapeEnd, capsule, context.count > 0 ? b3_colorRed : b3_colorGreen );
|
||||
DrawSolidCapsule( shapeEnd, capsule, MakeColor( context.count > 0 ? b3_colorRed : b3_colorGreen ) );
|
||||
|
||||
if ( context.count > 0 )
|
||||
{
|
||||
b3Vec3 p = context.points[0];
|
||||
b3Vec3 n = context.normals[0];
|
||||
DrawLine( m_scene, p, p + 0.5f * n, b3_colorAliceBlue );
|
||||
DrawPoint( m_scene, p, 8.0f, b3_colorAliceBlue );
|
||||
DrawLine( p, p + 0.5f * n, MakeColor( b3_colorAliceBlue ) );
|
||||
DrawPoint( p, 8.0f, MakeColor( b3_colorAliceBlue ) );
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1440,7 +1442,7 @@ public:
|
|||
bool m_initialOverlap;
|
||||
};
|
||||
|
||||
static int sampleInitialOverlap = SampleManager::Register( "Collision", "Initial Overlap", InitialOverlap::Create );
|
||||
static int sampleInitialOverlap = RegisterSample( "Collision", "Initial Overlap", InitialOverlap::Create );
|
||||
|
||||
// pointA[0] = {0.000000000, 0.000000000, 0.000000000}
|
||||
// pointA[1] = {0.000000000, -6400.000000000, 0.000000000}
|
||||
|
|
@ -1507,8 +1509,8 @@ public:
|
|||
{
|
||||
Sample::Render();
|
||||
|
||||
DrawGrid( m_scene, 10 );
|
||||
DrawTransform( m_scene, b3Transform_identity, 1.0f );
|
||||
DrawGroundGrid( 10 );
|
||||
DrawAxes( b3Transform_identity, 1.0f );
|
||||
|
||||
b3ShapeCastPairInput input;
|
||||
input.proxyA = { m_triangle, 3, 0.0f };
|
||||
|
|
@ -1522,21 +1524,21 @@ public:
|
|||
|
||||
b3CastOutput output = b3ShapeCast( &input );
|
||||
|
||||
DrawFace( m_scene, m_triangle[0], m_triangle[1], m_triangle[2], b3_colorCyan );
|
||||
DrawTriangle( m_triangle[0], m_triangle[1], m_triangle[2], MakeColor( b3_colorCyan ) );
|
||||
// DrawHull( m_scene, m_transform, m_box, b3_colorGreen, false );
|
||||
DrawCapsule( m_scene, m_transform, m_capsule, b3_colorGreen );
|
||||
DrawSolidCapsule( m_transform, m_capsule, MakeColor( b3_colorGreen ) );
|
||||
|
||||
if ( output.hit )
|
||||
{
|
||||
// final position with overlap resolution
|
||||
b3Vec3 shapeEnd = m_transform.p + output.fraction * m_translation;
|
||||
// DrawHull( m_scene, { shapeEnd, m_transform.q }, m_box, b3_colorRed, false );
|
||||
DrawCapsule( m_scene, { shapeEnd, m_transform.q }, m_capsule, b3_colorRed );
|
||||
DrawSolidCapsule( { shapeEnd, m_transform.q }, m_capsule, MakeColor( b3_colorRed ) );
|
||||
}
|
||||
|
||||
b3Vec3 shapeEnd = m_transform.p + m_translation;
|
||||
// DrawHull( m_scene, { shapeEnd, m_transform.q }, m_box, b3_colorGray, false );
|
||||
DrawCapsule( m_scene, { shapeEnd, m_transform.q }, m_capsule, b3_colorGray );
|
||||
DrawSolidCapsule( { shapeEnd, m_transform.q }, m_capsule, MakeColor( b3_colorGray ) );
|
||||
}
|
||||
|
||||
static Sample* Create( SampleContext* context )
|
||||
|
|
@ -1552,7 +1554,7 @@ public:
|
|||
b3Vec3 m_triangle[3];
|
||||
};
|
||||
|
||||
static int sampleShapeCastDebug = SampleManager::Register( "Collision", "Shape Cast Debug", ShapeCastDebug::Create );
|
||||
static int sampleShapeCastDebug = RegisterSample( "Collision", "Shape Cast Debug", ShapeCastDebug::Create );
|
||||
|
||||
class DistanceDebug : public Sample
|
||||
{
|
||||
|
|
@ -1616,21 +1618,20 @@ public:
|
|||
{
|
||||
Sample::Render();
|
||||
|
||||
DrawGrid( m_scene, 10 );
|
||||
DrawTransform( m_scene, b3Transform_identity, 1.0f );
|
||||
DrawGroundGrid( 10 );
|
||||
DrawAxes( b3Transform_identity, 1.0f );
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool HasSolverControls() const override
|
||||
{
|
||||
float height = 80.0f;
|
||||
ImGui::SetNextWindowPos( ImVec2( 10.0f, m_camera->m_height - height - 50.0f ), ImGuiCond_Once );
|
||||
ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) );
|
||||
|
||||
ImGui::Begin( "Distance Debug", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize );
|
||||
return false;
|
||||
}
|
||||
|
||||
bool DrawControls() override
|
||||
{
|
||||
ImGui::SliderInt( "simplex index", &m_simplexIndex, 0, m_simplexCount - 1 );
|
||||
|
||||
ImGui::End();
|
||||
return true;
|
||||
}
|
||||
|
||||
static void BuildWitnessPoints( const b3Simplex* simplex, b3Vec3& vertexA, b3Vec3& vertexB )
|
||||
|
|
@ -1712,18 +1713,18 @@ public:
|
|||
// DrawFace( m_scene, m_triangle[0], m_triangle[1], m_triangle[2], b3_colorCyan );
|
||||
// DrawHull( m_scene, m_transformB, m_box, b3_colorGreen, false );
|
||||
|
||||
DrawHull( m_scene, b3Transform_identity, &m_boxA.base, b3_colorGreen, false );
|
||||
DrawHull( m_scene, m_transformB, &m_boxB.base, b3_colorCyan, false );
|
||||
DrawHull( b3Transform_identity, &m_boxA.base, MakeColor( b3_colorGreen ) );
|
||||
DrawHull( m_transformB, &m_boxB.base, MakeColor( b3_colorCyan ) );
|
||||
|
||||
for ( int i = 0; i < m_boxB.base.vertexCount; ++i )
|
||||
{
|
||||
b3Vec3 p = b3TransformPoint( m_transformB, m_boxB.boxPoints[i] );
|
||||
DrawWorldString( m_camera, p, b3_colorAliceBlue, " %d", i );
|
||||
DrawWorldString( p, MakeColor( b3_colorAliceBlue ), " %d", i );
|
||||
}
|
||||
|
||||
DrawPoint( m_scene, output.pointA, 5.0f, b3_colorWhite );
|
||||
DrawPoint( m_scene, output.pointB, 5.0f, b3_colorWhite );
|
||||
DrawLine( m_scene, output.pointA, output.pointA + 1.0f * output.normal, b3_colorWhite );
|
||||
DrawPoint( output.pointA, 5.0f, MakeColor( b3_colorWhite ) );
|
||||
DrawPoint( output.pointB, 5.0f, MakeColor( b3_colorWhite ) );
|
||||
DrawLine( output.pointA, output.pointA + 1.0f * output.normal, MakeColor( b3_colorWhite ) );
|
||||
|
||||
b3Vec3 n = output.normal;
|
||||
DrawTextLine( "distance = %g, normal = %g, %g, %g", output.distance, n.x, n.y, n.z );
|
||||
|
|
@ -1737,15 +1738,15 @@ public:
|
|||
b3Vec3 v1, v2;
|
||||
BuildWitnessPoints( simplex, v1, v2 );
|
||||
|
||||
DrawPoint( m_scene, v1, 10.0f, b3_colorGreen );
|
||||
DrawPoint( m_scene, v2, 10.0f, b3_colorGreen );
|
||||
DrawPoint( v1, 10.0f, MakeColor( b3_colorGreen ) );
|
||||
DrawPoint( v2, 10.0f, MakeColor( b3_colorGreen ) );
|
||||
|
||||
for ( int i = 0; i < simplex->count; ++i )
|
||||
{
|
||||
v1 = simplex->vertices[i].wA;
|
||||
v2 = simplex->vertices[i].wB;
|
||||
DrawPoint( m_scene, v1, 5.0f, b3_colorRed );
|
||||
DrawPoint( m_scene, v2, 5.0f, b3_colorRed );
|
||||
DrawPoint( v1, 5.0f, MakeColor( b3_colorRed ) );
|
||||
DrawPoint( v2, 5.0f, MakeColor( b3_colorRed ) );
|
||||
}
|
||||
|
||||
b3Vec3 p = GetClosestPoint( simplex );
|
||||
|
|
@ -1805,7 +1806,7 @@ public:
|
|||
int m_simplexCount;
|
||||
};
|
||||
|
||||
static int sampleDistanceDebug = SampleManager::Register( "Collision", "Distance Debug", DistanceDebug::Create );
|
||||
static int sampleDistanceDebug = RegisterSample( "Collision", "Distance Debug", DistanceDebug::Create );
|
||||
|
||||
class ShapeDistance : public Sample
|
||||
{
|
||||
|
|
@ -1914,12 +1915,12 @@ public:
|
|||
.center = m_point,
|
||||
.radius = radius,
|
||||
};
|
||||
DrawSphere( m_scene, transform, sphere, color );
|
||||
DrawSolidSphere( transform, sphere, MakeColor( color ) );
|
||||
}
|
||||
else
|
||||
{
|
||||
b3Vec3 p = b3TransformPoint( transform, m_point );
|
||||
DrawPoint( m_scene, p, 5.0f, color );
|
||||
DrawPoint( p, 5.0f, MakeColor( color ) );
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
|
@ -1934,13 +1935,13 @@ public:
|
|||
.radius = radius,
|
||||
};
|
||||
|
||||
DrawCapsule( m_scene, transform, capsule, color );
|
||||
DrawSolidCapsule( transform, capsule, MakeColor( color ) );
|
||||
}
|
||||
else
|
||||
{
|
||||
b3Vec3 p1 = b3TransformPoint( transform, m_segment[0] );
|
||||
b3Vec3 p2 = b3TransformPoint( transform, m_segment[1] );
|
||||
DrawLine( m_scene, p1, p2, color );
|
||||
DrawLine( p1, p2, MakeColor( color ) );
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
|
@ -1950,14 +1951,14 @@ public:
|
|||
b3Vec3 p1 = b3TransformPoint( transform, m_triangle[0] );
|
||||
b3Vec3 p2 = b3TransformPoint( transform, m_triangle[1] );
|
||||
b3Vec3 p3 = b3TransformPoint( transform, m_triangle[2] );
|
||||
DrawLine( m_scene, p1, p2, color );
|
||||
DrawLine( m_scene, p2, p3, color );
|
||||
DrawLine( m_scene, p3, p1, color );
|
||||
DrawLine( p1, p2, MakeColor( color ) );
|
||||
DrawLine( p2, p3, MakeColor( color ) );
|
||||
DrawLine( p3, p1, MakeColor( color ) );
|
||||
}
|
||||
break;
|
||||
|
||||
case e_box:
|
||||
DrawHull( m_scene, transform, &m_box.base, color, false );
|
||||
DrawHull( transform, &m_box.base, MakeColor( color ) );
|
||||
break;
|
||||
|
||||
default:
|
||||
|
|
@ -1965,15 +1966,13 @@ public:
|
|||
}
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool HasSolverControls() const override
|
||||
{
|
||||
float fontSize = ImGui::GetFontSize();
|
||||
float height = 16.0f * fontSize;
|
||||
ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->m_height - height - 2.0f * fontSize ), ImGuiCond_Once );
|
||||
ImGui::SetNextWindowSize( ImVec2( 19.0f * fontSize, height ) );
|
||||
|
||||
ImGui::Begin( "Shape Distance", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize );
|
||||
return false;
|
||||
}
|
||||
|
||||
bool DrawControls() override
|
||||
{
|
||||
const char* shapeTypes[] = { "point", "segment", "triangle", "box" };
|
||||
int shapeType = int( m_typeA );
|
||||
if ( ImGui::Combo( "shape A", &shapeType, shapeTypes, IM_ARRAYSIZE( shapeTypes ) ) )
|
||||
|
|
@ -2017,12 +2016,12 @@ public:
|
|||
m_simplexIndex = b3ClampInt( m_simplexIndex, 0, m_simplexCount - 1 );
|
||||
}
|
||||
|
||||
ImGui::End();
|
||||
return true;
|
||||
}
|
||||
|
||||
void MouseDown( b3Vec2 ps, int button, int mods ) override
|
||||
{
|
||||
if ( button == GLFW_MOUSE_BUTTON_1 )
|
||||
if ( button == MOUSE_LEFT )
|
||||
{
|
||||
if ( mods == 0 && m_rotating == false )
|
||||
{
|
||||
|
|
@ -2038,7 +2037,7 @@ public:
|
|||
m_dragStart = b3MulSub( ray.origin, b3Dot( ray.origin, d ), d );
|
||||
m_basePosition = m_transform.p;
|
||||
}
|
||||
else if ( mods == GLFW_MOD_SHIFT && m_dragging == false )
|
||||
else if ( mods == MOD_SHIFT && m_dragging == false )
|
||||
{
|
||||
m_rotating = true;
|
||||
m_rotateStart = ps.x;
|
||||
|
|
@ -2049,7 +2048,7 @@ public:
|
|||
|
||||
void MouseUp( b3Vec2, int button ) override
|
||||
{
|
||||
if ( button == GLFW_MOUSE_BUTTON_1 )
|
||||
if ( button == MOUSE_LEFT )
|
||||
{
|
||||
m_dragging = false;
|
||||
m_rotating = false;
|
||||
|
|
@ -2121,7 +2120,7 @@ public:
|
|||
|
||||
void Render() override
|
||||
{
|
||||
DrawTransform( m_scene, b3Transform_identity, 0.5f );
|
||||
DrawAxes( b3Transform_identity, 0.5f );
|
||||
Sample::Render();
|
||||
}
|
||||
|
||||
|
|
@ -2169,9 +2168,9 @@ public:
|
|||
b3Vec3 pointA, pointB;
|
||||
ComputeWitnessPoints( &pointA, &pointB, simplex );
|
||||
|
||||
DrawLine( m_scene, pointA, pointB, b3_colorWhite );
|
||||
DrawPoint( m_scene, pointA, 10.0f, b3_colorLightGreen );
|
||||
DrawPoint( m_scene, pointB, 10.0f, b3_colorLightBlue );
|
||||
DrawLine( pointA, pointB, MakeColor( b3_colorWhite ) );
|
||||
DrawPoint( pointA, 10.0f, MakeColor( b3_colorLightGreen ) );
|
||||
DrawPoint( pointB, 10.0f, MakeColor( b3_colorLightBlue ) );
|
||||
}
|
||||
|
||||
b3HexColor colors[3] = { b3_colorRed, b3_colorGreen, b3_colorBlue };
|
||||
|
|
@ -2179,16 +2178,16 @@ public:
|
|||
for ( int i = 0; i < simplex->count; ++i )
|
||||
{
|
||||
b3SimplexVertex* vertex = vertices + i;
|
||||
DrawPoint( m_scene, vertex->wA, 10.0f, colors[i] );
|
||||
DrawPoint( m_scene, vertex->wB, 10.0f, colors[i] );
|
||||
DrawPoint( vertex->wA, 10.0f, MakeColor( colors[i] ) );
|
||||
DrawPoint( vertex->wB, 10.0f, MakeColor( colors[i] ) );
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
DrawLine( m_scene, output.pointA, output.pointB, b3_colorDimGray );
|
||||
DrawPoint( m_scene, output.pointA, 10.0f, b3_colorLightGreen );
|
||||
DrawPoint( m_scene, output.pointB, 10.0f, b3_colorLightBlue );
|
||||
DrawLine( m_scene, output.pointA, output.pointA + 0.5f * output.normal, b3_colorYellow );
|
||||
DrawLine( output.pointA, output.pointB, MakeColor( b3_colorDimGray ) );
|
||||
DrawPoint( output.pointA, 10.0f, MakeColor( b3_colorLightGreen ) );
|
||||
DrawPoint( output.pointB, 10.0f, MakeColor( b3_colorLightBlue ) );
|
||||
DrawLine( output.pointA, output.pointA + 0.5f * output.normal, MakeColor( b3_colorYellow ) );
|
||||
}
|
||||
|
||||
if ( m_showIndices )
|
||||
|
|
@ -2196,13 +2195,13 @@ public:
|
|||
for ( int i = 0; i < m_proxyA.count; ++i )
|
||||
{
|
||||
b3Vec3 p = m_proxyA.points[i];
|
||||
DrawWorldString( m_camera, p, b3_colorWhite, " %d", i );
|
||||
DrawWorldString( p, MakeColor( b3_colorWhite ), " %d", i );
|
||||
}
|
||||
|
||||
for ( int i = 0; i < m_proxyB.count; ++i )
|
||||
{
|
||||
b3Vec3 p = b3TransformPoint( m_transform, m_proxyB.points[i] );
|
||||
DrawWorldString( m_camera, p, b3_colorWhite, " %d", i );
|
||||
DrawWorldString( p, MakeColor( b3_colorWhite ), " %d", i );
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -2265,7 +2264,7 @@ public:
|
|||
bool m_drawSimplex;
|
||||
};
|
||||
|
||||
static int sampleShapeDistance = SampleManager::Register( "Collision", "Shape Distance", ShapeDistance::Create );
|
||||
static int sampleShapeDistance = RegisterSample( "Collision", "Shape Distance", ShapeDistance::Create );
|
||||
|
||||
class TimeOfImpact : public Sample
|
||||
{
|
||||
|
|
@ -2343,14 +2342,14 @@ public:
|
|||
{
|
||||
case e_capsule:
|
||||
{
|
||||
DrawCapsule( m_scene, transform, m_capsule, color );
|
||||
DrawSolidCapsule( transform, m_capsule, MakeColor( color ) );
|
||||
b3Vec3 center = b3Lerp( m_capsule.center1, m_capsule.center2, 0.5f );
|
||||
center = b3TransformPoint( transform, center );
|
||||
b3Transform xf = {
|
||||
.p = center,
|
||||
.q = transform.q,
|
||||
};
|
||||
DrawTransform( m_scene, xf, 0.025f );
|
||||
DrawAxes( xf, 0.025f );
|
||||
}
|
||||
break;
|
||||
|
||||
|
|
@ -2359,17 +2358,17 @@ public:
|
|||
b3Vec3 p1 = b3TransformPoint( transform, m_triangle[0] );
|
||||
b3Vec3 p2 = b3TransformPoint( transform, m_triangle[1] );
|
||||
b3Vec3 p3 = b3TransformPoint( transform, m_triangle[2] );
|
||||
DrawLine( m_scene, p1, p2, color );
|
||||
DrawLine( m_scene, p2, p3, color );
|
||||
DrawLine( m_scene, p3, p1, color );
|
||||
DrawWorldString( m_camera, p1, b3_colorWhite, "0" );
|
||||
DrawWorldString( m_camera, p2, b3_colorWhite, "1" );
|
||||
DrawWorldString( m_camera, p3, b3_colorWhite, "2" );
|
||||
DrawLine( p1, p2, MakeColor( color ) );
|
||||
DrawLine( p2, p3, MakeColor( color ) );
|
||||
DrawLine( p3, p1, MakeColor( color ) );
|
||||
DrawWorldString( p1, MakeColor( b3_colorWhite ), "0" );
|
||||
DrawWorldString( p2, MakeColor( b3_colorWhite ), "1" );
|
||||
DrawWorldString( p3, MakeColor( b3_colorWhite ), "2" );
|
||||
}
|
||||
break;
|
||||
|
||||
case e_box:
|
||||
DrawHull( m_scene, transform, &m_box.base, color, false );
|
||||
DrawHull( transform, &m_box.base, MakeColor( color ) );
|
||||
break;
|
||||
|
||||
default:
|
||||
|
|
@ -2377,15 +2376,13 @@ public:
|
|||
}
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool HasSolverControls() const override
|
||||
{
|
||||
float fontSize = ImGui::GetFontSize();
|
||||
float height = 16.0f * fontSize;
|
||||
ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->m_height - height - 2.0f * fontSize ), ImGuiCond_Once );
|
||||
ImGui::SetNextWindowSize( ImVec2( 19.0f * fontSize, height ) );
|
||||
|
||||
ImGui::Begin( "Time of Impact", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize );
|
||||
return false;
|
||||
}
|
||||
|
||||
bool DrawControls() override
|
||||
{
|
||||
const char* shapeTypes[] = { "point", "segment", "triangle", "box" };
|
||||
int shapeType = int( m_typeA );
|
||||
if ( ImGui::Combo( "shape A", &shapeType, shapeTypes, IM_ARRAYSIZE( shapeTypes ) ) )
|
||||
|
|
@ -2401,14 +2398,12 @@ public:
|
|||
m_proxyB = MakeProxy( m_typeB );
|
||||
}
|
||||
|
||||
ImGui::Separator();
|
||||
|
||||
ImGui::End();
|
||||
return true;
|
||||
}
|
||||
|
||||
void Render() override
|
||||
{
|
||||
DrawTransform( m_scene, b3Transform_identity, 0.5f );
|
||||
DrawAxes( b3Transform_identity, 0.5f );
|
||||
Sample::Render();
|
||||
}
|
||||
|
||||
|
|
@ -2445,8 +2440,8 @@ public:
|
|||
|
||||
if ( output.state == b3_toiStateHit || output.state == b3_toiStateFailed )
|
||||
{
|
||||
DrawLine( m_scene, output.point, output.point + 0.5f * output.normal, b3_colorDimGray );
|
||||
DrawPoint( m_scene, output.point, 10.0f, b3_colorLightGreen );
|
||||
DrawLine( output.point, output.point + 0.5f * output.normal, MakeColor( b3_colorDimGray ) );
|
||||
DrawPoint( output.point, 10.0f, MakeColor( b3_colorLightGreen ) );
|
||||
}
|
||||
|
||||
switch ( output.state )
|
||||
|
|
@ -2497,7 +2492,7 @@ public:
|
|||
b3Sweep m_sweepB;
|
||||
};
|
||||
|
||||
static int sampleTimeOfImpact = SampleManager::Register( "Collision", "Time of Impact", TimeOfImpact::Create );
|
||||
static int sampleTimeOfImpact = RegisterSample( "Collision", "Time of Impact", TimeOfImpact::Create );
|
||||
|
||||
class CapsuleCastRay : public Sample
|
||||
{
|
||||
|
|
@ -2542,10 +2537,10 @@ public:
|
|||
{
|
||||
Sample::Render();
|
||||
|
||||
DrawGrid( m_scene, 10 );
|
||||
DrawLine( m_scene, b3Vec3_zero, 0.4f * b3Vec3_axisX, b3_colorRed );
|
||||
DrawLine( m_scene, b3Vec3_zero, 0.4f * b3Vec3_axisY, b3_colorGreen );
|
||||
DrawLine( m_scene, b3Vec3_zero, 0.4f * b3Vec3_axisZ, b3_colorBlue );
|
||||
DrawGroundGrid( 10 );
|
||||
DrawLine( b3Vec3_zero, 0.4f * b3Vec3_axisX, MakeColor( b3_colorRed ) );
|
||||
DrawLine( b3Vec3_zero, 0.4f * b3Vec3_axisY, MakeColor( b3_colorGreen ) );
|
||||
DrawLine( b3Vec3_zero, 0.4f * b3Vec3_axisZ, MakeColor( b3_colorBlue ) );
|
||||
|
||||
b3BodyRayCastInput input;
|
||||
input.origin = { -1.0f, 0.5f, 0.0f };
|
||||
|
|
@ -2555,13 +2550,13 @@ public:
|
|||
|
||||
b3BodyCastResult result = b3Body_CastRay( m_bodyId, &input, b3Transform_identity );
|
||||
|
||||
DrawLine( m_scene, input.origin, input.origin + input.translation, b3_colorGray );
|
||||
DrawPoint( m_scene, input.origin, 4.0f, b3_colorGreen );
|
||||
DrawPoint( m_scene, input.origin + input.translation, 4.0f, b3_colorRed );
|
||||
DrawLine( input.origin, input.origin + input.translation, MakeColor( b3_colorGray ) );
|
||||
DrawPoint( input.origin, 4.0f, MakeColor( b3_colorGreen ) );
|
||||
DrawPoint( input.origin + input.translation, 4.0f, MakeColor( b3_colorRed ) );
|
||||
|
||||
if ( result.hit )
|
||||
{
|
||||
DrawPoint( m_scene, result.point, 4.0f, b3_colorOrange );
|
||||
DrawPoint( result.point, 4.0f, MakeColor( b3_colorOrange ) );
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -2570,4 +2565,4 @@ public:
|
|||
float m_scale;
|
||||
};
|
||||
|
||||
static int sampleCapsuleCastRay = SampleManager::Register( "Collision", "Capsule Cast Ray", CapsuleCastRay::Create );
|
||||
static int sampleCapsuleCastRay = RegisterSample( "Collision", "Capsule Cast Ray", CapsuleCastRay::Create );
|
||||
|
|
|
|||
|
|
@ -1,12 +1,10 @@
|
|||
// 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 "gfx/draw.h"
|
||||
#include "utils.h"
|
||||
|
||||
#include "box3d/box3d.h"
|
||||
|
|
@ -91,7 +89,7 @@ public:
|
|||
{
|
||||
Sample::Render();
|
||||
b3Transform transform = { { 0.0f, 0.01f, 0.0f }, b3Quat_identity };
|
||||
DrawTransform( m_scene, transform, 1.0f );
|
||||
DrawAxes( transform, 1.0f );
|
||||
|
||||
int height = b3DynamicTree_GetHeight( &m_compound->tree );
|
||||
DrawTextLine( "compound tree height = %d", height );
|
||||
|
|
@ -105,7 +103,7 @@ public:
|
|||
b3Compound* m_compound;
|
||||
};
|
||||
|
||||
static int sampleSimple = SampleManager::Register( "Compound", "Simple", SimpleCompound::Create );
|
||||
static int sampleSimple = RegisterSample( "Compound", "Simple", SimpleCompound::Create );
|
||||
|
||||
class CompoundSpheres : public Sample
|
||||
{
|
||||
|
|
@ -151,7 +149,7 @@ public:
|
|||
{
|
||||
Sample::Render();
|
||||
b3Transform transform = { { 0.0f, 0.01f, 0.0f }, b3Quat_identity };
|
||||
DrawTransform( m_scene, transform, 1.0f );
|
||||
DrawAxes( transform, 1.0f );
|
||||
|
||||
int height = b3DynamicTree_GetHeight( &m_compound->tree );
|
||||
DrawTextLine( "compound tree height = %d", height );
|
||||
|
|
@ -166,7 +164,7 @@ public:
|
|||
b3Compound* m_compound;
|
||||
};
|
||||
|
||||
static int sampleCompoundSpheres = SampleManager::Register( "Compound", "Spheres", CompoundSpheres::Create );
|
||||
static int sampleCompoundSpheres = RegisterSample( "Compound", "Spheres", CompoundSpheres::Create );
|
||||
|
||||
class CompoundHulls : public Sample
|
||||
{
|
||||
|
|
@ -225,7 +223,7 @@ public:
|
|||
{
|
||||
Sample::Render();
|
||||
b3Transform transform = { { 0.0f, 0.01f, 0.0f }, b3Quat_identity };
|
||||
DrawTransform( m_scene, transform, 1.0f );
|
||||
DrawAxes( transform, 1.0f );
|
||||
|
||||
int height = b3DynamicTree_GetHeight( &m_compound->tree );
|
||||
DrawTextLine( "compound tree height = %d", height );
|
||||
|
|
@ -240,7 +238,7 @@ public:
|
|||
b3Compound* m_compound;
|
||||
};
|
||||
|
||||
static int sampleCompoundHulls = SampleManager::Register( "Compound", "Hulls", CompoundHulls::Create );
|
||||
static int sampleCompoundHulls = RegisterSample( "Compound", "Hulls", CompoundHulls::Create );
|
||||
|
||||
class TileFloor : public Sample
|
||||
{
|
||||
|
|
@ -340,7 +338,7 @@ public:
|
|||
{
|
||||
Sample::Render();
|
||||
b3Transform transform = { { 0.0f, 0.01f, 0.0f }, b3Quat_identity };
|
||||
DrawTransform( m_scene, transform, 1.0f );
|
||||
DrawAxes( 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 );
|
||||
|
|
@ -358,7 +356,7 @@ public:
|
|||
b3Compound* m_compound;
|
||||
};
|
||||
|
||||
static int sampleTileFloor = SampleManager::Register( "Compound", "Tile Floor", TileFloor::Create );
|
||||
static int sampleTileFloor = RegisterSample( "Compound", "Tile Floor", TileFloor::Create );
|
||||
|
||||
class MeshTile : public Sample
|
||||
{
|
||||
|
|
@ -457,7 +455,7 @@ public:
|
|||
{
|
||||
Sample::Render();
|
||||
b3Transform transform = { { 0.0f, 0.01f, 0.0f }, b3Quat_identity };
|
||||
DrawTransform( m_scene, transform, 1.0f );
|
||||
DrawAxes( transform, 1.0f );
|
||||
|
||||
DrawTextLine( "compound instance count = %d, byte count = %d", m_compound->meshCount, m_compound->byteCount );
|
||||
|
||||
|
|
@ -474,7 +472,7 @@ public:
|
|||
b3Compound* m_compound;
|
||||
};
|
||||
|
||||
static int sampleCompoundMesh = SampleManager::Register( "Compound", "Mesh Tile", MeshTile::Create );
|
||||
static int sampleCompoundMesh = RegisterSample( "Compound", "Mesh Tile", MeshTile::Create );
|
||||
|
||||
static bool OverlapResultFcn( b3ShapeId shapeId, void* context )
|
||||
{
|
||||
|
|
@ -688,7 +686,7 @@ public:
|
|||
{
|
||||
Sample::Render();
|
||||
b3Transform transform = { { 0.0f, 0.01f, 0.0f }, b3Quat_identity };
|
||||
DrawTransform( m_scene, transform, 4.0f );
|
||||
DrawAxes( transform, 4.0f );
|
||||
|
||||
DrawTextLine( "surface type = %d", m_userMaterialId );
|
||||
DrawTextLine( "compound capsules/hulls/meshes/sphere = %d / %d / %d / %d", m_compound->capsuleCount,
|
||||
|
|
@ -712,13 +710,13 @@ public:
|
|||
CastClosestContext context = {};
|
||||
(void)b3World_CastRay( m_worldId, m_rayOrigin, translation, filter, CastClosestCallback, &context );
|
||||
|
||||
DrawLine( m_scene, m_rayOrigin, m_rayOrigin + translation, b3_colorAliceBlue );
|
||||
DrawLine( m_rayOrigin, m_rayOrigin + translation, MakeColor( 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 );
|
||||
DrawLine( p1, p2, MakeColor( b3_colorYellow ) );
|
||||
DrawPoint( p1, 8.0f, MakeColor( b3_colorLightCoral ) );
|
||||
DrawTextLine( "ray hit triangle/child/material = %d / %d / %d", context.triangleIndex, context.childIndex,
|
||||
context.materialId );
|
||||
}
|
||||
|
|
@ -734,16 +732,16 @@ public:
|
|||
b3ShapeProxy proxy = { &origin, 1, 0.25f };
|
||||
b3World_CastShape( m_worldId, &proxy, translation, filter, CastClosestCallback, &context );
|
||||
|
||||
DrawLine( m_scene, origin, origin + translation, b3_colorAliceBlue );
|
||||
DrawLine( origin, origin + translation, MakeColor( 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 );
|
||||
DrawLine( p1, p2, MakeColor( b3_colorYellow ) );
|
||||
DrawPoint( p1, 8.0f, MakeColor( b3_colorLightCoral ) );
|
||||
b3Sphere sphere = { position, 0.25f };
|
||||
DrawSphere( m_scene, b3Transform_identity, sphere, b3_colorOrchid );
|
||||
DrawSolidSphere( b3Transform_identity, sphere, MakeColor( b3_colorOrchid ) );
|
||||
DrawTextLine( "shape hit triangle/child/material = %d / %d / %d", context.triangleIndex, context.childIndex,
|
||||
context.materialId );
|
||||
}
|
||||
|
|
@ -761,7 +759,7 @@ public:
|
|||
|
||||
b3HexColor color = overlap ? b3_colorDarkMagenta : b3_colorDarkSeaGreen;
|
||||
b3Sphere sphere = { origin, 0.3f };
|
||||
DrawSphere( m_scene, b3Transform_identity, sphere, color );
|
||||
DrawSolidSphere( b3Transform_identity, sphere, MakeColor( color ) );
|
||||
}
|
||||
|
||||
if ( m_rayOrigin.x > 0.45f * m_worldWidth )
|
||||
|
|
@ -797,4 +795,4 @@ public:
|
|||
b3Vec3 m_rayOrigin;
|
||||
};
|
||||
|
||||
static int sampleVillage = SampleManager::Register( "Compound", "Village", Village::Create );
|
||||
static int sampleVillage = RegisterSample( "Compound", "Village", Village::Create );
|
||||
|
|
|
|||
|
|
@ -1,15 +1,14 @@
|
|||
// 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 "gfx/draw.h"
|
||||
#include "stability.h"
|
||||
#include "utils.h"
|
||||
|
||||
#include "gfx/debug_adapter.h"
|
||||
|
||||
#include "box3d/box3d.h"
|
||||
|
||||
#include <stdio.h>
|
||||
|
|
@ -26,14 +25,11 @@ public:
|
|||
m_camera->SetView( 45.0f, 30.0f, 30.0f, b3Vec3_zero );
|
||||
}
|
||||
|
||||
AddGroundBox( 40.0f );
|
||||
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
|
||||
bodyDef.position = { 0.0f, -1.0f, 0.0f };
|
||||
b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef );
|
||||
b3BoxHull groundBox = b3MakeBoxHull( 50.0f, 1.0f, 50.0f );
|
||||
b3CreateHullShape( groundId, &shapeDef, &groundBox.base );
|
||||
|
||||
bodyDef.position = { 0.0f, 10.0f, 0.0f };
|
||||
bodyDef.rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisX, 90.0f * B3_DEG_TO_RAD );
|
||||
b3BodyId wallId = b3CreateBody( m_worldId, &bodyDef );
|
||||
|
|
@ -74,7 +70,7 @@ public:
|
|||
}
|
||||
};
|
||||
|
||||
static int sampleThinWall = SampleManager::Register( "Continuous", "Thin Wall", ThinWall::Create );
|
||||
static int sampleThinWall = RegisterSample( "Continuous", "Thin Wall", ThinWall::Create );
|
||||
|
||||
class BounceHouse : public Sample
|
||||
{
|
||||
|
|
@ -87,14 +83,14 @@ public:
|
|||
m_camera->SetView( 45.0f, 45.0f, 50.0f, b3Vec3_zero );
|
||||
}
|
||||
|
||||
AddGroundBox( 10.0f );
|
||||
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
|
||||
bodyDef.position = { 0.0f, -1.0f, 0.0f };
|
||||
b3BodyId groundBodyId = b3CreateBody( m_worldId, &bodyDef );
|
||||
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
b3BoxHull groundBox = b3MakeBoxHull( 10.0f, 1.0f, 10.0f );
|
||||
b3CreateHullShape( groundBodyId, &shapeDef, &groundBox.base );
|
||||
|
||||
{
|
||||
b3Transform transform = { { 10.0f, 5.0f, 0.0f }, b3Quat_identity };
|
||||
|
|
@ -148,7 +144,7 @@ public:
|
|||
b3MeshData* m_dummyMesh;
|
||||
};
|
||||
|
||||
static int sampleBounceHouse = SampleManager::Register( "Continuous", "Bounce House", BounceHouse::Create );
|
||||
static int sampleBounceHouse = RegisterSample( "Continuous", "Bounce House", BounceHouse::Create );
|
||||
|
||||
class SpinningStick : public Sample
|
||||
{
|
||||
|
|
@ -158,20 +154,17 @@ public:
|
|||
{
|
||||
if ( context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 45.0f, 25.0f, 50.0f, { 0.0f, 2.0f, 0.0f } );
|
||||
m_camera->SetView( 45.0f, 25.0f, 20.0f, { 0.0f, 2.0f, 0.0f } );
|
||||
}
|
||||
|
||||
AddGroundBox( 10.0f );
|
||||
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
|
||||
bodyDef.position = { 0.0f, -0.1f, 0.0f };
|
||||
b3BodyId groundBodyId = b3CreateBody( m_worldId, &bodyDef );
|
||||
b3BoxHull groundBox = b3MakeBoxHull( 10.0f, 0.1f, 10.0f );
|
||||
b3CreateHullShape( groundBodyId, &shapeDef, &groundBox.base );
|
||||
|
||||
bodyDef.position = { 0.0f, 0.5f, 0.0f };
|
||||
b3BodyId wallBodyId = b3CreateBody( m_worldId, &bodyDef );
|
||||
|
||||
b3BoxHull wallBox = b3MakeBoxHull( 0.125f, 0.5f, 10.0f );
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
b3CreateHullShape( wallBodyId, &shapeDef, &wallBox.base );
|
||||
|
||||
bodyDef.type = b3_dynamicBody;
|
||||
|
|
@ -193,7 +186,7 @@ public:
|
|||
}
|
||||
};
|
||||
|
||||
static int sampleSpinningStick = SampleManager::Register( "Continuous", "Spinning Stick", SpinningStick::Create );
|
||||
static int sampleSpinningStick = RegisterSample( "Continuous", "Spinning Stick", SpinningStick::Create );
|
||||
|
||||
// This tests bullets and chain reactions
|
||||
class BulletVersusStack : public Sample
|
||||
|
|
@ -209,18 +202,17 @@ public:
|
|||
{
|
||||
if ( context->restart == false )
|
||||
{
|
||||
m_camera->SetView( -7.5f, 20.0f, 30.0f, { 0.0f, 2.0f, 0.0f } );
|
||||
m_camera->SetView( 15.0f, 20.0f, 30.0f, { 0.0f, 2.0f, 0.0f } );
|
||||
}
|
||||
|
||||
AddGroundBox( 50.0f );
|
||||
|
||||
{
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.position = { 0.0f, -1.0f, 0.0f };
|
||||
b3BodyId groundBodyId = b3CreateBody( m_worldId, &bodyDef );
|
||||
b3BoxHull groundBox = b3MakeBoxHull( 50.0f, 1.0f, 50.0f );
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
b3CreateHullShape( groundBodyId, &shapeDef, &groundBox.base );
|
||||
|
||||
b3Transform transform = { { 1.0f, 5.0f, 0.0f }, b3Quat_identity };
|
||||
b3Transform transform = { { -1.0f, 5.0f, 0.0f }, b3Quat_identity };
|
||||
b3BoxHull wallBox = b3MakeTransformedBoxHull( 0.1f, 5.0f, 10.0f, transform );
|
||||
b3CreateHullShape( groundBodyId, &shapeDef, &wallBox.base );
|
||||
}
|
||||
|
|
@ -239,12 +231,6 @@ public:
|
|||
m_bulletId = b3_nullBodyId;
|
||||
}
|
||||
|
||||
void Render() override
|
||||
{
|
||||
Sample::Render();
|
||||
DrawTransform( m_scene, { { 0.0f, 0.1f, 0.0f }, b3Quat_identity }, 1.0f );
|
||||
}
|
||||
|
||||
void Launch()
|
||||
{
|
||||
if ( B3_IS_NON_NULL( m_bulletId ) )
|
||||
|
|
@ -255,8 +241,8 @@ public:
|
|||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.type = b3_dynamicBody;
|
||||
bodyDef.isBullet = true;
|
||||
bodyDef.position = { -20.5f, 5.5f, 0.0f };
|
||||
bodyDef.linearVelocity = { 500.0f, 0.0f, 0.0f };
|
||||
bodyDef.position = { 20.5f, 5.5f, 0.0f };
|
||||
bodyDef.linearVelocity = { -500.0f, 0.0f, 0.0f };
|
||||
m_bulletId = b3CreateBody( m_worldId, &bodyDef );
|
||||
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
|
|
@ -273,15 +259,9 @@ public:
|
|||
}
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool DrawControls() override
|
||||
{
|
||||
float height = 80.0f;
|
||||
ImGui::SetNextWindowPos( ImVec2( 10.0f, m_camera->m_height - height - 50.0f ), ImGuiCond_Once );
|
||||
ImGui::SetNextWindowSize( ImVec2( 150.0f, height ) );
|
||||
|
||||
ImGui::Begin( "Bullet vs Stack", nullptr, ImGuiWindowFlags_NoResize );
|
||||
|
||||
ImGui::PushItemWidth( 200.0f );
|
||||
ImGui::PushItemWidth( 6.0f * ImGui::GetFontSize() );
|
||||
|
||||
if ( ImGui::Button( "Launch" ) )
|
||||
{
|
||||
|
|
@ -290,13 +270,13 @@ public:
|
|||
|
||||
ImGui::PopItemWidth();
|
||||
|
||||
ImGui::End();
|
||||
return true;
|
||||
}
|
||||
|
||||
b3BodyId m_bulletId;
|
||||
};
|
||||
|
||||
static int sampleContinuous6 = SampleManager::Register( "Continuous", "Bullet vs Stack", BulletVersusStack::Create );
|
||||
static int sampleContinuous6 = RegisterSample( "Continuous", "Bullet vs Stack", BulletVersusStack::Create );
|
||||
|
||||
class NeedleMesh : public Sample
|
||||
{
|
||||
|
|
@ -343,7 +323,7 @@ public:
|
|||
|
||||
void Render() override
|
||||
{
|
||||
DrawGrid( m_scene, 10 );
|
||||
DrawGroundGrid( 10 );
|
||||
Sample::Render();
|
||||
}
|
||||
|
||||
|
|
@ -407,7 +387,7 @@ public:
|
|||
b3Hull* mConvex;
|
||||
};
|
||||
|
||||
static int sampleNeedleMesh = SampleManager::Register( "Continuous", "Needle Mesh", NeedleMesh::Create );
|
||||
static int sampleNeedleMesh = RegisterSample( "Continuous", "Needle Mesh", NeedleMesh::Create );
|
||||
|
||||
struct IndexPair
|
||||
{
|
||||
|
|
@ -447,7 +427,7 @@ public:
|
|||
if ( context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 0.0f, 30.0f, 20.0f, b3Vec3_zero );
|
||||
m_context->debugDraw.forceScale = 0.1f;
|
||||
GetGuiDraw()->forceScale = 0.1f;
|
||||
}
|
||||
|
||||
m_groundId = b3_nullBodyId;
|
||||
|
|
@ -632,17 +612,8 @@ public:
|
|||
assert( bodyIndex == m_bodyCount );
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool DrawControls() override
|
||||
{
|
||||
Sample::UpdateUI();
|
||||
|
||||
float fontSize = ImGui::GetFontSize();
|
||||
float height = 9.0f * fontSize;
|
||||
ImGui::SetNextWindowPos( ImVec2( 0.5f * fontSize, m_camera->m_height - height - 2.0f * fontSize ), ImGuiCond_Once );
|
||||
ImGui::SetNextWindowSize( ImVec2( 19.0f * fontSize, height ) );
|
||||
|
||||
ImGui::Begin( "Mesh Drop", nullptr, ImGuiWindowFlags_NoResize );
|
||||
|
||||
const char* shapeTypes[] = { "box", "capsule", "cylinder", "sphere" };
|
||||
int shapeType = (int)m_shapeType;
|
||||
if ( ImGui::Combo( "Type", &shapeType, shapeTypes, IM_ARRAYSIZE( shapeTypes ) ) )
|
||||
|
|
@ -669,7 +640,7 @@ public:
|
|||
m_stepCount = 0;
|
||||
}
|
||||
|
||||
ImGui::End();
|
||||
return true;
|
||||
}
|
||||
|
||||
void Step() override
|
||||
|
|
@ -677,9 +648,7 @@ public:
|
|||
Sample::Step();
|
||||
|
||||
{
|
||||
double screenX, screenY;
|
||||
glfwGetCursorPos( m_window, &screenX, &screenY );
|
||||
PickRay pickRay = m_camera->BuildPickRay( (float)screenX, (float)screenY );
|
||||
PickRay pickRay = m_camera->BuildPickRay( m_context->mouseX, m_context->mouseY );
|
||||
|
||||
b3RayResult result = b3World_CastRayClosest( m_worldId, pickRay.origin, pickRay.translation, b3DefaultQueryFilter() );
|
||||
|
||||
|
|
@ -773,7 +742,7 @@ public:
|
|||
bool m_autoGenerate;
|
||||
};
|
||||
|
||||
static int sampleMeshDrop = SampleManager::Register( "Continuous", "Mesh Drop", MeshDrop::Create );
|
||||
static int sampleMeshDrop = RegisterSample( "Continuous", "Mesh Drop", MeshDrop::Create );
|
||||
|
||||
class MeshDropUnitTest : public Sample
|
||||
{
|
||||
|
|
@ -784,7 +753,7 @@ public:
|
|||
if ( context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 0.0f, 30.0f, 20.0f, b3Vec3_zero );
|
||||
m_context->debugDraw.forceScale = 0.1f;
|
||||
GetGuiDraw()->forceScale = 0.1f;
|
||||
}
|
||||
|
||||
m_data = CreateMeshDrop( m_worldId );
|
||||
|
|
@ -827,7 +796,7 @@ public:
|
|||
bool m_failed;
|
||||
};
|
||||
|
||||
static int sampleMeshDropUnitTest = SampleManager::Register( "Continuous", "Mesh Drop Unit Test", MeshDropUnitTest::Create );
|
||||
static int sampleMeshDropUnitTest = RegisterSample( "Continuous", "Mesh Drop Unit Test", MeshDropUnitTest::Create );
|
||||
|
||||
// This sample shows that clustering based on the manifold normal can lead to clipping and/or tunneling.
|
||||
class HumpMesh : public Sample
|
||||
|
|
@ -838,9 +807,11 @@ public:
|
|||
{
|
||||
if ( context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 45.0f, 25.0f, 4.0f, { 0.0f, 1.2f, 0.0f } );
|
||||
m_camera->SetView( 45.0f, 25.0f, 10.0f, { 0.0f, 1.2f, 0.0f } );
|
||||
}
|
||||
|
||||
AddGroundBox( 20.0f );
|
||||
|
||||
m_hump = CreateHump( 8.0f );
|
||||
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
|
|
@ -863,12 +834,6 @@ public:
|
|||
b3DestroyMesh( m_hump );
|
||||
}
|
||||
|
||||
void Render() override
|
||||
{
|
||||
DrawGrid( m_scene, 10 );
|
||||
Sample::Render();
|
||||
}
|
||||
|
||||
b3MeshData* CreateHump( float cellWidth ) const
|
||||
{
|
||||
// Vertices
|
||||
|
|
@ -944,7 +909,7 @@ public:
|
|||
b3MeshData* m_hump;
|
||||
};
|
||||
|
||||
static int sampleHumpMesh = SampleManager::Register( "Continuous", "Hump Mesh", HumpMesh::Create );
|
||||
static int sampleHumpMesh = RegisterSample( "Continuous", "Hump Mesh", HumpMesh::Create );
|
||||
|
||||
class IsFast : public Sample
|
||||
{
|
||||
|
|
@ -955,19 +920,10 @@ public:
|
|||
if ( context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 0.0f, 15.0f, 50.0f, { 0.0f, 15.0f, 0.0f } );
|
||||
EnableGrid( m_scene, true );
|
||||
|
||||
}
|
||||
|
||||
{
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.type = b3_staticBody;
|
||||
bodyDef.position = { 0.0f, -1.0f, 0.0f };
|
||||
b3BodyId groundBody = b3CreateBody( m_worldId, &bodyDef );
|
||||
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
b3BoxHull groundBox = b3MakeBoxHull( 40.0f, 1.0f, 40.0f );
|
||||
b3CreateHullShape( groundBody, &shapeDef, &groundBox.base );
|
||||
}
|
||||
AddGroundBox( 40.0f );
|
||||
|
||||
b3BoxHull box = b3MakeBoxHull( 0.5f, 10.0f, 0.5f );
|
||||
b3Capsule capsule = {{0.0f, -9.5f, 0.0f}, {0.0f, 9.5f, 0.0f}, 0.5f};
|
||||
|
|
@ -1038,4 +994,4 @@ public:
|
|||
}
|
||||
};
|
||||
|
||||
static int sampleIsFast = SampleManager::Register( "Continuous", "Is Fast", IsFast::Create );
|
||||
static int sampleIsFast = RegisterSample( "Continuous", "Is Fast", IsFast::Create );
|
||||
|
|
|
|||
|
|
@ -1,10 +1,10 @@
|
|||
// SPDX-FileCopyrightText: 2025 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "camera.h"
|
||||
#include "determinism.h"
|
||||
#include "sample.h"
|
||||
#include "scene.h"
|
||||
|
||||
#include "box3d/box3d.h"
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
|
|
@ -56,4 +56,4 @@ public:
|
|||
bool m_done;
|
||||
};
|
||||
|
||||
static int sampleFallingRagdolls = SampleManager::Register( "Determinism", "Falling Ragdolls", FallingRagdolls::Create );
|
||||
static int sampleFallingRagdolls = RegisterSample( "Determinism", "Falling Ragdolls", FallingRagdolls::Create );
|
||||
|
|
|
|||
|
|
@ -1,14 +1,13 @@
|
|||
// 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 "gfx/draw.h"
|
||||
#include "utils.h"
|
||||
|
||||
#include "gfx/keycodes.h"
|
||||
|
||||
#include "box3d/box3d.h"
|
||||
|
||||
#include <assert.h>
|
||||
|
|
@ -54,7 +53,7 @@ public:
|
|||
|
||||
void Render() override
|
||||
{
|
||||
DrawGrid( m_scene, 10 );
|
||||
DrawGroundGrid( 10 );
|
||||
Sample::Render();
|
||||
}
|
||||
|
||||
|
|
@ -79,7 +78,7 @@ public:
|
|||
b3ShapeId m_sensorShapeId;
|
||||
};
|
||||
|
||||
static int sampleSensorVisit = SampleManager::Register( "Events", "Sensor Visit", SensorVisit::Create );
|
||||
static int sampleSensorVisit = RegisterSample( "Events", "Sensor Visit", SensorVisit::Create );
|
||||
|
||||
class HitEvent : public Sample
|
||||
{
|
||||
|
|
@ -207,7 +206,7 @@ public:
|
|||
{
|
||||
Sample::Render();
|
||||
b3Transform transform = { { 0.0f, 0.1f, 0.0f }, b3Quat_identity };
|
||||
DrawTransform( m_scene, transform, 4.0f );
|
||||
DrawAxes( transform, 4.0f );
|
||||
|
||||
for ( int i = 0; i < m_eventCount; ++i )
|
||||
{
|
||||
|
|
@ -215,12 +214,12 @@ public:
|
|||
// 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 );
|
||||
DrawPoint( m_events[i].point, 10.0f, MakeColor( b3_colorYellow ) );
|
||||
|
||||
b3Vec3 p2 = p1 - m_events[i].approachSpeed * m_events[i].normal;
|
||||
DrawLine( m_scene, p1, p2, b3_colorYellow );
|
||||
DrawLine( p1, p2, MakeColor( b3_colorYellow ) );
|
||||
|
||||
DrawWorldString( m_camera, p1, b3_colorWhite, "%.1f, %d", m_events[i].approachSpeed, m_events[i].userMaterialIdA );
|
||||
DrawWorldString( p1, MakeColor( b3_colorWhite ), "%.1f, %d", m_events[i].approachSpeed, m_events[i].userMaterialIdA );
|
||||
}
|
||||
|
||||
DrawTextLine( "event count = %d", m_eventCount );
|
||||
|
|
@ -244,7 +243,7 @@ public:
|
|||
int m_eventCount;
|
||||
};
|
||||
|
||||
static int sampleHitEvent = SampleManager::Register( "Events", "Hit", HitEvent::Create );
|
||||
static int sampleHitEvent = RegisterSample( "Events", "Hit", HitEvent::Create );
|
||||
|
||||
class MoveEvent : public Sample
|
||||
{
|
||||
|
|
@ -255,19 +254,12 @@ public:
|
|||
if ( context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 0.0f, 30.0f, 40.0f, { 0.0f, 5.0f, 0.0f } );
|
||||
EnableGrid( m_scene, true );
|
||||
|
||||
}
|
||||
|
||||
AddGroundBox( 40.0f );
|
||||
|
||||
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;
|
||||
|
|
@ -276,6 +268,7 @@ public:
|
|||
|
||||
m_localPivot = b3Body_GetLocalPoint( m_bodyId, pivot );
|
||||
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
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 );
|
||||
|
|
@ -296,8 +289,6 @@ public:
|
|||
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 );
|
||||
|
|
@ -335,7 +326,7 @@ public:
|
|||
b3Vec3 m_localPivot;
|
||||
};
|
||||
|
||||
static int sampleMoveEvent = SampleManager::Register( "Events", "Move", MoveEvent::Create );
|
||||
static int sampleMoveEvent = RegisterSample( "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
|
||||
|
|
@ -352,16 +343,15 @@ public:
|
|||
if ( m_context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 0.0f, 30.0f, 40.0f, { 0.0f, 5.0f, 0.0f } );
|
||||
EnableGrid( m_scene, true );
|
||||
|
||||
}
|
||||
|
||||
AddGroundBox( 20.0f );
|
||||
|
||||
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 )
|
||||
|
|
@ -579,7 +569,7 @@ public:
|
|||
b3JointId m_jointIds[e_count];
|
||||
};
|
||||
|
||||
static int sampleJointEvent = SampleManager::Register( "Events", "Joint", JointEvent::Create );
|
||||
static int sampleJointEvent = RegisterSample( "Events", "Joint", JointEvent::Create );
|
||||
|
||||
class PersistentContact : public Sample
|
||||
{
|
||||
|
|
@ -657,9 +647,9 @@ public:
|
|||
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 );
|
||||
DrawLine( p1, p2, MakeColor( b3_colorCrimson ) );
|
||||
DrawPoint( p1, 6.0f, MakeColor( b3_colorCrimson ) );
|
||||
DrawWorldString( p1, MakeColor( b3_colorGray ), "%.2f", manifoldPoint->totalNormalImpulse );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -678,7 +668,7 @@ public:
|
|||
b3MeshData* m_meshData;
|
||||
};
|
||||
|
||||
static int samplePersistentContact = SampleManager::Register( "Events", "Persistent Contact", PersistentContact::Create );
|
||||
static int samplePersistentContact = RegisterSample( "Events", "Persistent Contact", PersistentContact::Create );
|
||||
|
||||
class SensorHits : public Sample
|
||||
{
|
||||
|
|
@ -690,9 +680,11 @@ public:
|
|||
if ( m_context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 0.0f, 30.0f, 40.0f, { 0.0f, 5.0f, 0.0f } );
|
||||
EnableGrid( m_scene, true );
|
||||
|
||||
}
|
||||
|
||||
AddGroundBox( 10.0f );
|
||||
|
||||
b3BodyId groundId;
|
||||
{
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
|
|
@ -701,9 +693,6 @@ public:
|
|||
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 );
|
||||
}
|
||||
|
|
@ -812,22 +801,16 @@ public:
|
|||
m_shapeId = b3CreateSphereShape( m_bodyId, &shapeDef, &sphere );
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool DrawControls() 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 )
|
||||
if ( ImGui::Button( "Launch" ) || IsKeyDown( KEY_B ) )
|
||||
{
|
||||
Launch();
|
||||
}
|
||||
|
||||
ImGui::End();
|
||||
return true;
|
||||
}
|
||||
|
||||
void CollectTransforms( b3ShapeId sensorShapeId )
|
||||
|
|
@ -871,7 +854,7 @@ public:
|
|||
|
||||
for ( int i = 0; i < m_transformCount; ++i )
|
||||
{
|
||||
DrawTransform( m_scene, m_transforms[i], 0.1f );
|
||||
DrawAxes( m_transforms[i], 0.1f );
|
||||
}
|
||||
|
||||
b3SensorEvents sensorEvents = b3World_GetSensorEvents( m_worldId );
|
||||
|
|
@ -915,4 +898,4 @@ public:
|
|||
int m_endCount;
|
||||
};
|
||||
|
||||
static int sampleSensorHits = SampleManager::Register( "Events", "Sensor Hits", SensorHits::Create );
|
||||
static int sampleSensorHits = RegisterSample( "Events", "Sensor Hits", SensorHits::Create );
|
||||
|
|
|
|||
|
|
@ -1,12 +1,12 @@
|
|||
// SPDX-FileCopyrightText: 2025 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "camera.h"
|
||||
#include "renderer.h"
|
||||
#include "sample.h"
|
||||
#include "scene.h"
|
||||
#include "gfx/draw.h"
|
||||
#include "utils.h"
|
||||
|
||||
#include "box3d/box3d.h"
|
||||
|
||||
#include <imgui.h>
|
||||
|
||||
class BoxHull : public Sample
|
||||
|
|
@ -69,14 +69,15 @@ public:
|
|||
m_box = b3MakeScaledBoxHull( h, transform, postScale );
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool HasSolverControls() const 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 );
|
||||
return false;
|
||||
}
|
||||
|
||||
ImGui::PushItemWidth( 320.0f );
|
||||
bool DrawControls() override
|
||||
{
|
||||
float fontSize = ImGui::GetFontSize();
|
||||
ImGui::PushItemWidth( 10.0f * fontSize );
|
||||
|
||||
if ( ImGui::SliderFloat3( "h", &m_halfWidths.x, 0.1f, 2.0f, "%.1f" ) )
|
||||
{
|
||||
|
|
@ -99,22 +100,22 @@ public:
|
|||
CreateHulls( m_halfWidths, m_transform, m_postScale );
|
||||
}
|
||||
|
||||
ImGui::PopItemWidth();
|
||||
|
||||
if ( ImGui::Button( "refresh" ) )
|
||||
if ( ImGui::Button( "Refresh" ) )
|
||||
{
|
||||
CreateHulls( m_halfWidths, m_transform, m_postScale );
|
||||
}
|
||||
|
||||
ImGui::End();
|
||||
ImGui::PopItemWidth();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void Render() override
|
||||
{
|
||||
DrawHull( m_scene, b3Transform_identity, m_hull, b3_colorYellow, true );
|
||||
DrawHull( m_scene, b3Transform_identity, &m_box.base, b3_colorCyan, true );
|
||||
DrawHull( b3Transform_identity, m_hull, MakeColor( b3_colorYellow ) );
|
||||
DrawHull( b3Transform_identity, &m_box.base, MakeColor( b3_colorCyan ) );
|
||||
|
||||
DrawTransform( m_scene, b3Transform_identity, 1.0f );
|
||||
DrawAxes( b3Transform_identity, 1.0f );
|
||||
|
||||
Sample::Render();
|
||||
}
|
||||
|
|
@ -132,7 +133,7 @@ public:
|
|||
b3Hull* m_hull;
|
||||
};
|
||||
|
||||
static int sampleBoxHull = SampleManager::Register( "Geometry", "Box Hull", BoxHull::Create );
|
||||
static int sampleBoxHull = RegisterSample( "Geometry", "Box Hull", BoxHull::Create );
|
||||
|
||||
class Hull : public Sample
|
||||
{
|
||||
|
|
@ -208,10 +209,10 @@ public:
|
|||
{
|
||||
if ( m_hull != nullptr )
|
||||
{
|
||||
DrawHull( m_scene, b3Transform_identity, m_hull, b3_colorYellow, true );
|
||||
DrawHull( b3Transform_identity, m_hull, MakeColor( b3_colorYellow ) );
|
||||
}
|
||||
|
||||
DrawTransform( m_scene, b3Transform_identity, 1.0f );
|
||||
DrawAxes( b3Transform_identity, 1.0f );
|
||||
|
||||
Sample::Render();
|
||||
}
|
||||
|
|
@ -227,7 +228,7 @@ public:
|
|||
int m_count;
|
||||
};
|
||||
|
||||
static int sampleHull = SampleManager::Register( "Geometry", "Hull", Hull::Create );
|
||||
static int sampleHull = RegisterSample( "Geometry", "Hull", Hull::Create );
|
||||
|
||||
class HullReduction : public Sample
|
||||
{
|
||||
|
|
@ -301,15 +302,13 @@ public:
|
|||
}
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool HasSolverControls() const 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 );
|
||||
return false;
|
||||
}
|
||||
|
||||
bool DrawControls() override
|
||||
{
|
||||
if ( ImGui::RadioButton( "Box", m_type == e_box ) )
|
||||
{
|
||||
m_type = e_box;
|
||||
|
|
@ -329,19 +328,19 @@ public:
|
|||
GenerateHull();
|
||||
}
|
||||
|
||||
ImGui::End();
|
||||
return true;
|
||||
}
|
||||
|
||||
void Render() override
|
||||
{
|
||||
if ( m_hull != nullptr )
|
||||
{
|
||||
DrawHull( m_scene, b3Transform_identity, m_hull, b3_colorYellow, true );
|
||||
DrawHull( b3Transform_identity, m_hull, MakeColor( b3_colorYellow ) );
|
||||
|
||||
DrawTextLine( "v/f/e = %d/%d/%d", m_hull->vertexCount, m_hull->faceCount, m_hull->edgeCount / 2 );
|
||||
}
|
||||
|
||||
DrawTransform( m_scene, b3Transform_identity, 1.0f );
|
||||
DrawAxes( b3Transform_identity, 1.0f );
|
||||
|
||||
Sample::Render();
|
||||
}
|
||||
|
|
@ -358,7 +357,7 @@ public:
|
|||
int m_count;
|
||||
};
|
||||
|
||||
static int sampleHullReduction = SampleManager::Register( "Geometry", "Hull Reduction", HullReduction::Create );
|
||||
static int sampleHullReduction = RegisterSample( "Geometry", "Hull Reduction", HullReduction::Create );
|
||||
|
||||
class HullScale : public Sample
|
||||
{
|
||||
|
|
@ -407,9 +406,9 @@ public:
|
|||
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 );
|
||||
DrawHull( transform1, m_original, MakeColor( b3_colorGreen ) );
|
||||
DrawHull( transform2, m_hull, MakeColor( b3_colorYellow ) );
|
||||
DrawAxes( b3Transform_identity, 1.0f );
|
||||
|
||||
DrawTextLine( "hull 1: area = %g, volume = %g, radius = %g", m_original->surfaceArea, m_original->volume,
|
||||
m_original->innerRadius );
|
||||
|
|
@ -418,15 +417,13 @@ public:
|
|||
Sample::Render();
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool HasSolverControls() const 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 );
|
||||
return false;
|
||||
}
|
||||
|
||||
bool DrawControls() override
|
||||
{
|
||||
if ( ImGui::SliderFloat( "sx", &m_scale.x, -2.0f, 2.0f, "%.1f" ) )
|
||||
{
|
||||
UpdateHull();
|
||||
|
|
@ -472,7 +469,7 @@ public:
|
|||
UpdateHull();
|
||||
}
|
||||
|
||||
ImGui::End();
|
||||
return true;
|
||||
}
|
||||
|
||||
static Sample* Create( SampleContext* sampleContext )
|
||||
|
|
@ -488,7 +485,7 @@ public:
|
|||
b3Vec3 m_offset;
|
||||
};
|
||||
|
||||
static int sampleHullScale = SampleManager::Register( "Geometry", "Hull Scale", HullScale::Create );
|
||||
static int sampleHullScale = RegisterSample( "Geometry", "Hull Scale", HullScale::Create );
|
||||
|
||||
class CapsuleMass : public Sample
|
||||
{
|
||||
|
|
@ -582,15 +579,15 @@ public:
|
|||
|
||||
void Render() override
|
||||
{
|
||||
DrawCapsule( m_scene, b3Transform_identity, m_capsule, b3_colorAqua );
|
||||
DrawHull( m_scene, b3Transform_identity, &m_box.base, b3_colorBlueViolet, true );
|
||||
DrawSolidCapsule( b3Transform_identity, m_capsule, MakeColorAlpha( b3_colorAqua, 0.8f ) );
|
||||
DrawHull( b3Transform_identity, &m_box.base, MakeColor( b3_colorBlueViolet ) );
|
||||
|
||||
if ( m_hull != nullptr )
|
||||
{
|
||||
DrawHull( m_scene, b3Transform_identity, m_hull, b3_colorYellow, true );
|
||||
DrawHull( b3Transform_identity, m_hull, MakeColor( b3_colorYellow ) );
|
||||
}
|
||||
|
||||
DrawTransform( m_scene, b3Transform_identity, 1.0f );
|
||||
DrawAxes( b3Transform_identity, 1.0f );
|
||||
|
||||
if ( m_hull != nullptr )
|
||||
{
|
||||
|
|
@ -618,19 +615,19 @@ public:
|
|||
Sample::Render();
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool HasSolverControls() const 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 );
|
||||
return false;
|
||||
}
|
||||
|
||||
bool DrawControls() override
|
||||
{
|
||||
if ( ImGui::SliderInt( "sides", &m_sides, 3, m_maxSides ) )
|
||||
{
|
||||
CreateCapsuleHull( m_sides );
|
||||
}
|
||||
|
||||
ImGui::End();
|
||||
return true;
|
||||
}
|
||||
|
||||
static Sample* Create( SampleContext* sampleContext )
|
||||
|
|
@ -648,4 +645,4 @@ public:
|
|||
int m_sides;
|
||||
};
|
||||
|
||||
static int sampleCapsuleMass = SampleManager::Register( "Geometry", "Capsule Mass", CapsuleMass::Create );
|
||||
static int sampleCapsuleMass = RegisterSample( "Geometry", "Capsule Mass", CapsuleMass::Create );
|
||||
|
|
|
|||
|
|
@ -1,12 +1,10 @@
|
|||
// SPDX-FileCopyrightText: 2025 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "camera.h"
|
||||
#include "imgui.h"
|
||||
#include "mesh_loader.h"
|
||||
#include "renderer.h"
|
||||
#include "sample.h"
|
||||
#include "scene.h"
|
||||
#include "gfx/draw.h"
|
||||
|
||||
#include "box3d/box3d.h"
|
||||
|
||||
|
|
@ -49,7 +47,7 @@ public:
|
|||
std::vector<b3MeshData*> m_meshes;
|
||||
};
|
||||
|
||||
static int sampleDumpLoader = SampleManager::Register( "Issues", "Dump Loader", DumpLoader::Create );
|
||||
static int sampleDumpLoader = RegisterSample( "Issues", "Dump Loader", DumpLoader::Create );
|
||||
|
||||
class Crash : public Sample
|
||||
{
|
||||
|
|
@ -92,14 +90,8 @@ public:
|
|||
b3DestroyMesh( m_gridMesh );
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool DrawControls() 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();
|
||||
|
|
@ -108,7 +100,7 @@ public:
|
|||
b3CreateWeldJoint( m_worldId, &jointDef );
|
||||
}
|
||||
|
||||
ImGui::End();
|
||||
return true;
|
||||
}
|
||||
|
||||
static Sample* Create( SampleContext* context )
|
||||
|
|
@ -121,7 +113,7 @@ public:
|
|||
b3MeshData* m_gridMesh;
|
||||
};
|
||||
|
||||
static int sampleCrash = SampleManager::Register( "Issues", "Crash", Crash::Create );
|
||||
static int sampleCrash = RegisterSample( "Issues", "Crash", Crash::Create );
|
||||
|
||||
class MultiplePrismatic : public Sample
|
||||
{
|
||||
|
|
@ -131,7 +123,7 @@ public:
|
|||
{
|
||||
if ( context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 0.0f, 0.0f, 65.0f, { 0.0f, 0.0f, 0.0f } );
|
||||
m_camera->SetView( 0.0f, 0.0f, 25.0f, { 0.0f, 5.0f, 0.0f } );
|
||||
}
|
||||
|
||||
b3BodyId groundId;
|
||||
|
|
@ -177,7 +169,7 @@ public:
|
|||
}
|
||||
};
|
||||
|
||||
static int sampleMultiplePrismatic = SampleManager::Register( "Issues", "Multiple Prismatic", MultiplePrismatic::Create );
|
||||
static int sampleMultiplePrismatic = RegisterSample( "Issues", "Multiple Prismatic", MultiplePrismatic::Create );
|
||||
|
||||
class HullCrash : public Sample
|
||||
{
|
||||
|
|
@ -252,17 +244,17 @@ public:
|
|||
{
|
||||
if ( m_hull != nullptr )
|
||||
{
|
||||
DrawHull( m_scene, b3Transform_identity, m_hull, b3_colorYellow, true );
|
||||
DrawHull( b3Transform_identity, m_hull, MakeColor( b3_colorYellow ) );
|
||||
}
|
||||
else
|
||||
{
|
||||
for ( int i = 0; i < m_count; ++i )
|
||||
{
|
||||
DrawPoint( m_scene, m_points[i], 5.0f, b3_colorWhite );
|
||||
DrawPoint( m_points[i], 5.0f, MakeColor( b3_colorWhite ) );
|
||||
}
|
||||
}
|
||||
|
||||
DrawTransform( m_scene, b3Transform_identity, 1.0f );
|
||||
DrawAxes( b3Transform_identity, 1.0f );
|
||||
|
||||
Sample::Render();
|
||||
}
|
||||
|
|
@ -278,7 +270,7 @@ public:
|
|||
int m_count;
|
||||
};
|
||||
|
||||
static int sampleHullCrash = SampleManager::Register( "Issues", "Hull Crash", HullCrash::Create );
|
||||
static int sampleHullCrash = RegisterSample( "Issues", "Hull Crash", HullCrash::Create );
|
||||
|
||||
class ConvexJitter : public Sample
|
||||
{
|
||||
|
|
@ -289,20 +281,10 @@ public:
|
|||
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
|
||||
AddGroundBox( 10.0f );
|
||||
|
||||
float s = 0.01f;
|
||||
|
||||
|
|
@ -398,7 +380,7 @@ public:
|
|||
}
|
||||
};
|
||||
|
||||
static int sampleConvexJitter = SampleManager::Register( "Issues", "Convex Jitter", ConvexJitter::Create );
|
||||
static int sampleConvexJitter = RegisterSample( "Issues", "Convex Jitter", ConvexJitter::Create );
|
||||
|
||||
class SBoxMover : public Sample
|
||||
{
|
||||
|
|
@ -463,7 +445,7 @@ public:
|
|||
{
|
||||
Sample::Render();
|
||||
b3Transform transform = { { 0.0f, 1.1f, 0.0f }, b3Quat_identity };
|
||||
DrawTransform( m_scene, transform, 3.0f );
|
||||
DrawAxes( transform, 3.0f );
|
||||
}
|
||||
|
||||
static Sample* Create( SampleContext* context )
|
||||
|
|
@ -476,7 +458,7 @@ public:
|
|||
b3MeshData* m_gridMesh;
|
||||
};
|
||||
|
||||
static int sampleBoxMesh = SampleManager::Register( "Issues", "s&box mover", SBoxMover::Create );
|
||||
static int sampleBoxMesh = RegisterSample( "Issues", "s&box mover", SBoxMover::Create );
|
||||
|
||||
class CapsuleMeshBug : public Sample
|
||||
{
|
||||
|
|
@ -486,7 +468,7 @@ public:
|
|||
{
|
||||
if ( m_context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 120.0f, 30.0f, 10.0f, { 0.0f, 2.0f, 0.0f } );
|
||||
m_camera->SetView( 20.0f, 10.0f, 30.0f, { 0.0f, 2.0f, 0.0f } );
|
||||
}
|
||||
|
||||
// --- Ground plane ---
|
||||
|
|
@ -547,4 +529,4 @@ public:
|
|||
b3MeshData* m_building = nullptr;
|
||||
};
|
||||
|
||||
static int sampleIndex = SampleManager::Register( "Issues", "Capsule Mesh", CapsuleMeshBug::Create );
|
||||
static int sampleIndex = RegisterSample( "Issues", "Capsule Mesh", CapsuleMeshBug::Create );
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -1,12 +1,12 @@
|
|||
// 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 "gfx/draw.h"
|
||||
|
||||
#include "gfx/keycodes.h"
|
||||
|
||||
#include "box3d/box3d.h"
|
||||
#include "box3d/constants.h"
|
||||
|
||||
#include <imgui.h>
|
||||
|
|
@ -54,7 +54,7 @@ public:
|
|||
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 );
|
||||
DrawAxes( b3Transform_identity, 1.0f );
|
||||
|
||||
if ( m_manifold.pointCount == 0 )
|
||||
{
|
||||
|
|
@ -70,35 +70,34 @@ public:
|
|||
|
||||
b3Vec3 point = b3TransformPoint( m_transformA, manifoldPoint.point );
|
||||
|
||||
DrawLine( m_scene, point, point + length * normal, b3_colorWhite );
|
||||
DrawLine( point, point + length * normal, MakeColor( b3_colorWhite ) );
|
||||
|
||||
if ( manifoldPoint.separation > 0.0f )
|
||||
{
|
||||
DrawPoint( m_scene, point, 10.0f, b3_colorWhite );
|
||||
DrawPoint( point, 10.0f, MakeColor( b3_colorWhite ) );
|
||||
}
|
||||
else
|
||||
{
|
||||
DrawPoint( m_scene, point, 10.0f, b3_colorYellow );
|
||||
DrawPoint( point, 10.0f, MakeColor( b3_colorYellow ) );
|
||||
}
|
||||
|
||||
DrawWorldString( m_camera, point, b3_colorWhite, " %.3f", manifoldPoint.separation );
|
||||
DrawWorldString( point, MakeColor( 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 );
|
||||
DrawWorldString( point + 0.025f * normal + 0.05f * perp, MakeColor( b3_colorPapayaWhip ), " %X:%X %X:%X", pair.owner1, pair.index1, pair.owner2, pair.index2 );
|
||||
}
|
||||
|
||||
Sample::Render();
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool HasSolverControls() const override
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
bool DrawControls() 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 )
|
||||
{
|
||||
|
|
@ -108,14 +107,14 @@ public:
|
|||
ImGui::RadioButton( "edgePair", &m_manualFeature, 3 );
|
||||
}
|
||||
|
||||
ImGui::End();
|
||||
return true;
|
||||
}
|
||||
|
||||
void MouseDown( b3Vec2 p, int button, int modifiers ) override
|
||||
{
|
||||
if ( button == 0 && ( modifiers & GLFW_MOD_ALT ) == 0 )
|
||||
if ( button == 0 && ( modifiers & MOD_ALT ) == 0 )
|
||||
{
|
||||
if ( modifiers & GLFW_MOD_SHIFT )
|
||||
if ( modifiers & MOD_SHIFT )
|
||||
{
|
||||
m_baseX = p.x;
|
||||
m_baseY = p.y;
|
||||
|
|
@ -222,7 +221,7 @@ public:
|
|||
DrawTextLine( "feature = %d", m_manifold.feature );
|
||||
DrawTextLine( "cache hit = %d", m_satCache.hit );
|
||||
|
||||
DrawTransform( m_scene, b3Transform_identity, 1.0f );
|
||||
DrawAxes( b3Transform_identity, 1.0f );
|
||||
|
||||
if ( m_manifold.pointCount > 0 )
|
||||
{
|
||||
|
|
@ -234,49 +233,47 @@ public:
|
|||
|
||||
b3Vec3 point = manifoldPoint.point;
|
||||
|
||||
DrawLine( m_scene, point, point + length * m_manifold.normal, b3_colorWhite );
|
||||
DrawLine( point, point + length * m_manifold.normal, MakeColor( b3_colorWhite ) );
|
||||
|
||||
if ( manifoldPoint.separation > 0.0f )
|
||||
{
|
||||
DrawPoint( m_scene, point, 10.0f, b3_colorWhite );
|
||||
DrawPoint( point, 10.0f, MakeColor( b3_colorWhite ) );
|
||||
}
|
||||
else
|
||||
{
|
||||
DrawPoint( m_scene, point, 10.0f, b3_colorYellow );
|
||||
DrawPoint( point, 10.0f, MakeColor( b3_colorYellow ) );
|
||||
}
|
||||
|
||||
DrawWorldString( m_camera, point, b3_colorWhite, " %.2f", 100.0f * manifoldPoint.separation );
|
||||
DrawWorldString( point, MakeColor( 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 );
|
||||
DrawWorldString( point + 0.025f * m_manifold.normal, MakeColor( 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 );
|
||||
DrawTriangle( p1, p2, p3, MakeColor( b3_colorCyan ) );
|
||||
|
||||
DrawWorldString( m_camera, p1, b3_colorWhite, "0" );
|
||||
DrawWorldString( m_camera, p2, b3_colorWhite, "1" );
|
||||
DrawWorldString( m_camera, p3, b3_colorWhite, "2" );
|
||||
DrawWorldString( p1, MakeColor( b3_colorWhite ), "0" );
|
||||
DrawWorldString( p2, MakeColor( b3_colorWhite ), "1" );
|
||||
DrawWorldString( p3, MakeColor( 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 );
|
||||
DrawArrow( center, center + 0.5f * normal, MakeColor( b3_colorMediumPurple ) );
|
||||
|
||||
Sample::Render();
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool HasSolverControls() const 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 ) );
|
||||
return false;
|
||||
}
|
||||
|
||||
ImGui::Begin( "Triangle Manifold", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize );
|
||||
bool DrawControls() override
|
||||
{
|
||||
ImGui::Checkbox( "Use cache", &m_useCache );
|
||||
if ( m_useCache )
|
||||
{
|
||||
|
|
@ -286,14 +283,14 @@ public:
|
|||
ImGui::RadioButton( "edgePair", &m_manualFeature, 3 );
|
||||
}
|
||||
|
||||
ImGui::End();
|
||||
return true;
|
||||
}
|
||||
|
||||
void MouseDown( b3Vec2 p, int button, int modifiers ) override
|
||||
{
|
||||
if ( button == 0 && ( modifiers & GLFW_MOD_ALT ) == 0 )
|
||||
if ( button == 0 && ( modifiers & MOD_ALT ) == 0 )
|
||||
{
|
||||
if ( modifiers & GLFW_MOD_SHIFT )
|
||||
if ( modifiers & MOD_SHIFT )
|
||||
{
|
||||
m_baseX = p.x;
|
||||
m_baseY = p.y;
|
||||
|
|
@ -366,8 +363,8 @@ public:
|
|||
|
||||
void Render() override
|
||||
{
|
||||
DrawSphere( m_scene, m_transformA, m_sphere, b3_colorGreen );
|
||||
DrawSphere( m_scene, m_transformB, m_sphere, b3_colorCyan );
|
||||
DrawSolidSphere( m_transformA, m_sphere, MakeColor( b3_colorGreen ) );
|
||||
DrawSolidSphere( m_transformB, m_sphere, MakeColor( b3_colorCyan ) );
|
||||
|
||||
Manifold::Render();
|
||||
}
|
||||
|
|
@ -386,7 +383,7 @@ public:
|
|||
b3Sphere m_sphere;
|
||||
};
|
||||
|
||||
static int sampleCollideSpheres = SampleManager::Register( "Manifold", "Sphere vs Sphere", SphereAndSphere::Create );
|
||||
static int sampleCollideSpheres = RegisterSample( "Manifold", "Sphere vs Sphere", SphereAndSphere::Create );
|
||||
|
||||
class CapsuleAndSphere : public Manifold
|
||||
{
|
||||
|
|
@ -408,8 +405,8 @@ public:
|
|||
|
||||
void Render() override
|
||||
{
|
||||
DrawCapsule( m_scene, m_transformA, m_capsule, b3_colorCyan );
|
||||
DrawSphere( m_scene, m_transformB, m_sphere, b3_colorGreen );
|
||||
DrawSolidCapsule( m_transformA, m_capsule, MakeColor( b3_colorCyan ) );
|
||||
DrawSolidSphere( m_transformB, m_sphere, MakeColor( b3_colorGreen ) );
|
||||
|
||||
Manifold::Render();
|
||||
}
|
||||
|
|
@ -424,7 +421,7 @@ public:
|
|||
b3Capsule m_capsule;
|
||||
};
|
||||
|
||||
static int sampleSphereAndCapsule = SampleManager::Register( "Manifold", "Capsule vs Sphere", CapsuleAndSphere::Create );
|
||||
static int sampleSphereAndCapsule = RegisterSample( "Manifold", "Capsule vs Sphere", CapsuleAndSphere::Create );
|
||||
|
||||
class HullAndSphere : public Manifold
|
||||
{
|
||||
|
|
@ -441,8 +438,8 @@ public:
|
|||
|
||||
void Render() override
|
||||
{
|
||||
DrawHull( m_scene, m_transformA, &m_hull.base, b3_colorCyan, false );
|
||||
DrawSphere( m_scene, m_transformB, m_sphere, b3_colorGreen );
|
||||
DrawHull( m_transformA, &m_hull.base, MakeColor( b3_colorCyan ) );
|
||||
DrawSolidSphere( m_transformB, m_sphere, MakeColor( b3_colorGreen ) );
|
||||
|
||||
Manifold::Render();
|
||||
}
|
||||
|
|
@ -467,7 +464,7 @@ public:
|
|||
b3BoxHull m_hull;
|
||||
};
|
||||
|
||||
static int sampleSphereAndHull = SampleManager::Register( "Manifold", "Hull vs Sphere", HullAndSphere::Create );
|
||||
static int sampleSphereAndHull = RegisterSample( "Manifold", "Hull vs Sphere", HullAndSphere::Create );
|
||||
|
||||
class TriangleAndSphere : public TriangleManifold
|
||||
{
|
||||
|
|
@ -499,7 +496,7 @@ public:
|
|||
|
||||
void Render() override
|
||||
{
|
||||
DrawSphere( m_scene, m_transformB, m_sphere, b3_colorGreen );
|
||||
DrawSolidSphere( m_transformB, m_sphere, MakeColor( b3_colorGreen ) );
|
||||
|
||||
TriangleManifold::Render();
|
||||
}
|
||||
|
|
@ -527,7 +524,7 @@ public:
|
|||
b3Sphere m_sphere;
|
||||
};
|
||||
|
||||
static int sampleSphereAndTriangle = SampleManager::Register( "Manifold", "Triangle vs Sphere", TriangleAndSphere::Create );
|
||||
static int sampleSphereAndTriangle = RegisterSample( "Manifold", "Triangle vs Sphere", TriangleAndSphere::Create );
|
||||
|
||||
class CapsuleAndCapsule : public Manifold
|
||||
{
|
||||
|
|
@ -543,8 +540,8 @@ public:
|
|||
|
||||
void Render() override
|
||||
{
|
||||
DrawCapsule( m_scene, m_transformA, m_capsule, b3_colorGreen );
|
||||
DrawCapsule( m_scene, m_transformB, m_capsule, b3_colorCyan );
|
||||
DrawSolidCapsule( m_transformA, m_capsule, MakeColor( b3_colorGreen ) );
|
||||
DrawSolidCapsule( m_transformB, m_capsule, MakeColor( b3_colorCyan ) );
|
||||
|
||||
Manifold::Render();
|
||||
}
|
||||
|
|
@ -563,7 +560,7 @@ public:
|
|||
b3Capsule m_capsule;
|
||||
};
|
||||
|
||||
static int sampleCapsuleAndCapsule = SampleManager::Register( "Manifold", "Capsule vs Capsule", CapsuleAndCapsule::Create );
|
||||
static int sampleCapsuleAndCapsule = RegisterSample( "Manifold", "Capsule vs Capsule", CapsuleAndCapsule::Create );
|
||||
|
||||
class CapsuleAndHull : public Manifold
|
||||
{
|
||||
|
|
@ -596,8 +593,8 @@ public:
|
|||
|
||||
void Render() override
|
||||
{
|
||||
DrawHull( m_scene, m_transformA, &m_hull.base, b3_colorCyan, false );
|
||||
DrawCapsule( m_scene, m_transformB, m_capsule, b3_colorGreen );
|
||||
DrawHull( m_transformA, &m_hull.base, MakeColor( b3_colorCyan ) );
|
||||
DrawSolidCapsule( m_transformB, m_capsule, MakeColor( b3_colorGreen ) );
|
||||
|
||||
Manifold::Render();
|
||||
}
|
||||
|
|
@ -622,7 +619,7 @@ public:
|
|||
b3Capsule m_capsule;
|
||||
};
|
||||
|
||||
static int sampleCapsuleAndHull = SampleManager::Register( "Manifold", "Capsule vs Hull", CapsuleAndHull::Create );
|
||||
static int sampleCapsuleAndHull = RegisterSample( "Manifold", "Capsule vs Hull", CapsuleAndHull::Create );
|
||||
|
||||
class TriangleAndCapsule : public TriangleManifold
|
||||
{
|
||||
|
|
@ -655,8 +652,8 @@ public:
|
|||
|
||||
void Render() override
|
||||
{
|
||||
DrawCapsule( m_scene, m_transformB, m_capsule, b3_colorGreen );
|
||||
DrawTransform( m_scene, m_transformB, 0.1f );
|
||||
DrawSolidCapsule( m_transformB, m_capsule, MakeColor( b3_colorGreen ) );
|
||||
DrawAxes( m_transformB, 0.1f );
|
||||
|
||||
TriangleManifold::Render();
|
||||
}
|
||||
|
|
@ -689,7 +686,7 @@ public:
|
|||
b3Capsule m_capsule;
|
||||
};
|
||||
|
||||
static int sampleCapsuleAndTriangle = SampleManager::Register( "Manifold", "Triangle vs Capsule", TriangleAndCapsule::Create );
|
||||
static int sampleCapsuleAndTriangle = RegisterSample( "Manifold", "Triangle vs Capsule", TriangleAndCapsule::Create );
|
||||
|
||||
class HullAndHull : public Manifold
|
||||
{
|
||||
|
|
@ -749,13 +746,13 @@ public:
|
|||
}
|
||||
}
|
||||
|
||||
b3Hull* CreateConvex( float radius1, float height1, float radius2, float height2, Arena arena ) const
|
||||
b3Hull* CreateConvex( float radius1, float height1, float radius2, float height2 ) const
|
||||
{
|
||||
const int sideCount = 32;
|
||||
constexpr 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 ) ) );
|
||||
b3Vec3 vertexBase[2 * sideCount];
|
||||
|
||||
float alpha = 0.0f;
|
||||
for ( int sideIndex = 0; sideIndex < sideCount; ++sideIndex )
|
||||
|
|
@ -777,8 +774,8 @@ public:
|
|||
|
||||
void Render() override
|
||||
{
|
||||
DrawHull( m_scene, m_transformA, m_hullA, b3_colorGreen, false );
|
||||
DrawHull( m_scene, m_transformB, m_hullB, b3_colorCyan, false );
|
||||
DrawHull( m_transformA, m_hullA, MakeColor( b3_colorGreen ) );
|
||||
DrawHull( m_transformB, m_hullB, MakeColor( b3_colorCyan ) );
|
||||
|
||||
Manifold::Render();
|
||||
}
|
||||
|
|
@ -822,7 +819,7 @@ public:
|
|||
b3Hull* m_hullB;
|
||||
};
|
||||
|
||||
static int sampleCollideHulls = SampleManager::Register( "Manifold", "Hull vs Hull", HullAndHull::Create );
|
||||
static int sampleCollideHulls = RegisterSample( "Manifold", "Hull vs Hull", HullAndHull::Create );
|
||||
|
||||
class TriangleAndHull : public TriangleManifold
|
||||
{
|
||||
|
|
@ -882,12 +879,12 @@ public:
|
|||
|
||||
void Render() override
|
||||
{
|
||||
DrawHull( m_scene, m_transformB, m_hull, b3_colorGreen, false );
|
||||
DrawHull( m_transformB, m_hull, MakeColor( b3_colorGreen ) );
|
||||
|
||||
b3Transform xf;
|
||||
xf.p = b3TransformPoint( m_transformB, m_hull->center );
|
||||
xf.q = m_transformB.q;
|
||||
DrawTransform( m_scene, xf, 0.1f );
|
||||
DrawAxes( xf, 0.1f );
|
||||
|
||||
TriangleManifold::Render();
|
||||
}
|
||||
|
|
@ -938,4 +935,4 @@ public:
|
|||
b3Hull* m_hull;
|
||||
};
|
||||
|
||||
static int sampleHullAndTriangle = SampleManager::Register( "Manifold", "Triangle vs Hull", TriangleAndHull::Create );
|
||||
static int sampleHullAndTriangle = RegisterSample( "Manifold", "Triangle vs Hull", TriangleAndHull::Create );
|
||||
|
|
|
|||
|
|
@ -1,12 +1,12 @@
|
|||
// 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 "gfx/draw.h"
|
||||
|
||||
#include "gfx/debug_adapter.h"
|
||||
|
||||
#include "box3d/box3d.h"
|
||||
|
||||
|
|
@ -55,7 +55,7 @@ public:
|
|||
|
||||
Spawn();
|
||||
|
||||
m_context->debugDraw.forceScale = 0.01f;
|
||||
GetGuiDraw()->forceScale = 0.01f;
|
||||
}
|
||||
|
||||
~GridMesh() override
|
||||
|
|
@ -125,13 +125,8 @@ public:
|
|||
}
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool DrawControls() override
|
||||
{
|
||||
float height = 220.0f;
|
||||
ImGui::SetNextWindowPos( ImVec2( 10.0f, m_camera->m_height - height - 50.0f ), ImGuiCond_Once );
|
||||
ImGui::SetNextWindowSize( ImVec2( 280.0f, height ) );
|
||||
ImGui::Begin( "Mesh Grid", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize );
|
||||
|
||||
if ( ImGui::RadioButton( "Sphere", m_shapeType == ShapeType::sphere ) )
|
||||
{
|
||||
m_shapeType = ShapeType::sphere;
|
||||
|
|
@ -167,7 +162,7 @@ public:
|
|||
b3Shape_SetMesh( m_gridShapeId, m_gridMesh, m_scale );
|
||||
}
|
||||
|
||||
ImGui::End();
|
||||
return true;
|
||||
}
|
||||
|
||||
void Render() override
|
||||
|
|
@ -176,7 +171,7 @@ public:
|
|||
|
||||
DrawTextLine( "triangle count = %d, bytes = %d", m_gridMesh->triangleCount, m_gridMesh->byteCount );
|
||||
b3Transform transform = { { 0.0f, 0.01f, 0.0f }, b3Quat_identity };
|
||||
DrawTransform( m_scene, transform, 1.0f );
|
||||
DrawAxes( transform, 1.0f );
|
||||
}
|
||||
|
||||
void Step() override
|
||||
|
|
@ -210,7 +205,7 @@ public:
|
|||
b3Vec3 m_scale;
|
||||
};
|
||||
|
||||
static int sampleGridMesh = SampleManager::Register( "Mesh", "Grid", GridMesh::Create );
|
||||
static int sampleGridMesh = RegisterSample( "Mesh", "Grid", GridMesh::Create );
|
||||
|
||||
class BigBoxMesh : public Sample
|
||||
{
|
||||
|
|
@ -306,13 +301,8 @@ public:
|
|||
}
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool DrawControls() override
|
||||
{
|
||||
float height = 220.0f;
|
||||
ImGui::SetNextWindowPos( ImVec2( 10.0f, m_camera->m_height - height - 50.0f ), ImGuiCond_Once );
|
||||
ImGui::SetNextWindowSize( ImVec2( 280.0f, height ) );
|
||||
ImGui::Begin( "Mesh Grid", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize );
|
||||
|
||||
if ( ImGui::RadioButton( "Sphere", m_shapeType == ShapeType::sphere ) )
|
||||
{
|
||||
m_shapeType = ShapeType::sphere;
|
||||
|
|
@ -348,14 +338,14 @@ public:
|
|||
b3Shape_SetMesh( m_gridShapeId, m_boxMesh, m_scale );
|
||||
}
|
||||
|
||||
ImGui::End();
|
||||
return true;
|
||||
}
|
||||
|
||||
void Render() override
|
||||
{
|
||||
Sample::Render();
|
||||
b3Transform transform = { { 0.0f, 0.01f, 0.0f }, b3Quat_identity };
|
||||
DrawTransform( m_scene, transform, 1.0f );
|
||||
DrawAxes( transform, 1.0f );
|
||||
}
|
||||
|
||||
void Step() override
|
||||
|
|
@ -389,7 +379,7 @@ public:
|
|||
b3Vec3 m_scale;
|
||||
};
|
||||
|
||||
static int sampleBigBoxMesh = SampleManager::Register( "Mesh", "Big Box", BigBoxMesh::Create );
|
||||
static int sampleBigBoxMesh = RegisterSample( "Mesh", "Big Box", BigBoxMesh::Create );
|
||||
|
||||
class BoxMesh : public Sample
|
||||
{
|
||||
|
|
@ -400,17 +390,17 @@ public:
|
|||
if ( m_context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 45.0f, 30.0f, 6.0f, b3Vec3_zero );
|
||||
EnableGrid( m_scene, true );
|
||||
|
||||
}
|
||||
|
||||
AddGroundBox( 20.0f );
|
||||
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.position = { 0.0f, -1.0f, 0.0f };
|
||||
bodyDef.rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisY, 0.25f * B3_PI );
|
||||
b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef );
|
||||
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
b3BoxHull box = b3MakeBoxHull( 20.0f, 1.0f, 20.0f );
|
||||
b3CreateHullShape( groundId, &shapeDef, &box.base );
|
||||
|
||||
m_boxMesh = b3CreateBoxMesh( { 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 1.0f }, true );
|
||||
// m_scale = { -0.6f, 1.0f, 2.0f };
|
||||
|
|
@ -487,13 +477,8 @@ public:
|
|||
}
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool DrawControls() override
|
||||
{
|
||||
float height = 220.0f;
|
||||
ImGui::SetNextWindowPos( ImVec2( 10.0f, m_camera->m_height - height - 50.0f ), ImGuiCond_Once );
|
||||
ImGui::SetNextWindowSize( ImVec2( 280.0f, height ) );
|
||||
ImGui::Begin( "Box Mesh", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize );
|
||||
|
||||
if ( ImGui::RadioButton( "Sphere", m_shapeType == ShapeType::sphere ) )
|
||||
{
|
||||
m_shapeType = ShapeType::sphere;
|
||||
|
|
@ -529,14 +514,7 @@ public:
|
|||
b3Shape_SetMesh( m_boxShapeId, m_boxMesh, m_scale );
|
||||
}
|
||||
|
||||
ImGui::End();
|
||||
}
|
||||
|
||||
void Render() override
|
||||
{
|
||||
Sample::Render();
|
||||
b3Transform transform = { { 0.0f, 0.1f, 0.0f }, b3Quat_identity };
|
||||
DrawTransform( m_scene, transform, 2.0f );
|
||||
return true;
|
||||
}
|
||||
|
||||
void Step() override
|
||||
|
|
@ -570,7 +548,7 @@ public:
|
|||
b3Vec3 m_scale;
|
||||
};
|
||||
|
||||
static int sampleBoxMesh = SampleManager::Register( "Mesh", "Box", BoxMesh::Create );
|
||||
static int sampleBoxMesh = RegisterSample( "Mesh", "Box", BoxMesh::Create );
|
||||
|
||||
class MeshReflection : public Sample
|
||||
{
|
||||
|
|
@ -682,12 +660,8 @@ public:
|
|||
}
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool DrawControls() override
|
||||
{
|
||||
ImGui::SetNextWindowPos( ImVec2( 10.0f, 600.0f ) );
|
||||
ImGui::SetNextWindowSize( ImVec2( 200.0f, 150.0f ) );
|
||||
ImGui::Begin( "Mesh Reflection", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize );
|
||||
|
||||
bool changed = false;
|
||||
b3Vec3 scale = m_scale;
|
||||
if ( ImGui::RadioButton( "Neg X", scale.x < 0.0f ) )
|
||||
|
|
@ -739,7 +713,7 @@ public:
|
|||
b3Shape_SetMesh( m_meshShapeId, m_buildingMesh, m_scale );
|
||||
}
|
||||
|
||||
ImGui::End();
|
||||
return true;
|
||||
}
|
||||
|
||||
void Render() override
|
||||
|
|
@ -763,7 +737,7 @@ public:
|
|||
Human m_humans[e_humanCount];
|
||||
};
|
||||
|
||||
static int sampleMeshReflection = SampleManager::Register( "Mesh", "Reflection", MeshReflection::Create );
|
||||
static int sampleMeshReflection = RegisterSample( "Mesh", "Reflection", MeshReflection::Create );
|
||||
|
||||
struct CastContext
|
||||
{
|
||||
|
|
@ -883,16 +857,9 @@ public:
|
|||
#endif
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool DrawControls() 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( { 40.0f * fontSize, height } );
|
||||
|
||||
ImGui::Begin( "Height Field", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize );
|
||||
|
||||
ImGui::PushItemWidth( 500.0f );
|
||||
ImGui::PushItemWidth( 6.0f * ImGui::GetFontSize() );
|
||||
|
||||
if ( ImGui::SliderInt( "columns", &m_columnCount, 1, 500 ) )
|
||||
{
|
||||
|
|
@ -925,14 +892,14 @@ public:
|
|||
ImGui::SliderFloat( "radius", &m_radius, 0.0f, 1.0f );
|
||||
|
||||
ImGui::PopItemWidth();
|
||||
ImGui::End();
|
||||
return true;
|
||||
}
|
||||
|
||||
void Render() override
|
||||
{
|
||||
Sample::Render();
|
||||
b3Transform transform = { { 0.0f, 0.1f, 0.0f }, b3Quat_identity };
|
||||
DrawTransform( m_scene, transform, 0.5f );
|
||||
DrawAxes( transform, 0.5f );
|
||||
}
|
||||
|
||||
// This callback finds the closest hit.
|
||||
|
|
@ -968,15 +935,15 @@ public:
|
|||
|
||||
b3RayResult result = b3World_CastRayClosest( m_worldId, m_rayOrigin, m_rayTranslation, b3DefaultQueryFilter() );
|
||||
|
||||
DrawPoint( m_scene, m_rayOrigin, 6.0f, b3_colorGreenYellow );
|
||||
DrawPoint( m_scene, m_rayOrigin + m_rayTranslation, 6.0f, b3_colorRed );
|
||||
DrawLine( m_scene, m_rayOrigin, m_rayOrigin + m_rayTranslation, b3_colorGray );
|
||||
DrawPoint( m_rayOrigin, 6.0f, MakeColor( b3_colorGreenYellow ) );
|
||||
DrawPoint( m_rayOrigin + m_rayTranslation, 6.0f, MakeColor( b3_colorRed ) );
|
||||
DrawLine( m_rayOrigin, m_rayOrigin + m_rayTranslation, MakeColor( b3_colorGray ) );
|
||||
|
||||
if ( result.hit )
|
||||
{
|
||||
b3Vec3 point = result.point;
|
||||
DrawLine( m_scene, point, point + 0.5f * result.normal, b3_colorGray );
|
||||
DrawPoint( m_scene, point, 10.0f, b3_colorOrange );
|
||||
DrawLine( point, point + 0.5f * result.normal, MakeColor( b3_colorGray ) );
|
||||
DrawPoint( point, 10.0f, MakeColor( b3_colorOrange ) );
|
||||
}
|
||||
}
|
||||
else
|
||||
|
|
@ -992,18 +959,18 @@ public:
|
|||
|
||||
b3World_CastShape( m_worldId, &proxy, m_rayTranslation, b3DefaultQueryFilter(), CastCallback, &result );
|
||||
|
||||
DrawPoint( m_scene, m_rayOrigin, 2.0f, b3_colorGreen );
|
||||
DrawPoint( m_scene, m_rayOrigin + m_rayTranslation, 2.0f, b3_colorRed );
|
||||
DrawLine( m_scene, m_rayOrigin, m_rayOrigin + m_rayTranslation, b3_colorYellow );
|
||||
DrawPoint( m_rayOrigin, 2.0f, MakeColor( b3_colorGreen ) );
|
||||
DrawPoint( m_rayOrigin + m_rayTranslation, 2.0f, MakeColor( b3_colorRed ) );
|
||||
DrawLine( m_rayOrigin, m_rayOrigin + m_rayTranslation, MakeColor( b3_colorYellow ) );
|
||||
|
||||
b3Sphere sphere = { b3Vec3_zero, m_radius };
|
||||
DrawSphere( m_scene, { m_rayOrigin + result.fraction * m_rayTranslation, b3Quat_identity }, sphere, b3_colorOrange );
|
||||
DrawSolidSphere( { m_rayOrigin + result.fraction * m_rayTranslation, b3Quat_identity }, sphere, MakeColor( b3_colorOrange ) );
|
||||
|
||||
if ( result.hit )
|
||||
{
|
||||
b3Vec3 point = result.point;
|
||||
DrawLine( m_scene, point, point + 0.5f * result.normal, b3_colorGreen );
|
||||
DrawPoint( m_scene, point, 6.0f, b3_colorPurple );
|
||||
DrawLine( point, point + 0.5f * result.normal, MakeColor( b3_colorGreen ) );
|
||||
DrawPoint( point, 6.0f, MakeColor( b3_colorPurple ) );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1022,7 +989,7 @@ public:
|
|||
bool m_holes;
|
||||
};
|
||||
|
||||
static int sampleHeightField = SampleManager::Register( "Mesh", "Height Field", HeightField::Create );
|
||||
static int sampleHeightField = RegisterSample( "Mesh", "Height Field", HeightField::Create );
|
||||
|
||||
static float ComputeInternalSurfaceArea( const b3MeshData* data )
|
||||
{
|
||||
|
|
@ -1178,25 +1145,25 @@ public:
|
|||
node->lowerBound,
|
||||
node->upperBound,
|
||||
};
|
||||
DrawBounds( m_scene, box, 0.0f, colors[level % colorCount] );
|
||||
DrawBounds( box, 0.0f, MakeColor( colors[level % colorCount] ) );
|
||||
|
||||
int axis = node->data.asNode.axis;
|
||||
b3Vec3 center = b3AABB_Center( box );
|
||||
if ( axis == 0 )
|
||||
{
|
||||
DrawArrow( m_scene, center, center + 0.1f * b3Vec3_axisX, 0.02f, b3_colorRed );
|
||||
DrawArrow( center, center + 0.1f * b3Vec3_axisX, MakeColor( b3_colorRed ) );
|
||||
}
|
||||
else if ( axis == 1 )
|
||||
{
|
||||
DrawArrow( m_scene, center, center + 0.1f * b3Vec3_axisY, 0.02f, b3_colorGreen );
|
||||
DrawArrow( center, center + 0.1f * b3Vec3_axisY, MakeColor( b3_colorGreen ) );
|
||||
}
|
||||
else if ( axis == 2 )
|
||||
{
|
||||
DrawArrow( m_scene, center, center + 0.1f * b3Vec3_axisZ, 0.02f, b3_colorBlue );
|
||||
DrawArrow( center, center + 0.1f * b3Vec3_axisZ, MakeColor( b3_colorBlue ) );
|
||||
}
|
||||
else
|
||||
{
|
||||
DrawSphere( m_scene, b3Transform_identity, { center, 0.03f }, b3_colorOrange );
|
||||
DrawSolidSphere( b3Transform_identity, { center, 0.03f }, MakeColor( b3_colorOrange ) );
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1217,15 +1184,8 @@ public:
|
|||
}
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool DrawControls() override
|
||||
{
|
||||
float fontSize = ImGui::GetFontSize();
|
||||
float height = 14.0f * fontSize;
|
||||
ImGui::SetNextWindowPos( { 1.0f * fontSize, m_camera->m_height - height - 3.0f * fontSize }, ImGuiCond_Once );
|
||||
ImGui::SetNextWindowSize( { 20.0f * fontSize, height } );
|
||||
|
||||
ImGui::Begin( "Mesh Viewer", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize );
|
||||
|
||||
if ( ImGui::SliderInt( "index", &m_meshIndex, 0, m_meshCount - 1 ) )
|
||||
{
|
||||
LoadMesh();
|
||||
|
|
@ -1259,13 +1219,13 @@ public:
|
|||
}
|
||||
|
||||
ImGui::SliderInt( "draw level", &m_drawLevel, -1, m_height );
|
||||
ImGui::End();
|
||||
return true;
|
||||
}
|
||||
|
||||
void Render() override
|
||||
{
|
||||
Sample::Render();
|
||||
DrawTransform( m_scene, b3Transform_identity, 1.0f );
|
||||
DrawAxes( b3Transform_identity, 1.0f );
|
||||
|
||||
DrawTextLine( "triangle count = %d", m_mesh->triangleCount );
|
||||
DrawTextLine( "vertex count = %d", m_mesh->vertexCount );
|
||||
|
|
@ -1291,18 +1251,18 @@ public:
|
|||
(void)area;
|
||||
|
||||
b3Vec3 p = ( 1.0f / 3.0f ) * ( v1 + v2 + v3 );
|
||||
DrawPoint( m_scene, p, 10.0f, b3_colorCyan );
|
||||
DrawPoint( p, 10.0f, MakeColor( b3_colorCyan ) );
|
||||
|
||||
DrawWorldString( m_camera, p + offset, b3_colorOrange, "%d", triangleIndex );
|
||||
DrawWorldString( p + offset, MakeColor( b3_colorOrange ), "%d", triangleIndex );
|
||||
|
||||
{
|
||||
DrawPoint( m_scene, v1, 10.0f, b3_colorRed );
|
||||
DrawPoint( m_scene, v2, 10.0f, b3_colorGreen );
|
||||
DrawPoint( m_scene, v3, 10.0f, b3_colorBlue );
|
||||
DrawPoint( v1, 10.0f, MakeColor( b3_colorRed ) );
|
||||
DrawPoint( v2, 10.0f, MakeColor( b3_colorGreen ) );
|
||||
DrawPoint( v3, 10.0f, MakeColor( b3_colorBlue ) );
|
||||
|
||||
DrawWorldString( m_camera, v1 + offset, b3_colorRed, "%d", i1 );
|
||||
DrawWorldString( m_camera, v2 + offset, b3_colorGreen, "%d", i2 );
|
||||
DrawWorldString( m_camera, v3 + offset, b3_colorBlue, "%d", i3 );
|
||||
DrawWorldString( v1 + offset, MakeColor( b3_colorRed ), "%d", i1 );
|
||||
DrawWorldString( v2 + offset, MakeColor( b3_colorGreen ), "%d", i2 );
|
||||
DrawWorldString( v3 + offset, MakeColor( b3_colorBlue ), "%d", i3 );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1329,7 +1289,7 @@ public:
|
|||
bool m_weldVertices;
|
||||
};
|
||||
|
||||
static int sampleMeshViewer = SampleManager::Register( "Mesh", "Viewer", MeshViewer::Create );
|
||||
static int sampleMeshViewer = RegisterSample( "Mesh", "Viewer", MeshViewer::Create );
|
||||
|
||||
// Results 9/29/25
|
||||
// base median split: 0.222 ms per mesh
|
||||
|
|
@ -1410,7 +1370,7 @@ public:
|
|||
float m_time;
|
||||
};
|
||||
|
||||
static int sampleMeshCreationBenchmark = SampleManager::Register( "Mesh", "Creation Benchmark", MeshCreationBenchmark::Create );
|
||||
static int sampleMeshCreationBenchmark = RegisterSample( "Mesh", "Creation Benchmark", MeshCreationBenchmark::Create );
|
||||
|
||||
class VoxelMesh : public Sample
|
||||
{
|
||||
|
|
@ -1526,7 +1486,7 @@ public:
|
|||
Human m_human;
|
||||
};
|
||||
|
||||
static int sampleVoxelMesh = SampleManager::Register( "Mesh", "Voxel", VoxelMesh::Create );
|
||||
static int sampleVoxelMesh = RegisterSample( "Mesh", "Voxel", VoxelMesh::Create );
|
||||
|
||||
// Pause this to check contact manifolds for axis aligned collisions.
|
||||
class HollowBox : public Sample
|
||||
|
|
@ -1537,7 +1497,7 @@ public:
|
|||
{
|
||||
if ( m_context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 45.0f, 30.0f, 6.0f, b3Vec3_zero );
|
||||
m_camera->SetView( 45.0f, 30.0f, 30.0f, b3Vec3_zero );
|
||||
}
|
||||
|
||||
{
|
||||
|
|
@ -1601,7 +1561,7 @@ public:
|
|||
Sample::Render();
|
||||
|
||||
b3Transform transform = { { 0.0f, 0.01f, 0.0f }, b3Quat_identity };
|
||||
DrawTransform( m_scene, transform, 1.0f );
|
||||
DrawAxes( transform, 1.0f );
|
||||
}
|
||||
|
||||
void Step() override
|
||||
|
|
@ -1617,4 +1577,4 @@ public:
|
|||
b3MeshData* m_mesh;
|
||||
};
|
||||
|
||||
static int sampleHollowBox = SampleManager::Register( "Mesh", "Hollow Box", HollowBox::Create );
|
||||
static int sampleHollowBox = RegisterSample( "Mesh", "Hollow Box", HollowBox::Create );
|
||||
|
|
|
|||
|
|
@ -1,11 +1,10 @@
|
|||
// 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 "gfx/draw.h"
|
||||
|
||||
#include "box3d/box3d.h"
|
||||
|
||||
|
|
@ -18,18 +17,9 @@ public:
|
|||
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 );
|
||||
}
|
||||
AddGroundBox( 20.0f );
|
||||
|
||||
m_jointFrictionTorque = 5.0f;
|
||||
m_jointHertz = 1.0f;
|
||||
|
|
@ -47,14 +37,9 @@ public:
|
|||
// Human_ApplyRandomAngularImpulse( &m_human, 10.0f );
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool DrawControls() 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 );
|
||||
ImGui::PushItemWidth( 6.0f * ImGui::GetFontSize() );
|
||||
|
||||
if ( ImGui::SliderFloat( "Joint Friction", &m_jointFrictionTorque, 0.0f, 20.0f, "%3.0f" ) )
|
||||
{
|
||||
|
|
@ -77,7 +62,7 @@ public:
|
|||
Spawn();
|
||||
}
|
||||
ImGui::PopItemWidth();
|
||||
ImGui::End();
|
||||
return true;
|
||||
}
|
||||
|
||||
static Sample* Create( SampleContext* context )
|
||||
|
|
@ -91,7 +76,7 @@ public:
|
|||
float m_jointDampingRatio;
|
||||
};
|
||||
|
||||
static int sampleRagdollOnBox = SampleManager::Register( "Ragdoll", "Box", RagdollOnBox::Create );
|
||||
static int sampleRagdollOnBox = RegisterSample( "Ragdoll", "Box", RagdollOnBox::Create );
|
||||
|
||||
class RagdollOnMesh : public Sample
|
||||
{
|
||||
|
|
@ -176,14 +161,9 @@ public:
|
|||
Human_CreateParallelAnchors( &m_human, m_worldId );
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool DrawControls() 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 );
|
||||
ImGui::PushItemWidth( 6.0f * ImGui::GetFontSize() );
|
||||
|
||||
if ( ImGui::SliderFloat( "Joint Friction", &m_jointFrictionTorque, 0.0f, 20.0f, "%3.0f" ) )
|
||||
{
|
||||
|
|
@ -206,7 +186,7 @@ public:
|
|||
Spawn();
|
||||
}
|
||||
ImGui::PopItemWidth();
|
||||
ImGui::End();
|
||||
return true;
|
||||
}
|
||||
|
||||
static Sample* Create( SampleContext* context )
|
||||
|
|
@ -222,7 +202,7 @@ public:
|
|||
float m_jointDampingRatio;
|
||||
};
|
||||
|
||||
static int sampleRagdollMesh = SampleManager::Register( "Ragdoll", "Mesh", RagdollOnMesh::Create );
|
||||
static int sampleRagdollMesh = RegisterSample( "Ragdoll", "Mesh", RagdollOnMesh::Create );
|
||||
|
||||
class RagdollPile : public Sample
|
||||
{
|
||||
|
|
@ -279,7 +259,7 @@ public:
|
|||
Human m_humans[e_count] = {};
|
||||
};
|
||||
|
||||
static int sampleRagdollPile = SampleManager::Register( "Ragdoll", "Pile", RagdollPile::Create );
|
||||
static int sampleRagdollPile = RegisterSample( "Ragdoll", "Pile", RagdollPile::Create );
|
||||
|
||||
class RagdollIncline : public Sample
|
||||
{
|
||||
|
|
@ -354,7 +334,7 @@ public:
|
|||
bool m_motorized;
|
||||
};
|
||||
|
||||
static int sampleRagdollIncline = SampleManager::Register( "Ragdoll", "Incline", RagdollIncline::Create );
|
||||
static int sampleRagdollIncline = RegisterSample( "Ragdoll", "Incline", RagdollIncline::Create );
|
||||
|
||||
#if 0
|
||||
class RagdollPose : public Sample
|
||||
|
|
@ -480,5 +460,5 @@ public:
|
|||
bool m_poseControl;
|
||||
};
|
||||
|
||||
static int sampleRagodllPose = SampleManager::Register( "Ragdoll", "Pose", RagdollPose::Create );
|
||||
static int sampleRagodllPose = RegisterSample( "Ragdoll", "Pose", RagdollPose::Create );
|
||||
#endif
|
||||
|
|
|
|||
|
|
@ -1,13 +1,13 @@
|
|||
// SPDX-FileCopyrightText: 2025 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "camera.h"
|
||||
#include "overflow_color.h"
|
||||
#include "sample.h"
|
||||
#include "scene.h"
|
||||
#include "gfx/draw.h"
|
||||
|
||||
#include "box3d/box3d.h"
|
||||
#include "box3d/constants.h"
|
||||
#include "gfx/debug_adapter.h"
|
||||
|
||||
#include <imgui.h>
|
||||
#include <stdlib.h>
|
||||
|
|
@ -21,20 +21,14 @@ public:
|
|||
{
|
||||
if ( m_context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 45.0f, 20.0f, 50.0f, b3Vec3_zero );
|
||||
EnableGrid( m_scene, true );
|
||||
m_camera->SetView( 30.0f, 15.0f, 70.0f, b3Vec3_zero );
|
||||
|
||||
}
|
||||
|
||||
AddGroundBox( 50.0f );
|
||||
|
||||
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;
|
||||
|
|
@ -73,7 +67,7 @@ public:
|
|||
}
|
||||
};
|
||||
|
||||
static int sampleHighMassRatio1 = SampleManager::Register( "Robustness", "HighMassRatio1", HighMassRatio1::Create );
|
||||
static int sampleHighMassRatio1 = RegisterSample( "Robustness", "HighMassRatio1", HighMassRatio1::Create );
|
||||
|
||||
// A pyramid of 5cm boxes. Stacking tiny objects is challenging for physics engines due to rotational effects.
|
||||
// This is also challenging for Box3D because of the AABB margin and linear slop are close to the shape size. This
|
||||
|
|
@ -86,17 +80,10 @@ public:
|
|||
{
|
||||
if ( m_context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 0.0f, 20.0f, 2.5f, { 0.0f, 0.75f, 0.0f } );
|
||||
EnableGrid( m_scene, true );
|
||||
m_camera->SetView( -30.0f, 20.0f, 10.0f, { 0.0f, 0.5f, 0.0f } );
|
||||
}
|
||||
|
||||
{
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef );
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
b3BoxHull box = b3MakeTransformedBoxHull( 40.0f, 1.0f, 40.0f, { { 0.0f, -1.0f, 0.0f }, b3Quat_identity } );
|
||||
b3CreateHullShape( groundId, &shapeDef, &box.base );
|
||||
}
|
||||
AddGroundBox( 20.0f );
|
||||
|
||||
{
|
||||
m_extent = 0.025f;
|
||||
|
|
@ -139,7 +126,7 @@ public:
|
|||
float m_extent;
|
||||
};
|
||||
|
||||
static int sampleTinyPyramid = SampleManager::Register( "Robustness", "Tiny Pyramid", TinyPyramid::Create );
|
||||
static int sampleTinyPyramid = RegisterSample( "Robustness", "Tiny Pyramid", TinyPyramid::Create );
|
||||
|
||||
class OverlapRecovery : public Sample
|
||||
{
|
||||
|
|
@ -149,8 +136,7 @@ public:
|
|||
{
|
||||
if ( m_context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 45.0f, 20.0f, 50.0f, b3Vec3_zero );
|
||||
EnableGrid( m_scene, true );
|
||||
m_camera->SetView( 45.0f, 20.0f, 15.0f, b3Vec3_zero );
|
||||
}
|
||||
|
||||
m_bodyIds = nullptr;
|
||||
|
|
@ -162,13 +148,7 @@ public:
|
|||
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 );
|
||||
}
|
||||
AddGroundBox( 20.0f );
|
||||
|
||||
CreateScene();
|
||||
}
|
||||
|
|
@ -221,14 +201,9 @@ public:
|
|||
assert( bodyIndex == m_bodyCount );
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool DrawControls() 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 );
|
||||
ImGui::PushItemWidth( 6.0f * ImGui::GetFontSize() );
|
||||
|
||||
bool changed = false;
|
||||
changed = changed || ImGui::SliderFloat( "Extent", &m_extent, 0.1f, 1.0f, "%.1f" );
|
||||
|
|
@ -245,7 +220,7 @@ public:
|
|||
}
|
||||
|
||||
ImGui::PopItemWidth();
|
||||
ImGui::End();
|
||||
return true;
|
||||
}
|
||||
|
||||
static Sample* Create( SampleContext* context )
|
||||
|
|
@ -263,7 +238,7 @@ public:
|
|||
float m_dampingRatio;
|
||||
};
|
||||
|
||||
static int sampleOverlapRecovery = SampleManager::Register( "Robustness", "Overlap Recovery", OverlapRecovery::Create );
|
||||
static int sampleOverlapRecovery = RegisterSample( "Robustness", "Overlap Recovery", OverlapRecovery::Create );
|
||||
|
||||
class Cart : public Sample
|
||||
{
|
||||
|
|
@ -275,18 +250,10 @@ public:
|
|||
{
|
||||
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 );
|
||||
}
|
||||
AddGroundBox( 20.0f );
|
||||
|
||||
b3World_SetGravity( m_worldId, { 0, -22, 0 } );
|
||||
|
||||
|
|
@ -402,14 +369,9 @@ public:
|
|||
m_jointId4 = b3CreateSphericalJoint( m_worldId, &jointDef );
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool DrawControls() 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 );
|
||||
ImGui::PushItemWidth( 6.0f * ImGui::GetFontSize() );
|
||||
|
||||
bool changed = false;
|
||||
ImGui::Text( "Contact" );
|
||||
|
|
@ -444,7 +406,7 @@ public:
|
|||
}
|
||||
|
||||
ImGui::PopItemWidth();
|
||||
ImGui::End();
|
||||
return true;
|
||||
}
|
||||
|
||||
static Sample* Create( SampleContext* context )
|
||||
|
|
@ -469,13 +431,9 @@ public:
|
|||
float m_constraintDampingRatio;
|
||||
};
|
||||
|
||||
static int sampleCart = SampleManager::Register( "Robustness", "Cart", Cart::Create );
|
||||
static int sampleCart = RegisterSample( "Robustness", "Cart", Cart::Create );
|
||||
|
||||
// Drives the b3*_Overflow solver path. A heavy hub touches more dynamic
|
||||
// neighbors than B3_DYNAMIC_COLOR_COUNT (= 20), so several contacts land in
|
||||
// the overflow color. The HUD reports the per-step overflow contact count
|
||||
// because the scene is visually unremarkable when working correctly — the
|
||||
// point is that it stays unremarkable.
|
||||
// This forces a constraint graph color overflow
|
||||
class OverflowColorPile : public Sample
|
||||
{
|
||||
public:
|
||||
|
|
@ -484,11 +442,13 @@ public:
|
|||
{
|
||||
if ( m_context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 5.0f, 3.0f, 6.0f, b3Vec3_zero );
|
||||
EnableGrid( m_scene, true );
|
||||
m_camera->SetView( 30.0f, 35.0f, 15.0f, b3Vec3_zero );
|
||||
|
||||
}
|
||||
|
||||
m_data = CreateOverflowColorPile( m_worldId );
|
||||
|
||||
SetGroundShape( m_data.groundShapeId );
|
||||
}
|
||||
|
||||
void Step() override
|
||||
|
|
@ -511,4 +471,4 @@ public:
|
|||
OverflowColorPileData m_data;
|
||||
};
|
||||
|
||||
static int sampleOverflowColorPile = SampleManager::Register( "Robustness", "Overflow Color Pile", OverflowColorPile::Create );
|
||||
static int sampleOverflowColorPile = RegisterSample( "Robustness", "Overflow Color Pile", OverflowColorPile::Create );
|
||||
|
|
|
|||
|
|
@ -1,14 +1,12 @@
|
|||
// SPDX-FileCopyrightText: 2025 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "camera.h"
|
||||
#include "gfx/draw.h"
|
||||
#include "human.h"
|
||||
#include "imgui.h"
|
||||
#include "mesh_loader.h"
|
||||
#include "utils.h"
|
||||
#include "renderer.h"
|
||||
#include "sample.h"
|
||||
#include "scene.h"
|
||||
#include "utils.h"
|
||||
|
||||
#include "box3d/box3d.h"
|
||||
|
||||
|
|
@ -21,22 +19,16 @@ public:
|
|||
if ( context->restart == false )
|
||||
{
|
||||
m_camera->SetView( -55.0f, 30.0f, 60.0f, { 0.0f, 7.5f, 0.0f } );
|
||||
EnableGrid( m_scene, true );
|
||||
}
|
||||
|
||||
AddGroundBox( 50.0f );
|
||||
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.position = { 0.0f, -1.0f, 0.0f };
|
||||
b3BodyId groundBody = b3CreateBody( m_worldId, &bodyDef );
|
||||
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
shapeDef.baseMaterial.friction = 1.0f;
|
||||
b3BoxHull groundBox = b3MakeBoxHull( 50.0f, 1.0f, 50.0f );
|
||||
b3CreateHullShape( groundBody, &shapeDef, &groundBox.base );
|
||||
|
||||
bodyDef.position = { 0.0f, 7.5f, -5.0f };
|
||||
bodyDef.rotation = b3MakeQuatFromAxisAngle( { 1.0f, 0.0f, 0.0f }, 40.0f * B3_DEG_TO_RAD );
|
||||
b3BodyId planeBody = b3CreateBody( m_worldId, &bodyDef );
|
||||
b3BoxHull planeBox = b3MakeBoxHull( 16.0f, 0.5f, 10.0f );
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
shapeDef.baseMaterial.friction = 1.0f;
|
||||
b3CreateHullShape( planeBody, &shapeDef, &planeBox.base );
|
||||
|
||||
|
|
@ -59,7 +51,7 @@ public:
|
|||
static constexpr int m_boxCount = 5;
|
||||
};
|
||||
|
||||
static int sampleInclinedPlane = SampleManager::Register( "Shapes", "Inclined Plane", InclinedPlane::Create );
|
||||
static int sampleInclinedPlane = RegisterSample( "Shapes", "Inclined Plane", InclinedPlane::Create );
|
||||
|
||||
class RollingResistance : public Sample
|
||||
{
|
||||
|
|
@ -70,24 +62,19 @@ public:
|
|||
if ( m_context->restart == false )
|
||||
{
|
||||
m_camera->SetView( -140.0f, 17.0f, 60.0f, { 0.0f, 7.5f, 0.0f } );
|
||||
EnableGrid( m_scene, true );
|
||||
}
|
||||
|
||||
AddGroundBox( 50.0f );
|
||||
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
|
||||
bodyDef.position = { 0.0f, -1.0f, 0.0f };
|
||||
b3BodyId groundBody = b3CreateBody( m_worldId, &bodyDef );
|
||||
|
||||
b3BoxHull mGround = b3MakeBoxHull( 50.0f, 1.0f, 50.0f );
|
||||
b3CreateHullShape( groundBody, &shapeDef, &mGround.base );
|
||||
|
||||
bodyDef.position = { 0.0f, 2.0f, -20.0f };
|
||||
bodyDef.rotation = b3MakeQuatFromAxisAngle( { 1.0f, 0.0f, 0.0f }, 10.0f * B3_DEG_TO_RAD );
|
||||
b3BodyId planeBody = b3CreateBody( m_worldId, &bodyDef );
|
||||
|
||||
b3BoxHull mPlane = b3MakeBoxHull( 32.0f, 0.5f, 15.0f );
|
||||
b3CreateHullShape( planeBody, &shapeDef, &mPlane.base );
|
||||
b3BoxHull plane = b3MakeBoxHull( 32.0f, 0.5f, 15.0f );
|
||||
b3CreateHullShape( planeBody, &shapeDef, &plane.base );
|
||||
|
||||
b3Sphere sphere = { b3Vec3_zero, 1.0f };
|
||||
bodyDef.type = b3_dynamicBody;
|
||||
|
|
@ -120,7 +107,7 @@ public:
|
|||
}
|
||||
};
|
||||
|
||||
static int sampleRollingResistance = SampleManager::Register( "Shapes", "Rolling Resistance", RollingResistance::Create );
|
||||
static int sampleRollingResistance = RegisterSample( "Shapes", "Rolling Resistance", RollingResistance::Create );
|
||||
|
||||
class HighResistance : public Sample
|
||||
{
|
||||
|
|
@ -131,18 +118,13 @@ public:
|
|||
if ( m_context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 0.0f, 5.0f, 40.0f, { 0.0f, 7.5f, 0.0f } );
|
||||
EnableGrid( m_scene, true );
|
||||
}
|
||||
|
||||
AddGroundBox( 50.0f );
|
||||
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
|
||||
bodyDef.position = { 0.0f, -1.0f, 0.0f };
|
||||
b3BodyId groundBody = b3CreateBody( m_worldId, &bodyDef );
|
||||
|
||||
b3BoxHull mGround = b3MakeBoxHull( 50.0f, 1.0f, 50.0f );
|
||||
b3CreateHullShape( groundBody, &shapeDef, &mGround.base );
|
||||
|
||||
b3Capsule capsule = { { 0.0f, -1.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 0.5f };
|
||||
bodyDef.type = b3_dynamicBody;
|
||||
bodyDef.rotation = b3MakeQuatFromAxisAngle( b3Vec3_axisZ, B3_DEG_TO_RAD * 30.0f );
|
||||
|
|
@ -164,7 +146,7 @@ public:
|
|||
static constexpr int m_count = 10;
|
||||
};
|
||||
|
||||
static int sampleHighResistance = SampleManager::Register( "Shapes", "High Resistance", HighResistance::Create );
|
||||
static int sampleHighResistance = RegisterSample( "Shapes", "High Resistance", HighResistance::Create );
|
||||
|
||||
class IsotropicFriction : public Sample
|
||||
{
|
||||
|
|
@ -175,20 +157,14 @@ public:
|
|||
if ( context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 45.0f, 30.0f, 150.0f, b3Vec3_zero );
|
||||
EnableGrid( m_scene, true );
|
||||
}
|
||||
|
||||
AddGroundBox( 100.0f );
|
||||
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.position = { 0.0f, -1.0f, 0.0f };
|
||||
b3BodyId groundBody = b3CreateBody( m_worldId, &bodyDef );
|
||||
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
b3BoxHull mGround = b3MakeBoxHull( 75.0f, 1.0f, 75.0f );
|
||||
shapeDef.baseMaterial.friction = 1.0f;
|
||||
b3CreateHullShape( groundBody, &shapeDef, &mGround.base );
|
||||
|
||||
b3BoxHull box = b3MakeBoxHull( 1.0f, 1.0f, 1.0f );
|
||||
bodyDef.type = b3_dynamicBody;
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
shapeDef.baseMaterial.friction = 0.6f;
|
||||
for ( int index = 0; index < m_boxCount; ++index )
|
||||
{
|
||||
|
|
@ -214,7 +190,7 @@ public:
|
|||
static constexpr int m_boxCount = 32;
|
||||
};
|
||||
|
||||
static int sampleIsotropicFriction = SampleManager::Register( "Shapes", "Isotropic Friction", IsotropicFriction::Create );
|
||||
static int sampleIsotropicFriction = RegisterSample( "Shapes", "Isotropic Friction", IsotropicFriction::Create );
|
||||
|
||||
// todo what is the point of this?
|
||||
class SlideTwist : public Sample
|
||||
|
|
@ -225,28 +201,24 @@ public:
|
|||
{
|
||||
if ( context->restart == false )
|
||||
{
|
||||
m_camera->SetView( -30.0f, 17.0f, 22.0f, { 0.0f, 5.0f, 0.0f } );
|
||||
EnableGrid( m_scene, true );
|
||||
m_camera->SetView( -30.0f, 17.0f, 30.0f, { 0.0f, 5.0f, 0.0f } );
|
||||
}
|
||||
|
||||
AddGroundBox( 50.0f );
|
||||
|
||||
b3Quat orientation = b3MakeQuatFromAxisAngle( b3Vec3_axisX, 20.0f * B3_DEG_TO_RAD );
|
||||
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.position = { 0.0f, -1.0f, 0.0f };
|
||||
b3BodyId groundBody = b3CreateBody( m_worldId, &bodyDef );
|
||||
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
shapeDef.baseMaterial.friction = 1.0f;
|
||||
b3BoxHull mGround = b3MakeBoxHull( 50.0f, 1.0f, 50.0f );
|
||||
b3CreateHullShape( groundBody, &shapeDef, &mGround.base );
|
||||
|
||||
bodyDef.position = { 0.0f, 4.0f, 0.0f };
|
||||
bodyDef.rotation = orientation;
|
||||
b3BodyId planeBody = b3CreateBody( m_worldId, &bodyDef );
|
||||
|
||||
b3BoxHull mPlane = b3MakeBoxHull( 10.0f, 0.5f, 10.0f );
|
||||
b3BoxHull plane = b3MakeBoxHull( 10.0f, 0.5f, 10.0f );
|
||||
shapeDef.baseMaterial.friction = 0.6f;
|
||||
b3CreateHullShape( planeBody, &shapeDef, &mPlane.base );
|
||||
b3CreateHullShape( planeBody, &shapeDef, &plane.base );
|
||||
|
||||
bodyDef.type = b3_dynamicBody;
|
||||
bodyDef.position = { 0.0f, 5.0f, 0.0f };
|
||||
|
|
@ -264,7 +236,7 @@ public:
|
|||
}
|
||||
};
|
||||
|
||||
static int sampleSlideTwist = SampleManager::Register( "Shapes", "Slide Twist", SlideTwist::Create );
|
||||
static int sampleSlideTwist = RegisterSample( "Shapes", "Slide Twist", SlideTwist::Create );
|
||||
|
||||
class Restitution : public Sample
|
||||
{
|
||||
|
|
@ -281,15 +253,9 @@ public:
|
|||
if ( context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 0.0f, 25.0f, 85.0f, { 0.0f, 20.0f, 0.0f } );
|
||||
EnableGrid( m_scene, true );
|
||||
}
|
||||
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.position = { 0.0f, -1.0f, 0.0f };
|
||||
b3BodyId groundBody = b3CreateBody( m_worldId, &bodyDef );
|
||||
b3BoxHull groundBox = b3MakeBoxHull( 50.0f, 1.0f, 20.0f );
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
b3CreateHullShape( groundBody, &shapeDef, &groundBox.base );
|
||||
AddGroundBox( 50.0f );
|
||||
|
||||
m_shapeType = e_sphereShape;
|
||||
|
||||
|
|
@ -340,14 +306,8 @@ public:
|
|||
}
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool DrawControls() override
|
||||
{
|
||||
float height = 100.0f;
|
||||
ImGui::SetNextWindowPos( ImVec2( 10.0f, m_camera->m_height - height - 50.0f ), ImGuiCond_Once );
|
||||
ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) );
|
||||
|
||||
ImGui::Begin( "Restitution", nullptr, ImGuiWindowFlags_NoResize );
|
||||
|
||||
if ( ImGui::RadioButton( "Sphere", m_shapeType == e_sphereShape ) )
|
||||
{
|
||||
m_shapeType = e_sphereShape;
|
||||
|
|
@ -360,7 +320,7 @@ public:
|
|||
CreateBodies();
|
||||
}
|
||||
|
||||
ImGui::End();
|
||||
return true;
|
||||
}
|
||||
|
||||
static Sample* Create( SampleContext* context )
|
||||
|
|
@ -374,7 +334,7 @@ public:
|
|||
ShapeType m_shapeType;
|
||||
};
|
||||
|
||||
static int sampleRestitution = SampleManager::Register( "Shapes", "Restitution", Restitution::Create );
|
||||
static int sampleRestitution = RegisterSample( "Shapes", "Restitution", Restitution::Create );
|
||||
|
||||
// This shows an optimization when creating many static shapes you can skip having them invoke collision, assuming
|
||||
// dynamic bodies are added after the static bodies.
|
||||
|
|
@ -387,20 +347,16 @@ public:
|
|||
if ( context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 0.0f, 25.0f, 10.0f, { 0.0f, 1.0f, 0.0f } );
|
||||
EnableGrid( m_scene, true );
|
||||
}
|
||||
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.position = { 0.0f, -1.0f, 0.0f };
|
||||
b3BodyId groundBody = b3CreateBody( m_worldId, &bodyDef );
|
||||
b3BoxHull groundBox = b3MakeBoxHull( 20.0f, 1.0f, 20.0f );
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
b3CreateHullShape( groundBody, &shapeDef, &groundBox.base );
|
||||
AddGroundBox( 20.0f );
|
||||
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.type = b3_dynamicBody;
|
||||
bodyDef.position = { 0.25f, 1.0f, 0.0f };
|
||||
b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef );
|
||||
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
shapeDef.baseMaterial.rollingResistance = 0.2f;
|
||||
b3Sphere sphere = { b3Vec3_zero, 0.5f };
|
||||
b3CreateSphereShape( bodyId, &shapeDef, &sphere );
|
||||
|
|
@ -427,14 +383,8 @@ public:
|
|||
b3CreateSphereShape( m_bodyId, &shapeDef, &sphere );
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool DrawControls() override
|
||||
{
|
||||
float height = 150.0f;
|
||||
ImGui::SetNextWindowPos( ImVec2( 10.0f, m_camera->m_height - height - 50.0f ), ImGuiCond_Once );
|
||||
ImGui::SetNextWindowSize( ImVec2( 240.0f, height ) );
|
||||
|
||||
ImGui::Begin( "Restitution", nullptr, ImGuiWindowFlags_NoResize );
|
||||
|
||||
if ( ImGui::RadioButton( "Invoke", m_invoke == true ) )
|
||||
{
|
||||
m_invoke = true;
|
||||
|
|
@ -461,14 +411,7 @@ public:
|
|||
}
|
||||
}
|
||||
|
||||
ImGui::End();
|
||||
}
|
||||
|
||||
void Render() override
|
||||
{
|
||||
Sample::Render();
|
||||
b3Transform transform = { { 0.0f, 0.1f, 0.0f }, b3Quat_identity };
|
||||
DrawTransform( m_scene, transform, 4.0f );
|
||||
return true;
|
||||
}
|
||||
|
||||
void Step() override
|
||||
|
|
@ -490,7 +433,7 @@ public:
|
|||
bool m_invoke;
|
||||
};
|
||||
|
||||
static int sampleStaticInvoke = SampleManager::Register( "Shapes", "Static Invoke", StaticInvoke::Create );
|
||||
static int sampleStaticInvoke = RegisterSample( "Shapes", "Static Invoke", StaticInvoke::Create );
|
||||
|
||||
class ConveyorBelt : public Sample
|
||||
{
|
||||
|
|
@ -501,19 +444,9 @@ public:
|
|||
if ( context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 0.0f, 25.0f, 40.0f, { 0.0f, 1.0f, 0.0f } );
|
||||
EnableGrid( m_scene, true );
|
||||
}
|
||||
|
||||
// Ground
|
||||
{
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.position = { 0.0f, -1.0f, 0.0f };
|
||||
b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef );
|
||||
|
||||
b3BoxHull groundBox = b3MakeBoxHull( 20.0f, 1.0f, 20.0f );
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
b3CreateHullShape( groundId, &shapeDef, &groundBox.base );
|
||||
}
|
||||
AddGroundBox( 20.0f );
|
||||
|
||||
// Platform
|
||||
{
|
||||
|
|
@ -544,20 +477,13 @@ public:
|
|||
}
|
||||
}
|
||||
|
||||
void Render() override
|
||||
{
|
||||
Sample::Render();
|
||||
b3Transform transform = { { 0.0f, 0.1f, 0.0f }, b3Quat_identity };
|
||||
DrawTransform( m_scene, transform, 4.0f );
|
||||
}
|
||||
|
||||
static Sample* Create( SampleContext* context )
|
||||
{
|
||||
return new ConveyorBelt( context );
|
||||
}
|
||||
};
|
||||
|
||||
static int sampleConveyorBelt = SampleManager::Register( "Shapes", "Conveyor Belt", ConveyorBelt::Create );
|
||||
static int sampleConveyorBelt = RegisterSample( "Shapes", "Conveyor Belt", ConveyorBelt::Create );
|
||||
|
||||
class ConveyorMesh : public Sample
|
||||
{
|
||||
|
|
@ -568,19 +494,9 @@ public:
|
|||
if ( context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 65.0f, 25.0f, 28.0f, { 0.0f, 1.0f, 0.0f } );
|
||||
EnableGrid( m_scene, true );
|
||||
}
|
||||
|
||||
// Ground
|
||||
{
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.position = { 0.0f, -1.0f, 0.0f };
|
||||
b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef );
|
||||
|
||||
b3BoxHull groundBox = b3MakeBoxHull( 20.0f, 1.0f, 20.0f );
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
b3CreateHullShape( groundId, &shapeDef, &groundBox.base );
|
||||
}
|
||||
AddGroundBox( 20.0f );
|
||||
|
||||
// Mesh
|
||||
{
|
||||
|
|
@ -623,12 +539,18 @@ public:
|
|||
materialIndices[24] = 6;
|
||||
m_velocities[6] = { 0.0f, 0.0f, -1.3f };
|
||||
|
||||
b3HexColor colors[7] = {
|
||||
b3_colorGreen, b3_colorGreenYellow, b3_colorHoneyDew, b3_colorHotPink,
|
||||
b3_colorIndianRed, b3_colorIndigo, b3_colorIvory,
|
||||
};
|
||||
|
||||
b3SurfaceMaterial materials[7];
|
||||
for ( int i = 0; i < 7; ++i )
|
||||
{
|
||||
materials[i] = b3DefaultSurfaceMaterial();
|
||||
materials[i].friction = 0.8f;
|
||||
materials[i].tangentVelocity = 2.0f * m_velocities[i];
|
||||
materials[i].customColor = colors[i];
|
||||
}
|
||||
|
||||
m_meshTransform.p = { 0.0f, 0.5f, 6.0f };
|
||||
|
|
@ -729,15 +651,15 @@ public:
|
|||
b3Vec3 p = 1.0f / 3.0f * ( v1 + v2 + v3 );
|
||||
p = b3TransformPoint( m_meshTransform, p );
|
||||
|
||||
DrawWorldString( m_camera, p, b3_colorAqua, "%d", i );
|
||||
DrawWorldString( p, MakeColor( b3_colorAqua ), "%d", i );
|
||||
|
||||
int materialIndex = materialIndices[i];
|
||||
|
||||
b3Vec3 v = b3RotateVector( m_meshTransform.q, m_velocities[materialIndex] );
|
||||
DrawLine( m_scene, p, p + v, b3_colorBlueViolet );
|
||||
DrawLine( p, p + v, MakeColor( b3_colorBlueViolet ) );
|
||||
}
|
||||
|
||||
DrawTransform( m_scene, b3Transform_identity, 0.5f );
|
||||
DrawAxes( b3Transform_identity, 0.5f );
|
||||
}
|
||||
|
||||
static Sample* Create( SampleContext* context )
|
||||
|
|
@ -751,7 +673,7 @@ public:
|
|||
b3Vec3 m_velocities[7];
|
||||
};
|
||||
|
||||
static int sampleConveyorMesh = SampleManager::Register( "Shapes", "Conveyor Mesh", ConveyorMesh::Create );
|
||||
static int sampleConveyorMesh = RegisterSample( "Shapes", "Conveyor Mesh", ConveyorMesh::Create );
|
||||
|
||||
class Wind : public Sample
|
||||
{
|
||||
|
|
@ -770,20 +692,21 @@ public:
|
|||
if ( context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 0.0f, 0.0f, 5.0f, { 0.0f, 1.0f, 0.0f } );
|
||||
EnableGrid( m_scene, true );
|
||||
}
|
||||
|
||||
AddGroundBox( 20.0f );
|
||||
|
||||
{
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
m_groundId = b3CreateBody( m_worldId, &bodyDef );
|
||||
}
|
||||
|
||||
m_shapeType = e_sphereShape;
|
||||
m_wind = { 6.0f, 0.0f };
|
||||
m_shapeType = e_boxShape;
|
||||
m_wind = { 6.0f, 0.0f, 0.0f };
|
||||
m_drag = 1.0f;
|
||||
m_lift = 0.75f;
|
||||
m_count = 10;
|
||||
m_noise = { 0.0f, 0.0f };
|
||||
m_noise = { 0.0f, 0.0f, 0.0f };
|
||||
|
||||
// Need this to be false for debug draw to work
|
||||
m_stepWhilePaused = false;
|
||||
|
|
@ -803,13 +726,15 @@ public:
|
|||
}
|
||||
|
||||
float radius = 0.1f;
|
||||
float verticalOffset = 2.0f;
|
||||
|
||||
b3Sphere sphere = { { 0.0f, 0.0f, 0.0f }, radius };
|
||||
b3Capsule capsule = { { 0.0f, -radius }, { 0.0f, radius }, 0.25f * radius };
|
||||
b3BoxHull box = b3MakeBoxHull( 0.25f * radius, 1.25f * radius, 0.5f * radius );
|
||||
b3Capsule capsule = { { -radius, 0.0f, 0.0f }, { radius, 0.0f, 0.0f }, 0.5f * radius };
|
||||
b3BoxHull box = b3MakeBoxHull( 1.25f * radius, 0.75f * radius, 0.125f * radius );
|
||||
|
||||
b3SphericalJointDef jointDef = b3DefaultSphericalJointDef();
|
||||
jointDef.base.bodyIdA = m_groundId;
|
||||
jointDef.base.localFrameA.p = { 0.0f, 2.0f + radius };
|
||||
jointDef.base.localFrameA.p = { 0.0f, verticalOffset, 0.0f };
|
||||
jointDef.base.drawScale = 0.1f;
|
||||
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
|
|
@ -822,7 +747,7 @@ public:
|
|||
|
||||
for ( int i = 0; i < m_count; ++i )
|
||||
{
|
||||
bodyDef.position = { 0.0f, 2.0f - 2.0f * radius * i };
|
||||
bodyDef.position = { ( 2.0f * i + 1.0f ) * radius, verticalOffset, 0.0f };
|
||||
m_bodyIds[i] = b3CreateBody( m_worldId, &bodyDef );
|
||||
|
||||
if ( m_shapeType == e_sphereShape )
|
||||
|
|
@ -839,24 +764,16 @@ public:
|
|||
}
|
||||
|
||||
jointDef.base.bodyIdB = m_bodyIds[i];
|
||||
jointDef.base.localFrameB.p = { 0.0f, radius };
|
||||
jointDef.base.localFrameB.p = { -radius, 0.0f, 0.0f };
|
||||
b3CreateSphericalJoint( m_worldId, &jointDef );
|
||||
|
||||
jointDef.base.bodyIdA = m_bodyIds[i];
|
||||
jointDef.base.localFrameA.p = { 0.0f, -radius };
|
||||
jointDef.base.localFrameA.p = { radius, 0.0f, 0.0f };
|
||||
}
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool DrawControls() override
|
||||
{
|
||||
float fontSize = ImGui::GetFontSize();
|
||||
float height = 15.0f * fontSize;
|
||||
ImGui::SetNextWindowPos( { 0.5f * fontSize, m_camera->m_height - height - 2.0f * fontSize }, ImGuiCond_Once );
|
||||
ImGui::SetNextWindowSize( { 24.0f * fontSize, height } );
|
||||
|
||||
ImGui::Begin( "Wind", nullptr, ImGuiWindowFlags_NoResize );
|
||||
ImGui::PushItemWidth( 18.0f * fontSize );
|
||||
|
||||
const char* shapeTypes[] = { "Circle", "Capsule", "Box" };
|
||||
int shapeType = int( m_shapeType );
|
||||
if ( ImGui::Combo( "Shape", &shapeType, shapeTypes, IM_ARRAYSIZE( shapeTypes ) ) )
|
||||
|
|
@ -865,7 +782,7 @@ public:
|
|||
CreateScene();
|
||||
}
|
||||
|
||||
ImGui::SliderFloat2( "Wind", &m_wind.x, -50.0f, 50.0f, "%.1f" );
|
||||
ImGui::SliderFloat( "Wind", &m_wind.x, -50.0f, 50.0f, "%.1f" );
|
||||
ImGui::SliderFloat( "Drag", &m_drag, 0.0f, 1.0f, "%.2f" );
|
||||
ImGui::SliderFloat( "Lift", &m_lift, 0.0f, 4.0f, "%.2f" );
|
||||
if ( ImGui::SliderInt( "Count", &m_count, 1, m_maxCount, "%d" ) )
|
||||
|
|
@ -873,15 +790,7 @@ public:
|
|||
CreateScene();
|
||||
}
|
||||
|
||||
ImGui::PopItemWidth();
|
||||
ImGui::End();
|
||||
}
|
||||
|
||||
void Render() override
|
||||
{
|
||||
Sample::Render();
|
||||
|
||||
DrawGrid( m_scene, 20 );
|
||||
return true;
|
||||
}
|
||||
|
||||
void Step() override
|
||||
|
|
@ -908,7 +817,9 @@ public:
|
|||
b3Vec3 rand = RandomVec3( { -0.3f, -0.3f, -0.3f }, { 0.3f, 0.3f, 0.3f } );
|
||||
m_noise = b3Lerp( m_noise, rand, 0.05f );
|
||||
|
||||
DrawLine( m_scene, b3Vec3_zero, b3MulSV( 0.2f, wind ), b3_colorFuchsia );
|
||||
b3Vec3 p1 = { 0.0f, 0.5f, 0.0f };
|
||||
b3Vec3 p2 = b3MulAdd( p1, 0.2f, wind );
|
||||
DrawArrow( p1, p2, MakeColor( b3_colorFuchsia ) );
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -929,7 +840,7 @@ public:
|
|||
int m_count;
|
||||
};
|
||||
|
||||
static int sampleWind = SampleManager::Register( "Shapes", "Wind", Wind::Create );
|
||||
static int sampleWind = RegisterSample( "Shapes", "Wind", Wind::Create );
|
||||
|
||||
class WindDrop : public Sample
|
||||
{
|
||||
|
|
@ -939,20 +850,10 @@ public:
|
|||
{
|
||||
if ( context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 0.0f, -10.0f, 20.0f, { 0.0f, 5.0f, 0.0f } );
|
||||
m_camera->SetView( -45.0f, 15.0f, 20.0f, { 0.0f, 5.0f, 0.0f } );
|
||||
}
|
||||
|
||||
{
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.name = "ground";
|
||||
bodyDef.position = { 0.0f, -1.0f, 0.0f };
|
||||
|
||||
b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef );
|
||||
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
b3BoxHull hull = b3MakeBoxHull( 15.0f, 1.0f, 15.0f );
|
||||
b3CreateHullShape( groundId, &shapeDef, &hull.base );
|
||||
}
|
||||
AddGroundBox( 15.0f );
|
||||
|
||||
m_drag = 1.0f;
|
||||
m_lift = 4.0f;
|
||||
|
|
@ -979,14 +880,6 @@ public:
|
|||
m_shapeId = b3CreateHullShape( bodyId, &shapeDef, &box.base );
|
||||
}
|
||||
|
||||
void Render() override
|
||||
{
|
||||
Sample::Render();
|
||||
|
||||
b3Transform transform = { { 0.0f, 0.1f, 0.0f }, b3Quat_identity };
|
||||
DrawTransform( m_scene, transform, 1.0f );
|
||||
}
|
||||
|
||||
void Step() override
|
||||
{
|
||||
bool shouldStep = m_context->pause == false || m_context->singleStep > 0;
|
||||
|
|
@ -1008,7 +901,7 @@ public:
|
|||
b3ShapeId m_shapeId;
|
||||
};
|
||||
|
||||
static int sampleWindDrop = SampleManager::Register( "Shapes", "Wind Drop", WindDrop::Create );
|
||||
static int sampleWindDrop = RegisterSample( "Shapes", "Wind Drop", WindDrop::Create );
|
||||
|
||||
class WindFlap : public Sample
|
||||
{
|
||||
|
|
@ -1018,20 +911,10 @@ public:
|
|||
{
|
||||
if ( context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 0.0f, -10.0f, 20.0f, { 0.0f, 5.0f, 0.0f } );
|
||||
m_camera->SetView( -35.0f, 15.0f, 65.0f, { 0.0f, 5.0f, 10.0f } );
|
||||
}
|
||||
|
||||
{
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.name = "ground";
|
||||
bodyDef.position = { 0.0f, -1.0f, 0.0f };
|
||||
|
||||
b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef );
|
||||
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
b3BoxHull hull = b3MakeBoxHull( 50.0f, 1.0f, 50.0f );
|
||||
b3CreateHullShape( groundId, &shapeDef, &hull.base );
|
||||
}
|
||||
AddGroundBox( 50.0f );
|
||||
|
||||
m_drag = 1.0f;
|
||||
m_lift = 2.0f;
|
||||
|
|
@ -1042,10 +925,10 @@ public:
|
|||
float a = 0.4f;
|
||||
// b3BoxHull box = b3MakeBoxHull( 0.25f * radius, 1.25f * radius, 0.25f * radius );
|
||||
b3Capsule capsule = { { 0.0f, 0.0f, -a }, { 0.0f, 0.0f, a }, 0.25f * a };
|
||||
//b3BoxHull box = b3MakeBoxHull( 2.0f * a, 0.01f, a );
|
||||
b3Transform wingTransform1 = {b3Vec3_zero, b3MakeQuatFromAxisAngle(b3Vec3_axisX, 0.1f)};
|
||||
// b3BoxHull box = b3MakeBoxHull( 2.0f * a, 0.01f, a );
|
||||
b3Transform wingTransform1 = { b3Vec3_zero, b3MakeQuatFromAxisAngle( b3Vec3_axisX, 0.1f ) };
|
||||
b3BoxHull box1 = b3MakeTransformedBoxHull( 2.0f * a, 0.01f, a, wingTransform1 );
|
||||
b3Transform wingTransform2 = {b3Vec3_zero, b3MakeQuatFromAxisAngle(b3Vec3_axisX, 0.1f)};
|
||||
b3Transform wingTransform2 = { b3Vec3_zero, b3MakeQuatFromAxisAngle( b3Vec3_axisX, 0.1f ) };
|
||||
b3BoxHull box2 = b3MakeTransformedBoxHull( 2.0f * a, 0.01f, a, wingTransform2 );
|
||||
|
||||
float y = 20.0f;
|
||||
|
|
@ -1054,7 +937,7 @@ public:
|
|||
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.type = b3_dynamicBody;
|
||||
//bodyDef.gravityScale = 0.5f;
|
||||
// bodyDef.gravityScale = 0.5f;
|
||||
|
||||
shapeDef.density = 5.0f;
|
||||
bodyDef.position = { -2.0f * a, y, 0.0f };
|
||||
|
|
@ -1066,9 +949,9 @@ public:
|
|||
m_shapeId2 = b3CreateHullShape( wingBodyId2, &shapeDef, &box2.base );
|
||||
|
||||
bodyDef.position = { 0.0f, y, 0.0f };
|
||||
//bodyDef.type = b3_staticBody;
|
||||
// bodyDef.type = b3_staticBody;
|
||||
b3BodyId torsoBodyId = b3CreateBody( m_worldId, &bodyDef );
|
||||
|
||||
|
||||
shapeDef.density = 10.0f;
|
||||
m_torsoShapeId = b3CreateCapsuleShape( torsoBodyId, &shapeDef, &capsule );
|
||||
|
||||
|
|
@ -1098,14 +981,6 @@ public:
|
|||
m_time = 0.0f;
|
||||
}
|
||||
|
||||
void Render() override
|
||||
{
|
||||
Sample::Render();
|
||||
|
||||
b3Transform transform = { { 0.0f, 0.1f, 0.0f }, b3Quat_identity };
|
||||
DrawTransform( m_scene, transform, 1.0f );
|
||||
}
|
||||
|
||||
void Step() override
|
||||
{
|
||||
bool shouldStep = m_context->pause == false || m_context->singleStep > 0;
|
||||
|
|
@ -1117,11 +992,11 @@ public:
|
|||
bool wake = false;
|
||||
b3Shape_ApplyWind( m_shapeId1, b3Vec3_zero, m_drag, m_lift, maxSpeed, wake );
|
||||
b3Shape_ApplyWind( m_shapeId2, b3Vec3_zero, m_drag, m_lift, maxSpeed, wake );
|
||||
//b3Shape_ApplyWind( m_torsoShapeId, b3Vec3_zero, m_drag, m_lift, maxSpeed, wake );
|
||||
// b3Shape_ApplyWind( m_torsoShapeId, b3Vec3_zero, m_drag, m_lift, maxSpeed, wake );
|
||||
|
||||
float angle = b3Sin( 10.0f * m_time );
|
||||
b3RevoluteJoint_SetTargetAngle(m_jointId1, angle);
|
||||
b3RevoluteJoint_SetTargetAngle(m_jointId2, -angle);
|
||||
b3RevoluteJoint_SetTargetAngle( m_jointId1, angle );
|
||||
b3RevoluteJoint_SetTargetAngle( m_jointId2, -angle );
|
||||
|
||||
m_time += m_context->hertz > 0.0f ? 1.0f / m_context->hertz : 0.0f;
|
||||
}
|
||||
|
|
@ -1142,4 +1017,4 @@ public:
|
|||
b3JointId m_jointId2;
|
||||
};
|
||||
|
||||
static int sampleWindFlap = SampleManager::Register( "Shapes", "Wind Flap", WindFlap::Create );
|
||||
static int sampleWindFlap = RegisterSample( "Shapes", "Wind Flap", WindFlap::Create );
|
||||
|
|
|
|||
|
|
@ -1,11 +1,12 @@
|
|||
// SPDX-FileCopyrightText: 2025 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "camera.h"
|
||||
#include "gfx/debug_adapter.h"
|
||||
#include "gfx/keycodes.h"
|
||||
#include "imgui.h"
|
||||
#include "mesh_loader.h"
|
||||
#include "sample.h"
|
||||
#include "scene.h"
|
||||
#include "gfx/draw.h"
|
||||
|
||||
#include "box3d/box3d.h"
|
||||
|
||||
|
|
@ -18,9 +19,10 @@ public:
|
|||
if ( context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 0.0f, 25.0f, 10.0f, { 0.0f, 2.0f, 0.0f } );
|
||||
EnableGrid( m_scene, true );
|
||||
}
|
||||
|
||||
AddGroundBox( 10.0f );
|
||||
|
||||
const float alpha = 25.0f * B3_DEG_TO_RAD;
|
||||
const float width = 0.38f;
|
||||
const float height = 0.98f;
|
||||
|
|
@ -29,13 +31,6 @@ public:
|
|||
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 );
|
||||
|
|
@ -91,7 +86,7 @@ public:
|
|||
}
|
||||
};
|
||||
|
||||
static int sampleCardHouseThick = SampleManager::Register( "Stacking", "Card House Thick", CardHouseThick::Create );
|
||||
static int sampleCardHouseThick = RegisterSample( "Stacking", "Card House Thick", CardHouseThick::Create );
|
||||
|
||||
// From PEEL
|
||||
class CardHouse : public Sample
|
||||
|
|
@ -102,21 +97,14 @@ public:
|
|||
{
|
||||
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 );
|
||||
m_camera->SetView( 30.0f, 10.0f, 3.0f, { 0.75, 1.0, 0.4f } );
|
||||
}
|
||||
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.position = { 0.0f, -2.0f };
|
||||
b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef );
|
||||
AddGroundBox( 10.0f );
|
||||
|
||||
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;
|
||||
|
|
@ -127,6 +115,7 @@ public:
|
|||
|
||||
// todo box hull is limiting the minimum thickness, breaking this test
|
||||
b3BoxHull cardBox = b3MakeBoxHull( cardThickness, cardHeight, cardDepth );
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.type = b3_dynamicBody;
|
||||
|
||||
int Nb = 5;
|
||||
|
|
@ -171,7 +160,7 @@ public:
|
|||
}
|
||||
};
|
||||
|
||||
static int sampleCardHouse = SampleManager::Register( "Stacking", "Card House", CardHouse::Create );
|
||||
static int sampleCardHouse = RegisterSample( "Stacking", "Card House", CardHouse::Create );
|
||||
|
||||
class SphereStack : public Sample
|
||||
{
|
||||
|
|
@ -181,21 +170,10 @@ public:
|
|||
{
|
||||
if ( context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 0.0f, 15.0f, 50.0f, {0.0f, 10.0f, 0.0f} );
|
||||
EnableGrid( m_scene, true );
|
||||
m_camera->SetView( 0.0f, 15.0f, 50.0f, { 0.0f, 10.0f, 0.0f } );
|
||||
}
|
||||
|
||||
{
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.name = "ground";
|
||||
bodyDef.position = { 0.0f, -1.0f, 0.0f };
|
||||
|
||||
b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef );
|
||||
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
b3BoxHull hull = b3MakeBoxHull( 15.0f, 1.0f, 15.0f );
|
||||
b3CreateHullShape( groundId, &shapeDef, &hull.base );
|
||||
}
|
||||
AddGroundBox( 15.0f );
|
||||
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.type = b3_dynamicBody;
|
||||
|
|
@ -210,7 +188,7 @@ public:
|
|||
for ( int i = 0; i < 30; ++i )
|
||||
{
|
||||
bodyDef.name = "sphere";
|
||||
//bodyDef.position.x = 0.1f * i;
|
||||
// bodyDef.position.x = 0.1f * i;
|
||||
bodyDef.position.y = y;
|
||||
bodyDef.angularVelocity = { 0.0f, 0.0f, 0.0f };
|
||||
b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef );
|
||||
|
|
@ -243,7 +221,7 @@ public:
|
|||
b3BodyId m_bodyId;
|
||||
};
|
||||
|
||||
static int sampleSphereStack = SampleManager::Register( "Stacking", "Sphere Stack", SphereStack::Create );
|
||||
static int sampleSphereStack = RegisterSample( "Stacking", "Sphere Stack", SphereStack::Create );
|
||||
|
||||
class CapsuleStack : public Sample
|
||||
{
|
||||
|
|
@ -254,20 +232,9 @@ public:
|
|||
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( 40.0f, 1.0f, 40.0f );
|
||||
b3CreateHullShape( groundId, &shapeDef, &hull.base );
|
||||
}
|
||||
AddGroundBox( 40.0f );
|
||||
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.type = b3_dynamicBody;
|
||||
|
|
@ -277,7 +244,7 @@ public:
|
|||
bodyDef.motionLocks.angularZ = true;
|
||||
|
||||
float r = 0.5f;
|
||||
b3Capsule capsule = { {-1.0f, 0.0f, 0.0f}, {1.0f, 0.0f, 0.0f}, r };
|
||||
b3Capsule capsule = { { -1.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f }, r };
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
|
||||
float y = 1.5f * r;
|
||||
|
|
@ -298,7 +265,7 @@ public:
|
|||
}
|
||||
};
|
||||
|
||||
static int sampleCapsuleStack = SampleManager::Register( "Stacking", "Capsule Stack", CapsuleStack::Create );
|
||||
static int sampleCapsuleStack = RegisterSample( "Stacking", "Capsule Stack", CapsuleStack::Create );
|
||||
|
||||
class SingleBox : public Sample
|
||||
{
|
||||
|
|
@ -309,48 +276,22 @@ public:
|
|||
if ( context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 0.0f, 25.0f, 10.0f, b3Vec3_zero );
|
||||
EnableGrid( m_scene, true );
|
||||
}
|
||||
|
||||
AddGroundBox( 20.0f );
|
||||
|
||||
{
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.name = "ground";
|
||||
bodyDef.position = { 0.0f, -1.0f, 0.0f };
|
||||
|
||||
b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef );
|
||||
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
b3BoxHull hull = b3MakeBoxHull( 15.0f, 1.0f, 15.0f );
|
||||
b3CreateHullShape( groundId, &shapeDef, &hull.base );
|
||||
}
|
||||
|
||||
#if 1
|
||||
{
|
||||
b3BoxHull cube = b3MakeBoxHull( 0.5f, 0.5f, 0.5f );
|
||||
b3BoxHull cube = b3MakeCubeHull( 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
|
||||
|
|
@ -369,7 +310,7 @@ public:
|
|||
b3BodyId m_bodyId;
|
||||
};
|
||||
|
||||
static int sampleSingleBox = SampleManager::Register( "Stacking", "Single Box", SingleBox::Create );
|
||||
static int sampleSingleBox = RegisterSample( "Stacking", "Single Box", SingleBox::Create );
|
||||
|
||||
class Cylinder : public Sample
|
||||
{
|
||||
|
|
@ -380,20 +321,9 @@ public:
|
|||
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 );
|
||||
}
|
||||
AddGroundBox( 10.0f );
|
||||
|
||||
{
|
||||
m_hull = b3CreateCylinder( 1.0f, 0.25f, 0.0f, 12 );
|
||||
|
|
@ -410,7 +340,7 @@ public:
|
|||
b3CreateHullShape( bodyId, &shapeDef, m_hull );
|
||||
}
|
||||
|
||||
m_context->debugDraw.forceScale = 0.01f;
|
||||
GetGuiDraw()->forceScale = 0.01f;
|
||||
}
|
||||
|
||||
~Cylinder() override
|
||||
|
|
@ -431,7 +361,7 @@ public:
|
|||
b3Hull* m_hull;
|
||||
};
|
||||
|
||||
static int sampleCylinder = SampleManager::Register( "Stacking", "Cylinder", Cylinder::Create );
|
||||
static int sampleCylinder = RegisterSample( "Stacking", "Cylinder", Cylinder::Create );
|
||||
|
||||
class CylinderStack : public Sample
|
||||
{
|
||||
|
|
@ -441,21 +371,10 @@ public:
|
|||
{
|
||||
if ( context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 0.0f, 15.0f, 15.0f, {0.0f, 5.0f, 0.0f} );
|
||||
EnableGrid( m_scene, true );
|
||||
m_camera->SetView( 0.0f, 15.0f, 15.0f, { 0.0f, 5.0f, 0.0f } );
|
||||
}
|
||||
|
||||
{
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.name = "ground";
|
||||
bodyDef.position = { 0.0f, -1.0f, 0.0f };
|
||||
|
||||
b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef );
|
||||
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
b3BoxHull hull = b3MakeBoxHull( 10.0f, 1.0f, 10.0f );
|
||||
b3CreateHullShape( groundId, &shapeDef, &hull.base );
|
||||
}
|
||||
AddGroundBox( 10.0f );
|
||||
|
||||
m_hull = b3CreateCylinder( 1.0f, 0.5f, 0.0f, 15 );
|
||||
|
||||
|
|
@ -475,11 +394,11 @@ public:
|
|||
b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef );
|
||||
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
//shapeDef.baseMaterial.rollingResistance = 0.1f;
|
||||
// shapeDef.baseMaterial.rollingResistance = 0.1f;
|
||||
b3CreateTransformedHullShape( bodyId, &shapeDef, m_hull, b3Transform_identity, scales[i % 4] );
|
||||
}
|
||||
|
||||
m_context->debugDraw.forceScale = 0.001f;
|
||||
GetGuiDraw()->forceScale = 0.001f;
|
||||
}
|
||||
|
||||
~CylinderStack() override
|
||||
|
|
@ -500,7 +419,7 @@ public:
|
|||
b3Hull* m_hull;
|
||||
};
|
||||
|
||||
static int sampleCylinderStack = SampleManager::Register( "Stacking", "Cylinder Stack", CylinderStack::Create );
|
||||
static int sampleCylinderStack = RegisterSample( "Stacking", "Cylinder Stack", CylinderStack::Create );
|
||||
|
||||
class BoxStack : public Sample
|
||||
{
|
||||
|
|
@ -510,21 +429,10 @@ public:
|
|||
{
|
||||
if ( context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 0.0f, 15.0f, 50.0f, {0.0f, 20.0f, 0.0f} );
|
||||
EnableGrid( m_scene, true );
|
||||
m_camera->SetView( 0.0f, 15.0f, 50.0f, { 0.0f, 20.0f, 0.0f } );
|
||||
}
|
||||
|
||||
{
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.name = "ground";
|
||||
bodyDef.position = { 0.0f, -1.0f, 0.0f };
|
||||
|
||||
b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef );
|
||||
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
b3BoxHull hull = b3MakeBoxHull( 40.0f, 1.0f, 40.0f );
|
||||
b3CreateHullShape( groundId, &shapeDef, &hull.base );
|
||||
}
|
||||
AddGroundBox( 40.0f );
|
||||
|
||||
float a = 0.5f;
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
|
|
@ -566,7 +474,7 @@ public:
|
|||
}
|
||||
};
|
||||
|
||||
static int sampleBoxStack = SampleManager::Register( "Stacking", "Box Stack", BoxStack::Create );
|
||||
static int sampleBoxStack = RegisterSample( "Stacking", "Box Stack", BoxStack::Create );
|
||||
|
||||
class JengaStack : public Sample
|
||||
{
|
||||
|
|
@ -577,7 +485,6 @@ public:
|
|||
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;
|
||||
|
|
@ -586,15 +493,7 @@ public:
|
|||
|
||||
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 );
|
||||
}
|
||||
AddGroundBox( 60.0f );
|
||||
|
||||
{
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
|
|
@ -634,15 +533,8 @@ public:
|
|||
}
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool DrawControls() 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 ) )
|
||||
|
|
@ -659,9 +551,7 @@ public:
|
|||
CreateStack();
|
||||
}
|
||||
|
||||
ImGui::End();
|
||||
|
||||
Sample::UpdateUI();
|
||||
return true;
|
||||
}
|
||||
|
||||
static Sample* Create( SampleContext* context )
|
||||
|
|
@ -673,7 +563,7 @@ public:
|
|||
b3ShapeType m_shapeType;
|
||||
};
|
||||
|
||||
static int sampleJengaStack = SampleManager::Register( "Stacking", "Jenga Stack", JengaStack::Create );
|
||||
static int sampleJengaStack = RegisterSample( "Stacking", "Jenga Stack", JengaStack::Create );
|
||||
|
||||
class Dominoes : public Sample
|
||||
{
|
||||
|
|
@ -683,17 +573,17 @@ public:
|
|||
{
|
||||
if ( m_context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 0.0f, 15.0f, 50.0f, b3Vec3_zero );
|
||||
EnableGrid( m_scene, true );
|
||||
if (m_isDebug)
|
||||
{
|
||||
m_camera->SetView( 0.0f, 15.0f, 25.0f, b3Vec3_zero );
|
||||
}
|
||||
else
|
||||
{
|
||||
m_camera->SetView( 0.0f, 15.0f, 75.0f, b3Vec3_zero );
|
||||
}
|
||||
}
|
||||
|
||||
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 );
|
||||
AddGroundBox( 80.0f );
|
||||
|
||||
constexpr int n = m_isDebug ? 2 : 30;
|
||||
|
||||
|
|
@ -739,7 +629,7 @@ public:
|
|||
}
|
||||
};
|
||||
|
||||
static int sampleDominoes = SampleManager::Register( "Stacking", "Dominoes", Dominoes::Create );
|
||||
static int sampleDominoes = RegisterSample( "Stacking", "Dominoes", Dominoes::Create );
|
||||
|
||||
// This wedge shape can have an incorrect manifold if not handled correctly
|
||||
class Wedge : public Sample
|
||||
|
|
@ -755,16 +645,10 @@ public:
|
|||
{
|
||||
if ( context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 77.0f, 10.0f, 5.0f );
|
||||
m_camera->SetView( 75.0f, 10.0f, 10.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 );
|
||||
AddGroundBox( 20.0f );
|
||||
|
||||
b3Vec3 vertices[] = {
|
||||
{ -1.0, 1.0f, -0.1f }, { 1.0, 1.0f, -0.1f }, { -1.0, 1.0f, 0.1f },
|
||||
|
|
@ -773,9 +657,12 @@ public:
|
|||
|
||||
m_wedgeHull = b3CreateHull( vertices, 6, 6 );
|
||||
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.type = b3_dynamicBody;
|
||||
bodyDef.position = { 0.0f, 1.0f, 0.0f };
|
||||
b3BodyId wedgeBody = b3CreateBody( m_worldId, &bodyDef );
|
||||
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
b3CreateHullShape( wedgeBody, &shapeDef, m_wedgeHull );
|
||||
}
|
||||
|
||||
|
|
@ -787,7 +674,7 @@ public:
|
|||
b3Hull* m_wedgeHull;
|
||||
};
|
||||
|
||||
static int sampleWedge = SampleManager::Register( "Stacking", "Wedge", Wedge::Create );
|
||||
static int sampleWedge = RegisterSample( "Stacking", "Wedge", Wedge::Create );
|
||||
|
||||
// jitter
|
||||
/*
|
||||
|
|
@ -846,10 +733,11 @@ public:
|
|||
{
|
||||
if ( context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 0.0f, 15.0f, 30.0f, { 0.0f, 5.0f, 0.0f } );
|
||||
EnableGrid( m_scene, true );
|
||||
m_camera->SetView( 25.0f, 10.0f, 30.0f, { 0.0f, 5.0f, 0.0f } );
|
||||
}
|
||||
|
||||
AddGroundBox( 40.0f );
|
||||
|
||||
b3Vec3 ps1[9] = { { 16.0f, 0.0f, 0.0f },
|
||||
{ 14.93803712795643f, 5.133601056842984f, 0.0f },
|
||||
{ 13.79871746027416f, 10.24928069555078f, 0.0f },
|
||||
|
|
@ -882,14 +770,7 @@ public:
|
|||
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 );
|
||||
}
|
||||
shapeDef.density = 200.0f;
|
||||
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.type = b3_dynamicBody;
|
||||
|
|
@ -898,10 +779,10 @@ public:
|
|||
{
|
||||
b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef );
|
||||
b3Vec3 ps[8] = {
|
||||
{ ps1[i].x, ps1[i].y, -halfDepth }, { ps2[i].x, ps2[i].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 },
|
||||
{ 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 );
|
||||
|
|
@ -912,10 +793,10 @@ public:
|
|||
{
|
||||
b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef );
|
||||
b3Vec3 ps[8] = {
|
||||
{ -ps2[i].x, ps2[i].y, -halfDepth }, { -ps1[i].x, ps1[i].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 },
|
||||
{ -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 );
|
||||
|
|
@ -925,10 +806,9 @@ public:
|
|||
{
|
||||
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 },
|
||||
{ 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 );
|
||||
|
|
@ -950,7 +830,7 @@ public:
|
|||
}
|
||||
};
|
||||
|
||||
static int sampleArch = SampleManager::Register( "Stacking", "Arch", Arch::Create );
|
||||
static int sampleArch = RegisterSample( "Stacking", "Arch", Arch::Create );
|
||||
|
||||
class DoubleDomino : public Sample
|
||||
{
|
||||
|
|
@ -960,18 +840,10 @@ public:
|
|||
{
|
||||
if ( m_context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 0.0f, 15.0f, 20.0f, { 0.0f, 4.0f, 0.0f } );
|
||||
m_camera->SetView( 0.0f, 15.0f, 15.0f, { 0.0f, 0.5f, 1.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();
|
||||
b3CreateHullShape( groundId, &shapeDef, &groundBox.base );
|
||||
}
|
||||
AddGroundBox( 20.0f );
|
||||
|
||||
b3BoxHull box = b3MakeBoxHull( 0.125f, 0.5f, 0.25f );
|
||||
|
||||
|
|
@ -1004,7 +876,7 @@ public:
|
|||
}
|
||||
};
|
||||
|
||||
static int sampleDoubleDomino = SampleManager::Register( "Stacking", "Double Domino", DoubleDomino::Create );
|
||||
static int sampleDoubleDomino = RegisterSample( "Stacking", "Double Domino", DoubleDomino::Create );
|
||||
|
||||
class Pyramid2D : public Sample
|
||||
{
|
||||
|
|
@ -1017,17 +889,7 @@ public:
|
|||
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 );
|
||||
}
|
||||
AddGroundBox( 40.0f );
|
||||
|
||||
float a = 1.0f;
|
||||
b3BoxHull box = b3MakeBoxHull( a, a, a );
|
||||
|
|
@ -1043,7 +905,7 @@ public:
|
|||
{
|
||||
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 };
|
||||
bodyDef.position = { ( -10.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 );
|
||||
|
|
@ -1059,5 +921,4 @@ public:
|
|||
static constexpr int m_size = 12;
|
||||
};
|
||||
|
||||
static int samplePyramid2D = SampleManager::Register( "Stacking", "Pyramid2D", Pyramid2D::Create );
|
||||
|
||||
static int samplePyramid2D = RegisterSample( "Stacking", "Pyramid2D", Pyramid2D::Create );
|
||||
|
|
|
|||
|
|
@ -5,12 +5,12 @@
|
|||
#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 "gfx/draw.h"
|
||||
|
||||
#include "box3d/box3d.h"
|
||||
|
||||
#include <queue>
|
||||
#include <stdio.h>
|
||||
|
|
@ -615,7 +615,12 @@ public:
|
|||
m_closestTime = b3GetMilliseconds( ticks );
|
||||
}
|
||||
|
||||
void UpdateUI() override
|
||||
bool HasSolverControls() const override
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
bool DrawControls() override
|
||||
{
|
||||
DrawTextLine( "leaves = %d, height = %d, area = %g", m_tree.proxyCount, m_height, m_areaRatio );
|
||||
DrawTextLine( "build time = %g ms", m_buildTime );
|
||||
|
|
@ -624,13 +629,6 @@ public:
|
|||
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();
|
||||
|
|
@ -672,14 +670,14 @@ public:
|
|||
|
||||
ImGui::SliderFloat( "Load Scale", &m_loadScale, 0.01f, 1.0f );
|
||||
|
||||
ImGui::End();
|
||||
return true;
|
||||
}
|
||||
|
||||
void Render() override
|
||||
{
|
||||
Sample::Render();
|
||||
|
||||
DrawTransform( m_scene, b3Transform_identity, 2.0f );
|
||||
DrawAxes( b3Transform_identity, 2.0f );
|
||||
|
||||
b3Vec3 cp = m_camera->GetPosition();
|
||||
b3TreeNode* nodes = m_tree.nodes;
|
||||
|
|
@ -708,7 +706,7 @@ public:
|
|||
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] );
|
||||
DrawBounds( node->aabb, 0.0f, MakeColor( colors[m_drawLevel % colorCount] ) );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -733,13 +731,13 @@ public:
|
|||
Proxy& proxy = m_proxies[node->userData];
|
||||
if ( proxy.queryTimeStamp == m_timeStamp || proxy.rayTimeStamp == m_timeStamp )
|
||||
{
|
||||
DrawBounds( m_scene, node->aabb, 0.0f, b3_colorLightGray );
|
||||
DrawBounds( node->aabb, 0.0f, MakeColor( b3_colorLightGray ) );
|
||||
}
|
||||
else
|
||||
{
|
||||
// float extension = 0.01f * node->height;
|
||||
float extension = 0.0f;
|
||||
DrawBounds( m_scene, node->aabb, extension, b3_colorLightBlue );
|
||||
DrawBounds( node->aabb, extension, MakeColor( b3_colorLightBlue ) );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -747,20 +745,20 @@ public:
|
|||
if ( m_doRay )
|
||||
{
|
||||
Ray ray = m_rays[m_testIndex];
|
||||
DrawLine( m_scene, ray.origin, ray.origin + ray.translation, b3_colorRed );
|
||||
DrawLine( ray.origin, ray.origin + ray.translation, MakeColor( b3_colorRed ) );
|
||||
}
|
||||
|
||||
if ( m_doOverlap )
|
||||
{
|
||||
DrawBounds( m_scene, m_overlapQueries[m_testIndex], 0.0f, b3_colorRed );
|
||||
DrawBounds( m_overlapQueries[m_testIndex], 0.0f, MakeColor( b3_colorRed ) );
|
||||
}
|
||||
|
||||
if ( m_doClosest )
|
||||
{
|
||||
DrawSphere( m_scene, b3Transform_identity, m_closestPointQueries[m_testIndex], b3_colorCyan );
|
||||
DrawSolidSphere( b3Transform_identity, m_closestPointQueries[m_testIndex], MakeColor( b3_colorCyan ) );
|
||||
if ( m_haveClosest )
|
||||
{
|
||||
DrawPoint( m_scene, m_closestPoint, 15.0f, b3_colorOrange );
|
||||
DrawPoint( m_closestPoint, 15.0f, MakeColor( b3_colorOrange ) );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -845,4 +843,4 @@ public:
|
|||
bool m_doRay;
|
||||
};
|
||||
|
||||
static int sampleTree = SampleManager::Register( "Tree", "Benchmark", TreeBenchmark::Create );
|
||||
static int sampleTree = RegisterSample( "Tree", "Benchmark", TreeBenchmark::Create );
|
||||
|
|
|
|||
2146
samples/scene.cpp
2146
samples/scene.cpp
File diff suppressed because it is too large
Load diff
147
samples/scene.h
147
samples/scene.h
|
|
@ -1,147 +0,0 @@
|
|||
// 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 );
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue