diff --git a/.github/workflows/cmake.yml b/.github/workflows/cmake.yml new file mode 100644 index 000000000..52fbdd80c --- /dev/null +++ b/.github/workflows/cmake.yml @@ -0,0 +1,93 @@ +name: CMake Builds + +on: + push: + pull_request: + +env: + # Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.) + BUILD_TYPE: Release + +jobs: + build_windows: + name: Windows Build + # The CMake configure and build commands are platform agnostic and should work equally + # well on Windows or Mac. You can convert this to a matrix build if you need + # cross-platform coverage. + # See: https://docs.github.com/en/free-pro-team@latest/actions/learn-github-actions/managing-complex-workflows#using-a-build-matrix + runs-on: windows-latest + + steps: + - uses: actions/checkout@v2 + + - name: Create Build Environment + # Some projects don't allow in-source building, so create a separate build directory + # We'll use this as our working directory for all subsequent commands + run: cmake -E make_directory ${{github.workspace}}/build + + - name: Configure CMake + # Use a bash shell so we can use the same syntax for environment variable + # access regardless of the host operating system + shell: powershell + working-directory: ${{github.workspace}}/build + # Note the current convention is to use the -S and -B options here to specify source + # and build directories, but this is only available with CMake 3.13 and higher. + # The CMake binaries on the Github Actions machines are (as of this writing) 3.12 + run: cmake $env:GITHUB_WORKSPACE -DCMAKE_BUILD_TYPE=$env:BUILD_TYPE -DPLATFORM=Desktop + + - name: Build + working-directory: ${{github.workspace}}/build + shell: powershell + # Execute the build. You can specify a specific target with "--target " + run: cmake --build . --config $env:BUILD_TYPE + + - name: Test + working-directory: ${{github.workspace}}/build + shell: powershell + # Execute tests defined by the CMake configuration. + # See https://cmake.org/cmake/help/latest/manual/ctest.1.html for more detail + run: ctest -C $env:BUILD_TYPE + + build_linux: + name: Linux Build + # The CMake configure and build commands are platform agnostic and should work equally + # well on Windows or Mac. You can convert this to a matrix build if you need + # cross-platform coverage. + # See: https://docs.github.com/en/free-pro-team@latest/actions/learn-github-actions/managing-complex-workflows#using-a-build-matrix + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + + - name: Create Build Environment + # Some projects don't allow in-source building, so create a separate build directory + # We'll use this as our working directory for all subsequent commands + run: cmake -E make_directory ${{github.workspace}}/build + + - name: Setup Environment + run: | + sudo apt-get update -qq + sudo apt-get install gcc-multilib + sudo apt-get install -y --no-install-recommends libglfw3 libglfw3-dev libx11-dev libxcursor-dev libxrandr-dev libxinerama-dev libxi-dev libxext-dev libxfixes-dev + - name: Configure CMake + # Use a bash shell so we can use the same syntax for environment variable + # access regardless of the host operating system + shell: bash + working-directory: ${{github.workspace}}/build + # Note the current convention is to use the -S and -B options here to specify source + # and build directories, but this is only available with CMake 3.13 and higher. + # The CMake binaries on the Github Actions machines are (as of this writing) 3.12 + run: cmake $GITHUB_WORKSPACE -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DPLATFORM=Desktop + + - name: Build + working-directory: ${{github.workspace}}/build + shell: bash + # Execute the build. You can specify a specific target with "--target " + run: cmake --build . --config $BUILD_TYPE + + - name: Test + working-directory: ${{github.workspace}}/build + shell: bash + # Execute tests defined by the CMake configuration. + # See https://cmake.org/cmake/help/latest/manual/ctest.1.html for more detail + run: ctest -C $BUILD_TYPE \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt index 8c5d2113c..5fe826dff 100755 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,9 +2,11 @@ cmake_minimum_required(VERSION 3.0) project(raylib) # Directory for easier includes +# Anywhere you see include(...) you can check /cmake for that file set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake) -# RAYLIB_IS_MAIN determines whether the project is being used from root, or as a dependency. +# RAYLIB_IS_MAIN determines whether the project is being used from root +# or if it is added as a dependency (through add_subdirectory for example). if ("${CMAKE_SOURCE_DIR}" STREQUAL "${CMAKE_CURRENT_SOURCE_DIR}") set(RAYLIB_IS_MAIN TRUE) else() @@ -17,7 +19,7 @@ include(CompilerFlags) # Registers build options that are exposed to cmake include(CMakeOptions.txt) -# Checks a few environment and compiler configurations +# Enforces a few environment and compiler configurations include(BuildOptions) # Main sources directory (the second parameter sets the output directory name to raylib) diff --git a/CMakeOptions.txt b/CMakeOptions.txt index f39d17a1e..d60ca2b79 100644 --- a/CMakeOptions.txt +++ b/CMakeOptions.txt @@ -8,16 +8,16 @@ enum_option(OPENGL_VERSION "OFF;3.3;2.1;1.1;ES 2.0" "Force a specific OpenGL Ver # Configuration options option(BUILD_EXAMPLES "Build the examples." ${RAYLIB_IS_MAIN}) +option(CUSTOMIZE_BUILD "Show options for customizing your Raylib library build." OFF) option(ENABLE_ASAN "Enable AddressSanitizer (ASAN) for debugging (degrades performance)" OFF) option(ENABLE_UBSAN "Enable UndefinedBehaviorSanitizer (UBSan) for debugging" OFF) option(ENABLE_MSAN "Enable MemorySanitizer (MSan) for debugging (not recommended to run with ASAN)" OFF) # Shared library is always PIC. Static library should be PIC too if linked into a shared library option(WITH_PIC "Compile static library as position-independent code" OFF) -option(SHARED "Build raylib as a dynamic library" OFF) -option(STATIC "Build raylib as a static library" ON) +option(BUILD_SHARED_LIBS "Build raylib as a shared library" OFF) option(MACOS_FATLIB "Build fat library for both i386 and x86_64 on macOS" OFF) -option(USE_AUDIO "Build raylib with audio module" ON) +cmake_dependent_option(USE_AUDIO "Build raylib with audio module" ON CUSTOMIZE_BUILD ON) enum_option(USE_EXTERNAL_GLFW "OFF;IF_POSSIBLE;ON" "Link raylib against system GLFW instead of embedded one") if(UNIX AND NOT APPLE) @@ -28,61 +28,62 @@ option(INCLUDE_EVERYTHING "Include everything disabled by default (for CI usage" set(OFF ${INCLUDE_EVERYTHING} CACHE INTERNAL "Replace any OFF by default with \${OFF} to have it covered by this option") # core.c -option(SUPPORT_CAMERA_SYSTEM "Provide camera module (camera.h) with multiple predefined cameras: free, 1st/3rd person, orbital" ON) -option(SUPPORT_GESTURES_SYSTEM "Gestures module is included (gestures.h) to support gestures detection: tap, hold, swipe, drag" ON) -option(SUPPORT_MOUSE_GESTURES "Mouse gestures are directly mapped like touches and processed by gestures system" ON) -option(SUPPORT_SSH_KEYBOARD_RPI "Reconfigure standard input to receive key inputs, works with SSH connection" OFF) -option(SUPPORT_DEFAULT_FONT "Default font is loaded on window initialization to be available for the user to render simple text. If enabled, uses external module functions to load default raylib font (module: text)" ON) -option(SUPPORT_SCREEN_CAPTURE "Allow automatic screen capture of current screen pressing F12, defined in KeyCallback()" ON) -option(SUPPORT_GIF_RECORDING "Allow automatic gif recording of current screen pressing CTRL+F12, defined in KeyCallback()" ON) -option(SUPPORT_BUSY_WAIT_LOOP "Use busy wait loop for timing sync instead of a high-resolution timer" OFF) -option(SUPPORT_EVENTS_WAITING "Wait for events passively (sleeping while no events) instead of polling them actively every frame" OFF) -option(SUPPORT_HIGH_DPI "Support high DPI displays" OFF) -option(SUPPORT_DATA_STORAGE "Support for persistent data storage" ON) +cmake_dependent_option(SUPPORT_CAMERA_SYSTEM "Provide camera module (camera.h) with multiple predefined cameras: free, 1st/3rd person, orbital" ON CUSTOMIZE_BUILD ON) +cmake_dependent_option(SUPPORT_GESTURES_SYSTEM "Gestures module is included (gestures.h) to support gestures detection: tap, hold, swipe, drag" ON CUSTOMIZE_BUILD ON) +cmake_dependent_option(SUPPORT_MOUSE_GESTURES "Mouse gestures are directly mapped like touches and processed by gestures system" ON CUSTOMIZE_BUILD ON) +cmake_dependent_option(SUPPORT_SSH_KEYBOARD_RPI "Reconfigure standard input to receive key inputs, works with SSH connection" OFF CUSTOMIZE_BUILD OFF) +cmake_dependent_option(SUPPORT_DEFAULT_FONT "Default font is loaded on window initialization to be available for the user to render simple text. If enabled, uses external module functions to load default raylib font (module: text)" ON CUSTOMIZE_BUILD ON) +cmake_dependent_option(SUPPORT_SCREEN_CAPTURE "Allow automatic screen capture of current screen pressing F12, defined in KeyCallback()" ON CUSTOMIZE_BUILD ON) +cmake_dependent_option(SUPPORT_GIF_RECORDING "Allow automatic gif recording of current screen pressing CTRL+F12, defined in KeyCallback()" ON CUSTOMIZE_BUILD ON) +cmake_dependent_option(SUPPORT_BUSY_WAIT_LOOP "Use busy wait loop for timing sync instead of a high-resolution timer" OFF CUSTOMIZE_BUILD OFF) +cmake_dependent_option(SUPPORT_EVENTS_WAITING "Wait for events passively (sleeping while no events) instead of polling them actively every frame" OFF CUSTOMIZE_BUILD OFF) +cmake_dependent_option(SUPPORT_HIGH_DPI "Support high DPI displays" OFF CUSTOMIZE_BUILD OFF) +cmake_dependent_option(SUPPORT_DATA_STORAGE "Support for persistent data storage" ON CUSTOMIZE_BUILD ON) +cmake_dependent_option(SUPPORT_COMPRESSION_API "Support for compression API" ON CUSTOMIZE_BUILD ON) # rlgl.h -option(SUPPORT_VR_SIMULATOR "Support VR simulation functionality (stereo rendering)" ON) +cmake_dependent_option(SUPPORT_VR_SIMULATOR "Support VR simulation functionality (stereo rendering)" ON CUSTOMIZE_BUILD ON) # shapes.c -option(SUPPORT_FONT_TEXTURE "Draw rectangle shapes using font texture white character instead of default white texture. Allows drawing rectangles and text with a single draw call, very useful for GUI systems!" ON) -option(SUPPORT_QUADS_DRAW_MODE "Use QUADS instead of TRIANGLES for drawing when possible. Some lines-based shapes could still use lines" ON) +cmake_dependent_option(SUPPORT_FONT_TEXTURE "Draw rectangle shapes using font texture white character instead of default white texture. Allows drawing rectangles and text with a single draw call, very useful for GUI systems!" ON CUSTOMIZE_BUILD ON) +cmake_dependent_option(SUPPORT_QUADS_DRAW_MODE "Use QUADS instead of TRIANGLES for drawing when possible. Some lines-based shapes could still use lines" ON CUSTOMIZE_BUILD ON) # textures.c -option(SUPPORT_IMAGE_EXPORT "Support image exporting to file" ON) -option(SUPPORT_IMAGE_GENERATION "Support procedural image generation functionality (gradient, spot, perlin-noise, cellular)" ON) -option(SUPPORT_IMAGE_MANIPULATION "Support multiple image editing functions to scale, adjust colors, flip, draw on images, crop... If not defined only three image editing functions supported: ImageFormat(), ImageAlphaMask(), ImageToPOT()" ON) -option(SUPPORT_FILEFORMAT_PNG "Support loading PNG as textures" ON) -option(SUPPORT_FILEFORMAT_DDS "Support loading DDS as textures" ON) -option(SUPPORT_FILEFORMAT_HDR "Support loading HDR as textures" ON) -option(SUPPORT_FILEFORMAT_KTX "Support loading KTX as textures" ON) -option(SUPPORT_FILEFORMAT_ASTC "Support loading ASTC as textures" ON) -option(SUPPORT_FILEFORMAT_BMP "Support loading BMP as textures" ${OFF}) -option(SUPPORT_FILEFORMAT_TGA "Support loading TGA as textures" ${OFF}) -option(SUPPORT_FILEFORMAT_JPG "Support loading JPG as textures" ${OFF}) -option(SUPPORT_FILEFORMAT_GIF "Support loading GIF as textures" ${OFF}) -option(SUPPORT_FILEFORMAT_PSD "Support loading PSD as textures" ${OFF}) -option(SUPPORT_FILEFORMAT_PKM "Support loading PKM as textures" ${OFF}) -option(SUPPORT_FILEFORMAT_PVR "Support loading PVR as textures" ${OFF}) +cmake_dependent_option(SUPPORT_IMAGE_EXPORT "Support image exporting to file" ON CUSTOMIZE_BUILD ON) +cmake_dependent_option(SUPPORT_IMAGE_GENERATION "Support procedural image generation functionality (gradient, spot, perlin-noise, cellular)" ON CUSTOMIZE_BUILD ON) +cmake_dependent_option(SUPPORT_IMAGE_MANIPULATION "Support multiple image editing functions to scale, adjust colors, flip, draw on images, crop... If not defined only three image editing functions supported: ImageFormat(), ImageAlphaMask(), ImageToPOT()" ON CUSTOMIZE_BUILD ON) +cmake_dependent_option(SUPPORT_FILEFORMAT_PNG "Support loading PNG as textures" ON CUSTOMIZE_BUILD ON) +cmake_dependent_option(SUPPORT_FILEFORMAT_DDS "Support loading DDS as textures" ON CUSTOMIZE_BUILD ON) +cmake_dependent_option(SUPPORT_FILEFORMAT_HDR "Support loading HDR as textures" ON CUSTOMIZE_BUILD ON) +cmake_dependent_option(SUPPORT_FILEFORMAT_KTX "Support loading KTX as textures" ON CUSTOMIZE_BUILD ON) +cmake_dependent_option(SUPPORT_FILEFORMAT_ASTC "Support loading ASTC as textures" ON CUSTOMIZE_BUILD ON) +cmake_dependent_option(SUPPORT_FILEFORMAT_BMP "Support loading BMP as textures" ${OFF} CUSTOMIZE_BUILD OFF) +cmake_dependent_option(SUPPORT_FILEFORMAT_TGA "Support loading TGA as textures" ${OFF} CUSTOMIZE_BUILD OFF) +cmake_dependent_option(SUPPORT_FILEFORMAT_JPG "Support loading JPG as textures" ${OFF} CUSTOMIZE_BUILD OFF) +cmake_dependent_option(SUPPORT_FILEFORMAT_GIF "Support loading GIF as textures" ${OFF} CUSTOMIZE_BUILD OFF) +cmake_dependent_option(SUPPORT_FILEFORMAT_PSD "Support loading PSD as textures" ${OFF} CUSTOMIZE_BUILD OFF) +cmake_dependent_option(SUPPORT_FILEFORMAT_PKM "Support loading PKM as textures" ${OFF} CUSTOMIZE_BUILD OFF) +cmake_dependent_option(SUPPORT_FILEFORMAT_PVR "Support loading PVR as textures" ${OFF} CUSTOMIZE_BUILD OFF) # text.c -option(SUPPORT_FILEFORMAT_FNT "Support loading fonts in FNT format" ON) -option(SUPPORT_FILEFORMAT_TTF "Support loading font in TTF/OTF format" ON) -option(SUPPORT_TEXT_MANIPULATION "Support text manipulation functions" ON) +cmake_dependent_option(SUPPORT_FILEFORMAT_FNT "Support loading fonts in FNT format" ON CUSTOMIZE_BUILD ON) +cmake_dependent_option(SUPPORT_FILEFORMAT_TTF "Support loading font in TTF/OTF format" ON CUSTOMIZE_BUILD ON) +cmake_dependent_option(SUPPORT_TEXT_MANIPULATION "Support text manipulation functions" ON CUSTOMIZE_BUILD ON) # models.c -option(SUPPORT_MESH_GENERATION "Support procedural mesh generation functions, uses external par_shapes.h library. NOTE: Some generated meshes DO NOT include generated texture coordinates" ON) -option(SUPPORT_FILEFORMAT_OBJ "Support loading OBJ file format" ON) -option(SUPPORT_FILEFORMAT_MTL "Support loading MTL file format" ON) -option(SUPPORT_FILEFORMAT_IQM "Support loading IQM file format" ON) -option(SUPPORT_FILEFORMAT_GLTF "Support loading GLTF file format" ON) +cmake_dependent_option(SUPPORT_MESH_GENERATION "Support procedural mesh generation functions, uses external par_shapes.h library. NOTE: Some generated meshes DO NOT include generated texture coordinates" ON CUSTOMIZE_BUILD ON) +cmake_dependent_option(SUPPORT_FILEFORMAT_OBJ "Support loading OBJ file format" ON CUSTOMIZE_BUILD ON) +cmake_dependent_option(SUPPORT_FILEFORMAT_MTL "Support loading MTL file format" ON CUSTOMIZE_BUILD ON) +cmake_dependent_option(SUPPORT_FILEFORMAT_IQM "Support loading IQM file format" ON CUSTOMIZE_BUILD ON) +cmake_dependent_option(SUPPORT_FILEFORMAT_GLTF "Support loading GLTF file format" ON CUSTOMIZE_BUILD ON) # raudio.c -option(SUPPORT_FILEFORMAT_WAV "Support loading WAV for sound" ON) -option(SUPPORT_FILEFORMAT_OGG "Support loading OGG for sound" ON) -option(SUPPORT_FILEFORMAT_XM "Support loading XM for sound" ON) -option(SUPPORT_FILEFORMAT_MOD "Support loading MOD for sound" ON) -option(SUPPORT_FILEFORMAT_MP3 "Support loading MP3 for sound" ON) -option(SUPPORT_FILEFORMAT_FLAC "Support loading FLAC for sound" ${OFF}) +cmake_dependent_option(SUPPORT_FILEFORMAT_WAV "Support loading WAV for sound" ON CUSTOMIZE_BUILD ON) +cmake_dependent_option(SUPPORT_FILEFORMAT_OGG "Support loading OGG for sound" ON CUSTOMIZE_BUILD ON) +cmake_dependent_option(SUPPORT_FILEFORMAT_XM "Support loading XM for sound" ON CUSTOMIZE_BUILD ON) +cmake_dependent_option(SUPPORT_FILEFORMAT_MOD "Support loading MOD for sound" ON CUSTOMIZE_BUILD ON) +cmake_dependent_option(SUPPORT_FILEFORMAT_MP3 "Support loading MP3 for sound" ON CUSTOMIZE_BUILD ON) +cmake_dependent_option(SUPPORT_FILEFORMAT_FLAC "Support loading FLAC for sound" ${OFF} CUSTOMIZE_BUILD OFF) # utils.c -option(SUPPORT_TRACELOG "Show TraceLog() output messages. NOTE: By default LOG_DEBUG traces not shown" ON) +cmake_dependent_option(SUPPORT_TRACELOG "Show TraceLog() output messages. NOTE: By default LOG_DEBUG traces not shown" ON CUSTOMIZE_BUILD ON) diff --git a/cmake/BuildOptions.cmake b/cmake/BuildOptions.cmake index 00586c23c..0fce64292 100644 --- a/cmake/BuildOptions.cmake +++ b/cmake/BuildOptions.cmake @@ -1,24 +1,3 @@ -if(NOT (STATIC OR SHARED)) - message(FATAL_ERROR "Nothing to do if both -DSHARED=OFF and -DSTATIC=OFF...") -endif() - -if (DEFINED BUILD_SHARED_LIBS) - set(SHARED ${BUILD_SHARED_LIBS}) - if (${BUILD_SHARED_LIBS}) - set(STATIC OFF) - else() - set(STATIC ON) - endif() -endif() -if(DEFINED SHARED_RAYLIB) - set(SHARED ${SHARED_RAYLIB}) - message(DEPRECATION "-DSHARED_RAYLIB is deprecated. Please use -DSHARED instead.") -endif() -if(DEFINED STATIC_RAYLIB) - set(STATIC ${STATIC_RAYLIB}) - message(DEPRECATION "-DSTATIC_RAYLIB is deprecated. Please use -DSTATIC instead.") -endif() - if(${PLATFORM} MATCHES "Desktop" AND APPLE) if(MACOS_FATLIB) if (CMAKE_OSX_ARCHITECTURES) diff --git a/cmake/CompileDefinitions.cmake b/cmake/CompileDefinitions.cmake new file mode 100644 index 000000000..b07503c16 --- /dev/null +++ b/cmake/CompileDefinitions.cmake @@ -0,0 +1,109 @@ +# Adding compile definitions +target_compile_definitions("raylib" PUBLIC "${PLATFORM_CPP}") +target_compile_definitions("raylib" PUBLIC "${GRAPHICS}") + +function(define_if target variable) + if (${${variable}}) + target_compile_definitions(${target} PUBLIC "${variable}") + endif () +endfunction() + +if (${CUSTOMIZE_BUILD}) + target_compile_definitions("raylib" PUBLIC EXTERNAL_CONFIG_FLAGS) + define_if("raylib" SUPPORT_CAMERA_SYSTEM) + define_if("raylib" SUPPORT_GESTURES_SYSTEM) + define_if("raylib" SUPPORT_MOUSE_GESTURES) + define_if("raylib" SUPPORT_SSH_KEYBOARD_RPI) + define_if("raylib" SUPPORT_BUSY_WAIT_LOOP) + define_if("raylib" SUPPORT_EVENTS_WAITING) + define_if("raylib" SUPPORT_SCREEN_CAPTURE) + define_if("raylib" SUPPORT_GIF_RECORDING) + define_if("raylib" SUPPORT_HIGH_DPI) + define_if("raylib" SUPPORT_COMPRESSION_API) + define_if("raylib" SUPPORT_DATA_STORAGE) + define_if("raylib" SUPPORT_VR_SIMULATOR) + define_if("raylib" SUPPORT_FONT_TEXTURE) + define_if("raylib" SUPPORT_QUADS_DRAW_MODE) + define_if("raylib" SUPPORT_FILEFORMAT_PNG) + define_if("raylib" SUPPORT_FILEFORMAT_DDS) + define_if("raylib" SUPPORT_FILEFORMAT_HDR) + define_if("raylib" SUPPORT_FILEFORMAT_KTX) + define_if("raylib" SUPPORT_FILEFORMAT_ASTC) + define_if("raylib" SUPPORT_FILEFORMAT_BMP) + define_if("raylib" SUPPORT_FILEFORMAT_TGA) + define_if("raylib" SUPPORT_FILEFORMAT_JPG) + define_if("raylib" SUPPORT_FILEFORMAT_GIF) + define_if("raylib" SUPPORT_FILEFORMAT_PSD) + define_if("raylib" SUPPORT_FILEFORMAT_PKM) + define_if("raylib" SUPPORT_FILEFORMAT_PVR) + define_if("raylib" ORT_IMAGE_EXPORT) + define_if("raylib" SUPPORT_IMAGE_MANIPULATION) + define_if("raylib" SUPPORT_IMAGE_GENERATION) + define_if("raylib" SUPPORT_DEFAULT_FONT) + define_if("raylib" SUPPORT_FILEFORMAT_FNT) + define_if("raylib" SUPPORT_FILEFORMAT_TTF) + define_if("raylib" SUPPORT_TEXT_MANIPULATION) + define_if("raylib" SUPPORT_FILEFORMAT_OBJ) + define_if("raylib" SUPPORT_FILEFORMAT_MTL) + define_if("raylib" SUPPORT_FILEFORMAT_IQM) + define_if("raylib" SUPPORT_FILEFORMAT_GLTF) + define_if("raylib" SUPPORT_MESH_GENERATION) + define_if("raylib" SUPPORT_FILEFORMAT_WAV) + define_if("raylib" SUPPORT_FILEFORMAT_OGG) + define_if("raylib" SUPPORT_FILEFORMAT_XM) + define_if("raylib" SUPPORT_FILEFORMAT_MOD) + define_if("raylib" SUPPORT_FILEFORMAT_FLAC) + define_if("raylib" SUPPORT_FILEFORMAT_MP3) + define_if("raylib" SUPPORT_TRACELOG) + define_if("raylib" SUPPORT_COMPRESSION_API) + + + if (UNIX AND NOT APPLE) + target_compile_definitions("raylib" PUBLIC "MAX_FILEPATH_LENGTH=4096") + else () + target_compile_definitions("raylib" PUBLIC "MAX_FILEPATH_LENGTH=512") + endif () + + target_compile_definitions("raylib" PUBLIC "MAX_GAMEPADS=4") + target_compile_definitions("raylib" PUBLIC "MAX_GAMEPAD_AXIS=8") + target_compile_definitions("raylib" PUBLIC "MAX_GAMEPAD_BUTTONS=32") + target_compile_definitions("raylib" PUBLIC "MAX_TOUCH_POINTS=10") + target_compile_definitions("raylib" PUBLIC "MAX_KEY_PRESSED_QUEUE=16") + + target_compile_definitions("raylib" PUBLIC "STORAGE_DATA_FILE=\"storage.data\"") + target_compile_definitions("raylib" PUBLIC "MAX_KEY_PRESSED_QUEUE=16") + target_compile_definitions("raylib" PUBLIC "MAX_DECOMPRESSION_SIZE=64") + + if (${GRAPHICS} MATCHES "GRAPHICS_API_OPENGL_33" OR ${GRAPHICS} MATCHES "GRAPHICS_API_OPENGL_11") + target_compile_definitions("raylib" PUBLIC "DEFAULT_BATCH_BUFFER_ELEMENTS=8192") + elseif (${GRAPHICS} MATCHES "GRAPHICS_API_OPENGL_ES2") + target_compile_definitions("raylib" PUBLIC "DEFAULT_BATCH_BUFFER_ELEMENTS=2048") + endif () + + target_compile_definitions("raylib" PUBLIC "DEFAULT_BATCH_DRAWCALLS=256") + target_compile_definitions("raylib" PUBLIC "MAX_MATRIX_STACK_SIZE=32") + target_compile_definitions("raylib" PUBLIC "MAX_SHADER_LOCATIONS=32") + target_compile_definitions("raylib" PUBLIC "MAX_MATERIAL_MAPS=12") + target_compile_definitions("raylib" PUBLIC "RL_CULL_DISTANCE_NEAR=0.01") + target_compile_definitions("raylib" PUBLIC "RL_CULL_DISTANCE_FAR=1000.0") + + target_compile_definitions("raylib" PUBLIC "DEFAULT_SHADER_ATTRIB_NAME_POSITION=\"vertexPosition\"") + target_compile_definitions("raylib" PUBLIC "DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD=\"vertexTexCoord\"") + target_compile_definitions("raylib" PUBLIC "DEFAULT_SHADER_ATTRIB_NAME_NORMAL=\"vertexNormal\"") + target_compile_definitions("raylib" PUBLIC "DEFAULT_SHADER_ATTRIB_NAME_COLOR=\"vertexColor\"") + target_compile_definitions("raylib" PUBLIC "DEFAULT_SHADER_ATTRIB_NAME_TANGENT=\"vertexTangent\"") + target_compile_definitions("raylib" PUBLIC "DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD2=\"vertexTexCoord2\"") + + target_compile_definitions("raylib" PUBLIC "MAX_TEXT_BUFFER_LENGTH=1024") + target_compile_definitions("raylib" PUBLIC "MAX_TEXT_UNICODE_CHARS=512") + target_compile_definitions("raylib" PUBLIC "MAX_TEXTSPLIT_COUNT=128") + + target_compile_definitions("raylib" PUBLIC "AUDIO_DEVICE_FORMAT=ma_format_f32") + target_compile_definitions("raylib" PUBLIC "AUDIO_DEVICE_CHANNELS=2") + target_compile_definitions("raylib" PUBLIC "AUDIO_DEVICE_SAMPLE_RATE=44100") + target_compile_definitions("raylib" PUBLIC "DEFAULT_AUDIO_BUFFER_SIZE=4096") + + target_compile_definitions("raylib" PUBLIC "MAX_TRACELOG_MSG_LENGTH=128") + target_compile_definitions("raylib" PUBLIC "MAX_UWP_MESSAGES=512") +endif () + diff --git a/cmake/CompilerFlags.cmake b/cmake/CompilerFlags.cmake index 41fee6922..970462c8b 100644 --- a/cmake/CompilerFlags.cmake +++ b/cmake/CompilerFlags.cmake @@ -1,28 +1,52 @@ include(AddIfFlagCompiles) +# Makes +/- operations on void pointers be considered an error +# https://gcc.gnu.org/onlinedocs/gcc/Pointer-Arith.html add_if_flag_compiles(-Werror=pointer-arith CMAKE_C_FLAGS) + +# Generates error whenever a function is used before being declared +# https://gcc.gnu.org/onlinedocs/gcc-4.0.1/gcc/Warning-Options.html add_if_flag_compiles(-Werror=implicit-function-declaration CMAKE_C_FLAGS) -# src/external/jar_xm.h does shady stuff + +# Allows some casting of pointers without generating a warning add_if_flag_compiles(-fno-strict-aliasing CMAKE_C_FLAGS) -if (ENABLE_ASAN) - add_if_flag_compiles(-fno-omit-frame-pointer CMAKE_C_FLAGS CMAKE_LINKER_FLAGS) - add_if_flag_compiles(-fsanitize=address CMAKE_C_FLAGS CMAKE_LINKER_FLAGS) -endif() -if (ENABLE_UBSAN) - add_if_flag_compiles(-fno-omit-frame-pointer CMAKE_C_FLAGS CMAKE_LINKER_FLAGS) - add_if_flag_compiles(-fsanitize=undefined CMAKE_C_FLAGS CMAKE_LINKER_FLAGS) -endif() -if (ENABLE_MSAN) - add_if_flag_compiles(-fno-omit-frame-pointer CMAKE_C_FLAGS CMAKE_LINKER_FLAGS) - add_if_flag_compiles(-fsanitize=memory CMAKE_C_FLAGS CMAKE_LINKER_FLAGS) -endif() - if (ENABLE_MSAN AND ENABLE_ASAN) + # MSAN and ASAN both work on memory - ASAN does more things MESSAGE(WARNING "Compiling with both AddressSanitizer and MemorySanitizer is not recommended") endif() -add_definitions("-DRAYLIB_CMAKE=1") +if (ENABLE_ASAN) + + # If enabled it would generate errors/warnings for all kinds of memory errors + # (like returning a stack variable by reference) + # https://clang.llvm.org/docs/AddressSanitizer.html + + add_if_flag_compiles(-fno-omit-frame-pointer CMAKE_C_FLAGS CMAKE_LINKER_FLAGS) + add_if_flag_compiles(-fsanitize=address CMAKE_C_FLAGS CMAKE_LINKER_FLAGS) + +endif() + +if (ENABLE_UBSAN) + + # If enabled this will generate errors for undefined behavior points + # (like adding +1 to the maximum int value) + # https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html + + add_if_flag_compiles(-fno-omit-frame-pointer CMAKE_C_FLAGS CMAKE_LINKER_FLAGS) + add_if_flag_compiles(-fsanitize=undefined CMAKE_C_FLAGS CMAKE_LINKER_FLAGS) + +endif() + +if (ENABLE_MSAN) + + # If enabled this will generate warnings for places where uninitialized memory is used + # https://clang.llvm.org/docs/MemorySanitizer.html + + add_if_flag_compiles(-fno-omit-frame-pointer CMAKE_C_FLAGS CMAKE_LINKER_FLAGS) + add_if_flag_compiles(-fsanitize=memory CMAKE_C_FLAGS CMAKE_LINKER_FLAGS) + +endif() if(CMAKE_VERSION VERSION_LESS "3.1") if(CMAKE_C_COMPILER_ID STREQUAL "GNU") @@ -31,3 +55,25 @@ if(CMAKE_VERSION VERSION_LESS "3.1") else() set (CMAKE_C_STANDARD 99) endif() + +if(${PLATFORM} MATCHES "Android") + + # If enabled will remove dead code during the linking process + # https://gcc.gnu.org/onlinedocs/gnat_ugn/Compilation-options.html + add_if_flag_compiles(-ffunction-sections CMAKE_C_FLAGS) + + # If enabled will generate some exception data (usually disabled for C programs) + # https://gcc.gnu.org/onlinedocs/gcc-4.2.4/gcc/Code-Gen-Options.html + add_if_flag_compiles(-funwind-tables CMAKE_C_FLAGS) + + # If enabled adds stack protection guards around functions that allocate memory + # https://www.keil.com/support/man/docs/armclang_ref/armclang_ref_cjh1548250046139.htm + add_if_flag_compiles(-fstack-protector-strong CMAKE_C_FLAGS) + + # Marks that the library will not be compiled with an executable stack + add_if_flag_compiles(-Wa,--noexecstack CMAKE_C_FLAGS) + + # Do not expand symbolic links or resolve paths like "/./" or "/../", etc. + # https://gcc.gnu.org/onlinedocs/gcc/Directory-Options.html + add_if_flag_compiles(-no-canonical-prefixes CMAKE_C_FLAGS) +endif() diff --git a/cmake/GlfwImport.cmake b/cmake/GlfwImport.cmake index 12dbfeb9f..b740884f7 100644 --- a/cmake/GlfwImport.cmake +++ b/cmake/GlfwImport.cmake @@ -16,14 +16,19 @@ if(NOT glfw3_FOUND AND NOT USE_EXTERNAL_GLFW STREQUAL "ON" AND "${PLATFORM}" MAT set(GLFW_BUILD_TESTS OFF CACHE BOOL "" FORCE) set(GLFW_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) set(GLFW_INSTALL OFF CACHE BOOL "" FORCE) - set(BUILD_SHARED_LIBS OFF CACHE BOOL " " FORCE) set(GLFW_USE_WAYLAND ${USE_WAYLAND} CACHE BOOL "" FORCE) + set(WAS_SHARED ${BUILD_SHARED_LIBS}) + set(BUILD_SHARED_LIBS OFF CACHE BOOL " " FORCE) + add_subdirectory(external/glfw) + + set(BUILD_SHARED_LIBS ${WAS_SHARED} CACHE BOOL " " FORCE) + unset(WAS_SHARED) list(APPEND raylib_sources $) include_directories(BEFORE SYSTEM external/glfw/include) else() MESSAGE(STATUS "Using external GLFW") set(GLFW_PKG_DEPS glfw3) -endif() \ No newline at end of file +endif() diff --git a/cmake/InstallConfigurations.cmake b/cmake/InstallConfigurations.cmake index a26fedf55..6a89ad55c 100644 --- a/cmake/InstallConfigurations.cmake +++ b/cmake/InstallConfigurations.cmake @@ -7,12 +7,12 @@ install( ) # PKG_CONFIG_LIBS_PRIVATE is used in raylib.pc.in -if (STATIC) +if (NOT BUILD_SHARED_LIBS) include(LibraryPathToLinkerFlags) library_path_to_linker_flags(__PKG_CONFIG_LIBS_PRIVATE "${LIBS_PRIVATE}") set(PKG_CONFIG_LIBS_PRIVATE ${__PKG_CONFIG_LIBS_PRIVATE} ${GLFW_PKG_LIBS}) string(REPLACE ";" " " PKG_CONFIG_LIBS_PRIVATE "${PKG_CONFIG_LIBS_PRIVATE}") -elseif (SHARED) +elseif (BUILD_SHARED_LIBS) set(PKG_CONFIG_LIBS_EXTRA "") endif () diff --git a/cmake/LibraryConfigurations.cmake b/cmake/LibraryConfigurations.cmake index 8cca24649..1b1961b9b 100644 --- a/cmake/LibraryConfigurations.cmake +++ b/cmake/LibraryConfigurations.cmake @@ -1,12 +1,7 @@ - -### Config options ### -# Translate the config options to what raylib wants -configure_file(config.h.in ${CMAKE_BINARY_DIR}/cmake/config.h) - -if(${PLATFORM} MATCHES "Desktop") +if (${PLATFORM} MATCHES "Desktop") set(PLATFORM_CPP "PLATFORM_DESKTOP") - if(APPLE) + if (APPLE) # Need to force OpenGL 3.3 on OS X # See: https://github.com/raysan5/raylib/issues/341 set(GRAPHICS "GRAPHICS_API_OPENGL_33") @@ -16,40 +11,35 @@ if(${PLATFORM} MATCHES "Desktop") if (NOT CMAKE_SYSTEM STRLESS "Darwin-18.0.0") add_definitions(-DGL_SILENCE_DEPRECATION) MESSAGE(AUTHOR_WARNING "OpenGL is deprecated starting with macOS 10.14 (Mojave)!") - endif() - elseif(WIN32) + endif () + elseif (WIN32) add_definitions(-D_CRT_SECURE_NO_WARNINGS) set(LIBS_PRIVATE ${LIBS_PRIVATE} winmm) - else() + else () find_library(pthread NAMES pthread) find_package(OpenGL QUIET) if ("${OPENGL_LIBRARIES}" STREQUAL "") set(OPENGL_LIBRARIES "GL") - endif() + endif () if ("${CMAKE_SYSTEM_NAME}" MATCHES "(Net|Open)BSD") find_library(OSS_LIBRARY ossaudio) - endif() + endif () set(LIBS_PRIVATE m pthread ${OPENGL_LIBRARIES} ${OSS_LIBRARY}) - endif() + endif () -elseif(${PLATFORM} MATCHES "Web") +elseif (${PLATFORM} MATCHES "Web") set(PLATFORM_CPP "PLATFORM_WEB") set(GRAPHICS "GRAPHICS_API_OPENGL_ES2") - set(CMAKE_C_FLAGS "-s USE_GLFW=3 -s ASSERTIONS=1 --profiling") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -s USE_GLFW=3 -s ASSERTIONS=1 --profiling") set(CMAKE_STATIC_LIBRARY_SUFFIX ".a") -elseif(${PLATFORM} MATCHES "Android") +elseif (${PLATFORM} MATCHES "Android") set(PLATFORM_CPP "PLATFORM_ANDROID") set(GRAPHICS "GRAPHICS_API_OPENGL_ES2") - include(AddIfFlagCompiles) - add_if_flag_compiles(-ffunction-sections CMAKE_C_FLAGS) - add_if_flag_compiles(-funwind-tables CMAKE_C_FLAGS) - add_if_flag_compiles(-fstack-protector-strong CMAKE_C_FLAGS) set(CMAKE_POSITION_INDEPENDENT_CODE ON) - add_if_flag_compiles(-Wa,--noexecstack CMAKE_C_FLAGS) - add_if_flag_compiles(-no-canonical-prefixes CMAKE_C_FLAGS) + add_definitions(-DANDROID -D__ANDROID_API__=21) include_directories(external/android/native_app_glue) set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,--exclude-libs,libatomic.a -Wl,--build-id -Wl,-z,noexecstack -Wl,-z,relro -Wl,-z,now -Wl,--warn-shared-textrel -Wl,--fatal-warnings -uANativeActivity_onCreate") @@ -57,7 +47,7 @@ elseif(${PLATFORM} MATCHES "Android") find_library(OPENGL_LIBRARY OpenGL) set(LIBS_PRIVATE m log android EGL GLESv2 OpenSLES atomic c) -elseif(${PLATFORM} MATCHES "Raspberry Pi") +elseif (${PLATFORM} MATCHES "Raspberry Pi") set(PLATFORM_CPP "PLATFORM_RPI") set(GRAPHICS "GRAPHICS_API_OPENGL_ES2") @@ -70,7 +60,7 @@ elseif(${PLATFORM} MATCHES "Raspberry Pi") link_directories(/opt/vc/lib) set(LIBS_PRIVATE ${GLESV2} ${EGL} ${BCMHOST} pthread rt m dl) -elseif(${PLATFORM} MATCHES "DRM") +elseif (${PLATFORM} MATCHES "DRM") set(PLATFORM_CPP "PLATFORM_DRM") set(GRAPHICS "GRAPHICS_API_OPENGL_ES2") @@ -86,7 +76,7 @@ elseif(${PLATFORM} MATCHES "DRM") include_directories(/usr/include/libdrm) set(LIBS_PRIVATE ${GLESV2} ${EGL} ${DRM} ${GBM} pthread m dl) -endif() +endif () if (${OPENGL_VERSION}) set(${SUGGESTED_GRAPHICS} "${GRAPHICS}") @@ -98,12 +88,18 @@ if (${OPENGL_VERSION}) set(GRAPHICS "GRAPHICS_API_OPENGL_11") elseif (${OPENGL_VERSION} MATCHES "ES 2.0") set(GRAPHICS "GRAPHICS_API_OPENGL_ES2") - endif() + endif () if ("${SUGGESTED_GRAPHICS}" AND NOT "${SUGGESTED_GRAPHICS}" STREQUAL "${GRAPHICS}") message(WARNING "You are overriding the suggested GRAPHICS=${SUGGESTED_GRAPHICS} with ${GRAPHICS}! This may fail") - endif() -endif() + endif () +endif () -if(NOT GRAPHICS) +if (NOT GRAPHICS) set(GRAPHICS "GRAPHICS_API_OPENGL_33") -endif() \ No newline at end of file +endif () + +set(LIBS_PRIVATE ${LIBS_PRIVATE} ${OPENAL_LIBRARY}) + +if (${PLATFORM} MATCHES "Desktop") + set(LIBS_PRIVATE ${LIBS_PRIVATE} glfw) +endif () \ No newline at end of file diff --git a/cmake/test-pkgconfig.sh b/cmake/test-pkgconfig.sh deleted file mode 100755 index ccbdfb652..000000000 --- a/cmake/test-pkgconfig.sh +++ /dev/null @@ -1,21 +0,0 @@ -#!/bin/sh -# Test if including/linking/running an installed raylib works - -set -x -export LD_RUN_PATH=/usr/local/lib - -CFLAGS="-Wall -Wextra -Werror $CFLAGS" -if [ "$ARCH" = "i386" ]; then -CFLAGS="-m32 $CLFAGS" -fi - -cat << EOF | ${CC:-cc} -otest -xc - $(pkg-config --libs --cflags $@ raylib.pc) $CFLAGS && exec ./test -#include -#include - -int main(void) -{ - int num = GetRandomValue(42, 1337); - return 42 <= num && num <= 1337 ? EXIT_SUCCESS : EXIT_FAILURE; -} -EOF diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index e3ef3a0fc..ad391edd4 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -1,122 +1,138 @@ # Setup the project and settings project(examples) -# Get the sources together -set(example_dirs audio core models others shaders shapes text textures) +# Directories that contain examples +set(example_dirs + audio + core + models + others + shaders + shapes + text + textures + ) + +# Next few lines will check for existence of symbols or header files +# They are needed for the physac example and threads examples set(CMAKE_REQUIRED_DEFINITIONS -D_POSIX_C_SOURCE=199309L) - include(CheckSymbolExists) - check_symbol_exists(CLOCK_MONOTONIC time.h HAVE_CLOCK_MONOTONIC) - check_symbol_exists(QueryPerformanceCounter windows.h HAVE_QPC) +include(CheckSymbolExists) +check_symbol_exists(CLOCK_MONOTONIC time.h HAVE_CLOCK_MONOTONIC) +check_symbol_exists(QueryPerformanceCounter windows.h HAVE_QPC) set(CMAKE_REQUIRED_DEFINITIONS) -if(HAVE_QPC OR HAVE_CLOCK_MONOTONIC) - set(example_dirs ${example_dirs} physac) -endif() -set(example_sources) -set(example_resources) -foreach(example_dir ${example_dirs}) - # Get the .c files - file(GLOB sources ${example_dir}/*.c) - list(APPEND example_sources ${sources}) - - # Any any resources - file(GLOB resources ${example_dir}/resources/*) - list(APPEND example_resources ${resources}) -endforeach() - -if (APPLE AND NOT CMAKE_SYSTEM STRLESS "Darwin-18.0.0") - add_definitions(-DGL_SILENCE_DEPRECATION) - MESSAGE(AUTHOR_WARNING "OpenGL is deprecated starting with macOS 10.14 (Mojave)!") -endif() +if (HAVE_QPC OR HAVE_CLOCK_MONOTONIC) + set(example_dirs ${example_dirs} physac) +endif () include(CheckIncludeFile) CHECK_INCLUDE_FILE("stdatomic.h" HAVE_STDATOMIC_H) set(CMAKE_THREAD_PREFER_PTHREAD TRUE) find_package(Threads) if (CMAKE_USE_PTHREADS_INIT AND HAVE_STDATOMIC_H) - add_if_flag_compiles("-std=c11" CMAKE_C_FLAGS) - if(THREADS_HAVE_PTHREAD_ARG) - add_if_flag_compiles("-pthread" CMAKE_C_FLAGS) - endif() - if(CMAKE_THREAD_LIBS_INIT) - link_libraries("${CMAKE_THREAD_LIBS_INIT}") - endif() -else() - # Items requiring pthreads - list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/core/core_loading_thread.c) -endif() + add_if_flag_compiles("-std=c11" CMAKE_C_FLAGS) + if (THREADS_HAVE_PTHREAD_ARG) + add_if_flag_compiles("-pthread" CMAKE_C_FLAGS) + endif () + if (CMAKE_THREAD_LIBS_INIT) + link_libraries("${CMAKE_THREAD_LIBS_INIT}") + endif () +endif () +if (APPLE AND NOT CMAKE_SYSTEM STRLESS "Darwin-18.0.0") + add_definitions(-DGL_SILENCE_DEPRECATION) + MESSAGE(AUTHOR_WARNING "OpenGL is deprecated starting with macOS 10.14 (Mojave)!") +endif () -if(${PLATFORM} MATCHES "Android") - list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/others/rlgl_standalone.c) - list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/others/standard_lighting.c) - list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/core/core_3d_picking.c) - list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/core/core_vr_simulator.c) - list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/core/core_3d_camera_free.c) - list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/core/core_3d_camera_first_person.c) - list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/core/core_world_screen.c) +# Collect all source files and resource files +# into a CMake variable +set(example_sources) +set(example_resources) +foreach (example_dir ${example_dirs}) + # Get the .c files + file(GLOB sources ${example_dir}/*.c) + list(APPEND example_sources ${sources}) + + # Any any resources + file(GLOB resources ${example_dir}/resources/*) + list(APPEND example_resources ${resources}) +endforeach () - list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/models/models_mesh_picking.c) - list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/models/models_material_pbr.c) - list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/models/models_cubicmap.c) - list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/models/models_skybox.c) - list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/models/models_mesh_picking.c) - list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/models/models_mesh_generation.c) - list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/models/models_heightmap.c) - list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/models/models_billboard.c) - list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/models/models_rlgl_solar_system.c) - list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/models/models_rlgl_full_solar_system.c) - list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/models/models_solar_system.c) - list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/models/models_obj_viewer.c) - list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/models/models_animation.c) - list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/models/models_first_person_maze.c) +if(NOT CMAKE_USE_PTHREADS_INIT OR NOT HAVE_STDATOMIC_H) + # Items requiring pthreads + list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/core/core_loading_thread.c) +endif () - list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/shaders/shaders_custom_uniform.c) - list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/shaders/shaders_model_shader.c) - list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/shaders/shaders_postprocessing.c) - list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/shaders/shaders_raymarching.c) - list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/shaders/shaders_palette_switch.c) - list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/shaders/shaders_basic_lighting.c) +if (${PLATFORM} MATCHES "Android") + list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/others/rlgl_standalone.c) + list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/others/standard_lighting.c) + list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/core/core_3d_picking.c) + list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/core/core_vr_simulator.c) + list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/core/core_3d_camera_free.c) + list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/core/core_3d_camera_first_person.c) + list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/core/core_world_screen.c) + + list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/models/models_mesh_picking.c) + list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/models/models_material_pbr.c) + list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/models/models_cubicmap.c) + list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/models/models_skybox.c) + list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/models/models_mesh_picking.c) + list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/models/models_mesh_generation.c) + list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/models/models_heightmap.c) + list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/models/models_billboard.c) + list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/models/models_rlgl_solar_system.c) + list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/models/models_rlgl_full_solar_system.c) + list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/models/models_solar_system.c) + list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/models/models_obj_viewer.c) + list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/models/models_animation.c) + list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/models/models_first_person_maze.c) + + list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/shaders/shaders_custom_uniform.c) + list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/shaders/shaders_model_shader.c) + list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/shaders/shaders_postprocessing.c) + list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/shaders/shaders_raymarching.c) + list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/shaders/shaders_palette_switch.c) + list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/shaders/shaders_basic_lighting.c) -elseif(${PLATFORM} MATCHES "Web") - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Os -s USE_GLFW=3 -s ASSERTIONS=1 -s WASM=1 -s ASYNCIFY") - # Since WASM is used, ALLOW_MEMORY_GROWTH has no extra overheads - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -s ALLOW_MEMORY_GROWTH=1 --no-heap-copy") - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} --shell-file ${CMAKE_SOURCE_DIR}/src/shell.html") - set(CMAKE_EXECUTABLE_SUFFIX ".html") - - # Remove the -rdynamic flag because otherwise emscripten - # does not generate HTML+JS+WASM files, only a non-working - # and fat HTML - string(REPLACE "-rdynamic" "" CMAKE_SHARED_LIBRARY_LINK_C_FLAGS "${CMAKE_SHARED_LIBRARY_LINK_C_FLAGS}") -endif() +elseif (${PLATFORM} MATCHES "Web") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Os -s USE_GLFW=3 -s ASSERTIONS=1 -s WASM=1 -s ASYNCIFY") + # Since WASM is used, ALLOW_MEMORY_GROWTH has no extra overheads + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -s ALLOW_MEMORY_GROWTH=1 --no-heap-copy") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} --shell-file ${CMAKE_SOURCE_DIR}/src/shell.html") + set(CMAKE_EXECUTABLE_SUFFIX ".html") + + # Remove the -rdynamic flag because otherwise emscripten + # does not generate HTML+JS+WASM files, only a non-working + # and fat HTML + string(REPLACE "-rdynamic" "" CMAKE_SHARED_LIBRARY_LINK_C_FLAGS "${CMAKE_SHARED_LIBRARY_LINK_C_FLAGS}") +endif () include_directories(BEFORE SYSTEM others/external/include) if (NOT TARGET raylib) - find_package(raylib 2.0 REQUIRED) -endif() + find_package(raylib 2.0 REQUIRED) +endif () # Do each example -foreach(example_source ${example_sources}) - # Create the basename for the example - get_filename_component(example_name ${example_source} NAME) - string(REPLACE ".c" "" example_name ${example_name}) - - # Setup the example - add_executable(${example_name} ${example_source}) - - target_link_libraries(${example_name} raylib) - - string(REGEX MATCH ".*/.*/" resources_dir ${example_source}) - string(APPEND resources_dir "resources") - - if(${PLATFORM} MATCHES "Web" AND EXISTS ${resources_dir}) - # The local resources path needs to be mapped to /resources virtual path - string(APPEND resources_dir "@resources") - set_target_properties(${example_name} PROPERTIES LINK_FLAGS "--preload-file ${resources_dir}") - endif() -endforeach() +foreach (example_source ${example_sources}) + # Create the basename for the example + get_filename_component(example_name ${example_source} NAME) + string(REPLACE ".c" "" example_name ${example_name}) + + # Setup the example + add_executable(${example_name} ${example_source}) + + target_link_libraries(${example_name} raylib) + + string(REGEX MATCH ".*/.*/" resources_dir ${example_source}) + string(APPEND resources_dir "resources") + + if (${PLATFORM} MATCHES "Web" AND EXISTS ${resources_dir}) + # The local resources path needs to be mapped to /resources virtual path + string(APPEND resources_dir "@resources") + set_target_properties(${example_name} PROPERTIES LINK_FLAGS "--preload-file ${resources_dir}") + endif () +endforeach () # Copy all of the resource files to the destination file(COPY ${example_resources} DESTINATION "resources/") diff --git a/examples/models/models_first_person_maze.c b/examples/models/models_first_person_maze.c index 07c51b9ad..2d37e978c 100644 --- a/examples/models/models_first_person_maze.c +++ b/examples/models/models_first_person_maze.c @@ -35,7 +35,7 @@ int main(void) model.materials[0].maps[MAP_DIFFUSE].texture = texture; // Set map diffuse texture // Get map image data to be used for collision detection - Color *mapPixels = GetImageData(imMap); + Color *mapPixels = LoadImageColors(imMap); UnloadImage(imMap); // Unload image from RAM Vector3 mapPosition = { -16.0f, 0.0f, -8.0f }; // Set model position @@ -113,13 +113,13 @@ int main(void) // De-Initialization //-------------------------------------------------------------------------------------- - free(mapPixels); // Unload color array + UnloadImageColors(mapPixels); // Unload color array - UnloadTexture(cubicmap); // Unload cubicmap texture - UnloadTexture(texture); // Unload map texture - UnloadModel(model); // Unload map model + UnloadTexture(cubicmap); // Unload cubicmap texture + UnloadTexture(texture); // Unload map texture + UnloadModel(model); // Unload map model - CloseWindow(); // Close window and OpenGL context + CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- return 0; diff --git a/examples/models/models_gltf_animation.c b/examples/models/models_gltf_animation.c new file mode 100644 index 000000000..e31205002 --- /dev/null +++ b/examples/models/models_gltf_animation.c @@ -0,0 +1,115 @@ +/******************************************************************************************* +* +* raylib [models] example - Load 3d gltf model with animations and play them +* +* This example has been created using raylib 3.5 (www.raylib.com) +* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) +* +* Example contributed by Hristo Stamenov (@object71) and reviewed by Ramon Santamaria (@raysan5) +* +* Copyright (c) 2021 Hristo Stamenov (@object71) and Ramon Santamaria (@raysan5) +* +******************************************************************************************** +* +* To export a model from blender, make sure it is not posed, the vertices need to be in the +* same position as they would be in edit mode. +* and that the scale of your models is set to 0. Scaling can be done from the export menu. +* +********************************************************************************************/ + +#include "raylib.h" + +#include + + +int main(void) +{ + // Initialization + //-------------------------------------------------------------------------------------- + const int screenWidth = 800; + const int screenHeight = 450; + + InitWindow(screenWidth, screenHeight, "raylib [models] example - model animation"); + + // Define the camera to look into our 3d world + Camera camera = { 0 }; + camera.position = (Vector3){ 10.0f, 10.0f, 10.0f }; // Camera position + camera.target = (Vector3){ 0.0f, 0.0f, 0.0f }; // Camera looking at point + camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target) + camera.fovy = 45.0f; // Camera field-of-view Y + camera.type = CAMERA_PERSPECTIVE; // Camera mode type + + Model model = LoadModel("resources/gltf/rigged_figure.glb"); // Load the animated model mesh and + // basic data +// Texture2D texture = LoadTexture("resources/guy/guytex.png"); // Load model texture and set material +// SetMaterialTexture(&model.materials[0], MAP_DIFFUSE, texture); // Set model material map texture + + Vector3 position = { 0.0f, 0.0f, 0.0f }; // Set model position + + // Load animation data + int animsCount = 0; + ModelAnimation *anims = LoadModelAnimations("resources/gltf/rigged_figure.glb", &animsCount); + int animFrameCounter = 0; + + SetCameraMode(camera, CAMERA_FREE); // Set free camera mode + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second + //-------------------------------------------------------------------------------------- + + // Main game loop + while (!WindowShouldClose()) // Detect window close button or ESC key + { + // Update + //---------------------------------------------------------------------------------- + UpdateCamera(&camera); + + // Play animation when spacebar is held down + if (IsKeyDown(KEY_SPACE)) + { + animFrameCounter++; + UpdateModelAnimation(model, anims[0], animFrameCounter); + if (animFrameCounter >= anims[0].frameCount) animFrameCounter = 0; + } + //---------------------------------------------------------------------------------- + + // Draw + //---------------------------------------------------------------------------------- + BeginDrawing(); + + ClearBackground(RAYWHITE); + + BeginMode3D(camera); + + DrawModelEx(model, position, (Vector3){ 1.0f, 0.0f, 0.0f }, -90.0f, (Vector3){ 1.0f, 1.0f, 1.0f }, WHITE); + + for (int i = 0; i < model.boneCount; i++) + { + DrawSphere(anims[0].framePoses[animFrameCounter][i].translation, 0.01f, RED); + } + + DrawGrid(10, 1.0f); // Draw a grid + + EndMode3D(); + + DrawText("PRESS SPACE to PLAY MODEL ANIMATION", 10, 10, 20, MAROON); + DrawText("(cc4) Rigged Figure by @Cesium", screenWidth - 200, screenHeight - 20, 10, GRAY); + + EndDrawing(); + //---------------------------------------------------------------------------------- + } + + // De-Initialization + //-------------------------------------------------------------------------------------- +// UnloadTexture(texture); // Unload texture + + // Unload model animations data + for (int i = 0; i < animsCount; i++) UnloadModelAnimation(anims[i]); + RL_FREE(anims); + + UnloadModel(model); // Unload model + + CloseWindow(); // Close window and OpenGL context + //-------------------------------------------------------------------------------------- + + return 0; +} diff --git a/examples/models/models_gltf_model.c b/examples/models/models_gltf_model.c new file mode 100644 index 000000000..c064e34f8 --- /dev/null +++ b/examples/models/models_gltf_model.c @@ -0,0 +1,87 @@ +/******************************************************************************************* +* +* raylib [models] example - Load 3d gltf model +* +* This example has been created using raylib 3.5 (www.raylib.com) +* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) +* +* Example contributed by Hristo Stamenov (@object71) and reviewed by Ramon Santamaria (@raysan5) +* +* Copyright (c) 2021 Hristo Stamenov (@object71) and Ramon Santamaria (@raysan5) +* +******************************************************************************************** +* +* To export a model from blender, make sure it is not posed, the vertices need to be in the +* same position as they would be in edit mode. +* and that the scale of your models is set to 0. Scaling can be done from the export menu. +* +********************************************************************************************/ + +#include "raylib.h" + +#include + + +int main(void) +{ + // Initialization + //-------------------------------------------------------------------------------------- + const int screenWidth = 800; + const int screenHeight = 450; + + InitWindow(screenWidth, screenHeight, "raylib [models] example - model animation"); + + // Define the camera to look into our 3d world + Camera camera = { 0 }; + camera.position = (Vector3){ 10.0f, 10.0f, 10.0f }; // Camera position + camera.target = (Vector3){ 0.0f, 0.0f, 0.0f }; // Camera looking at point + camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target) + camera.fovy = 45.0f; // Camera field-of-view Y + camera.type = CAMERA_PERSPECTIVE; // Camera mode type + + Model model = LoadModel("resources/gltf/Avocado.glb"); // Load the animated model mesh and + + Vector3 position = { 0.0f, 0.0f, 0.0f }; // Set model position + + SetCameraMode(camera, CAMERA_FREE); // Set free camera mode + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second + //-------------------------------------------------------------------------------------- + + // Main game loop + while (!WindowShouldClose()) // Detect window close button or ESC key + { + // Update + //---------------------------------------------------------------------------------- + UpdateCamera(&camera); + + // Draw + //---------------------------------------------------------------------------------- + BeginDrawing(); + + ClearBackground(RAYWHITE); + + BeginMode3D(camera); + + DrawModelEx(model, position, (Vector3){ 0.0f, 1.0f, 0.0f }, 180.0f, (Vector3){ 15.0f, 15.0f, 15.0f }, WHITE); + + DrawGrid(10, 1.0f); // Draw a grid + + EndMode3D(); + + DrawText("(cc0) Avocado by @Microsoft", screenWidth - 200, screenHeight - 20, 10, GRAY); + + EndDrawing(); + //---------------------------------------------------------------------------------- + } + + // De-Initialization + //-------------------------------------------------------------------------------------- + + UnloadModel(model); // Unload model + + CloseWindow(); // Close window and OpenGL context + //-------------------------------------------------------------------------------------- + + return 0; +} diff --git a/examples/models/resources/gltf/Avocado.glb b/examples/models/resources/gltf/Avocado.glb new file mode 100644 index 000000000..006b79c39 Binary files /dev/null and b/examples/models/resources/gltf/Avocado.glb differ diff --git a/examples/models/resources/gltf/LICENSE b/examples/models/resources/gltf/LICENSE new file mode 100644 index 000000000..77c73c62e --- /dev/null +++ b/examples/models/resources/gltf/LICENSE @@ -0,0 +1,11 @@ +Rigged Figure model has been created by Cesium (https://cesium.com/cesiumjs/), +and licensed as Creative Commons Attribution 4.0 International License. + +Check for details: http://creativecommons.org/licenses/by/4.0/ + +Avocado model is provided by Microsoft +and licensed as CC0 Universal Public Domain + +Check for details: https://creativecommons.org/publicdomain/zero/1.0/ + +GLTF sample models for testing are taken from: https://github.com/KhronosGroup/glTF-Sample-Models/ diff --git a/examples/models/resources/gltf/rigged_figure.glb b/examples/models/resources/gltf/rigged_figure.glb new file mode 100644 index 000000000..c505a33df Binary files /dev/null and b/examples/models/resources/gltf/rigged_figure.glb differ diff --git a/examples/models/resources/shaders/glsl330/brdf.fs b/examples/models/resources/shaders/glsl330/brdf.fs index d04bc6618..f2774f81c 100644 --- a/examples/models/resources/shaders/glsl330/brdf.fs +++ b/examples/models/resources/shaders/glsl330/brdf.fs @@ -41,27 +41,27 @@ float RadicalInverseVdC(uint bits) // Compute Hammersley coordinates vec2 Hammersley(uint i, uint N) { - return vec2(float(i)/float(N), RadicalInverseVdC(i)); + return vec2(float(i)/float(N), RadicalInverseVdC(i)); } // Integrate number of importance samples for (roughness and NoV) vec3 ImportanceSampleGGX(vec2 Xi, vec3 N, float roughness) { - float a = roughness*roughness; - float phi = 2.0 * PI * Xi.x; - float cosTheta = sqrt((1.0 - Xi.y)/(1.0 + (a*a - 1.0)*Xi.y)); - float sinTheta = sqrt(1.0 - cosTheta*cosTheta); + float a = roughness*roughness; + float phi = 2.0 * PI * Xi.x; + float cosTheta = sqrt((1.0 - Xi.y)/(1.0 + (a*a - 1.0)*Xi.y)); + float sinTheta = sqrt(1.0 - cosTheta*cosTheta); - // Transform from spherical coordinates to cartesian coordinates (halfway vector) - vec3 H = vec3(cos(phi)*sinTheta, sin(phi)*sinTheta, cosTheta); + // Transform from spherical coordinates to cartesian coordinates (halfway vector) + vec3 H = vec3(cos(phi)*sinTheta, sin(phi)*sinTheta, cosTheta); - // Transform from tangent space H vector to world space sample vector - vec3 up = ((abs(N.z) < 0.999) ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0)); - vec3 tangent = normalize(cross(up, N)); - vec3 bitangent = cross(N, tangent); - vec3 sampleVec = tangent*H.x + bitangent*H.y + N*H.z; + // Transform from tangent space H vector to world space sample vector + vec3 up = ((abs(N.z) < 0.999) ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0)); + vec3 tangent = normalize(cross(up, N)); + vec3 bitangent = cross(N, tangent); + vec3 sampleVec = tangent*H.x + bitangent*H.y + N*H.z; - return normalize(sampleVec); + return normalize(sampleVec); } float GeometrySchlickGGX(float NdotV, float roughness) diff --git a/examples/models/resources/shaders/glsl330/prefilter.fs b/examples/models/resources/shaders/glsl330/prefilter.fs index 941ea86c0..82f0f7710 100644 --- a/examples/models/resources/shaders/glsl330/prefilter.fs +++ b/examples/models/resources/shaders/glsl330/prefilter.fs @@ -54,26 +54,26 @@ float RadicalInverse_VdC(uint bits) vec2 Hammersley(uint i, uint N) { - return vec2(float(i)/float(N), RadicalInverse_VdC(i)); + return vec2(float(i)/float(N), RadicalInverse_VdC(i)); } vec3 ImportanceSampleGGX(vec2 Xi, vec3 N, float roughness) { - float a = roughness*roughness; - float phi = 2.0*PI*Xi.x; - float cosTheta = sqrt((1.0 - Xi.y)/(1.0 + (a*a - 1.0)*Xi.y)); - float sinTheta = sqrt(1.0 - cosTheta*cosTheta); + float a = roughness*roughness; + float phi = 2.0*PI*Xi.x; + float cosTheta = sqrt((1.0 - Xi.y)/(1.0 + (a*a - 1.0)*Xi.y)); + float sinTheta = sqrt(1.0 - cosTheta*cosTheta); - // Transform from spherical coordinates to cartesian coordinates (halfway vector) - vec3 H = vec3(cos(phi)*sinTheta, sin(phi)*sinTheta, cosTheta); + // Transform from spherical coordinates to cartesian coordinates (halfway vector) + vec3 H = vec3(cos(phi)*sinTheta, sin(phi)*sinTheta, cosTheta); - // Transform from tangent space H vector to world space sample vector - vec3 up = ((abs(N.z) < 0.999) ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0)); - vec3 tangent = normalize(cross(up, N)); - vec3 bitangent = cross(N, tangent); - vec3 sampleVec = tangent*H.x + bitangent*H.y + N*H.z; + // Transform from tangent space H vector to world space sample vector + vec3 up = ((abs(N.z) < 0.999) ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0)); + vec3 tangent = normalize(cross(up, N)); + vec3 bitangent = cross(N, tangent); + vec3 sampleVec = tangent*H.x + bitangent*H.y + N*H.z; - return normalize(sampleVec); + return normalize(sampleVec); } void main() diff --git a/examples/models/resources/shaders/glsl330/skybox.fs b/examples/models/resources/shaders/glsl330/skybox.fs index c7a17883e..dd8078e09 100644 --- a/examples/models/resources/shaders/glsl330/skybox.fs +++ b/examples/models/resources/shaders/glsl330/skybox.fs @@ -4,7 +4,7 @@ * * Copyright (c) 2017 Victor Fisac * -* 19-Jun-2020 - modified by Giuseppe Mastrangelo (@peppemas) - VFlip Support +* 19-Jun-2020 - modified by Giuseppe Mastrangelo (@peppemas) - VFlip Support * **********************************************************************************************/ diff --git a/examples/physics/physics_demo.c b/examples/physics/physics_demo.c index 421c82a90..9763bf990 100644 --- a/examples/physics/physics_demo.c +++ b/examples/physics/physics_demo.c @@ -1,24 +1,19 @@ /******************************************************************************************* * -* Physac - Physics demo +* raylib [physac] example - physics demo * -* NOTE 1: Physac requires multi-threading, when InitPhysics() a second thread is created to manage physics calculations. -* NOTE 2: Physac requires static C library linkage to avoid dependency on MinGW DLL (-static -lpthread) +* This example has been created using raylib 1.5 (www.raylib.com) +* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * -* Use the following line to compile: +* This example uses physac 1.1 (https://github.com/raysan5/raylib/blob/master/src/physac.h) * -* gcc -o $(NAME_PART).exe $(FILE_NAME) -s -static / -* -lraylib -lpthread -lglfw3 -lopengl32 -lgdi32 -lopenal32 -lwinmm / -* -std=c99 -Wl,--subsystem,windows -Wl,-allow-multiple-definition -* -* Copyright (c) 2016-2018 Victor Fisac +* Copyright (c) 2016-2021 Victor Fisac (@victorfisac) and Ramon Santamaria (@raysan5) * ********************************************************************************************/ #include "raylib.h" #define PHYSAC_IMPLEMENTATION -#define PHYSAC_NO_THREADS #include "physac.h" int main(void) @@ -29,12 +24,11 @@ int main(void) const int screenHeight = 450; SetConfigFlags(FLAG_MSAA_4X_HINT); - InitWindow(screenWidth, screenHeight, "Physac [raylib] - Physics demo"); + InitWindow(screenWidth, screenHeight, "raylib [physac] example - physics demo"); // Physac logo drawing position int logoX = screenWidth - MeasureText("Physac", 30) - 10; int logoY = 15; - bool needsReset = false; // Initialize physics and default physics bodies InitPhysics(); @@ -55,25 +49,17 @@ int main(void) { // Update //---------------------------------------------------------------------------------- - // Delay initialization of variables due to physics reset async - RunPhysicsStep(); + UpdatePhysics(); // Update physics system - if (needsReset) + if (IsKeyPressed('R')) // Reset physics system { + ResetPhysics(); + floor = CreatePhysicsBodyRectangle((Vector2){ screenWidth/2, screenHeight }, 500, 100, 10); floor->enabled = false; circle = CreatePhysicsBodyCircle((Vector2){ screenWidth/2, screenHeight/2 }, 45, 10); circle->enabled = false; - - needsReset = false; - } - - // Reset physics input - if (IsKeyPressed('R')) - { - ResetPhysics(); - needsReset = true; } // Physics body creation inputs diff --git a/examples/physics/physics_friction.c b/examples/physics/physics_friction.c index 0acf88aea..b91950391 100644 --- a/examples/physics/physics_friction.c +++ b/examples/physics/physics_friction.c @@ -1,24 +1,19 @@ /******************************************************************************************* * -* Physac - Physics friction +* raylib [physac] example - physics friction * -* NOTE 1: Physac requires multi-threading, when InitPhysics() a second thread is created to manage physics calculations. -* NOTE 2: Physac requires static C library linkage to avoid dependency on MinGW DLL (-static -lpthread) +* This example has been created using raylib 1.5 (www.raylib.com) +* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * -* Use the following line to compile: +* This example uses physac 1.1 (https://github.com/raysan5/raylib/blob/master/src/physac.h) * -* gcc -o $(NAME_PART).exe $(FILE_NAME) -s -static / -* -lraylib -lpthread -lglfw3 -lopengl32 -lgdi32 -lopenal32 -lwinmm / -* -std=c99 -Wl,--subsystem,windows -Wl,-allow-multiple-definition -* -* Copyright (c) 2016-2018 Victor Fisac +* Copyright (c) 2016-2021 Victor Fisac (@victorfisac) and Ramon Santamaria (@raysan5) * ********************************************************************************************/ #include "raylib.h" #define PHYSAC_IMPLEMENTATION -#define PHYSAC_NO_THREADS #include "physac.h" int main(void) @@ -29,7 +24,7 @@ int main(void) const int screenHeight = 450; SetConfigFlags(FLAG_MSAA_4X_HINT); - InitWindow(screenWidth, screenHeight, "Physac [raylib] - Physics friction"); + InitWindow(screenWidth, screenHeight, "raylib [physac] example - physics friction"); // Physac logo drawing position int logoX = screenWidth - MeasureText("Physac", 30) - 10; @@ -73,9 +68,9 @@ int main(void) { // Update //---------------------------------------------------------------------------------- - RunPhysicsStep(); + UpdatePhysics(); // Update physics system - if (IsKeyPressed('R')) // Reset physics input + if (IsKeyPressed('R')) // Reset physics system { // Reset dynamic physics bodies position, velocity and rotation bodyA->position = (Vector2){ 35, screenHeight*0.6f }; diff --git a/examples/physics/physics_movement.c b/examples/physics/physics_movement.c index d946811d1..73a1f9277 100644 --- a/examples/physics/physics_movement.c +++ b/examples/physics/physics_movement.c @@ -1,24 +1,19 @@ /******************************************************************************************* * -* Physac - Physics movement +* raylib [physac] example - physics movement * -* NOTE 1: Physac requires multi-threading, when InitPhysics() a second thread is created to manage physics calculations. -* NOTE 2: Physac requires static C library linkage to avoid dependency on MinGW DLL (-static -lpthread) +* This example has been created using raylib 1.5 (www.raylib.com) +* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * -* Use the following line to compile: +* This example uses physac 1.1 (https://github.com/raysan5/raylib/blob/master/src/physac.h) * -* gcc -o $(NAME_PART).exe $(FILE_NAME) -s -static / -* -lraylib -lpthread -lglfw3 -lopengl32 -lgdi32 -lopenal32 -lwinmm / -* -std=c99 -Wl,--subsystem,windows -Wl,-allow-multiple-definition -* -* Copyright (c) 2016-2018 Victor Fisac +* Copyright (c) 2016-2021 Victor Fisac (@victorfisac) and Ramon Santamaria (@raysan5) * ********************************************************************************************/ #include "raylib.h" #define PHYSAC_IMPLEMENTATION -#define PHYSAC_NO_THREADS #include "physac.h" #define VELOCITY 0.5f @@ -31,7 +26,7 @@ int main(void) const int screenHeight = 450; SetConfigFlags(FLAG_MSAA_4X_HINT); - InitWindow(screenWidth, screenHeight, "Physac [raylib] - Physics movement"); + InitWindow(screenWidth, screenHeight, "raylib [physac] example - physics movement"); // Physac logo drawing position int logoX = screenWidth - MeasureText("Physac", 30) - 10; @@ -66,9 +61,9 @@ int main(void) { // Update //---------------------------------------------------------------------------------- - RunPhysicsStep(); + UpdatePhysics(); // Update physics system - if (IsKeyPressed('R')) // Reset physics input + if (IsKeyPressed('R')) // Reset physics input { // Reset movement physics body position, velocity and rotation body->position = (Vector2){ screenWidth/2, screenHeight/2 }; diff --git a/examples/physics/physics_restitution.c b/examples/physics/physics_restitution.c index 12a2a9220..787db98d9 100644 --- a/examples/physics/physics_restitution.c +++ b/examples/physics/physics_restitution.c @@ -1,24 +1,19 @@ /******************************************************************************************* * -* Physac - Physics restitution +* raylib [physac] example - physics restitution * -* NOTE 1: Physac requires multi-threading, when InitPhysics() a second thread is created to manage physics calculations. -* NOTE 2: Physac requires static C library linkage to avoid dependency on MinGW DLL (-static -lpthread) +* This example has been created using raylib 1.5 (www.raylib.com) +* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * -* Use the following line to compile: +* This example uses physac 1.1 (https://github.com/raysan5/raylib/blob/master/src/physac.h) * -* gcc -o $(NAME_PART).exe $(FILE_NAME) -s -static / -* -lraylib -lpthread -lglfw3 -lopengl32 -lgdi32 -lopenal32 -lwinmm / -* -std=c99 -Wl,--subsystem,windows -Wl,-allow-multiple-definition -* -* Copyright (c) 2016-2018 Victor Fisac +* Copyright (c) 2016-2021 Victor Fisac (@victorfisac) and Ramon Santamaria (@raysan5) * ********************************************************************************************/ #include "raylib.h" #define PHYSAC_IMPLEMENTATION -#define PHYSAC_NO_THREADS #include "physac.h" int main(void) @@ -29,7 +24,7 @@ int main(void) const int screenHeight = 450; SetConfigFlags(FLAG_MSAA_4X_HINT); - InitWindow(screenWidth, screenHeight, "Physac [raylib] - Physics restitution"); + InitWindow(screenWidth, screenHeight, "raylib [physac] example - physics restitution"); // Physac logo drawing position int logoX = screenWidth - MeasureText("Physac", 30) - 10; @@ -62,9 +57,9 @@ int main(void) { // Update //---------------------------------------------------------------------------------- - RunPhysicsStep(); + UpdatePhysics(); // Update physics system - if (IsKeyPressed('R')) // Reset physics input + if (IsKeyPressed('R')) // Reset physics input { // Reset circles physics bodies position and velocity circleA->position = (Vector2){ screenWidth*0.25f, screenHeight/2 }; @@ -124,6 +119,7 @@ int main(void) DestroyPhysicsBody(circleB); DestroyPhysicsBody(circleC); DestroyPhysicsBody(floor); + ClosePhysics(); // Unitialize physics CloseWindow(); // Close window and OpenGL context diff --git a/examples/physics/physics_shatter.c b/examples/physics/physics_shatter.c index cbc65221d..46876ff7c 100644 --- a/examples/physics/physics_shatter.c +++ b/examples/physics/physics_shatter.c @@ -1,24 +1,19 @@ /******************************************************************************************* * -* Physac - Body shatter +* raylib [physac] example - physics shatter * -* NOTE 1: Physac requires multi-threading, when InitPhysics() a second thread is created to manage physics calculations. -* NOTE 2: Physac requires static C library linkage to avoid dependency on MinGW DLL (-static -lpthread) +* This example has been created using raylib 1.5 (www.raylib.com) +* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * -* Use the following line to compile: +* This example uses physac 1.1 (https://github.com/raysan5/raylib/blob/master/src/physac.h) * -* gcc -o $(NAME_PART).exe $(FILE_NAME) -s -static / -* -lraylib -lpthread -lglfw3 -lopengl32 -lgdi32 -lopenal32 -lwinmm / -* -std=c99 -Wl,--subsystem,windows -Wl,-allow-multiple-definition -* -* Copyright (c) 2016-2018 Victor Fisac +* Copyright (c) 2016-2021 Victor Fisac (@victorfisac) and Ramon Santamaria (@raysan5) * ********************************************************************************************/ #include "raylib.h" #define PHYSAC_IMPLEMENTATION -#define PHYSAC_NO_THREADS #include "physac.h" int main(void) @@ -29,12 +24,11 @@ int main(void) const int screenHeight = 450; SetConfigFlags(FLAG_MSAA_4X_HINT); - InitWindow(screenWidth, screenHeight, "Physac [raylib] - Body shatter"); + InitWindow(screenWidth, screenHeight, "raylib [physac] example - physics shatter"); // Physac logo drawing position int logoX = screenWidth - MeasureText("Physac", 30) - 10; int logoY = 15; - bool needsReset = false; // Initialize physics and default physics bodies InitPhysics(); @@ -49,31 +43,23 @@ int main(void) // Main game loop while (!WindowShouldClose()) // Detect window close button or ESC key { - // Update - RunPhysicsStep(); - //---------------------------------------------------------------------------------- - // Delay initialization of variables due to physics reset asynchronous - if (needsReset) - { - // Create random polygon physics body to shatter - CreatePhysicsBodyPolygon((Vector2){ screenWidth/2, screenHeight/2 }, GetRandomValue(80, 200), GetRandomValue(3, 8), 10); - needsReset = false; - } - - if (IsKeyPressed('R')) // Reset physics input + UpdatePhysics(); // Update physics system + + if (IsKeyPressed('R')) // Reset physics input { ResetPhysics(); - needsReset = true; + + CreatePhysicsBodyPolygon((Vector2){ screenWidth/2, screenHeight/2 }, GetRandomValue(80, 200), GetRandomValue(3, 8), 10); } if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) // Physics shatter input { - // Note: some values need to be stored in variables due to asynchronous changes during main thread int count = GetPhysicsBodiesCount(); for (int i = count - 1; i >= 0; i--) { PhysicsBody currentBody = GetPhysicsBody(i); + if (currentBody != NULL) PhysicsShatter(currentBody, GetMousePosition(), 10/currentBody->inverseMass); } } diff --git a/examples/shaders/resources/shaders/glsl100/bloom.fs b/examples/shaders/resources/shaders/glsl100/bloom.fs index a8e1d20f7..673e0116a 100644 --- a/examples/shaders/resources/shaders/glsl100/bloom.fs +++ b/examples/shaders/resources/shaders/glsl100/bloom.fs @@ -14,7 +14,7 @@ uniform vec4 colDiffuse; const vec2 size = vec2(800, 450); // render size const float samples = 5.0; // pixels per axis; higher = bigger glow, worse performance -const float quality = 2.5; // lower = smaller glow, better quality +const float quality = 2.5; // lower = smaller glow, better quality void main() { diff --git a/examples/shaders/resources/shaders/glsl100/dream_vision.fs b/examples/shaders/resources/shaders/glsl100/dream_vision.fs index fa9c5b771..7014b5920 100644 --- a/examples/shaders/resources/shaders/glsl100/dream_vision.fs +++ b/examples/shaders/resources/shaders/glsl100/dream_vision.fs @@ -34,4 +34,4 @@ void main() color = color/9.5; gl_FragColor = color; -} \ No newline at end of file +} \ No newline at end of file diff --git a/examples/shaders/resources/shaders/glsl100/raymarching.fs b/examples/shaders/resources/shaders/glsl100/raymarching.fs index c823e01eb..7535086b5 100644 --- a/examples/shaders/resources/shaders/glsl100/raymarching.fs +++ b/examples/shaders/resources/shaders/glsl100/raymarching.fs @@ -42,7 +42,7 @@ uniform vec2 resolution; float sdPlane( vec3 p ) { - return p.y; + return p.y; } float sdSphere( vec3 p, float s ) @@ -85,9 +85,9 @@ float sdHexPrism( vec3 p, vec2 h ) float sdCapsule( vec3 p, vec3 a, vec3 b, float r ) { - vec3 pa = p-a, ba = b-a; - float h = clamp( dot(pa,ba)/dot(ba,ba), 0.0, 1.0 ); - return length( pa - ba*h ) - r; + vec3 pa = p-a, ba = b-a; + float h = clamp( dot(pa,ba)/dot(ba,ba), 0.0, 1.0 ); + return length( pa - ba*h ) - r; } float sdEquilateralTriangle( in vec2 p ) @@ -154,19 +154,19 @@ float sdPryamid4(vec3 p, vec3 h ) // h = { cos a, sin a, height } float length2( vec2 p ) { - return sqrt( p.x*p.x + p.y*p.y ); + return sqrt( p.x*p.x + p.y*p.y ); } float length6( vec2 p ) { - p = p*p*p; p = p*p; - return pow( p.x + p.y, 1.0/6.0 ); + p = p*p*p; p = p*p; + return pow( p.x + p.y, 1.0/6.0 ); } float length8( vec2 p ) { - p = p*p; p = p*p; p = p*p; - return pow( p.x + p.y, 1.0/8.0 ); + p = p*p; p = p*p; p = p*p; + return pow( p.x + p.y, 1.0/8.0 ); } float sdTorus82( vec3 p, vec2 t ) @@ -195,7 +195,7 @@ float opS( float d1, float d2 ) vec2 opU( vec2 d1, vec2 d2 ) { - return (d1.xtmax ) break; t += res.x; - m = res.y; + m = res.y; } if( t>tmax ) m=-1.0; @@ -271,11 +271,11 @@ vec2 castRay( in vec3 ro, in vec3 rd ) float calcSoftshadow( in vec3 ro, in vec3 rd, in float mint, in float tmax ) { - float res = 1.0; + float res = 1.0; float t = mint; for( int i=0; i<16; i++ ) { - float h = map( ro + rd*t ).x; + float h = map( ro + rd*t ).x; res = min( res, 8.0*h/t ); t += clamp( h, 0.02, 0.10 ); if( h<0.001 || t>tmax ) break; @@ -287,22 +287,22 @@ vec3 calcNormal( in vec3 pos ) { vec2 e = vec2(1.0,-1.0)*0.5773*0.0005; return normalize( e.xyy*map( pos + e.xyy ).x + - e.yyx*map( pos + e.yyx ).x + - e.yxy*map( pos + e.yxy ).x + - e.xxx*map( pos + e.xxx ).x ); + e.yyx*map( pos + e.yyx ).x + + e.yxy*map( pos + e.yxy ).x + + e.xxx*map( pos + e.xxx ).x ); /* - vec3 eps = vec3( 0.0005, 0.0, 0.0 ); - vec3 nor = vec3( - map(pos+eps.xyy).x - map(pos-eps.xyy).x, - map(pos+eps.yxy).x - map(pos-eps.yxy).x, - map(pos+eps.yyx).x - map(pos-eps.yyx).x ); - return normalize(nor); - */ + vec3 eps = vec3( 0.0005, 0.0, 0.0 ); + vec3 nor = vec3( + map(pos+eps.xyy).x - map(pos-eps.xyy).x, + map(pos+eps.yxy).x - map(pos-eps.yxy).x, + map(pos+eps.yyx).x - map(pos-eps.yyx).x ); + return normalize(nor); + */ } float calcAO( in vec3 pos, in vec3 nor ) { - float occ = 0.0; + float occ = 0.0; float sca = 1.0; for( int i=0; i<5; i++ ) { @@ -331,7 +331,7 @@ vec3 render( in vec3 ro, in vec3 rd ) vec3 col = vec3(0.7, 0.9, 1.0) +rd.y*0.8; vec2 res = castRay(ro,rd); float t = res.x; - float m = res.y; + float m = res.y; if( m>-0.5 ) { vec3 pos = ro + t*rd; @@ -339,7 +339,7 @@ vec3 render( in vec3 ro, in vec3 rd ) vec3 ref = reflect( rd, nor ); // material - col = 0.45 + 0.35*sin( vec3(0.05,0.08,0.10)*(m-1.0) ); + col = 0.45 + 0.35*sin( vec3(0.05,0.08,0.10)*(m-1.0) ); if( m<1.5 ) { @@ -349,9 +349,9 @@ vec3 render( in vec3 ro, in vec3 rd ) // lighting float occ = calcAO( pos, nor ); - vec3 lig = normalize( vec3(cos(-0.4 * runTime), sin(0.7 * runTime), -0.6) ); + vec3 lig = normalize( vec3(cos(-0.4 * runTime), sin(0.7 * runTime), -0.6) ); vec3 hal = normalize( lig-rd ); - float amb = clamp( 0.5+0.5*nor.y, 0.0, 1.0 ); + float amb = clamp( 0.5+0.5*nor.y, 0.0, 1.0 ); float dif = clamp( dot( nor, lig ), 0.0, 1.0 ); float bac = clamp( dot( nor, normalize(vec3(-lig.x,0.0,-lig.z))), 0.0, 1.0 )*clamp( 1.0-pos.y,0.0,1.0); float dom = smoothstep( -0.1, 0.1, ref.y ); @@ -360,31 +360,31 @@ vec3 render( in vec3 ro, in vec3 rd ) dif *= calcSoftshadow( pos, lig, 0.02, 2.5 ); dom *= calcSoftshadow( pos, ref, 0.02, 2.5 ); - float spe = pow( clamp( dot( nor, hal ), 0.0, 1.0 ),16.0)* + float spe = pow( clamp( dot( nor, hal ), 0.0, 1.0 ),16.0)* dif * (0.04 + 0.96*pow( clamp(1.0+dot(hal,rd),0.0,1.0), 5.0 )); - vec3 lin = vec3(0.0); + vec3 lin = vec3(0.0); lin += 1.30*dif*vec3(1.00,0.80,0.55); lin += 0.40*amb*vec3(0.40,0.60,1.00)*occ; lin += 0.50*dom*vec3(0.40,0.60,1.00)*occ; lin += 0.50*bac*vec3(0.25,0.25,0.25)*occ; lin += 0.25*fre*vec3(1.00,1.00,1.00)*occ; - col = col*lin; - col += 10.00*spe*vec3(1.00,0.90,0.70); + col = col*lin; + col += 10.00*spe*vec3(1.00,0.90,0.70); - col = mix( col, vec3(0.8,0.9,1.0), 1.0-exp( -0.0002*t*t*t ) ); + col = mix( col, vec3(0.8,0.9,1.0), 1.0-exp( -0.0002*t*t*t ) ); } - return vec3( clamp(col,0.0,1.0) ); + return vec3( clamp(col,0.0,1.0) ); } mat3 setCamera( in vec3 ro, in vec3 ta, float cr ) { vec3 cw = normalize(ta-ro); - vec3 cp = vec3(sin(cr), cos(cr),0.0); - vec3 cu = normalize( cross(cw,cp) ); - vec3 cv = normalize( cross(cu,cw) ); + vec3 cp = vec3(sin(cr), cos(cr),0.0); + vec3 cu = normalize( cross(cw,cp) ); + vec3 cv = normalize( cross(cu,cw) ); return mat3( cu, cv, cw ); } @@ -402,7 +402,7 @@ void main() vec2 p = (-resolution.xy + 2.0*gl_FragCoord.xy)/resolution.y; #endif - // RAY: Camera is provided from raylib + // RAY: Camera is provided from raylib //vec3 ro = vec3( -0.5+3.5*cos(0.1*time + 6.0*mo.x), 1.0 + 2.0*mo.y, 0.5 + 4.0*sin(0.1*time + 6.0*mo.x) ); vec3 ro = viewEye; @@ -413,10 +413,10 @@ void main() // ray direction vec3 rd = ca * normalize( vec3(p.xy,2.0) ); - // render + // render vec3 col = render( ro, rd ); - // gamma + // gamma col = pow( col, vec3(0.4545) ); tot += col; diff --git a/examples/shaders/resources/shaders/glsl100/sobel.fs b/examples/shaders/resources/shaders/glsl100/sobel.fs index 745562ad0..3e5c22dda 100644 --- a/examples/shaders/resources/shaders/glsl100/sobel.fs +++ b/examples/shaders/resources/shaders/glsl100/sobel.fs @@ -15,26 +15,26 @@ vec2 resolution = vec2(800.0, 450.0); void main() { - float x = 1.0/resolution.x; - float y = 1.0/resolution.y; + float x = 1.0/resolution.x; + float y = 1.0/resolution.y; - vec4 horizEdge = vec4(0.0); - horizEdge -= texture2D(texture0, vec2(fragTexCoord.x - x, fragTexCoord.y - y))*1.0; - horizEdge -= texture2D(texture0, vec2(fragTexCoord.x - x, fragTexCoord.y ))*2.0; - horizEdge -= texture2D(texture0, vec2(fragTexCoord.x - x, fragTexCoord.y + y))*1.0; - horizEdge += texture2D(texture0, vec2(fragTexCoord.x + x, fragTexCoord.y - y))*1.0; - horizEdge += texture2D(texture0, vec2(fragTexCoord.x + x, fragTexCoord.y ))*2.0; - horizEdge += texture2D(texture0, vec2(fragTexCoord.x + x, fragTexCoord.y + y))*1.0; + vec4 horizEdge = vec4(0.0); + horizEdge -= texture2D(texture0, vec2(fragTexCoord.x - x, fragTexCoord.y - y))*1.0; + horizEdge -= texture2D(texture0, vec2(fragTexCoord.x - x, fragTexCoord.y ))*2.0; + horizEdge -= texture2D(texture0, vec2(fragTexCoord.x - x, fragTexCoord.y + y))*1.0; + horizEdge += texture2D(texture0, vec2(fragTexCoord.x + x, fragTexCoord.y - y))*1.0; + horizEdge += texture2D(texture0, vec2(fragTexCoord.x + x, fragTexCoord.y ))*2.0; + horizEdge += texture2D(texture0, vec2(fragTexCoord.x + x, fragTexCoord.y + y))*1.0; - vec4 vertEdge = vec4(0.0); - vertEdge -= texture2D(texture0, vec2(fragTexCoord.x - x, fragTexCoord.y - y))*1.0; - vertEdge -= texture2D(texture0, vec2(fragTexCoord.x , fragTexCoord.y - y))*2.0; - vertEdge -= texture2D(texture0, vec2(fragTexCoord.x + x, fragTexCoord.y - y))*1.0; - vertEdge += texture2D(texture0, vec2(fragTexCoord.x - x, fragTexCoord.y + y))*1.0; - vertEdge += texture2D(texture0, vec2(fragTexCoord.x , fragTexCoord.y + y))*2.0; - vertEdge += texture2D(texture0, vec2(fragTexCoord.x + x, fragTexCoord.y + y))*1.0; + vec4 vertEdge = vec4(0.0); + vertEdge -= texture2D(texture0, vec2(fragTexCoord.x - x, fragTexCoord.y - y))*1.0; + vertEdge -= texture2D(texture0, vec2(fragTexCoord.x , fragTexCoord.y - y))*2.0; + vertEdge -= texture2D(texture0, vec2(fragTexCoord.x + x, fragTexCoord.y - y))*1.0; + vertEdge += texture2D(texture0, vec2(fragTexCoord.x - x, fragTexCoord.y + y))*1.0; + vertEdge += texture2D(texture0, vec2(fragTexCoord.x , fragTexCoord.y + y))*2.0; + vertEdge += texture2D(texture0, vec2(fragTexCoord.x + x, fragTexCoord.y + y))*1.0; - vec3 edge = sqrt((horizEdge.rgb*horizEdge.rgb) + (vertEdge.rgb*vertEdge.rgb)); - - gl_FragColor = vec4(edge, texture2D(texture0, fragTexCoord).a); + vec3 edge = sqrt((horizEdge.rgb*horizEdge.rgb) + (vertEdge.rgb*vertEdge.rgb)); + + gl_FragColor = vec4(edge, texture2D(texture0, fragTexCoord).a); } \ No newline at end of file diff --git a/examples/shaders/resources/shaders/glsl100/spotlight.fs b/examples/shaders/resources/shaders/glsl100/spotlight.fs index c1202610e..c8d830381 100644 --- a/examples/shaders/resources/shaders/glsl100/spotlight.fs +++ b/examples/shaders/resources/shaders/glsl100/spotlight.fs @@ -5,9 +5,9 @@ precision mediump float; #define MAX_SPOTS 3 struct Spot { - vec2 pos; // window coords of spot - float inner; // inner fully transparent centre radius - float radius; // alpha fades out to this radius + vec2 pos; // window coords of spot + float inner; // inner fully transparent centre radius + float radius; // alpha fades out to this radius }; uniform Spot spots[MAX_SPOTS]; // Spotlight positions array @@ -15,63 +15,63 @@ uniform float screenWidth; // Width of the screen void main() { - float alpha = 1.0; + float alpha = 1.0; - // Get the position of the current fragment (screen coordinates!) - vec2 pos = vec2(gl_FragCoord.x, gl_FragCoord.y); - - // Find out which spotlight is nearest - float d = 65000.0; // some high value - int fi = -1; // found index + // Get the position of the current fragment (screen coordinates!) + vec2 pos = vec2(gl_FragCoord.x, gl_FragCoord.y); + + // Find out which spotlight is nearest + float d = 65000.0; // some high value + int fi = -1; // found index for (int i = 0; i < MAX_SPOTS; i++) { - for (int j = 0; j < MAX_SPOTS; j++) - { - float dj = distance(pos, spots[j].pos) - spots[j].radius + spots[i].radius; + for (int j = 0; j < MAX_SPOTS; j++) + { + float dj = distance(pos, spots[j].pos) - spots[j].radius + spots[i].radius; - if (d > dj) - { - d = dj; - fi = i; - } - } + if (d > dj) + { + d = dj; + fi = i; + } + } } // d now equals distance to nearest spot... // allowing for the different radii of all spotlights if (fi == 0) { - if (d > spots[0].radius) alpha = 1.0; - else - { - if (d < spots[0].inner) alpha = 0.0; - else alpha = (d - spots[0].inner)/(spots[0].radius - spots[0].inner); - } - } + if (d > spots[0].radius) alpha = 1.0; + else + { + if (d < spots[0].inner) alpha = 0.0; + else alpha = (d - spots[0].inner)/(spots[0].radius - spots[0].inner); + } + } else if (fi == 1) { - if (d > spots[1].radius) alpha = 1.0; - else - { - if (d < spots[1].inner) alpha = 0.0; - else alpha = (d - spots[1].inner)/(spots[1].radius - spots[1].inner); - } - } + if (d > spots[1].radius) alpha = 1.0; + else + { + if (d < spots[1].inner) alpha = 0.0; + else alpha = (d - spots[1].inner)/(spots[1].radius - spots[1].inner); + } + } else if (fi == 2) { - if (d > spots[2].radius) alpha = 1.0; - else - { - if (d < spots[2].inner) alpha = 0.0; - else alpha = (d - spots[2].inner)/(spots[2].radius - spots[2].inner); - } - } - - // Right hand side of screen is dimly lit, + if (d > spots[2].radius) alpha = 1.0; + else + { + if (d < spots[2].inner) alpha = 0.0; + else alpha = (d - spots[2].inner)/(spots[2].radius - spots[2].inner); + } + } + + // Right hand side of screen is dimly lit, // could make the threshold value user definable - if ((pos.x > screenWidth/2.0) && (alpha > 0.9)) alpha = 0.9; + if ((pos.x > screenWidth/2.0) && (alpha > 0.9)) alpha = 0.9; - // could make the black out colour user definable... + // could make the black out colour user definable... gl_FragColor = vec4(0, 0, 0, alpha); } diff --git a/examples/shaders/resources/shaders/glsl100/wave.fs b/examples/shaders/resources/shaders/glsl100/wave.fs index bcc156cc6..50c4e02f3 100644 --- a/examples/shaders/resources/shaders/glsl100/wave.fs +++ b/examples/shaders/resources/shaders/glsl100/wave.fs @@ -22,15 +22,15 @@ uniform float speedX; uniform float speedY; void main() { - float pixelWidth = 1.0 / size.x; - float pixelHeight = 1.0 / size.y; - float aspect = pixelHeight / pixelWidth; - float boxLeft = 0.0; - float boxTop = 0.0; + float pixelWidth = 1.0 / size.x; + float pixelHeight = 1.0 / size.y; + float aspect = pixelHeight / pixelWidth; + float boxLeft = 0.0; + float boxTop = 0.0; - vec2 p = fragTexCoord; - p.x += cos((fragTexCoord.y - boxTop) * freqX / ( pixelWidth * 750.0) + (secondes * speedX)) * ampX * pixelWidth; - p.y += sin((fragTexCoord.x - boxLeft) * freqY * aspect / ( pixelHeight * 750.0) + (secondes * speedY)) * ampY * pixelHeight; + vec2 p = fragTexCoord; + p.x += cos((fragTexCoord.y - boxTop) * freqX / ( pixelWidth * 750.0) + (secondes * speedX)) * ampX * pixelWidth; + p.y += sin((fragTexCoord.x - boxLeft) * freqY * aspect / ( pixelHeight * 750.0) + (secondes * speedY)) * ampY * pixelHeight; - gl_FragColor = texture2D(texture0, p)*colDiffuse*fragColor; + gl_FragColor = texture2D(texture0, p)*colDiffuse*fragColor; } diff --git a/examples/shaders/resources/shaders/glsl120/bloom.fs b/examples/shaders/resources/shaders/glsl120/bloom.fs index c28836b0d..f97c18ed7 100644 --- a/examples/shaders/resources/shaders/glsl120/bloom.fs +++ b/examples/shaders/resources/shaders/glsl120/bloom.fs @@ -12,7 +12,7 @@ uniform vec4 colDiffuse; const vec2 size = vec2(800, 450); // render size const float samples = 5.0; // pixels per axis; higher = bigger glow, worse performance -const float quality = 2.5; // lower = smaller glow, better quality +const float quality = 2.5; // lower = smaller glow, better quality void main() { diff --git a/examples/shaders/resources/shaders/glsl120/dream_vision.fs b/examples/shaders/resources/shaders/glsl120/dream_vision.fs index 4ca2a8634..cb97b2bd0 100644 --- a/examples/shaders/resources/shaders/glsl120/dream_vision.fs +++ b/examples/shaders/resources/shaders/glsl120/dream_vision.fs @@ -32,4 +32,4 @@ void main() color = color/9.5; gl_FragColor = color; -} \ No newline at end of file +} \ No newline at end of file diff --git a/examples/shaders/resources/shaders/glsl120/sobel.fs b/examples/shaders/resources/shaders/glsl120/sobel.fs index a3f3f2bf7..73e72703a 100644 --- a/examples/shaders/resources/shaders/glsl120/sobel.fs +++ b/examples/shaders/resources/shaders/glsl120/sobel.fs @@ -13,26 +13,26 @@ vec2 resolution = vec2(800.0, 450.0); void main() { - float x = 1.0/resolution.x; - float y = 1.0/resolution.y; + float x = 1.0/resolution.x; + float y = 1.0/resolution.y; - vec4 horizEdge = vec4(0.0); - horizEdge -= texture2D(texture0, vec2(fragTexCoord.x - x, fragTexCoord.y - y))*1.0; - horizEdge -= texture2D(texture0, vec2(fragTexCoord.x - x, fragTexCoord.y ))*2.0; - horizEdge -= texture2D(texture0, vec2(fragTexCoord.x - x, fragTexCoord.y + y))*1.0; - horizEdge += texture2D(texture0, vec2(fragTexCoord.x + x, fragTexCoord.y - y))*1.0; - horizEdge += texture2D(texture0, vec2(fragTexCoord.x + x, fragTexCoord.y ))*2.0; - horizEdge += texture2D(texture0, vec2(fragTexCoord.x + x, fragTexCoord.y + y))*1.0; + vec4 horizEdge = vec4(0.0); + horizEdge -= texture2D(texture0, vec2(fragTexCoord.x - x, fragTexCoord.y - y))*1.0; + horizEdge -= texture2D(texture0, vec2(fragTexCoord.x - x, fragTexCoord.y ))*2.0; + horizEdge -= texture2D(texture0, vec2(fragTexCoord.x - x, fragTexCoord.y + y))*1.0; + horizEdge += texture2D(texture0, vec2(fragTexCoord.x + x, fragTexCoord.y - y))*1.0; + horizEdge += texture2D(texture0, vec2(fragTexCoord.x + x, fragTexCoord.y ))*2.0; + horizEdge += texture2D(texture0, vec2(fragTexCoord.x + x, fragTexCoord.y + y))*1.0; - vec4 vertEdge = vec4(0.0); - vertEdge -= texture2D(texture0, vec2(fragTexCoord.x - x, fragTexCoord.y - y))*1.0; - vertEdge -= texture2D(texture0, vec2(fragTexCoord.x , fragTexCoord.y - y))*2.0; - vertEdge -= texture2D(texture0, vec2(fragTexCoord.x + x, fragTexCoord.y - y))*1.0; - vertEdge += texture2D(texture0, vec2(fragTexCoord.x - x, fragTexCoord.y + y))*1.0; - vertEdge += texture2D(texture0, vec2(fragTexCoord.x , fragTexCoord.y + y))*2.0; - vertEdge += texture2D(texture0, vec2(fragTexCoord.x + x, fragTexCoord.y + y))*1.0; + vec4 vertEdge = vec4(0.0); + vertEdge -= texture2D(texture0, vec2(fragTexCoord.x - x, fragTexCoord.y - y))*1.0; + vertEdge -= texture2D(texture0, vec2(fragTexCoord.x , fragTexCoord.y - y))*2.0; + vertEdge -= texture2D(texture0, vec2(fragTexCoord.x + x, fragTexCoord.y - y))*1.0; + vertEdge += texture2D(texture0, vec2(fragTexCoord.x - x, fragTexCoord.y + y))*1.0; + vertEdge += texture2D(texture0, vec2(fragTexCoord.x , fragTexCoord.y + y))*2.0; + vertEdge += texture2D(texture0, vec2(fragTexCoord.x + x, fragTexCoord.y + y))*1.0; - vec3 edge = sqrt((horizEdge.rgb*horizEdge.rgb) + (vertEdge.rgb*vertEdge.rgb)); - - gl_FragColor = vec4(edge, texture2D(texture0, fragTexCoord).a); + vec3 edge = sqrt((horizEdge.rgb*horizEdge.rgb) + (vertEdge.rgb*vertEdge.rgb)); + + gl_FragColor = vec4(edge, texture2D(texture0, fragTexCoord).a); } \ No newline at end of file diff --git a/examples/shaders/resources/shaders/glsl330/bloom.fs b/examples/shaders/resources/shaders/glsl330/bloom.fs index 333d5b059..549cde8f8 100644 --- a/examples/shaders/resources/shaders/glsl330/bloom.fs +++ b/examples/shaders/resources/shaders/glsl330/bloom.fs @@ -15,7 +15,7 @@ out vec4 finalColor; const vec2 size = vec2(800, 450); // render size const float samples = 5.0; // pixels per axis; higher = bigger glow, worse performance -const float quality = 2.5; // lower = smaller glow, better quality +const float quality = 2.5; // lower = smaller glow, better quality void main() { diff --git a/examples/shaders/resources/shaders/glsl330/color_mix.fs b/examples/shaders/resources/shaders/glsl330/color_mix.fs index 11515b0cd..1ac7520a9 100644 --- a/examples/shaders/resources/shaders/glsl330/color_mix.fs +++ b/examples/shaders/resources/shaders/glsl330/color_mix.fs @@ -19,7 +19,7 @@ void main() vec4 texelColor1 = texture(texture1, fragTexCoord); float x = fract(fragTexCoord.s); - float out = smoothstep(0.4, 0.6, x); + float outVal = smoothstep(0.4, 0.6, x); - finalColor = mix(texelColor0, texelColor1, out); + finalColor = mix(texelColor0, texelColor1, outVal); } \ No newline at end of file diff --git a/examples/shaders/resources/shaders/glsl330/dream_vision.fs b/examples/shaders/resources/shaders/glsl330/dream_vision.fs index 031158628..31d3fd2f3 100644 --- a/examples/shaders/resources/shaders/glsl330/dream_vision.fs +++ b/examples/shaders/resources/shaders/glsl330/dream_vision.fs @@ -31,4 +31,4 @@ void main() color = color/9.5; fragColor = color; -} \ No newline at end of file +} \ No newline at end of file diff --git a/examples/shaders/resources/shaders/glsl330/eratosthenes.fs b/examples/shaders/resources/shaders/glsl330/eratosthenes.fs index 92d2d2571..14711222b 100644 --- a/examples/shaders/resources/shaders/glsl330/eratosthenes.fs +++ b/examples/shaders/resources/shaders/glsl330/eratosthenes.fs @@ -38,9 +38,9 @@ vec4 Colorizer(float counter, float maxSize) void main() { - vec4 color = vec4(1.0); - float scale = 1000.0; // Makes 100x100 square grid. Change this variable to make a smaller or larger grid. - int value = int(scale*floor(fragTexCoord.y*scale)+floor(fragTexCoord.x*scale)); // Group pixels into boxes representing integer values + vec4 color = vec4(1.0); + float scale = 1000.0; // Makes 100x100 square grid. Change this variable to make a smaller or larger grid. + int value = int(scale*floor(fragTexCoord.y*scale)+floor(fragTexCoord.x*scale)); // Group pixels into boxes representing integer values if ((value == 0) || (value == 1) || (value == 2)) finalColor = vec4(1.0); else diff --git a/examples/shaders/resources/shaders/glsl330/raymarching.fs b/examples/shaders/resources/shaders/glsl330/raymarching.fs index 3cec58a2b..5b0caa652 100644 --- a/examples/shaders/resources/shaders/glsl330/raymarching.fs +++ b/examples/shaders/resources/shaders/glsl330/raymarching.fs @@ -43,7 +43,7 @@ uniform vec2 resolution; float sdPlane( vec3 p ) { - return p.y; + return p.y; } float sdSphere( vec3 p, float s ) @@ -86,9 +86,9 @@ float sdHexPrism( vec3 p, vec2 h ) float sdCapsule( vec3 p, vec3 a, vec3 b, float r ) { - vec3 pa = p-a, ba = b-a; - float h = clamp( dot(pa,ba)/dot(ba,ba), 0.0, 1.0 ); - return length( pa - ba*h ) - r; + vec3 pa = p-a, ba = b-a; + float h = clamp( dot(pa,ba)/dot(ba,ba), 0.0, 1.0 ); + return length( pa - ba*h ) - r; } float sdEquilateralTriangle( in vec2 p ) @@ -155,19 +155,19 @@ float sdPryamid4(vec3 p, vec3 h ) // h = { cos a, sin a, height } float length2( vec2 p ) { - return sqrt( p.x*p.x + p.y*p.y ); + return sqrt( p.x*p.x + p.y*p.y ); } float length6( vec2 p ) { - p = p*p*p; p = p*p; - return pow( p.x + p.y, 1.0/6.0 ); + p = p*p*p; p = p*p; + return pow( p.x + p.y, 1.0/6.0 ); } float length8( vec2 p ) { - p = p*p; p = p*p; p = p*p; - return pow( p.x + p.y, 1.0/8.0 ); + p = p*p; p = p*p; p = p*p; + return pow( p.x + p.y, 1.0/8.0 ); } float sdTorus82( vec3 p, vec2 t ) @@ -196,7 +196,7 @@ float opS( float d1, float d2 ) vec2 opU( vec2 d1, vec2 d2 ) { - return (d1.xtmax ) break; t += res.x; - m = res.y; + m = res.y; } if( t>tmax ) m=-1.0; @@ -272,11 +272,11 @@ vec2 castRay( in vec3 ro, in vec3 rd ) float calcSoftshadow( in vec3 ro, in vec3 rd, in float mint, in float tmax ) { - float res = 1.0; + float res = 1.0; float t = mint; for( int i=0; i<16; i++ ) { - float h = map( ro + rd*t ).x; + float h = map( ro + rd*t ).x; res = min( res, 8.0*h/t ); t += clamp( h, 0.02, 0.10 ); if( h<0.001 || t>tmax ) break; @@ -288,22 +288,22 @@ vec3 calcNormal( in vec3 pos ) { vec2 e = vec2(1.0,-1.0)*0.5773*0.0005; return normalize( e.xyy*map( pos + e.xyy ).x + - e.yyx*map( pos + e.yyx ).x + - e.yxy*map( pos + e.yxy ).x + - e.xxx*map( pos + e.xxx ).x ); + e.yyx*map( pos + e.yyx ).x + + e.yxy*map( pos + e.yxy ).x + + e.xxx*map( pos + e.xxx ).x ); /* - vec3 eps = vec3( 0.0005, 0.0, 0.0 ); - vec3 nor = vec3( - map(pos+eps.xyy).x - map(pos-eps.xyy).x, - map(pos+eps.yxy).x - map(pos-eps.yxy).x, - map(pos+eps.yyx).x - map(pos-eps.yyx).x ); - return normalize(nor); - */ + vec3 eps = vec3( 0.0005, 0.0, 0.0 ); + vec3 nor = vec3( + map(pos+eps.xyy).x - map(pos-eps.xyy).x, + map(pos+eps.yxy).x - map(pos-eps.yxy).x, + map(pos+eps.yyx).x - map(pos-eps.yyx).x ); + return normalize(nor); + */ } float calcAO( in vec3 pos, in vec3 nor ) { - float occ = 0.0; + float occ = 0.0; float sca = 1.0; for( int i=0; i<5; i++ ) { @@ -332,7 +332,7 @@ vec3 render( in vec3 ro, in vec3 rd ) vec3 col = vec3(0.7, 0.9, 1.0) +rd.y*0.8; vec2 res = castRay(ro,rd); float t = res.x; - float m = res.y; + float m = res.y; if( m>-0.5 ) { vec3 pos = ro + t*rd; @@ -340,7 +340,7 @@ vec3 render( in vec3 ro, in vec3 rd ) vec3 ref = reflect( rd, nor ); // material - col = 0.45 + 0.35*sin( vec3(0.05,0.08,0.10)*(m-1.0) ); + col = 0.45 + 0.35*sin( vec3(0.05,0.08,0.10)*(m-1.0) ); if( m<1.5 ) { @@ -350,9 +350,9 @@ vec3 render( in vec3 ro, in vec3 rd ) // lighting float occ = calcAO( pos, nor ); - vec3 lig = normalize( vec3(cos(-0.4 * runTime), sin(0.7 * runTime), -0.6) ); + vec3 lig = normalize( vec3(cos(-0.4 * runTime), sin(0.7 * runTime), -0.6) ); vec3 hal = normalize( lig-rd ); - float amb = clamp( 0.5+0.5*nor.y, 0.0, 1.0 ); + float amb = clamp( 0.5+0.5*nor.y, 0.0, 1.0 ); float dif = clamp( dot( nor, lig ), 0.0, 1.0 ); float bac = clamp( dot( nor, normalize(vec3(-lig.x,0.0,-lig.z))), 0.0, 1.0 )*clamp( 1.0-pos.y,0.0,1.0); float dom = smoothstep( -0.1, 0.1, ref.y ); @@ -361,31 +361,31 @@ vec3 render( in vec3 ro, in vec3 rd ) dif *= calcSoftshadow( pos, lig, 0.02, 2.5 ); dom *= calcSoftshadow( pos, ref, 0.02, 2.5 ); - float spe = pow( clamp( dot( nor, hal ), 0.0, 1.0 ),16.0)* + float spe = pow( clamp( dot( nor, hal ), 0.0, 1.0 ),16.0)* dif * (0.04 + 0.96*pow( clamp(1.0+dot(hal,rd),0.0,1.0), 5.0 )); - vec3 lin = vec3(0.0); + vec3 lin = vec3(0.0); lin += 1.30*dif*vec3(1.00,0.80,0.55); lin += 0.40*amb*vec3(0.40,0.60,1.00)*occ; lin += 0.50*dom*vec3(0.40,0.60,1.00)*occ; lin += 0.50*bac*vec3(0.25,0.25,0.25)*occ; lin += 0.25*fre*vec3(1.00,1.00,1.00)*occ; - col = col*lin; - col += 10.00*spe*vec3(1.00,0.90,0.70); + col = col*lin; + col += 10.00*spe*vec3(1.00,0.90,0.70); - col = mix( col, vec3(0.8,0.9,1.0), 1.0-exp( -0.0002*t*t*t ) ); + col = mix( col, vec3(0.8,0.9,1.0), 1.0-exp( -0.0002*t*t*t ) ); } - return vec3( clamp(col,0.0,1.0) ); + return vec3( clamp(col,0.0,1.0) ); } mat3 setCamera( in vec3 ro, in vec3 ta, float cr ) { vec3 cw = normalize(ta-ro); - vec3 cp = vec3(sin(cr), cos(cr),0.0); - vec3 cu = normalize( cross(cw,cp) ); - vec3 cv = normalize( cross(cu,cw) ); + vec3 cp = vec3(sin(cr), cos(cr),0.0); + vec3 cu = normalize( cross(cw,cp) ); + vec3 cv = normalize( cross(cu,cw) ); return mat3( cu, cv, cw ); } @@ -403,7 +403,7 @@ void main() vec2 p = (-resolution.xy + 2.0*gl_FragCoord.xy)/resolution.y; #endif - // RAY: Camera is provided from raylib + // RAY: Camera is provided from raylib //vec3 ro = vec3( -0.5+3.5*cos(0.1*time + 6.0*mo.x), 1.0 + 2.0*mo.y, 0.5 + 4.0*sin(0.1*time + 6.0*mo.x) ); vec3 ro = viewEye; @@ -414,10 +414,10 @@ void main() // ray direction vec3 rd = ca * normalize( vec3(p.xy,2.0) ); - // render + // render vec3 col = render( ro, rd ); - // gamma + // gamma col = pow( col, vec3(0.4545) ); tot += col; diff --git a/examples/shaders/resources/shaders/glsl330/reload.fs b/examples/shaders/resources/shaders/glsl330/reload.fs index 9891a4b5f..21ce18e02 100644 --- a/examples/shaders/resources/shaders/glsl330/reload.fs +++ b/examples/shaders/resources/shaders/glsl330/reload.fs @@ -15,26 +15,26 @@ uniform float time; // Total run time (in secods) // Draw circle vec4 DrawCircle(vec2 fragCoord, vec2 position, float radius, vec3 color) { - float d = length(position - fragCoord) - radius; - float t = clamp(d, 0.0, 1.0); - return vec4(color, 1.0 - t); + float d = length(position - fragCoord) - radius; + float t = clamp(d, 0.0, 1.0); + return vec4(color, 1.0 - t); } void main() { - vec2 fragCoord = gl_FragCoord.xy; - vec2 position = vec2(mouse.x, resolution.y - mouse.y); - float radius = 40.0; + vec2 fragCoord = gl_FragCoord.xy; + vec2 position = vec2(mouse.x, resolution.y - mouse.y); + float radius = 40.0; // Draw background layer vec4 colorA = vec4(0.2,0.2,0.8, 1.0); vec4 colorB = vec4(1.0,0.7,0.2, 1.0); - vec4 layer1 = mix(colorA, colorB, abs(sin(time*0.1))); + vec4 layer1 = mix(colorA, colorB, abs(sin(time*0.1))); - // Draw circle layer - vec3 color = vec3(0.9, 0.16, 0.21); - vec4 layer2 = DrawCircle(fragCoord, position, radius, color); - - // Blend the two layers - finalColor = mix(layer1, layer2, layer2.a); + // Draw circle layer + vec3 color = vec3(0.9, 0.16, 0.21); + vec4 layer2 = DrawCircle(fragCoord, position, radius, color); + + // Blend the two layers + finalColor = mix(layer1, layer2, layer2.a); } diff --git a/examples/shaders/resources/shaders/glsl330/sobel.fs b/examples/shaders/resources/shaders/glsl330/sobel.fs index a1430cdd0..f317ae328 100644 --- a/examples/shaders/resources/shaders/glsl330/sobel.fs +++ b/examples/shaders/resources/shaders/glsl330/sobel.fs @@ -16,26 +16,26 @@ uniform vec2 resolution = vec2(800, 450); void main() { - float x = 1.0/resolution.x; - float y = 1.0/resolution.y; + float x = 1.0/resolution.x; + float y = 1.0/resolution.y; - vec4 horizEdge = vec4(0.0); - horizEdge -= texture2D(texture0, vec2(fragTexCoord.x - x, fragTexCoord.y - y))*1.0; - horizEdge -= texture2D(texture0, vec2(fragTexCoord.x - x, fragTexCoord.y ))*2.0; - horizEdge -= texture2D(texture0, vec2(fragTexCoord.x - x, fragTexCoord.y + y))*1.0; - horizEdge += texture2D(texture0, vec2(fragTexCoord.x + x, fragTexCoord.y - y))*1.0; - horizEdge += texture2D(texture0, vec2(fragTexCoord.x + x, fragTexCoord.y ))*2.0; - horizEdge += texture2D(texture0, vec2(fragTexCoord.x + x, fragTexCoord.y + y))*1.0; + vec4 horizEdge = vec4(0.0); + horizEdge -= texture2D(texture0, vec2(fragTexCoord.x - x, fragTexCoord.y - y))*1.0; + horizEdge -= texture2D(texture0, vec2(fragTexCoord.x - x, fragTexCoord.y ))*2.0; + horizEdge -= texture2D(texture0, vec2(fragTexCoord.x - x, fragTexCoord.y + y))*1.0; + horizEdge += texture2D(texture0, vec2(fragTexCoord.x + x, fragTexCoord.y - y))*1.0; + horizEdge += texture2D(texture0, vec2(fragTexCoord.x + x, fragTexCoord.y ))*2.0; + horizEdge += texture2D(texture0, vec2(fragTexCoord.x + x, fragTexCoord.y + y))*1.0; - vec4 vertEdge = vec4(0.0); - vertEdge -= texture2D(texture0, vec2(fragTexCoord.x - x, fragTexCoord.y - y))*1.0; - vertEdge -= texture2D(texture0, vec2(fragTexCoord.x , fragTexCoord.y - y))*2.0; - vertEdge -= texture2D(texture0, vec2(fragTexCoord.x + x, fragTexCoord.y - y))*1.0; - vertEdge += texture2D(texture0, vec2(fragTexCoord.x - x, fragTexCoord.y + y))*1.0; - vertEdge += texture2D(texture0, vec2(fragTexCoord.x , fragTexCoord.y + y))*2.0; - vertEdge += texture2D(texture0, vec2(fragTexCoord.x + x, fragTexCoord.y + y))*1.0; + vec4 vertEdge = vec4(0.0); + vertEdge -= texture2D(texture0, vec2(fragTexCoord.x - x, fragTexCoord.y - y))*1.0; + vertEdge -= texture2D(texture0, vec2(fragTexCoord.x , fragTexCoord.y - y))*2.0; + vertEdge -= texture2D(texture0, vec2(fragTexCoord.x + x, fragTexCoord.y - y))*1.0; + vertEdge += texture2D(texture0, vec2(fragTexCoord.x - x, fragTexCoord.y + y))*1.0; + vertEdge += texture2D(texture0, vec2(fragTexCoord.x , fragTexCoord.y + y))*2.0; + vertEdge += texture2D(texture0, vec2(fragTexCoord.x + x, fragTexCoord.y + y))*1.0; - vec3 edge = sqrt((horizEdge.rgb*horizEdge.rgb) + (vertEdge.rgb*vertEdge.rgb)); - - finalColor = vec4(edge, texture2D(texture0, fragTexCoord).a); + vec3 edge = sqrt((horizEdge.rgb*horizEdge.rgb) + (vertEdge.rgb*vertEdge.rgb)); + + finalColor = vec4(edge, texture2D(texture0, fragTexCoord).a); } \ No newline at end of file diff --git a/examples/shaders/resources/shaders/glsl330/spotlight.fs b/examples/shaders/resources/shaders/glsl330/spotlight.fs index 97a4377b4..c573be8f3 100644 --- a/examples/shaders/resources/shaders/glsl330/spotlight.fs +++ b/examples/shaders/resources/shaders/glsl330/spotlight.fs @@ -12,9 +12,9 @@ out vec4 finalColor; #define MAX_SPOTS 3 struct Spot { - vec2 pos; // window coords of spot - float inner; // inner fully transparent centre radius - float radius; // alpha fades out to this radius + vec2 pos; // window coords of spot + float inner; // inner fully transparent centre radius + float radius; // alpha fades out to this radius }; uniform Spot spots[MAX_SPOTS]; // Spotlight positions array @@ -22,44 +22,44 @@ uniform float screenWidth; // Width of the screen void main() { - float alpha = 1.0; + float alpha = 1.0; - // Get the position of the current fragment (screen coordinates!) - vec2 pos = vec2(gl_FragCoord.x, gl_FragCoord.y); - - // Find out which spotlight is nearest - float d = 65000; // some high value - int fi = -1; // found index + // Get the position of the current fragment (screen coordinates!) + vec2 pos = vec2(gl_FragCoord.x, gl_FragCoord.y); + + // Find out which spotlight is nearest + float d = 65000; // some high value + int fi = -1; // found index for (int i = 0; i < MAX_SPOTS; i++) { - for (int j = 0; j < MAX_SPOTS; j++) - { - float dj = distance(pos, spots[j].pos) - spots[j].radius + spots[i].radius; + for (int j = 0; j < MAX_SPOTS; j++) + { + float dj = distance(pos, spots[j].pos) - spots[j].radius + spots[i].radius; - if (d > dj) - { - d = dj; - fi = i; - } - } + if (d > dj) + { + d = dj; + fi = i; + } + } } // d now equals distance to nearest spot... // allowing for the different radii of all spotlights if (fi != -1) { - if (d > spots[fi].radius) alpha = 1.0; - else - { - if (d < spots[fi].inner) alpha = 0.0; - else alpha = (d - spots[fi].inner) / (spots[fi].radius - spots[fi].inner); - } - } - - // Right hand side of screen is dimly lit, + if (d > spots[fi].radius) alpha = 1.0; + else + { + if (d < spots[fi].inner) alpha = 0.0; + else alpha = (d - spots[fi].inner) / (spots[fi].radius - spots[fi].inner); + } + } + + // Right hand side of screen is dimly lit, // could make the threshold value user definable - if ((pos.x > screenWidth/2.0) && (alpha > 0.9)) alpha = 0.9; + if ((pos.x > screenWidth/2.0) && (alpha > 0.9)) alpha = 0.9; finalColor = vec4(0, 0, 0, alpha); } diff --git a/examples/shaders/resources/shaders/glsl330/wave.fs b/examples/shaders/resources/shaders/glsl330/wave.fs index f139f3957..43efee234 100644 --- a/examples/shaders/resources/shaders/glsl330/wave.fs +++ b/examples/shaders/resources/shaders/glsl330/wave.fs @@ -23,15 +23,15 @@ uniform float speedX; uniform float speedY; void main() { - float pixelWidth = 1.0 / size.x; - float pixelHeight = 1.0 / size.y; - float aspect = pixelHeight / pixelWidth; - float boxLeft = 0.0; - float boxTop = 0.0; + float pixelWidth = 1.0 / size.x; + float pixelHeight = 1.0 / size.y; + float aspect = pixelHeight / pixelWidth; + float boxLeft = 0.0; + float boxTop = 0.0; - vec2 p = fragTexCoord; - p.x += cos((fragTexCoord.y - boxTop) * freqX / ( pixelWidth * 750.0) + (secondes * speedX)) * ampX * pixelWidth; - p.y += sin((fragTexCoord.x - boxLeft) * freqY * aspect / ( pixelHeight * 750.0) + (secondes * speedY)) * ampY * pixelHeight; + vec2 p = fragTexCoord; + p.x += cos((fragTexCoord.y - boxTop) * freqX / ( pixelWidth * 750.0) + (secondes * speedX)) * ampX * pixelWidth; + p.y += sin((fragTexCoord.x - boxLeft) * freqY * aspect / ( pixelHeight * 750.0) + (secondes * speedY)) * ampY * pixelHeight; - finalColor = texture(texture0, p)*colDiffuse*fragColor; + finalColor = texture(texture0, p)*colDiffuse*fragColor; } diff --git a/projects/VSCode/Makefile b/projects/VSCode/Makefile index b15eb7f6f..5e09d668e 100644 --- a/projects/VSCode/Makefile +++ b/projects/VSCode/Makefile @@ -25,8 +25,7 @@ # Define required raylib variables PROJECT_NAME ?= game -RAYLIB_VERSION ?= 3.0.0 -RAYLIB_API_VERSION ?= 300 +RAYLIB_VERSION ?= 3.5.0 RAYLIB_PATH ?= ..\.. # Define compiler path on Windows diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 3319ef03d..d1d80652b 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -10,6 +10,8 @@ include(JoinPaths) if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) if(RAYLIB_IS_MAIN) set(default_build_type Debug) + else() + message(WARNING "Default build type is not set (CMAKE_BUILD_TYPE)") endif() message(STATUS "Setting build type to '${default_build_type}' as none was specified.") @@ -18,7 +20,7 @@ if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release" "MinSizeRel" "RelWithDebInfo") endif() -# Get the sources together +# Used as public API to be included into other projects set(raylib_public_headers raylib.h rlgl.h @@ -27,6 +29,7 @@ set(raylib_public_headers raudio.h ) +# Sources to be compiled set(raylib_sources core.c models.c @@ -36,7 +39,7 @@ set(raylib_sources utils.c ) -# cmake/GlfwImport.cmake handles the details around the inclusion of glfw +# /cmake/GlfwImport.cmake handles the details around the inclusion of glfw include(GlfwImport) @@ -47,56 +50,42 @@ else () MESSAGE(STATUS "Audio Backend: None (-DUSE_AUDIO=OFF)") endif () +# Sets additional platform options and link libraries for each platform +# also selects the proper graphics API and version for that platform +# Produces a variable LIBS_PRIVATE that will be used later include(LibraryConfigurations) -set(LIBS_PRIVATE ${LIBS_PRIVATE} ${OPENAL_LIBRARY}) +add_library(raylib ${raylib_sources} ${raylib_public_headers}) -if (STATIC) +if (NOT BUILD_SHARED_LIBS) MESSAGE(STATUS "Building raylib static library") - - add_library(raylib STATIC ${raylib_sources} ${raylib_public_headers}) add_library(raylib_static ALIAS raylib) - - add_test("pkg-config--static" ${PROJECT_SOURCE_DIR}/../cmake/test-pkgconfig.sh --static) -endif (STATIC) - - -if (SHARED) +else() MESSAGE(STATUS "Building raylib shared library") - add_library(raylib SHARED ${raylib_sources} ${raylib_public_headers}) - if (MSVC) target_compile_definitions(raylib PRIVATE $ INTERFACE $ ) endif () - - add_test("pkg-config" ${PROJECT_SOURCE_DIR}/../cmake/test-pkgconfig.sh) -endif () +endif() -# Setting target properties set_target_properties(raylib PROPERTIES PUBLIC_HEADER "${raylib_public_headers}" VERSION ${PROJECT_VERSION} SOVERSION ${API_VERSION} ) -if (WITH_PIC OR SHARED) +if (WITH_PIC OR BUILD_SHARED_LIBS) set_property(TARGET raylib PROPERTY POSITION_INDEPENDENT_CODE ON) endif () -# Linking libraries target_link_libraries(raylib "${LIBS_PRIVATE}") -if (${PLATFORM} MATCHES "Desktop") - target_link_libraries(raylib glfw) -endif () -# Adding compile definitions -target_compile_definitions(raylib - PUBLIC "${PLATFORM_CPP}" - PUBLIC "${GRAPHICS}" - ) +# Sets some compile time definitions for the pre-processor +# If CUSTOMIZE_BUILD option is on you will not use config.h by default +# and you will be able to select more build options +include(CompileDefinitions) # Registering include directories target_include_directories(raylib @@ -105,7 +94,6 @@ target_include_directories(raylib $ PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} - ${CMAKE_BINARY_DIR} # For cmake/config.h ${OPENGL_INCLUDE_DIR} ${OPENAL_INCLUDE_DIR} ) @@ -113,6 +101,8 @@ target_include_directories(raylib # Copy the header files to the build directory for convenience file(COPY ${raylib_public_headers} DESTINATION "include") +# Includes information on how the library will be installed on the system +# when cmake --install is run include(InstallConfigurations) # Print the flags for the user @@ -126,6 +116,7 @@ message(STATUS "Compiling with the flags:") message(STATUS " PLATFORM=" ${PLATFORM_CPP}) message(STATUS " GRAPHICS=" ${GRAPHICS}) +# Options if you want to create an installer using CPack include(PackConfigurations) enable_testing() diff --git a/src/config.h b/src/config.h index dbe77cd9f..f73804223 100644 --- a/src/config.h +++ b/src/config.h @@ -27,12 +27,6 @@ #define RAYLIB_VERSION "3.5" -// Edit to control what features Makefile'd raylib is compiled with -#if defined(RAYLIB_CMAKE) - // Edit cmake/RaylibOptions.cmake for CMake instead - #include "cmake/config.h" -#else - //------------------------------------------------------------------------------------ // Module: core - Configuration Flags //------------------------------------------------------------------------------------ @@ -217,6 +211,3 @@ //------------------------------------------------------------------------------------ #define MAX_TRACELOG_MSG_LENGTH 128 // Max length of one trace-log message #define MAX_UWP_MESSAGES 512 // Max UWP messages to process - - -#endif //defined(RAYLIB_CMAKE) diff --git a/src/config.h.in b/src/config.h.in deleted file mode 100644 index 4cb217b5c..000000000 --- a/src/config.h.in +++ /dev/null @@ -1,91 +0,0 @@ -// config.h.in - -// core.c -// Camera module is included (camera.h) and multiple predefined cameras are available: free, 1st/3rd person, orbital -#cmakedefine SUPPORT_CAMERA_SYSTEM 1 -// Gestures module is included (gestures.h) to support gestures detection: tap, hold, swipe, drag -#cmakedefine SUPPORT_GESTURES_SYSTEM 1 -// Mouse gestures are directly mapped like touches and processed by gestures system. -#cmakedefine SUPPORT_MOUSE_GESTURES 1 -// Reconfigure standard input to receive key inputs, works with SSH connection. -#cmakedefine SUPPORT_SSH_KEYBOARD_RPI 1 -// Use busy wait loop for timing sync, if not defined, a high-resolution timer is setup and used -#cmakedefine SUPPORT_BUSY_WAIT_LOOP 1 -// Wait for events passively (sleeping while no events) instead of polling them actively every frame -#cmakedefine SUPPORT_EVENTS_WAITING 1 -// Allow automatic screen capture of current screen pressing F12, defined in KeyCallback() -#cmakedefine SUPPORT_SCREEN_CAPTURE 1 -// Allow automatic gif recording of current screen pressing CTRL+F12, defined in KeyCallback() -#cmakedefine SUPPORT_GIF_RECORDING 1 -// Support high DPI displays -#cmakedefine SUPPORT_HIGH_DPI 1 -// Support CompressData() and DecompressData() functions -#cmakedefine SUPPORT_COMPRESSION_API 1 -// Support for persistent data storage -#cmakedefine SUPPORT_DATA_STORAGE 1 - -// rlgl.h -// Support VR simulation functionality (stereo rendering) -#cmakedefine SUPPORT_VR_SIMULATOR 1 - -// shapes.c -// Draw rectangle shapes using font texture white character instead of default white texture -#cmakedefine SUPPORT_FONT_TEXTURE 1 -// Use QUADS instead of TRIANGLES for drawing when possible -// Some lines-based shapes could still use lines -#cmakedefine SUPPORT_QUADS_DRAW_MODE 1 - -// textures.c -// Selecte desired fileformats to be supported for image data loading. -#cmakedefine SUPPORT_FILEFORMAT_PNG 1 -#cmakedefine SUPPORT_FILEFORMAT_DDS 1 -#cmakedefine SUPPORT_FILEFORMAT_HDR 1 -#cmakedefine SUPPORT_FILEFORMAT_KTX 1 -#cmakedefine SUPPORT_FILEFORMAT_ASTC 1 -#cmakedefine SUPPORT_FILEFORMAT_BMP 1 -#cmakedefine SUPPORT_FILEFORMAT_TGA 1 -#cmakedefine SUPPORT_FILEFORMAT_JPG 1 -#cmakedefine SUPPORT_FILEFORMAT_GIF 1 -#cmakedefine SUPPORT_FILEFORMAT_PSD 1 -#cmakedefine SUPPORT_FILEFORMAT_PKM 1 -#cmakedefine SUPPORT_FILEFORMAT_PVR 1 -// Support image export functionality (.png, .bmp, .tga, .jpg) -#define SUPPORT_IMAGE_EXPORT 1 -// Support multiple image editing functions to scale, adjust colors, flip, draw on images, crop... If not defined only three image editing functions supported: ImageFormat(), ImageAlphaMask(), ImageToPOT() -#cmakedefine SUPPORT_IMAGE_MANIPULATION 1 -// Support procedural image generation functionality (gradient, spot, perlin-noise, cellular) -#cmakedefine SUPPORT_IMAGE_GENERATION 1 - -// text.c -// Default font is loaded on window initialization to be available for the user to render simple text. NOTE: If enabled, uses external module functions to load default raylib font (module: text) -#cmakedefine SUPPORT_DEFAULT_FONT 1 -// Selected desired fileformats to be supported for loading. -#cmakedefine SUPPORT_FILEFORMAT_FNT 1 -#cmakedefine SUPPORT_FILEFORMAT_TTF 1 -// Support text management functions -// If not defined, still some functions are supported: TextLength(), TextFormat() -#cmakedefine SUPPORT_TEXT_MANIPULATION 1 - -// models.c -// Selected desired fileformats to be supported for loading. -#cmakedefine SUPPORT_FILEFORMAT_OBJ 1 -#cmakedefine SUPPORT_FILEFORMAT_MTL 1 -#cmakedefine SUPPORT_FILEFORMAT_IQM 1 -#cmakedefine SUPPORT_FILEFORMAT_GLTF 1 -// Support procedural mesh generation functions, uses external par_shapes.h library -// NOTE: Some generated meshes DO NOT include generated texture coordinates -#cmakedefine SUPPORT_MESH_GENERATION 1 - -// raudio.c -// Desired fileformats to be supported for loading. -#cmakedefine SUPPORT_FILEFORMAT_WAV 1 -#cmakedefine SUPPORT_FILEFORMAT_OGG 1 -#cmakedefine SUPPORT_FILEFORMAT_XM 1 -#cmakedefine SUPPORT_FILEFORMAT_MOD 1 -#cmakedefine SUPPORT_FILEFORMAT_FLAC 1 -#cmakedefine SUPPORT_FILEFORMAT_MP3 1 - -// utils.c -// Show TraceLog() output messages. NOTE: By default LOG_DEBUG traces not shown -#cmakedefine SUPPORT_TRACELOG 1 - diff --git a/src/core.c b/src/core.c index 3cac4796a..6b3906e71 100644 --- a/src/core.c +++ b/src/core.c @@ -189,13 +189,13 @@ #if defined(PLATFORM_DESKTOP) #define GLFW_INCLUDE_NONE // Disable the standard OpenGL header inclusion on GLFW3 // NOTE: Already provided by rlgl implementation (on glad.h) - #include // GLFW3 library: Windows, OpenGL context and Input management + #include "GLFW/glfw3.h" // GLFW3 library: Windows, OpenGL context and Input management // NOTE: GLFW3 already includes gl.h (OpenGL) headers // Support retrieving native window handlers #if defined(_WIN32) #define GLFW_EXPOSE_NATIVE_WIN32 - #include // WARNING: It requires customization to avoid windows.h inclusion! + #include "GLFW/glfw3native.h" // WARNING: It requires customization to avoid windows.h inclusion! #if !defined(SUPPORT_BUSY_WAIT_LOOP) // NOTE: Those functions require linking with winmm library @@ -209,12 +209,12 @@ //#define GLFW_EXPOSE_NATIVE_X11 // WARNING: Exposing Xlib.h > X.h results in dup symbols for Font type //#define GLFW_EXPOSE_NATIVE_WAYLAND //#define GLFW_EXPOSE_NATIVE_MIR - #include // Required for: glfwGetX11Window() + #include "GLFW/glfw3native.h" // Required for: glfwGetX11Window() #elif defined(__APPLE__) #include // Required for: usleep() //#define GLFW_EXPOSE_NATIVE_COCOA // WARNING: Fails due to type redefinition - #include // Required for: glfwGetCocoaWindow() + #include "GLFW/glfw3native.h" // Required for: glfwGetCocoaWindow() #endif #endif @@ -263,7 +263,7 @@ #if defined(PLATFORM_WEB) #define GLFW_INCLUDE_ES2 // GLFW3: Enable OpenGL ES 2.0 (translated to WebGL) - #include // GLFW3 library: Windows, OpenGL context and Input management + #include "GLFW/glfw3.h" // GLFW3 library: Windows, OpenGL context and Input management #include // Required for: timespec, nanosleep(), select() - POSIX #include // Emscripten library - LLVM to JavaScript compiler @@ -1738,6 +1738,9 @@ void EnableCursor(void) #if defined(PLATFORM_DESKTOP) glfwSetInputMode(CORE.Window.handle, GLFW_CURSOR, GLFW_CURSOR_NORMAL); #endif +#if defined(PLATFORM_WEB) + emscripten_exit_pointerlock(); +#endif #if defined(PLATFORM_UWP) UWPGetMouseUnlockFunc()(); #endif @@ -1750,6 +1753,9 @@ void DisableCursor(void) #if defined(PLATFORM_DESKTOP) glfwSetInputMode(CORE.Window.handle, GLFW_CURSOR, GLFW_CURSOR_DISABLED); #endif +#if defined(PLATFORM_WEB) + emscripten_request_pointerlock("#canvas", 1); +#endif #if defined(PLATFORM_UWP) UWPGetMouseLockFunc()(); #endif @@ -2854,9 +2860,7 @@ bool IsGamepadAvailable(int gamepad) { bool result = false; -#if !defined(PLATFORM_ANDROID) if ((gamepad < MAX_GAMEPADS) && CORE.Input.Gamepad.ready[gamepad]) result = true; -#endif return result; } @@ -2865,13 +2869,10 @@ bool IsGamepadAvailable(int gamepad) bool IsGamepadName(int gamepad, const char *name) { bool result = false; - -#if !defined(PLATFORM_ANDROID) const char *currentName = NULL; if (CORE.Input.Gamepad.ready[gamepad]) currentName = GetGamepadName(gamepad); if ((name != NULL) && (currentName != NULL)) result = (strcmp(name, currentName) == 0); -#endif return result; } @@ -2899,6 +2900,7 @@ int GetGamepadAxisCount(int gamepad) if (CORE.Input.Gamepad.ready[gamepad]) ioctl(CORE.Input.Gamepad.streamId[gamepad], JSIOCGAXES, &axisCount); CORE.Input.Gamepad.axisCount = axisCount; #endif + return CORE.Input.Gamepad.axisCount; } @@ -2907,11 +2909,8 @@ float GetGamepadAxisMovement(int gamepad, int axis) { float value = 0; -#if !defined(PLATFORM_ANDROID) if ((gamepad < MAX_GAMEPADS) && CORE.Input.Gamepad.ready[gamepad] && (axis < MAX_GAMEPAD_AXIS) && - ((axis == GAMEPAD_AXIS_LEFT_TRIGGER) || (axis == GAMEPAD_AXIS_RIGHT_TRIGGER) || - (fabsf(CORE.Input.Gamepad.axisState[gamepad][axis]) >= 0.2f))) value = CORE.Input.Gamepad.axisState[gamepad][axis]; -#endif + (fabsf(CORE.Input.Gamepad.axisState[gamepad][axis]) > 0.1f)) value = CORE.Input.Gamepad.axisState[gamepad][axis]; // 0.1f = GAMEPAD_AXIS_MINIMUM_DRIFT/DELTA return value; } @@ -2921,11 +2920,9 @@ bool IsGamepadButtonPressed(int gamepad, int button) { bool pressed = false; -#if !defined(PLATFORM_ANDROID) if ((gamepad < MAX_GAMEPADS) && CORE.Input.Gamepad.ready[gamepad] && (button < MAX_GAMEPAD_BUTTONS) && - (CORE.Input.Gamepad.currentState[gamepad][button] != CORE.Input.Gamepad.previousState[gamepad][button]) && - (CORE.Input.Gamepad.currentState[gamepad][button] == 1)) pressed = true; -#endif + (CORE.Input.Gamepad.previousState[gamepad][button] == 0) && (CORE.Input.Gamepad.currentState[gamepad][button] == 1)) pressed = true; + else pressed = false; return pressed; } @@ -2935,10 +2932,8 @@ bool IsGamepadButtonDown(int gamepad, int button) { bool result = false; -#if !defined(PLATFORM_ANDROID) if ((gamepad < MAX_GAMEPADS) && CORE.Input.Gamepad.ready[gamepad] && (button < MAX_GAMEPAD_BUTTONS) && (CORE.Input.Gamepad.currentState[gamepad][button] == 1)) result = true; -#endif return result; } @@ -2948,11 +2943,9 @@ bool IsGamepadButtonReleased(int gamepad, int button) { bool released = false; -#if !defined(PLATFORM_ANDROID) if ((gamepad < MAX_GAMEPADS) && CORE.Input.Gamepad.ready[gamepad] && (button < MAX_GAMEPAD_BUTTONS) && - (CORE.Input.Gamepad.currentState[gamepad][button] != CORE.Input.Gamepad.previousState[gamepad][button]) && - (CORE.Input.Gamepad.currentState[gamepad][button] == 0)) released = true; -#endif + (CORE.Input.Gamepad.previousState[gamepad][button] == 1) && (CORE.Input.Gamepad.currentState[gamepad][button] == 0)) released = true; + else released = false; return released; } @@ -2962,10 +2955,8 @@ bool IsGamepadButtonUp(int gamepad, int button) { bool result = false; -#if !defined(PLATFORM_ANDROID) if ((gamepad < MAX_GAMEPADS) && CORE.Input.Gamepad.ready[gamepad] && (button < MAX_GAMEPAD_BUTTONS) && (CORE.Input.Gamepad.currentState[gamepad][button] == 0)) result = true; -#endif return result; } @@ -2976,6 +2967,18 @@ int GetGamepadButtonPressed(void) return CORE.Input.Gamepad.lastButtonPressed; } +// Set internal gamepad mappings +int SetGamepadMappings(const char *mappings) +{ + int result = 0; + +#if defined(PLATFORM_DESKTOP) + result = glfwUpdateGamepadMappings(mappings); +#endif + + return result; +} + // Detect if a mouse button has been pressed once bool IsMouseButtonPressed(int button) { @@ -3275,7 +3278,11 @@ static bool InitGraphicsDevice(int width, int height) else glfwWindowHint(GLFW_SCALE_TO_MONITOR, GLFW_FALSE); #endif - if (CORE.Window.flags & FLAG_MSAA_4X_HINT) glfwWindowHint(GLFW_SAMPLES, 4); // Tries to enable multisampling x4 (MSAA), default is 0 + if (CORE.Window.flags & FLAG_MSAA_4X_HINT) + { + TRACELOG(LOG_INFO, "DISPLAY: Trying to enable MSAA x4"); + glfwWindowHint(GLFW_SAMPLES, 4); // Tries to enable multisampling x4 (MSAA), default is 0 + } // NOTE: When asking for an OpenGL context version, most drivers provide highest supported version // with forward compatibility to older OpenGL versions. @@ -4228,7 +4235,8 @@ static void Wait(float ms) // Get gamepad button generic to all platforms static int GetGamepadButton(int button) { - int btn = GAMEPAD_BUTTON_UNKNOWN; + int btn = -1; + #if defined(PLATFORM_DESKTOP) switch (button) { @@ -4317,6 +4325,16 @@ static void PollInputEvents(void) CORE.Input.Mouse.previousButtonState[i] = CORE.Input.Mouse.currentButtonState[i]; CORE.Input.Mouse.currentButtonState[i] = CORE.Input.Mouse.currentButtonStateEvdev[i]; } + + // Register gamepads buttons events + for (int i = 0; i < MAX_GAMEPADS; i++) + { + if (CORE.Input.Gamepad.ready[i]) // Check if gamepad is available + { + // Register previous gamepad states + for (int k = 0; k < MAX_GAMEPAD_BUTTONS; k++) CORE.Input.Gamepad.previousState[i][k] = CORE.Input.Gamepad.currentState[i][k]; + } + } #endif #if defined(PLATFORM_UWP) @@ -4615,6 +4633,7 @@ static void KeyCallback(GLFWwindow *window, int key, int scancode, int action, i // NOTE: Before closing window, while loop must be left! } +#if defined(SUPPORT_SCREEN_CAPTURE) else if (key == GLFW_KEY_F12 && action == GLFW_PRESS) { #if defined(SUPPORT_GIF_RECORDING) @@ -4657,14 +4676,13 @@ static void KeyCallback(GLFWwindow *window, int key, int scancode, int action, i } } else -#endif // SUPPORT_GIF_RECORDING -#if defined(SUPPORT_SCREEN_CAPTURE) +#endif // SUPPORT_GIF_RECORDING { TakeScreenshot(TextFormat("screenshot%03i.png", screenshotCounter)); screenshotCounter++; } -#endif // SUPPORT_SCREEN_CAPTURE } +#endif // SUPPORT_SCREEN_CAPTURE else { // WARNING: GLFW could return GLFW_REPEAT, we need to consider it as 1 @@ -5084,17 +5102,7 @@ static EM_BOOL EmscriptenMouseCallback(int eventType, const EmscriptenMouseEvent // Lock mouse pointer when click on screen if (eventType == EMSCRIPTEN_EVENT_CLICK) { - EmscriptenPointerlockChangeEvent plce; - emscripten_get_pointerlock_status(&plce); - - int result = emscripten_request_pointerlock("#canvas", 1); // TODO: It does not work! - - // result -> EMSCRIPTEN_RESULT_DEFERRED - // The requested operation cannot be completed now for web security reasons, - // and has been deferred for completion in the next event handler. --> but it never happens! - - //if (!plce.isActive) emscripten_request_pointerlock(0, 1); - //else emscripten_exit_pointerlock(); + // TODO: Manage mouse events if required (note that GLFW JS wrapper manages it now) } return 0; @@ -5896,7 +5904,7 @@ static void *GamepadThread(void *arg) // Process gamepad events by type if (gamepadEvent.type == JS_EVENT_BUTTON) { - TRACELOGD("RPI: Gamepad button: %i, value: %i", gamepadEvent.number, gamepadEvent.value); + //TRACELOG(LOG_WARNING, "RPI: Gamepad button: %i, value: %i", gamepadEvent.number, gamepadEvent.value); if (gamepadEvent.number < MAX_GAMEPAD_BUTTONS) { @@ -5909,7 +5917,7 @@ static void *GamepadThread(void *arg) } else if (gamepadEvent.type == JS_EVENT_AXIS) { - TRACELOGD("RPI: Gamepad axis: %i, value: %i", gamepadEvent.number, gamepadEvent.value); + //TRACELOG(LOG_WARNING, "RPI: Gamepad axis: %i, value: %i", gamepadEvent.number, gamepadEvent.value); if (gamepadEvent.number < MAX_GAMEPAD_AXIS) { @@ -5987,6 +5995,7 @@ void UWPKeyDownEvent(int key, bool down, bool controlKey) // Time to close the window. CORE.Window.shouldClose = true; } +#if defined(SUPPORT_SCREEN_CAPTURE) else if (key == KEY_F12 && down) { #if defined(SUPPORT_GIF_RECORDING) @@ -6020,14 +6029,13 @@ void UWPKeyDownEvent(int key, bool down, bool controlKey) } } else -#endif // SUPPORT_GIF_RECORDING -#if defined(SUPPORT_SCREEN_CAPTURE) +#endif // SUPPORT_GIF_RECORDING { TakeScreenshot(TextFormat("screenshot%03i.png", screenshotCounter)); screenshotCounter++; } -#endif // SUPPORT_SCREEN_CAPTURE } +#endif // SUPPORT_SCREEN_CAPTURE else { CORE.Input.Keyboard.currentKeyState[key] = down; diff --git a/src/models.c b/src/models.c index 60e08171c..b3b784317 100644 --- a/src/models.c +++ b/src/models.c @@ -114,9 +114,11 @@ static Model LoadOBJ(const char *fileName); // Load OBJ mesh data #endif #if defined(SUPPORT_FILEFORMAT_IQM) static Model LoadIQM(const char *fileName); // Load IQM mesh data +static ModelAnimation *LoadIQMModelAnimations(const char *fileName, int *animCount); // Load IQM animation data #endif #if defined(SUPPORT_FILEFORMAT_GLTF) static Model LoadGLTF(const char *fileName); // Load GLTF mesh data +static ModelAnimation *LoadGLTFModelAnimations(const char *fileName, int *animCount); // Load GLTF animation data #endif //---------------------------------------------------------------------------------- @@ -849,6 +851,12 @@ Mesh *LoadMeshes(const char *fileName, int *meshCount) return meshes; } +// Upload mesh vertex data to GPU +void UploadMesh(Mesh *mesh) +{ + rlLoadMesh(mesh, false); // Static mesh by default +} + // Unload mesh from memory (RAM and/or VRAM) void UnloadMesh(Mesh mesh) { @@ -1008,211 +1016,15 @@ void SetModelMeshMaterial(Model *model, int meshId, int materialId) // Load model animations from file ModelAnimation *LoadModelAnimations(const char *fileName, int *animCount) { - #define IQM_MAGIC "INTERQUAKEMODEL" // IQM file magic number - #define IQM_VERSION 2 // only IQM version 2 supported - - unsigned int fileSize = 0; - unsigned char *fileData = LoadFileData(fileName, &fileSize); - unsigned char *fileDataPtr = fileData; - - typedef struct IQMHeader { - char magic[16]; - unsigned int version; - unsigned int filesize; - unsigned int flags; - unsigned int num_text, ofs_text; - unsigned int num_meshes, ofs_meshes; - unsigned int num_vertexarrays, num_vertexes, ofs_vertexarrays; - unsigned int num_triangles, ofs_triangles, ofs_adjacency; - unsigned int num_joints, ofs_joints; - unsigned int num_poses, ofs_poses; - unsigned int num_anims, ofs_anims; - unsigned int num_frames, num_framechannels, ofs_frames, ofs_bounds; - unsigned int num_comment, ofs_comment; - unsigned int num_extensions, ofs_extensions; - } IQMHeader; - - typedef struct IQMPose { - int parent; - unsigned int mask; - float channeloffset[10]; - float channelscale[10]; - } IQMPose; - - typedef struct IQMAnim { - unsigned int name; - unsigned int first_frame, num_frames; - float framerate; - unsigned int flags; - } IQMAnim; - - // In case file can not be read, return an empty model - if (fileDataPtr == NULL) return NULL; - - // Read IQM header - IQMHeader *iqmHeader = (IQMHeader *)fileDataPtr; - - if (memcmp(iqmHeader->magic, IQM_MAGIC, sizeof(IQM_MAGIC)) != 0) - { - TRACELOG(LOG_WARNING, "MODEL: [%s] IQM file is not a valid model", fileName); - return NULL; - } - - if (iqmHeader->version != IQM_VERSION) - { - TRACELOG(LOG_WARNING, "MODEL: [%s] IQM file version not supported (%i)", fileName, iqmHeader->version); - return NULL; - } - - // Get bones data - IQMPose *poses = RL_MALLOC(iqmHeader->num_poses*sizeof(IQMPose)); - //fseek(iqmFile, iqmHeader->ofs_poses, SEEK_SET); - //fread(poses, iqmHeader->num_poses*sizeof(IQMPose), 1, iqmFile); - memcpy(poses, fileDataPtr + iqmHeader->ofs_poses, iqmHeader->num_poses*sizeof(IQMPose)); - - // Get animations data - *animCount = iqmHeader->num_anims; - IQMAnim *anim = RL_MALLOC(iqmHeader->num_anims*sizeof(IQMAnim)); - //fseek(iqmFile, iqmHeader->ofs_anims, SEEK_SET); - //fread(anim, iqmHeader->num_anims*sizeof(IQMAnim), 1, iqmFile); - memcpy(anim, fileDataPtr + iqmHeader->ofs_anims, iqmHeader->num_anims*sizeof(IQMAnim)); - - ModelAnimation *animations = RL_MALLOC(iqmHeader->num_anims*sizeof(ModelAnimation)); - - // frameposes - unsigned short *framedata = RL_MALLOC(iqmHeader->num_frames*iqmHeader->num_framechannels*sizeof(unsigned short)); - //fseek(iqmFile, iqmHeader->ofs_frames, SEEK_SET); - //fread(framedata, iqmHeader->num_frames*iqmHeader->num_framechannels*sizeof(unsigned short), 1, iqmFile); - memcpy(framedata, fileDataPtr + iqmHeader->ofs_frames, iqmHeader->num_frames*iqmHeader->num_framechannels*sizeof(unsigned short)); - - for (unsigned int a = 0; a < iqmHeader->num_anims; a++) - { - animations[a].frameCount = anim[a].num_frames; - animations[a].boneCount = iqmHeader->num_poses; - animations[a].bones = RL_MALLOC(iqmHeader->num_poses*sizeof(BoneInfo)); - animations[a].framePoses = RL_MALLOC(anim[a].num_frames*sizeof(Transform *)); - //animations[a].framerate = anim.framerate; // TODO: Use framerate? - - for (unsigned int j = 0; j < iqmHeader->num_poses; j++) - { - strcpy(animations[a].bones[j].name, "ANIMJOINTNAME"); - animations[a].bones[j].parent = poses[j].parent; - } - - for (unsigned int j = 0; j < anim[a].num_frames; j++) animations[a].framePoses[j] = RL_MALLOC(iqmHeader->num_poses*sizeof(Transform)); - - int dcounter = anim[a].first_frame*iqmHeader->num_framechannels; - - for (unsigned int frame = 0; frame < anim[a].num_frames; frame++) - { - for (unsigned int i = 0; i < iqmHeader->num_poses; i++) - { - animations[a].framePoses[frame][i].translation.x = poses[i].channeloffset[0]; - - if (poses[i].mask & 0x01) - { - animations[a].framePoses[frame][i].translation.x += framedata[dcounter]*poses[i].channelscale[0]; - dcounter++; - } - - animations[a].framePoses[frame][i].translation.y = poses[i].channeloffset[1]; - - if (poses[i].mask & 0x02) - { - animations[a].framePoses[frame][i].translation.y += framedata[dcounter]*poses[i].channelscale[1]; - dcounter++; - } - - animations[a].framePoses[frame][i].translation.z = poses[i].channeloffset[2]; - - if (poses[i].mask & 0x04) - { - animations[a].framePoses[frame][i].translation.z += framedata[dcounter]*poses[i].channelscale[2]; - dcounter++; - } - - animations[a].framePoses[frame][i].rotation.x = poses[i].channeloffset[3]; - - if (poses[i].mask & 0x08) - { - animations[a].framePoses[frame][i].rotation.x += framedata[dcounter]*poses[i].channelscale[3]; - dcounter++; - } - - animations[a].framePoses[frame][i].rotation.y = poses[i].channeloffset[4]; - - if (poses[i].mask & 0x10) - { - animations[a].framePoses[frame][i].rotation.y += framedata[dcounter]*poses[i].channelscale[4]; - dcounter++; - } - - animations[a].framePoses[frame][i].rotation.z = poses[i].channeloffset[5]; - - if (poses[i].mask & 0x20) - { - animations[a].framePoses[frame][i].rotation.z += framedata[dcounter]*poses[i].channelscale[5]; - dcounter++; - } - - animations[a].framePoses[frame][i].rotation.w = poses[i].channeloffset[6]; - - if (poses[i].mask & 0x40) - { - animations[a].framePoses[frame][i].rotation.w += framedata[dcounter]*poses[i].channelscale[6]; - dcounter++; - } - - animations[a].framePoses[frame][i].scale.x = poses[i].channeloffset[7]; - - if (poses[i].mask & 0x80) - { - animations[a].framePoses[frame][i].scale.x += framedata[dcounter]*poses[i].channelscale[7]; - dcounter++; - } - - animations[a].framePoses[frame][i].scale.y = poses[i].channeloffset[8]; - - if (poses[i].mask & 0x100) - { - animations[a].framePoses[frame][i].scale.y += framedata[dcounter]*poses[i].channelscale[8]; - dcounter++; - } - - animations[a].framePoses[frame][i].scale.z = poses[i].channeloffset[9]; - - if (poses[i].mask & 0x200) - { - animations[a].framePoses[frame][i].scale.z += framedata[dcounter]*poses[i].channelscale[9]; - dcounter++; - } - - animations[a].framePoses[frame][i].rotation = QuaternionNormalize(animations[a].framePoses[frame][i].rotation); - } - } - - // Build frameposes - for (unsigned int frame = 0; frame < anim[a].num_frames; frame++) - { - for (int i = 0; i < animations[a].boneCount; i++) - { - if (animations[a].bones[i].parent >= 0) - { - animations[a].framePoses[frame][i].rotation = QuaternionMultiply(animations[a].framePoses[frame][animations[a].bones[i].parent].rotation, animations[a].framePoses[frame][i].rotation); - animations[a].framePoses[frame][i].translation = Vector3RotateByQuaternion(animations[a].framePoses[frame][i].translation, animations[a].framePoses[frame][animations[a].bones[i].parent].rotation); - animations[a].framePoses[frame][i].translation = Vector3Add(animations[a].framePoses[frame][i].translation, animations[a].framePoses[frame][animations[a].bones[i].parent].translation); - animations[a].framePoses[frame][i].scale = Vector3Multiply(animations[a].framePoses[frame][i].scale, animations[a].framePoses[frame][animations[a].bones[i].parent].scale); - } - } - } - } - - RL_FREE(fileData); - - RL_FREE(framedata); - RL_FREE(poses); - RL_FREE(anim); + ModelAnimation *animations = NULL; +#if defined(SUPPORT_FILEFORMAT_IQM) + if (IsFileExtension(fileName, ".iqm")) animations = LoadIQMModelAnimations(fileName, animCount); +#endif +#if defined(SUPPORT_FILEFORMAT_GLTF) + if (IsFileExtension(fileName, ".gltf;.glb")) animations = LoadGLTFModelAnimations(fileName, animCount); +#endif + return animations; } @@ -3548,6 +3360,218 @@ static Model LoadIQM(const char *fileName) return model; } + +// Load IQM animation data +static ModelAnimation* LoadIQMModelAnimations(const char* fileName, int* animCount) +{ +#define IQM_MAGIC "INTERQUAKEMODEL" // IQM file magic number +#define IQM_VERSION 2 // only IQM version 2 supported + + unsigned int fileSize = 0; + unsigned char *fileData = LoadFileData(fileName, &fileSize); + unsigned char *fileDataPtr = fileData; + + typedef struct IQMHeader { + char magic[16]; + unsigned int version; + unsigned int filesize; + unsigned int flags; + unsigned int num_text, ofs_text; + unsigned int num_meshes, ofs_meshes; + unsigned int num_vertexarrays, num_vertexes, ofs_vertexarrays; + unsigned int num_triangles, ofs_triangles, ofs_adjacency; + unsigned int num_joints, ofs_joints; + unsigned int num_poses, ofs_poses; + unsigned int num_anims, ofs_anims; + unsigned int num_frames, num_framechannels, ofs_frames, ofs_bounds; + unsigned int num_comment, ofs_comment; + unsigned int num_extensions, ofs_extensions; + } IQMHeader; + + typedef struct IQMPose { + int parent; + unsigned int mask; + float channeloffset[10]; + float channelscale[10]; + } IQMPose; + + typedef struct IQMAnim { + unsigned int name; + unsigned int first_frame, num_frames; + float framerate; + unsigned int flags; + } IQMAnim; + + // In case file can not be read, return an empty model + if (fileDataPtr == NULL) return NULL; + + // Read IQM header + IQMHeader *iqmHeader = (IQMHeader *)fileDataPtr; + + if (memcmp(iqmHeader->magic, IQM_MAGIC, sizeof(IQM_MAGIC)) != 0) + { + TRACELOG(LOG_WARNING, "MODEL: [%s] IQM file is not a valid model", fileName); + return NULL; + } + + if (iqmHeader->version != IQM_VERSION) + { + TRACELOG(LOG_WARNING, "MODEL: [%s] IQM file version not supported (%i)", fileName, iqmHeader->version); + return NULL; + } + + // Get bones data + IQMPose *poses = RL_MALLOC(iqmHeader->num_poses*sizeof(IQMPose)); + //fseek(iqmFile, iqmHeader->ofs_poses, SEEK_SET); + //fread(poses, iqmHeader->num_poses*sizeof(IQMPose), 1, iqmFile); + memcpy(poses, fileDataPtr + iqmHeader->ofs_poses, iqmHeader->num_poses*sizeof(IQMPose)); + + // Get animations data + *animCount = iqmHeader->num_anims; + IQMAnim *anim = RL_MALLOC(iqmHeader->num_anims*sizeof(IQMAnim)); + //fseek(iqmFile, iqmHeader->ofs_anims, SEEK_SET); + //fread(anim, iqmHeader->num_anims*sizeof(IQMAnim), 1, iqmFile); + memcpy(anim, fileDataPtr + iqmHeader->ofs_anims, iqmHeader->num_anims*sizeof(IQMAnim)); + + ModelAnimation *animations = RL_MALLOC(iqmHeader->num_anims*sizeof(ModelAnimation)); + + // frameposes + unsigned short *framedata = RL_MALLOC(iqmHeader->num_frames*iqmHeader->num_framechannels*sizeof(unsigned short)); + //fseek(iqmFile, iqmHeader->ofs_frames, SEEK_SET); + //fread(framedata, iqmHeader->num_frames*iqmHeader->num_framechannels*sizeof(unsigned short), 1, iqmFile); + memcpy(framedata, fileDataPtr + iqmHeader->ofs_frames, iqmHeader->num_frames*iqmHeader->num_framechannels*sizeof(unsigned short)); + + for (unsigned int a = 0; a < iqmHeader->num_anims; a++) + { + animations[a].frameCount = anim[a].num_frames; + animations[a].boneCount = iqmHeader->num_poses; + animations[a].bones = RL_MALLOC(iqmHeader->num_poses*sizeof(BoneInfo)); + animations[a].framePoses = RL_MALLOC(anim[a].num_frames*sizeof(Transform *)); + //animations[a].framerate = anim.framerate; // TODO: Use framerate? + + for (unsigned int j = 0; j < iqmHeader->num_poses; j++) + { + strcpy(animations[a].bones[j].name, "ANIMJOINTNAME"); + animations[a].bones[j].parent = poses[j].parent; + } + + for (unsigned int j = 0; j < anim[a].num_frames; j++) animations[a].framePoses[j] = RL_MALLOC(iqmHeader->num_poses*sizeof(Transform)); + + int dcounter = anim[a].first_frame*iqmHeader->num_framechannels; + + for (unsigned int frame = 0; frame < anim[a].num_frames; frame++) + { + for (unsigned int i = 0; i < iqmHeader->num_poses; i++) + { + animations[a].framePoses[frame][i].translation.x = poses[i].channeloffset[0]; + + if (poses[i].mask & 0x01) + { + animations[a].framePoses[frame][i].translation.x += framedata[dcounter]*poses[i].channelscale[0]; + dcounter++; + } + + animations[a].framePoses[frame][i].translation.y = poses[i].channeloffset[1]; + + if (poses[i].mask & 0x02) + { + animations[a].framePoses[frame][i].translation.y += framedata[dcounter]*poses[i].channelscale[1]; + dcounter++; + } + + animations[a].framePoses[frame][i].translation.z = poses[i].channeloffset[2]; + + if (poses[i].mask & 0x04) + { + animations[a].framePoses[frame][i].translation.z += framedata[dcounter]*poses[i].channelscale[2]; + dcounter++; + } + + animations[a].framePoses[frame][i].rotation.x = poses[i].channeloffset[3]; + + if (poses[i].mask & 0x08) + { + animations[a].framePoses[frame][i].rotation.x += framedata[dcounter]*poses[i].channelscale[3]; + dcounter++; + } + + animations[a].framePoses[frame][i].rotation.y = poses[i].channeloffset[4]; + + if (poses[i].mask & 0x10) + { + animations[a].framePoses[frame][i].rotation.y += framedata[dcounter]*poses[i].channelscale[4]; + dcounter++; + } + + animations[a].framePoses[frame][i].rotation.z = poses[i].channeloffset[5]; + + if (poses[i].mask & 0x20) + { + animations[a].framePoses[frame][i].rotation.z += framedata[dcounter]*poses[i].channelscale[5]; + dcounter++; + } + + animations[a].framePoses[frame][i].rotation.w = poses[i].channeloffset[6]; + + if (poses[i].mask & 0x40) + { + animations[a].framePoses[frame][i].rotation.w += framedata[dcounter]*poses[i].channelscale[6]; + dcounter++; + } + + animations[a].framePoses[frame][i].scale.x = poses[i].channeloffset[7]; + + if (poses[i].mask & 0x80) + { + animations[a].framePoses[frame][i].scale.x += framedata[dcounter]*poses[i].channelscale[7]; + dcounter++; + } + + animations[a].framePoses[frame][i].scale.y = poses[i].channeloffset[8]; + + if (poses[i].mask & 0x100) + { + animations[a].framePoses[frame][i].scale.y += framedata[dcounter]*poses[i].channelscale[8]; + dcounter++; + } + + animations[a].framePoses[frame][i].scale.z = poses[i].channeloffset[9]; + + if (poses[i].mask & 0x200) + { + animations[a].framePoses[frame][i].scale.z += framedata[dcounter]*poses[i].channelscale[9]; + dcounter++; + } + + animations[a].framePoses[frame][i].rotation = QuaternionNormalize(animations[a].framePoses[frame][i].rotation); + } + } + + // Build frameposes + for (unsigned int frame = 0; frame < anim[a].num_frames; frame++) + { + for (int i = 0; i < animations[a].boneCount; i++) + { + if (animations[a].bones[i].parent >= 0) + { + animations[a].framePoses[frame][i].rotation = QuaternionMultiply(animations[a].framePoses[frame][animations[a].bones[i].parent].rotation, animations[a].framePoses[frame][i].rotation); + animations[a].framePoses[frame][i].translation = Vector3RotateByQuaternion(animations[a].framePoses[frame][i].translation, animations[a].framePoses[frame][animations[a].bones[i].parent].rotation); + animations[a].framePoses[frame][i].translation = Vector3Add(animations[a].framePoses[frame][i].translation, animations[a].framePoses[frame][animations[a].bones[i].parent].translation); + animations[a].framePoses[frame][i].scale = Vector3Multiply(animations[a].framePoses[frame][i].scale, animations[a].framePoses[frame][animations[a].bones[i].parent].scale); + } + } + } + } + + RL_FREE(fileData); + + RL_FREE(framedata); + RL_FREE(poses); + RL_FREE(anim); + + return animations; +} + #endif #if defined(SUPPORT_FILEFORMAT_GLTF) @@ -3757,7 +3781,8 @@ static Model LoadGLTF(const char *fileName) int primitivesCount = 0; - for (unsigned int i = 0; i < data->meshes_count; i++) primitivesCount += (int)data->meshes[i].primitives_count; + for (unsigned int i = 0; i < data->meshes_count; i++) + primitivesCount += (int)data->meshes[i].primitives_count; // Process glTF data and map to model model.meshCount = primitivesCount; @@ -3765,9 +3790,65 @@ static Model LoadGLTF(const char *fileName) model.materialCount = (int)data->materials_count + 1; model.materials = RL_MALLOC(model.materialCount*sizeof(Material)); model.meshMaterial = RL_MALLOC(model.meshCount*sizeof(int)); + model.boneCount = data->nodes_count; + model.bones = RL_CALLOC(model.boneCount, sizeof(BoneInfo)); + model.bindPose = RL_CALLOC(model.boneCount, sizeof(Transform)); - for (int i = 0; i < model.meshCount; i++) model.meshes[i].vboId = (unsigned int *)RL_CALLOC(DEFAULT_MESH_VERTEX_BUFFERS, sizeof(unsigned int)); - + for (int i = 0; i < model.meshCount; i++) + model.meshes[i].vboId = (unsigned int *)RL_CALLOC(DEFAULT_MESH_VERTEX_BUFFERS, sizeof(unsigned int)); + + for (unsigned int j = 0; j < data->nodes_count; j++) + { + strcpy(model.bones[j].name, data->nodes[j].name == 0 ? "ANIMJOINT" : data->nodes[j].name); + model.bones[j].parent = j != 0 ? data->nodes[j].parent - data->nodes : 0; + } + + for (unsigned int i = 0; i < data->nodes_count; i++) + { + if(data->nodes[i].has_translation) + { + memcpy(&model.bindPose[i].translation, data->nodes[i].translation, 3 * sizeof(float)); + } + else + { + model.bindPose[i].translation = Vector3Zero(); + } + + if(data->nodes[i].has_rotation) + { + memcpy(&model.bindPose[i].rotation, data->nodes[i].rotation, 4 * sizeof(float)); + } + else + { + model.bindPose[i].rotation = QuaternionIdentity(); + } + model.bindPose[i].rotation = QuaternionNormalize(model.bindPose[i].rotation); + + if(data->nodes[i].has_scale) + { + memcpy(&model.bindPose[i].scale, data->nodes[i].scale, 3 * sizeof(float)); + } + else + { + model.bindPose[i].scale = Vector3One(); + } + } + + for (int i = 0; i < model.boneCount; i++) + { + Transform* currentTransform = model.bindPose + i; + BoneInfo* currentBone = model.bones + i; + Transform* parentTransform = model.bindPose + currentBone->parent; + + if (currentBone->parent >= 0) + { + currentTransform->rotation = QuaternionMultiply(parentTransform->rotation, currentTransform->rotation); + currentTransform->translation = Vector3RotateByQuaternion(currentTransform->translation, parentTransform->rotation); + currentTransform->translation = Vector3Add(currentTransform->translation, parentTransform->translation); + currentTransform->scale = Vector3Multiply(parentTransform->scale, parentTransform->scale); + } + } + for (int i = 0; i < model.materialCount - 1; i++) { model.materials[i] = LoadMaterialDefault(); @@ -3848,16 +3929,22 @@ static Model LoadGLTF(const char *fileName) { cgltf_accessor *acc = data->meshes[i].primitives[p].attributes[j].data; model.meshes[primitiveIndex].vertexCount = (int)acc->count; - model.meshes[primitiveIndex].vertices = RL_MALLOC(model.meshes[primitiveIndex].vertexCount*3*sizeof(float)); + int bufferSize = model.meshes[primitiveIndex].vertexCount * 3 * sizeof(float); + model.meshes[primitiveIndex].vertices = RL_MALLOC(bufferSize); + model.meshes[primitiveIndex].animVertices = RL_MALLOC(bufferSize); - LOAD_ACCESSOR(float, 3, acc, model.meshes[primitiveIndex].vertices) + LOAD_ACCESSOR(float, 3, acc, model.meshes[primitiveIndex].vertices); + memcpy(model.meshes[primitiveIndex].animVertices, model.meshes[primitiveIndex].vertices, bufferSize); } else if (data->meshes[i].primitives[p].attributes[j].type == cgltf_attribute_type_normal) { cgltf_accessor *acc = data->meshes[i].primitives[p].attributes[j].data; - model.meshes[primitiveIndex].normals = RL_MALLOC(acc->count*3*sizeof(float)); + int bufferSize = acc->count*3*sizeof(float); + model.meshes[primitiveIndex].normals = RL_MALLOC(bufferSize); + model.meshes[primitiveIndex].animNormals = RL_MALLOC(bufferSize); - LOAD_ACCESSOR(float, 3, acc, model.meshes[primitiveIndex].normals) + LOAD_ACCESSOR(float, 3, acc, model.meshes[primitiveIndex].normals); + memcpy(model.meshes[primitiveIndex].animNormals, model.meshes[primitiveIndex].normals, bufferSize); } else if (data->meshes[i].primitives[p].attributes[j].type == cgltf_attribute_type_texcoord) { @@ -3874,6 +3961,45 @@ static Model LoadGLTF(const char *fileName) TRACELOG(LOG_WARNING, "MODEL: [%s] glTF texture coordinates must be float", fileName); } } + else if (data->meshes[i].primitives[p].attributes[j].type == cgltf_attribute_type_joints) + { + cgltf_accessor *acc = data->meshes[i].primitives[p].attributes[j].data; + + if(acc->component_type == cgltf_component_type_r_16u) + { + model.meshes[primitiveIndex].boneIds = RL_MALLOC(sizeof(int) * acc->count * 4); + short* bones = RL_MALLOC(sizeof(short) * acc->count * 4); + + LOAD_ACCESSOR(short, 4, acc, bones); + for(int a = 0; a < acc->count * 4; a ++) + { + cgltf_node* skinJoint = data->skins->joints[bones[a]]; + + for(int k = 0; k < data->nodes_count; k++) + { + if(&(data->nodes[k]) == skinJoint) + { + model.meshes[primitiveIndex].boneIds[a] = k; + break; + } + } + } + RL_FREE(bones); + } + else + { + // TODO: Support other size of bone index? + TRACELOG(LOG_WARNING, "MODEL: [%s] glTF bones in unexpected format", fileName); + } + + } + else if (data->meshes[i].primitives[p].attributes[j].type == cgltf_attribute_type_weights) + { + cgltf_accessor *acc = data->meshes[i].primitives[p].attributes[j].data; + + model.meshes[primitiveIndex].boneWeights = RL_MALLOC(acc->count*4*sizeof(float)); + LOAD_ACCESSOR(float, 4, acc, model.meshes[primitiveIndex].boneWeights) + } } cgltf_accessor *acc = data->meshes[i].primitives[p].indices; @@ -3907,9 +4033,12 @@ static Model LoadGLTF(const char *fileName) { model.meshMaterial[primitiveIndex] = model.materialCount - 1;; } - + +// if(data->meshes[i].) + primitiveIndex++; } + } cgltf_free(data); @@ -3920,4 +4049,146 @@ static Model LoadGLTF(const char *fileName) return model; } + +// LoadGLTF loads in animation data from given filename +static ModelAnimation* LoadGLTFModelAnimations(const char *fileName, int *animCount) +{ + /*********************************************************************************** + + Function implemented by Hristo Stamenov (@object71) + + Features: + - Supports .gltf and .glb files + + Some restrictions (not exhaustive): + - ... + + *************************************************************************************/ + // glTF file loading + unsigned int dataSize = 0; + unsigned char *fileData = LoadFileData(fileName, &dataSize); + + ModelAnimation *animations = NULL; + + if (fileData == NULL) return animations; + + // glTF data loading + cgltf_options options = { 0 }; + cgltf_data *data = NULL; + cgltf_result result = cgltf_parse(&options, fileData, dataSize, &data); + + if (result == cgltf_result_success) + { + TRACELOG(LOG_INFO, "MODEL: [%s] glTF animations (%s) count: %i", fileName, (data->file_type == 2)? "glb" : + "gltf", data->animations_count); + + animations = RL_MALLOC(data->animations_count*sizeof(ModelAnimation)); + + for (unsigned int a = 0; a < data->animations_count; a++) + { + cgltf_animation *animation = data->animations + a; + + ModelAnimation *output = animations + a; + + output->frameCount = animation->channels->sampler->input->count; + output->boneCount = data->nodes_count; + output->bones = RL_MALLOC(output->boneCount*sizeof(BoneInfo)); + output->framePoses = RL_MALLOC(output->frameCount*sizeof(Transform *)); + + for (unsigned int j = 0; j < data->nodes_count; j++) + { + strcpy(output->bones[j].name, data->nodes[j].name == 0 ? "ANIMJOINT" : data->nodes[j].name); + output->bones[j].parent = j != 0 ? (int)(data->nodes[j].parent - data->nodes) : 0; + } + + for (unsigned int j = 0; j < output->frameCount; j++) + output->framePoses[j] = RL_MALLOC(output->frameCount*data->nodes_count*sizeof(Transform)); + + for (unsigned int frame = 0; frame < output->frameCount; frame++) + { + for (unsigned int i = 0; i < data->nodes_count; i++) + { + output->framePoses[frame][i].translation = Vector3Zero(); + output->framePoses[frame][i].rotation = QuaternionIdentity(); + output->framePoses[frame][i].rotation = QuaternionNormalize(output->framePoses[frame][i].rotation); + output->framePoses[frame][i].scale = Vector3One(); + } + } + + for(int channelId = 0; channelId < animation->channels_count; channelId++) + { + cgltf_animation_channel* channel = animation->channels + channelId; + cgltf_animation_sampler* sampler = channel->sampler; + + int boneId = channel->target_node - data->nodes; + + for(int frame = 0; frame < output->frameCount; frame++) + { + if(channel->target_path == cgltf_animation_path_type_translation) { + Vector3 translation; + if(cgltf_accessor_read_float(sampler->output, frame, (float*)&translation, 3)) + { + output->framePoses[frame][boneId].translation = translation; + } + else if (output->frameCount == 2) + { + memcpy(&translation, frame == 0 ? &(sampler->output->min) : &(sampler->output->max), 3 * sizeof(float)); + output->framePoses[frame][boneId].translation = translation; + } + } + if(channel->target_path == cgltf_animation_path_type_rotation) { + Quaternion rotation; + if(cgltf_accessor_read_float(sampler->output, frame, (float*)&rotation, 4)) + { + output->framePoses[frame][boneId].rotation = rotation; + output->framePoses[frame][boneId].rotation = QuaternionNormalize(output->framePoses[frame][boneId].rotation); + } + else if (output->frameCount == 2) + { + memcpy(&rotation, frame == 0 ? &(sampler->output->min) : &(sampler->output->max), 4 * sizeof(float)); + output->framePoses[frame][boneId].rotation = rotation; + output->framePoses[frame][boneId].rotation = QuaternionNormalize(output->framePoses[frame][boneId].rotation); + } + } + if(channel->target_path == cgltf_animation_path_type_scale) { + Vector3 scale; + if(cgltf_accessor_read_float(sampler->output, frame, (float*)&scale, 4)) + { + output->framePoses[frame][boneId].scale = scale; + } + else if (output->frameCount == 2) + { + memcpy(&scale, frame == 0 ? &(sampler->output->min) : &(sampler->output->max), 3 * sizeof(float)); + output->framePoses[frame][boneId].scale = scale; + } + } + } + } + + // Build frameposes + for (unsigned int frame = 0; frame < output->frameCount; frame++) + { + for (int i = 0; i < output->boneCount; i++) + { + if (output->bones[i].parent >= 0) + { + output->framePoses[frame][i].rotation = QuaternionMultiply(output->framePoses[frame][output->bones[i].parent].rotation, output->framePoses[frame][i].rotation); + output->framePoses[frame][i].translation = Vector3RotateByQuaternion(output->framePoses[frame][i].translation, output->framePoses[frame][output->bones[i].parent].rotation); + output->framePoses[frame][i].translation = Vector3Add(output->framePoses[frame][i].translation, output->framePoses[frame][output->bones[i].parent].translation); + output->framePoses[frame][i].scale = Vector3Multiply(output->framePoses[frame][i].scale, output->framePoses[frame][output->bones[i].parent].scale); + } + } + } + + } + + cgltf_free(data); + } + else TRACELOG(LOG_WARNING, ": [%s] Failed to load glTF data", fileName); + + RL_FREE(fileData); + + return animations; +} + #endif diff --git a/src/physac.h b/src/physac.h index c3898d2fc..695e399d4 100644 --- a/src/physac.h +++ b/src/physac.h @@ -1,6 +1,6 @@ /********************************************************************************************** * -* Physac v1.0 - 2D Physics library for videogames +* Physac v1.1 - 2D Physics library for videogames * * DESCRIPTION: * @@ -20,38 +20,44 @@ * The generated implementation will stay private inside implementation file and all * internal symbols and functions will only be visible inside that file. * -* #define PHYSAC_NO_THREADS -* The generated implementation won't include pthread library and user must create a secondary thread to call PhysicsThread(). -* It is so important that the thread where PhysicsThread() is called must not have v-sync or any other CPU limitation. -* -* #define PHYSAC_STANDALONE -* Avoid raylib.h header inclusion in this file. Data types defined on raylib are defined -* internally in the library and input management and drawing functions must be provided by -* the user (check library implementation for further details). -* * #define PHYSAC_DEBUG -* Traces log messages when creating and destroying physics bodies and detects errors in physics -* calculations and reference exceptions; it is useful for debug purposes +* Show debug traces log messages about physic bodies creation/destruction, physic system errors, +* some calculations results and NULL reference exceptions +* +* #define PHYSAC_DEFINE_VECTOR2_TYPE +* Forces library to define struct Vector2 data type (float x; float y) +* +* #define PHYSAC_AVOID_TIMMING_SYSTEM +* Disables internal timming system, used by UpdatePhysics() to launch timmed physic steps, +* it allows just running UpdatePhysics() automatically on a separate thread at a desired time step. +* In case physics steps update needs to be controlled by user with a custom timming mechanism, +* just define this flag and the internal timming mechanism will be avoided, in that case, +* timming libraries are neither required by the module. * * #define PHYSAC_MALLOC() +* #define PHYSAC_CALLOC() * #define PHYSAC_FREE() * You can define your own malloc/free implementation replacing stdlib.h malloc()/free() functions. * Otherwise it will include stdlib.h and use the C standard library malloc()/free() function. * +* COMPILATION: * -* NOTE 1: Physac requires multi-threading, when InitPhysics() a second thread is created to manage physics calculations. -* NOTE 2: Physac requires static C library linkage to avoid dependency on MinGW DLL (-static -lpthread) +* Use the following code to compile with GCC: +* gcc -o $(NAME_PART).exe $(FILE_NAME) -s -static -lraylib -lopengl32 -lgdi32 -lwinmm -std=c99 * -* Use the following code to compile: -* gcc -o $(NAME_PART).exe $(FILE_NAME) -s -static -lraylib -lpthread -lopengl32 -lgdi32 -lwinmm -std=c99 -* -* VERY THANKS TO: -* Ramon Santamaria (github: @raysan5) +* VERSIONS HISTORY: +* 1.1 (20-Jan-2021) @raysan5: Library general revision +* Removed threading system (up to the user) +* Support MSVC C++ compilation using CLITERAL() +* Review DEBUG mechanism for TRACELOG() and all TRACELOG() messages +* Review internal variables/functions naming for consistency +* Allow option to avoid internal timming system, to allow app manage the steps +* 1.0 (12-Jun-2017) First release of the library * * * LICENSE: zlib/libpng * -* Copyright (c) 2016-2018 Victor Fisac (github: @victorfisac) +* Copyright (c) 2016-2021 Victor Fisac (@victorfisac) and Ramon Santamaria (@raysan5) * * 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. @@ -87,6 +93,9 @@ #ifndef PHYSAC_MALLOC #define PHYSAC_MALLOC(size) malloc(size) #endif +#ifndef PHYSAC_CALLOC + #define PHYSAC_CALLOC(size, n) calloc(size, n) +#endif #ifndef PHYSAC_FREE #define PHYSAC_FREE(ptr) free(ptr) #endif @@ -94,10 +103,10 @@ //---------------------------------------------------------------------------------- // Defines and Macros //---------------------------------------------------------------------------------- -#define PHYSAC_MAX_BODIES 64 -#define PHYSAC_MAX_MANIFOLDS 4096 -#define PHYSAC_MAX_VERTICES 24 -#define PHYSAC_CIRCLE_VERTICES 24 +#define PHYSAC_MAX_BODIES 64 // Maximum number of physic bodies supported +#define PHYSAC_MAX_MANIFOLDS 4096 // Maximum number of physic bodies interactions (64x64) +#define PHYSAC_MAX_VERTICES 24 // Maximum number of vertex for polygons shapes +#define PHYSAC_DEFAULT_CIRCLE_VERTICES 24 // Default number of vertices for circle shapes #define PHYSAC_COLLISION_ITERATIONS 100 #define PHYSAC_PENETRATION_ALLOWANCE 0.05f @@ -106,34 +115,28 @@ #define PHYSAC_PI 3.14159265358979323846 #define PHYSAC_DEG2RAD (PHYSAC_PI/180.0f) -//---------------------------------------------------------------------------------- -// Types and Structures Definition -// NOTE: Below types are required for PHYSAC_STANDALONE usage -//---------------------------------------------------------------------------------- -#if defined(PHYSAC_STANDALONE) - // Boolean type - #if defined(__STDC__) && __STDC_VERSION__ >= 199901L - #include - #elif !defined(__cplusplus) && !defined(bool) - typedef enum { false, true } bool; - #endif - - // Vector2 type - typedef struct Vector2 { - float x; - float y; - } Vector2; -#endif - //---------------------------------------------------------------------------------- // Data Types Structure Definition //---------------------------------------------------------------------------------- +#if defined(__STDC__) && __STDC_VERSION__ >= 199901L + #include +#elif !defined(__cplusplus) && !defined(bool) + typedef enum { false, true } bool; +#endif -typedef enum PhysicsShapeType { PHYSICS_CIRCLE, PHYSICS_POLYGON } PhysicsShapeType; +typedef enum PhysicsShapeType { PHYSICS_CIRCLE = 0, PHYSICS_POLYGON } PhysicsShapeType; // Previously defined to be used in PhysicsShape struct as circular dependencies typedef struct PhysicsBodyData *PhysicsBody; +#if defined(PHYSAC_DEFINE_VECTOR2_TYPE) +// Vector2 type +typedef struct Vector2 { + float x; + float y; +} Vector2; +#endif + // Matrix2x2 type (used for polygon shape rotation matrix) typedef struct Matrix2x2 { float m00; @@ -142,22 +145,22 @@ typedef struct Matrix2x2 { float m11; } Matrix2x2; -typedef struct PolygonData { - unsigned int vertexCount; // Current used vertex and normals count - Vector2 positions[PHYSAC_MAX_VERTICES]; // Polygon vertex positions vectors - Vector2 normals[PHYSAC_MAX_VERTICES]; // Polygon vertex normals vectors -} PolygonData; +typedef struct PhysicsVertexData { + unsigned int vertexCount; // Vertex count (positions and normals) + Vector2 positions[PHYSAC_MAX_VERTICES]; // Vertex positions vectors + Vector2 normals[PHYSAC_MAX_VERTICES]; // Vertex normals vectors +} PhysicsVertexData; typedef struct PhysicsShape { - PhysicsShapeType type; // Physics shape type (circle or polygon) - PhysicsBody body; // Shape physics body reference - float radius; // Circle shape radius (used for circle shapes) + PhysicsShapeType type; // Shape type (circle or polygon) + PhysicsBody body; // Shape physics body data pointer + PhysicsVertexData vertexData; // Shape vertices data (used for polygon shapes) + float radius; // Shape radius (used for circle shapes) Matrix2x2 transform; // Vertices transform matrix 2x2 - PolygonData vertexData; // Polygon shape vertices position and normals data (just used for polygon shapes) } PhysicsShape; typedef struct PhysicsBodyData { - unsigned int id; // Reference unique identifier + unsigned int id; // Unique identifier bool enabled; // Enabled dynamics state (collisions are calculated anyway) Vector2 position; // Physics body shape pivot Vector2 velocity; // Current linear velocity applied to position @@ -175,11 +178,11 @@ typedef struct PhysicsBodyData { bool useGravity; // Apply gravity force to dynamics bool isGrounded; // Physics grounded on other body state bool freezeOrient; // Physics rotation constraint - PhysicsShape shape; // Physics body shape information (type, radius, vertices, normals) + PhysicsShape shape; // Physics body shape information (type, radius, vertices, transform) } PhysicsBodyData; typedef struct PhysicsManifoldData { - unsigned int id; // Reference unique identifier + unsigned int id; // Unique identifier PhysicsBody bodyA; // Manifold first physics body reference PhysicsBody bodyB; // Manifold second physics body reference float penetration; // Depth of penetration from collision @@ -198,26 +201,32 @@ extern "C" { // Prevents name mangling of fun //---------------------------------------------------------------------------------- // Module Functions Declaration //---------------------------------------------------------------------------------- -PHYSACDEF void InitPhysics(void); // Initializes physics values, pointers and creates physics loop thread -PHYSACDEF void RunPhysicsStep(void); // Run physics step, to be used if PHYSICS_NO_THREADS is set in your main loop +// Physics system management +PHYSACDEF void InitPhysics(void); // Initializes physics system +PHYSACDEF void UpdatePhysics(void); // Update physics system +PHYSACDEF void ResetPhysics(void); // Reset physics system (global variables) +PHYSACDEF void ClosePhysics(void); // Close physics system and unload used memory PHYSACDEF void SetPhysicsTimeStep(double delta); // Sets physics fixed time step in milliseconds. 1.666666 by default -PHYSACDEF bool IsPhysicsEnabled(void); // Returns true if physics thread is currently enabled PHYSACDEF void SetPhysicsGravity(float x, float y); // Sets physics global gravity force + +// Physic body creation/destroy PHYSACDEF PhysicsBody CreatePhysicsBodyCircle(Vector2 pos, float radius, float density); // Creates a new circle physics body with generic parameters PHYSACDEF PhysicsBody CreatePhysicsBodyRectangle(Vector2 pos, float width, float height, float density); // Creates a new rectangle physics body with generic parameters PHYSACDEF PhysicsBody CreatePhysicsBodyPolygon(Vector2 pos, float radius, int sides, float density); // Creates a new polygon physics body with generic parameters +PHYSACDEF void DestroyPhysicsBody(PhysicsBody body); // Destroy a physics body + +// Physic body forces PHYSACDEF void PhysicsAddForce(PhysicsBody body, Vector2 force); // Adds a force to a physics body PHYSACDEF void PhysicsAddTorque(PhysicsBody body, float amount); // Adds an angular force to a physics body PHYSACDEF void PhysicsShatter(PhysicsBody body, Vector2 position, float force); // Shatters a polygon shape physics body to little physics bodies with explosion force -PHYSACDEF int GetPhysicsBodiesCount(void); // Returns the current amount of created physics bodies +PHYSACDEF void SetPhysicsBodyRotation(PhysicsBody body, float radians); // Sets physics body shape transform based on radians parameter + +// Query physics info PHYSACDEF PhysicsBody GetPhysicsBody(int index); // Returns a physics body of the bodies pool at a specific index +PHYSACDEF int GetPhysicsBodiesCount(void); // Returns the current amount of created physics bodies PHYSACDEF int GetPhysicsShapeType(int index); // Returns the physics body shape type (PHYSICS_CIRCLE or PHYSICS_POLYGON) PHYSACDEF int GetPhysicsShapeVerticesCount(int index); // Returns the amount of vertices of a physics body shape PHYSACDEF Vector2 GetPhysicsShapeVertex(PhysicsBody body, int vertex); // Returns transformed position of a body shape (body position + vertex transformed position) -PHYSACDEF void SetPhysicsBodyRotation(PhysicsBody body, float radians); // Sets physics body shape transform based on radians parameter -PHYSACDEF void DestroyPhysicsBody(PhysicsBody body); // Unitializes and destroy a physics body -PHYSACDEF void ResetPhysics(void); // Destroys created physics bodies and manifolds and resets global values -PHYSACDEF void ClosePhysics(void); // Unitializes physics pointers and closes physics loop thread #if defined(__cplusplus) } @@ -233,151 +242,138 @@ PHYSACDEF void ClosePhysics(void); #if defined(PHYSAC_IMPLEMENTATION) -#if !defined(PHYSAC_NO_THREADS) - #include // Required for: pthread_t, pthread_create() -#endif - -#if defined(PHYSAC_DEBUG) - -#endif - // Support TRACELOG macros #if defined(PHYSAC_DEBUG) #include // Required for: printf() #define TRACELOG(...) printf(__VA_ARGS__) #else - #define TRACELOG(...) (void)0 + #define TRACELOG(...) (void)0; #endif -#include // Required for: malloc(), free(), srand(), rand() +#include // Required for: malloc(), calloc(), free() #include // Required for: cosf(), sinf(), fabs(), sqrtf() -#if !defined(PHYSAC_STANDALONE) - #include "raymath.h" // Required for: Vector2Add(), Vector2Subtract() +#if !defined(PHYSAC_AVOID_TIMMING_SYSTEM) + // Time management functionality + #include // Required for: time(), clock_gettime() + #if defined(_WIN32) + // Functions required to query time on Windows + int __stdcall QueryPerformanceCounter(unsigned long long int *lpPerformanceCount); + int __stdcall QueryPerformanceFrequency(unsigned long long int *lpFrequency); + #elif defined(__linux__) + #if _POSIX_C_SOURCE < 199309L + #undef _POSIX_C_SOURCE + #define _POSIX_C_SOURCE 199309L // Required for CLOCK_MONOTONIC if compiled with c99 without gnu ext. + #endif + #include // Required for: timespec + #elif defined(__APPLE__) // macOS also defines __MACH__ + #include // Required for: mach_absolute_time() + #endif #endif -// Time management functionality -#include // Required for: time(), clock_gettime() -#if defined(_WIN32) - // Functions required to query time on Windows - int __stdcall QueryPerformanceCounter(unsigned long long int *lpPerformanceCount); - int __stdcall QueryPerformanceFrequency(unsigned long long int *lpFrequency); -#elif defined(__linux__) - #if _POSIX_C_SOURCE < 199309L - #undef _POSIX_C_SOURCE - #define _POSIX_C_SOURCE 199309L // Required for CLOCK_MONOTONIC if compiled with c99 without gnu ext. - #endif - #include // Required for: timespec -#elif defined(__APPLE__) // macOS also defines __MACH__ - #include // Required for: mach_absolute_time() +// NOTE: MSVC C++ compiler does not support compound literals (C99 feature) +// Plain structures in C++ (without constructors) can be initialized from { } initializers. +#if defined(__cplusplus) + #define CLITERAL(type) type +#else + #define CLITERAL(type) (type) #endif //---------------------------------------------------------------------------------- // Defines and Macros //---------------------------------------------------------------------------------- -#define min(a,b) (((a)<(b))?(a):(b)) -#define max(a,b) (((a)>(b))?(a):(b)) -#define PHYSAC_FLT_MAX 3.402823466e+38f -#define PHYSAC_EPSILON 0.000001f -#define PHYSAC_K 1.0f/3.0f -#define PHYSAC_VECTOR_ZERO (Vector2){ 0.0f, 0.0f } +#define PHYSAC_MIN(a,b) (((a)<(b))?(a):(b)) +#define PHYSAC_MAX(a,b) (((a)>(b))?(a):(b)) +#define PHYSAC_FLT_MAX 3.402823466e+38f +#define PHYSAC_EPSILON 0.000001f +#define PHYSAC_K 1.0f/3.0f +#define PHYSAC_VECTOR_ZERO CLITERAL(Vector2){ 0.0f, 0.0f } //---------------------------------------------------------------------------------- // Global Variables Definition //---------------------------------------------------------------------------------- -#if !defined(PHYSAC_NO_THREADS) -static pthread_t physicsThreadId; // Physics thread id -#endif -static unsigned int usedMemory = 0; // Total allocated dynamic memory -static bool physicsThreadEnabled = false; // Physics thread enabled state -static double baseTime = 0.0; // Offset time for MONOTONIC clock -static double startTime = 0.0; // Start time in milliseconds -static double deltaTime = 1.0/60.0/10.0 * 1000; // Delta time used for physics steps, in milliseconds -static double currentTime = 0.0; // Current time in milliseconds -static unsigned long long int frequency = 0; // Hi-res clock frequency +static double deltaTime = 1.0/60.0/10.0 * 1000; // Delta time in milliseconds used for physics steps -static double accumulator = 0.0; // Physics time step delta time accumulator -static unsigned int stepsCount = 0; // Total physics steps processed -static Vector2 gravityForce = { 0.0f, 9.81f }; // Physics world gravity force +#if !defined(PHYSAC_AVOID_TIMMING_SYSTEM) +// Time measure variables +static double baseClockTicks = 0.0; // Offset clock ticks for MONOTONIC clock +static unsigned long long int frequency = 0; // Hi-res clock frequency +static double startTime = 0.0; // Start time in milliseconds +static double currentTime = 0.0; // Current time in milliseconds +#endif + +// Physics system configuration static PhysicsBody bodies[PHYSAC_MAX_BODIES]; // Physics bodies pointers array static unsigned int physicsBodiesCount = 0; // Physics world current bodies counter static PhysicsManifold contacts[PHYSAC_MAX_MANIFOLDS]; // Physics bodies pointers array static unsigned int physicsManifoldsCount = 0; // Physics world current manifolds counter +static Vector2 gravityForce = { 0.0f, 9.81f }; // Physics world gravity force + +// Utilities variables +static unsigned int usedMemory = 0; // Total allocated dynamic memory + //---------------------------------------------------------------------------------- // Module Internal Functions Declaration //---------------------------------------------------------------------------------- +#if !defined(PHYSAC_AVOID_TIMMING_SYSTEM) +// Timming measure functions +static void InitTimer(void); // Initializes hi-resolution MONOTONIC timer +static unsigned long long int GetClockTicks(void); // Get hi-res MONOTONIC time measure in mseconds +static double GetCurrentTime(void); // Get current time measure in milliseconds +#endif + +static void UpdatePhysicsStep(void); // Update physics step (dynamics, collisions and position corrections) + static int FindAvailableBodyIndex(); // Finds a valid index for a new physics body initialization -static PolygonData CreateRandomPolygon(float radius, int sides); // Creates a random polygon shape with max vertex distance from polygon pivot -static PolygonData CreateRectanglePolygon(Vector2 pos, Vector2 size); // Creates a rectangle polygon shape based on a min and max positions -static void *PhysicsLoop(void *arg); // Physics loop thread function -static void PhysicsStep(void); // Physics steps calculations (dynamics, collisions and position corrections) static int FindAvailableManifoldIndex(); // Finds a valid index for a new manifold initialization +static PhysicsVertexData CreateDefaultPolygon(float radius, int sides); // Creates a random polygon shape with max vertex distance from polygon pivot +static PhysicsVertexData CreateRectanglePolygon(Vector2 pos, Vector2 size); // Creates a rectangle polygon shape based on a min and max positions + +static void InitializePhysicsManifolds(PhysicsManifold manifold); // Initializes physics manifolds to solve collisions static PhysicsManifold CreatePhysicsManifold(PhysicsBody a, PhysicsBody b); // Creates a new physics manifold to solve collision static void DestroyPhysicsManifold(PhysicsManifold manifold); // Unitializes and destroys a physics manifold + static void SolvePhysicsManifold(PhysicsManifold manifold); // Solves a created physics manifold between two physics bodies static void SolveCircleToCircle(PhysicsManifold manifold); // Solves collision between two circle shape physics bodies static void SolveCircleToPolygon(PhysicsManifold manifold); // Solves collision between a circle to a polygon shape physics bodies static void SolvePolygonToCircle(PhysicsManifold manifold); // Solves collision between a polygon to a circle shape physics bodies static void SolvePolygonToPolygon(PhysicsManifold manifold); // Solves collision between two polygons shape physics bodies static void IntegratePhysicsForces(PhysicsBody body); // Integrates physics forces into velocity -static void InitializePhysicsManifolds(PhysicsManifold manifold); // Initializes physics manifolds to solve collisions -static void IntegratePhysicsImpulses(PhysicsManifold manifold); // Integrates physics collisions impulses to solve collisions static void IntegratePhysicsVelocity(PhysicsBody body); // Integrates physics velocity into position and forces +static void IntegratePhysicsImpulses(PhysicsManifold manifold); // Integrates physics collisions impulses to solve collisions static void CorrectPhysicsPositions(PhysicsManifold manifold); // Corrects physics bodies positions based on manifolds collision information -static float FindAxisLeastPenetration(int *faceIndex, PhysicsShape shapeA, PhysicsShape shapeB); // Finds polygon shapes axis least penetration static void FindIncidentFace(Vector2 *v0, Vector2 *v1, PhysicsShape ref, PhysicsShape inc, int index); // Finds two polygon shapes incident face -static int Clip(Vector2 normal, float clip, Vector2 *faceA, Vector2 *faceB); // Calculates clipping based on a normal and two faces -static bool BiasGreaterThan(float valueA, float valueB); // Check if values are between bias range -static Vector2 TriangleBarycenter(Vector2 v1, Vector2 v2, Vector2 v3); // Returns the barycenter of a triangle given by 3 points +static float FindAxisLeastPenetration(int *faceIndex, PhysicsShape shapeA, PhysicsShape shapeB); // Finds polygon shapes axis least penetration -static void InitTimer(void); // Initializes hi-resolution MONOTONIC timer -static unsigned long long int GetTimeCount(void); // Get hi-res MONOTONIC time measure in mseconds -static double GetCurrentTime(void); // Get current time measure in milliseconds - -// Math functions -static Vector2 MathCross(float value, Vector2 vector); // Returns the cross product of a vector and a value -static float MathCrossVector2(Vector2 v1, Vector2 v2); // Returns the cross product of two vectors -static float MathLenSqr(Vector2 vector); // Returns the len square root of a vector -static float MathDot(Vector2 v1, Vector2 v2); // Returns the dot product of two vectors -static inline float DistSqr(Vector2 v1, Vector2 v2); // Returns the square root of distance between two vectors -static void MathNormalize(Vector2 *vector); // Returns the normalized values of a vector -#if defined(PHYSAC_STANDALONE) -static Vector2 Vector2Add(Vector2 v1, Vector2 v2); // Returns the sum of two given vectors -static Vector2 Vector2Subtract(Vector2 v1, Vector2 v2); // Returns the subtract of two given vectors -#endif - -static Matrix2x2 Mat2Radians(float radians); // Creates a matrix 2x2 from a given radians value -static void Mat2Set(Matrix2x2 *matrix, float radians); // Set values from radians to a created matrix 2x2 -static inline Matrix2x2 Mat2Transpose(Matrix2x2 matrix); // Returns the transpose of a given matrix 2x2 -static inline Vector2 Mat2MultiplyVector2(Matrix2x2 matrix, Vector2 vector); // Multiplies a vector by a matrix 2x2 +// Math required functions +static Vector2 MathVector2Product(Vector2 vector, float value); // Returns the product of a vector and a value +static float MathVector2CrossProduct(Vector2 v1, Vector2 v2); // Returns the cross product of two vectors +static float MathVector2SqrLen(Vector2 vector); // Returns the len square root of a vector +static float MathVector2DotProduct(Vector2 v1, Vector2 v2); // Returns the dot product of two vectors +static inline float MathVector2SqrDistance(Vector2 v1, Vector2 v2); // Returns the square root of distance between two vectors +static void MathVector2Normalize(Vector2 *vector); // Returns the normalized values of a vector +static Vector2 MathVector2Add(Vector2 v1, Vector2 v2); // Returns the sum of two given vectors +static Vector2 MathVector2Subtract(Vector2 v1, Vector2 v2); // Returns the subtract of two given vectors +static Matrix2x2 MathMatFromRadians(float radians); // Returns a matrix 2x2 from a given radians value +static inline Matrix2x2 MathMatTranspose(Matrix2x2 matrix); // Returns the transpose of a given matrix 2x2 +static inline Vector2 MathMatVector2Product(Matrix2x2 matrix, Vector2 vector); // Returns product between matrix 2x2 and vector +static int MathVector2Clip(Vector2 normal, Vector2 *faceA, Vector2 *faceB, float clip); // Returns clipping value based on a normal and two faces +static Vector2 MathTriangleBarycenter(Vector2 v1, Vector2 v2, Vector2 v3); // Returns the barycenter of a triangle given by 3 points //---------------------------------------------------------------------------------- // Module Functions Definition //---------------------------------------------------------------------------------- + // Initializes physics values, pointers and creates physics loop thread PHYSACDEF void InitPhysics(void) { - #if !defined(PHYSAC_NO_THREADS) - // NOTE: if defined, user will need to create a thread for PhysicsThread function manually - // Create physics thread using POSIXS thread libraries - pthread_create(&physicsThreadId, NULL, &PhysicsLoop, NULL); - #endif - +#if !defined(PHYSAC_AVOID_TIMMING_SYSTEM) // Initialize high resolution timer InitTimer(); +#endif - #if defined(PHYSAC_DEBUG) - TRACELOG("[PHYSAC] physics module initialized successfully\n"); - #endif - - accumulator = 0.0; -} - -// Returns true if physics thread is currently enabled -PHYSACDEF bool IsPhysicsEnabled(void) -{ - return physicsThreadEnabled; + TRACELOG("[PHYSAC] Physics module initialized successfully\n"); } // Sets physics global gravity force @@ -390,47 +386,42 @@ PHYSACDEF void SetPhysicsGravity(float x, float y) // Creates a new circle physics body with generic parameters PHYSACDEF PhysicsBody CreatePhysicsBodyCircle(Vector2 pos, float radius, float density) { - PhysicsBody newBody = CreatePhysicsBodyPolygon(pos, radius, PHYSAC_CIRCLE_VERTICES, density); - return newBody; + PhysicsBody body = CreatePhysicsBodyPolygon(pos, radius, PHYSAC_DEFAULT_CIRCLE_VERTICES, density); + return body; } // Creates a new rectangle physics body with generic parameters PHYSACDEF PhysicsBody CreatePhysicsBodyRectangle(Vector2 pos, float width, float height, float density) { - PhysicsBody newBody = (PhysicsBody)PHYSAC_MALLOC(sizeof(PhysicsBodyData)); + // NOTE: Make sure body data is initialized to 0 + PhysicsBody body = (PhysicsBody)PHYSAC_CALLOC(sizeof(PhysicsBodyData), 1); usedMemory += sizeof(PhysicsBodyData); - int newId = FindAvailableBodyIndex(); - if (newId != -1) + int id = FindAvailableBodyIndex(); + if (id != -1) { // Initialize new body with generic values - newBody->id = newId; - newBody->enabled = true; - newBody->position = pos; - newBody->velocity = (Vector2){ 0.0f, 0.0f }; - newBody->force = (Vector2){ 0.0f, 0.0f }; - newBody->angularVelocity = 0.0f; - newBody->torque = 0.0f; - newBody->orient = 0.0f; - newBody->shape.type = PHYSICS_POLYGON; - newBody->shape.body = newBody; - newBody->shape.radius = 0.0f; - newBody->shape.transform = Mat2Radians(0.0f); - newBody->shape.vertexData = CreateRectanglePolygon(pos, (Vector2){ width, height }); + body->id = id; + body->enabled = true; + body->position = pos; + body->shape.type = PHYSICS_POLYGON; + body->shape.body = body; + body->shape.transform = MathMatFromRadians(0.0f); + body->shape.vertexData = CreateRectanglePolygon(pos, CLITERAL(Vector2){ width, height }); // Calculate centroid and moment of inertia Vector2 center = { 0.0f, 0.0f }; float area = 0.0f; float inertia = 0.0f; - for (int i = 0; i < newBody->shape.vertexData.vertexCount; i++) + for (int i = 0; i < body->shape.vertexData.vertexCount; i++) { // Triangle vertices, third vertex implied as (0, 0) - Vector2 p1 = newBody->shape.vertexData.positions[i]; - int nextIndex = (((i + 1) < newBody->shape.vertexData.vertexCount) ? (i + 1) : 0); - Vector2 p2 = newBody->shape.vertexData.positions[nextIndex]; + Vector2 p1 = body->shape.vertexData.positions[i]; + int nextIndex = (((i + 1) < body->shape.vertexData.vertexCount) ? (i + 1) : 0); + Vector2 p2 = body->shape.vertexData.positions[nextIndex]; - float D = MathCrossVector2(p1, p2); + float D = MathVector2CrossProduct(p1, p2); float triangleArea = D/2; area += triangleArea; @@ -449,74 +440,70 @@ PHYSACDEF PhysicsBody CreatePhysicsBodyRectangle(Vector2 pos, float width, float // Translate vertices to centroid (make the centroid (0, 0) for the polygon in model space) // Note: this is not really necessary - for (int i = 0; i < newBody->shape.vertexData.vertexCount; i++) + for (int i = 0; i < body->shape.vertexData.vertexCount; i++) { - newBody->shape.vertexData.positions[i].x -= center.x; - newBody->shape.vertexData.positions[i].y -= center.y; + body->shape.vertexData.positions[i].x -= center.x; + body->shape.vertexData.positions[i].y -= center.y; } - newBody->mass = density*area; - newBody->inverseMass = ((newBody->mass != 0.0f) ? 1.0f/newBody->mass : 0.0f); - newBody->inertia = density*inertia; - newBody->inverseInertia = ((newBody->inertia != 0.0f) ? 1.0f/newBody->inertia : 0.0f); - newBody->staticFriction = 0.4f; - newBody->dynamicFriction = 0.2f; - newBody->restitution = 0.0f; - newBody->useGravity = true; - newBody->isGrounded = false; - newBody->freezeOrient = false; + body->mass = density*area; + body->inverseMass = ((body->mass != 0.0f) ? 1.0f/body->mass : 0.0f); + body->inertia = density*inertia; + body->inverseInertia = ((body->inertia != 0.0f) ? 1.0f/body->inertia : 0.0f); + body->staticFriction = 0.4f; + body->dynamicFriction = 0.2f; + body->restitution = 0.0f; + body->useGravity = true; + body->isGrounded = false; + body->freezeOrient = false; // Add new body to bodies pointers array and update bodies count - bodies[physicsBodiesCount] = newBody; + bodies[physicsBodiesCount] = body; physicsBodiesCount++; - #if defined(PHYSAC_DEBUG) - TRACELOG("[PHYSAC] created polygon physics body id %i\n", newBody->id); - #endif + TRACELOG("[PHYSAC] Physic body created successfully (id: %i)\n", body->id); } - #if defined(PHYSAC_DEBUG) - else TRACELOG("[PHYSAC] new physics body creation failed because there is any available id to use\n"); - #endif + else TRACELOG("[PHYSAC] Physic body could not be created, PHYSAC_MAX_BODIES reached\n"); - return newBody; + return body; } // Creates a new polygon physics body with generic parameters PHYSACDEF PhysicsBody CreatePhysicsBodyPolygon(Vector2 pos, float radius, int sides, float density) { - PhysicsBody newBody = (PhysicsBody)PHYSAC_MALLOC(sizeof(PhysicsBodyData)); + PhysicsBody body = (PhysicsBody)PHYSAC_MALLOC(sizeof(PhysicsBodyData)); usedMemory += sizeof(PhysicsBodyData); - int newId = FindAvailableBodyIndex(); - if (newId != -1) + int id = FindAvailableBodyIndex(); + if (id != -1) { // Initialize new body with generic values - newBody->id = newId; - newBody->enabled = true; - newBody->position = pos; - newBody->velocity = PHYSAC_VECTOR_ZERO; - newBody->force = PHYSAC_VECTOR_ZERO; - newBody->angularVelocity = 0.0f; - newBody->torque = 0.0f; - newBody->orient = 0.0f; - newBody->shape.type = PHYSICS_POLYGON; - newBody->shape.body = newBody; - newBody->shape.transform = Mat2Radians(0.0f); - newBody->shape.vertexData = CreateRandomPolygon(radius, sides); + body->id = id; + body->enabled = true; + body->position = pos; + body->velocity = PHYSAC_VECTOR_ZERO; + body->force = PHYSAC_VECTOR_ZERO; + body->angularVelocity = 0.0f; + body->torque = 0.0f; + body->orient = 0.0f; + body->shape.type = PHYSICS_POLYGON; + body->shape.body = body; + body->shape.transform = MathMatFromRadians(0.0f); + body->shape.vertexData = CreateDefaultPolygon(radius, sides); // Calculate centroid and moment of inertia Vector2 center = { 0.0f, 0.0f }; float area = 0.0f; float inertia = 0.0f; - for (int i = 0; i < newBody->shape.vertexData.vertexCount; i++) + for (int i = 0; i < body->shape.vertexData.vertexCount; i++) { // Triangle vertices, third vertex implied as (0, 0) - Vector2 position1 = newBody->shape.vertexData.positions[i]; - int nextIndex = (((i + 1) < newBody->shape.vertexData.vertexCount) ? (i + 1) : 0); - Vector2 position2 = newBody->shape.vertexData.positions[nextIndex]; + Vector2 position1 = body->shape.vertexData.positions[i]; + int nextIndex = (((i + 1) < body->shape.vertexData.vertexCount) ? (i + 1) : 0); + Vector2 position2 = body->shape.vertexData.positions[nextIndex]; - float cross = MathCrossVector2(position1, position2); + float cross = MathVector2CrossProduct(position1, position2); float triangleArea = cross/2; area += triangleArea; @@ -535,42 +522,38 @@ PHYSACDEF PhysicsBody CreatePhysicsBodyPolygon(Vector2 pos, float radius, int si // Translate vertices to centroid (make the centroid (0, 0) for the polygon in model space) // Note: this is not really necessary - for (int i = 0; i < newBody->shape.vertexData.vertexCount; i++) + for (int i = 0; i < body->shape.vertexData.vertexCount; i++) { - newBody->shape.vertexData.positions[i].x -= center.x; - newBody->shape.vertexData.positions[i].y -= center.y; + body->shape.vertexData.positions[i].x -= center.x; + body->shape.vertexData.positions[i].y -= center.y; } - newBody->mass = density*area; - newBody->inverseMass = ((newBody->mass != 0.0f) ? 1.0f/newBody->mass : 0.0f); - newBody->inertia = density*inertia; - newBody->inverseInertia = ((newBody->inertia != 0.0f) ? 1.0f/newBody->inertia : 0.0f); - newBody->staticFriction = 0.4f; - newBody->dynamicFriction = 0.2f; - newBody->restitution = 0.0f; - newBody->useGravity = true; - newBody->isGrounded = false; - newBody->freezeOrient = false; + body->mass = density*area; + body->inverseMass = ((body->mass != 0.0f) ? 1.0f/body->mass : 0.0f); + body->inertia = density*inertia; + body->inverseInertia = ((body->inertia != 0.0f) ? 1.0f/body->inertia : 0.0f); + body->staticFriction = 0.4f; + body->dynamicFriction = 0.2f; + body->restitution = 0.0f; + body->useGravity = true; + body->isGrounded = false; + body->freezeOrient = false; // Add new body to bodies pointers array and update bodies count - bodies[physicsBodiesCount] = newBody; + bodies[physicsBodiesCount] = body; physicsBodiesCount++; - #if defined(PHYSAC_DEBUG) - TRACELOG("[PHYSAC] created polygon physics body id %i\n", newBody->id); - #endif + TRACELOG("[PHYSAC] Physic body created successfully (id: %i)\n", body->id); } - #if defined(PHYSAC_DEBUG) - else TRACELOG("[PHYSAC] new physics body creation failed because there is any available id to use\n"); - #endif + else TRACELOG("[PHYSAC] Physics body could not be created, PHYSAC_MAX_BODIES reached\n"); - return newBody; + return body; } // Adds a force to a physics body PHYSACDEF void PhysicsAddForce(PhysicsBody body, Vector2 force) { - if (body != NULL) body->force = Vector2Add(body->force, force); + if (body != NULL) body->force = MathVector2Add(body->force, force); } // Adds an angular force to a physics body @@ -586,15 +569,15 @@ PHYSACDEF void PhysicsShatter(PhysicsBody body, Vector2 position, float force) { if (body->shape.type == PHYSICS_POLYGON) { - PolygonData vertexData = body->shape.vertexData; + PhysicsVertexData vertexData = body->shape.vertexData; bool collision = false; for (int i = 0; i < vertexData.vertexCount; i++) { Vector2 positionA = body->position; - Vector2 positionB = Mat2MultiplyVector2(body->shape.transform, Vector2Add(body->position, vertexData.positions[i])); + Vector2 positionB = MathMatVector2Product(body->shape.transform, MathVector2Add(body->position, vertexData.positions[i])); int nextIndex = (((i + 1) < vertexData.vertexCount) ? (i + 1) : 0); - Vector2 positionC = Mat2MultiplyVector2(body->shape.transform, Vector2Add(body->position, vertexData.positions[nextIndex])); + Vector2 positionC = MathMatVector2Product(body->shape.transform, MathVector2Add(body->position, vertexData.positions[nextIndex])); // Check collision between each triangle float alpha = ((positionB.y - positionC.y)*(position.x - positionC.x) + (positionC.x - positionB.x)*(position.y - positionC.y))/ @@ -626,54 +609,54 @@ PHYSACDEF void PhysicsShatter(PhysicsBody body, Vector2 position, float force) for (int i = 0; i < count; i++) { int nextIndex = (((i + 1) < count) ? (i + 1) : 0); - Vector2 center = TriangleBarycenter(vertices[i], vertices[nextIndex], PHYSAC_VECTOR_ZERO); - center = Vector2Add(bodyPos, center); - Vector2 offset = Vector2Subtract(center, bodyPos); + Vector2 center = MathTriangleBarycenter(vertices[i], vertices[nextIndex], PHYSAC_VECTOR_ZERO); + center = MathVector2Add(bodyPos, center); + Vector2 offset = MathVector2Subtract(center, bodyPos); - PhysicsBody newBody = CreatePhysicsBodyPolygon(center, 10, 3, 10); // Create polygon physics body with relevant values + PhysicsBody body = CreatePhysicsBodyPolygon(center, 10, 3, 10); // Create polygon physics body with relevant values - PolygonData newData = { 0 }; - newData.vertexCount = 3; + PhysicsVertexData vertexData = { 0 }; + vertexData.vertexCount = 3; - newData.positions[0] = Vector2Subtract(vertices[i], offset); - newData.positions[1] = Vector2Subtract(vertices[nextIndex], offset); - newData.positions[2] = Vector2Subtract(position, center); + vertexData.positions[0] = MathVector2Subtract(vertices[i], offset); + vertexData.positions[1] = MathVector2Subtract(vertices[nextIndex], offset); + vertexData.positions[2] = MathVector2Subtract(position, center); // Separate vertices to avoid unnecessary physics collisions - newData.positions[0].x *= 0.95f; - newData.positions[0].y *= 0.95f; - newData.positions[1].x *= 0.95f; - newData.positions[1].y *= 0.95f; - newData.positions[2].x *= 0.95f; - newData.positions[2].y *= 0.95f; + vertexData.positions[0].x *= 0.95f; + vertexData.positions[0].y *= 0.95f; + vertexData.positions[1].x *= 0.95f; + vertexData.positions[1].y *= 0.95f; + vertexData.positions[2].x *= 0.95f; + vertexData.positions[2].y *= 0.95f; // Calculate polygon faces normals - for (int j = 0; j < newData.vertexCount; j++) + for (int j = 0; j < vertexData.vertexCount; j++) { - int nextVertex = (((j + 1) < newData.vertexCount) ? (j + 1) : 0); - Vector2 face = Vector2Subtract(newData.positions[nextVertex], newData.positions[j]); + int nextVertex = (((j + 1) < vertexData.vertexCount) ? (j + 1) : 0); + Vector2 face = MathVector2Subtract(vertexData.positions[nextVertex], vertexData.positions[j]); - newData.normals[j] = (Vector2){ face.y, -face.x }; - MathNormalize(&newData.normals[j]); + vertexData.normals[j] = CLITERAL(Vector2){ face.y, -face.x }; + MathVector2Normalize(&vertexData.normals[j]); } // Apply computed vertex data to new physics body shape - newBody->shape.vertexData = newData; - newBody->shape.transform = trans; + body->shape.vertexData = vertexData; + body->shape.transform = trans; // Calculate centroid and moment of inertia center = PHYSAC_VECTOR_ZERO; float area = 0.0f; float inertia = 0.0f; - for (int j = 0; j < newBody->shape.vertexData.vertexCount; j++) + for (int j = 0; j < body->shape.vertexData.vertexCount; j++) { // Triangle vertices, third vertex implied as (0, 0) - Vector2 p1 = newBody->shape.vertexData.positions[j]; - int nextVertex = (((j + 1) < newBody->shape.vertexData.vertexCount) ? (j + 1) : 0); - Vector2 p2 = newBody->shape.vertexData.positions[nextVertex]; + Vector2 p1 = body->shape.vertexData.positions[j]; + int nextVertex = (((j + 1) < body->shape.vertexData.vertexCount) ? (j + 1) : 0); + Vector2 p2 = body->shape.vertexData.positions[nextVertex]; - float D = MathCrossVector2(p1, p2); + float D = MathVector2CrossProduct(p1, p2); float triangleArea = D/2; area += triangleArea; @@ -690,32 +673,30 @@ PHYSACDEF void PhysicsShatter(PhysicsBody body, Vector2 position, float force) center.x *= 1.0f/area; center.y *= 1.0f/area; - newBody->mass = area; - newBody->inverseMass = ((newBody->mass != 0.0f) ? 1.0f/newBody->mass : 0.0f); - newBody->inertia = inertia; - newBody->inverseInertia = ((newBody->inertia != 0.0f) ? 1.0f/newBody->inertia : 0.0f); + body->mass = area; + body->inverseMass = ((body->mass != 0.0f) ? 1.0f/body->mass : 0.0f); + body->inertia = inertia; + body->inverseInertia = ((body->inertia != 0.0f) ? 1.0f/body->inertia : 0.0f); // Calculate explosion force direction - Vector2 pointA = newBody->position; - Vector2 pointB = Vector2Subtract(newData.positions[1], newData.positions[0]); + Vector2 pointA = body->position; + Vector2 pointB = MathVector2Subtract(vertexData.positions[1], vertexData.positions[0]); pointB.x /= 2.0f; pointB.y /= 2.0f; - Vector2 forceDirection = Vector2Subtract(Vector2Add(pointA, Vector2Add(newData.positions[0], pointB)), newBody->position); - MathNormalize(&forceDirection); + Vector2 forceDirection = MathVector2Subtract(MathVector2Add(pointA, MathVector2Add(vertexData.positions[0], pointB)), body->position); + MathVector2Normalize(&forceDirection); forceDirection.x *= force; forceDirection.y *= force; // Apply force to new physics body - PhysicsAddForce(newBody, forceDirection); + PhysicsAddForce(body, forceDirection); } PHYSAC_FREE(vertices); } } } - #if defined(PHYSAC_DEBUG) - else TRACELOG("[PHYSAC] error when trying to shatter a null reference physics body"); - #endif + else TRACELOG("[PHYSAC] WARNING: PhysicsShatter: NULL physic body\n"); } // Returns the current amount of created physics bodies @@ -733,16 +714,9 @@ PHYSACDEF PhysicsBody GetPhysicsBody(int index) { body = bodies[index]; - if (body == NULL) - { - #if defined(PHYSAC_DEBUG) - TRACELOG("[PHYSAC] error when trying to get a null reference physics body"); - #endif - } + if (body == NULL) TRACELOG("[PHYSAC] WARNING: GetPhysicsBody: NULL physic body\n"); } - #if defined(PHYSAC_DEBUG) - else TRACELOG("[PHYSAC] physics body index is out of bounds"); - #endif + else TRACELOG("[PHYSAC] WARNING: Physic body index is out of bounds\n"); return body; } @@ -757,13 +731,9 @@ PHYSACDEF int GetPhysicsShapeType(int index) PhysicsBody body = bodies[index]; if (body != NULL) result = body->shape.type; - #if defined(PHYSAC_DEBUG) - else TRACELOG("[PHYSAC] error when trying to get a null reference physics body"); - #endif + else TRACELOG("[PHYSAC] WARNING: GetPhysicsShapeType: NULL physic body\n"); } - #if defined(PHYSAC_DEBUG) - else TRACELOG("[PHYSAC] physics body index is out of bounds"); - #endif + else TRACELOG("[PHYSAC] WARNING: Physic body index is out of bounds\n"); return result; } @@ -781,18 +751,14 @@ PHYSACDEF int GetPhysicsShapeVerticesCount(int index) { switch (body->shape.type) { - case PHYSICS_CIRCLE: result = PHYSAC_CIRCLE_VERTICES; break; + case PHYSICS_CIRCLE: result = PHYSAC_DEFAULT_CIRCLE_VERTICES; break; case PHYSICS_POLYGON: result = body->shape.vertexData.vertexCount; break; default: break; } } - #if defined(PHYSAC_DEBUG) - else TRACELOG("[PHYSAC] error when trying to get a null reference physics body"); - #endif + else TRACELOG("[PHYSAC] WARNING: GetPhysicsShapeVerticesCount: NULL physic body\n"); } - #if defined(PHYSAC_DEBUG) - else TRACELOG("[PHYSAC] physics body index is out of bounds"); - #endif + else TRACELOG("[PHYSAC] WARNING: Physic body index is out of bounds\n"); return result; } @@ -808,20 +774,18 @@ PHYSACDEF Vector2 GetPhysicsShapeVertex(PhysicsBody body, int vertex) { case PHYSICS_CIRCLE: { - position.x = body->position.x + cosf(360.0f/PHYSAC_CIRCLE_VERTICES*vertex*PHYSAC_DEG2RAD)*body->shape.radius; - position.y = body->position.y + sinf(360.0f/PHYSAC_CIRCLE_VERTICES*vertex*PHYSAC_DEG2RAD)*body->shape.radius; + position.x = body->position.x + cosf(360.0f/PHYSAC_DEFAULT_CIRCLE_VERTICES*vertex*PHYSAC_DEG2RAD)*body->shape.radius; + position.y = body->position.y + sinf(360.0f/PHYSAC_DEFAULT_CIRCLE_VERTICES*vertex*PHYSAC_DEG2RAD)*body->shape.radius; } break; case PHYSICS_POLYGON: { - PolygonData vertexData = body->shape.vertexData; - position = Vector2Add(body->position, Mat2MultiplyVector2(body->shape.transform, vertexData.positions[vertex])); + PhysicsVertexData vertexData = body->shape.vertexData; + position = MathVector2Add(body->position, MathMatVector2Product(body->shape.transform, vertexData.positions[vertex])); } break; default: break; } } - #if defined(PHYSAC_DEBUG) - else TRACELOG("[PHYSAC] error when trying to get a null reference physics body"); - #endif + else TRACELOG("[PHYSAC] WARNING: GetPhysicsShapeVertex: NULL physic body\n"); return position; } @@ -833,7 +797,7 @@ PHYSACDEF void SetPhysicsBodyRotation(PhysicsBody body, float radians) { body->orient = radians; - if (body->shape.type == PHYSICS_POLYGON) body->shape.transform = Mat2Radians(radians); + if (body->shape.type == PHYSICS_POLYGON) body->shape.transform = MathMatFromRadians(radians); } } @@ -856,9 +820,7 @@ PHYSACDEF void DestroyPhysicsBody(PhysicsBody body) if (index == -1) { - #if defined(PHYSAC_DEBUG) - TRACELOG("[PHYSAC] Not possible to find body id %i in pointers array\n", id); - #endif + TRACELOG("[PHYSAC] WARNING: Requested body (id: %i) can not be found\n", id); return; // Prevent access to index -1 } @@ -876,13 +838,9 @@ PHYSACDEF void DestroyPhysicsBody(PhysicsBody body) // Update physics bodies count physicsBodiesCount--; - #if defined(PHYSAC_DEBUG) - TRACELOG("[PHYSAC] destroyed physics body id %i\n", id); - #endif + TRACELOG("[PHYSAC] Physic body destroyed successfully (id: %i)\n", id); } - #if defined(PHYSAC_DEBUG) - else TRACELOG("[PHYSAC] error trying to destroy a null referenced body\n"); - #endif + else TRACELOG("[PHYSAC] WARNING: DestroyPhysicsBody: NULL physic body\n"); } // Destroys created physics bodies and manifolds and resets global values @@ -918,32 +876,28 @@ PHYSACDEF void ResetPhysics(void) physicsManifoldsCount = 0; - #if defined(PHYSAC_DEBUG) - TRACELOG("[PHYSAC] physics module reset successfully\n"); - #endif + TRACELOG("[PHYSAC] Physics module reseted successfully\n"); } // Unitializes physics pointers and exits physics loop thread PHYSACDEF void ClosePhysics(void) { - // Exit physics loop thread - physicsThreadEnabled = false; - - #if !defined(PHYSAC_NO_THREADS) - pthread_join(physicsThreadId, NULL); - #endif - // Unitialize physics manifolds dynamic memory allocations for (int i = physicsManifoldsCount - 1; i >= 0; i--) DestroyPhysicsManifold(contacts[i]); // Unitialize physics bodies dynamic memory allocations for (int i = physicsBodiesCount - 1; i >= 0; i--) DestroyPhysicsBody(bodies[i]); - #if defined(PHYSAC_DEBUG) - if (physicsBodiesCount > 0 || usedMemory != 0) TRACELOG("[PHYSAC] physics module closed with %i still allocated bodies [MEMORY: %i bytes]\n", physicsBodiesCount, usedMemory); - else if (physicsManifoldsCount > 0 || usedMemory != 0) TRACELOG("[PHYSAC] physics module closed with %i still allocated manifolds [MEMORY: %i bytes]\n", physicsManifoldsCount, usedMemory); - else TRACELOG("[PHYSAC] physics module closed successfully\n"); - #endif + // Trace log info + if ((physicsBodiesCount > 0) || (usedMemory != 0)) + { + TRACELOG("[PHYSAC] WARNING: Physics module closed with unallocated bodies (BODIES: %i, MEMORY: %i bytes)\n", physicsBodiesCount, usedMemory); + } + else if ((physicsManifoldsCount > 0) || (usedMemory != 0)) + { + TRACELOG("[PHYSAC] WARNING: Pysics module closed with unallocated manifolds (MANIFOLDS: %i, MEMORY: %i bytes)\n", physicsManifoldsCount, usedMemory); + } + else TRACELOG("[PHYSAC] Physics module closed successfully\n"); } //---------------------------------------------------------------------------------- @@ -978,10 +932,10 @@ static int FindAvailableBodyIndex() return index; } -// Creates a random polygon shape with max vertex distance from polygon pivot -static PolygonData CreateRandomPolygon(float radius, int sides) +// Creates a default polygon shape with max vertex distance from polygon pivot +static PhysicsVertexData CreateDefaultPolygon(float radius, int sides) { - PolygonData data = { 0 }; + PhysicsVertexData data = { 0 }; data.vertexCount = sides; // Calculate polygon vertices positions @@ -995,67 +949,43 @@ static PolygonData CreateRandomPolygon(float radius, int sides) for (int i = 0; i < data.vertexCount; i++) { int nextIndex = (((i + 1) < sides) ? (i + 1) : 0); - Vector2 face = Vector2Subtract(data.positions[nextIndex], data.positions[i]); + Vector2 face = MathVector2Subtract(data.positions[nextIndex], data.positions[i]); - data.normals[i] = (Vector2){ face.y, -face.x }; - MathNormalize(&data.normals[i]); + data.normals[i] = CLITERAL(Vector2){ face.y, -face.x }; + MathVector2Normalize(&data.normals[i]); } return data; } // Creates a rectangle polygon shape based on a min and max positions -static PolygonData CreateRectanglePolygon(Vector2 pos, Vector2 size) +static PhysicsVertexData CreateRectanglePolygon(Vector2 pos, Vector2 size) { - PolygonData data = { 0 }; + PhysicsVertexData data = { 0 }; data.vertexCount = 4; // Calculate polygon vertices positions - data.positions[0] = (Vector2){ pos.x + size.x/2, pos.y - size.y/2 }; - data.positions[1] = (Vector2){ pos.x + size.x/2, pos.y + size.y/2 }; - data.positions[2] = (Vector2){ pos.x - size.x/2, pos.y + size.y/2 }; - data.positions[3] = (Vector2){ pos.x - size.x/2, pos.y - size.y/2 }; + data.positions[0] = CLITERAL(Vector2){ pos.x + size.x/2, pos.y - size.y/2 }; + data.positions[1] = CLITERAL(Vector2){ pos.x + size.x/2, pos.y + size.y/2 }; + data.positions[2] = CLITERAL(Vector2){ pos.x - size.x/2, pos.y + size.y/2 }; + data.positions[3] = CLITERAL(Vector2){ pos.x - size.x/2, pos.y - size.y/2 }; // Calculate polygon faces normals for (int i = 0; i < data.vertexCount; i++) { int nextIndex = (((i + 1) < data.vertexCount) ? (i + 1) : 0); - Vector2 face = Vector2Subtract(data.positions[nextIndex], data.positions[i]); + Vector2 face = MathVector2Subtract(data.positions[nextIndex], data.positions[i]); - data.normals[i] = (Vector2){ face.y, -face.x }; - MathNormalize(&data.normals[i]); + data.normals[i] = CLITERAL(Vector2){ face.y, -face.x }; + MathVector2Normalize(&data.normals[i]); } return data; } -// Physics loop thread function -static void *PhysicsLoop(void *arg) +// Update physics step (dynamics, collisions and position corrections) +void UpdatePhysicsStep(void) { -#if !defined(PHYSAC_NO_THREADS) - #if defined(PHYSAC_DEBUG) - TRACELOG("[PHYSAC] physics thread created successfully\n"); - #endif - - // Initialize physics loop thread values - physicsThreadEnabled = true; - - // Physics update loop - while (physicsThreadEnabled) - { - RunPhysicsStep(); - } -#endif - - return NULL; -} - -// Physics steps calculations (dynamics, collisions and position corrections) -static void PhysicsStep(void) -{ - // Update current steps count - stepsCount++; - // Clear previous generated collisions information for (int i = physicsManifoldsCount - 1; i >= 0; i--) { @@ -1091,15 +1021,15 @@ static void PhysicsStep(void) if (manifold->contactsCount > 0) { // Create a new manifold with same information as previously solved manifold and add it to the manifolds pool last slot - PhysicsManifold newManifold = CreatePhysicsManifold(bodyA, bodyB); - newManifold->penetration = manifold->penetration; - newManifold->normal = manifold->normal; - newManifold->contacts[0] = manifold->contacts[0]; - newManifold->contacts[1] = manifold->contacts[1]; - newManifold->contactsCount = manifold->contactsCount; - newManifold->restitution = manifold->restitution; - newManifold->dynamicFriction = manifold->dynamicFriction; - newManifold->staticFriction = manifold->staticFriction; + PhysicsManifold manifold = CreatePhysicsManifold(bodyA, bodyB); + manifold->penetration = manifold->penetration; + manifold->normal = manifold->normal; + manifold->contacts[0] = manifold->contacts[0]; + manifold->contacts[1] = manifold->contacts[1]; + manifold->contactsCount = manifold->contactsCount; + manifold->restitution = manifold->restitution; + manifold->dynamicFriction = manifold->dynamicFriction; + manifold->staticFriction = manifold->staticFriction; } } } @@ -1156,31 +1086,34 @@ static void PhysicsStep(void) } } -// Wrapper to ensure PhysicsStep is run with at a fixed time step -PHYSACDEF void RunPhysicsStep(void) +// Update physics system +// Physics steps are launched at a fixed time step if enabled +PHYSACDEF void UpdatePhysics(void) { - // Calculate current time +#if !defined(PHYSAC_AVOID_TIMMING_SYSTEM) + static double deltaTimeAccumulator = 0.0; + + // Calculate current time (ms) currentTime = GetCurrentTime(); - // Calculate current delta time + // Calculate current delta time (ms) const double delta = currentTime - startTime; // Store the time elapsed since the last frame began - accumulator += delta; + deltaTimeAccumulator += delta; // Fixed time stepping loop - while (accumulator >= deltaTime) + while (deltaTimeAccumulator >= deltaTime) { -#ifdef PHYSAC_DEBUG - //TRACELOG("currentTime %f, startTime %f, accumulator-pre %f, accumulator-post %f, delta %f, deltaTime %f\n", - // currentTime, startTime, accumulator, accumulator-deltaTime, delta, deltaTime); -#endif - PhysicsStep(); - accumulator -= deltaTime; + UpdatePhysicsStep(); + deltaTimeAccumulator -= deltaTime; } // Record the starting of this frame startTime = currentTime; +#else + UpdatePhysicsStep(); +#endif } PHYSACDEF void SetPhysicsTimeStep(double delta) @@ -1220,34 +1153,32 @@ static int FindAvailableManifoldIndex() // Creates a new physics manifold to solve collision static PhysicsManifold CreatePhysicsManifold(PhysicsBody a, PhysicsBody b) { - PhysicsManifold newManifold = (PhysicsManifold)PHYSAC_MALLOC(sizeof(PhysicsManifoldData)); + PhysicsManifold manifold = (PhysicsManifold)PHYSAC_MALLOC(sizeof(PhysicsManifoldData)); usedMemory += sizeof(PhysicsManifoldData); - int newId = FindAvailableManifoldIndex(); - if (newId != -1) + int id = FindAvailableManifoldIndex(); + if (id != -1) { // Initialize new manifold with generic values - newManifold->id = newId; - newManifold->bodyA = a; - newManifold->bodyB = b; - newManifold->penetration = 0; - newManifold->normal = PHYSAC_VECTOR_ZERO; - newManifold->contacts[0] = PHYSAC_VECTOR_ZERO; - newManifold->contacts[1] = PHYSAC_VECTOR_ZERO; - newManifold->contactsCount = 0; - newManifold->restitution = 0.0f; - newManifold->dynamicFriction = 0.0f; - newManifold->staticFriction = 0.0f; + manifold->id = id; + manifold->bodyA = a; + manifold->bodyB = b; + manifold->penetration = 0; + manifold->normal = PHYSAC_VECTOR_ZERO; + manifold->contacts[0] = PHYSAC_VECTOR_ZERO; + manifold->contacts[1] = PHYSAC_VECTOR_ZERO; + manifold->contactsCount = 0; + manifold->restitution = 0.0f; + manifold->dynamicFriction = 0.0f; + manifold->staticFriction = 0.0f; // Add new body to bodies pointers array and update bodies count - contacts[physicsManifoldsCount] = newManifold; + contacts[physicsManifoldsCount] = manifold; physicsManifoldsCount++; } - #if defined(PHYSAC_DEBUG) - else TRACELOG("[PHYSAC] new physics manifold creation failed because there is any available id to use\n"); - #endif + else TRACELOG("[PHYSAC] Physic manifold could not be created, PHYSAC_MAX_MANIFOLDS reached\n"); - return newManifold; + return manifold; } // Unitializes and destroys a physics manifold @@ -1267,13 +1198,7 @@ static void DestroyPhysicsManifold(PhysicsManifold manifold) } } - if (index == -1) - { - #if defined(PHYSAC_DEBUG) - TRACELOG("[PHYSAC] Not possible to manifold id %i in pointers array\n", id); - #endif - return; // Prevent access to index -1 - } + if (index == -1) return; // Prevent access to index -1 // Free manifold allocated memory PHYSAC_FREE(manifold); @@ -1289,9 +1214,7 @@ static void DestroyPhysicsManifold(PhysicsManifold manifold) // Update physics manifolds count physicsManifoldsCount--; } - #if defined(PHYSAC_DEBUG) - else TRACELOG("[PHYSAC] error trying to destroy a null referenced manifold\n"); - #endif + else TRACELOG("[PHYSAC] WARNING: DestroyPhysicsManifold: NULL physic manifold\n"); } // Solves a created physics manifold between two physics bodies @@ -1333,9 +1256,9 @@ static void SolveCircleToCircle(PhysicsManifold manifold) if ((bodyA == NULL) || (bodyB == NULL)) return; // Calculate translational vector, which is normal - Vector2 normal = Vector2Subtract(bodyB->position, bodyA->position); + Vector2 normal = MathVector2Subtract(bodyB->position, bodyA->position); - float distSqr = MathLenSqr(normal); + float distSqr = MathVector2SqrLen(normal); float radius = bodyA->shape.radius + bodyB->shape.radius; // Check if circles are not in contact @@ -1351,14 +1274,14 @@ static void SolveCircleToCircle(PhysicsManifold manifold) if (distance == 0.0f) { manifold->penetration = bodyA->shape.radius; - manifold->normal = (Vector2){ 1.0f, 0.0f }; + manifold->normal = CLITERAL(Vector2){ 1.0f, 0.0f }; manifold->contacts[0] = bodyA->position; } else { manifold->penetration = radius - distance; - manifold->normal = (Vector2){ normal.x/distance, normal.y/distance }; // Faster than using MathNormalize() due to sqrt is already performed - manifold->contacts[0] = (Vector2){ manifold->normal.x*bodyA->shape.radius + bodyA->position.x, manifold->normal.y*bodyA->shape.radius + bodyA->position.y }; + manifold->normal = CLITERAL(Vector2){ normal.x/distance, normal.y/distance }; // Faster than using MathVector2Normalize() due to sqrt is already performed + manifold->contacts[0] = CLITERAL(Vector2){ manifold->normal.x*bodyA->shape.radius + bodyA->position.x, manifold->normal.y*bodyA->shape.radius + bodyA->position.y }; } // Update physics body grounded state if normal direction is down @@ -1377,17 +1300,17 @@ static void SolveCircleToPolygon(PhysicsManifold manifold) // Transform circle center to polygon transform space Vector2 center = bodyA->position; - center = Mat2MultiplyVector2(Mat2Transpose(bodyB->shape.transform), Vector2Subtract(center, bodyB->position)); + center = MathMatVector2Product(MathMatTranspose(bodyB->shape.transform), MathVector2Subtract(center, bodyB->position)); // Find edge with minimum penetration // It is the same concept as using support points in SolvePolygonToPolygon float separation = -PHYSAC_FLT_MAX; int faceNormal = 0; - PolygonData vertexData = bodyB->shape.vertexData; + PhysicsVertexData vertexData = bodyB->shape.vertexData; for (int i = 0; i < vertexData.vertexCount; i++) { - float currentSeparation = MathDot(vertexData.normals[i], Vector2Subtract(center, vertexData.positions[i])); + float currentSeparation = MathVector2DotProduct(vertexData.normals[i], MathVector2Subtract(center, vertexData.positions[i])); if (currentSeparation > bodyA->shape.radius) return; @@ -1407,53 +1330,53 @@ static void SolveCircleToPolygon(PhysicsManifold manifold) if (separation < PHYSAC_EPSILON) { manifold->contactsCount = 1; - Vector2 normal = Mat2MultiplyVector2(bodyB->shape.transform, vertexData.normals[faceNormal]); - manifold->normal = (Vector2){ -normal.x, -normal.y }; - manifold->contacts[0] = (Vector2){ manifold->normal.x*bodyA->shape.radius + bodyA->position.x, manifold->normal.y*bodyA->shape.radius + bodyA->position.y }; + Vector2 normal = MathMatVector2Product(bodyB->shape.transform, vertexData.normals[faceNormal]); + manifold->normal = CLITERAL(Vector2){ -normal.x, -normal.y }; + manifold->contacts[0] = CLITERAL(Vector2){ manifold->normal.x*bodyA->shape.radius + bodyA->position.x, manifold->normal.y*bodyA->shape.radius + bodyA->position.y }; manifold->penetration = bodyA->shape.radius; return; } // Determine which voronoi region of the edge center of circle lies within - float dot1 = MathDot(Vector2Subtract(center, v1), Vector2Subtract(v2, v1)); - float dot2 = MathDot(Vector2Subtract(center, v2), Vector2Subtract(v1, v2)); + float dot1 = MathVector2DotProduct(MathVector2Subtract(center, v1), MathVector2Subtract(v2, v1)); + float dot2 = MathVector2DotProduct(MathVector2Subtract(center, v2), MathVector2Subtract(v1, v2)); manifold->penetration = bodyA->shape.radius - separation; if (dot1 <= 0.0f) // Closest to v1 { - if (DistSqr(center, v1) > bodyA->shape.radius*bodyA->shape.radius) return; + if (MathVector2SqrDistance(center, v1) > bodyA->shape.radius*bodyA->shape.radius) return; manifold->contactsCount = 1; - Vector2 normal = Vector2Subtract(v1, center); - normal = Mat2MultiplyVector2(bodyB->shape.transform, normal); - MathNormalize(&normal); + Vector2 normal = MathVector2Subtract(v1, center); + normal = MathMatVector2Product(bodyB->shape.transform, normal); + MathVector2Normalize(&normal); manifold->normal = normal; - v1 = Mat2MultiplyVector2(bodyB->shape.transform, v1); - v1 = Vector2Add(v1, bodyB->position); + v1 = MathMatVector2Product(bodyB->shape.transform, v1); + v1 = MathVector2Add(v1, bodyB->position); manifold->contacts[0] = v1; } else if (dot2 <= 0.0f) // Closest to v2 { - if (DistSqr(center, v2) > bodyA->shape.radius*bodyA->shape.radius) return; + if (MathVector2SqrDistance(center, v2) > bodyA->shape.radius*bodyA->shape.radius) return; manifold->contactsCount = 1; - Vector2 normal = Vector2Subtract(v2, center); - v2 = Mat2MultiplyVector2(bodyB->shape.transform, v2); - v2 = Vector2Add(v2, bodyB->position); + Vector2 normal = MathVector2Subtract(v2, center); + v2 = MathMatVector2Product(bodyB->shape.transform, v2); + v2 = MathVector2Add(v2, bodyB->position); manifold->contacts[0] = v2; - normal = Mat2MultiplyVector2(bodyB->shape.transform, normal); - MathNormalize(&normal); + normal = MathMatVector2Product(bodyB->shape.transform, normal); + MathVector2Normalize(&normal); manifold->normal = normal; } else // Closest to face { Vector2 normal = vertexData.normals[faceNormal]; - if (MathDot(Vector2Subtract(center, v1), normal) > bodyA->shape.radius) return; + if (MathVector2DotProduct(MathVector2Subtract(center, v1), normal) > bodyA->shape.radius) return; - normal = Mat2MultiplyVector2(bodyB->shape.transform, normal); - manifold->normal = (Vector2){ -normal.x, -normal.y }; - manifold->contacts[0] = (Vector2){ manifold->normal.x*bodyA->shape.radius + bodyA->position.x, manifold->normal.y*bodyA->shape.radius + bodyA->position.y }; + normal = MathMatVector2Product(bodyB->shape.transform, normal); + manifold->normal = CLITERAL(Vector2){ -normal.x, -normal.y }; + manifold->contacts[0] = CLITERAL(Vector2){ manifold->normal.x*bodyA->shape.radius + bodyA->position.x, manifold->normal.y*bodyA->shape.radius + bodyA->position.y }; manifold->contactsCount = 1; } } @@ -1500,7 +1423,8 @@ static void SolvePolygonToPolygon(PhysicsManifold manifold) PhysicsShape incPoly; // Incident // Determine which shape contains reference face - if (BiasGreaterThan(penetrationA, penetrationB)) + // Checking bias range for penetration + if (penetrationA >= (penetrationB*0.95f + penetrationA*0.01f)) { refPoly = bodyA; incPoly = bodyB; @@ -1519,37 +1443,37 @@ static void SolvePolygonToPolygon(PhysicsManifold manifold) FindIncidentFace(&incidentFace[0], &incidentFace[1], refPoly, incPoly, referenceIndex); // Setup reference face vertices - PolygonData refData = refPoly.vertexData; + PhysicsVertexData refData = refPoly.vertexData; Vector2 v1 = refData.positions[referenceIndex]; referenceIndex = (((referenceIndex + 1) < refData.vertexCount) ? (referenceIndex + 1) : 0); Vector2 v2 = refData.positions[referenceIndex]; // Transform vertices to world space - v1 = Mat2MultiplyVector2(refPoly.transform, v1); - v1 = Vector2Add(v1, refPoly.body->position); - v2 = Mat2MultiplyVector2(refPoly.transform, v2); - v2 = Vector2Add(v2, refPoly.body->position); + v1 = MathMatVector2Product(refPoly.transform, v1); + v1 = MathVector2Add(v1, refPoly.body->position); + v2 = MathMatVector2Product(refPoly.transform, v2); + v2 = MathVector2Add(v2, refPoly.body->position); // Calculate reference face side normal in world space - Vector2 sidePlaneNormal = Vector2Subtract(v2, v1); - MathNormalize(&sidePlaneNormal); + Vector2 sidePlaneNormal = MathVector2Subtract(v2, v1); + MathVector2Normalize(&sidePlaneNormal); // Orthogonalize Vector2 refFaceNormal = { sidePlaneNormal.y, -sidePlaneNormal.x }; - float refC = MathDot(refFaceNormal, v1); - float negSide = MathDot(sidePlaneNormal, v1)*-1; - float posSide = MathDot(sidePlaneNormal, v2); + float refC = MathVector2DotProduct(refFaceNormal, v1); + float negSide = MathVector2DotProduct(sidePlaneNormal, v1)*-1; + float posSide = MathVector2DotProduct(sidePlaneNormal, v2); - // Clip incident face to reference face side planes (due to floating point error, possible to not have required points - if (Clip((Vector2){ -sidePlaneNormal.x, -sidePlaneNormal.y }, negSide, &incidentFace[0], &incidentFace[1]) < 2) return; - if (Clip(sidePlaneNormal, posSide, &incidentFace[0], &incidentFace[1]) < 2) return; + // MathVector2Clip incident face to reference face side planes (due to floating point error, possible to not have required points + if (MathVector2Clip(CLITERAL(Vector2){ -sidePlaneNormal.x, -sidePlaneNormal.y }, &incidentFace[0], &incidentFace[1], negSide) < 2) return; + if (MathVector2Clip(sidePlaneNormal, &incidentFace[0], &incidentFace[1], posSide) < 2) return; // Flip normal if required - manifold->normal = (flip ? (Vector2){ -refFaceNormal.x, -refFaceNormal.y } : refFaceNormal); + manifold->normal = (flip ? CLITERAL(Vector2){ -refFaceNormal.x, -refFaceNormal.y } : refFaceNormal); // Keep points behind reference face - int currentPoint = 0; // Clipped points behind reference face - float separation = MathDot(refFaceNormal, incidentFace[0]) - refC; + int currentPoint = 0; // MathVector2Clipped points behind reference face + float separation = MathVector2DotProduct(refFaceNormal, incidentFace[0]) - refC; if (separation <= 0.0f) { manifold->contacts[currentPoint] = incidentFace[0]; @@ -1558,7 +1482,7 @@ static void SolvePolygonToPolygon(PhysicsManifold manifold) } else manifold->penetration = 0.0f; - separation = MathDot(refFaceNormal, incidentFace[1]) - refC; + separation = MathVector2DotProduct(refFaceNormal, incidentFace[1]) - refC; if (separation <= 0.0f) { @@ -1606,11 +1530,11 @@ static void InitializePhysicsManifolds(PhysicsManifold manifold) for (int i = 0; i < manifold->contactsCount; i++) { // Caculate radius from center of mass to contact - Vector2 radiusA = Vector2Subtract(manifold->contacts[i], bodyA->position); - Vector2 radiusB = Vector2Subtract(manifold->contacts[i], bodyB->position); + Vector2 radiusA = MathVector2Subtract(manifold->contacts[i], bodyA->position); + Vector2 radiusB = MathVector2Subtract(manifold->contacts[i], bodyB->position); - Vector2 crossA = MathCross(bodyA->angularVelocity, radiusA); - Vector2 crossB = MathCross(bodyB->angularVelocity, radiusB); + Vector2 crossA = MathVector2Product(radiusA, bodyA->angularVelocity); + Vector2 crossB = MathVector2Product(radiusB, bodyB->angularVelocity); Vector2 radiusV = { 0.0f, 0.0f }; radiusV.x = bodyB->velocity.x + crossB.x - bodyA->velocity.x - crossA.x; @@ -1618,7 +1542,7 @@ static void InitializePhysicsManifolds(PhysicsManifold manifold) // Determine if we should perform a resting collision or not; // The idea is if the only thing moving this object is gravity, then the collision should be performed without any restitution - if (MathLenSqr(radiusV) < (MathLenSqr((Vector2){ gravityForce.x*deltaTime/1000, gravityForce.y*deltaTime/1000 }) + PHYSAC_EPSILON)) manifold->restitution = 0; + if (MathVector2SqrLen(radiusV) < (MathVector2SqrLen(CLITERAL(Vector2){ gravityForce.x*deltaTime/1000, gravityForce.y*deltaTime/1000 }) + PHYSAC_EPSILON)) manifold->restitution = 0; } } @@ -1641,22 +1565,22 @@ static void IntegratePhysicsImpulses(PhysicsManifold manifold) for (int i = 0; i < manifold->contactsCount; i++) { // Calculate radius from center of mass to contact - Vector2 radiusA = Vector2Subtract(manifold->contacts[i], bodyA->position); - Vector2 radiusB = Vector2Subtract(manifold->contacts[i], bodyB->position); + Vector2 radiusA = MathVector2Subtract(manifold->contacts[i], bodyA->position); + Vector2 radiusB = MathVector2Subtract(manifold->contacts[i], bodyB->position); // Calculate relative velocity Vector2 radiusV = { 0.0f, 0.0f }; - radiusV.x = bodyB->velocity.x + MathCross(bodyB->angularVelocity, radiusB).x - bodyA->velocity.x - MathCross(bodyA->angularVelocity, radiusA).x; - radiusV.y = bodyB->velocity.y + MathCross(bodyB->angularVelocity, radiusB).y - bodyA->velocity.y - MathCross(bodyA->angularVelocity, radiusA).y; + radiusV.x = bodyB->velocity.x + MathVector2Product(radiusB, bodyB->angularVelocity).x - bodyA->velocity.x - MathVector2Product(radiusA, bodyA->angularVelocity).x; + radiusV.y = bodyB->velocity.y + MathVector2Product(radiusB, bodyB->angularVelocity).y - bodyA->velocity.y - MathVector2Product(radiusA, bodyA->angularVelocity).y; // Relative velocity along the normal - float contactVelocity = MathDot(radiusV, manifold->normal); + float contactVelocity = MathVector2DotProduct(radiusV, manifold->normal); // Do not resolve if velocities are separating if (contactVelocity > 0.0f) return; - float raCrossN = MathCrossVector2(radiusA, manifold->normal); - float rbCrossN = MathCrossVector2(radiusB, manifold->normal); + float raCrossN = MathVector2CrossProduct(radiusA, manifold->normal); + float rbCrossN = MathVector2CrossProduct(radiusB, manifold->normal); float inverseMassSum = bodyA->inverseMass + bodyB->inverseMass + (raCrossN*raCrossN)*bodyA->inverseInertia + (rbCrossN*rbCrossN)*bodyB->inverseInertia; @@ -1672,25 +1596,25 @@ static void IntegratePhysicsImpulses(PhysicsManifold manifold) { bodyA->velocity.x += bodyA->inverseMass*(-impulseV.x); bodyA->velocity.y += bodyA->inverseMass*(-impulseV.y); - if (!bodyA->freezeOrient) bodyA->angularVelocity += bodyA->inverseInertia*MathCrossVector2(radiusA, (Vector2){ -impulseV.x, -impulseV.y }); + if (!bodyA->freezeOrient) bodyA->angularVelocity += bodyA->inverseInertia*MathVector2CrossProduct(radiusA, CLITERAL(Vector2){ -impulseV.x, -impulseV.y }); } if (bodyB->enabled) { bodyB->velocity.x += bodyB->inverseMass*(impulseV.x); bodyB->velocity.y += bodyB->inverseMass*(impulseV.y); - if (!bodyB->freezeOrient) bodyB->angularVelocity += bodyB->inverseInertia*MathCrossVector2(radiusB, impulseV); + if (!bodyB->freezeOrient) bodyB->angularVelocity += bodyB->inverseInertia*MathVector2CrossProduct(radiusB, impulseV); } // Apply friction impulse to each physics body - radiusV.x = bodyB->velocity.x + MathCross(bodyB->angularVelocity, radiusB).x - bodyA->velocity.x - MathCross(bodyA->angularVelocity, radiusA).x; - radiusV.y = bodyB->velocity.y + MathCross(bodyB->angularVelocity, radiusB).y - bodyA->velocity.y - MathCross(bodyA->angularVelocity, radiusA).y; + radiusV.x = bodyB->velocity.x + MathVector2Product(radiusB, bodyB->angularVelocity).x - bodyA->velocity.x - MathVector2Product(radiusA, bodyA->angularVelocity).x; + radiusV.y = bodyB->velocity.y + MathVector2Product(radiusB, bodyB->angularVelocity).y - bodyA->velocity.y - MathVector2Product(radiusA, bodyA->angularVelocity).y; - Vector2 tangent = { radiusV.x - (manifold->normal.x*MathDot(radiusV, manifold->normal)), radiusV.y - (manifold->normal.y*MathDot(radiusV, manifold->normal)) }; - MathNormalize(&tangent); + Vector2 tangent = { radiusV.x - (manifold->normal.x*MathVector2DotProduct(radiusV, manifold->normal)), radiusV.y - (manifold->normal.y*MathVector2DotProduct(radiusV, manifold->normal)) }; + MathVector2Normalize(&tangent); // Calculate impulse tangent magnitude - float impulseTangent = -MathDot(radiusV, tangent); + float impulseTangent = -MathVector2DotProduct(radiusV, tangent); impulseTangent /= inverseMassSum; impulseTangent /= (float)manifold->contactsCount; @@ -1701,8 +1625,8 @@ static void IntegratePhysicsImpulses(PhysicsManifold manifold) // Apply coulumb's law Vector2 tangentImpulse = { 0.0f, 0.0f }; - if (absImpulseTangent < impulse*manifold->staticFriction) tangentImpulse = (Vector2){ tangent.x*impulseTangent, tangent.y*impulseTangent }; - else tangentImpulse = (Vector2){ tangent.x*-impulse*manifold->dynamicFriction, tangent.y*-impulse*manifold->dynamicFriction }; + if (absImpulseTangent < impulse*manifold->staticFriction) tangentImpulse = CLITERAL(Vector2){ tangent.x*impulseTangent, tangent.y*impulseTangent }; + else tangentImpulse = CLITERAL(Vector2){ tangent.x*-impulse*manifold->dynamicFriction, tangent.y*-impulse*manifold->dynamicFriction }; // Apply friction impulse if (bodyA->enabled) @@ -1710,7 +1634,7 @@ static void IntegratePhysicsImpulses(PhysicsManifold manifold) bodyA->velocity.x += bodyA->inverseMass*(-tangentImpulse.x); bodyA->velocity.y += bodyA->inverseMass*(-tangentImpulse.y); - if (!bodyA->freezeOrient) bodyA->angularVelocity += bodyA->inverseInertia*MathCrossVector2(radiusA, (Vector2){ -tangentImpulse.x, -tangentImpulse.y }); + if (!bodyA->freezeOrient) bodyA->angularVelocity += bodyA->inverseInertia*MathVector2CrossProduct(radiusA, CLITERAL(Vector2){ -tangentImpulse.x, -tangentImpulse.y }); } if (bodyB->enabled) @@ -1718,7 +1642,7 @@ static void IntegratePhysicsImpulses(PhysicsManifold manifold) bodyB->velocity.x += bodyB->inverseMass*(tangentImpulse.x); bodyB->velocity.y += bodyB->inverseMass*(tangentImpulse.y); - if (!bodyB->freezeOrient) bodyB->angularVelocity += bodyB->inverseInertia*MathCrossVector2(radiusB, tangentImpulse); + if (!bodyB->freezeOrient) bodyB->angularVelocity += bodyB->inverseInertia*MathVector2CrossProduct(radiusB, tangentImpulse); } } } @@ -1732,7 +1656,7 @@ static void IntegratePhysicsVelocity(PhysicsBody body) body->position.y += body->velocity.y*deltaTime; if (!body->freezeOrient) body->orient += body->angularVelocity*deltaTime; - Mat2Set(&body->shape.transform, body->orient); + body->shape.transform = MathMatFromRadians(body->orient); IntegratePhysicsForces(body); } @@ -1746,8 +1670,8 @@ static void CorrectPhysicsPositions(PhysicsManifold manifold) if ((bodyA == NULL) || (bodyB == NULL)) return; Vector2 correction = { 0.0f, 0.0f }; - correction.x = (max(manifold->penetration - PHYSAC_PENETRATION_ALLOWANCE, 0.0f)/(bodyA->inverseMass + bodyB->inverseMass))*manifold->normal.x*PHYSAC_PENETRATION_CORRECTION; - correction.y = (max(manifold->penetration - PHYSAC_PENETRATION_ALLOWANCE, 0.0f)/(bodyA->inverseMass + bodyB->inverseMass))*manifold->normal.y*PHYSAC_PENETRATION_CORRECTION; + correction.x = (PHYSAC_MAX(manifold->penetration - PHYSAC_PENETRATION_ALLOWANCE, 0.0f)/(bodyA->inverseMass + bodyB->inverseMass))*manifold->normal.x*PHYSAC_PENETRATION_CORRECTION; + correction.y = (PHYSAC_MAX(manifold->penetration - PHYSAC_PENETRATION_ALLOWANCE, 0.0f)/(bodyA->inverseMass + bodyB->inverseMass))*manifold->normal.y*PHYSAC_PENETRATION_CORRECTION; if (bodyA->enabled) { @@ -1767,12 +1691,12 @@ static Vector2 GetSupport(PhysicsShape shape, Vector2 dir) { float bestProjection = -PHYSAC_FLT_MAX; Vector2 bestVertex = { 0.0f, 0.0f }; - PolygonData data = shape.vertexData; + PhysicsVertexData data = shape.vertexData; for (int i = 0; i < data.vertexCount; i++) { Vector2 vertex = data.positions[i]; - float projection = MathDot(vertex, dir); + float projection = MathVector2DotProduct(vertex, dir); if (projection > bestProjection) { @@ -1790,31 +1714,31 @@ static float FindAxisLeastPenetration(int *faceIndex, PhysicsShape shapeA, Physi float bestDistance = -PHYSAC_FLT_MAX; int bestIndex = 0; - PolygonData dataA = shapeA.vertexData; - //PolygonData dataB = shapeB.vertexData; + PhysicsVertexData dataA = shapeA.vertexData; + //PhysicsVertexData dataB = shapeB.vertexData; for (int i = 0; i < dataA.vertexCount; i++) { // Retrieve a face normal from A shape Vector2 normal = dataA.normals[i]; - Vector2 transNormal = Mat2MultiplyVector2(shapeA.transform, normal); + Vector2 transNormal = MathMatVector2Product(shapeA.transform, normal); // Transform face normal into B shape's model space - Matrix2x2 buT = Mat2Transpose(shapeB.transform); - normal = Mat2MultiplyVector2(buT, transNormal); + Matrix2x2 buT = MathMatTranspose(shapeB.transform); + normal = MathMatVector2Product(buT, transNormal); // Retrieve support point from B shape along -n - Vector2 support = GetSupport(shapeB, (Vector2){ -normal.x, -normal.y }); + Vector2 support = GetSupport(shapeB, CLITERAL(Vector2){ -normal.x, -normal.y }); // Retrieve vertex on face from A shape, transform into B shape's model space Vector2 vertex = dataA.positions[i]; - vertex = Mat2MultiplyVector2(shapeA.transform, vertex); - vertex = Vector2Add(vertex, shapeA.body->position); - vertex = Vector2Subtract(vertex, shapeB.body->position); - vertex = Mat2MultiplyVector2(buT, vertex); + vertex = MathMatVector2Product(shapeA.transform, vertex); + vertex = MathVector2Add(vertex, shapeA.body->position); + vertex = MathVector2Subtract(vertex, shapeB.body->position); + vertex = MathMatVector2Product(buT, vertex); // Compute penetration distance in B shape's model space - float distance = MathDot(normal, Vector2Subtract(support, vertex)); + float distance = MathVector2DotProduct(normal, MathVector2Subtract(support, vertex)); // Store greatest distance if (distance > bestDistance) @@ -1831,14 +1755,14 @@ static float FindAxisLeastPenetration(int *faceIndex, PhysicsShape shapeA, Physi // Finds two polygon shapes incident face static void FindIncidentFace(Vector2 *v0, Vector2 *v1, PhysicsShape ref, PhysicsShape inc, int index) { - PolygonData refData = ref.vertexData; - PolygonData incData = inc.vertexData; + PhysicsVertexData refData = ref.vertexData; + PhysicsVertexData incData = inc.vertexData; Vector2 referenceNormal = refData.normals[index]; // Calculate normal in incident's frame of reference - referenceNormal = Mat2MultiplyVector2(ref.transform, referenceNormal); // To world space - referenceNormal = Mat2MultiplyVector2(Mat2Transpose(inc.transform), referenceNormal); // To incident's model space + referenceNormal = MathMatVector2Product(ref.transform, referenceNormal); // To world space + referenceNormal = MathMatVector2Product(MathMatTranspose(inc.transform), referenceNormal); // To incident's model space // Find most anti-normal face on polygon int incidentFace = 0; @@ -1846,7 +1770,7 @@ static void FindIncidentFace(Vector2 *v0, Vector2 *v1, PhysicsShape ref, Physics for (int i = 0; i < incData.vertexCount; i++) { - float dot = MathDot(referenceNormal, incData.normals[i]); + float dot = MathVector2DotProduct(referenceNormal, incData.normals[i]); if (dot < minDot) { @@ -1856,22 +1780,22 @@ static void FindIncidentFace(Vector2 *v0, Vector2 *v1, PhysicsShape ref, Physics } // Assign face vertices for incident face - *v0 = Mat2MultiplyVector2(inc.transform, incData.positions[incidentFace]); - *v0 = Vector2Add(*v0, inc.body->position); + *v0 = MathMatVector2Product(inc.transform, incData.positions[incidentFace]); + *v0 = MathVector2Add(*v0, inc.body->position); incidentFace = (((incidentFace + 1) < incData.vertexCount) ? (incidentFace + 1) : 0); - *v1 = Mat2MultiplyVector2(inc.transform, incData.positions[incidentFace]); - *v1 = Vector2Add(*v1, inc.body->position); + *v1 = MathMatVector2Product(inc.transform, incData.positions[incidentFace]); + *v1 = MathVector2Add(*v1, inc.body->position); } -// Calculates clipping based on a normal and two faces -static int Clip(Vector2 normal, float clip, Vector2 *faceA, Vector2 *faceB) +// Returns clipping value based on a normal and two faces +static int MathVector2Clip(Vector2 normal, Vector2 *faceA, Vector2 *faceB, float clip) { int sp = 0; Vector2 out[2] = { *faceA, *faceB }; // Retrieve distances from each endpoint to the line - float distanceA = MathDot(normal, *faceA) - clip; - float distanceB = MathDot(normal, *faceB) - clip; + float distanceA = MathVector2DotProduct(normal, *faceA) - clip; + float distanceB = MathVector2DotProduct(normal, *faceB) - clip; // If negative (behind plane) if (distanceA <= 0.0f) out[sp++] = *faceA; @@ -1883,10 +1807,10 @@ static int Clip(Vector2 normal, float clip, Vector2 *faceA, Vector2 *faceB) // Push intersection point float alpha = distanceA/(distanceA - distanceB); out[sp] = *faceA; - Vector2 delta = Vector2Subtract(*faceB, *faceA); + Vector2 delta = MathVector2Subtract(*faceB, *faceA); delta.x *= alpha; delta.y *= alpha; - out[sp] = Vector2Add(out[sp], delta); + out[sp] = MathVector2Add(out[sp], delta); sp++; } @@ -1897,14 +1821,8 @@ static int Clip(Vector2 normal, float clip, Vector2 *faceA, Vector2 *faceB) return sp; } -// Check if values are between bias range -static bool BiasGreaterThan(float valueA, float valueB) -{ - return (valueA >= (valueB*0.95f + valueA*0.01f)); -} - // Returns the barycenter of a triangle given by 3 points -static Vector2 TriangleBarycenter(Vector2 v1, Vector2 v2, Vector2 v3) +static Vector2 MathTriangleBarycenter(Vector2 v1, Vector2 v2, Vector2 v3) { Vector2 result = { 0.0f, 0.0f }; @@ -1914,11 +1832,10 @@ static Vector2 TriangleBarycenter(Vector2 v1, Vector2 v2, Vector2 v3) return result; } +#if !defined(PHYSAC_AVOID_TIMMING_SYSTEM) // Initializes hi-resolution MONOTONIC timer static void InitTimer(void) { - srand(time(NULL)); // Initialize random seed - #if defined(_WIN32) QueryPerformanceFrequency((unsigned long long int *) &frequency); #endif @@ -1934,12 +1851,12 @@ static void InitTimer(void) frequency = (timebase.denom*1e9)/timebase.numer; #endif - baseTime = GetTimeCount(); // Get MONOTONIC clock time offset - startTime = GetCurrentTime(); // Get current time + baseClockTicks = GetClockTicks(); // Get MONOTONIC clock time offset + startTime = GetCurrentTime(); // Get current time in milliseconds } -// Get hi-res MONOTONIC time measure in seconds -static unsigned long long int GetTimeCount(void) +// Get hi-res MONOTONIC time measure in clock ticks +static unsigned long long int GetClockTicks(void) { unsigned long long int value = 0; @@ -1963,42 +1880,45 @@ static unsigned long long int GetTimeCount(void) // Get current time in milliseconds static double GetCurrentTime(void) { - return (double)(GetTimeCount() - baseTime)/frequency*1000; + return (double)(GetClockTicks() - baseClockTicks)/frequency*1000; } +#endif // !PHYSAC_AVOID_TIMMING_SYSTEM + // Returns the cross product of a vector and a value -static inline Vector2 MathCross(float value, Vector2 vector) +static inline Vector2 MathVector2Product(Vector2 vector, float value) { - return (Vector2){ -value*vector.y, value*vector.x }; + Vector2 result = { -value*vector.y, value*vector.x }; + return result; } // Returns the cross product of two vectors -static inline float MathCrossVector2(Vector2 v1, Vector2 v2) +static inline float MathVector2CrossProduct(Vector2 v1, Vector2 v2) { return (v1.x*v2.y - v1.y*v2.x); } // Returns the len square root of a vector -static inline float MathLenSqr(Vector2 vector) +static inline float MathVector2SqrLen(Vector2 vector) { return (vector.x*vector.x + vector.y*vector.y); } // Returns the dot product of two vectors -static inline float MathDot(Vector2 v1, Vector2 v2) +static inline float MathVector2DotProduct(Vector2 v1, Vector2 v2) { return (v1.x*v2.x + v1.y*v2.y); } // Returns the square root of distance between two vectors -static inline float DistSqr(Vector2 v1, Vector2 v2) +static inline float MathVector2SqrDistance(Vector2 v1, Vector2 v2) { - Vector2 dir = Vector2Subtract(v1, v2); - return MathDot(dir, dir); + Vector2 dir = MathVector2Subtract(v1, v2); + return MathVector2DotProduct(dir, dir); } // Returns the normalized values of a vector -static void MathNormalize(Vector2 *vector) +static void MathVector2Normalize(Vector2 *vector) { float length, ilength; @@ -2013,51 +1933,42 @@ static void MathNormalize(Vector2 *vector) vector->y *= ilength; } -#if defined(PHYSAC_STANDALONE) // Returns the sum of two given vectors -static inline Vector2 Vector2Add(Vector2 v1, Vector2 v2) +static inline Vector2 MathVector2Add(Vector2 v1, Vector2 v2) { - return (Vector2){ v1.x + v2.x, v1.y + v2.y }; + Vector2 result = { v1.x + v2.x, v1.y + v2.y }; + return result; } // Returns the subtract of two given vectors -static inline Vector2 Vector2Subtract(Vector2 v1, Vector2 v2) +static inline Vector2 MathVector2Subtract(Vector2 v1, Vector2 v2) { - return (Vector2){ v1.x - v2.x, v1.y - v2.y }; + Vector2 result = { v1.x - v2.x, v1.y - v2.y }; + return result; } -#endif // Creates a matrix 2x2 from a given radians value -static Matrix2x2 Mat2Radians(float radians) -{ - float c = cosf(radians); - float s = sinf(radians); - - return (Matrix2x2){ c, -s, s, c }; -} - -// Set values from radians to a created matrix 2x2 -static void Mat2Set(Matrix2x2 *matrix, float radians) +static Matrix2x2 MathMatFromRadians(float radians) { float cos = cosf(radians); float sin = sinf(radians); - matrix->m00 = cos; - matrix->m01 = -sin; - matrix->m10 = sin; - matrix->m11 = cos; + Matrix2x2 result = { cos, -sin, sin, cos }; + return result; } // Returns the transpose of a given matrix 2x2 -static inline Matrix2x2 Mat2Transpose(Matrix2x2 matrix) +static inline Matrix2x2 MathMatTranspose(Matrix2x2 matrix) { - return (Matrix2x2){ matrix.m00, matrix.m10, matrix.m01, matrix.m11 }; + Matrix2x2 result = { matrix.m00, matrix.m10, matrix.m01, matrix.m11 }; + return result; } // Multiplies a vector by a matrix 2x2 -static inline Vector2 Mat2MultiplyVector2(Matrix2x2 matrix, Vector2 vector) +static inline Vector2 MathMatVector2Product(Matrix2x2 matrix, Vector2 vector) { - return (Vector2){ matrix.m00*vector.x + matrix.m01*vector.y, matrix.m10*vector.x + matrix.m11*vector.y }; + Vector2 result = { matrix.m00*vector.x + matrix.m01*vector.y, matrix.m10*vector.x + matrix.m11*vector.y }; + return result; } #endif // PHYSAC_IMPLEMENTATION diff --git a/src/raylib.h b/src/raylib.h index 24992a4f6..d693f026b 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -113,7 +113,7 @@ #define RL_FREE(ptr) free(ptr) #endif -// NOTE: MSC C++ compiler does not support compound literals (C99 feature) +// NOTE: MSVC C++ compiler does not support compound literals (C99 feature) // Plain structures in C++ (without constructors) can be initialized from { } initializers. #if defined(__cplusplus) #define CLITERAL(type) type @@ -674,9 +674,9 @@ typedef enum { GAMEPAD_BUTTON_RIGHT_TRIGGER_2, // These are buttons in the center of the gamepad - GAMEPAD_BUTTON_MIDDLE_LEFT, //PS3 Select - GAMEPAD_BUTTON_MIDDLE, //PS Button/XBOX Button - GAMEPAD_BUTTON_MIDDLE_RIGHT, //PS3 Start + GAMEPAD_BUTTON_MIDDLE_LEFT, // PS3 Select + GAMEPAD_BUTTON_MIDDLE, // PS Button/XBOX Button + GAMEPAD_BUTTON_MIDDLE_RIGHT, // PS3 Start // These are the joystick press in buttons GAMEPAD_BUTTON_LEFT_THUMB, @@ -1035,6 +1035,7 @@ RLAPI bool IsGamepadButtonUp(int gamepad, int button); // Detect if a gam RLAPI int GetGamepadButtonPressed(void); // Get the last gamepad button pressed RLAPI int GetGamepadAxisCount(int gamepad); // Return gamepad axis count for a gamepad RLAPI float GetGamepadAxisMovement(int gamepad, int axis); // Return axis movement value for a gamepad axis +RLAPI int SetGamepadMappings(const char *mappings); // Set internal gamepad mappings (SDL_GameControllerDB) // Input-related functions: mouse RLAPI bool IsMouseButtonPressed(int button); // Detect if a mouse button has been pressed once @@ -1338,6 +1339,7 @@ RLAPI void UnloadModelKeepMeshes(Model model); // Mesh loading/unloading functions RLAPI Mesh *LoadMeshes(const char *fileName, int *meshCount); // Load meshes from model file +RLAPI void UploadMesh(Mesh *mesh); // Upload mesh vertex data to GPU (VRAM) RLAPI void UnloadMesh(Mesh mesh); // Unload mesh from memory (RAM and/or VRAM) RLAPI bool ExportMesh(Mesh mesh, const char *fileName); // Export mesh data to file, returns true on success diff --git a/src/rlgl.h b/src/rlgl.h index d8e3de9d6..11f511cca 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -840,7 +840,7 @@ typedef struct RenderBatch { float currentDepth; // Current depth value for next draw } RenderBatch; -#if defined(SUPPORT_VR_SIMULATOR) +#if defined(SUPPORT_VR_SIMULATOR) && !defined(RLGL_STANDALONE) // VR Stereo rendering configuration for simulator typedef struct VrStereoConfig { Shader distortionShader; // VR stereo rendering distortion shader diff --git a/templates/advance_game/Makefile b/templates/advance_game/Makefile index 7097e2c2c..65c14cdff 100644 --- a/templates/advance_game/Makefile +++ b/templates/advance_game/Makefile @@ -237,7 +237,7 @@ ifeq ($(PLATFORM),PLATFORM_WEB) # -O2 # optimization level 2, if used, also set --memory-init-file 0 # -s USE_GLFW=3 # Use glfw3 library (context/input management) # -s ALLOW_MEMORY_GROWTH=1 # to allow memory resizing -> WARNING: Audio buffers could FAIL! - # -s TOTAL_MEMORY=16777216 # to specify heap memory size (default = 16MB) + # -s TOTAL_MEMORY=16777216 # to specify heap memory size (default = 16MB) (67108864 = 64MB) # -s USE_PTHREADS=1 # multithreading support # -s WASM=0 # disable Web Assembly, emitted by default # -s ASYNCIFY # lets synchronous C/C++ code interact with asynchronous JS