diff --git a/.gitignore b/.gitignore index 5666a7c..df84571 100644 --- a/.gitignore +++ b/.gitignore @@ -291,3 +291,6 @@ __pycache__/ *.odx.cs *.xsd.cs .DS_Store + +# CMake output +cmake-build-debug/ \ No newline at end of file diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..f2714ec --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "game/src/libs/raylib"] + path = game/src/libs/raylib + url = https://github.com/alexBraidwood/raylib diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..b9d1d66 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.8) +project(ludum-dare-40) + +find_package(glfw3 REQUIRED) +find_package(OpenAL REQUIRED) + +set(CMAKE_C_STANDARD 11) +set(CMAKE_CXX_STANDARD 14) + +add_subdirectory(game/src/libs/raylib) + +add_executable(ludum-dare-40 "") +target_link_libraries(ludum-dare-40 PRIVATE raylib) +target_include_directories(ludum-dare-40 PUBLIC game/src/include) +target_sources(ludum-dare-40 PRIVATE + # sources + game/src/collision.c + game/src/levelgen.c + game/src/main.c + + # headers + game/src/entity.h + game/src/hashset.h + game/src/item.h + game/src/main.h + game/src/vector2i.h) \ No newline at end of file diff --git a/README.md b/README.md index 6e355ed..fd5f1b5 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,9 @@ Project uses following libraries: - Build Script: build-win32.bat #### Linux/Mac -TODO(nick) +- Compiler: GCC >= 5.0 or Clang >= 3.4 +- CMake version >= 3.8 +- Building from cloned directory: `mkdir build && cd build && cmake .. && make` #### Web - SDK: emcscriptensdk diff --git a/game/src/libs/raylib b/game/src/libs/raylib new file mode 160000 index 0000000..401a8f5 --- /dev/null +++ b/game/src/libs/raylib @@ -0,0 +1 @@ +Subproject commit 401a8f5ac2573640615dc96015c0e3be65160df7 diff --git a/game/src/libs/raylib/Makefile b/game/src/libs/raylib/Makefile deleted file mode 100644 index 13be784..0000000 --- a/game/src/libs/raylib/Makefile +++ /dev/null @@ -1,443 +0,0 @@ -#****************************************************************************** -# -# raylib makefile -# -# Platforms supported: -# PLATFORM_DESKTOP: Windows (win32/Win64) -# PLATFORM_DESKTOP: Linux -# PLATFORM_DESKTOP: OSX (Mac) -# PLATFORM_ANDROID: Android (ARM or ARM64) -# PLATFORM_RPI: Raspberry Pi (Raspbian) -# PLATFORM_WEB: HTML5 (Chrome, Firefox) -# -# Many thanks to Milan Nikolic (@gen2brain) for implementing Android platform pipeline. -# Many thanks to Emanuele Petriglia for his contribution on GNU/Linux pipeline. -# -# Copyright (c) 2014-2017 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. -# -# Permission is granted to anyone to use this software for any purpose, -# including commercial applications, and to alter it and redistribute it -# freely, subject to the following restrictions: -# -# 1. The origin of this software must not be misrepresented; you must not -# claim that you wrote the original software. If you use this software in a -# product, an acknowledgment in the product documentation would be -# appreciated but is not required. -# -# 2. Altered source versions must be plainly marked as such, and must not -# be misrepresented as being the original software. -# -# 3. This notice may not be removed or altered from any source distribution. -# -#****************************************************************************** - -# Please read the wiki to know how to compile raylib, because there are -# different methods. - -.PHONY: all clean install uninstall - -# Define required raylib variables -PLATFORM ?= PLATFORM_DESKTOP -RAYLIB_PATH ?= .. - -# Library type used for raylib and OpenAL Soft: STATIC (.a) or SHARED (.so/.dll) -# NOTE: OpenAL Soft library should be provided in the selected form -RAYLIB_LIBTYPE ?= STATIC -OPENAL_LIBTYPE ?= STATIC - -# On PLATFORM_WEB force OpenAL Soft shared library -ifeq ($(PLATFORM),PLATFORM_WEB) - OPENAL_LIBTYPE = SHARED -endif - -# Use cross-compiler for PLATFORM_RPI -ifeq ($(PLATFORM),PLATFORM_RPI) - RPI_CROSS_COMPILE ?= YES - RPI_TOOLCHAIN ?= C:/SysGCC/Raspberry - RPI_TOOLCHAIN_SYSROOT ?= $(RPI_TOOLCHAIN)/arm-linux-gnueabihf/sysroot -endif - -# Determine if the file has root access (only for installing raylib) -# "whoami" prints the name of the user that calls him (so, if it is the root -# user, "whoami" prints "root"). -ROOT = $(shell whoami) - -# Determine PLATFORM_OS in case PLATFORM_DESKTOP selected -ifeq ($(PLATFORM),PLATFORM_DESKTOP) - # No uname.exe on MinGW!, but OS=Windows_NT on Windows! - # ifeq ($(UNAME),Msys) -> Windows - ifeq ($(OS),Windows_NT) - PLATFORM_OS=WINDOWS - else - UNAMEOS=$(shell uname) - ifeq ($(UNAMEOS),Linux) - PLATFORM_OS=LINUX - else - ifeq ($(UNAMEOS),Darwin) - PLATFORM_OS=OSX - endif - endif - endif -endif - -ifeq ($(PLATFORM),PLATFORM_WEB) - # Emscripten required variables - EMSDK_PATH = C:/emsdk - EMSCRIPTEN_VERSION = 1.37.21 - CLANG_VERSION=e1.37.21_64bit - PYTHON_VERSION=2.7.5.3_64bit - NODE_VERSION=4.1.1_64bit - export PATH=$(EMSDK_PATH);$(EMSDK_PATH)\clang\$(CLANG_VERSION);$(EMSDK_PATH)\node\$(NODE_VERSION)\bin;$(EMSDK_PATH)\python\$(PYTHON_VERSION);$(EMSDK_PATH)\emscripten\$(EMSCRIPTEN_VERSION);C:\raylib\MinGW\bin:$$(PATH) - EMSCRIPTEN=$(EMSDK_PATH)\emscripten\$(EMSCRIPTEN_VERSION) -endif - -ifeq ($(PLATFORM),PLATFORM_ANDROID) - # Android required path variables - ANDROID_NDK = C:/android-ndk - ANDROID_TOOLCHAIN = C:/android_toolchain_arm_api16 - - # Android architecture: ARM or ARM64 - ANDROID_ARCH ?= ARM -endif - -RAYLIB_RELEASE_PATH ?= $(RAYLIB_PATH)/release/libs - -# Define output directory for compiled library -ifeq ($(PLATFORM),PLATFORM_DESKTOP) - ifeq ($(PLATFORM_OS),WINDOWS) - RAYLIB_RELEASE_PATH = $(RAYLIB_PATH)/release/libs/win32/mingw32 - endif - ifeq ($(PLATFORM_OS),LINUX) - RAYLIB_RELEASE_PATH = $(RAYLIB_PATH)/release/libs/linux - endif - ifeq ($(PLATFORM_OS),OSX) - RAYLIB_RELEASE_PATH = $(RAYLIB_PATH)/release/libs/osx - endif -endif -ifeq ($(PLATFORM),PLATFORM_RPI) - RAYLIB_RELEASE_PATH = $(RAYLIB_PATH)/release/libs/rpi -endif -ifeq ($(PLATFORM),PLATFORM_WEB) - RAYLIB_RELEASE_PATH = $(RAYLIB_PATH)/release/libs/html5 -endif -ifeq ($(PLATFORM),PLATFORM_ANDROID) - ifeq ($(ANDROID_ARCH),ARM) - RAYLIB_RELEASE_PATH = $(RAYLIB_PATH)/release/libs/android/armeabi-v7a - endif - ifeq ($(ANDROID_ARCH),ARM64) - RAYLIB_RELEASE_PATH = $(RAYLIB_PATH)/release/libs/android/arm64-v8a - endif -endif - -# Define raylib graphics api depending on selected platform -ifeq ($(PLATFORM),PLATFORM_DESKTOP) - # By default use OpenGL 3.3 on desktop platforms - GRAPHICS ?= GRAPHICS_API_OPENGL_33 - #GRAPHICS = GRAPHICS_API_OPENGL_11 # Uncomment to use OpenGL 1.1 - #GRAPHICS = GRAPHICS_API_OPENGL_21 # Uncomment to use OpenGL 2.1 -endif - -ifeq ($(PLATFORM),PLATFORM_RPI) - # On RPI OpenGL ES 2.0 must be used - GRAPHICS = GRAPHICS_API_OPENGL_ES2 -endif - -ifeq ($(PLATFORM),PLATFORM_WEB) - # On HTML5 OpenGL ES 2.0 is used, emscripten translates it to WebGL 1.0 - GRAPHICS = GRAPHICS_API_OPENGL_ES2 -endif - -ifeq ($(PLATFORM),PLATFORM_ANDROID) - # By default use OpenGL ES 2.0 on Android - GRAPHICS = GRAPHICS_API_OPENGL_ES2 -endif - -# Default C compiler: gcc -# NOTE: define g++ compiler if using C++ -CC = gcc - -ifeq ($(PLATFORM),PLATFORM_DESKTOP) - ifeq ($(PLATFORM_OS),OSX) - # OSX default compiler - CC = clang - endif -endif -ifeq ($(PLATFORM),PLATFORM_RPI) - ifeq ($(RPI_CROSS_COMPILE),YES) - # Define RPI cross-compiler - #CC = armv6j-hardfloat-linux-gnueabi-gcc - CC = $(RPI_TOOLCHAIN)/bin/arm-linux-gnueabihf-gcc - endif -endif -ifeq ($(PLATFORM),PLATFORM_WEB) - # HTML5 emscripten compiler - CC = emcc -endif -ifeq ($(PLATFORM),PLATFORM_ANDROID) - # Android toolchain (must be provided for desired architecture and compiler) - # NOTE: gcc compiler is being deprecated in Android NDK r16 - ifeq ($(ANDROID_ARCH),ARM) - CC = $(ANDROID_TOOLCHAIN)/bin/arm-linux-androideabi-gcc - endif - ifeq ($(ANDROID_ARCH),ARM64) - CC = $(ANDROID_TOOLCHAIN)/bin/aarch64-linux-android-gcc - endif -endif - -# Default archiver program to pack libraries -AR = ar - -ifeq ($(PLATFORM),PLATFORM_RPI) - ifeq ($(RPI_CROSS_COMPILE),YES) - # Define RPI cross-archiver - #CC = armv6j-hardfloat-linux-gnueabi-gcc - AR = $(RPI_TOOLCHAIN)/bin/arm-linux-gnueabihf-ar - endif -endif - -# Android archiver (also depends on desired architecture) -ifeq ($(PLATFORM),PLATFORM_ANDROID) - ifeq ($(ANDROID_ARCH),ARM) - AR = $(ANDROID_TOOLCHAIN)/bin/arm-linux-androideabi-ar - endif - ifeq ($(ANDROID_ARCH),ARM64) - AR = $(ANDROID_TOOLCHAIN)/bin/aarch64-linux-android-ar - endif -endif - -# Define compiler flags: -# -O1 defines optimization level -# -Og enable debugging -# -s strip unnecessary data from build -# -Wall turns on most, but not all, compiler warnings -# -std=c99 defines C language mode (standard C from 1999 revision) -# -std=gnu99 defines C language mode (GNU C from 1999 revision) -# -fgnu89-inline declaring inline functions support (GCC optimized) -# -Wno-missing-braces ignore invalid warning (GCC bug 53119) -# -D_DEFAULT_SOURCE use with -std=c99 -CFLAGS += -O1 -Wall -std=c99 -D_DEFAULT_SOURCE -fgnu89-inline -Wno-missing-braces - -# Additional flags for compiler (if desired) -#CFLAGS += -Wextra -Wmissing-prototypes -Wstrict-prototypes -ifeq ($(PLATFORM),PLATFORM_WEB) - # -O2 # if used, also set --memory-init-file 0 - # --memory-init-file 0 # to avoid an external memory initialization code file (.mem) - # -s ALLOW_MEMORY_GROWTH=1 # to allow memory resizing - # -s TOTAL_MEMORY=16777216 # to specify heap memory size (default = 16MB) - # -s USE_PTHREADS=1 # multithreading support - CFLAGS += -s USE_GLFW=3 -s ASSERTIONS=1 --profiling -endif -ifeq ($(PLATFORM),PLATFORM_ANDROID) - # Compiler flags for arquitecture - CFLAGS += -march=armv7-a -mfloat-abi=softfp -mfpu=vfpv3-d16 - # Compilation functions attributes options - CFLAGS += -ffunction-sections -funwind-tables -fstack-protector-strong -fPIC - # Compiler options for the linker - CFLAGS += -Wa,--noexecstack -Wformat -Werror=format-security -no-canonical-prefixes - # Preprocessor macro definitions - CFLAGS += -DANDROID -DPLATFORM_ANDROID -D__ANDROID_API__=16 -endif - -# Define required compilation flags for raylib SHARED lib -ifeq ($(RAYLIB_LIBTYPE),SHARED) - # make sure code is compiled as position independent - # BE CAREFUL: It seems that for gcc -fpic si not the same as -fPIC - # MinGW32 just doesn't need -fPIC, it shows warnings - CFLAGS += -fPIC -DBUILD_LIBTYPE_SHARED -endif - -# Define required compilation flags for OpenAL Soft STATIC lib -ifeq ($(OPENAL_LIBTYPE),STATIC) - ALFLAGS = -DAL_LIBTYPE_STATIC -Wl,-allow-multiple-definition -endif - -# Define include paths for required headers -# NOTE: Several external required libraries (stb and others) -INCLUDE_PATHS = -I. -Iexternal -Iexternal/include - -# Define additional directories containing required header files -ifeq ($(PLATFORM),PLATFORM_RPI) - # RPI requried libraries - INCLUDE_PATHS += -I$(RPI_TOOLCHAIN_SYSROOT)/opt/vc/include - INCLUDE_PATHS += -I$(RPI_TOOLCHAIN_SYSROOT)/opt/vc/include/interface/vmcs_host/linux - INCLUDE_PATHS += -I$(RPI_TOOLCHAIN_SYSROOT)/opt/vc/include/interface/vcos/pthreads - INCLUDE_PATHS += -I$(RPI_TOOLCHAIN_SYSROOT)/opt/vc/include/interface/vcos/pthreads -endif -ifeq ($(PLATFORM),PLATFORM_ANDROID) - # Android required libraries - INCLUDE_PATHS += -I$(ANDROID_TOOLCHAIN)/sysroot/usr/include - # Include android_native_app_glue.h - INCLUDE_PATHS += -Iexternal/android/native_app_glue - #INCLUDE_PATHS += -I$(ANDROID_NDK)/sources/android/native_app_glue -endif - -# Define linker options -ifeq ($(PLATFORM),PLATFORM_ANDROID) - LDFLAGS = -Wl,-soname,libraylib.so -Wl,--exclude-libs,libatomic.a - LDFLAGS += -Wl,--build-id -Wl,--no-undefined -Wl,-z,noexecstack -Wl,-z,relro -Wl,-z,now -Wl,--warn-shared-textrel -Wl,--fatal-warnings - # Force linking of library module to define symbol - LDFLAGS += -u ANativeActivity_onCreate - # Library paths containing required libs - LDFLAGS += -L. -Lsrc -L$(RAYLIB_RELEASE_PATH) - - LDLIBS = -lopenal -llog -landroid -lEGL -lGLESv2 -lOpenSLES -latomic -lc -lm -endif - -# Define all object files required with a wildcard -# The wildcard takes all files that finish with ".c", -# and replaces extentions with ".o", that are the object files -OBJS = $(patsubst %.c, %.o, $(wildcard *.c)) -OBJS += stb_vorbis.o - -# Default target entry -all: raylib - -# Generate standalone Android toolchain -# NOTE: Android toolchain could already be provided -generate_android_toolchain: -ifeq ($(PLATFORM),PLATFORM_ANDROID) - ifeq ($(ANDROID_ARCH),ARM) - $(ANDROID_NDK)/build/tools/make-standalone-toolchain.sh --platform=android-9 --toolchain=arm-linux-androideabi-4.9 --use-llvm --install-dir=$(ANDROID_TOOLCHAIN) - endif - ifeq ($(ANDROID_ARCH),ARM64) - $(ANDROID_NDK)/build/tools/make-standalone-toolchain.sh --platform=android-21 --toolchain=aarch64-linux-androideabi-4.9 --use-llvm --install-dir=$(ANDROID_TOOLCHAIN) - endif -endif - -# Compile raylib library -raylib: $(OBJS) -ifeq ($(PLATFORM),PLATFORM_WEB) - # Compile raylib for web. - emcc -O1 $(OBJS) -o $(RAYLIB_RELEASE_PATH)/libraylib.bc - @echo "raylib library generated (libraylib.bc)!" -else - ifeq ($(RAYLIB_LIBTYPE),SHARED) - # NOTE: If using OpenAL Soft as static library, all its dependencies must be also linked in the shared library - ifeq ($(PLATFORM_OS),WINDOWS) - $(CC) -shared -o $(RAYLIB_RELEASE_PATH)/raylib.dll $(OBJS) -L$(RAYLIB_RELEASE_PATH) -lglfw3 -lgdi32 -lopenal32 -lwinmm -Wl,--out-implib,$(RAYLIB_RELEASE_PATH)/libraylibdll.a - @echo "raylib dynamic library (raylib.dll) and import library (libraylibdll.a) generated!" - @echo "expected OpenAL Soft static library linking" - endif - ifeq ($(PLATFORM_OS),LINUX) - # Compile raylib to shared library version for GNU/Linux. - # WARNING: you should type "make clean" before doing this target - $(CC) -shared -o $(RAYLIB_RELEASE_PATH)/libraylib.so $(OBJS) -lglfw -lGL -lopenal -lm -lpthread -ldl - @echo "raylib shared library generated (libraylib.so)!" - endif - ifeq ($(PLATFORM_OS),OSX) - $(CC) -dynamiclib -o $(RAYLIB_RELEASE_PATH)/libraylib.dylib $(OBJS) -L/usr/local/Cellar/glfw/3.2.1/lib -lglfw -framework OpenGL -framework OpenAL -framework Cocoa - install_name_tool -id "libraylib.dylib" $(RAYLIB_RELEASE_PATH)/libraylib.dylib - @echo "raylib shared library generated (libraylib.dylib)!" - endif - ifeq ($(PLATFORM),PLATFORM_ANDROID) - $(CC) -shared -o $(RAYLIB_RELEASE_PATH)/libraylib.so $(OBJS) $(LDFLAGS) $(LDLIBS) - @echo "raylib shared library generated (libraylib.so)!" - endif - else - # Compile raylib static library - @echo raylib library release path is $(RAYLIB_RELEASE_PATH) - $(AR) rcs $(RAYLIB_RELEASE_PATH)/libraylib.a $(OBJS) - @echo "raylib static library generated (libraylib.a)!" - ifeq ($(OPENAL_LIBTYPE),STATIC) - @echo "expected OpenAL Soft static library linking" - else - @echo "expected OpenAL Soft shared library linking" - endif - endif -endif - -# Compile all modules with their prerequisites - -# Compile core module -core.o : core.c raylib.h rlgl.h utils.h raymath.h gestures.h - $(CC) -c $< $(CFLAGS) $(INCLUDE_PATHS) -D$(PLATFORM) -D$(GRAPHICS) - -# Compile rlgl module -rlgl.o : rlgl.c rlgl.h raymath.h - $(CC) -c $< $(CFLAGS) $(INCLUDE_PATHS) -D$(PLATFORM) -D$(GRAPHICS) - -# Compile shapes module -shapes.o : shapes.c raylib.h rlgl.h - $(CC) -c $< $(CFLAGS) $(INCLUDE_PATHS) -D$(PLATFORM) -D$(GRAPHICS) - -# Compile textures module -textures.o : textures.c rlgl.h utils.h - $(CC) -c $< $(CFLAGS) $(INCLUDE_PATHS) -D$(PLATFORM) -D$(GRAPHICS) - -# Compile text module -text.o : text.c raylib.h utils.h - $(CC) -c $< $(CFLAGS) $(INCLUDE_PATHS) -D$(PLATFORM) -D$(GRAPHICS) - -# Compile models module -models.o : models.c raylib.h rlgl.h raymath.h - $(CC) -c $< $(CFLAGS) $(INCLUDE_PATHS) -D$(PLATFORM) -D$(GRAPHICS) - -# Compile audio module -audio.o : audio.c raylib.h - $(CC) -c $< $(CFLAGS) $(INCLUDE_PATHS) -D$(PLATFORM) $(ALFLAGS) - -# Compile stb_vorbis library -stb_vorbis.o: external/stb_vorbis.c external/stb_vorbis.h - $(CC) -c $< $(CFLAGS) $(INCLUDE_PATHS) -D$(PLATFORM) - -# Compile utils module -utils.o : utils.c utils.h - $(CC) -c $< $(CFLAGS) $(INCLUDE_PATHS) -D$(PLATFORM) - -# Install generated and needed files to required directories -# TODO: add other platforms. -install : -ifeq ($(ROOT),root) - ifeq ($(PLATFORM_OS),LINUX) - # On GNU/Linux there are some standard directories that contain - # libraries and header files. These directory (/usr/local/lib and - # /usr/local/include/) are for libraries that are installed - # manually (without a package manager). - ifeq ($(RAYLIB_LIBTYPE),SHARED) - cp --update $(RAYLIB_RELEASE_PATH)/libraylib.so /usr/local/lib/libraylib.so - else - cp --update raylib.h /usr/local/include/raylib.h - cp --update $(RAYLIB_RELEASE_PATH)/libraylib.a /usr/local/lib/libraylib.a - endif - @echo "raylib dev files installed/updated!" - else - @echo "This function works only on GNU/Linux systems" - endif -else - @echo "Error: no root permissions" -endif - -# Remove raylib dev files installed on the system -# TODO: see 'install' target. -uninstall : -ifeq ($(ROOT),root) - ifeq ($(PLATFORM_OS),LINUX) - rm --force /usr/local/include/raylib.h - ifeq ($(RAYLIB_LIBTYPE),SHARED) - rm --force /usr/local/lib/libraylib.so - else - rm --force /usr/local/lib/libraylib.a - endif - @echo "raylib development files removed!" - else - @echo "This function works only on GNU/Linux systems" - endif -else - @echo "Error: no root permissions" -endif - -# Clean everything -clean: -ifeq ($(PLATFORM_OS),WINDOWS) - del *.o $(RAYLIB_RELEASE_PATH)/libraylib.a $(RAYLIB_RELEASE_PATH)/libraylib.bc $(RAYLIB_RELEASE_PATH)/libraylib.so external/stb_vorbis.o -else - rm -f *.o $(RAYLIB_RELEASE_PATH)/libraylib.a $(RAYLIB_RELEASE_PATH)/libraylib.bc $(RAYLIB_RELEASE_PATH)/libraylib.so external/stb_vorbis.o -endif -ifeq ($(PLATFORM),PLATFORM_ANDROID) - rm -rf $(ANDROID_TOOLCHAIN) -endif - @echo "removed all generated files!" diff --git a/game/src/libs/raylib/audio.c b/game/src/libs/raylib/audio.c deleted file mode 100644 index 06af8ed..0000000 --- a/game/src/libs/raylib/audio.c +++ /dev/null @@ -1,1353 +0,0 @@ -/********************************************************************************************** -* -* raylib.audio - Basic funtionality to work with audio -* -* FEATURES: -* - Manage audio device (init/close) -* - Load and unload audio files -* - Format wave data (sample rate, size, channels) -* - Play/Stop/Pause/Resume loaded audio -* - Manage mixing channels -* - Manage raw audio context -* -* CONFIGURATION: -* -* #define AUDIO_STANDALONE -* Define to use the module as standalone library (independently of raylib). -* Required types and functions are defined in the same module. -* -* #define SUPPORT_FILEFORMAT_WAV -* #define SUPPORT_FILEFORMAT_OGG -* #define SUPPORT_FILEFORMAT_XM -* #define SUPPORT_FILEFORMAT_MOD -* #define SUPPORT_FILEFORMAT_FLAC -* Selected desired fileformats to be supported for loading. Some of those formats are -* supported by default, to remove support, just comment unrequired #define in this module -* -* LIMITATIONS: -* Only up to two channels supported: MONO and STEREO (for additional channels, use AL_EXT_MCFORMATS) -* Only the following sample sizes supported: 8bit PCM, 16bit PCM, 32-bit float PCM (using AL_EXT_FLOAT32) -* -* DEPENDENCIES: -* OpenAL Soft - Audio device management (http://kcat.strangesoft.net/openal.html) -* stb_vorbis - OGG audio files loading (http://www.nothings.org/stb_vorbis/) -* jar_xm - XM module file loading -* jar_mod - MOD audio file loading -* dr_flac - FLAC audio file loading -* -* CONTRIBUTORS: -* Joshua Reisenauer (github: @kd7tck): -* - XM audio module support (jar_xm) -* - MOD audio module support (jar_mod) -* - Mixing channels support -* - Raw audio context support -* -* -* LICENSE: zlib/libpng -* -* Copyright (c) 2014-2017 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. -* -* Permission is granted to anyone to use this software for any purpose, including commercial -* applications, and to alter it and redistribute it freely, subject to the following restrictions: -* -* 1. The origin of this software must not be misrepresented; you must not claim that you -* wrote the original software. If you use this software in a product, an acknowledgment -* in the product documentation would be appreciated but is not required. -* -* 2. Altered source versions must be plainly marked as such, and must not be misrepresented -* as being the original software. -* -* 3. This notice may not be removed or altered from any source distribution. -* -**********************************************************************************************/ - -// Default configuration flags (supported features) -//------------------------------------------------- -#define SUPPORT_FILEFORMAT_WAV -#define SUPPORT_FILEFORMAT_OGG -#define SUPPORT_FILEFORMAT_XM -#define SUPPORT_FILEFORMAT_MOD -//------------------------------------------------- - -#if defined(AUDIO_STANDALONE) - #include "audio.h" - #include // Required for: va_list, va_start(), vfprintf(), va_end() -#else - #include "raylib.h" - #include "utils.h" // Required for: fopen() Android mapping -#endif - -#if defined(__APPLE__) - #include "OpenAL/al.h" // OpenAL basic header - #include "OpenAL/alc.h" // OpenAL context header (like OpenGL, OpenAL requires a context to work) -#else - #include "AL/al.h" // OpenAL basic header - #include "AL/alc.h" // OpenAL context header (like OpenGL, OpenAL requires a context to work) - //#include "AL/alext.h" // OpenAL extensions header, required for AL_EXT_FLOAT32 and AL_EXT_MCFORMATS -#endif - -// OpenAL extension: AL_EXT_FLOAT32 - Support for 32bit float samples -// OpenAL extension: AL_EXT_MCFORMATS - Support for multi-channel formats (Quad, 5.1, 6.1, 7.1) - -#include // Required for: malloc(), free() -#include // Required for: strcmp(), strncmp() -#include // Required for: FILE, fopen(), fclose(), fread() - -#if defined(SUPPORT_FILEFORMAT_OGG) - //#define STB_VORBIS_HEADER_ONLY - #include "external/stb_vorbis.h" // OGG loading functions -#endif - -#if defined(SUPPORT_FILEFORMAT_XM) - #define JAR_XM_IMPLEMENTATION - #include "external/jar_xm.h" // XM loading functions -#endif - -#if defined(SUPPORT_FILEFORMAT_MOD) - #define JAR_MOD_IMPLEMENTATION - #include "external/jar_mod.h" // MOD loading functions -#endif - -#if defined(SUPPORT_FILEFORMAT_FLAC) - #define DR_FLAC_IMPLEMENTATION - #define DR_FLAC_NO_WIN32_IO - #include "external/dr_flac.h" // FLAC loading functions -#endif - -#ifdef _MSC_VER - #undef bool -#endif - -//---------------------------------------------------------------------------------- -// Defines and Macros -//---------------------------------------------------------------------------------- -#define MAX_STREAM_BUFFERS 2 // Number of buffers for each audio stream - -// NOTE: Music buffer size is defined by number of samples, independent of sample size and channels number -// After some math, considering a sampleRate of 48000, a buffer refill rate of 1/60 seconds -// and double-buffering system, I concluded that a 4096 samples buffer should be enough -// In case of music-stalls, just increase this number -#define AUDIO_BUFFER_SIZE 4096 // PCM data samples (i.e. 16bit, Mono: 8Kb) - -// Support uncompressed PCM data in 32-bit float IEEE format -// NOTE: This definition is included in "AL/alext.h", but some OpenAL implementations -// could not provide the extensions header (Android), so its defined here -#if !defined(AL_EXT_float32) - #define AL_EXT_float32 1 - #define AL_FORMAT_MONO_FLOAT32 0x10010 - #define AL_FORMAT_STEREO_FLOAT32 0x10011 -#endif - -//---------------------------------------------------------------------------------- -// Types and Structures Definition -//---------------------------------------------------------------------------------- - -typedef enum { MUSIC_AUDIO_OGG = 0, MUSIC_AUDIO_FLAC, MUSIC_MODULE_XM, MUSIC_MODULE_MOD } MusicContextType; - -// Music type (file streaming from memory) -typedef struct MusicData { - MusicContextType ctxType; // Type of music context (OGG, XM, MOD) -#if defined(SUPPORT_FILEFORMAT_OGG) - stb_vorbis *ctxOgg; // OGG audio context -#endif -#if defined(SUPPORT_FILEFORMAT_FLAC) - drflac *ctxFlac; // FLAC audio context -#endif -#if defined(SUPPORT_FILEFORMAT_XM) - jar_xm_context_t *ctxXm; // XM chiptune context -#endif -#if defined(SUPPORT_FILEFORMAT_MOD) - jar_mod_context_t ctxMod; // MOD chiptune context -#endif - - AudioStream stream; // Audio stream (double buffering) - - int loopCount; // Loops count (times music repeats), -1 means infinite loop - unsigned int totalSamples; // Total number of samples - unsigned int samplesLeft; // Number of samples left to end -} MusicData; - -#if defined(AUDIO_STANDALONE) -typedef enum { LOG_INFO = 0, LOG_ERROR, LOG_WARNING, LOG_DEBUG, LOG_OTHER } TraceLogType; -#endif - -//---------------------------------------------------------------------------------- -// Global Variables Definition -//---------------------------------------------------------------------------------- -// ... - -//---------------------------------------------------------------------------------- -// Module specific Functions Declaration -//---------------------------------------------------------------------------------- -#if defined(SUPPORT_FILEFORMAT_WAV) -static Wave LoadWAV(const char *fileName); // Load WAV file -#endif -#if defined(SUPPORT_FILEFORMAT_OGG) -static Wave LoadOGG(const char *fileName); // Load OGG file -#endif -#if defined(SUPPORT_FILEFORMAT_FLAC) -static Wave LoadFLAC(const char *fileName); // Load FLAC file -#endif - -#if defined(AUDIO_STANDALONE) -bool IsFileExtension(const char *fileName, const char *ext); // Check file extension -void TraceLog(int msgType, const char *text, ...); // Show trace log messages (LOG_INFO, LOG_WARNING, LOG_ERROR, LOG_DEBUG) -#endif - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Audio Device initialization and Closing -//---------------------------------------------------------------------------------- - -// Initialize audio device -void InitAudioDevice(void) -{ - // Open and initialize a device with default settings - ALCdevice *device = alcOpenDevice(NULL); - - if (!device) TraceLog(LOG_ERROR, "Audio device could not be opened"); - else - { - ALCcontext *context = alcCreateContext(device, NULL); - - if ((context == NULL) || (alcMakeContextCurrent(context) == ALC_FALSE)) - { - if (context != NULL) alcDestroyContext(context); - - alcCloseDevice(device); - - TraceLog(LOG_ERROR, "Could not initialize audio context"); - } - else - { - TraceLog(LOG_INFO, "Audio device and context initialized successfully: %s", alcGetString(device, ALC_DEVICE_SPECIFIER)); - - // Listener definition (just for 2D) - alListener3f(AL_POSITION, 0.0f, 0.0f, 0.0f); - alListener3f(AL_VELOCITY, 0.0f, 0.0f, 0.0f); - alListener3f(AL_ORIENTATION, 0.0f, 0.0f, -1.0f); - - alListenerf(AL_GAIN, 1.0f); - } - } -} - -// Close the audio device for all contexts -void CloseAudioDevice(void) -{ - ALCdevice *device; - ALCcontext *context = alcGetCurrentContext(); - - if (context == NULL) TraceLog(LOG_WARNING, "Could not get current audio context for closing"); - - device = alcGetContextsDevice(context); - - alcMakeContextCurrent(NULL); - alcDestroyContext(context); - alcCloseDevice(device); - - TraceLog(LOG_INFO, "Audio device closed successfully"); -} - -// Check if device has been initialized successfully -bool IsAudioDeviceReady(void) -{ - ALCcontext *context = alcGetCurrentContext(); - - if (context == NULL) return false; - else - { - ALCdevice *device = alcGetContextsDevice(context); - - if (device == NULL) return false; - else return true; - } -} - -// Set master volume (listener) -void SetMasterVolume(float volume) -{ - if (volume < 0.0f) volume = 0.0f; - else if (volume > 1.0f) volume = 1.0f; - - alListenerf(AL_GAIN, volume); -} - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Sounds loading and playing (.WAV) -//---------------------------------------------------------------------------------- - -// Load wave data from file -Wave LoadWave(const char *fileName) -{ - Wave wave = { 0 }; - - if (IsFileExtension(fileName, ".wav")) wave = LoadWAV(fileName); -#if defined(SUPPORT_FILEFORMAT_OGG) - else if (IsFileExtension(fileName, ".ogg")) wave = LoadOGG(fileName); -#endif -#if defined(SUPPORT_FILEFORMAT_FLAC) - else if (IsFileExtension(fileName, ".flac")) wave = LoadFLAC(fileName); -#endif -#if !defined(AUDIO_STANDALONE) - else if (IsFileExtension(fileName, ".rres")) - { - RRES rres = LoadResource(fileName, 0); - - // NOTE: Parameters for RRES_TYPE_WAVE are: sampleCount, sampleRate, sampleSize, channels - - if (rres[0].type == RRES_TYPE_WAVE) wave = LoadWaveEx(rres[0].data, rres[0].param1, rres[0].param2, rres[0].param3, rres[0].param4); - else TraceLog(LOG_WARNING, "[%s] Resource file does not contain wave data", fileName); - - UnloadResource(rres); - } -#endif - else TraceLog(LOG_WARNING, "[%s] Audio fileformat not supported, it can't be loaded", fileName); - - return wave; -} - -// Load wave data from raw array data -Wave LoadWaveEx(void *data, int sampleCount, int sampleRate, int sampleSize, int channels) -{ - Wave wave; - - wave.data = data; - wave.sampleCount = sampleCount; - wave.sampleRate = sampleRate; - wave.sampleSize = sampleSize; - wave.channels = channels; - - // NOTE: Copy wave data to work with, user is responsible of input data to free - Wave cwave = WaveCopy(wave); - - WaveFormat(&cwave, sampleRate, sampleSize, channels); - - return cwave; -} - -// Load sound from file -// NOTE: The entire file is loaded to memory to be played (no-streaming) -Sound LoadSound(const char *fileName) -{ - Wave wave = LoadWave(fileName); - - Sound sound = LoadSoundFromWave(wave); - - UnloadWave(wave); // Sound is loaded, we can unload wave - - return sound; -} - -// Load sound from wave data -// NOTE: Wave data must be unallocated manually -Sound LoadSoundFromWave(Wave wave) -{ - Sound sound = { 0 }; - - if (wave.data != NULL) - { - ALenum format = 0; - - // The OpenAL format is worked out by looking at the number of channels and the sample size (bits per sample) - if (wave.channels == 1) - { - switch (wave.sampleSize) - { - case 8: format = AL_FORMAT_MONO8; break; - case 16: format = AL_FORMAT_MONO16; break; - case 32: format = AL_FORMAT_MONO_FLOAT32; break; // Requires OpenAL extension: AL_EXT_FLOAT32 - default: TraceLog(LOG_WARNING, "Wave sample size not supported: %i", wave.sampleSize); break; - } - } - else if (wave.channels == 2) - { - switch (wave.sampleSize) - { - case 8: format = AL_FORMAT_STEREO8; break; - case 16: format = AL_FORMAT_STEREO16; break; - case 32: format = AL_FORMAT_STEREO_FLOAT32; break; // Requires OpenAL extension: AL_EXT_FLOAT32 - default: TraceLog(LOG_WARNING, "Wave sample size not supported: %i", wave.sampleSize); break; - } - } - else TraceLog(LOG_WARNING, "Wave number of channels not supported: %i", wave.channels); - - // Create an audio source - ALuint source; - alGenSources(1, &source); // Generate pointer to audio source - - alSourcef(source, AL_PITCH, 1.0f); - alSourcef(source, AL_GAIN, 1.0f); - alSource3f(source, AL_POSITION, 0.0f, 0.0f, 0.0f); - alSource3f(source, AL_VELOCITY, 0.0f, 0.0f, 0.0f); - alSourcei(source, AL_LOOPING, AL_FALSE); - - // Convert loaded data to OpenAL buffer - //---------------------------------------- - ALuint buffer; - alGenBuffers(1, &buffer); // Generate pointer to buffer - - unsigned int dataSize = wave.sampleCount*wave.channels*wave.sampleSize/8; // Size in bytes - - // Upload sound data to buffer - alBufferData(buffer, format, wave.data, dataSize, wave.sampleRate); - - // Attach sound buffer to source - alSourcei(source, AL_BUFFER, buffer); - - TraceLog(LOG_INFO, "[SND ID %i][BUFR ID %i] Sound data loaded successfully (%i Hz, %i bit, %s)", source, buffer, wave.sampleRate, wave.sampleSize, (wave.channels == 1) ? "Mono" : "Stereo"); - - sound.source = source; - sound.buffer = buffer; - sound.format = format; - } - - return sound; -} - -// Unload wave data -void UnloadWave(Wave wave) -{ - if (wave.data != NULL) free(wave.data); - - TraceLog(LOG_INFO, "Unloaded wave data from RAM"); -} - -// Unload sound -void UnloadSound(Sound sound) -{ - alSourceStop(sound.source); - - alDeleteSources(1, &sound.source); - alDeleteBuffers(1, &sound.buffer); - - TraceLog(LOG_INFO, "[SND ID %i][BUFR ID %i] Unloaded sound data from RAM", sound.source, sound.buffer); -} - -// Update sound buffer with new data -// NOTE: data must match sound.format -void UpdateSound(Sound sound, const void *data, int samplesCount) -{ - ALint sampleRate, sampleSize, channels; - alGetBufferi(sound.buffer, AL_FREQUENCY, &sampleRate); - alGetBufferi(sound.buffer, AL_BITS, &sampleSize); // It could also be retrieved from sound.format - alGetBufferi(sound.buffer, AL_CHANNELS, &channels); // It could also be retrieved from sound.format - - TraceLog(LOG_DEBUG, "UpdateSound() : AL_FREQUENCY: %i", sampleRate); - TraceLog(LOG_DEBUG, "UpdateSound() : AL_BITS: %i", sampleSize); - TraceLog(LOG_DEBUG, "UpdateSound() : AL_CHANNELS: %i", channels); - - unsigned int dataSize = samplesCount*channels*sampleSize/8; // Size of data in bytes - - alSourceStop(sound.source); // Stop sound - alSourcei(sound.source, AL_BUFFER, 0); // Unbind buffer from sound to update - //alDeleteBuffers(1, &sound.buffer); // Delete current buffer data - //alGenBuffers(1, &sound.buffer); // Generate new buffer - - // Upload new data to sound buffer - alBufferData(sound.buffer, sound.format, data, dataSize, sampleRate); - - // Attach sound buffer to source again - alSourcei(sound.source, AL_BUFFER, sound.buffer); -} - -// Play a sound -void PlaySound(Sound sound) -{ - alSourcePlay(sound.source); // Play the sound - - //TraceLog(LOG_INFO, "Playing sound"); - - // Find the current position of the sound being played - // NOTE: Only work when the entire file is in a single buffer - //int byteOffset; - //alGetSourcei(sound.source, AL_BYTE_OFFSET, &byteOffset); - // - //int sampleRate; - //alGetBufferi(sound.buffer, AL_FREQUENCY, &sampleRate); // AL_CHANNELS, AL_BITS (bps) - - //float seconds = (float)byteOffset/sampleRate; // Number of seconds since the beginning of the sound - //or - //float result; - //alGetSourcef(sound.source, AL_SEC_OFFSET, &result); // AL_SAMPLE_OFFSET -} - -// Pause a sound -void PauseSound(Sound sound) -{ - alSourcePause(sound.source); -} - -// Resume a paused sound -void ResumeSound(Sound sound) -{ - ALenum state; - - alGetSourcei(sound.source, AL_SOURCE_STATE, &state); - - if (state == AL_PAUSED) alSourcePlay(sound.source); -} - -// Stop reproducing a sound -void StopSound(Sound sound) -{ - alSourceStop(sound.source); -} - -// Check if a sound is playing -bool IsSoundPlaying(Sound sound) -{ - bool playing = false; - ALint state; - - alGetSourcei(sound.source, AL_SOURCE_STATE, &state); - if (state == AL_PLAYING) playing = true; - - return playing; -} - -// Set volume for a sound -void SetSoundVolume(Sound sound, float volume) -{ - alSourcef(sound.source, AL_GAIN, volume); -} - -// Set pitch for a sound -void SetSoundPitch(Sound sound, float pitch) -{ - alSourcef(sound.source, AL_PITCH, pitch); -} - -// Convert wave data to desired format -void WaveFormat(Wave *wave, int sampleRate, int sampleSize, int channels) -{ - // Format sample rate - // NOTE: Only supported 22050 <--> 44100 - if (wave->sampleRate != sampleRate) - { - // TODO: Resample wave data (upsampling or downsampling) - // NOTE 1: To downsample, you have to drop samples or average them. - // NOTE 2: To upsample, you have to interpolate new samples. - - wave->sampleRate = sampleRate; - } - - // Format sample size - // NOTE: Only supported 8 bit <--> 16 bit <--> 32 bit - if (wave->sampleSize != sampleSize) - { - void *data = malloc(wave->sampleCount*wave->channels*sampleSize/8); - - for (int i = 0; i < wave->sampleCount; i++) - { - for (int j = 0; j < wave->channels; j++) - { - if (sampleSize == 8) - { - if (wave->sampleSize == 16) ((unsigned char *)data)[wave->channels*i + j] = (unsigned char)(((float)(((short *)wave->data)[wave->channels*i + j])/32767.0f)*256); - else if (wave->sampleSize == 32) ((unsigned char *)data)[wave->channels*i + j] = (unsigned char)(((float *)wave->data)[wave->channels*i + j]*127.0f + 127); - } - else if (sampleSize == 16) - { - if (wave->sampleSize == 8) ((short *)data)[wave->channels*i + j] = (short)(((float)(((unsigned char *)wave->data)[wave->channels*i + j] - 127)/256.0f)*32767); - else if (wave->sampleSize == 32) ((short *)data)[wave->channels*i + j] = (short)((((float *)wave->data)[wave->channels*i + j])*32767); - } - else if (sampleSize == 32) - { - if (wave->sampleSize == 8) ((float *)data)[wave->channels*i + j] = (float)(((unsigned char *)wave->data)[wave->channels*i + j] - 127)/256.0f; - else if (wave->sampleSize == 16) ((float *)data)[wave->channels*i + j] = (float)(((short *)wave->data)[wave->channels*i + j])/32767.0f; - } - } - } - - wave->sampleSize = sampleSize; - free(wave->data); - wave->data = data; - } - - // Format channels (interlaced mode) - // NOTE: Only supported mono <--> stereo - if (wave->channels != channels) - { - void *data = malloc(wave->sampleCount*wave->sampleSize/8*channels); - - if ((wave->channels == 1) && (channels == 2)) // mono ---> stereo (duplicate mono information) - { - for (int i = 0; i < wave->sampleCount; i++) - { - for (int j = 0; j < channels; j++) - { - if (wave->sampleSize == 8) ((unsigned char *)data)[channels*i + j] = ((unsigned char *)wave->data)[i]; - else if (wave->sampleSize == 16) ((short *)data)[channels*i + j] = ((short *)wave->data)[i]; - else if (wave->sampleSize == 32) ((float *)data)[channels*i + j] = ((float *)wave->data)[i]; - } - } - } - else if ((wave->channels == 2) && (channels == 1)) // stereo ---> mono (mix stereo channels) - { - for (int i = 0, j = 0; i < wave->sampleCount; i++, j += 2) - { - if (wave->sampleSize == 8) ((unsigned char *)data)[i] = (((unsigned char *)wave->data)[j] + ((unsigned char *)wave->data)[j + 1])/2; - else if (wave->sampleSize == 16) ((short *)data)[i] = (((short *)wave->data)[j] + ((short *)wave->data)[j + 1])/2; - else if (wave->sampleSize == 32) ((float *)data)[i] = (((float *)wave->data)[j] + ((float *)wave->data)[j + 1])/2.0f; - } - } - - // TODO: Add/remove additional interlaced channels - - wave->channels = channels; - free(wave->data); - wave->data = data; - } -} - -// Copy a wave to a new wave -Wave WaveCopy(Wave wave) -{ - Wave newWave = { 0 }; - - newWave.data = malloc(wave.sampleCount*wave.sampleSize/8*wave.channels); - - if (newWave.data != NULL) - { - // NOTE: Size must be provided in bytes - memcpy(newWave.data, wave.data, wave.sampleCount*wave.channels*wave.sampleSize/8); - - newWave.sampleCount = wave.sampleCount; - newWave.sampleRate = wave.sampleRate; - newWave.sampleSize = wave.sampleSize; - newWave.channels = wave.channels; - } - - return newWave; -} - -// Crop a wave to defined samples range -// NOTE: Security check in case of out-of-range -void WaveCrop(Wave *wave, int initSample, int finalSample) -{ - if ((initSample >= 0) && (initSample < finalSample) && - (finalSample > 0) && (finalSample < wave->sampleCount)) - { - int sampleCount = finalSample - initSample; - - void *data = malloc(sampleCount*wave->sampleSize/8*wave->channels); - - memcpy(data, (unsigned char*)wave->data + (initSample*wave->channels*wave->sampleSize/8), sampleCount*wave->channels*wave->sampleSize/8); - - free(wave->data); - wave->data = data; - } - else TraceLog(LOG_WARNING, "Wave crop range out of bounds"); -} - -// Get samples data from wave as a floats array -// NOTE: Returned sample values are normalized to range [-1..1] -float *GetWaveData(Wave wave) -{ - float *samples = (float *)malloc(wave.sampleCount*wave.channels*sizeof(float)); - - for (int i = 0; i < wave.sampleCount; i++) - { - for (int j = 0; j < wave.channels; j++) - { - if (wave.sampleSize == 8) samples[wave.channels*i + j] = (float)(((unsigned char *)wave.data)[wave.channels*i + j] - 127)/256.0f; - else if (wave.sampleSize == 16) samples[wave.channels*i + j] = (float)((short *)wave.data)[wave.channels*i + j]/32767.0f; - else if (wave.sampleSize == 32) samples[wave.channels*i + j] = ((float *)wave.data)[wave.channels*i + j]; - } - } - - return samples; -} - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Music loading and stream playing (.OGG) -//---------------------------------------------------------------------------------- - -// Load music stream from file -Music LoadMusicStream(const char *fileName) -{ - Music music = (MusicData *)malloc(sizeof(MusicData)); - - if (IsFileExtension(fileName, ".ogg")) - { - // Open ogg audio stream - music->ctxOgg = stb_vorbis_open_filename(fileName, NULL, NULL); - - if (music->ctxOgg == NULL) TraceLog(LOG_WARNING, "[%s] OGG audio file could not be opened", fileName); - else - { - stb_vorbis_info info = stb_vorbis_get_info(music->ctxOgg); // Get Ogg file info - - // OGG bit rate defaults to 16 bit, it's enough for compressed format - music->stream = InitAudioStream(info.sample_rate, 16, info.channels); - music->totalSamples = (unsigned int)stb_vorbis_stream_length_in_samples(music->ctxOgg); // Independent by channel - music->samplesLeft = music->totalSamples; - music->ctxType = MUSIC_AUDIO_OGG; - music->loopCount = -1; // Infinite loop by default - - TraceLog(LOG_DEBUG, "[%s] FLAC total samples: %i", fileName, music->totalSamples); - TraceLog(LOG_DEBUG, "[%s] OGG sample rate: %i", fileName, info.sample_rate); - TraceLog(LOG_DEBUG, "[%s] OGG channels: %i", fileName, info.channels); - TraceLog(LOG_DEBUG, "[%s] OGG memory required: %i", fileName, info.temp_memory_required); - } - } -#if defined(SUPPORT_FILEFORMAT_FLAC) - else if (IsFileExtension(fileName, ".flac")) - { - music->ctxFlac = drflac_open_file(fileName); - - if (music->ctxFlac == NULL) TraceLog(LOG_WARNING, "[%s] FLAC audio file could not be opened", fileName); - else - { - music->stream = InitAudioStream(music->ctxFlac->sampleRate, music->ctxFlac->bitsPerSample, music->ctxFlac->channels); - music->totalSamples = (unsigned int)music->ctxFlac->totalSampleCount/music->ctxFlac->channels; - music->samplesLeft = music->totalSamples; - music->ctxType = MUSIC_AUDIO_FLAC; - music->loopCount = -1; // Infinite loop by default - - TraceLog(LOG_DEBUG, "[%s] FLAC total samples: %i", fileName, music->totalSamples); - TraceLog(LOG_DEBUG, "[%s] FLAC sample rate: %i", fileName, music->ctxFlac->sampleRate); - TraceLog(LOG_DEBUG, "[%s] FLAC bits per sample: %i", fileName, music->ctxFlac->bitsPerSample); - TraceLog(LOG_DEBUG, "[%s] FLAC channels: %i", fileName, music->ctxFlac->channels); - } - } -#endif -#if defined(SUPPORT_FILEFORMAT_XM) - else if (IsFileExtension(fileName, ".xm")) - { - int result = jar_xm_create_context_from_file(&music->ctxXm, 48000, fileName); - - if (!result) // XM context created successfully - { - jar_xm_set_max_loop_count(music->ctxXm, 0); // Set infinite number of loops - - // NOTE: Only stereo is supported for XM - music->stream = InitAudioStream(48000, 16, 2); - music->totalSamples = (unsigned int)jar_xm_get_remaining_samples(music->ctxXm); - music->samplesLeft = music->totalSamples; - music->ctxType = MUSIC_MODULE_XM; - music->loopCount = -1; // Infinite loop by default - - TraceLog(LOG_DEBUG, "[%s] XM number of samples: %i", fileName, music->totalSamples); - TraceLog(LOG_DEBUG, "[%s] XM track length: %11.6f sec", fileName, (float)music->totalSamples/48000.0f); - } - else TraceLog(LOG_WARNING, "[%s] XM file could not be opened", fileName); - } -#endif -#if defined(SUPPORT_FILEFORMAT_MOD) - else if (IsFileExtension(fileName, ".mod")) - { - jar_mod_init(&music->ctxMod); - - if (jar_mod_load_file(&music->ctxMod, fileName)) - { - music->stream = InitAudioStream(48000, 16, 2); - music->totalSamples = (unsigned int)jar_mod_max_samples(&music->ctxMod); - music->samplesLeft = music->totalSamples; - music->ctxType = MUSIC_MODULE_MOD; - music->loopCount = -1; // Infinite loop by default - - TraceLog(LOG_DEBUG, "[%s] MOD number of samples: %i", fileName, music->samplesLeft); - TraceLog(LOG_DEBUG, "[%s] MOD track length: %11.6f sec", fileName, (float)music->totalSamples/48000.0f); - } - else TraceLog(LOG_WARNING, "[%s] MOD file could not be opened", fileName); - } -#endif - else TraceLog(LOG_WARNING, "[%s] Audio fileformat not supported, it can't be loaded", fileName); - - return music; -} - -// Unload music stream -void UnloadMusicStream(Music music) -{ - CloseAudioStream(music->stream); - - if (music->ctxType == MUSIC_AUDIO_OGG) stb_vorbis_close(music->ctxOgg); -#if defined(SUPPORT_FILEFORMAT_FLAC) - else if (music->ctxType == MUSIC_AUDIO_FLAC) drflac_free(music->ctxFlac); -#endif -#if defined(SUPPORT_FILEFORMAT_XM) - else if (music->ctxType == MUSIC_MODULE_XM) jar_xm_free_context(music->ctxXm); -#endif -#if defined(SUPPORT_FILEFORMAT_MOD) - else if (music->ctxType == MUSIC_MODULE_MOD) jar_mod_unload(&music->ctxMod); -#endif - - free(music); -} - -// Start music playing (open stream) -void PlayMusicStream(Music music) -{ - alSourcePlay(music->stream.source); -} - -// Pause music playing -void PauseMusicStream(Music music) -{ - alSourcePause(music->stream.source); -} - -// Resume music playing -void ResumeMusicStream(Music music) -{ - ALenum state; - alGetSourcei(music->stream.source, AL_SOURCE_STATE, &state); - - if (state == AL_PAUSED) - { - TraceLog(LOG_INFO, "[AUD ID %i] Resume music stream playing", music->stream.source); - alSourcePlay(music->stream.source); - } -} - -// Stop music playing (close stream) -// TODO: To clear a buffer, make sure they have been already processed! -void StopMusicStream(Music music) -{ - alSourceStop(music->stream.source); - - /* - // Clear stream buffers - // WARNING: Queued buffers must have been processed before unqueueing and reloaded with data!!! - void *pcm = calloc(AUDIO_BUFFER_SIZE*music->stream.sampleSize/8*music->stream.channels, 1); - - for (int i = 0; i < MAX_STREAM_BUFFERS; i++) - { - //UpdateAudioStream(music->stream, pcm, AUDIO_BUFFER_SIZE); // Update one buffer at a time - alBufferData(music->stream.buffers[i], music->stream.format, pcm, AUDIO_BUFFER_SIZE*music->stream.sampleSize/8*music->stream.channels, music->stream.sampleRate); - } - - free(pcm); - */ - - // Restart music context - switch (music->ctxType) - { - case MUSIC_AUDIO_OGG: stb_vorbis_seek_start(music->ctxOgg); break; -#if defined(SUPPORT_FILEFORMAT_FLAC) - case MUSIC_MODULE_FLAC: /* TODO: Restart FLAC context */ break; -#endif -#if defined(SUPPORT_FILEFORMAT_XM) - case MUSIC_MODULE_XM: /* TODO: Restart XM context */ break; -#endif -#if defined(SUPPORT_FILEFORMAT_MOD) - case MUSIC_MODULE_MOD: jar_mod_seek_start(&music->ctxMod); break; -#endif - default: break; - } - - music->samplesLeft = music->totalSamples; -} - -// Update (re-fill) music buffers if data already processed -// TODO: Make sure buffers are ready for update... check music state -void UpdateMusicStream(Music music) -{ - ALenum state; - ALint processed = 0; - - alGetSourcei(music->stream.source, AL_SOURCE_STATE, &state); // Get music stream state - alGetSourcei(music->stream.source, AL_BUFFERS_PROCESSED, &processed); // Get processed buffers - - if (processed > 0) - { - bool streamEnding = false; - - // NOTE: Using dynamic allocation because it could require more than 16KB - void *pcm = calloc(AUDIO_BUFFER_SIZE*music->stream.sampleSize/8*music->stream.channels, 1); - - int numBuffersToProcess = processed; - int samplesCount = 0; // Total size of data steamed in L+R samples for xm floats, - // individual L or R for ogg shorts - - for (int i = 0; i < numBuffersToProcess; i++) - { - if (music->samplesLeft >= AUDIO_BUFFER_SIZE) samplesCount = AUDIO_BUFFER_SIZE; - else samplesCount = music->samplesLeft; - - // TODO: Really don't like ctxType thingy... - switch (music->ctxType) - { - case MUSIC_AUDIO_OGG: - { - // NOTE: Returns the number of samples to process (be careful! we ask for number of shorts!) - int numSamplesOgg = stb_vorbis_get_samples_short_interleaved(music->ctxOgg, music->stream.channels, (short *)pcm, samplesCount*music->stream.channels); - - } break; - #if defined(SUPPORT_FILEFORMAT_FLAC) - case MUSIC_AUDIO_FLAC: - { - // NOTE: Returns the number of samples to process - unsigned int numSamplesFlac = (unsigned int)drflac_read_s16(music->ctxFlac, samplesCount*music->stream.channels, (short *)pcm); - - } break; - #endif - #if defined(SUPPORT_FILEFORMAT_XM) - case MUSIC_MODULE_XM: jar_xm_generate_samples_16bit(music->ctxXm, pcm, samplesCount); break; - #endif - #if defined(SUPPORT_FILEFORMAT_MOD) - case MUSIC_MODULE_MOD: jar_mod_fillbuffer(&music->ctxMod, pcm, samplesCount, 0); break; - #endif - default: break; - } - - UpdateAudioStream(music->stream, pcm, samplesCount); - music->samplesLeft -= samplesCount; - - if (music->samplesLeft <= 0) - { - streamEnding = true; - break; - } - } - - // Free allocated pcm data - free(pcm); - - // Reset audio stream for looping - if (streamEnding) - { - StopMusicStream(music); // Stop music (and reset) - - // Decrease loopCount to stop when required - if (music->loopCount > 0) - { - music->loopCount--; // Decrease loop count - PlayMusicStream(music); // Play again - } - } - else - { - // NOTE: In case window is minimized, music stream is stopped, - // just make sure to play again on window restore - if (state != AL_PLAYING) PlayMusicStream(music); - } - } -} - -// Check if any music is playing -bool IsMusicPlaying(Music music) -{ - bool playing = false; - ALint state; - - alGetSourcei(music->stream.source, AL_SOURCE_STATE, &state); - - if (state == AL_PLAYING) playing = true; - - return playing; -} - -// Set volume for music -void SetMusicVolume(Music music, float volume) -{ - alSourcef(music->stream.source, AL_GAIN, volume); -} - -// Set pitch for music -void SetMusicPitch(Music music, float pitch) -{ - alSourcef(music->stream.source, AL_PITCH, pitch); -} - -// Set music loop count (loop repeats) -// NOTE: If set to -1, means infinite loop -void SetMusicLoopCount(Music music, float count) -{ - music->loopCount = count; -} - -// Get music time length (in seconds) -float GetMusicTimeLength(Music music) -{ - float totalSeconds = (float)music->totalSamples/music->stream.sampleRate; - - return totalSeconds; -} - -// Get current music time played (in seconds) -float GetMusicTimePlayed(Music music) -{ - float secondsPlayed = 0.0f; - - unsigned int samplesPlayed = music->totalSamples - music->samplesLeft; - secondsPlayed = (float)samplesPlayed/music->stream.sampleRate; - - return secondsPlayed; -} - -// Init audio stream (to stream audio pcm data) -AudioStream InitAudioStream(unsigned int sampleRate, unsigned int sampleSize, unsigned int channels) -{ - AudioStream stream = { 0 }; - - stream.sampleRate = sampleRate; - stream.sampleSize = sampleSize; - - // Only mono and stereo channels are supported, more channels require AL_EXT_MCFORMATS extension - if ((channels > 0) && (channels < 3)) stream.channels = channels; - else - { - TraceLog(LOG_WARNING, "Init audio stream: Number of channels not supported: %i", channels); - stream.channels = 1; // Fallback to mono channel - } - - // Setup OpenAL format - if (stream.channels == 1) - { - switch (sampleSize) - { - case 8: stream.format = AL_FORMAT_MONO8; break; - case 16: stream.format = AL_FORMAT_MONO16; break; - case 32: stream.format = AL_FORMAT_MONO_FLOAT32; break; // Requires OpenAL extension: AL_EXT_FLOAT32 - default: TraceLog(LOG_WARNING, "Init audio stream: Sample size not supported: %i", sampleSize); break; - } - } - else if (stream.channels == 2) - { - switch (sampleSize) - { - case 8: stream.format = AL_FORMAT_STEREO8; break; - case 16: stream.format = AL_FORMAT_STEREO16; break; - case 32: stream.format = AL_FORMAT_STEREO_FLOAT32; break; // Requires OpenAL extension: AL_EXT_FLOAT32 - default: TraceLog(LOG_WARNING, "Init audio stream: Sample size not supported: %i", sampleSize); break; - } - } - - // Create an audio source - alGenSources(1, &stream.source); - alSourcef(stream.source, AL_PITCH, 1.0f); - alSourcef(stream.source, AL_GAIN, 1.0f); - alSource3f(stream.source, AL_POSITION, 0.0f, 0.0f, 0.0f); - alSource3f(stream.source, AL_VELOCITY, 0.0f, 0.0f, 0.0f); - - // Create Buffers (double buffering) - alGenBuffers(MAX_STREAM_BUFFERS, stream.buffers); - - // Initialize buffer with zeros by default - // NOTE: Using dynamic allocation because it requires more than 16KB - void *pcm = calloc(AUDIO_BUFFER_SIZE*stream.sampleSize/8*stream.channels, 1); - - for (int i = 0; i < MAX_STREAM_BUFFERS; i++) - { - alBufferData(stream.buffers[i], stream.format, pcm, AUDIO_BUFFER_SIZE*stream.sampleSize/8*stream.channels, stream.sampleRate); - } - - free(pcm); - - alSourceQueueBuffers(stream.source, MAX_STREAM_BUFFERS, stream.buffers); - - TraceLog(LOG_INFO, "[AUD ID %i] Audio stream loaded successfully (%i Hz, %i bit, %s)", stream.source, stream.sampleRate, stream.sampleSize, (stream.channels == 1) ? "Mono" : "Stereo"); - - return stream; -} - -// Close audio stream and free memory -void CloseAudioStream(AudioStream stream) -{ - // Stop playing channel - alSourceStop(stream.source); - - // Flush out all queued buffers - int queued = 0; - alGetSourcei(stream.source, AL_BUFFERS_QUEUED, &queued); - - ALuint buffer = 0; - - while (queued > 0) - { - alSourceUnqueueBuffers(stream.source, 1, &buffer); - queued--; - } - - // Delete source and buffers - alDeleteSources(1, &stream.source); - alDeleteBuffers(MAX_STREAM_BUFFERS, stream.buffers); - - TraceLog(LOG_INFO, "[AUD ID %i] Unloaded audio stream data", stream.source); -} - -// Update audio stream buffers with data -// NOTE 1: Only updates one buffer of the stream source: unqueue -> update -> queue -// NOTE 2: To unqueue a buffer it needs to be processed: IsAudioBufferProcessed() -void UpdateAudioStream(AudioStream stream, const void *data, int samplesCount) -{ - ALuint buffer = 0; - alSourceUnqueueBuffers(stream.source, 1, &buffer); - - // Check if any buffer was available for unqueue - if (alGetError() != AL_INVALID_VALUE) - { - alBufferData(buffer, stream.format, data, samplesCount*stream.sampleSize/8*stream.channels, stream.sampleRate); - alSourceQueueBuffers(stream.source, 1, &buffer); - } - else TraceLog(LOG_WARNING, "[AUD ID %i] Audio buffer not available for unqueuing", stream.source); -} - -// Check if any audio stream buffers requires refill -bool IsAudioBufferProcessed(AudioStream stream) -{ - ALint processed = 0; - - // Determine if music stream is ready to be written - alGetSourcei(stream.source, AL_BUFFERS_PROCESSED, &processed); - - return (processed > 0); -} - -// Play audio stream -void PlayAudioStream(AudioStream stream) -{ - alSourcePlay(stream.source); -} - -// Play audio stream -void PauseAudioStream(AudioStream stream) -{ - alSourcePause(stream.source); -} - -// Resume audio stream playing -void ResumeAudioStream(AudioStream stream) -{ - ALenum state; - alGetSourcei(stream.source, AL_SOURCE_STATE, &state); - - if (state == AL_PAUSED) alSourcePlay(stream.source); -} - -// Stop audio stream -void StopAudioStream(AudioStream stream) -{ - alSourceStop(stream.source); -} - -//---------------------------------------------------------------------------------- -// Module specific Functions Definition -//---------------------------------------------------------------------------------- - -#if defined(SUPPORT_FILEFORMAT_WAV) -// Load WAV file into Wave structure -static Wave LoadWAV(const char *fileName) -{ - // Basic WAV headers structs - typedef struct { - char chunkID[4]; - int chunkSize; - char format[4]; - } WAVRiffHeader; - - typedef struct { - char subChunkID[4]; - int subChunkSize; - short audioFormat; - short numChannels; - int sampleRate; - int byteRate; - short blockAlign; - short bitsPerSample; - } WAVFormat; - - typedef struct { - char subChunkID[4]; - int subChunkSize; - } WAVData; - - WAVRiffHeader wavRiffHeader; - WAVFormat wavFormat; - WAVData wavData; - - Wave wave = { 0 }; - FILE *wavFile; - - wavFile = fopen(fileName, "rb"); - - if (wavFile == NULL) - { - TraceLog(LOG_WARNING, "[%s] WAV file could not be opened", fileName); - wave.data = NULL; - } - else - { - // Read in the first chunk into the struct - fread(&wavRiffHeader, sizeof(WAVRiffHeader), 1, wavFile); - - // Check for RIFF and WAVE tags - if (strncmp(wavRiffHeader.chunkID, "RIFF", 4) || - strncmp(wavRiffHeader.format, "WAVE", 4)) - { - TraceLog(LOG_WARNING, "[%s] Invalid RIFF or WAVE Header", fileName); - } - else - { - // Read in the 2nd chunk for the wave info - fread(&wavFormat, sizeof(WAVFormat), 1, wavFile); - - // Check for fmt tag - if ((wavFormat.subChunkID[0] != 'f') || (wavFormat.subChunkID[1] != 'm') || - (wavFormat.subChunkID[2] != 't') || (wavFormat.subChunkID[3] != ' ')) - { - TraceLog(LOG_WARNING, "[%s] Invalid Wave format", fileName); - } - else - { - // Check for extra parameters; - if (wavFormat.subChunkSize > 16) fseek(wavFile, sizeof(short), SEEK_CUR); - - // Read in the the last byte of data before the sound file - fread(&wavData, sizeof(WAVData), 1, wavFile); - - // Check for data tag - if ((wavData.subChunkID[0] != 'd') || (wavData.subChunkID[1] != 'a') || - (wavData.subChunkID[2] != 't') || (wavData.subChunkID[3] != 'a')) - { - TraceLog(LOG_WARNING, "[%s] Invalid data header", fileName); - } - else - { - // Allocate memory for data - wave.data = malloc(wavData.subChunkSize); - - // Read in the sound data into the soundData variable - fread(wave.data, wavData.subChunkSize, 1, wavFile); - - // Store wave parameters - wave.sampleRate = wavFormat.sampleRate; - wave.sampleSize = wavFormat.bitsPerSample; - wave.channels = wavFormat.numChannels; - - // NOTE: Only support 8 bit, 16 bit and 32 bit sample sizes - if ((wave.sampleSize != 8) && (wave.sampleSize != 16) && (wave.sampleSize != 32)) - { - TraceLog(LOG_WARNING, "[%s] WAV sample size (%ibit) not supported, converted to 16bit", fileName, wave.sampleSize); - WaveFormat(&wave, wave.sampleRate, 16, wave.channels); - } - - // NOTE: Only support up to 2 channels (mono, stereo) - if (wave.channels > 2) - { - WaveFormat(&wave, wave.sampleRate, wave.sampleSize, 2); - TraceLog(LOG_WARNING, "[%s] WAV channels number (%i) not supported, converted to 2 channels", fileName, wave.channels); - } - - // NOTE: subChunkSize comes in bytes, we need to translate it to number of samples - wave.sampleCount = (wavData.subChunkSize/(wave.sampleSize/8))/wave.channels; - - TraceLog(LOG_INFO, "[%s] WAV file loaded successfully (%i Hz, %i bit, %s)", fileName, wave.sampleRate, wave.sampleSize, (wave.channels == 1) ? "Mono" : "Stereo"); - } - } - } - - fclose(wavFile); - } - - return wave; -} -#endif - -#if defined(SUPPORT_FILEFORMAT_OGG) -// Load OGG file into Wave structure -// NOTE: Using stb_vorbis library -static Wave LoadOGG(const char *fileName) -{ - Wave wave = { 0 }; - - stb_vorbis *oggFile = stb_vorbis_open_filename(fileName, NULL, NULL); - - if (oggFile == NULL) TraceLog(LOG_WARNING, "[%s] OGG file could not be opened", fileName); - else - { - stb_vorbis_info info = stb_vorbis_get_info(oggFile); - - wave.sampleRate = info.sample_rate; - wave.sampleSize = 16; // 16 bit per sample (short) - wave.channels = info.channels; - wave.sampleCount = (int)stb_vorbis_stream_length_in_samples(oggFile); // Independent by channel - - float totalSeconds = stb_vorbis_stream_length_in_seconds(oggFile); - if (totalSeconds > 10) TraceLog(LOG_WARNING, "[%s] Ogg audio length is larger than 10 seconds (%f), that's a big file in memory, consider music streaming", fileName, totalSeconds); - - wave.data = (short *)malloc(wave.sampleCount*wave.channels*sizeof(short)); - - // NOTE: Returns the number of samples to process (be careful! we ask for number of shorts!) - int numSamplesOgg = stb_vorbis_get_samples_short_interleaved(oggFile, info.channels, (short *)wave.data, wave.sampleCount*wave.channels); - - TraceLog(LOG_DEBUG, "[%s] Samples obtained: %i", fileName, numSamplesOgg); - - TraceLog(LOG_INFO, "[%s] OGG file loaded successfully (%i Hz, %i bit, %s)", fileName, wave.sampleRate, wave.sampleSize, (wave.channels == 1) ? "Mono" : "Stereo"); - - stb_vorbis_close(oggFile); - } - - return wave; -} -#endif - -#if defined(SUPPORT_FILEFORMAT_FLAC) -// Load FLAC file into Wave structure -// NOTE: Using dr_flac library -static Wave LoadFLAC(const char *fileName) -{ - Wave wave; - - // Decode an entire FLAC file in one go - uint64_t totalSampleCount; - wave.data = drflac_open_and_decode_file_s16(fileName, &wave.channels, &wave.sampleRate, &totalSampleCount); - - wave.sampleCount = (int)totalSampleCount/wave.channels; - wave.sampleSize = 16; - - // NOTE: Only support up to 2 channels (mono, stereo) - if (wave.channels > 2) TraceLog(LOG_WARNING, "[%s] FLAC channels number (%i) not supported", fileName, wave.channels); - - if (wave.data == NULL) TraceLog(LOG_WARNING, "[%s] FLAC data could not be loaded", fileName); - else TraceLog(LOG_INFO, "[%s] FLAC file loaded successfully (%i Hz, %i bit, %s)", fileName, wave.sampleRate, wave.sampleSize, (wave.channels == 1) ? "Mono" : "Stereo"); - - return wave; -} -#endif - -// Some required functions for audio standalone module version -#if defined(AUDIO_STANDALONE) -// Check file extension -bool IsFileExtension(const char *fileName, const char *ext) -{ - bool result = false; - const char *fileExt; - - if ((fileExt = strrchr(fileName, '.')) != NULL) - { - if (strcmp(fileExt, ext) == 0) result = true; - } - - return result; -} - -// Show trace log messages (LOG_INFO, LOG_WARNING, LOG_ERROR, LOG_DEBUG) -void TraceLog(int msgType, const char *text, ...) -{ - va_list args; - va_start(args, text); - - switch (msgType) - { - case LOG_INFO: fprintf(stdout, "INFO: "); break; - case LOG_ERROR: fprintf(stdout, "ERROR: "); break; - case LOG_WARNING: fprintf(stdout, "WARNING: "); break; - case LOG_DEBUG: fprintf(stdout, "DEBUG: "); break; - default: break; - } - - vfprintf(stdout, text, args); - fprintf(stdout, "\n"); - - va_end(args); - - if (msgType == LOG_ERROR) exit(1); -} -#endif diff --git a/game/src/libs/raylib/audio.h b/game/src/libs/raylib/audio.h deleted file mode 100644 index 48ef740..0000000 --- a/game/src/libs/raylib/audio.h +++ /dev/null @@ -1,170 +0,0 @@ -/********************************************************************************************** -* -* raylib.audio - Basic funtionality to work with audio -* -* FEATURES: -* - Manage audio device (init/close) -* - Load and unload audio files -* - Format wave data (sample rate, size, channels) -* - Play/Stop/Pause/Resume loaded audio -* - Manage mixing channels -* - Manage raw audio context -* -* LIMITATIONS: -* Only up to two channels supported: MONO and STEREO (for additional channels, use AL_EXT_MCFORMATS) -* Only the following sample sizes supported: 8bit PCM, 16bit PCM, 32-bit float PCM (using AL_EXT_FLOAT32) -* -* DEPENDENCIES: -* OpenAL Soft - Audio device management (http://kcat.strangesoft.net/openal.html) -* stb_vorbis - OGG audio files loading (http://www.nothings.org/stb_vorbis/) -* jar_xm - XM module file loading (#define SUPPORT_FILEFORMAT_XM) -* jar_mod - MOD audio file loading (#define SUPPORT_FILEFORMAT_MOD) -* dr_flac - FLAC audio file loading (#define SUPPORT_FILEFORMAT_FLAC) -* -* CONTRIBUTORS: -* Joshua Reisenauer (github: @kd7tck): -* - XM audio module support (jar_xm) -* - MOD audio module support (jar_mod) -* - Mixing channels support -* - Raw audio context support -* -* -* LICENSE: zlib/libpng -* -* Copyright (c) 2014-2017 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. -* -* Permission is granted to anyone to use this software for any purpose, including commercial -* applications, and to alter it and redistribute it freely, subject to the following restrictions: -* -* 1. The origin of this software must not be misrepresented; you must not claim that you -* wrote the original software. If you use this software in a product, an acknowledgment -* in the product documentation would be appreciated but is not required. -* -* 2. Altered source versions must be plainly marked as such, and must not be misrepresented -* as being the original software. -* -* 3. This notice may not be removed or altered from any source distribution. -* -**********************************************************************************************/ - -#ifndef AUDIO_H -#define AUDIO_H - -//---------------------------------------------------------------------------------- -// Defines and Macros -//---------------------------------------------------------------------------------- -//... - -//---------------------------------------------------------------------------------- -// Types and Structures Definition -// NOTE: Below types are required for CAMERA_STANDALONE usage -//---------------------------------------------------------------------------------- -#ifndef __cplusplus -// Boolean type - #if !defined(_STDBOOL_H) - typedef enum { false, true } bool; - #define _STDBOOL_H - #endif -#endif - -// Wave type, defines audio wave data -typedef struct Wave { - unsigned int sampleCount; // Number of samples - unsigned int sampleRate; // Frequency (samples per second) - unsigned int sampleSize; // Bit depth (bits per sample): 8, 16, 32 (24 not supported) - unsigned int channels; // Number of channels (1-mono, 2-stereo) - void *data; // Buffer data pointer -} Wave; - -// Sound source type -typedef struct Sound { - unsigned int source; // OpenAL audio source id - unsigned int buffer; // OpenAL audio buffer id - int format; // OpenAL audio format specifier -} Sound; - -// Music type (file streaming from memory) -// NOTE: Anything longer than ~10 seconds should be streamed -typedef struct MusicData *Music; - -// Audio stream type -// NOTE: Useful to create custom audio streams not bound to a specific file -typedef struct AudioStream { - unsigned int sampleRate; // Frequency (samples per second) - unsigned int sampleSize; // Bit depth (bits per sample): 8, 16, 32 (24 not supported) - unsigned int channels; // Number of channels (1-mono, 2-stereo) - - int format; // OpenAL audio format specifier - unsigned int source; // OpenAL audio source id - unsigned int buffers[2]; // OpenAL audio buffers (double buffering) -} AudioStream; - -#ifdef __cplusplus -extern "C" { // Prevents name mangling of functions -#endif - -//---------------------------------------------------------------------------------- -// Global Variables Definition -//---------------------------------------------------------------------------------- -//... - -//---------------------------------------------------------------------------------- -// Module Functions Declaration -//---------------------------------------------------------------------------------- -void InitAudioDevice(void); // Initialize audio device and context -void CloseAudioDevice(void); // Close the audio device and context -bool IsAudioDeviceReady(void); // Check if audio device has been initialized successfully -void SetMasterVolume(float volume); // Set master volume (listener) - -Wave LoadWave(const char *fileName); // Load wave data from file -Wave LoadWaveEx(void *data, int sampleCount, int sampleRate, int sampleSize, int channels); // Load wave data from raw array data -Sound LoadSound(const char *fileName); // Load sound from file -Sound LoadSoundFromWave(Wave wave); // Load sound from wave data -void UpdateSound(Sound sound, const void *data, int samplesCount);// Update sound buffer with new data -void UnloadWave(Wave wave); // Unload wave data -void UnloadSound(Sound sound); // Unload sound -void PlaySound(Sound sound); // Play a sound -void PauseSound(Sound sound); // Pause a sound -void ResumeSound(Sound sound); // Resume a paused sound -void StopSound(Sound sound); // Stop playing a sound -bool IsSoundPlaying(Sound sound); // Check if a sound is currently playing -void SetSoundVolume(Sound sound, float volume); // Set volume for a sound (1.0 is max level) -void SetSoundPitch(Sound sound, float pitch); // Set pitch for a sound (1.0 is base level) -void WaveFormat(Wave *wave, int sampleRate, int sampleSize, int channels); // Convert wave data to desired format -Wave WaveCopy(Wave wave); // Copy a wave to a new wave -void WaveCrop(Wave *wave, int initSample, int finalSample); // Crop a wave to defined samples range -float *GetWaveData(Wave wave); // Get samples data from wave as a floats array -Music LoadMusicStream(const char *fileName); // Load music stream from file -void UnloadMusicStream(Music music); // Unload music stream -void PlayMusicStream(Music music); // Start music playing -void UpdateMusicStream(Music music); // Updates buffers for music streaming -void StopMusicStream(Music music); // Stop music playing -void PauseMusicStream(Music music); // Pause music playing -void ResumeMusicStream(Music music); // Resume playing paused music -bool IsMusicPlaying(Music music); // Check if music is playing -void SetMusicVolume(Music music, float volume); // Set volume for music (1.0 is max level) -void SetMusicPitch(Music music, float pitch); // Set pitch for a music (1.0 is base level) -void SetMusicLoopCount(Music music, float count); // Set music loop count (loop repeats) -float GetMusicTimeLength(Music music); // Get music time length (in seconds) -float GetMusicTimePlayed(Music music); // Get current music time played (in seconds) - -// Raw audio stream functions -AudioStream InitAudioStream(unsigned int sampleRate, - unsigned int sampleSize, - unsigned int channels); // Init audio stream (to stream raw audio pcm data) -void UpdateAudioStream(AudioStream stream, const void *data, int samplesCount); // Update audio stream buffers with data -void CloseAudioStream(AudioStream stream); // Close audio stream and free memory -bool IsAudioBufferProcessed(AudioStream stream); // Check if any audio stream buffers requires refill -void PlayAudioStream(AudioStream stream); // Play audio stream -void PauseAudioStream(AudioStream stream); // Pause audio stream -void ResumeAudioStream(AudioStream stream); // Resume audio stream -void StopAudioStream(AudioStream stream); // Stop audio stream - -#ifdef __cplusplus -} -#endif - -#endif // AUDIO_H \ No newline at end of file diff --git a/game/src/libs/raylib/camera.h b/game/src/libs/raylib/camera.h deleted file mode 100644 index 8067e7b..0000000 --- a/game/src/libs/raylib/camera.h +++ /dev/null @@ -1,498 +0,0 @@ -/******************************************************************************************* -* -* raylib.camera - Camera system with multiple modes support -* -* NOTE: Memory footprint of this library is aproximately 52 bytes (global variables) -* -* CONFIGURATION: -* -* #define CAMERA_IMPLEMENTATION -* Generates the implementation of the library into the included file. -* If not defined, the library is in header only mode and can be included in other headers -* or source files without problems. But only ONE file should hold the implementation. -* -* #define CAMERA_STANDALONE -* If defined, the library can be used as standalone as a camera system but some -* functions must be redefined to manage inputs accordingly. -* -* CONTRIBUTORS: -* Marc Palau: Initial implementation (2014) -* Ramon Santamaria: Supervision, review, update and maintenance -* -* -* LICENSE: zlib/libpng -* -* Copyright (c) 2015-2017 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. -* -* Permission is granted to anyone to use this software for any purpose, including commercial -* applications, and to alter it and redistribute it freely, subject to the following restrictions: -* -* 1. The origin of this software must not be misrepresented; you must not claim that you -* wrote the original software. If you use this software in a product, an acknowledgment -* in the product documentation would be appreciated but is not required. -* -* 2. Altered source versions must be plainly marked as such, and must not be misrepresented -* as being the original software. -* -* 3. This notice may not be removed or altered from any source distribution. -* -**********************************************************************************************/ - -#ifndef CAMERA_H -#define CAMERA_H - -//---------------------------------------------------------------------------------- -// Defines and Macros -//---------------------------------------------------------------------------------- -//... - -//---------------------------------------------------------------------------------- -// Types and Structures Definition -// NOTE: Below types are required for CAMERA_STANDALONE usage -//---------------------------------------------------------------------------------- -#if defined(CAMERA_STANDALONE) - // Camera modes - typedef enum { - CAMERA_CUSTOM = 0, - CAMERA_FREE, - CAMERA_ORBITAL, - CAMERA_FIRST_PERSON, - CAMERA_THIRD_PERSON - } CameraMode; - - // Vector2 type - typedef struct Vector2 { - float x; - float y; - } Vector2; - - // Vector3 type - typedef struct Vector3 { - float x; - float y; - float z; - } Vector3; - - // Camera type, defines a camera position/orientation in 3d space - typedef struct Camera { - Vector3 position; - Vector3 target; - Vector3 up; - float fovy; - } Camera; -#endif - -#ifdef __cplusplus -extern "C" { // Prevents name mangling of functions -#endif - -//---------------------------------------------------------------------------------- -// Global Variables Definition -//---------------------------------------------------------------------------------- -//... - -//---------------------------------------------------------------------------------- -// Module Functions Declaration -//---------------------------------------------------------------------------------- -#if defined(CAMERA_STANDALONE) -void SetCameraMode(Camera camera, int mode); // Set camera mode (multiple camera modes available) -void UpdateCamera(Camera *camera); // Update camera position for selected mode - -void SetCameraPanControl(int panKey); // Set camera pan key to combine with mouse movement (free camera) -void SetCameraAltControl(int altKey); // Set camera alt key to combine with mouse movement (free camera) -void SetCameraSmoothZoomControl(int szKey); // Set camera smooth zoom key to combine with mouse (free camera) -void SetCameraMoveControls(int frontKey, int backKey, - int rightKey, int leftKey, - int upKey, int downKey); // Set camera move controls (1st person and 3rd person cameras) -#endif - -#ifdef __cplusplus -} -#endif - -#endif // CAMERA_H - - -/*********************************************************************************** -* -* CAMERA IMPLEMENTATION -* -************************************************************************************/ - -#if defined(CAMERA_IMPLEMENTATION) - -#include // Required for: sqrt(), sin(), cos() - -#ifndef PI - #define PI 3.14159265358979323846 -#endif - -#ifndef DEG2RAD - #define DEG2RAD (PI/180.0f) -#endif - -#ifndef RAD2DEG - #define RAD2DEG (180.0f/PI) -#endif - -//---------------------------------------------------------------------------------- -// Defines and Macros -//---------------------------------------------------------------------------------- -// Camera mouse movement sensitivity -#define CAMERA_MOUSE_MOVE_SENSITIVITY 0.003f -#define CAMERA_MOUSE_SCROLL_SENSITIVITY 1.5f - -// FREE_CAMERA -#define CAMERA_FREE_MOUSE_SENSITIVITY 0.01f -#define CAMERA_FREE_DISTANCE_MIN_CLAMP 0.3f -#define CAMERA_FREE_DISTANCE_MAX_CLAMP 120.0f -#define CAMERA_FREE_MIN_CLAMP 85.0f -#define CAMERA_FREE_MAX_CLAMP -85.0f -#define CAMERA_FREE_SMOOTH_ZOOM_SENSITIVITY 0.05f -#define CAMERA_FREE_PANNING_DIVIDER 5.1f - -// ORBITAL_CAMERA -#define CAMERA_ORBITAL_SPEED 0.01f // Radians per frame - -// FIRST_PERSON -//#define CAMERA_FIRST_PERSON_MOUSE_SENSITIVITY 0.003f -#define CAMERA_FIRST_PERSON_FOCUS_DISTANCE 25.0f -#define CAMERA_FIRST_PERSON_MIN_CLAMP 85.0f -#define CAMERA_FIRST_PERSON_MAX_CLAMP -85.0f - -#define CAMERA_FIRST_PERSON_STEP_TRIGONOMETRIC_DIVIDER 5.0f -#define CAMERA_FIRST_PERSON_STEP_DIVIDER 30.0f -#define CAMERA_FIRST_PERSON_WAVING_DIVIDER 200.0f - -// THIRD_PERSON -//#define CAMERA_THIRD_PERSON_MOUSE_SENSITIVITY 0.003f -#define CAMERA_THIRD_PERSON_DISTANCE_CLAMP 1.2f -#define CAMERA_THIRD_PERSON_MIN_CLAMP 5.0f -#define CAMERA_THIRD_PERSON_MAX_CLAMP -85.0f -#define CAMERA_THIRD_PERSON_OFFSET (Vector3){ 0.4f, 0.0f, 0.0f } - -// PLAYER (used by camera) -#define PLAYER_MOVEMENT_SENSITIVITY 20.0f - -//---------------------------------------------------------------------------------- -// Types and Structures Definition -//---------------------------------------------------------------------------------- -// Camera move modes (first person and third person cameras) -typedef enum { - MOVE_FRONT = 0, - MOVE_BACK, - MOVE_RIGHT, - MOVE_LEFT, - MOVE_UP, - MOVE_DOWN -} CameraMove; - -//---------------------------------------------------------------------------------- -// Global Variables Definition -//---------------------------------------------------------------------------------- -static Vector2 cameraAngle = { 0.0f, 0.0f }; // TODO: Remove! Compute it in UpdateCamera() -static float cameraTargetDistance = 0.0f; // TODO: Remove! Compute it in UpdateCamera() -static float playerEyesPosition = 1.85f; // Default player eyes position from ground (in meters) - -static int cameraMoveControl[6] = { 'W', 'S', 'D', 'A', 'E', 'Q' }; -static int cameraPanControlKey = 2; // raylib: MOUSE_MIDDLE_BUTTON -static int cameraAltControlKey = 342; // raylib: KEY_LEFT_ALT -static int cameraSmoothZoomControlKey = 341; // raylib: KEY_LEFT_CONTROL - -static int cameraMode = CAMERA_CUSTOM; // Current camera mode - -//---------------------------------------------------------------------------------- -// Module specific Functions Declaration -//---------------------------------------------------------------------------------- -#if defined(CAMERA_STANDALONE) -// NOTE: Camera controls depend on some raylib input functions -// TODO: Set your own input functions (used in UpdateCamera()) -static void EnableCursor() {} // Unlock cursor -static void DisableCursor() {} // Lock cursor - -static int IsKeyDown(int key) { return 0; } - -static int IsMouseButtonDown(int button) { return 0;} -static int GetMouseWheelMove() { return 0; } -static Vector2 GetMousePosition() { return (Vector2){ 0.0f, 0.0f }; } -#endif - -//---------------------------------------------------------------------------------- -// Module Functions Definition -//---------------------------------------------------------------------------------- - -// Select camera mode (multiple camera modes available) -void SetCameraMode(Camera camera, int mode) -{ - // TODO: cameraTargetDistance and cameraAngle should be - // calculated using camera parameters on UpdateCamera() - - Vector3 v1 = camera.position; - Vector3 v2 = camera.target; - - float dx = v2.x - v1.x; - float dy = v2.y - v1.y; - float dz = v2.z - v1.z; - - cameraTargetDistance = sqrtf(dx*dx + dy*dy + dz*dz); - - Vector2 distance = { 0.0f, 0.0f }; - distance.x = sqrtf(dx*dx + dz*dz); - distance.y = sqrtf(dx*dx + dy*dy); - - // Camera angle calculation - cameraAngle.x = asinf(fabsf(dx)/distance.x); // Camera angle in plane XZ (0 aligned with Z, move positive CCW) - cameraAngle.y = -asinf(fabsf(dy)/distance.y); // Camera angle in plane XY (0 aligned with X, move positive CW) - - // NOTE: Just testing what cameraAngle means - //cameraAngle.x = 0.0f*DEG2RAD; // Camera angle in plane XZ (0 aligned with Z, move positive CCW) - //cameraAngle.y = -60.0f*DEG2RAD; // Camera angle in plane XY (0 aligned with X, move positive CW) - - playerEyesPosition = camera.position.y; - - // Lock cursor for first person and third person cameras - if ((mode == CAMERA_FIRST_PERSON) || - (mode == CAMERA_THIRD_PERSON)) DisableCursor(); - else EnableCursor(); - - cameraMode = mode; -} - -// Update camera depending on selected mode -// NOTE: Camera controls depend on some raylib functions: -// System: EnableCursor(), DisableCursor() -// Mouse: IsMouseButtonDown(), GetMousePosition(), GetMouseWheelMove() -// Keys: IsKeyDown() -// TODO: Port to quaternion-based camera -void UpdateCamera(Camera *camera) -{ - static int swingCounter = 0; // Used for 1st person swinging movement - static Vector2 previousMousePosition = { 0.0f, 0.0f }; - - // TODO: Compute cameraTargetDistance and cameraAngle here - - // Mouse movement detection - Vector2 mousePositionDelta = { 0.0f, 0.0f }; - Vector2 mousePosition = GetMousePosition(); - int mouseWheelMove = GetMouseWheelMove(); - - // Keys input detection - bool panKey = IsMouseButtonDown(cameraPanControlKey); - bool altKey = IsKeyDown(cameraAltControlKey); - bool szoomKey = IsKeyDown(cameraSmoothZoomControlKey); - - bool direction[6] = { IsKeyDown(cameraMoveControl[MOVE_FRONT]), - IsKeyDown(cameraMoveControl[MOVE_BACK]), - IsKeyDown(cameraMoveControl[MOVE_RIGHT]), - IsKeyDown(cameraMoveControl[MOVE_LEFT]), - IsKeyDown(cameraMoveControl[MOVE_UP]), - IsKeyDown(cameraMoveControl[MOVE_DOWN]) }; - - // TODO: Consider touch inputs for camera - - if (cameraMode != CAMERA_CUSTOM) - { - mousePositionDelta.x = mousePosition.x - previousMousePosition.x; - mousePositionDelta.y = mousePosition.y - previousMousePosition.y; - - previousMousePosition = mousePosition; - } - - // Support for multiple automatic camera modes - switch (cameraMode) - { - case CAMERA_FREE: - { - // Camera zoom - if ((cameraTargetDistance < CAMERA_FREE_DISTANCE_MAX_CLAMP) && (mouseWheelMove < 0)) - { - cameraTargetDistance -= (mouseWheelMove*CAMERA_MOUSE_SCROLL_SENSITIVITY); - - if (cameraTargetDistance > CAMERA_FREE_DISTANCE_MAX_CLAMP) cameraTargetDistance = CAMERA_FREE_DISTANCE_MAX_CLAMP; - } - // Camera looking down - // TODO: Review, weird comparisson of cameraTargetDistance == 120.0f? - else if ((camera->position.y > camera->target.y) && (cameraTargetDistance == CAMERA_FREE_DISTANCE_MAX_CLAMP) && (mouseWheelMove < 0)) - { - camera->target.x += mouseWheelMove*(camera->target.x - camera->position.x)*CAMERA_MOUSE_SCROLL_SENSITIVITY/cameraTargetDistance; - camera->target.y += mouseWheelMove*(camera->target.y - camera->position.y)*CAMERA_MOUSE_SCROLL_SENSITIVITY/cameraTargetDistance; - camera->target.z += mouseWheelMove*(camera->target.z - camera->position.z)*CAMERA_MOUSE_SCROLL_SENSITIVITY/cameraTargetDistance; - } - else if ((camera->position.y > camera->target.y) && (camera->target.y >= 0)) - { - camera->target.x += mouseWheelMove*(camera->target.x - camera->position.x)*CAMERA_MOUSE_SCROLL_SENSITIVITY/cameraTargetDistance; - camera->target.y += mouseWheelMove*(camera->target.y - camera->position.y)*CAMERA_MOUSE_SCROLL_SENSITIVITY/cameraTargetDistance; - camera->target.z += mouseWheelMove*(camera->target.z - camera->position.z)*CAMERA_MOUSE_SCROLL_SENSITIVITY/cameraTargetDistance; - - // if (camera->target.y < 0) camera->target.y = -0.001; - } - else if ((camera->position.y > camera->target.y) && (camera->target.y < 0) && (mouseWheelMove > 0)) - { - cameraTargetDistance -= (mouseWheelMove*CAMERA_MOUSE_SCROLL_SENSITIVITY); - if (cameraTargetDistance < CAMERA_FREE_DISTANCE_MIN_CLAMP) cameraTargetDistance = CAMERA_FREE_DISTANCE_MIN_CLAMP; - } - // Camera looking up - // TODO: Review, weird comparisson of cameraTargetDistance == 120.0f? - else if ((camera->position.y < camera->target.y) && (cameraTargetDistance == CAMERA_FREE_DISTANCE_MAX_CLAMP) && (mouseWheelMove < 0)) - { - camera->target.x += mouseWheelMove*(camera->target.x - camera->position.x)*CAMERA_MOUSE_SCROLL_SENSITIVITY/cameraTargetDistance; - camera->target.y += mouseWheelMove*(camera->target.y - camera->position.y)*CAMERA_MOUSE_SCROLL_SENSITIVITY/cameraTargetDistance; - camera->target.z += mouseWheelMove*(camera->target.z - camera->position.z)*CAMERA_MOUSE_SCROLL_SENSITIVITY/cameraTargetDistance; - } - else if ((camera->position.y < camera->target.y) && (camera->target.y <= 0)) - { - camera->target.x += mouseWheelMove*(camera->target.x - camera->position.x)*CAMERA_MOUSE_SCROLL_SENSITIVITY/cameraTargetDistance; - camera->target.y += mouseWheelMove*(camera->target.y - camera->position.y)*CAMERA_MOUSE_SCROLL_SENSITIVITY/cameraTargetDistance; - camera->target.z += mouseWheelMove*(camera->target.z - camera->position.z)*CAMERA_MOUSE_SCROLL_SENSITIVITY/cameraTargetDistance; - - // if (camera->target.y > 0) camera->target.y = 0.001; - } - else if ((camera->position.y < camera->target.y) && (camera->target.y > 0) && (mouseWheelMove > 0)) - { - cameraTargetDistance -= (mouseWheelMove*CAMERA_MOUSE_SCROLL_SENSITIVITY); - if (cameraTargetDistance < CAMERA_FREE_DISTANCE_MIN_CLAMP) cameraTargetDistance = CAMERA_FREE_DISTANCE_MIN_CLAMP; - } - - // Input keys checks - if (panKey) - { - if (altKey) // Alternative key behaviour - { - if (szoomKey) - { - // Camera smooth zoom - cameraTargetDistance += (mousePositionDelta.y*CAMERA_FREE_SMOOTH_ZOOM_SENSITIVITY); - } - else - { - // Camera rotation - cameraAngle.x += mousePositionDelta.x*-CAMERA_FREE_MOUSE_SENSITIVITY; - cameraAngle.y += mousePositionDelta.y*-CAMERA_FREE_MOUSE_SENSITIVITY; - - // Angle clamp - if (cameraAngle.y > CAMERA_FREE_MIN_CLAMP*DEG2RAD) cameraAngle.y = CAMERA_FREE_MIN_CLAMP*DEG2RAD; - else if (cameraAngle.y < CAMERA_FREE_MAX_CLAMP*DEG2RAD) cameraAngle.y = CAMERA_FREE_MAX_CLAMP*DEG2RAD; - } - } - else - { - // Camera panning - camera->target.x += ((mousePositionDelta.x*-CAMERA_FREE_MOUSE_SENSITIVITY)*cosf(cameraAngle.x) + (mousePositionDelta.y*CAMERA_FREE_MOUSE_SENSITIVITY)*sinf(cameraAngle.x)*sinf(cameraAngle.y))*(cameraTargetDistance/CAMERA_FREE_PANNING_DIVIDER); - camera->target.y += ((mousePositionDelta.y*CAMERA_FREE_MOUSE_SENSITIVITY)*cosf(cameraAngle.y))*(cameraTargetDistance/CAMERA_FREE_PANNING_DIVIDER); - camera->target.z += ((mousePositionDelta.x*CAMERA_FREE_MOUSE_SENSITIVITY)*sinf(cameraAngle.x) + (mousePositionDelta.y*CAMERA_FREE_MOUSE_SENSITIVITY)*cosf(cameraAngle.x)*sinf(cameraAngle.y))*(cameraTargetDistance/CAMERA_FREE_PANNING_DIVIDER); - } - } - - } break; - case CAMERA_ORBITAL: - { - cameraAngle.x += CAMERA_ORBITAL_SPEED; // Camera orbit angle - cameraTargetDistance -= (mouseWheelMove*CAMERA_MOUSE_SCROLL_SENSITIVITY); // Camera zoom - - // Camera distance clamp - if (cameraTargetDistance < CAMERA_THIRD_PERSON_DISTANCE_CLAMP) cameraTargetDistance = CAMERA_THIRD_PERSON_DISTANCE_CLAMP; - - } break; - case CAMERA_FIRST_PERSON: - case CAMERA_THIRD_PERSON: - { - camera->position.x += (sinf(cameraAngle.x)*direction[MOVE_BACK] - - sinf(cameraAngle.x)*direction[MOVE_FRONT] - - cosf(cameraAngle.x)*direction[MOVE_LEFT] + - cosf(cameraAngle.x)*direction[MOVE_RIGHT])/PLAYER_MOVEMENT_SENSITIVITY; - - camera->position.y += (sinf(cameraAngle.y)*direction[MOVE_FRONT] - - sinf(cameraAngle.y)*direction[MOVE_BACK] + - 1.0f*direction[MOVE_UP] - 1.0f*direction[MOVE_DOWN])/PLAYER_MOVEMENT_SENSITIVITY; - - camera->position.z += (cosf(cameraAngle.x)*direction[MOVE_BACK] - - cosf(cameraAngle.x)*direction[MOVE_FRONT] + - sinf(cameraAngle.x)*direction[MOVE_LEFT] - - sinf(cameraAngle.x)*direction[MOVE_RIGHT])/PLAYER_MOVEMENT_SENSITIVITY; - - bool isMoving = false; // Required for swinging - - for (int i = 0; i < 6; i++) if (direction[i]) { isMoving = true; break; } - - // Camera orientation calculation - cameraAngle.x += (mousePositionDelta.x*-CAMERA_MOUSE_MOVE_SENSITIVITY); - cameraAngle.y += (mousePositionDelta.y*-CAMERA_MOUSE_MOVE_SENSITIVITY); - - if (cameraMode == CAMERA_THIRD_PERSON) - { - // Angle clamp - if (cameraAngle.y > CAMERA_THIRD_PERSON_MIN_CLAMP*DEG2RAD) cameraAngle.y = CAMERA_THIRD_PERSON_MIN_CLAMP*DEG2RAD; - else if (cameraAngle.y < CAMERA_THIRD_PERSON_MAX_CLAMP*DEG2RAD) cameraAngle.y = CAMERA_THIRD_PERSON_MAX_CLAMP*DEG2RAD; - - // Camera zoom - cameraTargetDistance -= (mouseWheelMove*CAMERA_MOUSE_SCROLL_SENSITIVITY); - - // Camera distance clamp - if (cameraTargetDistance < CAMERA_THIRD_PERSON_DISTANCE_CLAMP) cameraTargetDistance = CAMERA_THIRD_PERSON_DISTANCE_CLAMP; - - // Camera is always looking at player - camera->target.x = camera->position.x + CAMERA_THIRD_PERSON_OFFSET.x*cosf(cameraAngle.x) + CAMERA_THIRD_PERSON_OFFSET.z*sinf(cameraAngle.x); - camera->target.y = camera->position.y + CAMERA_THIRD_PERSON_OFFSET.y; - camera->target.z = camera->position.z + CAMERA_THIRD_PERSON_OFFSET.z*sinf(cameraAngle.x) - CAMERA_THIRD_PERSON_OFFSET.x*sinf(cameraAngle.x); - } - else // CAMERA_FIRST_PERSON - { - // Angle clamp - if (cameraAngle.y > CAMERA_FIRST_PERSON_MIN_CLAMP*DEG2RAD) cameraAngle.y = CAMERA_FIRST_PERSON_MIN_CLAMP*DEG2RAD; - else if (cameraAngle.y < CAMERA_FIRST_PERSON_MAX_CLAMP*DEG2RAD) cameraAngle.y = CAMERA_FIRST_PERSON_MAX_CLAMP*DEG2RAD; - - // Camera is always looking at player - camera->target.x = camera->position.x - sinf(cameraAngle.x)*CAMERA_FIRST_PERSON_FOCUS_DISTANCE; - camera->target.y = camera->position.y + sinf(cameraAngle.y)*CAMERA_FIRST_PERSON_FOCUS_DISTANCE; - camera->target.z = camera->position.z - cosf(cameraAngle.x)*CAMERA_FIRST_PERSON_FOCUS_DISTANCE; - - if (isMoving) swingCounter++; - - // Camera position update - // NOTE: On CAMERA_FIRST_PERSON player Y-movement is limited to player 'eyes position' - camera->position.y = playerEyesPosition - sinf(swingCounter/CAMERA_FIRST_PERSON_STEP_TRIGONOMETRIC_DIVIDER)/CAMERA_FIRST_PERSON_STEP_DIVIDER; - - camera->up.x = sinf(swingCounter/(CAMERA_FIRST_PERSON_STEP_TRIGONOMETRIC_DIVIDER*2))/CAMERA_FIRST_PERSON_WAVING_DIVIDER; - camera->up.z = -sinf(swingCounter/(CAMERA_FIRST_PERSON_STEP_TRIGONOMETRIC_DIVIDER*2))/CAMERA_FIRST_PERSON_WAVING_DIVIDER; - } - } break; - default: break; - } - - // Update camera position with changes - if ((cameraMode == CAMERA_FREE) || - (cameraMode == CAMERA_ORBITAL) || - (cameraMode == CAMERA_THIRD_PERSON)) - { - // TODO: It seems camera->position is not correctly updated or some rounding issue makes the camera move straight to camera->target... - camera->position.x = sinf(cameraAngle.x)*cameraTargetDistance*cosf(cameraAngle.y) + camera->target.x; - if (cameraAngle.y <= 0.0f) camera->position.y = sinf(cameraAngle.y)*cameraTargetDistance*sinf(cameraAngle.y) + camera->target.y; - else camera->position.y = -sinf(cameraAngle.y)*cameraTargetDistance*sinf(cameraAngle.y) + camera->target.y; - camera->position.z = cosf(cameraAngle.x)*cameraTargetDistance*cosf(cameraAngle.y) + camera->target.z; - } -} - -// Set camera pan key to combine with mouse movement (free camera) -void SetCameraPanControl(int panKey) { cameraPanControlKey = panKey; } - -// Set camera alt key to combine with mouse movement (free camera) -void SetCameraAltControl(int altKey) { cameraAltControlKey = altKey; } - -// Set camera smooth zoom key to combine with mouse (free camera) -void SetCameraSmoothZoomControl(int szKey) { cameraSmoothZoomControlKey = szKey; } - -// Set camera move controls (1st person and 3rd person cameras) -void SetCameraMoveControls(int frontKey, int backKey, int rightKey, int leftKey, int upKey, int downKey) -{ - cameraMoveControl[MOVE_FRONT] = frontKey; - cameraMoveControl[MOVE_BACK] = backKey; - cameraMoveControl[MOVE_RIGHT] = rightKey; - cameraMoveControl[MOVE_LEFT] = leftKey; - cameraMoveControl[MOVE_UP] = upKey; - cameraMoveControl[MOVE_DOWN] = downKey; -} - -#endif // CAMERA_IMPLEMENTATION diff --git a/game/src/libs/raylib/core.c b/game/src/libs/raylib/core.c deleted file mode 100644 index 5172a71..0000000 --- a/game/src/libs/raylib/core.c +++ /dev/null @@ -1,3475 +0,0 @@ -/********************************************************************************************** -* -* raylib.core - Basic functions to manage windows, OpenGL context and input on multiple platforms -* -* PLATFORMS SUPPORTED: -* - Windows (win32/Win64) -* - Linux (tested on Ubuntu) -* - OSX (Mac) -* - Android (ARM or ARM64) -* - Raspberry Pi (Raspbian) -* - HTML5 (Chrome, Firefox) -* -* CONFIGURATION: -* -* #define PLATFORM_DESKTOP -* Windowing and input system configured for desktop platforms: Windows, Linux, OSX (managed by GLFW3 library) -* NOTE: Oculus Rift CV1 requires PLATFORM_DESKTOP for mirror rendering - View [rlgl] module to enable it -* -* #define PLATFORM_ANDROID -* Windowing and input system configured for Android device, app activity managed internally in this module. -* NOTE: OpenGL ES 2.0 is required and graphic device is managed by EGL -* -* #define PLATFORM_RPI -* Windowing and input system configured for Raspberry Pi (tested on Raspbian), graphic device is managed by EGL -* and inputs are processed is raw mode, reading from /dev/input/ -* -* #define PLATFORM_WEB -* Windowing and input system configured for HTML5 (run on browser), code converted from C to asm.js -* using emscripten compiler. OpenGL ES 2.0 required for direct translation to WebGL equivalent code. -* -* #define SUPPORT_DEFAULT_FONT (default) -* 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) -* -* #define SUPPORT_CAMERA_SYSTEM -* Camera module is included (camera.h) and multiple predefined cameras are available: free, 1st/3rd person, orbital -* -* #define SUPPORT_GESTURES_SYSTEM -* Gestures module is included (gestures.h) to support gestures detection: tap, hold, swipe, drag -* -* #define SUPPORT_MOUSE_GESTURES -* Mouse gestures are directly mapped like touches and processed by gestures system. -* -* #define SUPPORT_BUSY_WAIT_LOOP -* Use busy wait loop for timming sync, if not defined, a high-resolution timer is setup and used -* -* #define SUPPORT_GIF_RECORDING -* Allow automatic gif recording of current screen pressing CTRL+F12, defined in KeyCallback() -* -* DEPENDENCIES: -* GLFW3 - Manage graphic device, OpenGL context and inputs on PLATFORM_DESKTOP (Windows, Linux, OSX) -* raymath - 3D math functionality (Vector3, Matrix, Quaternion) -* camera - Multiple 3D camera modes (free, orbital, 1st person, 3rd person) -* gestures - Gestures system for touch-ready devices (or simulated from mouse inputs) -* -* -* LICENSE: zlib/libpng -* -* Copyright (c) 2014-2017 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. -* -* Permission is granted to anyone to use this software for any purpose, including commercial -* applications, and to alter it and redistribute it freely, subject to the following restrictions: -* -* 1. The origin of this software must not be misrepresented; you must not claim that you -* wrote the original software. If you use this software in a product, an acknowledgment -* in the product documentation would be appreciated but is not required. -* -* 2. Altered source versions must be plainly marked as such, and must not be misrepresented -* as being the original software. -* -* 3. This notice may not be removed or altered from any source distribution. -* -**********************************************************************************************/ - -// Default configuration flags (supported features) -//------------------------------------------------- -#define SUPPORT_DEFAULT_FONT -#define SUPPORT_MOUSE_GESTURES -#define SUPPORT_CAMERA_SYSTEM -#define SUPPORT_GESTURES_SYSTEM -#define SUPPORT_BUSY_WAIT_LOOP -#define SUPPORT_GIF_RECORDING -//------------------------------------------------- - -#include "raylib.h" - -#include "rlgl.h" // raylib OpenGL abstraction layer to OpenGL 1.1, 3.3+ or ES2 -#include "utils.h" // Required for: fopen() Android mapping - -#define RAYMATH_IMPLEMENTATION // Use raymath as a header-only library (includes implementation) -#define RAYMATH_EXTERN_INLINE // Compile raymath functions as static inline (remember, it's a compiler hint) -#include "raymath.h" // Required for: Vector3 and Matrix functions - -#if defined(SUPPORT_GESTURES_SYSTEM) - #define GESTURES_IMPLEMENTATION - #include "gestures.h" // Gestures detection functionality -#endif - -#if defined(SUPPORT_CAMERA_SYSTEM) && !defined(PLATFORM_ANDROID) - #define CAMERA_IMPLEMENTATION - #include "camera.h" // Camera system functionality -#endif - -#if defined(SUPPORT_GIF_RECORDING) - #define RGIF_IMPLEMENTATION - #include "external/rgif.h" // Support GIF recording -#endif - -#if defined(__linux__) || defined(PLATFORM_WEB) - #define _POSIX_C_SOURCE 199309L // Required for CLOCK_MONOTONIC if compiled with c99 without gnu ext. -#endif - -#include // Standard input / output lib -#include // Required for: malloc(), free(), rand(), atexit() -#include // Required for: typedef unsigned long long int uint64_t, used by hi-res timer -#include // Required for: time() - Android/RPI hi-res timer (NOTE: Linux only!) -#include // Required for: tan() [Used in Begin3dMode() to set perspective] -#include // Required for: strrchr(), strcmp() -//#include // Macros for reporting and retrieving error conditions through error codes - -#ifdef _WIN32 - #include // Required for: _getch(), _chdir() - #define GETCWD _getcwd // NOTE: MSDN recommends not to use getcwd(), chdir() - #define CHDIR _chdir -#else - #include "unistd.h" // Required for: getch(), chdir() (POSIX) - #define GETCWD getcwd - #define CHDIR chdir -#endif - -#if defined(__linux__) || defined(PLATFORM_WEB) - #include // Required for: timespec, nanosleep(), select() - POSIX -#elif defined(__APPLE__) - #include // Required for: usleep() -#endif - -#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) - //#define GLFW_INCLUDE_NONE // Disable the standard OpenGL header inclusion on GLFW3 - #include // GLFW3 library: Windows, OpenGL context and Input management - - #if defined(__linux__) - #define GLFW_EXPOSE_NATIVE_X11 // Linux specific definitions for getting - #define GLFW_EXPOSE_NATIVE_GLX // native functions like glfwGetX11Window - #include // which are required for hiding mouse - #endif - //#include // OpenGL functions (GLFW3 already includes gl.h) - //#define GLFW_DLL // Using GLFW DLL on Windows -> No, we use static version! - - #if !defined(SUPPORT_BUSY_WAIT_LOOP) && defined(_WIN32) - // NOTE: Those functions require linking with winmm library - __stdcall unsigned int timeBeginPeriod(unsigned int uPeriod); - __stdcall unsigned int timeEndPeriod(unsigned int uPeriod); - #endif -#endif - -#if defined(PLATFORM_ANDROID) - //#include // Android sensors functions (accelerometer, gyroscope, light...) - #include // Defines AWINDOW_FLAG_FULLSCREEN and others - #include // Defines basic app state struct and manages activity - - #include // Khronos EGL library - Native platform display device control functions - #include // Khronos OpenGL ES 2.0 library -#endif - -#if defined(PLATFORM_RPI) - #include // POSIX file control definitions - open(), creat(), fcntl() - #include // POSIX standard function definitions - read(), close(), STDIN_FILENO - #include // POSIX terminal control definitions - tcgetattr(), tcsetattr() - #include // POSIX threads management (mouse input) - - #include // UNIX System call for device-specific input/output operations - ioctl() - #include // Linux: KDSKBMODE, K_MEDIUMRAM constants definition - #include // Linux: Keycodes constants definition (KEY_A, ...) - #include // Linux: Joystick support library - - #include "bcm_host.h" // Raspberry Pi VideoCore IV access functions - - #include "EGL/egl.h" // Khronos EGL library - Native platform display device control functions - #include "EGL/eglext.h" // Khronos EGL library - Extensions - #include "GLES2/gl2.h" // Khronos OpenGL ES 2.0 library -#endif - -#if defined(PLATFORM_WEB) - #include - #include -#endif - -//---------------------------------------------------------------------------------- -// Defines and Macros -//---------------------------------------------------------------------------------- -#if defined(PLATFORM_RPI) - // Old device inputs system - #define DEFAULT_KEYBOARD_DEV STDIN_FILENO // Standard input - #define DEFAULT_MOUSE_DEV "/dev/input/mouse0" // Mouse input - #define DEFAULT_TOUCH_DEV "/dev/input/event4" // Touch input virtual device (created by ts_uinput) - #define DEFAULT_GAMEPAD_DEV "/dev/input/js" // Gamepad input (base dev for all gamepads: js0, js1, ...) - - // New device input events (evdev) (must be detected) - //#define DEFAULT_KEYBOARD_DEV "/dev/input/eventN" - //#define DEFAULT_MOUSE_DEV "/dev/input/eventN" - //#define DEFAULT_GAMEPAD_DEV "/dev/input/eventN" - - #define MOUSE_SENSITIVITY 0.8f -#endif - -#define MAX_GAMEPADS 4 // Max number of gamepads supported -#define MAX_GAMEPAD_BUTTONS 32 // Max bumber of buttons supported (per gamepad) -#define MAX_GAMEPAD_AXIS 8 // Max number of axis supported (per gamepad) - -#define STORAGE_FILENAME "storage.data" - -//---------------------------------------------------------------------------------- -// Types and Structures Definition -//---------------------------------------------------------------------------------- -// ... - -//---------------------------------------------------------------------------------- -// Global Variables Definition -//---------------------------------------------------------------------------------- -#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) -static GLFWwindow *window; // Native window (graphic device) -static bool windowMinimized = false; -#endif - -#if defined(PLATFORM_ANDROID) -static struct android_app *app; // Android activity -static struct android_poll_source *source; // Android events polling source -static int ident, events; // Android ALooper_pollAll() variables -static const char *internalDataPath; // Android internal data path to write data (/data/data//files) - -static bool windowReady = false; // Used to detect display initialization -static bool appEnabled = true; // Used to detec if app is active -static bool contextRebindRequired = false; // Used to know context rebind required -#endif - -#if defined(PLATFORM_RPI) -static EGL_DISPMANX_WINDOW_T nativeWindow; // Native window (graphic device) - -// Keyboard input variables -// NOTE: For keyboard we will use the standard input (but reconfigured...) -static struct termios defaultKeyboardSettings; // Used to store default keyboard settings -static int defaultKeyboardMode; // Used to store default keyboard mode - -// Mouse input variables -static int mouseStream = -1; // Mouse device file descriptor -static bool mouseReady = false; // Flag to know if mouse is ready -static pthread_t mouseThreadId; // Mouse reading thread id - -// Touch input variables -static int touchStream = -1; // Touch device file descriptor -static bool touchReady = false; // Flag to know if touch interface is ready -static pthread_t touchThreadId; // Touch reading thread id - -// Gamepad input variables -static int gamepadStream[MAX_GAMEPADS] = { -1 };// Gamepad device file descriptor -static pthread_t gamepadThreadId; // Gamepad reading thread id -static char gamepadName[64]; // Gamepad name holder -#endif - -#if defined(PLATFORM_ANDROID) || defined(PLATFORM_RPI) -static EGLDisplay display; // Native display device (physical screen connection) -static EGLSurface surface; // Surface to draw on, framebuffers (connected to context) -static EGLContext context; // Graphic context, mode in which drawing can be done -static EGLConfig config; // Graphic config -static uint64_t baseTime; // Base time measure for hi-res timer -static bool windowShouldClose = false; // Flag to set window for closing -#endif - -// Display size-related data -static unsigned int displayWidth, displayHeight; // Display width and height (monitor, device-screen, LCD, ...) -static int screenWidth, screenHeight; // Screen width and height (used render area) -static int renderWidth, renderHeight; // Framebuffer width and height (render area, including black bars if required) -static int renderOffsetX = 0; // Offset X from render area (must be divided by 2) -static int renderOffsetY = 0; // Offset Y from render area (must be divided by 2) -static bool fullscreen = false; // Fullscreen mode (useful only for PLATFORM_DESKTOP) -static Matrix downscaleView; // Matrix to downscale view (in case screen size bigger than display size) - -#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI) || defined(PLATFORM_WEB) -static const char *windowTitle; // Window text title... -static bool cursorOnScreen = false; // Tracks if cursor is inside client area -static bool cursorHidden = false; // Track if cursor is hidden -static int screenshotCounter = 0; // Screenshots counter - -// Register mouse states -static char previousMouseState[3] = { 0 }; // Registers previous mouse button state -static char currentMouseState[3] = { 0 }; // Registers current mouse button state -static int previousMouseWheelY = 0; // Registers previous mouse wheel variation -static int currentMouseWheelY = 0; // Registers current mouse wheel variation - -// Register gamepads states -static bool gamepadReady[MAX_GAMEPADS] = { false }; // Flag to know if gamepad is ready -static float gamepadAxisState[MAX_GAMEPADS][MAX_GAMEPAD_AXIS]; // Gamepad axis state -static char previousGamepadState[MAX_GAMEPADS][MAX_GAMEPAD_BUTTONS]; // Previous gamepad buttons state -static char currentGamepadState[MAX_GAMEPADS][MAX_GAMEPAD_BUTTONS]; // Current gamepad buttons state - -// Keyboard configuration -static int exitKey = KEY_ESCAPE; // Default exit key (ESC) -#endif - -// Register keyboard states -static char previousKeyState[512] = { 0 }; // Registers previous frame key state -static char currentKeyState[512] = { 0 }; // Registers current frame key state - -static int lastKeyPressed = -1; // Register last key pressed -static int lastGamepadButtonPressed = -1; // Register last gamepad button pressed -static int gamepadAxisCount = 0; // Register number of available gamepad axis - -static Vector2 mousePosition; // Mouse position on screen - -#if defined(PLATFORM_WEB) -static bool toggleCursorLock = false; // Ask for cursor pointer lock on next click -#endif - -static Vector2 touchPosition[MAX_TOUCH_POINTS]; // Touch position on screen - -#if defined(PLATFORM_DESKTOP) -static char **dropFilesPath; // Store dropped files paths as strings -static int dropFilesCount = 0; // Count stored strings -#endif - -static double currentTime, previousTime; // Used to track timmings -static double updateTime, drawTime; // Time measures for update and draw -static double frameTime = 0.0; // Time measure for one frame -static double targetTime = 0.0; // Desired time for one frame, if 0 not applied - -static char configFlags = 0; // Configuration flags (bit based) -static bool showLogo = false; // Track if showing logo at init is enabled - -#if defined(SUPPORT_GIF_RECORDING) -static int gifFramesCounter = 0; -static bool gifRecording = false; -#endif - -//---------------------------------------------------------------------------------- -// Other Modules Functions Declaration (required by core) -//---------------------------------------------------------------------------------- -#if defined(SUPPORT_DEFAULT_FONT) -extern void LoadDefaultFont(void); // [Module: text] Loads default font on InitWindow() -extern void UnloadDefaultFont(void); // [Module: text] Unloads default font from GPU memory -#endif - -//---------------------------------------------------------------------------------- -// Module specific Functions Declaration -//---------------------------------------------------------------------------------- -static void InitGraphicsDevice(int width, int height); // Initialize graphics device -static void SetupFramebufferSize(int displayWidth, int displayHeight); -static void InitTimer(void); // Initialize timer -static double GetTime(void); // Returns time since InitTimer() was run -static void Wait(float ms); // Wait for some milliseconds (stop program execution) -static bool GetKeyStatus(int key); // Returns if a key has been pressed -static bool GetMouseButtonStatus(int button); // Returns if a mouse button has been pressed -static void PollInputEvents(void); // Register user events -static void SwapBuffers(void); // Copy back buffer to front buffers -static void LogoAnimation(void); // Plays raylib logo appearing animation -static void SetupViewport(void); // Set viewport parameters - -#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) -static void ErrorCallback(int error, const char *description); // GLFW3 Error Callback, runs on GLFW3 error -static void KeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods); // GLFW3 Keyboard Callback, runs on key pressed -static void MouseButtonCallback(GLFWwindow *window, int button, int action, int mods); // GLFW3 Mouse Button Callback, runs on mouse button pressed -static void MouseCursorPosCallback(GLFWwindow *window, double x, double y); // GLFW3 Cursor Position Callback, runs on mouse move -static void CharCallback(GLFWwindow *window, unsigned int key); // GLFW3 Char Key Callback, runs on key pressed (get char value) -static void ScrollCallback(GLFWwindow *window, double xoffset, double yoffset); // GLFW3 Srolling Callback, runs on mouse wheel -static void CursorEnterCallback(GLFWwindow *window, int enter); // GLFW3 Cursor Enter Callback, cursor enters client area -static void WindowSizeCallback(GLFWwindow *window, int width, int height); // GLFW3 WindowSize Callback, runs when window is resized -static void WindowIconifyCallback(GLFWwindow *window, int iconified); // GLFW3 WindowIconify Callback, runs when window is minimized/restored -#endif - -#if defined(PLATFORM_DESKTOP) -static void WindowDropCallback(GLFWwindow *window, int count, const char **paths); // GLFW3 Window Drop Callback, runs when drop files into window -#endif - -#if defined(PLATFORM_ANDROID) -static void AndroidCommandCallback(struct android_app *app, int32_t cmd); // Process Android activity lifecycle commands -static int32_t AndroidInputCallback(struct android_app *app, AInputEvent *event); // Process Android inputs -#endif - -#if defined(PLATFORM_WEB) -static EM_BOOL EmscriptenFullscreenChangeCallback(int eventType, const EmscriptenFullscreenChangeEvent *e, void *userData); -static EM_BOOL EmscriptenKeyboardCallback(int eventType, const EmscriptenKeyboardEvent *keyEvent, void *userData); -static EM_BOOL EmscriptenMouseCallback(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData); -static EM_BOOL EmscriptenTouchCallback(int eventType, const EmscriptenTouchEvent *touchEvent, void *userData); -static EM_BOOL EmscriptenGamepadCallback(int eventType, const EmscriptenGamepadEvent *gamepadEvent, void *userData); -#endif - -#if defined(PLATFORM_RPI) -static void InitKeyboard(void); // Init raw keyboard system (standard input reading) -static void ProcessKeyboard(void); // Process keyboard events -static void RestoreKeyboard(void); // Restore keyboard system -static void InitMouse(void); // Mouse initialization (including mouse thread) -static void *MouseThread(void *arg); // Mouse reading thread -static void InitTouch(void); // Touch device initialization (including touch thread) -static void *TouchThread(void *arg); // Touch device reading thread -static void InitGamepad(void); // Init raw gamepad input -static void *GamepadThread(void *arg); // Mouse reading thread -#endif - -#if defined(_WIN32) - // NOTE: We include Sleep() function signature here to avoid windows.h inclusion - void __stdcall Sleep(unsigned long msTimeout); // Required for Wait() -#endif - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Window and OpenGL Context Functions -//---------------------------------------------------------------------------------- -#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI) || defined(PLATFORM_WEB) -// Initialize window and OpenGL context -void InitWindow(int width, int height, const char *title) -{ - TraceLog(LOG_INFO, "Initializing raylib (v1.8.0)"); - - // Store window title (could be useful...) - windowTitle = title; - - // Init graphics device (display device and OpenGL context) - InitGraphicsDevice(width, height); - -#if defined(SUPPORT_DEFAULT_FONT) - // Load default font - // NOTE: External function (defined in module: text) - LoadDefaultFont(); -#endif - - // Init hi-res timer - InitTimer(); - -#if defined(PLATFORM_RPI) - // Init raw input system - InitMouse(); // Mouse init - InitTouch(); // Touch init - InitKeyboard(); // Keyboard init - InitGamepad(); // Gamepad init -#endif - -#if defined(PLATFORM_WEB) - emscripten_set_fullscreenchange_callback(0, 0, 1, EmscriptenFullscreenChangeCallback); - - // Support keyboard events - emscripten_set_keypress_callback("#canvas", NULL, 1, EmscriptenKeyboardCallback); - - // Support mouse events - emscripten_set_click_callback("#canvas", NULL, 1, EmscriptenMouseCallback); - - // Support touch events - emscripten_set_touchstart_callback("#canvas", NULL, 1, EmscriptenTouchCallback); - emscripten_set_touchend_callback("#canvas", NULL, 1, EmscriptenTouchCallback); - emscripten_set_touchmove_callback("#canvas", NULL, 1, EmscriptenTouchCallback); - emscripten_set_touchcancel_callback("#canvas", NULL, 1, EmscriptenTouchCallback); - //emscripten_set_touchstart_callback(0, NULL, 1, Emscripten_HandleTouch); - //emscripten_set_touchend_callback("#canvas", data, 0, Emscripten_HandleTouch); - - // Support gamepad events (not provided by GLFW3 on emscripten) - emscripten_set_gamepadconnected_callback(NULL, 1, EmscriptenGamepadCallback); - emscripten_set_gamepaddisconnected_callback(NULL, 1, EmscriptenGamepadCallback); -#endif - - mousePosition.x = (float)screenWidth/2.0f; - mousePosition.y = (float)screenHeight/2.0f; - - // raylib logo appearing animation (if enabled) - if (showLogo) - { - SetTargetFPS(60); - LogoAnimation(); - } -} -#endif - -#if defined(PLATFORM_ANDROID) -// Initialize Android activity -void InitWindow(int width, int height, void *state) -{ - TraceLog(LOG_INFO, "Initializing raylib (v1.8.0)"); - - screenWidth = width; - screenHeight = height; - - app = (struct android_app *)state; - internalDataPath = app->activity->internalDataPath; - - // Set desired windows flags before initializing anything - ANativeActivity_setWindowFlags(app->activity, AWINDOW_FLAG_FULLSCREEN, 0); //AWINDOW_FLAG_SCALED, AWINDOW_FLAG_DITHER - //ANativeActivity_setWindowFlags(app->activity, AWINDOW_FLAG_FORCE_NOT_FULLSCREEN, AWINDOW_FLAG_FULLSCREEN); - - int orientation = AConfiguration_getOrientation(app->config); - - if (orientation == ACONFIGURATION_ORIENTATION_PORT) TraceLog(LOG_INFO, "PORTRAIT window orientation"); - else if (orientation == ACONFIGURATION_ORIENTATION_LAND) TraceLog(LOG_INFO, "LANDSCAPE window orientation"); - - // TODO: Automatic orientation doesn't seem to work - if (width <= height) - { - AConfiguration_setOrientation(app->config, ACONFIGURATION_ORIENTATION_PORT); - TraceLog(LOG_WARNING, "Window set to portraid mode"); - } - else - { - AConfiguration_setOrientation(app->config, ACONFIGURATION_ORIENTATION_LAND); - TraceLog(LOG_WARNING, "Window set to landscape mode"); - } - - //AConfiguration_getDensity(app->config); - //AConfiguration_getKeyboard(app->config); - //AConfiguration_getScreenSize(app->config); - //AConfiguration_getScreenLong(app->config); - - //state->userData = &engine; - app->onAppCmd = AndroidCommandCallback; - app->onInputEvent = AndroidInputCallback; - - InitAssetManager(app->activity->assetManager); - - TraceLog(LOG_INFO, "Android app initialized successfully"); - - // Wait for window to be initialized (display and context) - while (!windowReady) - { - // Process events loop - while ((ident = ALooper_pollAll(0, NULL, &events,(void**)&source)) >= 0) - { - // Process this event - if (source != NULL) source->process(app, source); - - // NOTE: Never close window, native activity is controlled by the system! - //if (app->destroyRequested != 0) windowShouldClose = true; - } - } -} -#endif - -// Close window and unload OpenGL context -void CloseWindow(void) -{ -#if defined(SUPPORT_GIF_RECORDING) - if (gifRecording) - { - GifEnd(); - gifRecording = false; - } -#endif - -#if defined(SUPPORT_DEFAULT_FONT) - UnloadDefaultFont(); -#endif - - rlglClose(); // De-init rlgl - -#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) - glfwDestroyWindow(window); - glfwTerminate(); -#endif - -#if !defined(SUPPORT_BUSY_WAIT_LOOP) && defined(_WIN32) - timeEndPeriod(1); // Restore time period -#endif - -#if defined(PLATFORM_ANDROID) || defined(PLATFORM_RPI) - // Close surface, context and display - if (display != EGL_NO_DISPLAY) - { - eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); - - if (surface != EGL_NO_SURFACE) - { - eglDestroySurface(display, surface); - surface = EGL_NO_SURFACE; - } - - if (context != EGL_NO_CONTEXT) - { - eglDestroyContext(display, context); - context = EGL_NO_CONTEXT; - } - - eglTerminate(display); - display = EGL_NO_DISPLAY; - } -#endif - -#if defined(PLATFORM_RPI) - // Wait for mouse and gamepad threads to finish before closing - // NOTE: Those threads should already have finished at this point - // because they are controlled by windowShouldClose variable - - windowShouldClose = true; // Added to force threads to exit when the close window is called - - pthread_join(mouseThreadId, NULL); - pthread_join(touchThreadId, NULL); - pthread_join(gamepadThreadId, NULL); -#endif - - TraceLog(LOG_INFO, "Window closed successfully"); -} - -// Check if KEY_ESCAPE pressed or Close icon pressed -bool WindowShouldClose(void) -{ -#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) - // While window minimized, stop loop execution - while (windowMinimized) glfwWaitEvents(); - - return (glfwWindowShouldClose(window)); -#endif - -#if defined(PLATFORM_ANDROID) || defined(PLATFORM_RPI) - return windowShouldClose; -#endif -} - -// Check if window has been minimized (or lost focus) -bool IsWindowMinimized(void) -{ -#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) - return windowMinimized; -#else - return false; -#endif -} - -// Toggle fullscreen mode (only PLATFORM_DESKTOP) -void ToggleFullscreen(void) -{ -#if defined(PLATFORM_DESKTOP) - fullscreen = !fullscreen; // Toggle fullscreen flag - - // NOTE: glfwSetWindowMonitor() doesn't work properly (bugs) - if (fullscreen) glfwSetWindowMonitor(window, glfwGetPrimaryMonitor(), 0, 0, screenWidth, screenHeight, GLFW_DONT_CARE); - else glfwSetWindowMonitor(window, NULL, 0, 0, screenWidth, screenHeight, GLFW_DONT_CARE); -#endif - -#if defined(PLATFORM_ANDROID) || defined(PLATFORM_RPI) - TraceLog(LOG_WARNING, "Could not toggle to windowed mode"); -#endif -} - -// Set icon for window (only PLATFORM_DESKTOP) -void SetWindowIcon(Image image) -{ -#if defined(PLATFORM_DESKTOP) - ImageFormat(&image, UNCOMPRESSED_R8G8B8A8); - - GLFWimage icon[1]; - - icon[0].width = image.width; - icon[0].height = image.height; - icon[0].pixels = (unsigned char *)image.data; - - // NOTE: We only support one image icon - glfwSetWindowIcon(window, 1, icon); - - // TODO: Support multi-image icons --> image.mipmaps -#endif -} - -// Set title for window (only PLATFORM_DESKTOP) -void SetWindowTitle(const char *title) -{ -#if defined(PLATFORM_DESKTOP) - glfwSetWindowTitle(window, title); -#endif -} - -// Set window position on screen (windowed mode) -void SetWindowPosition(int x, int y) -{ -#if defined(PLATFORM_DESKTOP) - glfwSetWindowPos(window, x, y); -#endif -} - -// Set monitor for the current window (fullscreen mode) -void SetWindowMonitor(int monitor) -{ -#if defined(PLATFORM_DESKTOP) - int monitorCount; - GLFWmonitor** monitors = glfwGetMonitors(&monitorCount); - - if ((monitor >= 0) && (monitor < monitorCount)) - { - glfwSetWindowMonitor(window, monitors[monitor], 0, 0, screenWidth, screenHeight, GLFW_DONT_CARE); - TraceLog(LOG_INFO, "Selected fullscreen monitor: [%i] %s", monitor, glfwGetMonitorName(monitors[monitor])); - } - else TraceLog(LOG_WARNING, "Selected monitor not found"); -#endif -} - -// Set window minimum dimensions (FLAG_WINDOW_RESIZABLE) -void SetWindowMinSize(int width, int height) -{ -#if defined(PLATFORM_DESKTOP) - const GLFWvidmode *mode = glfwGetVideoMode(glfwGetPrimaryMonitor()); - glfwSetWindowSizeLimits(window, width, height, mode->width, mode->height); -#endif -} - -// Get current screen width -int GetScreenWidth(void) -{ - return screenWidth; -} - -// Get current screen height -int GetScreenHeight(void) -{ - return screenHeight; -} - -#if !defined(PLATFORM_ANDROID) -// Show mouse cursor -void ShowCursor() -{ -#if defined(PLATFORM_DESKTOP) - #if defined(__linux__) - XUndefineCursor(glfwGetX11Display(), glfwGetX11Window(window)); - #else - glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); - #endif -#endif - cursorHidden = false; -} - -// Hides mouse cursor -void HideCursor() -{ -#if defined(PLATFORM_DESKTOP) - #if defined(__linux__) - XColor col; - const char nil[] = {0}; - - Pixmap pix = XCreateBitmapFromData(glfwGetX11Display(), glfwGetX11Window(window), nil, 1, 1); - Cursor cur = XCreatePixmapCursor(glfwGetX11Display(), pix, pix, &col, &col, 0, 0); - - XDefineCursor(glfwGetX11Display(), glfwGetX11Window(window), cur); - XFreeCursor(glfwGetX11Display(), cur); - #else - glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); - #endif -#endif - cursorHidden = true; -} - -// Check if cursor is not visible -bool IsCursorHidden() -{ - return cursorHidden; -} - -// Enables cursor (unlock cursor) -void EnableCursor() -{ -#if defined(PLATFORM_DESKTOP) - glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); -#endif -#if defined(PLATFORM_WEB) - toggleCursorLock = true; -#endif - cursorHidden = false; -} - -// Disables cursor (lock cursor) -void DisableCursor() -{ -#if defined(PLATFORM_DESKTOP) - glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); -#endif -#if defined(PLATFORM_WEB) - toggleCursorLock = true; -#endif - cursorHidden = true; -} -#endif // !defined(PLATFORM_ANDROID) - -// Set background color (framebuffer clear color) -void ClearBackground(Color color) -{ - // Clear full framebuffer (not only render area) to color - rlClearColor(color.r, color.g, color.b, color.a); -} - -// Setup canvas (framebuffer) to start drawing -void BeginDrawing(void) -{ - currentTime = GetTime(); // Number of elapsed seconds since InitTimer() was called - updateTime = currentTime - previousTime; - previousTime = currentTime; - - rlClearScreenBuffers(); // Clear current framebuffers - rlLoadIdentity(); // Reset current matrix (MODELVIEW) - rlMultMatrixf(MatrixToFloat(downscaleView)); // If downscale required, apply it here - - //rlTranslatef(0.375, 0.375, 0); // HACK to have 2D pixel-perfect drawing on OpenGL 1.1 - // NOTE: Not required with OpenGL 3.3+ -} - -// End canvas drawing and swap buffers (double buffering) -void EndDrawing(void) -{ - rlglDraw(); // Draw Buffers (Only OpenGL 3+ and ES2) - -#if defined(SUPPORT_GIF_RECORDING) - - #define GIF_RECORD_FRAMERATE 10 - - if (gifRecording) - { - gifFramesCounter++; - - // NOTE: We record one gif frame every 10 game frames - if ((gifFramesCounter%GIF_RECORD_FRAMERATE) == 0) - { - // Get image data for the current frame (from backbuffer) - // NOTE: This process is very slow... :( - unsigned char *screenData = rlReadScreenPixels(screenWidth, screenHeight); - GifWriteFrame(screenData, screenWidth, screenHeight, 10, 8, false); - - free(screenData); // Free image data - } - - if (((gifFramesCounter/15)%2) == 1) - { - DrawCircle(30, screenHeight - 20, 10, RED); - DrawText("RECORDING", 50, screenHeight - 25, 10, MAROON); - } - - rlglDraw(); // Draw RECORDING message - } -#endif - - SwapBuffers(); // Copy back buffer to front buffer - PollInputEvents(); // Poll user events - - // Frame time control system - currentTime = GetTime(); - drawTime = currentTime - previousTime; - previousTime = currentTime; - - frameTime = updateTime + drawTime; - - // Wait for some milliseconds... - if (frameTime < targetTime) - { - Wait((targetTime - frameTime)*1000.0f); - - currentTime = GetTime(); - double extraTime = currentTime - previousTime; - previousTime = currentTime; - - frameTime += extraTime; - } -} - -// Initialize 2D mode with custom camera (2D) -void Begin2dMode(Camera2D camera) -{ - rlglDraw(); // Draw Buffers (Only OpenGL 3+ and ES2) - - rlLoadIdentity(); // Reset current matrix (MODELVIEW) - - // Camera rotation and scaling is always relative to target - Matrix matOrigin = MatrixTranslate(-camera.target.x, -camera.target.y, 0.0f); - Matrix matRotation = MatrixRotate((Vector3){ 0.0f, 0.0f, 1.0f }, camera.rotation*DEG2RAD); - Matrix matScale = MatrixScale(camera.zoom, camera.zoom, 1.0f); - Matrix matTranslation = MatrixTranslate(camera.offset.x + camera.target.x, camera.offset.y + camera.target.y, 0.0f); - - Matrix matTransform = MatrixMultiply(MatrixMultiply(matOrigin, MatrixMultiply(matScale, matRotation)), matTranslation); - - rlMultMatrixf(MatrixToFloat(matTransform)); -} - -// Ends 2D mode with custom camera -void End2dMode(void) -{ - rlglDraw(); // Draw Buffers (Only OpenGL 3+ and ES2) - - rlLoadIdentity(); // Reset current matrix (MODELVIEW) -} - -// Initializes 3D mode with custom camera (3D) -void Begin3dMode(Camera camera) -{ - rlglDraw(); // Draw Buffers (Only OpenGL 3+ and ES2) - - rlMatrixMode(RL_PROJECTION); // Switch to projection matrix - rlPushMatrix(); // Save previous matrix, which contains the settings for the 2d ortho projection - rlLoadIdentity(); // Reset current matrix (PROJECTION) - - // Setup perspective projection - float aspect = (float)screenWidth/(float)screenHeight; - double top = 0.01*tan(camera.fovy*0.5*DEG2RAD); - double right = top*aspect; - - // NOTE: zNear and zFar values are important when computing depth buffer values - rlFrustum(-right, right, -top, top, 0.01, 1000.0); - - rlMatrixMode(RL_MODELVIEW); // Switch back to modelview matrix - rlLoadIdentity(); // Reset current matrix (MODELVIEW) - - // Setup Camera view - Matrix matView = MatrixLookAt(camera.position, camera.target, camera.up); - rlMultMatrixf(MatrixToFloat(matView)); // Multiply MODELVIEW matrix by view matrix (camera) - - rlEnableDepthTest(); // Enable DEPTH_TEST for 3D -} - -// Ends 3D mode and returns to default 2D orthographic mode -void End3dMode(void) -{ - rlglDraw(); // Process internal buffers (update + draw) - - rlMatrixMode(RL_PROJECTION); // Switch to projection matrix - rlPopMatrix(); // Restore previous matrix (PROJECTION) from matrix stack - - rlMatrixMode(RL_MODELVIEW); // Get back to modelview matrix - rlLoadIdentity(); // Reset current matrix (MODELVIEW) - - rlDisableDepthTest(); // Disable DEPTH_TEST for 2D -} - -// Initializes render texture for drawing -void BeginTextureMode(RenderTexture2D target) -{ - rlglDraw(); // Draw Buffers (Only OpenGL 3+ and ES2) - - rlEnableRenderTexture(target.id); // Enable render target - - rlClearScreenBuffers(); // Clear render texture buffers - - // Set viewport to framebuffer size - rlViewport(0, 0, target.texture.width, target.texture.height); - - rlMatrixMode(RL_PROJECTION); // Switch to PROJECTION matrix - rlLoadIdentity(); // Reset current matrix (PROJECTION) - - // Set orthographic projection to current framebuffer size - // NOTE: Configured top-left corner as (0, 0) - rlOrtho(0, target.texture.width, target.texture.height, 0, 0.0f, 1.0f); - - rlMatrixMode(RL_MODELVIEW); // Switch back to MODELVIEW matrix - rlLoadIdentity(); // Reset current matrix (MODELVIEW) - - //rlScalef(0.0f, -1.0f, 0.0f); // Flip Y-drawing (?) -} - -// Ends drawing to render texture -void EndTextureMode(void) -{ - rlglDraw(); // Draw Buffers (Only OpenGL 3+ and ES2) - - rlDisableRenderTexture(); // Disable render target - - // Set viewport to default framebuffer size (screen size) - SetupViewport(); - - rlMatrixMode(RL_PROJECTION); // Switch to PROJECTION matrix - rlLoadIdentity(); // Reset current matrix (PROJECTION) - - // Set orthographic projection to current framebuffer size - // NOTE: Configured top-left corner as (0, 0) - rlOrtho(0, GetScreenWidth(), GetScreenHeight(), 0, 0.0f, 1.0f); - - rlMatrixMode(RL_MODELVIEW); // Switch back to MODELVIEW matrix - rlLoadIdentity(); // Reset current matrix (MODELVIEW) -} - -// Returns a ray trace from mouse position -Ray GetMouseRay(Vector2 mousePosition, Camera camera) -{ - Ray ray; - - // Calculate normalized device coordinates - // NOTE: y value is negative - float x = (2.0f*mousePosition.x)/(float)GetScreenWidth() - 1.0f; - float y = 1.0f - (2.0f*mousePosition.y)/(float)GetScreenHeight(); - float z = 1.0f; - - // Store values in a vector - Vector3 deviceCoords = { x, y, z }; - - TraceLog(LOG_DEBUG, "Device coordinates: (%f, %f, %f)", deviceCoords.x, deviceCoords.y, deviceCoords.z); - - // Calculate projection matrix from perspective - Matrix matProj = MatrixPerspective(camera.fovy*DEG2RAD, ((double)GetScreenWidth()/(double)GetScreenHeight()), 0.01, 1000.0); - - // Calculate view matrix from camera look at - Matrix matView = MatrixLookAt(camera.position, camera.target, camera.up); - - // Unproject far/near points - Vector3 nearPoint = rlUnproject((Vector3){ deviceCoords.x, deviceCoords.y, 0.0f }, matProj, matView); - Vector3 farPoint = rlUnproject((Vector3){ deviceCoords.x, deviceCoords.y, 1.0f }, matProj, matView); - - // Calculate normalized direction vector - Vector3 direction = Vector3Subtract(farPoint, nearPoint); - Vector3Normalize(&direction); - - // Apply calculated vectors to ray - ray.position = camera.position; - ray.direction = direction; - - return ray; -} - -// Returns the screen space position from a 3d world space position -Vector2 GetWorldToScreen(Vector3 position, Camera camera) -{ - // Calculate projection matrix (from perspective instead of frustum - Matrix matProj = MatrixPerspective(camera.fovy*DEG2RAD, (double)GetScreenWidth()/(double)GetScreenHeight(), 0.01, 1000.0); - - // Calculate view matrix from camera look at (and transpose it) - Matrix matView = MatrixLookAt(camera.position, camera.target, camera.up); - - // Convert world position vector to quaternion - Quaternion worldPos = { position.x, position.y, position.z, 1.0f }; - - // Transform world position to view - QuaternionTransform(&worldPos, matView); - - // Transform result to projection (clip space position) - QuaternionTransform(&worldPos, matProj); - - // Calculate normalized device coordinates (inverted y) - Vector3 ndcPos = { worldPos.x/worldPos.w, -worldPos.y/worldPos.w, worldPos.z/worldPos.w }; - - // Calculate 2d screen position vector - Vector2 screenPosition = { (ndcPos.x + 1.0f)/2.0f*(float)GetScreenWidth(), (ndcPos.y + 1.0f)/2.0f*(float)GetScreenHeight() }; - - return screenPosition; -} - -// Get transform matrix for camera -Matrix GetCameraMatrix(Camera camera) -{ - return MatrixLookAt(camera.position, camera.target, camera.up); -} - -// Set target FPS (maximum) -void SetTargetFPS(int fps) -{ - if (fps < 1) targetTime = 0.0; - else targetTime = 1.0/(double)fps; - - TraceLog(LOG_INFO, "Target time per frame: %02.03f milliseconds", (float)targetTime*1000); -} - -// Returns current FPS -int GetFPS(void) -{ - return (int)(1.0f/GetFrameTime()); -} - -// Returns time in seconds for last frame drawn -float GetFrameTime(void) -{ - // NOTE: We round value to milliseconds - return (float)frameTime; -} - -// Converts Color to float array and normalizes -float *ColorToFloat(Color color) -{ - static float buffer[4]; - - buffer[0] = (float)color.r/255; - buffer[1] = (float)color.g/255; - buffer[2] = (float)color.b/255; - buffer[3] = (float)color.a/255; - - return buffer; -} - -// Returns a Color struct from hexadecimal value -Color GetColor(int hexValue) -{ - Color color; - - color.r = (unsigned char)(hexValue >> 24) & 0xFF; - color.g = (unsigned char)(hexValue >> 16) & 0xFF; - color.b = (unsigned char)(hexValue >> 8) & 0xFF; - color.a = (unsigned char)hexValue & 0xFF; - - return color; -} - -// Returns hexadecimal value for a Color -int GetHexValue(Color color) -{ - return (((int)color.r << 24) | ((int)color.g << 16) | ((int)color.b << 8) | (int)color.a); -} - -// Returns a random value between min and max (both included) -int GetRandomValue(int min, int max) -{ - if (min > max) - { - int tmp = max; - max = min; - min = tmp; - } - - return (rand()%(abs(max-min)+1) + min); -} - -// Color fade-in or fade-out, alpha goes from 0.0f to 1.0f -Color Fade(Color color, float alpha) -{ - if (alpha < 0.0f) alpha = 0.0f; - else if (alpha > 1.0f) alpha = 1.0f; - - float colorAlpha = (float)color.a*alpha; - - return (Color){color.r, color.g, color.b, (unsigned char)colorAlpha}; -} - -// Activate raylib logo at startup (can be done with flags) -void ShowLogo(void) -{ - showLogo = true; -} - -// Setup window configuration flags (view FLAGS) -void SetConfigFlags(char flags) -{ - configFlags = flags; - - if (configFlags & FLAG_SHOW_LOGO) showLogo = true; - if (configFlags & FLAG_FULLSCREEN_MODE) fullscreen = true; -} - -// NOTE TraceLog() function is located in [utils.h] - -// Takes a screenshot of current screen (saved a .png) -void TakeScreenshot(const char *fileName) -{ -#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI) - unsigned char *imgData = rlReadScreenPixels(renderWidth, renderHeight); - SavePNG(fileName, imgData, renderWidth, renderHeight, 4); // Save image as PNG - free(imgData); - - TraceLog(LOG_INFO, "Screenshot taken: %s", fileName); -#endif -} - -// Check file extension -bool IsFileExtension(const char *fileName, const char *ext) -{ - bool result = false; - const char *fileExt; - - if ((fileExt = strrchr(fileName, '.')) != NULL) - { - if (strcmp(fileExt, ext) == 0) result = true; - } - - return result; -} - -// Get the extension for a filename -const char *GetExtension(const char *fileName) -{ - const char *dot = strrchr(fileName, '.'); - - if (!dot || dot == fileName) return ""; - - return (dot + 1); -} - -// Get directory for a given fileName (with path) -const char *GetDirectoryPath(const char *fileName) -{ - char *lastSlash = NULL; - static char filePath[256]; // MAX_DIRECTORY_PATH_SIZE = 256 - memset(filePath, 0, 256); - - lastSlash = strrchr(fileName, '\\'); - strncpy(filePath, fileName, strlen(fileName) - (strlen(lastSlash) - 1)); - filePath[strlen(fileName) - strlen(lastSlash)] = '\0'; - - return filePath; -} - -// Get current working directory -const char *GetWorkingDirectory(void) -{ - static char currentDir[256]; // MAX_DIRECTORY_PATH_SIZE = 256 - memset(currentDir, 0, 256); - - GETCWD(currentDir, 256 - 1); - - return currentDir; -} - -// Change working directory, returns true if success -bool ChangeDirectory(const char *dir) -{ - return (CHDIR(dir) == 0); -} - -#if defined(PLATFORM_DESKTOP) -// Check if a file has been dropped into window -bool IsFileDropped(void) -{ - if (dropFilesCount > 0) return true; - else return false; -} - -// Get dropped files names -char **GetDroppedFiles(int *count) -{ - *count = dropFilesCount; - return dropFilesPath; -} - -// Clear dropped files paths buffer -void ClearDroppedFiles(void) -{ - if (dropFilesCount > 0) - { - for (int i = 0; i < dropFilesCount; i++) free(dropFilesPath[i]); - - free(dropFilesPath); - - dropFilesCount = 0; - } -} -#endif - -// Save integer value to storage file (to defined position) -// NOTE: Storage positions is directly related to file memory layout (4 bytes each integer) -void StorageSaveValue(int position, int value) -{ - FILE *storageFile = NULL; - - char path[128]; -#if defined(PLATFORM_ANDROID) - strcpy(path, internalDataPath); - strcat(path, "/"); - strcat(path, STORAGE_FILENAME); -#else - strcpy(path, STORAGE_FILENAME); -#endif - - // Try open existing file to append data - storageFile = fopen(path, "rb+"); - - // If file doesn't exist, create a new storage data file - if (!storageFile) storageFile = fopen(path, "wb"); - - if (!storageFile) TraceLog(LOG_WARNING, "Storage data file could not be created"); - else - { - // Get file size - fseek(storageFile, 0, SEEK_END); - int fileSize = ftell(storageFile); // Size in bytes - fseek(storageFile, 0, SEEK_SET); - - if (fileSize < (position*4)) TraceLog(LOG_WARNING, "Storage position could not be found"); - else - { - fseek(storageFile, (position*4), SEEK_SET); - fwrite(&value, 1, 4, storageFile); - } - - fclose(storageFile); - } -} - -// Load integer value from storage file (from defined position) -// NOTE: If requested position could not be found, value 0 is returned -int StorageLoadValue(int position) -{ - int value = 0; - - char path[128]; -#if defined(PLATFORM_ANDROID) - strcpy(path, internalDataPath); - strcat(path, "/"); - strcat(path, STORAGE_FILENAME); -#else - strcpy(path, STORAGE_FILENAME); -#endif - - // Try open existing file to append data - FILE *storageFile = fopen(path, "rb"); - - if (!storageFile) TraceLog(LOG_WARNING, "Storage data file could not be found"); - else - { - // Get file size - fseek(storageFile, 0, SEEK_END); - int fileSize = ftell(storageFile); // Size in bytes - rewind(storageFile); - - if (fileSize < (position*4)) TraceLog(LOG_WARNING, "Storage position could not be found"); - else - { - fseek(storageFile, (position*4), SEEK_SET); - fread(&value, 4, 1, storageFile); // Read 1 element of 4 bytes size - } - - fclose(storageFile); - } - - return value; -} - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Input (Keyboard, Mouse, Gamepad) Functions -//---------------------------------------------------------------------------------- -// Detect if a key has been pressed once -bool IsKeyPressed(int key) -{ - bool pressed = false; - - if ((currentKeyState[key] != previousKeyState[key]) && (currentKeyState[key] == 1)) pressed = true; - else pressed = false; - - return pressed; -} - -// Detect if a key is being pressed (key held down) -bool IsKeyDown(int key) -{ - if (GetKeyStatus(key) == 1) return true; - else return false; -} - -// Detect if a key has been released once -bool IsKeyReleased(int key) -{ - bool released = false; - - if ((currentKeyState[key] != previousKeyState[key]) && (currentKeyState[key] == 0)) released = true; - else released = false; - - return released; -} - -// Detect if a key is NOT being pressed (key not held down) -bool IsKeyUp(int key) -{ - if (GetKeyStatus(key) == 0) return true; - else return false; -} - -// Get the last key pressed -int GetKeyPressed(void) -{ - return lastKeyPressed; -} - -// Set a custom key to exit program -// NOTE: default exitKey is ESCAPE -void SetExitKey(int key) -{ -#if !defined(PLATFORM_ANDROID) - exitKey = key; -#endif -} - -// NOTE: Gamepad support not implemented in emscripten GLFW3 (PLATFORM_WEB) - -// Detect if a gamepad is available -bool IsGamepadAvailable(int gamepad) -{ - bool result = false; - -#if !defined(PLATFORM_ANDROID) - if ((gamepad < MAX_GAMEPADS) && gamepadReady[gamepad]) result = true; -#endif - - return result; -} - -// Check gamepad name (if available) -bool IsGamepadName(int gamepad, const char *name) -{ - bool result = false; - -#if !defined(PLATFORM_ANDROID) - const char *gamepadName = NULL; - - if (gamepadReady[gamepad]) gamepadName = GetGamepadName(gamepad); - if ((name != NULL) && (gamepadName != NULL)) result = (strcmp(name, gamepadName) == 0); -#endif - - return result; -} - -// Return gamepad internal name id -const char *GetGamepadName(int gamepad) -{ -#if defined(PLATFORM_DESKTOP) - if (gamepadReady[gamepad]) return glfwGetJoystickName(gamepad); - else return NULL; -#elif defined(PLATFORM_RPI) - if (gamepadReady[gamepad]) ioctl(gamepadStream[gamepad], JSIOCGNAME(64), &gamepadName); - - return gamepadName; -#else - return NULL; -#endif -} - -// Return gamepad axis count -int GetGamepadAxisCount(int gamepad) -{ -#if defined(PLATFORM_RPI) - int axisCount = 0; - if (gamepadReady[gamepad]) ioctl(gamepadStream[gamepad], JSIOCGAXES, &axisCount); - gamepadAxisCount = axisCount; -#endif - return gamepadAxisCount; -} - -// Return axis movement vector for a gamepad -float GetGamepadAxisMovement(int gamepad, int axis) -{ - float value = 0; - -#if !defined(PLATFORM_ANDROID) - if ((gamepad < MAX_GAMEPADS) && gamepadReady[gamepad] && (axis < MAX_GAMEPAD_AXIS)) value = gamepadAxisState[gamepad][axis]; -#endif - - return value; -} - -// Detect if a gamepad button has been pressed once -bool IsGamepadButtonPressed(int gamepad, int button) -{ - bool pressed = false; - -#if !defined(PLATFORM_ANDROID) - if ((gamepad < MAX_GAMEPADS) && gamepadReady[gamepad] && (button < MAX_GAMEPAD_BUTTONS) && - (currentGamepadState[gamepad][button] != previousGamepadState[gamepad][button]) && - (currentGamepadState[gamepad][button] == 1)) pressed = true; -#endif - - return pressed; -} - -// Detect if a gamepad button is being pressed -bool IsGamepadButtonDown(int gamepad, int button) -{ - bool result = false; - -#if !defined(PLATFORM_ANDROID) - if ((gamepad < MAX_GAMEPADS) && gamepadReady[gamepad] && (button < MAX_GAMEPAD_BUTTONS) && - (currentGamepadState[gamepad][button] == 1)) result = true; -#endif - - return result; -} - -// Detect if a gamepad button has NOT been pressed once -bool IsGamepadButtonReleased(int gamepad, int button) -{ - bool released = false; - -#if !defined(PLATFORM_ANDROID) - if ((gamepad < MAX_GAMEPADS) && gamepadReady[gamepad] && (button < MAX_GAMEPAD_BUTTONS) && - (currentGamepadState[gamepad][button] != previousGamepadState[gamepad][button]) && - (currentGamepadState[gamepad][button] == 0)) released = true; -#endif - - return released; -} - -// Detect if a mouse button is NOT being pressed -bool IsGamepadButtonUp(int gamepad, int button) -{ - bool result = false; - -#if !defined(PLATFORM_ANDROID) - if ((gamepad < MAX_GAMEPADS) && gamepadReady[gamepad] && (button < MAX_GAMEPAD_BUTTONS) && - (currentGamepadState[gamepad][button] == 0)) result = true; -#endif - - return result; -} - -// Get the last gamepad button pressed -int GetGamepadButtonPressed(void) -{ - return lastGamepadButtonPressed; -} - -// Detect if a mouse button has been pressed once -bool IsMouseButtonPressed(int button) -{ - bool pressed = false; - -// TODO: Review, gestures could be not supported despite being on Android platform! -#if defined(PLATFORM_ANDROID) - if (IsGestureDetected(GESTURE_TAP)) pressed = true; -#else - if ((currentMouseState[button] != previousMouseState[button]) && (currentMouseState[button] == 1)) pressed = true; -#endif - - return pressed; -} - -// Detect if a mouse button is being pressed -bool IsMouseButtonDown(int button) -{ - bool down = false; - -#if defined(PLATFORM_ANDROID) - if (IsGestureDetected(GESTURE_HOLD)) down = true; -#else - if (GetMouseButtonStatus(button) == 1) down = true; -#endif - - return down; -} - -// Detect if a mouse button has been released once -bool IsMouseButtonReleased(int button) -{ - bool released = false; - -#if !defined(PLATFORM_ANDROID) - if ((currentMouseState[button] != previousMouseState[button]) && (currentMouseState[button] == 0)) released = true; -#endif - - return released; -} - -// Detect if a mouse button is NOT being pressed -bool IsMouseButtonUp(int button) -{ - bool up = false; - -#if !defined(PLATFORM_ANDROID) - if (GetMouseButtonStatus(button) == 0) up = true; -#endif - - return up; -} - -// Returns mouse position X -int GetMouseX(void) -{ -#if defined(PLATFORM_ANDROID) - return (int)touchPosition[0].x; -#else - return (int)mousePosition.x; -#endif -} - -// Returns mouse position Y -int GetMouseY(void) -{ -#if defined(PLATFORM_ANDROID) - return (int)touchPosition[0].x; -#else - return (int)mousePosition.y; -#endif -} - -// Returns mouse position XY -Vector2 GetMousePosition(void) -{ -#if defined(PLATFORM_ANDROID) - return GetTouchPosition(0); -#else - return mousePosition; -#endif -} - -// Set mouse position XY -void SetMousePosition(Vector2 position) -{ - mousePosition = position; -#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) - // NOTE: emscripten not implemented - glfwSetCursorPos(window, position.x, position.y); -#endif -} - -// Returns mouse wheel movement Y -int GetMouseWheelMove(void) -{ -#if defined(PLATFORM_ANDROID) - return 0; -#elif defined(PLATFORM_WEB) - return previousMouseWheelY/100; -#else - return previousMouseWheelY; -#endif -} - -// Returns touch position X for touch point 0 (relative to screen size) -int GetTouchX(void) -{ -#if defined(PLATFORM_ANDROID) || defined(PLATFORM_WEB) - return (int)touchPosition[0].x; -#else // PLATFORM_DESKTOP, PLATFORM_RPI - return GetMouseX(); -#endif -} - -// Returns touch position Y for touch point 0 (relative to screen size) -int GetTouchY(void) -{ -#if defined(PLATFORM_ANDROID) || defined(PLATFORM_WEB) - return (int)touchPosition[0].y; -#else // PLATFORM_DESKTOP, PLATFORM_RPI - return GetMouseY(); -#endif -} - -// Returns touch position XY for a touch point index (relative to screen size) -// TODO: Touch position should be scaled depending on display size and render size -Vector2 GetTouchPosition(int index) -{ - Vector2 position = { -1.0f, -1.0f }; - -#if defined(PLATFORM_ANDROID) || defined(PLATFORM_WEB) - if (index < MAX_TOUCH_POINTS) position = touchPosition[index]; - else TraceLog(LOG_WARNING, "Required touch point out of range (Max touch points: %i)", MAX_TOUCH_POINTS); - - if ((screenWidth > displayWidth) || (screenHeight > displayHeight)) - { - // TODO: Review touch position scaling for screenSize vs displaySize - position.x = position.x*((float)screenWidth/(float)(displayWidth - renderOffsetX)) - renderOffsetX/2; - position.y = position.y*((float)screenHeight/(float)(displayHeight - renderOffsetY)) - renderOffsetY/2; - } - else - { - position.x = position.x*((float)renderWidth/(float)displayWidth) - renderOffsetX/2; - position.y = position.y*((float)renderHeight/(float)displayHeight) - renderOffsetY/2; - } -#else // PLATFORM_DESKTOP, PLATFORM_RPI - if (index == 0) position = GetMousePosition(); -#endif - - return position; -} - -//---------------------------------------------------------------------------------- -// Module specific Functions Definition -//---------------------------------------------------------------------------------- - -// Initialize display device and framebuffer -// NOTE: width and height represent the screen (framebuffer) desired size, not actual display size -// If width or height are 0, default display size will be used for framebuffer size -static void InitGraphicsDevice(int width, int height) -{ - screenWidth = width; // User desired width - screenHeight = height; // User desired height - - // NOTE: Framebuffer (render area - renderWidth, renderHeight) could include black bars... - // ...in top-down or left-right to match display aspect ratio (no weird scalings) - - // Downscale matrix is required in case desired screen area is bigger than display area - downscaleView = MatrixIdentity(); - -#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) - glfwSetErrorCallback(ErrorCallback); - - if (!glfwInit()) TraceLog(LOG_ERROR, "Failed to initialize GLFW"); - - // NOTE: Getting video modes is not implemented in emscripten GLFW3 version -#if defined(PLATFORM_DESKTOP) - // Find monitor resolution - const GLFWvidmode *mode = glfwGetVideoMode(glfwGetPrimaryMonitor()); - - displayWidth = mode->width; - displayHeight = mode->height; - - // Screen size security check - if (screenWidth <= 0) screenWidth = displayWidth; - if (screenHeight <= 0) screenHeight = displayHeight; -#endif // defined(PLATFORM_DESKTOP) - -#if defined(PLATFORM_WEB) - displayWidth = screenWidth; - displayHeight = screenHeight; -#endif // defined(PLATFORM_WEB) - - glfwDefaultWindowHints(); // Set default windows hints - - // Check some Window creation flags - if (configFlags & FLAG_WINDOW_RESIZABLE) glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); // Resizable window - else glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // Avoid window being resizable - - if (configFlags & FLAG_WINDOW_DECORATED) glfwWindowHint(GLFW_DECORATED, GL_TRUE); // Border and buttons on Window - - if (configFlags & FLAG_WINDOW_TRANSPARENT) - { - // TODO: Enable transparent window (not ready yet on GLFW 3.2) - } - - if (configFlags & FLAG_MSAA_4X_HINT) - { - glfwWindowHint(GLFW_SAMPLES, 4); // Enables multisampling x4 (MSAA), default is 0 - TraceLog(LOG_INFO, "Trying to enable MSAA x4"); - } - - //glfwWindowHint(GLFW_RED_BITS, 8); // Framebuffer red color component bits - //glfwWindowHint(GLFW_DEPTH_BITS, 16); // Depthbuffer bits (24 by default) - //glfwWindowHint(GLFW_REFRESH_RATE, 0); // Refresh rate for fullscreen window - //glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API); // Default OpenGL API to use. Alternative: GLFW_OPENGL_ES_API - //glfwWindowHint(GLFW_AUX_BUFFERS, 0); // Number of auxiliar buffers - - // NOTE: When asking for an OpenGL context version, most drivers provide highest supported version - // with forward compatibility to older OpenGL versions. - // For example, if using OpenGL 1.1, driver can provide a 4.3 context forward compatible. - - // Check selection OpenGL version - if (rlGetVersion() == OPENGL_21) - { - glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); // Choose OpenGL major version (just hint) - glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); // Choose OpenGL minor version (just hint) - } - else if (rlGetVersion() == OPENGL_33) - { - glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // Choose OpenGL major version (just hint) - glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); // Choose OpenGL minor version (just hint) - glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Profiles Hint: Only 3.3 and above! - // Other values: GLFW_OPENGL_ANY_PROFILE, GLFW_OPENGL_COMPAT_PROFILE -#if defined(__APPLE__) - glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // OSX Requires -#else - glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_FALSE); // Fordward Compatibility Hint: Only 3.3 and above! -#endif - //glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); - } - - if (fullscreen) - { - // Obtain recommended displayWidth/displayHeight from a valid videomode for the monitor - int count; - const GLFWvidmode *modes = glfwGetVideoModes(glfwGetPrimaryMonitor(), &count); - - // Get closest videomode to desired screenWidth/screenHeight - for (int i = 0; i < count; i++) - { - if (modes[i].width >= screenWidth) - { - if (modes[i].height >= screenHeight) - { - displayWidth = modes[i].width; - displayHeight = modes[i].height; - break; - } - } - } - - TraceLog(LOG_WARNING, "Closest fullscreen videomode: %i x %i", displayWidth, displayHeight); - - // NOTE: ISSUE: Closest videomode could not match monitor aspect-ratio, for example, - // for a desired screen size of 800x450 (16:9), closest supported videomode is 800x600 (4:3), - // framebuffer is rendered correctly but once displayed on a 16:9 monitor, it gets stretched - // by the sides to fit all monitor space... - - // At this point we need to manage render size vs screen size - // NOTE: This function uses and modifies global module variables: - // screenWidth/screenHeight - renderWidth/renderHeight - downscaleView - SetupFramebufferSize(displayWidth, displayHeight); - - window = glfwCreateWindow(displayWidth, displayHeight, windowTitle, glfwGetPrimaryMonitor(), NULL); - - // NOTE: Full-screen change, not working properly... - //glfwSetWindowMonitor(window, glfwGetPrimaryMonitor(), 0, 0, screenWidth, screenHeight, GLFW_DONT_CARE); - } - else - { - // No-fullscreen window creation - window = glfwCreateWindow(screenWidth, screenHeight, windowTitle, NULL, NULL); - -#if defined(PLATFORM_DESKTOP) - // Center window on screen - int windowPosX = displayWidth/2 - screenWidth/2; - int windowPosY = displayHeight/2 - screenHeight/2; - - if (windowPosX < 0) windowPosX = 0; - if (windowPosY < 0) windowPosY = 0; - - glfwSetWindowPos(window, windowPosX, windowPosY); -#endif - renderWidth = screenWidth; - renderHeight = screenHeight; - } - - if (!window) - { - glfwTerminate(); - TraceLog(LOG_ERROR, "GLFW Failed to initialize Window"); - } - else - { - TraceLog(LOG_INFO, "Display device initialized successfully"); -#if defined(PLATFORM_DESKTOP) - TraceLog(LOG_INFO, "Display size: %i x %i", displayWidth, displayHeight); -#endif - TraceLog(LOG_INFO, "Render size: %i x %i", renderWidth, renderHeight); - TraceLog(LOG_INFO, "Screen size: %i x %i", screenWidth, screenHeight); - TraceLog(LOG_INFO, "Viewport offsets: %i, %i", renderOffsetX, renderOffsetY); - } - - glfwSetWindowSizeCallback(window, WindowSizeCallback); // NOTE: Resizing not allowed by default! - glfwSetCursorEnterCallback(window, CursorEnterCallback); - glfwSetKeyCallback(window, KeyCallback); - glfwSetMouseButtonCallback(window, MouseButtonCallback); - glfwSetCursorPosCallback(window, MouseCursorPosCallback); // Track mouse position changes - glfwSetCharCallback(window, CharCallback); - glfwSetScrollCallback(window, ScrollCallback); - glfwSetWindowIconifyCallback(window, WindowIconifyCallback); -#if defined(PLATFORM_DESKTOP) - glfwSetDropCallback(window, WindowDropCallback); -#endif - - glfwMakeContextCurrent(window); - - // Try to disable GPU V-Sync by default, set framerate using SetTargetFPS() - // NOTE: V-Sync can be enabled by graphic driver configuration - glfwSwapInterval(0); - -#if defined(PLATFORM_DESKTOP) - // Load OpenGL 3.3 extensions - // NOTE: GLFW loader function is passed as parameter - rlLoadExtensions(glfwGetProcAddress); -#endif - - // Try to enable GPU V-Sync, so frames are limited to screen refresh rate (60Hz -> 60 FPS) - // NOTE: V-Sync can be enabled by graphic driver configuration - if (configFlags & FLAG_VSYNC_HINT) - { - glfwSwapInterval(1); - TraceLog(LOG_INFO, "Trying to enable VSYNC"); - } -#endif // defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) - -#if defined(PLATFORM_ANDROID) || defined(PLATFORM_RPI) - fullscreen = true; - - // Screen size security check - if (screenWidth <= 0) screenWidth = displayWidth; - if (screenHeight <= 0) screenHeight = displayHeight; - -#if defined(PLATFORM_RPI) - bcm_host_init(); - - DISPMANX_ELEMENT_HANDLE_T dispmanElement; - DISPMANX_DISPLAY_HANDLE_T dispmanDisplay; - DISPMANX_UPDATE_HANDLE_T dispmanUpdate; - - VC_RECT_T dstRect; - VC_RECT_T srcRect; -#endif - - EGLint samples = 0; - EGLint sampleBuffer = 0; - if (configFlags & FLAG_MSAA_4X_HINT) - { - samples = 4; - sampleBuffer = 1; - TraceLog(LOG_INFO, "Trying to enable MSAA x4"); - } - - const EGLint framebufferAttribs[] = - { - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, // Type of context support -> Required on RPI? - //EGL_SURFACE_TYPE, EGL_WINDOW_BIT, // Don't use it on Android! - EGL_RED_SIZE, 8, // RED color bit depth (alternative: 5) - EGL_GREEN_SIZE, 8, // GREEN color bit depth (alternative: 6) - EGL_BLUE_SIZE, 8, // BLUE color bit depth (alternative: 5) - //EGL_ALPHA_SIZE, 8, // ALPHA bit depth (required for transparent framebuffer) - //EGL_TRANSPARENT_TYPE, EGL_NONE, // Request transparent framebuffer (EGL_TRANSPARENT_RGB does not work on RPI) - EGL_DEPTH_SIZE, 16, // Depth buffer size (Required to use Depth testing!) - //EGL_STENCIL_SIZE, 8, // Stencil buffer size - EGL_SAMPLE_BUFFERS, sampleBuffer, // Activate MSAA - EGL_SAMPLES, samples, // 4x Antialiasing if activated (Free on MALI GPUs) - EGL_NONE - }; - - EGLint contextAttribs[] = - { - EGL_CONTEXT_CLIENT_VERSION, 2, - EGL_NONE - }; - - EGLint numConfigs; - - // Get an EGL display connection - display = eglGetDisplay(EGL_DEFAULT_DISPLAY); - - // Initialize the EGL display connection - eglInitialize(display, NULL, NULL); - - // Get an appropriate EGL framebuffer configuration - eglChooseConfig(display, framebufferAttribs, &config, 1, &numConfigs); - - // Set rendering API - eglBindAPI(EGL_OPENGL_ES_API); - - // Create an EGL rendering context - context = eglCreateContext(display, config, EGL_NO_CONTEXT, contextAttribs); - - // Create an EGL window surface - //--------------------------------------------------------------------------------- -#if defined(PLATFORM_ANDROID) - EGLint displayFormat; - - displayWidth = ANativeWindow_getWidth(app->window); - displayHeight = ANativeWindow_getHeight(app->window); - - // EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is guaranteed to be accepted by ANativeWindow_setBuffersGeometry() - // As soon as we picked a EGLConfig, we can safely reconfigure the ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID - eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &displayFormat); - - // At this point we need to manage render size vs screen size - // NOTE: This function use and modify global module variables: screenWidth/screenHeight and renderWidth/renderHeight and downscaleView - SetupFramebufferSize(displayWidth, displayHeight); - - ANativeWindow_setBuffersGeometry(app->window, renderWidth, renderHeight, displayFormat); - //ANativeWindow_setBuffersGeometry(app->window, 0, 0, displayFormat); // Force use of native display size - - surface = eglCreateWindowSurface(display, config, app->window, NULL); -#endif // defined(PLATFORM_ANDROID) - -#if defined(PLATFORM_RPI) - graphics_get_display_size(0, &displayWidth, &displayHeight); - - // At this point we need to manage render size vs screen size - // NOTE: This function use and modify global module variables: screenWidth/screenHeight and renderWidth/renderHeight and downscaleView - SetupFramebufferSize(displayWidth, displayHeight); - - dstRect.x = 0; - dstRect.y = 0; - dstRect.width = displayWidth; - dstRect.height = displayHeight; - - srcRect.x = 0; - srcRect.y = 0; - srcRect.width = renderWidth << 16; - srcRect.height = renderHeight << 16; - - // NOTE: RPI dispmanx windowing system takes care of srcRec scaling to dstRec by hardware (no cost) - // Take care that renderWidth/renderHeight fit on displayWidth/displayHeight aspect ratio - - VC_DISPMANX_ALPHA_T alpha; - alpha.flags = DISPMANX_FLAGS_ALPHA_FIXED_ALL_PIXELS; - alpha.opacity = 255; // Set transparency level for framebuffer, requires EGLAttrib: EGL_TRANSPARENT_TYPE - alpha.mask = 0; - - dispmanDisplay = vc_dispmanx_display_open(0); // LCD - dispmanUpdate = vc_dispmanx_update_start(0); - - dispmanElement = vc_dispmanx_element_add(dispmanUpdate, dispmanDisplay, 0/*layer*/, &dstRect, 0/*src*/, - &srcRect, DISPMANX_PROTECTION_NONE, &alpha, 0/*clamp*/, DISPMANX_NO_ROTATE); - - nativeWindow.element = dispmanElement; - nativeWindow.width = renderWidth; - nativeWindow.height = renderHeight; - vc_dispmanx_update_submit_sync(dispmanUpdate); - - surface = eglCreateWindowSurface(display, config, &nativeWindow, NULL); - //--------------------------------------------------------------------------------- -#endif // defined(PLATFORM_RPI) - // There must be at least one frame displayed before the buffers are swapped - //eglSwapInterval(display, 1); - - if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE) - { - TraceLog(LOG_ERROR, "Unable to attach EGL rendering context to EGL surface"); - } - else - { - // Grab the width and height of the surface - //eglQuerySurface(display, surface, EGL_WIDTH, &renderWidth); - //eglQuerySurface(display, surface, EGL_HEIGHT, &renderHeight); - - TraceLog(LOG_INFO, "Display device initialized successfully"); - TraceLog(LOG_INFO, "Display size: %i x %i", displayWidth, displayHeight); - TraceLog(LOG_INFO, "Render size: %i x %i", renderWidth, renderHeight); - TraceLog(LOG_INFO, "Screen size: %i x %i", screenWidth, screenHeight); - TraceLog(LOG_INFO, "Viewport offsets: %i, %i", renderOffsetX, renderOffsetY); - } -#endif // defined(PLATFORM_ANDROID) || defined(PLATFORM_RPI) - - // Initialize OpenGL context (states and resources) - // NOTE: screenWidth and screenHeight not used, just stored as globals - rlglInit(screenWidth, screenHeight); - - // Setup default viewport - SetupViewport(); - - // Initialize internal projection and modelview matrices - // NOTE: Default to orthographic projection mode with top-left corner at (0,0) - rlMatrixMode(RL_PROJECTION); // Switch to PROJECTION matrix - rlLoadIdentity(); // Reset current matrix (PROJECTION) - rlOrtho(0, renderWidth - renderOffsetX, renderHeight - renderOffsetY, 0, 0.0f, 1.0f); - rlMatrixMode(RL_MODELVIEW); // Switch back to MODELVIEW matrix - rlLoadIdentity(); // Reset current matrix (MODELVIEW) - - ClearBackground(RAYWHITE); // Default background color for raylib games :P - -#if defined(PLATFORM_ANDROID) - windowReady = true; // IMPORTANT! -#endif -} - -// Set viewport parameters -static void SetupViewport(void) -{ -#if defined(__APPLE__) - // Get framebuffer size of current window - // NOTE: Required to handle HighDPI display correctly on OSX because framebuffer - // is automatically reasized to adapt to new DPI. - // When OS does that, it can be detected using GLFW3 callback: glfwSetFramebufferSizeCallback() - int fbWidth, fbHeight; - glfwGetFramebufferSize(window, &fbWidth, &fbHeight); - rlViewport(renderOffsetX/2, renderOffsetY/2, fbWidth - renderOffsetX, fbHeight - renderOffsetY); -#else - // Initialize screen viewport (area of the screen that you will actually draw to) - // NOTE: Viewport must be recalculated if screen is resized - rlViewport(renderOffsetX/2, renderOffsetY/2, renderWidth - renderOffsetX, renderHeight - renderOffsetY); -#endif -} - -// Compute framebuffer size relative to screen size and display size -// NOTE: Global variables renderWidth/renderHeight and renderOffsetX/renderOffsetY can be modified -static void SetupFramebufferSize(int displayWidth, int displayHeight) -{ - // Calculate renderWidth and renderHeight, we have the display size (input params) and the desired screen size (global var) - if ((screenWidth > displayWidth) || (screenHeight > displayHeight)) - { - TraceLog(LOG_WARNING, "DOWNSCALING: Required screen size (%ix%i) is bigger than display size (%ix%i)", screenWidth, screenHeight, displayWidth, displayHeight); - - // Downscaling to fit display with border-bars - float widthRatio = (float)displayWidth/(float)screenWidth; - float heightRatio = (float)displayHeight/(float)screenHeight; - - if (widthRatio <= heightRatio) - { - renderWidth = displayWidth; - renderHeight = (int)round((float)screenHeight*widthRatio); - renderOffsetX = 0; - renderOffsetY = (displayHeight - renderHeight); - } - else - { - renderWidth = (int)round((float)screenWidth*heightRatio); - renderHeight = displayHeight; - renderOffsetX = (displayWidth - renderWidth); - renderOffsetY = 0; - } - - // NOTE: downscale matrix required! - float scaleRatio = (float)renderWidth/(float)screenWidth; - - downscaleView = MatrixScale(scaleRatio, scaleRatio, scaleRatio); - - // NOTE: We render to full display resolution! - // We just need to calculate above parameters for downscale matrix and offsets - renderWidth = displayWidth; - renderHeight = displayHeight; - - TraceLog(LOG_WARNING, "Downscale matrix generated, content will be rendered at: %i x %i", renderWidth, renderHeight); - } - else if ((screenWidth < displayWidth) || (screenHeight < displayHeight)) - { - // Required screen size is smaller than display size - TraceLog(LOG_INFO, "UPSCALING: Required screen size: %i x %i -> Display size: %i x %i", screenWidth, screenHeight, displayWidth, displayHeight); - - // Upscaling to fit display with border-bars - float displayRatio = (float)displayWidth/(float)displayHeight; - float screenRatio = (float)screenWidth/(float)screenHeight; - - if (displayRatio <= screenRatio) - { - renderWidth = screenWidth; - renderHeight = (int)round((float)screenWidth/displayRatio); - renderOffsetX = 0; - renderOffsetY = (renderHeight - screenHeight); - } - else - { - renderWidth = (int)round((float)screenHeight*displayRatio); - renderHeight = screenHeight; - renderOffsetX = (renderWidth - screenWidth); - renderOffsetY = 0; - } - } - else // screen == display - { - renderWidth = screenWidth; - renderHeight = screenHeight; - renderOffsetX = 0; - renderOffsetY = 0; - } -} - -// Initialize hi-resolution timer -static void InitTimer(void) -{ - srand(time(NULL)); // Initialize random seed - -#if !defined(SUPPORT_BUSY_WAIT_LOOP) && defined(_WIN32) - timeBeginPeriod(1); // Setup high-resolution timer to 1ms (granularity of 1-2 ms) -#endif - -#if defined(PLATFORM_ANDROID) || defined(PLATFORM_RPI) - struct timespec now; - - if (clock_gettime(CLOCK_MONOTONIC, &now) == 0) // Success - { - baseTime = (uint64_t)now.tv_sec*1000000000LLU + (uint64_t)now.tv_nsec; - } - else TraceLog(LOG_WARNING, "No hi-resolution timer available"); -#endif - - previousTime = GetTime(); // Get time as double -} - -// Get current time measure (in seconds) since InitTimer() -static double GetTime(void) -{ -#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) - return glfwGetTime(); -#endif - -#if defined(PLATFORM_ANDROID) || defined(PLATFORM_RPI) - struct timespec ts; - clock_gettime(CLOCK_MONOTONIC, &ts); - uint64_t time = (uint64_t)ts.tv_sec*1000000000LLU + (uint64_t)ts.tv_nsec; - - return (double)(time - baseTime)*1e-9; -#endif -} - -// Wait for some milliseconds (stop program execution) -// NOTE: Sleep() granularity could be around 10 ms, it means, Sleep() could -// take longer than expected... for that reason we use the busy wait loop -// http://stackoverflow.com/questions/43057578/c-programming-win32-games-sleep-taking-longer-than-expected -static void Wait(float ms) -{ -#if defined(SUPPORT_BUSY_WAIT_LOOP) - double prevTime = GetTime(); - double nextTime = 0.0; - - // Busy wait loop - while ((nextTime - prevTime) < ms/1000.0f) nextTime = GetTime(); -#else - #if defined(_WIN32) - Sleep((unsigned int)ms); - #elif defined(__linux__) || defined(PLATFORM_WEB) - struct timespec req = { 0 }; - time_t sec = (int)(ms/1000.0f); - ms -= (sec*1000); - req.tv_sec = sec; - req.tv_nsec = ms*1000000L; - - // NOTE: Use nanosleep() on Unix platforms... usleep() it's deprecated. - while (nanosleep(&req, &req) == -1) continue; - #elif defined(__APPLE__) - usleep(ms*1000.0f); - #endif -#endif -} - -// Get one key state -static bool GetKeyStatus(int key) -{ -#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) - return glfwGetKey(window, key); -#elif defined(PLATFORM_ANDROID) - // NOTE: Android supports up to 260 keys - if (key < 0 || key > 260) return false; - else return currentKeyState[key]; -#elif defined(PLATFORM_RPI) - // NOTE: Keys states are filled in PollInputEvents() - if (key < 0 || key > 511) return false; - else return currentKeyState[key]; -#endif -} - -// Get one mouse button state -static bool GetMouseButtonStatus(int button) -{ -#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) - return glfwGetMouseButton(window, button); -#elif defined(PLATFORM_ANDROID) - // TODO: Check for virtual mouse? - return false; -#elif defined(PLATFORM_RPI) - // NOTE: Mouse buttons states are filled in PollInputEvents() - return currentMouseState[button]; -#endif -} - -// Poll (store) all input events -static void PollInputEvents(void) -{ -#if defined(SUPPORT_GESTURES_SYSTEM) - // NOTE: Gestures update must be called every frame to reset gestures correctly - // because ProcessGestureEvent() is just called on an event, not every frame - UpdateGestures(); -#endif - - // Reset last key pressed registered - lastKeyPressed = -1; - -#if !defined(PLATFORM_RPI) - // Reset last gamepad button/axis registered state - lastGamepadButtonPressed = -1; - gamepadAxisCount = 0; -#endif - -#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) - // Mouse input polling - double mouseX; - double mouseY; - - glfwGetCursorPos(window, &mouseX, &mouseY); - - mousePosition.x = (float)mouseX; - mousePosition.y = (float)mouseY; - - // Keyboard input polling (automatically managed by GLFW3 through callback) - - // Register previous keys states - for (int i = 0; i < 512; i++) previousKeyState[i] = currentKeyState[i]; - - // Register previous mouse states - for (int i = 0; i < 3; i++) previousMouseState[i] = currentMouseState[i]; - - previousMouseWheelY = currentMouseWheelY; - currentMouseWheelY = 0; -#endif - -#if defined(PLATFORM_DESKTOP) - // Check if gamepads are ready - // NOTE: We do it here in case of disconection - for (int i = 0; i < MAX_GAMEPADS; i++) - { - if (glfwJoystickPresent(i)) gamepadReady[i] = true; - else gamepadReady[i] = false; - } - - // Register gamepads buttons events - for (int i = 0; i < MAX_GAMEPADS; i++) - { - if (gamepadReady[i]) // Check if gamepad is available - { - // Register previous gamepad states - for (int k = 0; k < MAX_GAMEPAD_BUTTONS; k++) previousGamepadState[i][k] = currentGamepadState[i][k]; - - // Get current gamepad state - // NOTE: There is no callback available, so we get it manually - const unsigned char *buttons; - int buttonsCount; - - buttons = glfwGetJoystickButtons(i, &buttonsCount); - - for (int k = 0; (buttons != NULL) && (k < buttonsCount) && (buttonsCount < MAX_GAMEPAD_BUTTONS); k++) - { - if (buttons[k] == GLFW_PRESS) - { - currentGamepadState[i][k] = 1; - lastGamepadButtonPressed = k; - } - else currentGamepadState[i][k] = 0; - } - - // Get current axis state - const float *axes; - int axisCount = 0; - - axes = glfwGetJoystickAxes(i, &axisCount); - - for (int k = 0; (axes != NULL) && (k < axisCount) && (k < MAX_GAMEPAD_AXIS); k++) - { - gamepadAxisState[i][k] = axes[k]; - } - - gamepadAxisCount = axisCount; - } - } - - glfwPollEvents(); // Register keyboard/mouse events (callbacks)... and window events! -#endif - -// Gamepad support using emscripten API -// NOTE: GLFW3 joystick functionality not available in web -#if defined(PLATFORM_WEB) - // Get number of gamepads connected - int numGamepads = emscripten_get_num_gamepads(); - - for (int i = 0; (i < numGamepads) && (i < MAX_GAMEPADS); i++) - { - // Register previous gamepad button states - for (int k = 0; k < MAX_GAMEPAD_BUTTONS; k++) previousGamepadState[i][k] = currentGamepadState[i][k]; - - EmscriptenGamepadEvent gamepadState; - - int result = emscripten_get_gamepad_status(i, &gamepadState); - - if (result == EMSCRIPTEN_RESULT_SUCCESS) - { - // Register buttons data for every connected gamepad - for (int j = 0; (j < gamepadState.numButtons) && (j < MAX_GAMEPAD_BUTTONS); j++) - { - if (gamepadState.digitalButton[j] == 1) - { - currentGamepadState[i][j] = 1; - lastGamepadButtonPressed = j; - } - else currentGamepadState[i][j] = 0; - - //printf("Gamepad %d, button %d: Digital: %d, Analog: %g\n", gamepadState.index, j, gamepadState.digitalButton[j], gamepadState.analogButton[j]); - } - - // Register axis data for every connected gamepad - for (int j = 0; (j < gamepadState.numAxes) && (j < MAX_GAMEPAD_AXIS); j++) - { - gamepadAxisState[i][j] = gamepadState.axis[j]; - } - - gamepadAxisCount = gamepadState.numAxes; - } - } -#endif - -#if defined(PLATFORM_ANDROID) - // Register previous keys states - // NOTE: Android supports up to 260 keys - for (int i = 0; i < 260; i++) previousKeyState[i] = currentKeyState[i]; - - // Poll Events (registered events) - // NOTE: Activity is paused if not enabled (appEnabled) - while ((ident = ALooper_pollAll(appEnabled ? 0 : -1, NULL, &events,(void**)&source)) >= 0) - { - // Process this event - if (source != NULL) source->process(app, source); - - // NOTE: Never close window, native activity is controlled by the system! - if (app->destroyRequested != 0) - { - //TraceLog(LOG_INFO, "Closing Window..."); - //windowShouldClose = true; - //ANativeActivity_finish(app->activity); - } - } -#endif - -#if defined(PLATFORM_RPI) - // NOTE: Mouse input events polling is done asynchonously in another pthread - MouseThread() - - // NOTE: Keyboard reading could be done using input_event(s) reading or just read from stdin, - // we use method 2 (stdin) but maybe in a future we should change to method 1... - ProcessKeyboard(); - - // NOTE: Gamepad (Joystick) input events polling is done asynchonously in another pthread - GamepadThread() -#endif -} - -// Copy back buffer to front buffers -static void SwapBuffers(void) -{ -#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) - glfwSwapBuffers(window); -#endif - -#if defined(PLATFORM_ANDROID) || defined(PLATFORM_RPI) - eglSwapBuffers(display, surface); -#endif -} - -#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) -// GLFW3 Error Callback, runs on GLFW3 error -static void ErrorCallback(int error, const char *description) -{ - TraceLog(LOG_WARNING, "[GLFW3 Error] Code: %i Decription: %s", error, description); -} - -// GLFW3 Srolling Callback, runs on mouse wheel -static void ScrollCallback(GLFWwindow *window, double xoffset, double yoffset) -{ - currentMouseWheelY = (int)yoffset; -} - -// GLFW3 Keyboard Callback, runs on key pressed -static void KeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) -{ - if (key == exitKey && action == GLFW_PRESS) - { - glfwSetWindowShouldClose(window, GL_TRUE); - - // NOTE: Before closing window, while loop must be left! - } -#if defined(PLATFORM_DESKTOP) - else if (key == GLFW_KEY_F12 && action == GLFW_PRESS) - { - #if defined(SUPPORT_GIF_RECORDING) - if (mods == GLFW_MOD_CONTROL) - { - if (gifRecording) - { - GifEnd(); - gifRecording = false; - - TraceLog(LOG_INFO, "End animated GIF recording"); - } - else - { - gifRecording = true; - gifFramesCounter = 0; - - // NOTE: delay represents the time between frames in the gif, if we capture a gif frame every - // 10 game frames and each frame trakes 16.6ms (60fps), delay between gif frames should be ~16.6*10. - GifBegin(FormatText("screenrec%03i.gif", screenshotCounter), screenWidth, screenHeight, (int)(GetFrameTime()*10.0f), 8, false); - screenshotCounter++; - - TraceLog(LOG_INFO, "Begin animated GIF recording: %s", FormatText("screenrec%03i.gif", screenshotCounter)); - } - } - else - #endif // SUPPORT_GIF_RECORDING - { - TakeScreenshot(FormatText("screenshot%03i.png", screenshotCounter)); - screenshotCounter++; - } - } -#endif // PLATFORM_DESKTOP - else - { - currentKeyState[key] = action; - if (action == GLFW_PRESS) lastKeyPressed = key; - } -} - -// GLFW3 Mouse Button Callback, runs on mouse button pressed -static void MouseButtonCallback(GLFWwindow *window, int button, int action, int mods) -{ - currentMouseState[button] = action; - -#if defined(SUPPORT_GESTURES_SYSTEM) && defined(SUPPORT_MOUSE_GESTURES) - // Process mouse events as touches to be able to use mouse-gestures - GestureEvent gestureEvent; - - // Register touch actions - if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) gestureEvent.touchAction = TOUCH_DOWN; - else if (IsMouseButtonReleased(MOUSE_LEFT_BUTTON)) gestureEvent.touchAction = TOUCH_UP; - - // NOTE: TOUCH_MOVE event is registered in MouseCursorPosCallback() - - // Assign a pointer ID - gestureEvent.pointerId[0] = 0; - - // Register touch points count - gestureEvent.pointCount = 1; - - // Register touch points position, only one point registered - gestureEvent.position[0] = GetMousePosition(); - - // Normalize gestureEvent.position[0] for screenWidth and screenHeight - gestureEvent.position[0].x /= (float)GetScreenWidth(); - gestureEvent.position[0].y /= (float)GetScreenHeight(); - - // Gesture data is sent to gestures system for processing - ProcessGestureEvent(gestureEvent); -#endif -} - -// GLFW3 Cursor Position Callback, runs on mouse move -static void MouseCursorPosCallback(GLFWwindow *window, double x, double y) -{ -#if defined(SUPPORT_GESTURES_SYSTEM) && defined(SUPPORT_MOUSE_GESTURES) - // Process mouse events as touches to be able to use mouse-gestures - GestureEvent gestureEvent; - - gestureEvent.touchAction = TOUCH_MOVE; - - // Assign a pointer ID - gestureEvent.pointerId[0] = 0; - - // Register touch points count - gestureEvent.pointCount = 1; - - // Register touch points position, only one point registered - gestureEvent.position[0] = (Vector2){ (float)x, (float)y }; - - touchPosition[0] = gestureEvent.position[0]; - - // Normalize gestureEvent.position[0] for screenWidth and screenHeight - gestureEvent.position[0].x /= (float)GetScreenWidth(); - gestureEvent.position[0].y /= (float)GetScreenHeight(); - - // Gesture data is sent to gestures system for processing - ProcessGestureEvent(gestureEvent); -#endif -} - -// GLFW3 Char Key Callback, runs on key pressed (get char value) -static void CharCallback(GLFWwindow *window, unsigned int key) -{ - lastKeyPressed = key; - - //TraceLog(LOG_INFO, "Char Callback Key pressed: %i\n", key); -} - -// GLFW3 CursorEnter Callback, when cursor enters the window -static void CursorEnterCallback(GLFWwindow *window, int enter) -{ - if (enter == true) cursorOnScreen = true; - else cursorOnScreen = false; -} - -// GLFW3 WindowSize Callback, runs when window is resized -// NOTE: Window resizing not allowed by default -static void WindowSizeCallback(GLFWwindow *window, int width, int height) -{ - // If window is resized, viewport and projection matrix needs to be re-calculated - rlViewport(0, 0, width, height); // Set viewport width and height - rlMatrixMode(RL_PROJECTION); // Switch to PROJECTION matrix - rlLoadIdentity(); // Reset current matrix (PROJECTION) - rlOrtho(0, width, height, 0, 0.0f, 1.0f); // Orthographic projection mode with top-left corner at (0,0) - rlMatrixMode(RL_MODELVIEW); // Switch back to MODELVIEW matrix - rlLoadIdentity(); // Reset current matrix (MODELVIEW) - rlClearScreenBuffers(); // Clear screen buffers (color and depth) - - // Window size must be updated to be used on 3D mode to get new aspect ratio (Begin3dMode()) - screenWidth = width; - screenHeight = height; - renderWidth = width; - renderHeight = height; - - // NOTE: Postprocessing texture is not scaled to new size -} - -// GLFW3 WindowIconify Callback, runs when window is minimized/restored -static void WindowIconifyCallback(GLFWwindow* window, int iconified) -{ - if (iconified) windowMinimized = true; // The window was iconified - else windowMinimized = false; // The window was restored -} -#endif - -#if defined(PLATFORM_DESKTOP) -// GLFW3 Window Drop Callback, runs when drop files into window -// NOTE: Paths are stored in dinamic memory for further retrieval -// Everytime new files are dropped, old ones are discarded -static void WindowDropCallback(GLFWwindow *window, int count, const char **paths) -{ - ClearDroppedFiles(); - - dropFilesPath = (char **)malloc(sizeof(char *)*count); - - for (int i = 0; i < count; i++) - { - dropFilesPath[i] = (char *)malloc(sizeof(char)*256); // Max path length set to 256 char - strcpy(dropFilesPath[i], paths[i]); - } - - dropFilesCount = count; -} -#endif - -#if defined(PLATFORM_ANDROID) -// Android: Process activity lifecycle commands -static void AndroidCommandCallback(struct android_app *app, int32_t cmd) -{ - switch (cmd) - { - case APP_CMD_START: - { - //rendering = true; - TraceLog(LOG_INFO, "APP_CMD_START"); - } break; - case APP_CMD_RESUME: - { - TraceLog(LOG_INFO, "APP_CMD_RESUME"); - } break; - case APP_CMD_INIT_WINDOW: - { - TraceLog(LOG_INFO, "APP_CMD_INIT_WINDOW"); - - if (app->window != NULL) - { - if (contextRebindRequired) - { - // Reset screen scaling to full display size - EGLint displayFormat; - eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &displayFormat); - ANativeWindow_setBuffersGeometry(app->window, renderWidth, renderHeight, displayFormat); - - // Recreate display surface and re-attach OpenGL context - surface = eglCreateWindowSurface(display, config, app->window, NULL); - eglMakeCurrent(display, surface, surface, context); - - contextRebindRequired = false; - } - else - { - // Init graphics device (display device and OpenGL context) - InitGraphicsDevice(screenWidth, screenHeight); - - #if defined(SUPPORT_DEFAULT_FONT) - // Load default font - // NOTE: External function (defined in module: text) - LoadDefaultFont(); - #endif - - // TODO: GPU assets reload in case of lost focus (lost context) - // NOTE: This problem has been solved just unbinding and rebinding context from display - /* - if (assetsReloadRequired) - { - for (int i = 0; i < assetsCount; i++) - { - // TODO: Unload old asset if required - - // Load texture again to pointed texture - (*textureAsset + i) = LoadTexture(assetPath[i]); - } - } - */ - - // Init hi-res timer - InitTimer(); - - // raylib logo appearing animation (if enabled) - if (showLogo) - { - SetTargetFPS(60); // Not required on Android - LogoAnimation(); - } - } - } - } break; - case APP_CMD_GAINED_FOCUS: - { - TraceLog(LOG_INFO, "APP_CMD_GAINED_FOCUS"); - appEnabled = true; - //ResumeMusicStream(); - } break; - case APP_CMD_PAUSE: - { - TraceLog(LOG_INFO, "APP_CMD_PAUSE"); - } break; - case APP_CMD_LOST_FOCUS: - { - //DrawFrame(); - TraceLog(LOG_INFO, "APP_CMD_LOST_FOCUS"); - appEnabled = false; - //PauseMusicStream(); - } break; - case APP_CMD_TERM_WINDOW: - { - // Dettach OpenGL context and destroy display surface - // NOTE 1: Detaching context before destroying display surface avoids losing our resources (textures, shaders, VBOs...) - // NOTE 2: In some cases (too many context loaded), OS could unload context automatically... :( - eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); - eglDestroySurface(display, surface); - - contextRebindRequired = true; - - TraceLog(LOG_INFO, "APP_CMD_TERM_WINDOW"); - } break; - case APP_CMD_SAVE_STATE: - { - TraceLog(LOG_INFO, "APP_CMD_SAVE_STATE"); - } break; - case APP_CMD_STOP: - { - TraceLog(LOG_INFO, "APP_CMD_STOP"); - } break; - case APP_CMD_DESTROY: - { - // TODO: Finish activity? - //ANativeActivity_finish(app->activity); - - TraceLog(LOG_INFO, "APP_CMD_DESTROY"); - } break; - case APP_CMD_CONFIG_CHANGED: - { - //AConfiguration_fromAssetManager(app->config, app->activity->assetManager); - //print_cur_config(app); - - // Check screen orientation here! - - TraceLog(LOG_INFO, "APP_CMD_CONFIG_CHANGED"); - } break; - default: break; - } -} - -// Android: Get input events -static int32_t AndroidInputCallback(struct android_app *app, AInputEvent *event) -{ - //http://developer.android.com/ndk/reference/index.html - - int type = AInputEvent_getType(event); - - if (type == AINPUT_EVENT_TYPE_MOTION) - { - // Get first touch position - touchPosition[0].x = AMotionEvent_getX(event, 0); - touchPosition[0].y = AMotionEvent_getY(event, 0); - - // Get second touch position - touchPosition[1].x = AMotionEvent_getX(event, 1); - touchPosition[1].y = AMotionEvent_getY(event, 1); - } - else if (type == AINPUT_EVENT_TYPE_KEY) - { - int32_t keycode = AKeyEvent_getKeyCode(event); - //int32_t AKeyEvent_getMetaState(event); - - // Save current button and its state - // NOTE: Android key action is 0 for down and 1 for up - if (AKeyEvent_getAction(event) == 0) - { - currentKeyState[keycode] = 1; // Key down - lastKeyPressed = keycode; - } - else currentKeyState[keycode] = 0; // Key up - - if (keycode == AKEYCODE_POWER) - { - // Let the OS handle input to avoid app stuck. Behaviour: CMD_PAUSE -> CMD_SAVE_STATE -> CMD_STOP -> CMD_CONFIG_CHANGED -> CMD_LOST_FOCUS - // Resuming Behaviour: CMD_START -> CMD_RESUME -> CMD_CONFIG_CHANGED -> CMD_CONFIG_CHANGED -> CMD_GAINED_FOCUS - // It seems like locking mobile, screen size (CMD_CONFIG_CHANGED) is affected. - // NOTE: AndroidManifest.xml must have - // Before that change, activity was calling CMD_TERM_WINDOW and CMD_DESTROY when locking mobile, so that was not a normal behaviour - return 0; - } - else if ((keycode == AKEYCODE_BACK) || (keycode == AKEYCODE_MENU)) - { - // Eat BACK_BUTTON and AKEYCODE_MENU, just do nothing... and don't let to be handled by OS! - return 1; - } - else if ((keycode == AKEYCODE_VOLUME_UP) || (keycode == AKEYCODE_VOLUME_DOWN)) - { - // Set default OS behaviour - return 0; - } - } - - int32_t action = AMotionEvent_getAction(event); - unsigned int flags = action & AMOTION_EVENT_ACTION_MASK; - -#if defined(SUPPORT_GESTURES_SYSTEM) - GestureEvent gestureEvent; - - // Register touch actions - if (flags == AMOTION_EVENT_ACTION_DOWN) gestureEvent.touchAction = TOUCH_DOWN; - else if (flags == AMOTION_EVENT_ACTION_UP) gestureEvent.touchAction = TOUCH_UP; - else if (flags == AMOTION_EVENT_ACTION_MOVE) gestureEvent.touchAction = TOUCH_MOVE; - - // Register touch points count - gestureEvent.pointCount = AMotionEvent_getPointerCount(event); - - // Register touch points id - gestureEvent.pointerId[0] = AMotionEvent_getPointerId(event, 0); - gestureEvent.pointerId[1] = AMotionEvent_getPointerId(event, 1); - - // Register touch points position - // NOTE: Only two points registered - gestureEvent.position[0] = (Vector2){ AMotionEvent_getX(event, 0), AMotionEvent_getY(event, 0) }; - gestureEvent.position[1] = (Vector2){ AMotionEvent_getX(event, 1), AMotionEvent_getY(event, 1) }; - - // Normalize gestureEvent.position[x] for screenWidth and screenHeight - gestureEvent.position[0].x /= (float)GetScreenWidth(); - gestureEvent.position[0].y /= (float)GetScreenHeight(); - - gestureEvent.position[1].x /= (float)GetScreenWidth(); - gestureEvent.position[1].y /= (float)GetScreenHeight(); - - // Gesture data is sent to gestures system for processing - ProcessGestureEvent(gestureEvent); -#else - - // TODO: Support only simple touch position - -#endif - - return 0; -} -#endif - -#if defined(PLATFORM_WEB) - -// Register fullscreen change events -static EM_BOOL EmscriptenFullscreenChangeCallback(int eventType, const EmscriptenFullscreenChangeEvent *e, void *userData) -{ - //isFullscreen: int e->isFullscreen - //fullscreenEnabled: int e->fullscreenEnabled - //fs element nodeName: (char *) e->nodeName - //fs element id: (char *) e->id - //Current element size: (int) e->elementWidth, (int) e->elementHeight - //Screen size:(int) e->screenWidth, (int) e->screenHeight - - if (e->isFullscreen) - { - TraceLog(LOG_INFO, "Canvas scaled to fullscreen. ElementSize: (%ix%i), ScreenSize(%ix%i)", e->elementWidth, e->elementHeight, e->screenWidth, e->screenHeight); - } - else - { - TraceLog(LOG_INFO, "Canvas scaled to windowed. ElementSize: (%ix%i), ScreenSize(%ix%i)", e->elementWidth, e->elementHeight, e->screenWidth, e->screenHeight); - } - - // TODO: Depending on scaling factor (screen vs element), calculate factor to scale mouse/touch input - - return 0; -} - -// Register keyboard input events -static EM_BOOL EmscriptenKeyboardCallback(int eventType, const EmscriptenKeyboardEvent *keyEvent, void *userData) -{ - if ((eventType == EMSCRIPTEN_EVENT_KEYPRESS) && (strcmp(keyEvent->code, "Escape") == 0)) - { - emscripten_exit_pointerlock(); - } - - return 0; -} - -// Register mouse input events -static EM_BOOL EmscriptenMouseCallback(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData) -{ - // Lock mouse pointer when click on screen - if ((eventType == EMSCRIPTEN_EVENT_CLICK) && toggleCursorLock) - { - EmscriptenPointerlockChangeEvent plce; - emscripten_get_pointerlock_status(&plce); - - if (!plce.isActive) emscripten_request_pointerlock(0, 1); - else - { - emscripten_exit_pointerlock(); - emscripten_get_pointerlock_status(&plce); - //if (plce.isActive) TraceLog(LOG_WARNING, "Pointer lock exit did not work!"); - } - - toggleCursorLock = false; - } - - return 0; -} - -// Register touch input events -static EM_BOOL EmscriptenTouchCallback(int eventType, const EmscriptenTouchEvent *touchEvent, void *userData) -{ - /* - for (int i = 0; i < touchEvent->numTouches; i++) - { - long x, y, id; - - if (!touchEvent->touches[i].isChanged) continue; - - id = touchEvent->touches[i].identifier; - x = touchEvent->touches[i].canvasX; - y = touchEvent->touches[i].canvasY; - } - - printf("%s, numTouches: %d %s%s%s%s\n", emscripten_event_type_to_string(eventType), event->numTouches, - event->ctrlKey ? " CTRL" : "", event->shiftKey ? " SHIFT" : "", event->altKey ? " ALT" : "", event->metaKey ? " META" : ""); - - for (int i = 0; i < event->numTouches; ++i) - { - const EmscriptenTouchPoint *t = &event->touches[i]; - - printf(" %ld: screen: (%ld,%ld), client: (%ld,%ld), page: (%ld,%ld), isChanged: %d, onTarget: %d, canvas: (%ld, %ld)\n", - t->identifier, t->screenX, t->screenY, t->clientX, t->clientY, t->pageX, t->pageY, t->isChanged, t->onTarget, t->canvasX, t->canvasY); - } - */ - - GestureEvent gestureEvent; - - // Register touch actions - if (eventType == EMSCRIPTEN_EVENT_TOUCHSTART) gestureEvent.touchAction = TOUCH_DOWN; - else if (eventType == EMSCRIPTEN_EVENT_TOUCHEND) gestureEvent.touchAction = TOUCH_UP; - else if (eventType == EMSCRIPTEN_EVENT_TOUCHMOVE) gestureEvent.touchAction = TOUCH_MOVE; - - // Register touch points count - gestureEvent.pointCount = touchEvent->numTouches; - - // Register touch points id - gestureEvent.pointerId[0] = touchEvent->touches[0].identifier; - gestureEvent.pointerId[1] = touchEvent->touches[1].identifier; - - // Register touch points position - // NOTE: Only two points registered - // TODO: Touch data should be scaled accordingly! - //gestureEvent.position[0] = (Vector2){ touchEvent->touches[0].canvasX, touchEvent->touches[0].canvasY }; - //gestureEvent.position[1] = (Vector2){ touchEvent->touches[1].canvasX, touchEvent->touches[1].canvasY }; - gestureEvent.position[0] = (Vector2){ touchEvent->touches[0].targetX, touchEvent->touches[0].targetY }; - gestureEvent.position[1] = (Vector2){ touchEvent->touches[1].targetX, touchEvent->touches[1].targetY }; - - touchPosition[0] = gestureEvent.position[0]; - touchPosition[1] = gestureEvent.position[1]; - - // Normalize gestureEvent.position[x] for screenWidth and screenHeight - gestureEvent.position[0].x /= (float)GetScreenWidth(); - gestureEvent.position[0].y /= (float)GetScreenHeight(); - - gestureEvent.position[1].x /= (float)GetScreenWidth(); - gestureEvent.position[1].y /= (float)GetScreenHeight(); - - // Gesture data is sent to gestures system for processing - ProcessGestureEvent(gestureEvent); - - return 1; -} - -// Register connected/disconnected gamepads events -static EM_BOOL EmscriptenGamepadCallback(int eventType, const EmscriptenGamepadEvent *gamepadEvent, void *userData) -{ - /* - printf("%s: timeStamp: %g, connected: %d, index: %ld, numAxes: %d, numButtons: %d, id: \"%s\", mapping: \"%s\"\n", - eventType != 0 ? emscripten_event_type_to_string(eventType) : "Gamepad state", - gamepadEvent->timestamp, gamepadEvent->connected, gamepadEvent->index, gamepadEvent->numAxes, gamepadEvent->numButtons, gamepadEvent->id, gamepadEvent->mapping); - - for(int i = 0; i < gamepadEvent->numAxes; ++i) printf("Axis %d: %g\n", i, gamepadEvent->axis[i]); - for(int i = 0; i < gamepadEvent->numButtons; ++i) printf("Button %d: Digital: %d, Analog: %g\n", i, gamepadEvent->digitalButton[i], gamepadEvent->analogButton[i]); - */ - - if ((gamepadEvent->connected) && (gamepadEvent->index < MAX_GAMEPADS)) gamepadReady[gamepadEvent->index] = true; - else gamepadReady[gamepadEvent->index] = false; - - // TODO: Test gamepadEvent->index - - return 0; -} -#endif - -#if defined(PLATFORM_RPI) -// Initialize Keyboard system (using standard input) -static void InitKeyboard(void) -{ - // NOTE: We read directly from Standard Input (stdin) - STDIN_FILENO file descriptor - - // Make stdin non-blocking (not enough, need to configure to non-canonical mode) - int flags = fcntl(STDIN_FILENO, F_GETFL, 0); // F_GETFL: Get the file access mode and the file status flags - fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK); // F_SETFL: Set the file status flags to the value specified - - // Save terminal keyboard settings and reconfigure terminal with new settings - struct termios keyboardNewSettings; - tcgetattr(STDIN_FILENO, &defaultKeyboardSettings); // Get current keyboard settings - keyboardNewSettings = defaultKeyboardSettings; - - // New terminal settings for keyboard: turn off buffering (non-canonical mode), echo and key processing - // NOTE: ISIG controls if ^C and ^Z generate break signals or not - keyboardNewSettings.c_lflag &= ~(ICANON | ECHO | ISIG); - //keyboardNewSettings.c_iflag &= ~(ISTRIP | INLCR | ICRNL | IGNCR | IXON | IXOFF); - keyboardNewSettings.c_cc[VMIN] = 1; - keyboardNewSettings.c_cc[VTIME] = 0; - - // Set new keyboard settings (change occurs immediately) - tcsetattr(STDIN_FILENO, TCSANOW, &keyboardNewSettings); - - // NOTE: Reading directly from stdin will give chars already key-mapped by kernel to ASCII or UNICODE, we change that! -> WHY??? - - // Save old keyboard mode to restore it at the end - if (ioctl(STDIN_FILENO, KDGKBMODE, &defaultKeyboardMode) < 0) - { - // NOTE: It could mean we are using a remote keyboard through ssh! - TraceLog(LOG_WARNING, "Could not change keyboard mode (SSH keyboard?)"); - } - else - { - // We reconfigure keyboard mode to get: - // - scancodes (K_RAW) - // - keycodes (K_MEDIUMRAW) - // - ASCII chars (K_XLATE) - // - UNICODE chars (K_UNICODE) - ioctl(STDIN_FILENO, KDSKBMODE, K_XLATE); - } - - // Register keyboard restore when program finishes - atexit(RestoreKeyboard); -} - -// Process keyboard inputs -// TODO: Most probably input reading and processing should be in a separate thread -static void ProcessKeyboard(void) -{ - #define MAX_KEYBUFFER_SIZE 32 // Max size in bytes to read - - // Keyboard input polling (fill keys[256] array with status) - int bufferByteCount = 0; // Bytes available on the buffer - char keysBuffer[MAX_KEYBUFFER_SIZE]; // Max keys to be read at a time - - // Reset pressed keys array - for (int i = 0; i < 512; i++) currentKeyState[i] = 0; - - // Read availables keycodes from stdin - bufferByteCount = read(STDIN_FILENO, keysBuffer, MAX_KEYBUFFER_SIZE); // POSIX system call - - // Fill all read bytes (looking for keys) - for (int i = 0; i < bufferByteCount; i++) - { - TraceLog(LOG_DEBUG, "Bytes on keysBuffer: %i", bufferByteCount); - - //printf("Key(s) bytes: "); - //for (int i = 0; i < bufferByteCount; i++) printf("0x%02x ", keysBuffer[i]); - //printf("\n"); - - // NOTE: If (key == 0x1b), depending on next key, it could be a special keymap code! - // Up -> 1b 5b 41 / Left -> 1b 5b 44 / Right -> 1b 5b 43 / Down -> 1b 5b 42 - if (keysBuffer[i] == 0x1b) - { - // Detect ESC to stop program - if (bufferByteCount == 1) currentKeyState[256] = 1; // raylib key: KEY_ESCAPE - else - { - if (keysBuffer[i + 1] == 0x5b) // Special function key - { - if ((keysBuffer[i + 2] == 0x5b) || (keysBuffer[i + 2] == 0x31) || (keysBuffer[i + 2] == 0x32)) - { - // Process special function keys (F1 - F12) - switch (keysBuffer[i + 3]) - { - case 0x41: currentKeyState[290] = 1; break; // raylib KEY_F1 - case 0x42: currentKeyState[291] = 1; break; // raylib KEY_F2 - case 0x43: currentKeyState[292] = 1; break; // raylib KEY_F3 - case 0x44: currentKeyState[293] = 1; break; // raylib KEY_F4 - case 0x45: currentKeyState[294] = 1; break; // raylib KEY_F5 - case 0x37: currentKeyState[295] = 1; break; // raylib KEY_F6 - case 0x38: currentKeyState[296] = 1; break; // raylib KEY_F7 - case 0x39: currentKeyState[297] = 1; break; // raylib KEY_F8 - case 0x30: currentKeyState[298] = 1; break; // raylib KEY_F9 - case 0x31: currentKeyState[299] = 1; break; // raylib KEY_F10 - case 0x33: currentKeyState[300] = 1; break; // raylib KEY_F11 - case 0x34: currentKeyState[301] = 1; break; // raylib KEY_F12 - default: break; - } - - if (keysBuffer[i + 2] == 0x5b) i += 4; - else if ((keysBuffer[i + 2] == 0x31) || (keysBuffer[i + 2] == 0x32)) i += 5; - } - else - { - switch (keysBuffer[i + 2]) - { - case 0x41: currentKeyState[265] = 1; break; // raylib KEY_UP - case 0x42: currentKeyState[264] = 1; break; // raylib KEY_DOWN - case 0x43: currentKeyState[262] = 1; break; // raylib KEY_RIGHT - case 0x44: currentKeyState[263] = 1; break; // raylib KEY_LEFT - default: break; - } - - i += 3; // Jump to next key - } - - // NOTE: Some keys are not directly keymapped (CTRL, ALT, SHIFT) - } - } - } - else if (keysBuffer[i] == 0x0a) currentKeyState[257] = 1; // raylib KEY_ENTER (don't mix with KEY_*) - else if (keysBuffer[i] == 0x7f) currentKeyState[259] = 1; // raylib KEY_BACKSPACE - else - { - TraceLog(LOG_DEBUG, "Pressed key (ASCII): 0x%02x", keysBuffer[i]); - - // Translate lowercase a-z letters to A-Z - if ((keysBuffer[i] >= 97) && (keysBuffer[i] <= 122)) - { - currentKeyState[(int)keysBuffer[i] - 32] = 1; - } - else currentKeyState[(int)keysBuffer[i]] = 1; - } - } - - // Check exit key (same functionality as GLFW3 KeyCallback()) - if (currentKeyState[exitKey] == 1) windowShouldClose = true; - - // Check screen capture key (raylib key: KEY_F12) - if (currentKeyState[301] == 1) - { - TakeScreenshot(FormatText("screenshot%03i.png", screenshotCounter)); - screenshotCounter++; - } -} - -// Restore default keyboard input -static void RestoreKeyboard(void) -{ - // Reset to default keyboard settings - tcsetattr(STDIN_FILENO, TCSANOW, &defaultKeyboardSettings); - - // Reconfigure keyboard to default mode - ioctl(STDIN_FILENO, KDSKBMODE, defaultKeyboardMode); -} - -// Mouse initialization (including mouse thread) -static void InitMouse(void) -{ - // NOTE: We can use /dev/input/mice to read from all available mice - if ((mouseStream = open(DEFAULT_MOUSE_DEV, O_RDONLY|O_NONBLOCK)) < 0) - { - TraceLog(LOG_WARNING, "Mouse device could not be opened, no mouse available"); - } - else - { - mouseReady = true; - - int error = pthread_create(&mouseThreadId, NULL, &MouseThread, NULL); - - if (error != 0) TraceLog(LOG_WARNING, "Error creating mouse input event thread"); - else TraceLog(LOG_INFO, "Mouse device initialized successfully"); - } -} - -// Mouse reading thread -// NOTE: We need a separate thread to avoid loosing mouse events, -// if too much time passes between reads, queue gets full and new events override older ones... -static void *MouseThread(void *arg) -{ - const unsigned char XSIGN = (1 << 4); - const unsigned char YSIGN = (1 << 5); - - typedef struct { - char buttons; - char dx, dy; - } MouseEvent; - - MouseEvent mouse; - - int mouseRelX = 0; - int mouseRelY = 0; - - while (!windowShouldClose) - { - if (read(mouseStream, &mouse, sizeof(MouseEvent)) == (int)sizeof(MouseEvent)) - { - if ((mouse.buttons & 0x08) == 0) break; // This bit should always be set - - // Check Left button pressed - if ((mouse.buttons & 0x01) > 0) currentMouseState[0] = 1; - else currentMouseState[0] = 0; - - // Check Right button pressed - if ((mouse.buttons & 0x02) > 0) currentMouseState[1] = 1; - else currentMouseState[1] = 0; - - // Check Middle button pressed - if ((mouse.buttons & 0x04) > 0) currentMouseState[2] = 1; - else currentMouseState[2] = 0; - - mouseRelX = (int)mouse.dx; - mouseRelY = (int)mouse.dy; - - if ((mouse.buttons & XSIGN) > 0) mouseRelX = -1*(255 - mouseRelX); - if ((mouse.buttons & YSIGN) > 0) mouseRelY = -1*(255 - mouseRelY); - - // NOTE: Mouse movement is normalized to not be screen resolution dependant - // We suppose 2*255 (max relative movement) is equivalent to screenWidth (max pixels width) - // Result after normalization is multiplied by MOUSE_SENSITIVITY factor - - mousePosition.x += (float)mouseRelX*((float)screenWidth/(2*255))*MOUSE_SENSITIVITY; - mousePosition.y -= (float)mouseRelY*((float)screenHeight/(2*255))*MOUSE_SENSITIVITY; - - if (mousePosition.x < 0) mousePosition.x = 0; - if (mousePosition.y < 0) mousePosition.y = 0; - - if (mousePosition.x > screenWidth) mousePosition.x = screenWidth; - if (mousePosition.y > screenHeight) mousePosition.y = screenHeight; - } - //else read(mouseStream, &mouse, 1); // Try to sync up again - } - - return NULL; -} - -// Touch initialization (including touch thread) -static void InitTouch(void) -{ - if ((touchStream = open(DEFAULT_TOUCH_DEV, O_RDONLY|O_NONBLOCK)) < 0) - { - TraceLog(LOG_WARNING, "Touch device could not be opened, no touchscreen available"); - } - else - { - touchReady = true; - - int error = pthread_create(&touchThreadId, NULL, &TouchThread, NULL); - - if (error != 0) TraceLog(LOG_WARNING, "Error creating touch input event thread"); - else TraceLog(LOG_INFO, "Touch device initialized successfully"); - } -} - -// Touch reading thread. -// This reads from a Virtual Input Event /dev/input/event4 which is -// created by the ts_uinput daemon. This takes, filters and scales -// raw input from the Touchscreen (which appears in /dev/input/event3) -// based on the Calibration data referenced by tslib. -static void *TouchThread(void *arg) -{ - struct input_event ev; - GestureEvent gestureEvent; - - while (!windowShouldClose) - { - if (read(touchStream, &ev, sizeof(ev)) == (int)sizeof(ev)) - { - // if pressure > 0 then simulate left mouse button click - if (ev.type == EV_ABS && ev.code == 24 && ev.value == 0 && currentMouseState[0] == 1) - { - currentMouseState[0] = 0; - gestureEvent.touchAction = TOUCH_UP; - gestureEvent.pointCount = 1; - gestureEvent.pointerId[0] = 0; - gestureEvent.pointerId[1] = 1; - gestureEvent.position[0] = (Vector2){ mousePosition.x, mousePosition.y }; - gestureEvent.position[1] = (Vector2){ mousePosition.x, mousePosition.y }; - gestureEvent.position[0].x /= (float)GetScreenWidth(); - gestureEvent.position[0].y /= (float)GetScreenHeight(); - gestureEvent.position[1].x /= (float)GetScreenWidth(); - gestureEvent.position[1].y /= (float)GetScreenHeight(); - ProcessGestureEvent(gestureEvent); - } - if (ev.type == EV_ABS && ev.code == 24 && ev.value > 0 && currentMouseState[0] == 0) - { - currentMouseState[0] = 1; - gestureEvent.touchAction = TOUCH_DOWN; - gestureEvent.pointCount = 1; - gestureEvent.pointerId[0] = 0; - gestureEvent.pointerId[1] = 1; - gestureEvent.position[0] = (Vector2){ mousePosition.x, mousePosition.y }; - gestureEvent.position[1] = (Vector2){ mousePosition.x, mousePosition.y }; - gestureEvent.position[0].x /= (float)GetScreenWidth(); - gestureEvent.position[0].y /= (float)GetScreenHeight(); - gestureEvent.position[1].x /= (float)GetScreenWidth(); - gestureEvent.position[1].y /= (float)GetScreenHeight(); - ProcessGestureEvent(gestureEvent); - } - // x & y values supplied by event4 have been scaled & de-jittered using tslib calibration data - if (ev.type == EV_ABS && ev.code == 0) - { - mousePosition.x = ev.value; - if (mousePosition.x < 0) mousePosition.x = 0; - if (mousePosition.x > screenWidth) mousePosition.x = screenWidth; - gestureEvent.touchAction = TOUCH_MOVE; - gestureEvent.pointCount = 1; - gestureEvent.pointerId[0] = 0; - gestureEvent.pointerId[1] = 1; - gestureEvent.position[0] = (Vector2){ mousePosition.x, mousePosition.y }; - gestureEvent.position[1] = (Vector2){ mousePosition.x, mousePosition.y }; - gestureEvent.position[0].x /= (float)GetScreenWidth(); - gestureEvent.position[0].y /= (float)GetScreenHeight(); - gestureEvent.position[1].x /= (float)GetScreenWidth(); - gestureEvent.position[1].y /= (float)GetScreenHeight(); - ProcessGestureEvent(gestureEvent); - } - if (ev.type == EV_ABS && ev.code == 1) - { - mousePosition.y = ev.value; - if (mousePosition.y < 0) mousePosition.y = 0; - if (mousePosition.y > screenHeight) mousePosition.y = screenHeight; - gestureEvent.touchAction = TOUCH_MOVE; - gestureEvent.pointCount = 1; - gestureEvent.pointerId[0] = 0; - gestureEvent.pointerId[1] = 1; - gestureEvent.position[0] = (Vector2){ mousePosition.x, mousePosition.y }; - gestureEvent.position[1] = (Vector2){ mousePosition.x, mousePosition.y }; - gestureEvent.position[0].x /= (float)GetScreenWidth(); - gestureEvent.position[0].y /= (float)GetScreenHeight(); - gestureEvent.position[1].x /= (float)GetScreenWidth(); - gestureEvent.position[1].y /= (float)GetScreenHeight(); - ProcessGestureEvent(gestureEvent); - } - - } - } - return NULL; -} - -// Init gamepad system -static void InitGamepad(void) -{ - char gamepadDev[128] = ""; - - for (int i = 0; i < MAX_GAMEPADS; i++) - { - sprintf(gamepadDev, "%s%i", DEFAULT_GAMEPAD_DEV, i); - - if ((gamepadStream[i] = open(gamepadDev, O_RDONLY|O_NONBLOCK)) < 0) - { - // NOTE: Only show message for first gamepad - if (i == 0) TraceLog(LOG_WARNING, "Gamepad device could not be opened, no gamepad available"); - } - else - { - gamepadReady[i] = true; - - // NOTE: Only create one thread - if (i == 0) - { - int error = pthread_create(&gamepadThreadId, NULL, &GamepadThread, NULL); - - if (error != 0) TraceLog(LOG_WARNING, "Error creating gamepad input event thread"); - else TraceLog(LOG_INFO, "Gamepad device initialized successfully"); - } - } - } -} - -// Process Gamepad (/dev/input/js0) -static void *GamepadThread(void *arg) -{ - #define JS_EVENT_BUTTON 0x01 // Button pressed/released - #define JS_EVENT_AXIS 0x02 // Joystick axis moved - #define JS_EVENT_INIT 0x80 // Initial state of device - - struct js_event { - unsigned int time; // event timestamp in milliseconds - short value; // event value - unsigned char type; // event type - unsigned char number; // event axis/button number - }; - - // Read gamepad event - struct js_event gamepadEvent; - - while (!windowShouldClose) - { - for (int i = 0; i < MAX_GAMEPADS; i++) - { - if (read(gamepadStream[i], &gamepadEvent, sizeof(struct js_event)) == (int)sizeof(struct js_event)) - { - gamepadEvent.type &= ~JS_EVENT_INIT; // Ignore synthetic events - - // Process gamepad events by type - if (gamepadEvent.type == JS_EVENT_BUTTON) - { - TraceLog(LOG_DEBUG, "Gamepad button: %i, value: %i", gamepadEvent.number, gamepadEvent.value); - - if (gamepadEvent.number < MAX_GAMEPAD_BUTTONS) - { - // 1 - button pressed, 0 - button released - currentGamepadState[i][gamepadEvent.number] = (int)gamepadEvent.value; - - if ((int)gamepadEvent.value == 1) lastGamepadButtonPressed = gamepadEvent.number; - else lastGamepadButtonPressed = -1; - } - } - else if (gamepadEvent.type == JS_EVENT_AXIS) - { - TraceLog(LOG_DEBUG, "Gamepad axis: %i, value: %i", gamepadEvent.number, gamepadEvent.value); - - if (gamepadEvent.number < MAX_GAMEPAD_AXIS) - { - // NOTE: Scaling of gamepadEvent.value to get values between -1..1 - gamepadAxisState[i][gamepadEvent.number] = (float)gamepadEvent.value/32768; - } - } - } - } - } - - return NULL; -} -#endif // PLATFORM_RPI - -// Plays raylib logo appearing animation -static void LogoAnimation(void) -{ -#if !defined(PLATFORM_WEB) - int logoPositionX = screenWidth/2 - 128; - int logoPositionY = screenHeight/2 - 128; - - int framesCounter = 0; - int lettersCount = 0; - - int topSideRecWidth = 16; - int leftSideRecHeight = 16; - - int bottomSideRecWidth = 16; - int rightSideRecHeight = 16; - - int state = 0; // Tracking animation states (State Machine) - float alpha = 1.0f; // Useful for fading - - while (!WindowShouldClose() && (state != 4)) // Detect window close button or ESC key - { - // Update - //---------------------------------------------------------------------------------- - if (state == 0) // State 0: Small box blinking - { - framesCounter++; - - if (framesCounter == 84) - { - state = 1; - framesCounter = 0; // Reset counter... will be used later... - } - } - else if (state == 1) // State 1: Top and left bars growing - { - topSideRecWidth += 4; - leftSideRecHeight += 4; - - if (topSideRecWidth == 256) state = 2; - } - else if (state == 2) // State 2: Bottom and right bars growing - { - bottomSideRecWidth += 4; - rightSideRecHeight += 4; - - if (bottomSideRecWidth == 256) state = 3; - } - else if (state == 3) // State 3: Letters appearing (one by one) - { - framesCounter++; - - if (framesCounter/12) // Every 12 frames, one more letter! - { - lettersCount++; - framesCounter = 0; - } - - if (lettersCount >= 10) // When all letters have appeared, just fade out everything - { - alpha -= 0.02f; - - if (alpha <= 0.0f) - { - alpha = 0.0f; - state = 4; - } - } - } - //---------------------------------------------------------------------------------- - - // Draw - //---------------------------------------------------------------------------------- - BeginDrawing(); - - ClearBackground(RAYWHITE); - - if (state == 0) - { - if ((framesCounter/12)%2) DrawRectangle(logoPositionX, logoPositionY, 16, 16, BLACK); - } - else if (state == 1) - { - DrawRectangle(logoPositionX, logoPositionY, topSideRecWidth, 16, BLACK); - DrawRectangle(logoPositionX, logoPositionY, 16, leftSideRecHeight, BLACK); - } - else if (state == 2) - { - DrawRectangle(logoPositionX, logoPositionY, topSideRecWidth, 16, BLACK); - DrawRectangle(logoPositionX, logoPositionY, 16, leftSideRecHeight, BLACK); - - DrawRectangle(logoPositionX + 240, logoPositionY, 16, rightSideRecHeight, BLACK); - DrawRectangle(logoPositionX, logoPositionY + 240, bottomSideRecWidth, 16, BLACK); - } - else if (state == 3) - { - DrawRectangle(logoPositionX, logoPositionY, topSideRecWidth, 16, Fade(BLACK, alpha)); - DrawRectangle(logoPositionX, logoPositionY + 16, 16, leftSideRecHeight - 32, Fade(BLACK, alpha)); - - DrawRectangle(logoPositionX + 240, logoPositionY + 16, 16, rightSideRecHeight - 32, Fade(BLACK, alpha)); - DrawRectangle(logoPositionX, logoPositionY + 240, bottomSideRecWidth, 16, Fade(BLACK, alpha)); - - DrawRectangle(screenWidth/2 - 112, screenHeight/2 - 112, 224, 224, Fade(RAYWHITE, alpha)); - - DrawText(SubText("raylib", 0, lettersCount), screenWidth/2 - 44, screenHeight/2 + 48, 50, Fade(BLACK, alpha)); - } - - EndDrawing(); - //---------------------------------------------------------------------------------- - } -#endif - - showLogo = false; // Prevent for repeating when reloading window (Android) -} diff --git a/game/src/libs/raylib/easings.h b/game/src/libs/raylib/easings.h deleted file mode 100644 index 9ad2731..0000000 --- a/game/src/libs/raylib/easings.h +++ /dev/null @@ -1,253 +0,0 @@ -/******************************************************************************************* -* -* raylib easings (header only file) -* -* Useful easing functions for values animation -* -* This header uses: -* #define EASINGS_STATIC_INLINE // Inlines all functions code, so it runs faster. -* // This requires lots of memory on system. -* How to use: -* The four inputs t,b,c,d are defined as follows: -* t = current time (in any unit measure, but same unit as duration) -* b = starting value to interpolate -* c = the total change in value of b that needs to occur -* d = total time it should take to complete (duration) -* -* Example: -* -* int currentTime = 0; -* int duration = 100; -* float startPositionX = 0.0f; -* float finalPositionX = 30.0f; -* float currentPositionX = startPositionX; -* -* while (currentPositionX < finalPositionX) -* { -* currentPositionX = EaseSineIn(currentTime, startPositionX, finalPositionX - startPositionX, duration); -* currentTime++; -* } -* -* A port of Robert Penner's easing equations to C (http://robertpenner.com/easing/) -* -* Robert Penner License -* --------------------------------------------------------------------------------- -* Open source under the BSD License. -* -* Copyright (c) 2001 Robert Penner. All rights reserved. -* -* Redistribution and use in source and binary forms, with or without modification, -* are permitted provided that the following conditions are met: -* -* - Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* - Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the documentation -* and/or other materials provided with the distribution. -* - Neither the name of the author nor the names of contributors may be used -* to endorse or promote products derived from this software without specific -* prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, -* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED -* OF THE POSSIBILITY OF SUCH DAMAGE. -* --------------------------------------------------------------------------------- -* -* Copyright (c) 2015 Ramon Santamaria -* -* This software is provided "as-is", without any express or implied warranty. In no event -* will the authors be held liable for any damages arising from the use of this software. -* -* Permission is granted to anyone to use this software for any purpose, including commercial -* applications, and to alter it and redistribute it freely, subject to the following restrictions: -* -* 1. The origin of this software must not be misrepresented; you must not claim that you -* wrote the original software. If you use this software in a product, an acknowledgment -* in the product documentation would be appreciated but is not required. -* -* 2. Altered source versions must be plainly marked as such, and must not be misrepresented -* as being the original software. -* -* 3. This notice may not be removed or altered from any source distribution. -* -**********************************************************************************************/ - -#ifndef EASINGS_H -#define EASINGS_H - -#define EASINGS_STATIC_INLINE // NOTE: By default, compile functions as static inline - -#if defined(EASINGS_STATIC_INLINE) - #define EASEDEF static inline -#else - #define EASEDEF extern -#endif - -#include // Required for: sin(), cos(), sqrt(), pow() - -#ifdef __cplusplus -extern "C" { // Prevents name mangling of functions -#endif - -// Linear Easing functions -EASEDEF float EaseLinearNone(float t, float b, float c, float d) { return (c*t/d + b); } -EASEDEF float EaseLinearIn(float t, float b, float c, float d) { return (c*t/d + b); } -EASEDEF float EaseLinearOut(float t, float b, float c, float d) { return (c*t/d + b); } -EASEDEF float EaseLinearInOut(float t,float b, float c, float d) { return (c*t/d + b); } - -// Sine Easing functions -EASEDEF float EaseSineIn(float t, float b, float c, float d) { return (-c*cos(t/d*(PI/2)) + c + b); } -EASEDEF float EaseSineOut(float t, float b, float c, float d) { return (c*sin(t/d*(PI/2)) + b); } -EASEDEF float EaseSineInOut(float t, float b, float c, float d) { return (-c/2*(cos(PI*t/d) - 1) + b); } - -// Circular Easing functions -EASEDEF float EaseCircIn(float t, float b, float c, float d) { return (-c*(sqrt(1 - (t/=d)*t) - 1) + b); } -EASEDEF float EaseCircOut(float t, float b, float c, float d) { return (c*sqrt(1 - (t=t/d-1)*t) + b); } -EASEDEF float EaseCircInOut(float t, float b, float c, float d) -{ - if ((t/=d/2) < 1) return (-c/2*(sqrt(1 - t*t) - 1) + b); - return (c/2*(sqrt(1 - t*(t-=2)) + 1) + b); -} - -// Cubic Easing functions -EASEDEF float EaseCubicIn(float t, float b, float c, float d) { return (c*(t/=d)*t*t + b); } -EASEDEF float EaseCubicOut(float t, float b, float c, float d) { return (c*((t=t/d-1)*t*t + 1) + b); } -EASEDEF float EaseCubicInOut(float t, float b, float c, float d) -{ - if ((t/=d/2) < 1) return (c/2*t*t*t + b); - return (c/2*((t-=2)*t*t + 2) + b); -} - -// Quadratic Easing functions -EASEDEF float EaseQuadIn(float t, float b, float c, float d) { return (c*(t/=d)*t + b); } -EASEDEF float EaseQuadOut(float t, float b, float c, float d) { return (-c*(t/=d)*(t-2) + b); } -EASEDEF float EaseQuadInOut(float t, float b, float c, float d) -{ - if ((t/=d/2) < 1) return (((c/2)*(t*t)) + b); - return (-c/2*(((t-2)*(--t)) - 1) + b); -} - -// Exponential Easing functions -EASEDEF float EaseExpoIn(float t, float b, float c, float d) { return (t == 0) ? b : (c*pow(2, 10*(t/d - 1)) + b); } -EASEDEF float EaseExpoOut(float t, float b, float c, float d) { return (t == d) ? (b + c) : (c*(-pow(2, -10*t/d) + 1) + b); } -EASEDEF float EaseExpoInOut(float t, float b, float c, float d) -{ - if (t == 0) return b; - if (t == d) return (b + c); - if ((t/=d/2) < 1) return (c/2*pow(2, 10*(t - 1)) + b); - - return (c/2*(-pow(2, -10*--t) + 2) + b); -} - -// Back Easing functions -EASEDEF float EaseBackIn(float t, float b, float c, float d) -{ - float s = 1.70158f; - float postFix = t/=d; - return (c*(postFix)*t*((s + 1)*t - s) + b); -} - -EASEDEF float EaseBackOut(float t, float b, float c, float d) -{ - float s = 1.70158f; - return (c*((t=t/d-1)*t*((s + 1)*t + s) + 1) + b); -} - -EASEDEF float EaseBackInOut(float t, float b, float c, float d) -{ - float s = 1.70158f; - if ((t/=d/2) < 1) return (c/2*(t*t*(((s*=(1.525f)) + 1)*t - s)) + b); - - float postFix = t-=2; - return (c/2*((postFix)*t*(((s*=(1.525f)) + 1)*t + s) + 2) + b); -} - -// Bounce Easing functions -EASEDEF float EaseBounceOut(float t, float b, float c, float d) -{ - if ((t/=d) < (1/2.75f)) - { - return (c*(7.5625f*t*t) + b); - } - else if (t < (2/2.75f)) - { - float postFix = t-=(1.5f/2.75f); - return (c*(7.5625f*(postFix)*t + 0.75f) + b); - } - else if (t < (2.5/2.75)) - { - float postFix = t-=(2.25f/2.75f); - return (c*(7.5625f*(postFix)*t + 0.9375f) + b); - } - else - { - float postFix = t-=(2.625f/2.75f); - return (c*(7.5625f*(postFix)*t + 0.984375f) + b); - } -} - -EASEDEF float EaseBounceIn(float t, float b, float c, float d) { return (c - EaseBounceOut(d-t, 0, c, d) + b); } -EASEDEF float EaseBounceInOut(float t, float b, float c, float d) -{ - if (t < d/2) return (EaseBounceIn(t*2, 0, c, d)*0.5f + b); - else return (EaseBounceOut(t*2-d, 0, c, d)*0.5f + c*0.5f + b); -} - -// Elastic Easing functions -EASEDEF float EaseElasticIn(float t, float b, float c, float d) -{ - if (t == 0) return b; - if ((t/=d) == 1) return (b + c); - - float p = d*0.3f; - float a = c; - float s = p/4; - float postFix = a*pow(2, 10*(t-=1)); - - return (-(postFix*sin((t*d-s)*(2*PI)/p )) + b); -} - -EASEDEF float EaseElasticOut(float t, float b, float c, float d) -{ - if (t == 0) return b; - if ((t/=d) == 1) return (b + c); - - float p = d*0.3f; - float a = c; - float s = p/4; - - return (a*pow(2,-10*t)*sin((t*d-s)*(2*PI)/p) + c + b); -} - -EASEDEF float EaseElasticInOut(float t, float b, float c, float d) -{ - if (t == 0) return b; - if ((t/=d/2) == 2) return (b + c); - - float p = d*(0.3f*1.5f); - float a = c; - float s = p/4; - - if (t < 1) - { - float postFix = a*pow(2, 10*(t-=1)); - return -0.5f*(postFix*sin((t*d-s)*(2*PI)/p)) + b; - } - - float postFix = a*pow(2, -10*(t-=1)); - - return (postFix*sin((t*d-s)*(2*PI)/p)*0.5f + c + b); -} - -#ifdef __cplusplus -} -#endif - -#endif // EASINGS_H \ No newline at end of file diff --git a/game/src/libs/raylib/gestures.h b/game/src/libs/raylib/gestures.h deleted file mode 100644 index f4d38df..0000000 --- a/game/src/libs/raylib/gestures.h +++ /dev/null @@ -1,535 +0,0 @@ -/********************************************************************************************** -* -* raylib.gestures - Gestures system, gestures processing based on input events (touch/mouse) -* -* NOTE: Memory footprint of this library is aproximately 128 bytes (global variables) -* -* CONFIGURATION: -* -* #define GESTURES_IMPLEMENTATION -* Generates the implementation of the library into the included file. -* If not defined, the library is in header only mode and can be included in other headers -* or source files without problems. But only ONE file should hold the implementation. -* -* #define GESTURES_STANDALONE -* If defined, the library can be used as standalone to process gesture events with -* no external dependencies. -* -* CONTRIBUTORS: -* Marc Palau: Initial implementation (2014) -* Albert Martos: Complete redesign and testing (2015) -* Ian Eito: Complete redesign and testing (2015) -* Ramon Santamaria: Supervision, review, update and maintenance -* -* -* LICENSE: zlib/libpng -* -* Copyright (c) 2014-2017 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. -* -* Permission is granted to anyone to use this software for any purpose, including commercial -* applications, and to alter it and redistribute it freely, subject to the following restrictions: -* -* 1. The origin of this software must not be misrepresented; you must not claim that you -* wrote the original software. If you use this software in a product, an acknowledgment -* in the product documentation would be appreciated but is not required. -* -* 2. Altered source versions must be plainly marked as such, and must not be misrepresented -* as being the original software. -* -* 3. This notice may not be removed or altered from any source distribution. -* -**********************************************************************************************/ - -#ifndef GESTURES_H -#define GESTURES_H - -#ifndef PI - #define PI 3.14159265358979323846 -#endif - -//---------------------------------------------------------------------------------- -// Defines and Macros -//---------------------------------------------------------------------------------- -//... - -//---------------------------------------------------------------------------------- -// Types and Structures Definition -// NOTE: Below types are required for GESTURES_STANDALONE usage -//---------------------------------------------------------------------------------- -#if defined(GESTURES_STANDALONE) - #ifndef __cplusplus - // Boolean type - typedef enum { false, true } bool; - #endif - - // Vector2 type - typedef struct Vector2 { - float x; - float y; - } Vector2; - - // Gestures type - // NOTE: It could be used as flags to enable only some gestures - typedef enum { - GESTURE_NONE = 0, - GESTURE_TAP = 1, - GESTURE_DOUBLETAP = 2, - GESTURE_HOLD = 4, - GESTURE_DRAG = 8, - GESTURE_SWIPE_RIGHT = 16, - GESTURE_SWIPE_LEFT = 32, - GESTURE_SWIPE_UP = 64, - GESTURE_SWIPE_DOWN = 128, - GESTURE_PINCH_IN = 256, - GESTURE_PINCH_OUT = 512 - } Gestures; -#endif - -typedef enum { TOUCH_UP, TOUCH_DOWN, TOUCH_MOVE } TouchAction; - -// Gesture events -// NOTE: MAX_TOUCH_POINTS fixed to 4 -typedef struct { - int touchAction; - int pointCount; - int pointerId[4]; - Vector2 position[4]; -} GestureEvent; - -#ifdef __cplusplus -extern "C" { // Prevents name mangling of functions -#endif - -//---------------------------------------------------------------------------------- -// Global Variables Definition -//---------------------------------------------------------------------------------- -//... - -//---------------------------------------------------------------------------------- -// Module Functions Declaration -//---------------------------------------------------------------------------------- -void ProcessGestureEvent(GestureEvent event); // Process gesture event and translate it into gestures -void UpdateGestures(void); // Update gestures detected (must be called every frame) - -#if defined(GESTURES_STANDALONE) -void SetGesturesEnabled(unsigned int gestureFlags); // Enable a set of gestures using flags -bool IsGestureDetected(int gesture); // Check if a gesture have been detected -int GetGestureDetected(void); // Get latest detected gesture -int GetTouchPointsCount(void); // Get touch points count -float GetGestureHoldDuration(void); // Get gesture hold time in milliseconds -Vector2 GetGestureDragVector(void); // Get gesture drag vector -float GetGestureDragAngle(void); // Get gesture drag angle -Vector2 GetGesturePinchVector(void); // Get gesture pinch delta -float GetGesturePinchAngle(void); // Get gesture pinch angle -#endif - -#ifdef __cplusplus -} -#endif - -#endif // GESTURES_H - -/*********************************************************************************** -* -* GESTURES IMPLEMENTATION -* -************************************************************************************/ - -#if defined(GESTURES_IMPLEMENTATION) - -#include // Required for: atan2(), sqrt() -#include // Required for: uint64_t - -#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__) - #define _POSIX_C_SOURCE 199309L // Required for CLOCK_MONOTONIC if compiled with c99 without gnu ext. - #include // Required for: timespec - #include // Required for: clock_gettime() -#endif - -//---------------------------------------------------------------------------------- -// Defines and Macros -//---------------------------------------------------------------------------------- -#define FORCE_TO_SWIPE 0.0005f // Measured in normalized screen units/time -#define MINIMUM_DRAG 0.015f // Measured in normalized screen units (0.0f to 1.0f) -#define MINIMUM_PINCH 0.005f // Measured in normalized screen units (0.0f to 1.0f) -#define TAP_TIMEOUT 300 // Time in milliseconds -#define PINCH_TIMEOUT 300 // Time in milliseconds -#define DOUBLETAP_RANGE 0.03f // Measured in normalized screen units (0.0f to 1.0f) - -//---------------------------------------------------------------------------------- -// Types and Structures Definition -//---------------------------------------------------------------------------------- -// ... - -//---------------------------------------------------------------------------------- -// Global Variables Definition -//---------------------------------------------------------------------------------- - -// Touch gesture variables -static Vector2 touchDownPosition = { 0.0f, 0.0f }; -static Vector2 touchDownPosition2 = { 0.0f, 0.0f }; -static Vector2 touchDownDragPosition = { 0.0f, 0.0f }; -static Vector2 touchUpPosition = { 0.0f, 0.0f }; -static Vector2 moveDownPosition = { 0.0f, 0.0f }; -static Vector2 moveDownPosition2 = { 0.0f, 0.0f }; - -static int pointCount = 0; // Touch points counter -static int firstTouchId = -1; // Touch id for first touch point -static double eventTime = 0.0; // Time stamp when an event happened - -// Tap gesture variables -static int tapCounter = 0; // TAP counter (one tap implies TOUCH_DOWN and TOUCH_UP actions) - -// Hold gesture variables -static bool resetHold = false; // HOLD reset to get first touch point again -static double timeHold = 0.0f; // HOLD duration in milliseconds - -// Drag gesture variables -static Vector2 dragVector = { 0.0f , 0.0f }; // DRAG vector (between initial and current position) -static float dragAngle = 0.0f; // DRAG angle (relative to x-axis) -static float dragDistance = 0.0f; // DRAG distance (from initial touch point to final) (normalized [0..1]) -static float dragIntensity = 0.0f; // DRAG intensity, how far why did the DRAG (pixels per frame) - -// Swipe gestures variables -static bool startMoving = false; // SWIPE used to define when start measuring swipeTime -static double swipeTime = 0.0; // SWIPE time to calculate drag intensity - -// Pinch gesture variables -static Vector2 pinchVector = { 0.0f , 0.0f }; // PINCH vector (between first and second touch points) -static float pinchAngle = 0.0f; // PINCH angle (relative to x-axis) -static float pinchDistance = 0.0f; // PINCH displacement distance (normalized [0..1]) - -static int currentGesture = GESTURE_NONE; // Current detected gesture - -// Enabled gestures flags, all gestures enabled by default -static unsigned int enabledGestures = 0b0000001111111111; - -//---------------------------------------------------------------------------------- -// Module specific Functions Declaration -//---------------------------------------------------------------------------------- -#if defined(GESTURES_STANDALONE) -// Some required math functions provided by raymath.h -static float Vector2Angle(Vector2 initialPosition, Vector2 finalPosition); -static float Vector2Distance(Vector2 v1, Vector2 v2); -#endif -static double GetCurrentTime(void); - -//---------------------------------------------------------------------------------- -// Module Functions Definition -//---------------------------------------------------------------------------------- - -// Enable only desired getures to be detected -void SetGesturesEnabled(unsigned int gestureFlags) -{ - enabledGestures = gestureFlags; -} - -// Check if a gesture have been detected -bool IsGestureDetected(int gesture) -{ - if ((enabledGestures & currentGesture) == gesture) return true; - else return false; -} - -// Process gesture event and translate it into gestures -void ProcessGestureEvent(GestureEvent event) -{ - // Reset required variables - pointCount = event.pointCount; // Required on UpdateGestures() - - if (pointCount < 2) - { - if (event.touchAction == TOUCH_DOWN) - { - tapCounter++; // Tap counter - - // Detect GESTURE_DOUBLE_TAP - if ((currentGesture == GESTURE_NONE) && (tapCounter >= 2) && ((GetCurrentTime() - eventTime) < TAP_TIMEOUT) && (Vector2Distance(touchDownPosition, event.position[0]) < DOUBLETAP_RANGE)) - { - currentGesture = GESTURE_DOUBLETAP; - tapCounter = 0; - } - else // Detect GESTURE_TAP - { - tapCounter = 1; - currentGesture = GESTURE_TAP; - } - - touchDownPosition = event.position[0]; - touchDownDragPosition = event.position[0]; - - touchUpPosition = touchDownPosition; - eventTime = GetCurrentTime(); - - firstTouchId = event.pointerId[0]; - - dragVector = (Vector2){ 0.0f, 0.0f }; - } - else if (event.touchAction == TOUCH_UP) - { - if (currentGesture == GESTURE_DRAG) touchUpPosition = event.position[0]; - - // NOTE: dragIntensity dependend on the resolution of the screen - dragDistance = Vector2Distance(touchDownPosition, touchUpPosition); - dragIntensity = dragDistance/(float)((GetCurrentTime() - swipeTime)); - - startMoving = false; - - // Detect GESTURE_SWIPE - if ((dragIntensity > FORCE_TO_SWIPE) && (firstTouchId == event.pointerId[0])) - { - // NOTE: Angle should be inverted in Y - dragAngle = 360.0f - Vector2Angle(touchDownPosition, touchUpPosition); - - if ((dragAngle < 30) || (dragAngle > 330)) currentGesture = GESTURE_SWIPE_RIGHT; // Right - else if ((dragAngle > 30) && (dragAngle < 120)) currentGesture = GESTURE_SWIPE_UP; // Up - else if ((dragAngle > 120) && (dragAngle < 210)) currentGesture = GESTURE_SWIPE_LEFT; // Left - else if ((dragAngle > 210) && (dragAngle < 300)) currentGesture = GESTURE_SWIPE_DOWN; // Down - else currentGesture = GESTURE_NONE; - } - else - { - dragDistance = 0.0f; - dragIntensity = 0.0f; - dragAngle = 0.0f; - - currentGesture = GESTURE_NONE; - } - - touchDownDragPosition = (Vector2){ 0.0f, 0.0f }; - pointCount = 0; - } - else if (event.touchAction == TOUCH_MOVE) - { - if (currentGesture == GESTURE_DRAG) eventTime = GetCurrentTime(); - - if (!startMoving) - { - swipeTime = GetCurrentTime(); - startMoving = true; - } - - moveDownPosition = event.position[0]; - - if (currentGesture == GESTURE_HOLD) - { - if (resetHold) touchDownPosition = event.position[0]; - - resetHold = false; - - // Detect GESTURE_DRAG - if (Vector2Distance(touchDownPosition, moveDownPosition) >= MINIMUM_DRAG) - { - eventTime = GetCurrentTime(); - currentGesture = GESTURE_DRAG; - } - } - - dragVector.x = moveDownPosition.x - touchDownDragPosition.x; - dragVector.y = moveDownPosition.y - touchDownDragPosition.y; - } - } - else // Two touch points - { - if (event.touchAction == TOUCH_DOWN) - { - touchDownPosition = event.position[0]; - touchDownPosition2 = event.position[1]; - - //pinchDistance = Vector2Distance(touchDownPosition, touchDownPosition2); - - pinchVector.x = touchDownPosition2.x - touchDownPosition.x; - pinchVector.y = touchDownPosition2.y - touchDownPosition.y; - - currentGesture = GESTURE_HOLD; - timeHold = GetCurrentTime(); - } - else if (event.touchAction == TOUCH_MOVE) - { - pinchDistance = Vector2Distance(moveDownPosition, moveDownPosition2); - - touchDownPosition = moveDownPosition; - touchDownPosition2 = moveDownPosition2; - - moveDownPosition = event.position[0]; - moveDownPosition2 = event.position[1]; - - pinchVector.x = moveDownPosition2.x - moveDownPosition.x; - pinchVector.y = moveDownPosition2.y - moveDownPosition.y; - - if ((Vector2Distance(touchDownPosition, moveDownPosition) >= MINIMUM_PINCH) || (Vector2Distance(touchDownPosition2, moveDownPosition2) >= MINIMUM_PINCH)) - { - if ((Vector2Distance(moveDownPosition, moveDownPosition2) - pinchDistance) < 0) currentGesture = GESTURE_PINCH_IN; - else currentGesture = GESTURE_PINCH_OUT; - } - else - { - currentGesture = GESTURE_HOLD; - timeHold = GetCurrentTime(); - } - - // NOTE: Angle should be inverted in Y - pinchAngle = 360.0f - Vector2Angle(moveDownPosition, moveDownPosition2); - } - else if (event.touchAction == TOUCH_UP) - { - pinchDistance = 0.0f; - pinchAngle = 0.0f; - pinchVector = (Vector2){ 0.0f, 0.0f }; - pointCount = 0; - - currentGesture = GESTURE_NONE; - } - } -} - -// Update gestures detected (must be called every frame) -void UpdateGestures(void) -{ - // NOTE: Gestures are processed through system callbacks on touch events - - // Detect GESTURE_HOLD - if (((currentGesture == GESTURE_TAP) || (currentGesture == GESTURE_DOUBLETAP)) && (pointCount < 2)) - { - currentGesture = GESTURE_HOLD; - timeHold = GetCurrentTime(); - } - - if (((GetCurrentTime() - eventTime) > TAP_TIMEOUT) && (currentGesture == GESTURE_DRAG) && (pointCount < 2)) - { - currentGesture = GESTURE_HOLD; - timeHold = GetCurrentTime(); - resetHold = true; - } - - // Detect GESTURE_NONE - if ((currentGesture == GESTURE_SWIPE_RIGHT) || (currentGesture == GESTURE_SWIPE_UP) || (currentGesture == GESTURE_SWIPE_LEFT) || (currentGesture == GESTURE_SWIPE_DOWN)) - { - currentGesture = GESTURE_NONE; - } -} - -// Get number of touch points -int GetTouchPointsCount(void) -{ - // NOTE: point count is calculated when ProcessGestureEvent(GestureEvent event) is called - - return pointCount; -} - -// Get latest detected gesture -int GetGestureDetected(void) -{ - // Get current gesture only if enabled - return (enabledGestures & currentGesture); -} - -// Hold time measured in ms -float GetGestureHoldDuration(void) -{ - // NOTE: time is calculated on current gesture HOLD - - double time = 0.0; - - if (currentGesture == GESTURE_HOLD) time = GetCurrentTime() - timeHold; - - return (float)time; -} - -// Get drag vector (between initial touch point to current) -Vector2 GetGestureDragVector(void) -{ - // NOTE: drag vector is calculated on one touch points TOUCH_MOVE - - return dragVector; -} - -// Get drag angle -// NOTE: Angle in degrees, horizontal-right is 0, counterclock-wise -float GetGestureDragAngle(void) -{ - // NOTE: drag angle is calculated on one touch points TOUCH_UP - - return dragAngle; -} - -// Get distance between two pinch points -Vector2 GetGesturePinchVector(void) -{ - // NOTE: The position values used for pinchDistance are not modified like the position values of [core.c]-->GetTouchPosition(int index) - // NOTE: pinch distance is calculated on two touch points TOUCH_MOVE - - return pinchVector; -} - -// Get angle beween two pinch points -// NOTE: Angle in degrees, horizontal-right is 0, counterclock-wise -float GetGesturePinchAngle(void) -{ - // NOTE: pinch angle is calculated on two touch points TOUCH_MOVE - - return pinchAngle; -} - -//---------------------------------------------------------------------------------- -// Module specific Functions Definition -//---------------------------------------------------------------------------------- -#if defined(GESTURES_STANDALONE) -// Returns angle from two-points vector with X-axis -static float Vector2Angle(Vector2 v1, Vector2 v2) -{ - float angle = angle = atan2f(v2.y - v1.y, v2.x - v1.x)*(180.0f/PI); - - if (angle < 0) angle += 360.0f; - - return angle; -} - -// Calculate distance between two Vector2 -static float Vector2Distance(Vector2 v1, Vector2 v2) -{ - float result; - - float dx = v2.x - v1.x; - float dy = v2.y - v1.y; - - result = (float)sqrt(dx*dx + dy*dy); - - return result; -} -#endif - -// Time measure returned are milliseconds -static double GetCurrentTime(void) -{ - double time = 0; - -#if defined(_WIN32) - unsigned long long int clockFrequency, currentTime; - - QueryPerformanceFrequency(&clockFrequency); - QueryPerformanceCounter(¤tTime); - - time = (double)currentTime/clockFrequency*1000.0f; // Time in miliseconds -#endif - -#if defined(__linux__) - // NOTE: Only for Linux-based systems - struct timespec now; - clock_gettime(CLOCK_MONOTONIC, &now); - uint64_t nowTime = (uint64_t)now.tv_sec*1000000000LLU + (uint64_t)now.tv_nsec; // Time in nanoseconds - - time = ((double)nowTime/1000000.0); // Time in miliseconds -#endif - - return time; -} - -#endif // GESTURES_IMPLEMENTATION diff --git a/game/src/libs/raylib/models.c b/game/src/libs/raylib/models.c deleted file mode 100644 index 4b8a673..0000000 --- a/game/src/libs/raylib/models.c +++ /dev/null @@ -1,2580 +0,0 @@ -/********************************************************************************************** -* -* raylib.models - Basic functions to deal with 3d shapes and 3d models -* -* CONFIGURATION: -* -* #define SUPPORT_FILEFORMAT_OBJ -* Selected desired fileformats to be supported for loading. -* -* #define SUPPORT_FILEFORMAT_MTL -* Selected desired fileformats to be supported for loading. -* -* #define SUPPORT_MESH_GENERATION -* Support procedural mesh generation functions, uses external par_shapes.h library -* NOTE: Some generated meshes DO NOT include generated texture coordinates -* -* -* LICENSE: zlib/libpng -* -* Copyright (c) 2014-2017 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. -* -* Permission is granted to anyone to use this software for any purpose, including commercial -* applications, and to alter it and redistribute it freely, subject to the following restrictions: -* -* 1. The origin of this software must not be misrepresented; you must not claim that you -* wrote the original software. If you use this software in a product, an acknowledgment -* in the product documentation would be appreciated but is not required. -* -* 2. Altered source versions must be plainly marked as such, and must not be misrepresented -* as being the original software. -* -* 3. This notice may not be removed or altered from any source distribution. -* -**********************************************************************************************/ - -// Default configuration flags (supported features) -//------------------------------------------------- -#define SUPPORT_FILEFORMAT_OBJ -#define SUPPORT_FILEFORMAT_MTL -#define SUPPORT_MESH_GENERATION -//------------------------------------------------- - -#include "raylib.h" - -#if defined(PLATFORM_ANDROID) - #include "utils.h" // Android fopen function map -#endif - -#include // Required for: FILE, fopen(), fclose(), fscanf(), feof(), rewind(), fgets() -#include // Required for: malloc(), free() -#include // Required for: strcmp() -#include // Required for: sin(), cos() - -#include "rlgl.h" // raylib OpenGL abstraction layer to OpenGL 1.1, 2.1, 3.3+ or ES2 - -#define PAR_SHAPES_IMPLEMENTATION -#include "external/par_shapes.h" - -//---------------------------------------------------------------------------------- -// Defines and Macros -//---------------------------------------------------------------------------------- -// ... - -//---------------------------------------------------------------------------------- -// Types and Structures Definition -//---------------------------------------------------------------------------------- -// ... - -//---------------------------------------------------------------------------------- -// Global Variables Definition -//---------------------------------------------------------------------------------- -// ... - -//---------------------------------------------------------------------------------- -// Module specific Functions Declaration -//---------------------------------------------------------------------------------- -#if defined(SUPPORT_FILEFORMAT_OBJ) -static Mesh LoadOBJ(const char *fileName); // Load OBJ mesh data -#endif -#if defined(SUPPORT_FILEFORMAT_MTL) -static Material LoadMTL(const char *fileName); // Load MTL material data -#endif - -//---------------------------------------------------------------------------------- -// Module Functions Definition -//---------------------------------------------------------------------------------- - -// Draw a line in 3D world space -void DrawLine3D(Vector3 startPos, Vector3 endPos, Color color) -{ - rlBegin(RL_LINES); - rlColor4ub(color.r, color.g, color.b, color.a); - rlVertex3f(startPos.x, startPos.y, startPos.z); - rlVertex3f(endPos.x, endPos.y, endPos.z); - rlEnd(); -} - -// Draw a circle in 3D world space -void DrawCircle3D(Vector3 center, float radius, Vector3 rotationAxis, float rotationAngle, Color color) -{ - rlPushMatrix(); - rlTranslatef(center.x, center.y, center.z); - rlRotatef(rotationAngle, rotationAxis.x, rotationAxis.y, rotationAxis.z); - - rlBegin(RL_LINES); - for (int i = 0; i < 360; i += 10) - { - rlColor4ub(color.r, color.g, color.b, color.a); - - rlVertex3f(sinf(DEG2RAD*i)*radius, cosf(DEG2RAD*i)*radius, 0.0f); - rlVertex3f(sinf(DEG2RAD*(i + 10))*radius, cosf(DEG2RAD*(i + 10))*radius, 0.0f); - } - rlEnd(); - rlPopMatrix(); -} - -// Draw cube -// NOTE: Cube position is the center position -void DrawCube(Vector3 position, float width, float height, float length, Color color) -{ - float x = 0.0f; - float y = 0.0f; - float z = 0.0f; - - rlPushMatrix(); - // NOTE: Transformation is applied in inverse order (scale -> rotate -> translate) - rlTranslatef(position.x, position.y, position.z); - //rlRotatef(45, 0, 1, 0); - //rlScalef(1.0f, 1.0f, 1.0f); // NOTE: Vertices are directly scaled on definition - - rlBegin(RL_TRIANGLES); - rlColor4ub(color.r, color.g, color.b, color.a); - - // Front face - rlVertex3f(x - width/2, y - height/2, z + length/2); // Bottom Left - rlVertex3f(x + width/2, y - height/2, z + length/2); // Bottom Right - rlVertex3f(x - width/2, y + height/2, z + length/2); // Top Left - - rlVertex3f(x + width/2, y + height/2, z + length/2); // Top Right - rlVertex3f(x - width/2, y + height/2, z + length/2); // Top Left - rlVertex3f(x + width/2, y - height/2, z + length/2); // Bottom Right - - // Back face - rlVertex3f(x - width/2, y - height/2, z - length/2); // Bottom Left - rlVertex3f(x - width/2, y + height/2, z - length/2); // Top Left - rlVertex3f(x + width/2, y - height/2, z - length/2); // Bottom Right - - rlVertex3f(x + width/2, y + height/2, z - length/2); // Top Right - rlVertex3f(x + width/2, y - height/2, z - length/2); // Bottom Right - rlVertex3f(x - width/2, y + height/2, z - length/2); // Top Left - - // Top face - rlVertex3f(x - width/2, y + height/2, z - length/2); // Top Left - rlVertex3f(x - width/2, y + height/2, z + length/2); // Bottom Left - rlVertex3f(x + width/2, y + height/2, z + length/2); // Bottom Right - - rlVertex3f(x + width/2, y + height/2, z - length/2); // Top Right - rlVertex3f(x - width/2, y + height/2, z - length/2); // Top Left - rlVertex3f(x + width/2, y + height/2, z + length/2); // Bottom Right - - // Bottom face - rlVertex3f(x - width/2, y - height/2, z - length/2); // Top Left - rlVertex3f(x + width/2, y - height/2, z + length/2); // Bottom Right - rlVertex3f(x - width/2, y - height/2, z + length/2); // Bottom Left - - rlVertex3f(x + width/2, y - height/2, z - length/2); // Top Right - rlVertex3f(x + width/2, y - height/2, z + length/2); // Bottom Right - rlVertex3f(x - width/2, y - height/2, z - length/2); // Top Left - - // Right face - rlVertex3f(x + width/2, y - height/2, z - length/2); // Bottom Right - rlVertex3f(x + width/2, y + height/2, z - length/2); // Top Right - rlVertex3f(x + width/2, y + height/2, z + length/2); // Top Left - - rlVertex3f(x + width/2, y - height/2, z + length/2); // Bottom Left - rlVertex3f(x + width/2, y - height/2, z - length/2); // Bottom Right - rlVertex3f(x + width/2, y + height/2, z + length/2); // Top Left - - // Left face - rlVertex3f(x - width/2, y - height/2, z - length/2); // Bottom Right - rlVertex3f(x - width/2, y + height/2, z + length/2); // Top Left - rlVertex3f(x - width/2, y + height/2, z - length/2); // Top Right - - rlVertex3f(x - width/2, y - height/2, z + length/2); // Bottom Left - rlVertex3f(x - width/2, y + height/2, z + length/2); // Top Left - rlVertex3f(x - width/2, y - height/2, z - length/2); // Bottom Right - rlEnd(); - rlPopMatrix(); -} - -// Draw cube (Vector version) -void DrawCubeV(Vector3 position, Vector3 size, Color color) -{ - DrawCube(position, size.x, size.y, size.z, color); -} - -// Draw cube wires -void DrawCubeWires(Vector3 position, float width, float height, float length, Color color) -{ - float x = 0.0f; - float y = 0.0f; - float z = 0.0f; - - rlPushMatrix(); - rlTranslatef(position.x, position.y, position.z); - - rlBegin(RL_LINES); - rlColor4ub(color.r, color.g, color.b, color.a); - - // Front Face ----------------------------------------------------- - // Bottom Line - rlVertex3f(x-width/2, y-height/2, z+length/2); // Bottom Left - rlVertex3f(x+width/2, y-height/2, z+length/2); // Bottom Right - - // Left Line - rlVertex3f(x+width/2, y-height/2, z+length/2); // Bottom Right - rlVertex3f(x+width/2, y+height/2, z+length/2); // Top Right - - // Top Line - rlVertex3f(x+width/2, y+height/2, z+length/2); // Top Right - rlVertex3f(x-width/2, y+height/2, z+length/2); // Top Left - - // Right Line - rlVertex3f(x-width/2, y+height/2, z+length/2); // Top Left - rlVertex3f(x-width/2, y-height/2, z+length/2); // Bottom Left - - // Back Face ------------------------------------------------------ - // Bottom Line - rlVertex3f(x-width/2, y-height/2, z-length/2); // Bottom Left - rlVertex3f(x+width/2, y-height/2, z-length/2); // Bottom Right - - // Left Line - rlVertex3f(x+width/2, y-height/2, z-length/2); // Bottom Right - rlVertex3f(x+width/2, y+height/2, z-length/2); // Top Right - - // Top Line - rlVertex3f(x+width/2, y+height/2, z-length/2); // Top Right - rlVertex3f(x-width/2, y+height/2, z-length/2); // Top Left - - // Right Line - rlVertex3f(x-width/2, y+height/2, z-length/2); // Top Left - rlVertex3f(x-width/2, y-height/2, z-length/2); // Bottom Left - - // Top Face ------------------------------------------------------- - // Left Line - rlVertex3f(x-width/2, y+height/2, z+length/2); // Top Left Front - rlVertex3f(x-width/2, y+height/2, z-length/2); // Top Left Back - - // Right Line - rlVertex3f(x+width/2, y+height/2, z+length/2); // Top Right Front - rlVertex3f(x+width/2, y+height/2, z-length/2); // Top Right Back - - // Bottom Face --------------------------------------------------- - // Left Line - rlVertex3f(x-width/2, y-height/2, z+length/2); // Top Left Front - rlVertex3f(x-width/2, y-height/2, z-length/2); // Top Left Back - - // Right Line - rlVertex3f(x+width/2, y-height/2, z+length/2); // Top Right Front - rlVertex3f(x+width/2, y-height/2, z-length/2); // Top Right Back - rlEnd(); - rlPopMatrix(); -} - -// Draw cube -// NOTE: Cube position is the center position -void DrawCubeTexture(Texture2D texture, Vector3 position, float width, float height, float length, Color color) -{ - float x = position.x; - float y = position.y; - float z = position.z; - - rlEnableTexture(texture.id); - - //rlPushMatrix(); - // NOTE: Transformation is applied in inverse order (scale -> rotate -> translate) - //rlTranslatef(2.0f, 0.0f, 0.0f); - //rlRotatef(45, 0, 1, 0); - //rlScalef(2.0f, 2.0f, 2.0f); - - rlBegin(RL_QUADS); - rlColor4ub(color.r, color.g, color.b, color.a); - // Front Face - rlNormal3f(0.0f, 0.0f, 1.0f); // Normal Pointing Towards Viewer - rlTexCoord2f(0.0f, 0.0f); rlVertex3f(x - width/2, y - height/2, z + length/2); // Bottom Left Of The Texture and Quad - rlTexCoord2f(1.0f, 0.0f); rlVertex3f(x + width/2, y - height/2, z + length/2); // Bottom Right Of The Texture and Quad - rlTexCoord2f(1.0f, 1.0f); rlVertex3f(x + width/2, y + height/2, z + length/2); // Top Right Of The Texture and Quad - rlTexCoord2f(0.0f, 1.0f); rlVertex3f(x - width/2, y + height/2, z + length/2); // Top Left Of The Texture and Quad - // Back Face - rlNormal3f(0.0f, 0.0f, - 1.0f); // Normal Pointing Away From Viewer - rlTexCoord2f(1.0f, 0.0f); rlVertex3f(x - width/2, y - height/2, z - length/2); // Bottom Right Of The Texture and Quad - rlTexCoord2f(1.0f, 1.0f); rlVertex3f(x - width/2, y + height/2, z - length/2); // Top Right Of The Texture and Quad - rlTexCoord2f(0.0f, 1.0f); rlVertex3f(x + width/2, y + height/2, z - length/2); // Top Left Of The Texture and Quad - rlTexCoord2f(0.0f, 0.0f); rlVertex3f(x + width/2, y - height/2, z - length/2); // Bottom Left Of The Texture and Quad - // Top Face - rlNormal3f(0.0f, 1.0f, 0.0f); // Normal Pointing Up - rlTexCoord2f(0.0f, 1.0f); rlVertex3f(x - width/2, y + height/2, z - length/2); // Top Left Of The Texture and Quad - rlTexCoord2f(0.0f, 0.0f); rlVertex3f(x - width/2, y + height/2, z + length/2); // Bottom Left Of The Texture and Quad - rlTexCoord2f(1.0f, 0.0f); rlVertex3f(x + width/2, y + height/2, z + length/2); // Bottom Right Of The Texture and Quad - rlTexCoord2f(1.0f, 1.0f); rlVertex3f(x + width/2, y + height/2, z - length/2); // Top Right Of The Texture and Quad - // Bottom Face - rlNormal3f(0.0f, - 1.0f, 0.0f); // Normal Pointing Down - rlTexCoord2f(1.0f, 1.0f); rlVertex3f(x - width/2, y - height/2, z - length/2); // Top Right Of The Texture and Quad - rlTexCoord2f(0.0f, 1.0f); rlVertex3f(x + width/2, y - height/2, z - length/2); // Top Left Of The Texture and Quad - rlTexCoord2f(0.0f, 0.0f); rlVertex3f(x + width/2, y - height/2, z + length/2); // Bottom Left Of The Texture and Quad - rlTexCoord2f(1.0f, 0.0f); rlVertex3f(x - width/2, y - height/2, z + length/2); // Bottom Right Of The Texture and Quad - // Right face - rlNormal3f(1.0f, 0.0f, 0.0f); // Normal Pointing Right - rlTexCoord2f(1.0f, 0.0f); rlVertex3f(x + width/2, y - height/2, z - length/2); // Bottom Right Of The Texture and Quad - rlTexCoord2f(1.0f, 1.0f); rlVertex3f(x + width/2, y + height/2, z - length/2); // Top Right Of The Texture and Quad - rlTexCoord2f(0.0f, 1.0f); rlVertex3f(x + width/2, y + height/2, z + length/2); // Top Left Of The Texture and Quad - rlTexCoord2f(0.0f, 0.0f); rlVertex3f(x + width/2, y - height/2, z + length/2); // Bottom Left Of The Texture and Quad - // Left Face - rlNormal3f( - 1.0f, 0.0f, 0.0f); // Normal Pointing Left - rlTexCoord2f(0.0f, 0.0f); rlVertex3f(x - width/2, y - height/2, z - length/2); // Bottom Left Of The Texture and Quad - rlTexCoord2f(1.0f, 0.0f); rlVertex3f(x - width/2, y - height/2, z + length/2); // Bottom Right Of The Texture and Quad - rlTexCoord2f(1.0f, 1.0f); rlVertex3f(x - width/2, y + height/2, z + length/2); // Top Right Of The Texture and Quad - rlTexCoord2f(0.0f, 1.0f); rlVertex3f(x - width/2, y + height/2, z - length/2); // Top Left Of The Texture and Quad - rlEnd(); - //rlPopMatrix(); - - rlDisableTexture(); -} - -// Draw sphere -void DrawSphere(Vector3 centerPos, float radius, Color color) -{ - DrawSphereEx(centerPos, radius, 16, 16, color); -} - -// Draw sphere with extended parameters -void DrawSphereEx(Vector3 centerPos, float radius, int rings, int slices, Color color) -{ - rlPushMatrix(); - // NOTE: Transformation is applied in inverse order (scale -> translate) - rlTranslatef(centerPos.x, centerPos.y, centerPos.z); - rlScalef(radius, radius, radius); - - rlBegin(RL_TRIANGLES); - rlColor4ub(color.r, color.g, color.b, color.a); - - for (int i = 0; i < (rings + 2); i++) - { - for (int j = 0; j < slices; j++) - { - rlVertex3f(cosf(DEG2RAD*(270+(180/(rings + 1))*i))*sinf(DEG2RAD*(j*360/slices)), - sinf(DEG2RAD*(270+(180/(rings + 1))*i)), - cosf(DEG2RAD*(270+(180/(rings + 1))*i))*cosf(DEG2RAD*(j*360/slices))); - rlVertex3f(cosf(DEG2RAD*(270+(180/(rings + 1))*(i+1)))*sinf(DEG2RAD*((j+1)*360/slices)), - sinf(DEG2RAD*(270+(180/(rings + 1))*(i+1))), - cosf(DEG2RAD*(270+(180/(rings + 1))*(i+1)))*cosf(DEG2RAD*((j+1)*360/slices))); - rlVertex3f(cosf(DEG2RAD*(270+(180/(rings + 1))*(i+1)))*sinf(DEG2RAD*(j*360/slices)), - sinf(DEG2RAD*(270+(180/(rings + 1))*(i+1))), - cosf(DEG2RAD*(270+(180/(rings + 1))*(i+1)))*cosf(DEG2RAD*(j*360/slices))); - - rlVertex3f(cosf(DEG2RAD*(270+(180/(rings + 1))*i))*sinf(DEG2RAD*(j*360/slices)), - sinf(DEG2RAD*(270+(180/(rings + 1))*i)), - cosf(DEG2RAD*(270+(180/(rings + 1))*i))*cosf(DEG2RAD*(j*360/slices))); - rlVertex3f(cosf(DEG2RAD*(270+(180/(rings + 1))*(i)))*sinf(DEG2RAD*((j+1)*360/slices)), - sinf(DEG2RAD*(270+(180/(rings + 1))*(i))), - cosf(DEG2RAD*(270+(180/(rings + 1))*(i)))*cosf(DEG2RAD*((j+1)*360/slices))); - rlVertex3f(cosf(DEG2RAD*(270+(180/(rings + 1))*(i+1)))*sinf(DEG2RAD*((j+1)*360/slices)), - sinf(DEG2RAD*(270+(180/(rings + 1))*(i+1))), - cosf(DEG2RAD*(270+(180/(rings + 1))*(i+1)))*cosf(DEG2RAD*((j+1)*360/slices))); - } - } - rlEnd(); - rlPopMatrix(); -} - -// Draw sphere wires -void DrawSphereWires(Vector3 centerPos, float radius, int rings, int slices, Color color) -{ - rlPushMatrix(); - // NOTE: Transformation is applied in inverse order (scale -> translate) - rlTranslatef(centerPos.x, centerPos.y, centerPos.z); - rlScalef(radius, radius, radius); - - rlBegin(RL_LINES); - rlColor4ub(color.r, color.g, color.b, color.a); - - for (int i = 0; i < (rings + 2); i++) - { - for (int j = 0; j < slices; j++) - { - rlVertex3f(cosf(DEG2RAD*(270+(180/(rings + 1))*i))*sinf(DEG2RAD*(j*360/slices)), - sinf(DEG2RAD*(270+(180/(rings + 1))*i)), - cosf(DEG2RAD*(270+(180/(rings + 1))*i))*cosf(DEG2RAD*(j*360/slices))); - rlVertex3f(cosf(DEG2RAD*(270+(180/(rings + 1))*(i+1)))*sinf(DEG2RAD*((j+1)*360/slices)), - sinf(DEG2RAD*(270+(180/(rings + 1))*(i+1))), - cosf(DEG2RAD*(270+(180/(rings + 1))*(i+1)))*cosf(DEG2RAD*((j+1)*360/slices))); - - rlVertex3f(cosf(DEG2RAD*(270+(180/(rings + 1))*(i+1)))*sinf(DEG2RAD*((j+1)*360/slices)), - sinf(DEG2RAD*(270+(180/(rings + 1))*(i+1))), - cosf(DEG2RAD*(270+(180/(rings + 1))*(i+1)))*cosf(DEG2RAD*((j+1)*360/slices))); - rlVertex3f(cosf(DEG2RAD*(270+(180/(rings + 1))*(i+1)))*sinf(DEG2RAD*(j*360/slices)), - sinf(DEG2RAD*(270+(180/(rings + 1))*(i+1))), - cosf(DEG2RAD*(270+(180/(rings + 1))*(i+1)))*cosf(DEG2RAD*(j*360/slices))); - - rlVertex3f(cosf(DEG2RAD*(270+(180/(rings + 1))*(i+1)))*sinf(DEG2RAD*(j*360/slices)), - sinf(DEG2RAD*(270+(180/(rings + 1))*(i+1))), - cosf(DEG2RAD*(270+(180/(rings + 1))*(i+1)))*cosf(DEG2RAD*(j*360/slices))); - rlVertex3f(cosf(DEG2RAD*(270+(180/(rings + 1))*i))*sinf(DEG2RAD*(j*360/slices)), - sinf(DEG2RAD*(270+(180/(rings + 1))*i)), - cosf(DEG2RAD*(270+(180/(rings + 1))*i))*cosf(DEG2RAD*(j*360/slices))); - } - } - rlEnd(); - rlPopMatrix(); -} - -// Draw a cylinder -// NOTE: It could be also used for pyramid and cone -void DrawCylinder(Vector3 position, float radiusTop, float radiusBottom, float height, int sides, Color color) -{ - if (sides < 3) sides = 3; - - rlPushMatrix(); - rlTranslatef(position.x, position.y, position.z); - - rlBegin(RL_TRIANGLES); - rlColor4ub(color.r, color.g, color.b, color.a); - - if (radiusTop > 0) - { - // Draw Body ------------------------------------------------------------------------------------- - for (int i = 0; i < 360; i += 360/sides) - { - rlVertex3f(sinf(DEG2RAD*i)*radiusBottom, 0, cosf(DEG2RAD*i)*radiusBottom); //Bottom Left - rlVertex3f(sinf(DEG2RAD*(i + 360/sides))*radiusBottom, 0, cosf(DEG2RAD*(i + 360/sides))*radiusBottom); //Bottom Right - rlVertex3f(sinf(DEG2RAD*(i + 360/sides))*radiusTop, height, cosf(DEG2RAD*(i + 360/sides))*radiusTop); //Top Right - - rlVertex3f(sinf(DEG2RAD*i)*radiusTop, height, cosf(DEG2RAD*i)*radiusTop); //Top Left - rlVertex3f(sinf(DEG2RAD*i)*radiusBottom, 0, cosf(DEG2RAD*i)*radiusBottom); //Bottom Left - rlVertex3f(sinf(DEG2RAD*(i + 360/sides))*radiusTop, height, cosf(DEG2RAD*(i + 360/sides))*radiusTop); //Top Right - } - - // Draw Cap -------------------------------------------------------------------------------------- - for (int i = 0; i < 360; i += 360/sides) - { - rlVertex3f(0, height, 0); - rlVertex3f(sinf(DEG2RAD*i)*radiusTop, height, cosf(DEG2RAD*i)*radiusTop); - rlVertex3f(sinf(DEG2RAD*(i + 360/sides))*radiusTop, height, cosf(DEG2RAD*(i + 360/sides))*radiusTop); - } - } - else - { - // Draw Cone ------------------------------------------------------------------------------------- - for (int i = 0; i < 360; i += 360/sides) - { - rlVertex3f(0, height, 0); - rlVertex3f(sinf(DEG2RAD*i)*radiusBottom, 0, cosf(DEG2RAD*i)*radiusBottom); - rlVertex3f(sinf(DEG2RAD*(i + 360/sides))*radiusBottom, 0, cosf(DEG2RAD*(i + 360/sides))*radiusBottom); - } - } - - // Draw Base ----------------------------------------------------------------------------------------- - for (int i = 0; i < 360; i += 360/sides) - { - rlVertex3f(0, 0, 0); - rlVertex3f(sinf(DEG2RAD*(i + 360/sides))*radiusBottom, 0, cosf(DEG2RAD*(i + 360/sides))*radiusBottom); - rlVertex3f(sinf(DEG2RAD*i)*radiusBottom, 0, cosf(DEG2RAD*i)*radiusBottom); - } - rlEnd(); - rlPopMatrix(); -} - -// Draw a wired cylinder -// NOTE: It could be also used for pyramid and cone -void DrawCylinderWires(Vector3 position, float radiusTop, float radiusBottom, float height, int sides, Color color) -{ - if (sides < 3) sides = 3; - - rlPushMatrix(); - rlTranslatef(position.x, position.y, position.z); - - rlBegin(RL_LINES); - rlColor4ub(color.r, color.g, color.b, color.a); - - for (int i = 0; i < 360; i += 360/sides) - { - rlVertex3f(sinf(DEG2RAD*i)*radiusBottom, 0, cosf(DEG2RAD*i)*radiusBottom); - rlVertex3f(sinf(DEG2RAD*(i + 360/sides))*radiusBottom, 0, cosf(DEG2RAD*(i + 360/sides))*radiusBottom); - - rlVertex3f(sinf(DEG2RAD*(i + 360/sides))*radiusBottom, 0, cosf(DEG2RAD*(i + 360/sides))*radiusBottom); - rlVertex3f(sinf(DEG2RAD*(i + 360/sides))*radiusTop, height, cosf(DEG2RAD*(i + 360/sides))*radiusTop); - - rlVertex3f(sinf(DEG2RAD*(i + 360/sides))*radiusTop, height, cosf(DEG2RAD*(i + 360/sides))*radiusTop); - rlVertex3f(sinf(DEG2RAD*i)*radiusTop, height, cosf(DEG2RAD*i)*radiusTop); - - rlVertex3f(sinf(DEG2RAD*i)*radiusTop, height, cosf(DEG2RAD*i)*radiusTop); - rlVertex3f(sinf(DEG2RAD*i)*radiusBottom, 0, cosf(DEG2RAD*i)*radiusBottom); - } - rlEnd(); - rlPopMatrix(); -} - -// Draw a plane -void DrawPlane(Vector3 centerPos, Vector2 size, Color color) -{ - // NOTE: Plane is always created on XZ ground - rlPushMatrix(); - rlTranslatef(centerPos.x, centerPos.y, centerPos.z); - rlScalef(size.x, 1.0f, size.y); - - rlBegin(RL_TRIANGLES); - rlColor4ub(color.r, color.g, color.b, color.a); - rlNormal3f(0.0f, 1.0f, 0.0f); - - rlVertex3f(0.5f, 0.0f, -0.5f); - rlVertex3f(-0.5f, 0.0f, -0.5f); - rlVertex3f(-0.5f, 0.0f, 0.5f); - - rlVertex3f(-0.5f, 0.0f, 0.5f); - rlVertex3f(0.5f, 0.0f, 0.5f); - rlVertex3f(0.5f, 0.0f, -0.5f); - rlEnd(); - rlPopMatrix(); -} - -// Draw a ray line -void DrawRay(Ray ray, Color color) -{ - float scale = 10000; - - rlBegin(RL_LINES); - rlColor4ub(color.r, color.g, color.b, color.a); - rlColor4ub(color.r, color.g, color.b, color.a); - - rlVertex3f(ray.position.x, ray.position.y, ray.position.z); - rlVertex3f(ray.position.x + ray.direction.x*scale, ray.position.y + ray.direction.y*scale, ray.position.z + ray.direction.z*scale); - rlEnd(); -} - -// Draw a grid centered at (0, 0, 0) -void DrawGrid(int slices, float spacing) -{ - int halfSlices = slices/2; - - rlBegin(RL_LINES); - for (int i = -halfSlices; i <= halfSlices; i++) - { - if (i == 0) - { - rlColor3f(0.5f, 0.5f, 0.5f); - rlColor3f(0.5f, 0.5f, 0.5f); - rlColor3f(0.5f, 0.5f, 0.5f); - rlColor3f(0.5f, 0.5f, 0.5f); - } - else - { - rlColor3f(0.75f, 0.75f, 0.75f); - rlColor3f(0.75f, 0.75f, 0.75f); - rlColor3f(0.75f, 0.75f, 0.75f); - rlColor3f(0.75f, 0.75f, 0.75f); - } - - rlVertex3f((float)i*spacing, 0.0f, (float)-halfSlices*spacing); - rlVertex3f((float)i*spacing, 0.0f, (float)halfSlices*spacing); - - rlVertex3f((float)-halfSlices*spacing, 0.0f, (float)i*spacing); - rlVertex3f((float)halfSlices*spacing, 0.0f, (float)i*spacing); - } - rlEnd(); -} - -// Draw gizmo -void DrawGizmo(Vector3 position) -{ - // NOTE: RGB = XYZ - float length = 1.0f; - - rlPushMatrix(); - rlTranslatef(position.x, position.y, position.z); - rlScalef(length, length, length); - - rlBegin(RL_LINES); - rlColor3f(1.0f, 0.0f, 0.0f); rlVertex3f(0.0f, 0.0f, 0.0f); - rlColor3f(1.0f, 0.0f, 0.0f); rlVertex3f(1.0f, 0.0f, 0.0f); - - rlColor3f(0.0f, 1.0f, 0.0f); rlVertex3f(0.0f, 0.0f, 0.0f); - rlColor3f(0.0f, 1.0f, 0.0f); rlVertex3f(0.0f, 1.0f, 0.0f); - - rlColor3f(0.0f, 0.0f, 1.0f); rlVertex3f(0.0f, 0.0f, 0.0f); - rlColor3f(0.0f, 0.0f, 1.0f); rlVertex3f(0.0f, 0.0f, 1.0f); - rlEnd(); - rlPopMatrix(); -} - -// Load model from files (mesh and material) -Model LoadModel(const char *fileName) -{ - Model model = { 0 }; - - model.mesh = LoadMesh(fileName); - model.transform = MatrixIdentity(); - model.material = LoadMaterialDefault(); - - return model; -} - -// Load model from generated mesh -// WARNING: A shallow copy of mesh is generated, passed by value, -// as long as struct contains pointers to data and some values, we get a copy -// of mesh pointing to same data as original version... be careful! -Model LoadModelFromMesh(Mesh mesh) -{ - Model model = { 0 }; - - model.mesh = mesh; - model.transform = MatrixIdentity(); - model.material = LoadMaterialDefault(); - - return model; -} - -// Unload model from memory (RAM and/or VRAM) -void UnloadModel(Model model) -{ - UnloadMesh(&model.mesh); - UnloadMaterial(model.material); - - TraceLog(LOG_INFO, "Unloaded model data (mesh and material) from RAM and VRAM"); -} - -// Load mesh from file -// NOTE: Mesh data loaded in CPU and GPU -Mesh LoadMesh(const char *fileName) -{ - Mesh mesh = { 0 }; - -#if defined(SUPPORT_FILEFORMAT_OBJ) - if (IsFileExtension(fileName, ".obj")) mesh = LoadOBJ(fileName); -#else - TraceLog(LOG_WARNING, "[%s] Mesh fileformat not supported, it can't be loaded", fileName); -#endif - - if (mesh.vertexCount == 0) TraceLog(LOG_WARNING, "Mesh could not be loaded"); - else rlLoadMesh(&mesh, false); // Upload vertex data to GPU (static mesh) - - // TODO: Initialize default mesh data in case loading fails, maybe a cube? - - return mesh; -} - -// Unload mesh from memory (RAM and/or VRAM) -void UnloadMesh(Mesh *mesh) -{ - rlUnloadMesh(mesh); -} - -#if defined(SUPPORT_MESH_GENERATION) -// Generate plane mesh (with subdivisions) -Mesh GenMeshPlane(float width, float length, int resX, int resZ) -{ - Mesh mesh = { 0 }; - -#define CUSTOM_MESH_GEN_PLANE -#if defined(CUSTOM_MESH_GEN_PLANE) - resX++; - resZ++; - - // Vertices definition - int vertexCount = resX*resZ*6; // 6 vertex by quad - - Vector3 *vertices = (Vector3 *)malloc(vertexCount*sizeof(Vector3)); - for (int z = 0; z < resZ; z++) - { - // [-length/2, length/2] - float zPos = ((float)z/(resZ - 1) - 0.5f)*length; - for (int x = 0; x < resX; x++) - { - // [-width/2, width/2] - float xPos = ((float)x/(resX - 1) - 0.5f)*width; - vertices[x + z*resX] = (Vector3){ xPos, 0.0f, zPos }; - } - } - - // Normals definition - Vector3 *normals = (Vector3 *)malloc(vertexCount*sizeof(Vector3)); - for (int n = 0; n < vertexCount; n++) normals[n] = (Vector3){ 0.0f, 1.0f, 0.0f }; // Vector3.up; - - // TexCoords definition - Vector2 *texcoords = (Vector2 *)malloc(vertexCount*sizeof(Vector2)); - for (int v = 0; v < resZ; v++) - { - for (int u = 0; u < resX; u++) - { - texcoords[u + v*resX] = (Vector2){ (float)u/(resX - 1), (float)v/(resZ - 1) }; - } - } - - // Triangles definition (indices) - int numFaces = (resX - 1)*(resZ - 1); - int *triangles = (int *)malloc(numFaces*6*sizeof(int)); - int t = 0; - for (int face = 0; face < numFaces; face++) - { - // Retrieve lower left corner from face ind - int i = face % (resX - 1) + (face/(resZ - 1)*resX); - - triangles[t++] = i + resX; - triangles[t++] = i + 1; - triangles[t++] = i; - - triangles[t++] = i + resX; - triangles[t++] = i + resX + 1; - triangles[t++] = i + 1; - } - - mesh.vertexCount = vertexCount; - mesh.triangleCount = numFaces*2; - mesh.vertices = (float *)malloc(mesh.vertexCount*3*sizeof(float)); - mesh.texcoords = (float *)malloc(mesh.vertexCount*2*sizeof(float)); - mesh.normals = (float *)malloc(mesh.vertexCount*3*sizeof(float)); - mesh.indices = (unsigned short *)malloc(mesh.triangleCount*3*sizeof(unsigned short)); - - // Mesh vertices position array - for (int i = 0; i < mesh.vertexCount; i++) - { - mesh.vertices[3*i] = vertices[i].x; - mesh.vertices[3*i + 1] = vertices[i].y; - mesh.vertices[3*i + 2] = vertices[i].z; - } - - // Mesh texcoords array - for (int i = 0; i < mesh.vertexCount; i++) - { - mesh.texcoords[2*i] = texcoords[i].x; - mesh.texcoords[2*i + 1] = texcoords[i].y; - } - - // Mesh normals array - for (int i = 0; i < mesh.vertexCount; i++) - { - mesh.normals[3*i] = normals[i].x; - mesh.normals[3*i + 1] = normals[i].y; - mesh.normals[3*i + 2] = normals[i].z; - } - - // Mesh indices array initialization - for (int i = 0; i < mesh.triangleCount*3; i++) mesh.indices[i] = triangles[i]; - - free(vertices); - free(normals); - free(texcoords); - free(triangles); - -#else // Use par_shapes library to generate plane mesh - - par_shapes_mesh *plane = par_shapes_create_plane(resX, resZ); // No normals/texcoords generated!!! - par_shapes_scale(plane, width, length, 1.0f); - par_shapes_rotate(plane, -PI/2.0f, (float[]){ 1, 0, 0 }); - par_shapes_translate(plane, -width/2, 0.0f, length/2); - - mesh.vertices = (float *)malloc(plane->ntriangles*3*3*sizeof(float)); - mesh.texcoords = (float *)malloc(plane->ntriangles*3*2*sizeof(float)); - mesh.normals = (float *)malloc(plane->ntriangles*3*3*sizeof(float)); - - mesh.vertexCount = plane->ntriangles*3; - mesh.triangleCount = plane->ntriangles; - - for (int k = 0; k < mesh.vertexCount; k++) - { - mesh.vertices[k*3] = plane->points[plane->triangles[k]*3]; - mesh.vertices[k*3 + 1] = plane->points[plane->triangles[k]*3 + 1]; - mesh.vertices[k*3 + 2] = plane->points[plane->triangles[k]*3 + 2]; - - mesh.normals[k*3] = plane->normals[plane->triangles[k]*3]; - mesh.normals[k*3 + 1] = plane->normals[plane->triangles[k]*3 + 1]; - mesh.normals[k*3 + 2] = plane->normals[plane->triangles[k]*3 + 2]; - - mesh.texcoords[k*2] = plane->tcoords[plane->triangles[k]*2]; - mesh.texcoords[k*2 + 1] = plane->tcoords[plane->triangles[k]*2 + 1]; - } - - par_shapes_free_mesh(plane); -#endif - - // Upload vertex data to GPU (static mesh) - rlLoadMesh(&mesh, false); - - return mesh; -} - -// Generated cuboid mesh -Mesh GenMeshCube(float width, float height, float length) -{ - Mesh mesh = { 0 }; - -#define CUSTOM_MESH_GEN_CUBE -#if defined(CUSTOM_MESH_GEN_CUBE) - float vertices[] = { - -width/2, -height/2, length/2, - width/2, -height/2, length/2, - width/2, height/2, length/2, - -width/2, height/2, length/2, - -width/2, -height/2, -length/2, - -width/2, height/2, -length/2, - width/2, height/2, -length/2, - width/2, -height/2, -length/2, - -width/2, height/2, -length/2, - -width/2, height/2, length/2, - width/2, height/2, length/2, - width/2, height/2, -length/2, - -width/2, -height/2, -length/2, - width/2, -height/2, -length/2, - width/2, -height/2, length/2, - -width/2, -height/2, length/2, - width/2, -height/2, -length/2, - width/2, height/2, -length/2, - width/2, height/2, length/2, - width/2, -height/2, length/2, - -width/2, -height/2, -length/2, - -width/2, -height/2, length/2, - -width/2, height/2, length/2, - -width/2, height/2, -length/2 - }; - - float texcoords[] = { - 0.0f, 0.0f, - 1.0f, 0.0f, - 1.0f, 1.0f, - 0.0f, 1.0f, - 1.0f, 0.0f, - 1.0f, 1.0f, - 0.0f, 1.0f, - 0.0f, 0.0f, - 0.0f, 1.0f, - 0.0f, 0.0f, - 1.0f, 0.0f, - 1.0f, 1.0f, - 1.0f, 1.0f, - 0.0f, 1.0f, - 0.0f, 0.0f, - 1.0f, 0.0f, - 1.0f, 0.0f, - 1.0f, 1.0f, - 0.0f, 1.0f, - 0.0f, 0.0f, - 0.0f, 0.0f, - 1.0f, 0.0f, - 1.0f, 1.0f, - 0.0f, 1.0f - }; - - float normals[] = { - 0.0f, 0.0f, 1.0f, - 0.0f, 0.0f, 1.0f, - 0.0f, 0.0f, 1.0f, - 0.0f, 0.0f, 1.0f, - 0.0f, 0.0f,-1.0f, - 0.0f, 0.0f,-1.0f, - 0.0f, 0.0f,-1.0f, - 0.0f, 0.0f,-1.0f, - 0.0f, 1.0f, 0.0f, - 0.0f, 1.0f, 0.0f, - 0.0f, 1.0f, 0.0f, - 0.0f, 1.0f, 0.0f, - 0.0f,-1.0f, 0.0f, - 0.0f,-1.0f, 0.0f, - 0.0f,-1.0f, 0.0f, - 0.0f,-1.0f, 0.0f, - 1.0f, 0.0f, 0.0f, - 1.0f, 0.0f, 0.0f, - 1.0f, 0.0f, 0.0f, - 1.0f, 0.0f, 0.0f, - -1.0f, 0.0f, 0.0f, - -1.0f, 0.0f, 0.0f, - -1.0f, 0.0f, 0.0f, - -1.0f, 0.0f, 0.0f - }; - - mesh.vertices = (float *)malloc(24*3*sizeof(float)); - memcpy(mesh.vertices, vertices, 24*3*sizeof(float)); - - mesh.texcoords = (float *)malloc(24*2*sizeof(float)); - memcpy(mesh.texcoords, texcoords, 24*2*sizeof(float)); - - mesh.normals = (float *)malloc(24*3*sizeof(float)); - memcpy(mesh.normals, normals, 24*3*sizeof(float)); - - mesh.indices = (unsigned short *)malloc(36*sizeof(unsigned short)); - - int k = 0; - - // Indices can be initialized right now - for (int i = 0; i < 36; i+=6) - { - mesh.indices[i] = 4*k; - mesh.indices[i+1] = 4*k+1; - mesh.indices[i+2] = 4*k+2; - mesh.indices[i+3] = 4*k; - mesh.indices[i+4] = 4*k+2; - mesh.indices[i+5] = 4*k+3; - - k++; - } - - mesh.vertexCount = 24; - mesh.triangleCount = 12; - -#else // Use par_shapes library to generate cube mesh -/* -// Platonic solids: -par_shapes_mesh* par_shapes_create_tetrahedron(); // 4 sides polyhedron (pyramid) -par_shapes_mesh* par_shapes_create_cube(); // 6 sides polyhedron (cube) -par_shapes_mesh* par_shapes_create_octahedron(); // 8 sides polyhedron (dyamond) -par_shapes_mesh* par_shapes_create_dodecahedron(); // 12 sides polyhedron -par_shapes_mesh* par_shapes_create_icosahedron(); // 20 sides polyhedron -*/ - // Platonic solid generation: cube (6 sides) - // NOTE: No normals/texcoords generated by default - par_shapes_mesh *cube = par_shapes_create_cube(); - cube->tcoords = PAR_MALLOC(float, 2*cube->npoints); - for (int i = 0; i < 2*cube->npoints; i++) cube->tcoords[i] = 0.0f; - par_shapes_scale(cube, width, height, length); - par_shapes_translate(cube, -width/2, 0.0f, -length/2); - par_shapes_compute_normals(cube); - - mesh.vertices = (float *)malloc(cube->ntriangles*3*3*sizeof(float)); - mesh.texcoords = (float *)malloc(cube->ntriangles*3*2*sizeof(float)); - mesh.normals = (float *)malloc(cube->ntriangles*3*3*sizeof(float)); - - mesh.vertexCount = cube->ntriangles*3; - mesh.triangleCount = cube->ntriangles; - - for (int k = 0; k < mesh.vertexCount; k++) - { - mesh.vertices[k*3] = cube->points[cube->triangles[k]*3]; - mesh.vertices[k*3 + 1] = cube->points[cube->triangles[k]*3 + 1]; - mesh.vertices[k*3 + 2] = cube->points[cube->triangles[k]*3 + 2]; - - mesh.normals[k*3] = cube->normals[cube->triangles[k]*3]; - mesh.normals[k*3 + 1] = cube->normals[cube->triangles[k]*3 + 1]; - mesh.normals[k*3 + 2] = cube->normals[cube->triangles[k]*3 + 2]; - - mesh.texcoords[k*2] = cube->tcoords[cube->triangles[k]*2]; - mesh.texcoords[k*2 + 1] = cube->tcoords[cube->triangles[k]*2 + 1]; - } - - par_shapes_free_mesh(cube); -#endif - - // Upload vertex data to GPU (static mesh) - rlLoadMesh(&mesh, false); - - return mesh; -} - -// Generate sphere mesh (standard sphere) -RLAPI Mesh GenMeshSphere(float radius, int rings, int slices) -{ - Mesh mesh = { 0 }; - - par_shapes_mesh *sphere = par_shapes_create_parametric_sphere(slices, rings); - par_shapes_scale(sphere, radius, radius, radius); - // NOTE: Soft normals are computed internally - - mesh.vertices = (float *)malloc(sphere->ntriangles*3*3*sizeof(float)); - mesh.texcoords = (float *)malloc(sphere->ntriangles*3*2*sizeof(float)); - mesh.normals = (float *)malloc(sphere->ntriangles*3*3*sizeof(float)); - - mesh.vertexCount = sphere->ntriangles*3; - mesh.triangleCount = sphere->ntriangles; - - for (int k = 0; k < mesh.vertexCount; k++) - { - mesh.vertices[k*3] = sphere->points[sphere->triangles[k]*3]; - mesh.vertices[k*3 + 1] = sphere->points[sphere->triangles[k]*3 + 1]; - mesh.vertices[k*3 + 2] = sphere->points[sphere->triangles[k]*3 + 2]; - - mesh.normals[k*3] = sphere->normals[sphere->triangles[k]*3]; - mesh.normals[k*3 + 1] = sphere->normals[sphere->triangles[k]*3 + 1]; - mesh.normals[k*3 + 2] = sphere->normals[sphere->triangles[k]*3 + 2]; - - mesh.texcoords[k*2] = sphere->tcoords[sphere->triangles[k]*2]; - mesh.texcoords[k*2 + 1] = sphere->tcoords[sphere->triangles[k]*2 + 1]; - } - - par_shapes_free_mesh(sphere); - - // Upload vertex data to GPU (static mesh) - rlLoadMesh(&mesh, false); - - return mesh; -} - -// Generate hemi-sphere mesh (half sphere, no bottom cap) -RLAPI Mesh GenMeshHemiSphere(float radius, int rings, int slices) -{ - Mesh mesh = { 0 }; - - par_shapes_mesh *sphere = par_shapes_create_hemisphere(slices, rings); - par_shapes_scale(sphere, radius, radius, radius); - // NOTE: Soft normals are computed internally - - mesh.vertices = (float *)malloc(sphere->ntriangles*3*3*sizeof(float)); - mesh.texcoords = (float *)malloc(sphere->ntriangles*3*2*sizeof(float)); - mesh.normals = (float *)malloc(sphere->ntriangles*3*3*sizeof(float)); - - mesh.vertexCount = sphere->ntriangles*3; - mesh.triangleCount = sphere->ntriangles; - - for (int k = 0; k < mesh.vertexCount; k++) - { - mesh.vertices[k*3] = sphere->points[sphere->triangles[k]*3]; - mesh.vertices[k*3 + 1] = sphere->points[sphere->triangles[k]*3 + 1]; - mesh.vertices[k*3 + 2] = sphere->points[sphere->triangles[k]*3 + 2]; - - mesh.normals[k*3] = sphere->normals[sphere->triangles[k]*3]; - mesh.normals[k*3 + 1] = sphere->normals[sphere->triangles[k]*3 + 1]; - mesh.normals[k*3 + 2] = sphere->normals[sphere->triangles[k]*3 + 2]; - - mesh.texcoords[k*2] = sphere->tcoords[sphere->triangles[k]*2]; - mesh.texcoords[k*2 + 1] = sphere->tcoords[sphere->triangles[k]*2 + 1]; - } - - par_shapes_free_mesh(sphere); - - // Upload vertex data to GPU (static mesh) - rlLoadMesh(&mesh, false); - - return mesh; -} - -// Generate cylinder mesh -Mesh GenMeshCylinder(float radius, float height, int slices) -{ - Mesh mesh = { 0 }; - - // Instance a cylinder that sits on the Z=0 plane using the given tessellation - // levels across the UV domain. Think of "slices" like a number of pizza - // slices, and "stacks" like a number of stacked rings. - // Height and radius are both 1.0, but they can easily be changed with par_shapes_scale - par_shapes_mesh *cylinder = par_shapes_create_cylinder(slices, 8); - par_shapes_scale(cylinder, radius, radius, height); - par_shapes_rotate(cylinder, -PI/2.0f, (float[]){ 1, 0, 0 }); - - // Generate an orientable disk shape (top cap) - par_shapes_mesh *capTop = par_shapes_create_disk(radius, slices, (float[]){ 0, 0, 0 }, (float[]){ 0, 0, 1 }); - capTop->tcoords = PAR_MALLOC(float, 2*capTop->npoints); - for (int i = 0; i < 2*capTop->npoints; i++) capTop->tcoords[i] = 0.0f; - par_shapes_rotate(capTop, -PI/2.0f, (float[]){ 1, 0, 0 }); - par_shapes_translate(capTop, 0, height, 0); - - // Generate an orientable disk shape (bottom cap) - par_shapes_mesh *capBottom = par_shapes_create_disk(radius, slices, (float[]){ 0, 0, 0 }, (float[]){ 0, 0, -1 }); - capBottom->tcoords = PAR_MALLOC(float, 2*capBottom->npoints); - for (int i = 0; i < 2*capBottom->npoints; i++) capBottom->tcoords[i] = 0.95f; - par_shapes_rotate(capBottom, PI/2.0f, (float[]){ 1, 0, 0 }); - - par_shapes_merge_and_free(cylinder, capTop); - par_shapes_merge_and_free(cylinder, capBottom); - - mesh.vertices = (float *)malloc(cylinder->ntriangles*3*3*sizeof(float)); - mesh.texcoords = (float *)malloc(cylinder->ntriangles*3*2*sizeof(float)); - mesh.normals = (float *)malloc(cylinder->ntriangles*3*3*sizeof(float)); - - mesh.vertexCount = cylinder->ntriangles*3; - mesh.triangleCount = cylinder->ntriangles; - - for (int k = 0; k < mesh.vertexCount; k++) - { - mesh.vertices[k*3] = cylinder->points[cylinder->triangles[k]*3]; - mesh.vertices[k*3 + 1] = cylinder->points[cylinder->triangles[k]*3 + 1]; - mesh.vertices[k*3 + 2] = cylinder->points[cylinder->triangles[k]*3 + 2]; - - mesh.normals[k*3] = cylinder->normals[cylinder->triangles[k]*3]; - mesh.normals[k*3 + 1] = cylinder->normals[cylinder->triangles[k]*3 + 1]; - mesh.normals[k*3 + 2] = cylinder->normals[cylinder->triangles[k]*3 + 2]; - - mesh.texcoords[k*2] = cylinder->tcoords[cylinder->triangles[k]*2]; - mesh.texcoords[k*2 + 1] = cylinder->tcoords[cylinder->triangles[k]*2 + 1]; - } - - par_shapes_free_mesh(cylinder); - - // Upload vertex data to GPU (static mesh) - rlLoadMesh(&mesh, false); - - return mesh; -} - -// Generate torus mesh -Mesh GenMeshTorus(float radius, float size, int radSeg, int sides) -{ - Mesh mesh = { 0 }; - - if (radius > 1.0f) radius = 1.0f; - else if (radius < 0.1f) radius = 0.1f; - - // Create a donut that sits on the Z=0 plane with the specified inner radius - // The outer radius can be controlled with par_shapes_scale - par_shapes_mesh *torus = par_shapes_create_torus(radSeg, sides, radius); - par_shapes_scale(torus, size/2, size/2, size/2); - - mesh.vertices = (float *)malloc(torus->ntriangles*3*3*sizeof(float)); - mesh.texcoords = (float *)malloc(torus->ntriangles*3*2*sizeof(float)); - mesh.normals = (float *)malloc(torus->ntriangles*3*3*sizeof(float)); - - mesh.vertexCount = torus->ntriangles*3; - mesh.triangleCount = torus->ntriangles; - - for (int k = 0; k < mesh.vertexCount; k++) - { - mesh.vertices[k*3] = torus->points[torus->triangles[k]*3]; - mesh.vertices[k*3 + 1] = torus->points[torus->triangles[k]*3 + 1]; - mesh.vertices[k*3 + 2] = torus->points[torus->triangles[k]*3 + 2]; - - mesh.normals[k*3] = torus->normals[torus->triangles[k]*3]; - mesh.normals[k*3 + 1] = torus->normals[torus->triangles[k]*3 + 1]; - mesh.normals[k*3 + 2] = torus->normals[torus->triangles[k]*3 + 2]; - - mesh.texcoords[k*2] = torus->tcoords[torus->triangles[k]*2]; - mesh.texcoords[k*2 + 1] = torus->tcoords[torus->triangles[k]*2 + 1]; - } - - par_shapes_free_mesh(torus); - - // Upload vertex data to GPU (static mesh) - rlLoadMesh(&mesh, false); - - return mesh; -} - -// Generate trefoil knot mesh -Mesh GenMeshKnot(float radius, float size, int radSeg, int sides) -{ - Mesh mesh = { 0 }; - - if (radius > 3.0f) radius = 3.0f; - else if (radius < 0.5f) radius = 0.5f; - - par_shapes_mesh *knot = par_shapes_create_trefoil_knot(radSeg, sides, radius); - par_shapes_scale(knot, size, size, size); - - mesh.vertices = (float *)malloc(knot->ntriangles*3*3*sizeof(float)); - mesh.texcoords = (float *)malloc(knot->ntriangles*3*2*sizeof(float)); - mesh.normals = (float *)malloc(knot->ntriangles*3*3*sizeof(float)); - - mesh.vertexCount = knot->ntriangles*3; - mesh.triangleCount = knot->ntriangles; - - for (int k = 0; k < mesh.vertexCount; k++) - { - mesh.vertices[k*3] = knot->points[knot->triangles[k]*3]; - mesh.vertices[k*3 + 1] = knot->points[knot->triangles[k]*3 + 1]; - mesh.vertices[k*3 + 2] = knot->points[knot->triangles[k]*3 + 2]; - - mesh.normals[k*3] = knot->normals[knot->triangles[k]*3]; - mesh.normals[k*3 + 1] = knot->normals[knot->triangles[k]*3 + 1]; - mesh.normals[k*3 + 2] = knot->normals[knot->triangles[k]*3 + 2]; - - mesh.texcoords[k*2] = knot->tcoords[knot->triangles[k]*2]; - mesh.texcoords[k*2 + 1] = knot->tcoords[knot->triangles[k]*2 + 1]; - } - - par_shapes_free_mesh(knot); - - // Upload vertex data to GPU (static mesh) - rlLoadMesh(&mesh, false); - - return mesh; -} - -// Generate a mesh from heightmap -// NOTE: Vertex data is uploaded to GPU -Mesh GenMeshHeightmap(Image heightmap, Vector3 size) -{ - #define GRAY_VALUE(c) ((c.r+c.g+c.b)/3) - - Mesh mesh = { 0 }; - - int mapX = heightmap.width; - int mapZ = heightmap.height; - - Color *pixels = GetImageData(heightmap); - - // NOTE: One vertex per pixel - int triangleCount = (mapX-1)*(mapZ-1)*2; // One quad every four pixels - - mesh.vertexCount = triangleCount*3; - - mesh.vertices = (float *)malloc(mesh.vertexCount*3*sizeof(float)); - mesh.normals = (float *)malloc(mesh.vertexCount*3*sizeof(float)); - mesh.texcoords = (float *)malloc(mesh.vertexCount*2*sizeof(float)); - mesh.colors = NULL; - - int vCounter = 0; // Used to count vertices float by float - int tcCounter = 0; // Used to count texcoords float by float - int nCounter = 0; // Used to count normals float by float - - int trisCounter = 0; - - Vector3 scaleFactor = { size.x/mapX, size.y/255.0f, size.z/mapZ }; - - for (int z = 0; z < mapZ-1; z++) - { - for (int x = 0; x < mapX-1; x++) - { - // Fill vertices array with data - //---------------------------------------------------------- - - // one triangle - 3 vertex - mesh.vertices[vCounter] = (float)x*scaleFactor.x; - mesh.vertices[vCounter + 1] = (float)GRAY_VALUE(pixels[x + z*mapX])*scaleFactor.y; - mesh.vertices[vCounter + 2] = (float)z*scaleFactor.z; - - mesh.vertices[vCounter + 3] = (float)x*scaleFactor.x; - mesh.vertices[vCounter + 4] = (float)GRAY_VALUE(pixels[x + (z + 1)*mapX])*scaleFactor.y; - mesh.vertices[vCounter + 5] = (float)(z + 1)*scaleFactor.z; - - mesh.vertices[vCounter + 6] = (float)(x + 1)*scaleFactor.x; - mesh.vertices[vCounter + 7] = (float)GRAY_VALUE(pixels[(x + 1) + z*mapX])*scaleFactor.y; - mesh.vertices[vCounter + 8] = (float)z*scaleFactor.z; - - // another triangle - 3 vertex - mesh.vertices[vCounter + 9] = mesh.vertices[vCounter + 6]; - mesh.vertices[vCounter + 10] = mesh.vertices[vCounter + 7]; - mesh.vertices[vCounter + 11] = mesh.vertices[vCounter + 8]; - - mesh.vertices[vCounter + 12] = mesh.vertices[vCounter + 3]; - mesh.vertices[vCounter + 13] = mesh.vertices[vCounter + 4]; - mesh.vertices[vCounter + 14] = mesh.vertices[vCounter + 5]; - - mesh.vertices[vCounter + 15] = (float)(x + 1)*scaleFactor.x; - mesh.vertices[vCounter + 16] = (float)GRAY_VALUE(pixels[(x + 1) + (z + 1)*mapX])*scaleFactor.y; - mesh.vertices[vCounter + 17] = (float)(z + 1)*scaleFactor.z; - vCounter += 18; // 6 vertex, 18 floats - - // Fill texcoords array with data - //-------------------------------------------------------------- - mesh.texcoords[tcCounter] = (float)x/(mapX - 1); - mesh.texcoords[tcCounter + 1] = (float)z/(mapZ - 1); - - mesh.texcoords[tcCounter + 2] = (float)x/(mapX - 1); - mesh.texcoords[tcCounter + 3] = (float)(z + 1)/(mapZ - 1); - - mesh.texcoords[tcCounter + 4] = (float)(x + 1)/(mapX - 1); - mesh.texcoords[tcCounter + 5] = (float)z/(mapZ - 1); - - mesh.texcoords[tcCounter + 6] = mesh.texcoords[tcCounter + 4]; - mesh.texcoords[tcCounter + 7] = mesh.texcoords[tcCounter + 5]; - - mesh.texcoords[tcCounter + 8] = mesh.texcoords[tcCounter + 2]; - mesh.texcoords[tcCounter + 9] = mesh.texcoords[tcCounter + 3]; - - mesh.texcoords[tcCounter + 10] = (float)(x + 1)/(mapX - 1); - mesh.texcoords[tcCounter + 11] = (float)(z + 1)/(mapZ - 1); - tcCounter += 12; // 6 texcoords, 12 floats - - // Fill normals array with data - //-------------------------------------------------------------- - for (int i = 0; i < 18; i += 3) - { - mesh.normals[nCounter + i] = 0.0f; - mesh.normals[nCounter + i + 1] = 1.0f; - mesh.normals[nCounter + i + 2] = 0.0f; - } - - // TODO: Calculate normals in an efficient way - - nCounter += 18; // 6 vertex, 18 floats - trisCounter += 2; - } - } - - free(pixels); - - // Upload vertex data to GPU (static mesh) - rlLoadMesh(&mesh, false); - - return mesh; -} - -// Generate a cubes mesh from pixel data -// NOTE: Vertex data is uploaded to GPU -Mesh GenMeshCubicmap(Image cubicmap, Vector3 cubeSize) -{ - Mesh mesh = { 0 }; - - Color *cubicmapPixels = GetImageData(cubicmap); - - int mapWidth = cubicmap.width; - int mapHeight = cubicmap.height; - - // NOTE: Max possible number of triangles numCubes * (12 triangles by cube) - int maxTriangles = cubicmap.width*cubicmap.height*12; - - int vCounter = 0; // Used to count vertices - int tcCounter = 0; // Used to count texcoords - int nCounter = 0; // Used to count normals - - float w = cubeSize.x; - float h = cubeSize.z; - float h2 = cubeSize.y; - - Vector3 *mapVertices = (Vector3 *)malloc(maxTriangles*3*sizeof(Vector3)); - Vector2 *mapTexcoords = (Vector2 *)malloc(maxTriangles*3*sizeof(Vector2)); - Vector3 *mapNormals = (Vector3 *)malloc(maxTriangles*3*sizeof(Vector3)); - - // Define the 6 normals of the cube, we will combine them accordingly later... - Vector3 n1 = { 1.0f, 0.0f, 0.0f }; - Vector3 n2 = { -1.0f, 0.0f, 0.0f }; - Vector3 n3 = { 0.0f, 1.0f, 0.0f }; - Vector3 n4 = { 0.0f, -1.0f, 0.0f }; - Vector3 n5 = { 0.0f, 0.0f, 1.0f }; - Vector3 n6 = { 0.0f, 0.0f, -1.0f }; - - // NOTE: We use texture rectangles to define different textures for top-bottom-front-back-right-left (6) - typedef struct RectangleF { - float x; - float y; - float width; - float height; - } RectangleF; - - RectangleF rightTexUV = { 0.0f, 0.0f, 0.5f, 0.5f }; - RectangleF leftTexUV = { 0.5f, 0.0f, 0.5f, 0.5f }; - RectangleF frontTexUV = { 0.0f, 0.0f, 0.5f, 0.5f }; - RectangleF backTexUV = { 0.5f, 0.0f, 0.5f, 0.5f }; - RectangleF topTexUV = { 0.0f, 0.5f, 0.5f, 0.5f }; - RectangleF bottomTexUV = { 0.5f, 0.5f, 0.5f, 0.5f }; - - for (int z = 0; z < mapHeight; ++z) - { - for (int x = 0; x < mapWidth; ++x) - { - // Define the 8 vertex of the cube, we will combine them accordingly later... - Vector3 v1 = { w*(x - 0.5f), h2, h*(z - 0.5f) }; - Vector3 v2 = { w*(x - 0.5f), h2, h*(z + 0.5f) }; - Vector3 v3 = { w*(x + 0.5f), h2, h*(z + 0.5f) }; - Vector3 v4 = { w*(x + 0.5f), h2, h*(z - 0.5f) }; - Vector3 v5 = { w*(x + 0.5f), 0, h*(z - 0.5f) }; - Vector3 v6 = { w*(x - 0.5f), 0, h*(z - 0.5f) }; - Vector3 v7 = { w*(x - 0.5f), 0, h*(z + 0.5f) }; - Vector3 v8 = { w*(x + 0.5f), 0, h*(z + 0.5f) }; - - // We check pixel color to be WHITE, we will full cubes - if ((cubicmapPixels[z*cubicmap.width + x].r == 255) && - (cubicmapPixels[z*cubicmap.width + x].g == 255) && - (cubicmapPixels[z*cubicmap.width + x].b == 255)) - { - // Define triangles (Checking Collateral Cubes!) - //---------------------------------------------- - - // Define top triangles (2 tris, 6 vertex --> v1-v2-v3, v1-v3-v4) - mapVertices[vCounter] = v1; - mapVertices[vCounter + 1] = v2; - mapVertices[vCounter + 2] = v3; - mapVertices[vCounter + 3] = v1; - mapVertices[vCounter + 4] = v3; - mapVertices[vCounter + 5] = v4; - vCounter += 6; - - mapNormals[nCounter] = n3; - mapNormals[nCounter + 1] = n3; - mapNormals[nCounter + 2] = n3; - mapNormals[nCounter + 3] = n3; - mapNormals[nCounter + 4] = n3; - mapNormals[nCounter + 5] = n3; - nCounter += 6; - - mapTexcoords[tcCounter] = (Vector2){ topTexUV.x, topTexUV.y }; - mapTexcoords[tcCounter + 1] = (Vector2){ topTexUV.x, topTexUV.y + topTexUV.height }; - mapTexcoords[tcCounter + 2] = (Vector2){ topTexUV.x + topTexUV.width, topTexUV.y + topTexUV.height }; - mapTexcoords[tcCounter + 3] = (Vector2){ topTexUV.x, topTexUV.y }; - mapTexcoords[tcCounter + 4] = (Vector2){ topTexUV.x + topTexUV.width, topTexUV.y + topTexUV.height }; - mapTexcoords[tcCounter + 5] = (Vector2){ topTexUV.x + topTexUV.width, topTexUV.y }; - tcCounter += 6; - - // Define bottom triangles (2 tris, 6 vertex --> v6-v8-v7, v6-v5-v8) - mapVertices[vCounter] = v6; - mapVertices[vCounter + 1] = v8; - mapVertices[vCounter + 2] = v7; - mapVertices[vCounter + 3] = v6; - mapVertices[vCounter + 4] = v5; - mapVertices[vCounter + 5] = v8; - vCounter += 6; - - mapNormals[nCounter] = n4; - mapNormals[nCounter + 1] = n4; - mapNormals[nCounter + 2] = n4; - mapNormals[nCounter + 3] = n4; - mapNormals[nCounter + 4] = n4; - mapNormals[nCounter + 5] = n4; - nCounter += 6; - - mapTexcoords[tcCounter] = (Vector2){ bottomTexUV.x + bottomTexUV.width, bottomTexUV.y }; - mapTexcoords[tcCounter + 1] = (Vector2){ bottomTexUV.x, bottomTexUV.y + bottomTexUV.height }; - mapTexcoords[tcCounter + 2] = (Vector2){ bottomTexUV.x + bottomTexUV.width, bottomTexUV.y + bottomTexUV.height }; - mapTexcoords[tcCounter + 3] = (Vector2){ bottomTexUV.x + bottomTexUV.width, bottomTexUV.y }; - mapTexcoords[tcCounter + 4] = (Vector2){ bottomTexUV.x, bottomTexUV.y }; - mapTexcoords[tcCounter + 5] = (Vector2){ bottomTexUV.x, bottomTexUV.y + bottomTexUV.height }; - tcCounter += 6; - - if (((z < cubicmap.height - 1) && - (cubicmapPixels[(z + 1)*cubicmap.width + x].r == 0) && - (cubicmapPixels[(z + 1)*cubicmap.width + x].g == 0) && - (cubicmapPixels[(z + 1)*cubicmap.width + x].b == 0)) || (z == cubicmap.height - 1)) - { - // Define front triangles (2 tris, 6 vertex) --> v2 v7 v3, v3 v7 v8 - // NOTE: Collateral occluded faces are not generated - mapVertices[vCounter] = v2; - mapVertices[vCounter + 1] = v7; - mapVertices[vCounter + 2] = v3; - mapVertices[vCounter + 3] = v3; - mapVertices[vCounter + 4] = v7; - mapVertices[vCounter + 5] = v8; - vCounter += 6; - - mapNormals[nCounter] = n6; - mapNormals[nCounter + 1] = n6; - mapNormals[nCounter + 2] = n6; - mapNormals[nCounter + 3] = n6; - mapNormals[nCounter + 4] = n6; - mapNormals[nCounter + 5] = n6; - nCounter += 6; - - mapTexcoords[tcCounter] = (Vector2){ frontTexUV.x, frontTexUV.y }; - mapTexcoords[tcCounter + 1] = (Vector2){ frontTexUV.x, frontTexUV.y + frontTexUV.height }; - mapTexcoords[tcCounter + 2] = (Vector2){ frontTexUV.x + frontTexUV.width, frontTexUV.y }; - mapTexcoords[tcCounter + 3] = (Vector2){ frontTexUV.x + frontTexUV.width, frontTexUV.y }; - mapTexcoords[tcCounter + 4] = (Vector2){ frontTexUV.x, frontTexUV.y + frontTexUV.height }; - mapTexcoords[tcCounter + 5] = (Vector2){ frontTexUV.x + frontTexUV.width, frontTexUV.y + frontTexUV.height }; - tcCounter += 6; - } - - if (((z > 0) && - (cubicmapPixels[(z - 1)*cubicmap.width + x].r == 0) && - (cubicmapPixels[(z - 1)*cubicmap.width + x].g == 0) && - (cubicmapPixels[(z - 1)*cubicmap.width + x].b == 0)) || (z == 0)) - { - // Define back triangles (2 tris, 6 vertex) --> v1 v5 v6, v1 v4 v5 - // NOTE: Collateral occluded faces are not generated - mapVertices[vCounter] = v1; - mapVertices[vCounter + 1] = v5; - mapVertices[vCounter + 2] = v6; - mapVertices[vCounter + 3] = v1; - mapVertices[vCounter + 4] = v4; - mapVertices[vCounter + 5] = v5; - vCounter += 6; - - mapNormals[nCounter] = n5; - mapNormals[nCounter + 1] = n5; - mapNormals[nCounter + 2] = n5; - mapNormals[nCounter + 3] = n5; - mapNormals[nCounter + 4] = n5; - mapNormals[nCounter + 5] = n5; - nCounter += 6; - - mapTexcoords[tcCounter] = (Vector2){ backTexUV.x + backTexUV.width, backTexUV.y }; - mapTexcoords[tcCounter + 1] = (Vector2){ backTexUV.x, backTexUV.y + backTexUV.height }; - mapTexcoords[tcCounter + 2] = (Vector2){ backTexUV.x + backTexUV.width, backTexUV.y + backTexUV.height }; - mapTexcoords[tcCounter + 3] = (Vector2){ backTexUV.x + backTexUV.width, backTexUV.y }; - mapTexcoords[tcCounter + 4] = (Vector2){ backTexUV.x, backTexUV.y }; - mapTexcoords[tcCounter + 5] = (Vector2){ backTexUV.x, backTexUV.y + backTexUV.height }; - tcCounter += 6; - } - - if (((x < cubicmap.width - 1) && - (cubicmapPixels[z*cubicmap.width + (x + 1)].r == 0) && - (cubicmapPixels[z*cubicmap.width + (x + 1)].g == 0) && - (cubicmapPixels[z*cubicmap.width + (x + 1)].b == 0)) || (x == cubicmap.width - 1)) - { - // Define right triangles (2 tris, 6 vertex) --> v3 v8 v4, v4 v8 v5 - // NOTE: Collateral occluded faces are not generated - mapVertices[vCounter] = v3; - mapVertices[vCounter + 1] = v8; - mapVertices[vCounter + 2] = v4; - mapVertices[vCounter + 3] = v4; - mapVertices[vCounter + 4] = v8; - mapVertices[vCounter + 5] = v5; - vCounter += 6; - - mapNormals[nCounter] = n1; - mapNormals[nCounter + 1] = n1; - mapNormals[nCounter + 2] = n1; - mapNormals[nCounter + 3] = n1; - mapNormals[nCounter + 4] = n1; - mapNormals[nCounter + 5] = n1; - nCounter += 6; - - mapTexcoords[tcCounter] = (Vector2){ rightTexUV.x, rightTexUV.y }; - mapTexcoords[tcCounter + 1] = (Vector2){ rightTexUV.x, rightTexUV.y + rightTexUV.height }; - mapTexcoords[tcCounter + 2] = (Vector2){ rightTexUV.x + rightTexUV.width, rightTexUV.y }; - mapTexcoords[tcCounter + 3] = (Vector2){ rightTexUV.x + rightTexUV.width, rightTexUV.y }; - mapTexcoords[tcCounter + 4] = (Vector2){ rightTexUV.x, rightTexUV.y + rightTexUV.height }; - mapTexcoords[tcCounter + 5] = (Vector2){ rightTexUV.x + rightTexUV.width, rightTexUV.y + rightTexUV.height }; - tcCounter += 6; - } - - if (((x > 0) && - (cubicmapPixels[z*cubicmap.width + (x - 1)].r == 0) && - (cubicmapPixels[z*cubicmap.width + (x - 1)].g == 0) && - (cubicmapPixels[z*cubicmap.width + (x - 1)].b == 0)) || (x == 0)) - { - // Define left triangles (2 tris, 6 vertex) --> v1 v7 v2, v1 v6 v7 - // NOTE: Collateral occluded faces are not generated - mapVertices[vCounter] = v1; - mapVertices[vCounter + 1] = v7; - mapVertices[vCounter + 2] = v2; - mapVertices[vCounter + 3] = v1; - mapVertices[vCounter + 4] = v6; - mapVertices[vCounter + 5] = v7; - vCounter += 6; - - mapNormals[nCounter] = n2; - mapNormals[nCounter + 1] = n2; - mapNormals[nCounter + 2] = n2; - mapNormals[nCounter + 3] = n2; - mapNormals[nCounter + 4] = n2; - mapNormals[nCounter + 5] = n2; - nCounter += 6; - - mapTexcoords[tcCounter] = (Vector2){ leftTexUV.x, leftTexUV.y }; - mapTexcoords[tcCounter + 1] = (Vector2){ leftTexUV.x + leftTexUV.width, leftTexUV.y + leftTexUV.height }; - mapTexcoords[tcCounter + 2] = (Vector2){ leftTexUV.x + leftTexUV.width, leftTexUV.y }; - mapTexcoords[tcCounter + 3] = (Vector2){ leftTexUV.x, leftTexUV.y }; - mapTexcoords[tcCounter + 4] = (Vector2){ leftTexUV.x, leftTexUV.y + leftTexUV.height }; - mapTexcoords[tcCounter + 5] = (Vector2){ leftTexUV.x + leftTexUV.width, leftTexUV.y + leftTexUV.height }; - tcCounter += 6; - } - } - // We check pixel color to be BLACK, we will only draw floor and roof - else if ((cubicmapPixels[z*cubicmap.width + x].r == 0) && - (cubicmapPixels[z*cubicmap.width + x].g == 0) && - (cubicmapPixels[z*cubicmap.width + x].b == 0)) - { - // Define top triangles (2 tris, 6 vertex --> v1-v2-v3, v1-v3-v4) - mapVertices[vCounter] = v1; - mapVertices[vCounter + 1] = v3; - mapVertices[vCounter + 2] = v2; - mapVertices[vCounter + 3] = v1; - mapVertices[vCounter + 4] = v4; - mapVertices[vCounter + 5] = v3; - vCounter += 6; - - mapNormals[nCounter] = n4; - mapNormals[nCounter + 1] = n4; - mapNormals[nCounter + 2] = n4; - mapNormals[nCounter + 3] = n4; - mapNormals[nCounter + 4] = n4; - mapNormals[nCounter + 5] = n4; - nCounter += 6; - - mapTexcoords[tcCounter] = (Vector2){ topTexUV.x, topTexUV.y }; - mapTexcoords[tcCounter + 1] = (Vector2){ topTexUV.x + topTexUV.width, topTexUV.y + topTexUV.height }; - mapTexcoords[tcCounter + 2] = (Vector2){ topTexUV.x, topTexUV.y + topTexUV.height }; - mapTexcoords[tcCounter + 3] = (Vector2){ topTexUV.x, topTexUV.y }; - mapTexcoords[tcCounter + 4] = (Vector2){ topTexUV.x + topTexUV.width, topTexUV.y }; - mapTexcoords[tcCounter + 5] = (Vector2){ topTexUV.x + topTexUV.width, topTexUV.y + topTexUV.height }; - tcCounter += 6; - - // Define bottom triangles (2 tris, 6 vertex --> v6-v8-v7, v6-v5-v8) - mapVertices[vCounter] = v6; - mapVertices[vCounter + 1] = v7; - mapVertices[vCounter + 2] = v8; - mapVertices[vCounter + 3] = v6; - mapVertices[vCounter + 4] = v8; - mapVertices[vCounter + 5] = v5; - vCounter += 6; - - mapNormals[nCounter] = n3; - mapNormals[nCounter + 1] = n3; - mapNormals[nCounter + 2] = n3; - mapNormals[nCounter + 3] = n3; - mapNormals[nCounter + 4] = n3; - mapNormals[nCounter + 5] = n3; - nCounter += 6; - - mapTexcoords[tcCounter] = (Vector2){ bottomTexUV.x + bottomTexUV.width, bottomTexUV.y }; - mapTexcoords[tcCounter + 1] = (Vector2){ bottomTexUV.x + bottomTexUV.width, bottomTexUV.y + bottomTexUV.height }; - mapTexcoords[tcCounter + 2] = (Vector2){ bottomTexUV.x, bottomTexUV.y + bottomTexUV.height }; - mapTexcoords[tcCounter + 3] = (Vector2){ bottomTexUV.x + bottomTexUV.width, bottomTexUV.y }; - mapTexcoords[tcCounter + 4] = (Vector2){ bottomTexUV.x, bottomTexUV.y + bottomTexUV.height }; - mapTexcoords[tcCounter + 5] = (Vector2){ bottomTexUV.x, bottomTexUV.y }; - tcCounter += 6; - } - } - } - - // Move data from mapVertices temp arays to vertices float array - mesh.vertexCount = vCounter; - - mesh.vertices = (float *)malloc(mesh.vertexCount*3*sizeof(float)); - mesh.normals = (float *)malloc(mesh.vertexCount*3*sizeof(float)); - mesh.texcoords = (float *)malloc(mesh.vertexCount*2*sizeof(float)); - mesh.colors = NULL; - - int fCounter = 0; - - // Move vertices data - for (int i = 0; i < vCounter; i++) - { - mesh.vertices[fCounter] = mapVertices[i].x; - mesh.vertices[fCounter + 1] = mapVertices[i].y; - mesh.vertices[fCounter + 2] = mapVertices[i].z; - fCounter += 3; - } - - fCounter = 0; - - // Move normals data - for (int i = 0; i < nCounter; i++) - { - mesh.normals[fCounter] = mapNormals[i].x; - mesh.normals[fCounter + 1] = mapNormals[i].y; - mesh.normals[fCounter + 2] = mapNormals[i].z; - fCounter += 3; - } - - fCounter = 0; - - // Move texcoords data - for (int i = 0; i < tcCounter; i++) - { - mesh.texcoords[fCounter] = mapTexcoords[i].x; - mesh.texcoords[fCounter + 1] = mapTexcoords[i].y; - fCounter += 2; - } - - free(mapVertices); - free(mapNormals); - free(mapTexcoords); - - free(cubicmapPixels); // Free image pixel data - - // Upload vertex data to GPU (static mesh) - rlLoadMesh(&mesh, false); - - return mesh; -} -#endif // SUPPORT_MESH_GENERATION - -// Load material data (from file) -Material LoadMaterial(const char *fileName) -{ - Material material = { 0 }; - -#if defined(SUPPORT_FILEFORMAT_MTL) - if (IsFileExtension(fileName, ".mtl")) material = LoadMTL(fileName); -#else - TraceLog(LOG_WARNING, "[%s] Material fileformat not supported, it can't be loaded", fileName); -#endif - - // Our material uses the default shader (DIFFUSE, SPECULAR, NORMAL) - material.shader = GetShaderDefault(); - - return material; -} - -// Load default material (Supports: DIFFUSE, SPECULAR, NORMAL maps) -Material LoadMaterialDefault(void) -{ - Material material = { 0 }; - - material.shader = GetShaderDefault(); - material.maps[MAP_DIFFUSE].texture = GetTextureDefault(); // White texture (1x1 pixel) - //material.maps[MAP_NORMAL].texture; // NOTE: By default, not set - //material.maps[MAP_SPECULAR].texture; // NOTE: By default, not set - - material.maps[MAP_DIFFUSE].color = WHITE; // Diffuse color - material.maps[MAP_SPECULAR].color = WHITE; // Specular color - - return material; -} - -// Unload material from memory -void UnloadMaterial(Material material) -{ - // Unload material shader - UnloadShader(material.shader); - - // Unload loaded texture maps - for (int i = 0; i < MAX_MATERIAL_MAPS; i++) - { - // NOTE: We already check for (tex.id > 0) inside function - rlDeleteTextures(material.maps[i].texture.id); - } -} - -// Draw a model (with texture if set) -void DrawModel(Model model, Vector3 position, float scale, Color tint) -{ - Vector3 vScale = { scale, scale, scale }; - Vector3 rotationAxis = { 0.0f, 0.0f, 0.0f }; - - DrawModelEx(model, position, rotationAxis, 0.0f, vScale, tint); -} - -// Draw a model with extended parameters -void DrawModelEx(Model model, Vector3 position, Vector3 rotationAxis, float rotationAngle, Vector3 scale, Color tint) -{ - // Calculate transformation matrix from function parameters - // Get transform matrix (rotation -> scale -> translation) - Matrix matScale = MatrixScale(scale.x, scale.y, scale.z); - Matrix matRotation = MatrixRotate(rotationAxis, rotationAngle*DEG2RAD); - Matrix matTranslation = MatrixTranslate(position.x, position.y, position.z); - - Matrix matTransform = MatrixMultiply(MatrixMultiply(matScale, matRotation), matTranslation); - - // Combine model transformation matrix (model.transform) with matrix generated by function parameters (matTransform) - //Matrix matModel = MatrixMultiply(model.transform, matTransform); // Transform to world-space coordinates - - model.transform = MatrixMultiply(model.transform, matTransform); - model.material.maps[MAP_DIFFUSE].color = tint; // TODO: Multiply tint color by diffuse color? - - rlDrawMesh(model.mesh, model.material, model.transform); -} - -// Draw a model wires (with texture if set) -void DrawModelWires(Model model, Vector3 position, float scale, Color tint) -{ - rlEnableWireMode(); - - DrawModel(model, position, scale, tint); - - rlDisableWireMode(); -} - -// Draw a model wires (with texture if set) with extended parameters -void DrawModelWiresEx(Model model, Vector3 position, Vector3 rotationAxis, float rotationAngle, Vector3 scale, Color tint) -{ - rlEnableWireMode(); - - DrawModelEx(model, position, rotationAxis, rotationAngle, scale, tint); - - rlDisableWireMode(); -} - -// Draw a billboard -void DrawBillboard(Camera camera, Texture2D texture, Vector3 center, float size, Color tint) -{ - Rectangle sourceRec = { 0, 0, texture.width, texture.height }; - - DrawBillboardRec(camera, texture, sourceRec, center, size, tint); -} - -// Draw a billboard (part of a texture defined by a rectangle) -void DrawBillboardRec(Camera camera, Texture2D texture, Rectangle sourceRec, Vector3 center, float size, Color tint) -{ - // NOTE: Billboard size will maintain sourceRec aspect ratio, size will represent billboard width - Vector2 sizeRatio = { size, size*(float)sourceRec.height/sourceRec.width }; - - Matrix matView = MatrixLookAt(camera.position, camera.target, camera.up); - - Vector3 right = { matView.m0, matView.m4, matView.m8 }; - //Vector3 up = { matView.m1, matView.m5, matView.m9 }; - - // NOTE: Billboard locked on axis-Y - Vector3 up = { 0.0f, 1.0f, 0.0f }; -/* - a-------b - | | - | * | - | | - d-------c -*/ - Vector3Scale(&right, sizeRatio.x/2); - Vector3Scale(&up, sizeRatio.y/2); - - Vector3 p1 = Vector3Add(right, up); - Vector3 p2 = Vector3Subtract(right, up); - - Vector3 a = Vector3Subtract(center, p2); - Vector3 b = Vector3Add(center, p1); - Vector3 c = Vector3Add(center, p2); - Vector3 d = Vector3Subtract(center, p1); - - rlEnableTexture(texture.id); - - rlBegin(RL_QUADS); - rlColor4ub(tint.r, tint.g, tint.b, tint.a); - - // Bottom-left corner for texture and quad - rlTexCoord2f((float)sourceRec.x/texture.width, (float)sourceRec.y/texture.height); - rlVertex3f(a.x, a.y, a.z); - - // Top-left corner for texture and quad - rlTexCoord2f((float)sourceRec.x/texture.width, (float)(sourceRec.y + sourceRec.height)/texture.height); - rlVertex3f(d.x, d.y, d.z); - - // Top-right corner for texture and quad - rlTexCoord2f((float)(sourceRec.x + sourceRec.width)/texture.width, (float)(sourceRec.y + sourceRec.height)/texture.height); - rlVertex3f(c.x, c.y, c.z); - - // Bottom-right corner for texture and quad - rlTexCoord2f((float)(sourceRec.x + sourceRec.width)/texture.width, (float)sourceRec.y/texture.height); - rlVertex3f(b.x, b.y, b.z); - rlEnd(); - - rlDisableTexture(); -} - -// Draw a bounding box with wires -void DrawBoundingBox(BoundingBox box, Color color) -{ - Vector3 size; - - size.x = fabsf(box.max.x - box.min.x); - size.y = fabsf(box.max.y - box.min.y); - size.z = fabsf(box.max.z - box.min.z); - - Vector3 center = { box.min.x + size.x/2.0f, box.min.y + size.y/2.0f, box.min.z + size.z/2.0f }; - - DrawCubeWires(center, size.x, size.y, size.z, color); -} - -// Detect collision between two spheres -bool CheckCollisionSpheres(Vector3 centerA, float radiusA, Vector3 centerB, float radiusB) -{ - bool collision = false; - - float dx = centerA.x - centerB.x; // X distance between centers - float dy = centerA.y - centerB.y; // Y distance between centers - float dz = centerA.z - centerB.z; // Y distance between centers - - float distance = sqrtf(dx*dx + dy*dy + dz*dz); // Distance between centers - - if (distance <= (radiusA + radiusB)) collision = true; - - return collision; -} - -// Detect collision between two boxes -// NOTE: Boxes are defined by two points minimum and maximum -bool CheckCollisionBoxes(BoundingBox box1, BoundingBox box2) -{ - bool collision = true; - - if ((box1.max.x >= box2.min.x) && (box1.min.x <= box2.max.x)) - { - if ((box1.max.y < box2.min.y) || (box1.min.y > box2.max.y)) collision = false; - if ((box1.max.z < box2.min.z) || (box1.min.z > box2.max.z)) collision = false; - } - else collision = false; - - return collision; -} - -// Detect collision between box and sphere -bool CheckCollisionBoxSphere(BoundingBox box, Vector3 centerSphere, float radiusSphere) -{ - bool collision = false; - - float dmin = 0; - - if (centerSphere.x < box.min.x) dmin += powf(centerSphere.x - box.min.x, 2); - else if (centerSphere.x > box.max.x) dmin += powf(centerSphere.x - box.max.x, 2); - - if (centerSphere.y < box.min.y) dmin += powf(centerSphere.y - box.min.y, 2); - else if (centerSphere.y > box.max.y) dmin += powf(centerSphere.y - box.max.y, 2); - - if (centerSphere.z < box.min.z) dmin += powf(centerSphere.z - box.min.z, 2); - else if (centerSphere.z > box.max.z) dmin += powf(centerSphere.z - box.max.z, 2); - - if (dmin <= (radiusSphere*radiusSphere)) collision = true; - - return collision; -} - -// Detect collision between ray and sphere -bool CheckCollisionRaySphere(Ray ray, Vector3 spherePosition, float sphereRadius) -{ - bool collision = false; - - Vector3 raySpherePos = Vector3Subtract(spherePosition, ray.position); - float distance = Vector3Length(raySpherePos); - float vector = Vector3DotProduct(raySpherePos, ray.direction); - float d = sphereRadius*sphereRadius - (distance*distance - vector*vector); - - if (d >= 0.0f) collision = true; - - return collision; -} - -// Detect collision between ray and sphere with extended parameters and collision point detection -bool CheckCollisionRaySphereEx(Ray ray, Vector3 spherePosition, float sphereRadius, Vector3 *collisionPoint) -{ - bool collision = false; - - Vector3 raySpherePos = Vector3Subtract(spherePosition, ray.position); - float distance = Vector3Length(raySpherePos); - float vector = Vector3DotProduct(raySpherePos, ray.direction); - float d = sphereRadius*sphereRadius - (distance*distance - vector*vector); - - if (d >= 0.0f) collision = true; - - // Calculate collision point - Vector3 offset = ray.direction; - float collisionDistance = 0; - - // Check if ray origin is inside the sphere to calculate the correct collision point - if (distance < sphereRadius) collisionDistance = vector + sqrtf(d); - else collisionDistance = vector - sqrtf(d); - - Vector3Scale(&offset, collisionDistance); - Vector3 cPoint = Vector3Add(ray.position, offset); - - collisionPoint->x = cPoint.x; - collisionPoint->y = cPoint.y; - collisionPoint->z = cPoint.z; - - return collision; -} - -// Detect collision between ray and bounding box -bool CheckCollisionRayBox(Ray ray, BoundingBox box) -{ - bool collision = false; - - float t[8]; - t[0] = (box.min.x - ray.position.x)/ray.direction.x; - t[1] = (box.max.x - ray.position.x)/ray.direction.x; - t[2] = (box.min.y - ray.position.y)/ray.direction.y; - t[3] = (box.max.y - ray.position.y)/ray.direction.y; - t[4] = (box.min.z - ray.position.z)/ray.direction.z; - t[5] = (box.max.z - ray.position.z)/ray.direction.z; - t[6] = (float)fmax(fmax(fmin(t[0], t[1]), fmin(t[2], t[3])), fmin(t[4], t[5])); - t[7] = (float)fmin(fmin(fmax(t[0], t[1]), fmax(t[2], t[3])), fmax(t[4], t[5])); - - collision = !(t[7] < 0 || t[6] > t[7]); - - return collision; -} - -// Get collision info between ray and mesh -RayHitInfo GetCollisionRayMesh(Ray ray, Mesh *mesh) -{ - RayHitInfo result = { 0 }; - - // If mesh doesn't have vertex data on CPU, can't test it. - if (!mesh->vertices) return result; - - // mesh->triangleCount may not be set, vertexCount is more reliable - int triangleCount = mesh->vertexCount/3; - - // Test against all triangles in mesh - for (int i = 0; i < triangleCount; i++) - { - Vector3 a, b, c; - Vector3 *vertdata = (Vector3 *)mesh->vertices; - - if (mesh->indices) - { - a = vertdata[mesh->indices[i*3 + 0]]; - b = vertdata[mesh->indices[i*3 + 1]]; - c = vertdata[mesh->indices[i*3 + 2]]; - } - else - { - a = vertdata[i*3 + 0]; - b = vertdata[i*3 + 1]; - c = vertdata[i*3 + 2]; - } - - RayHitInfo triHitInfo = GetCollisionRayTriangle(ray, a, b, c); - - if (triHitInfo.hit) - { - // Save the closest hit triangle - if ((!result.hit) || (result.distance > triHitInfo.distance)) result = triHitInfo; - } - } - - return result; -} - -// Get collision info between ray and triangle -// NOTE: Based on https://en.wikipedia.org/wiki/M%C3%B6ller%E2%80%93Trumbore_intersection_algorithm -RayHitInfo GetCollisionRayTriangle(Ray ray, Vector3 p1, Vector3 p2, Vector3 p3) -{ - #define EPSILON 0.000001 // A small number - - Vector3 edge1, edge2; - Vector3 p, q, tv; - float det, invDet, u, v, t; - RayHitInfo result = {0}; - - // Find vectors for two edges sharing V1 - edge1 = Vector3Subtract(p2, p1); - edge2 = Vector3Subtract(p3, p1); - - // Begin calculating determinant - also used to calculate u parameter - p = Vector3CrossProduct(ray.direction, edge2); - - // If determinant is near zero, ray lies in plane of triangle or ray is parallel to plane of triangle - det = Vector3DotProduct(edge1, p); - - // Avoid culling! - if ((det > -EPSILON) && (det < EPSILON)) return result; - - invDet = 1.0f/det; - - // Calculate distance from V1 to ray origin - tv = Vector3Subtract(ray.position, p1); - - // Calculate u parameter and test bound - u = Vector3DotProduct(tv, p)*invDet; - - // The intersection lies outside of the triangle - if ((u < 0.0f) || (u > 1.0f)) return result; - - // Prepare to test v parameter - q = Vector3CrossProduct(tv, edge1); - - // Calculate V parameter and test bound - v = Vector3DotProduct(ray.direction, q)*invDet; - - // The intersection lies outside of the triangle - if ((v < 0.0f) || ((u + v) > 1.0f)) return result; - - t = Vector3DotProduct(edge2, q)*invDet; - - if (t > EPSILON) - { - // Ray hit, get hit point and normal - result.hit = true; - result.distance = t; - result.hit = true; - result.normal = Vector3CrossProduct(edge1, edge2); - Vector3Normalize(&result.normal); - Vector3 rayDir = ray.direction; - Vector3Scale(&rayDir, t); - result.position = Vector3Add(ray.position, rayDir); - } - - return result; -} - -// Get collision info between ray and ground plane (Y-normal plane) -RayHitInfo GetCollisionRayGround(Ray ray, float groundHeight) -{ - #define EPSILON 0.000001 // A small number - - RayHitInfo result = { 0 }; - - if (fabsf(ray.direction.y) > EPSILON) - { - float t = (ray.position.y - groundHeight)/-ray.direction.y; - - if (t >= 0.0) - { - Vector3 rayDir = ray.direction; - Vector3Scale(&rayDir, t); - result.hit = true; - result.distance = t; - result.normal = (Vector3){ 0.0, 1.0, 0.0 }; - result.position = Vector3Add(ray.position, rayDir); - } - } - - return result; -} - -// Calculate mesh bounding box limits -// NOTE: minVertex and maxVertex should be transformed by model transform matrix -BoundingBox CalculateBoundingBox(Mesh mesh) -{ - // Get min and max vertex to construct bounds (AABB) - Vector3 minVertex = { 0 }; - Vector3 maxVertex = { 0 }; - - if (mesh.vertices != NULL) - { - minVertex = (Vector3){ mesh.vertices[0], mesh.vertices[1], mesh.vertices[2] }; - maxVertex = (Vector3){ mesh.vertices[0], mesh.vertices[1], mesh.vertices[2] }; - - for (int i = 1; i < mesh.vertexCount; i++) - { - minVertex = Vector3Min(minVertex, (Vector3){ mesh.vertices[i*3], mesh.vertices[i*3 + 1], mesh.vertices[i*3 + 2] }); - maxVertex = Vector3Max(maxVertex, (Vector3){ mesh.vertices[i*3], mesh.vertices[i*3 + 1], mesh.vertices[i*3 + 2] }); - } - } - - // Create the bounding box - BoundingBox box; - box.min = minVertex; - box.max = maxVertex; - - return box; -} - -//---------------------------------------------------------------------------------- -// Module specific Functions Definition -//---------------------------------------------------------------------------------- - -#if defined(SUPPORT_FILEFORMAT_OBJ) -// Load OBJ mesh data -static Mesh LoadOBJ(const char *fileName) -{ - Mesh mesh = { 0 }; - - char dataType; - char comments[200]; - - int vertexCount = 0; - int normalCount = 0; - int texcoordCount = 0; - int triangleCount = 0; - - FILE *objFile; - - objFile = fopen(fileName, "rt"); - - if (objFile == NULL) - { - TraceLog(LOG_WARNING, "[%s] OBJ file could not be opened", fileName); - return mesh; - } - - // First reading pass: Get vertexCount, normalCount, texcoordCount, triangleCount - // NOTE: vertex, texcoords and normals could be optimized (to be used indexed on faces definition) - // NOTE: faces MUST be defined as TRIANGLES (3 vertex per face) - while (!feof(objFile)) - { - dataType = '\0'; - fscanf(objFile, "%c", &dataType); - - switch (dataType) - { - case '#': // Comments - case 'o': // Object name (One OBJ file can contain multible named meshes) - case 'g': // Group name - case 's': // Smoothing level - case 'm': // mtllib [external .mtl file name] - case 'u': // usemtl [material name] - { - fgets(comments, 200, objFile); - } break; - case 'v': - { - fscanf(objFile, "%c", &dataType); - - if (dataType == 't') // Read texCoord - { - texcoordCount++; - fgets(comments, 200, objFile); - } - else if (dataType == 'n') // Read normals - { - normalCount++; - fgets(comments, 200, objFile); - } - else // Read vertex - { - vertexCount++; - fgets(comments, 200, objFile); - } - } break; - case 'f': - { - triangleCount++; - fgets(comments, 200, objFile); - } break; - default: break; - } - } - - TraceLog(LOG_DEBUG, "[%s] Model vertices: %i", fileName, vertexCount); - TraceLog(LOG_DEBUG, "[%s] Model texcoords: %i", fileName, texcoordCount); - TraceLog(LOG_DEBUG, "[%s] Model normals: %i", fileName, normalCount); - TraceLog(LOG_DEBUG, "[%s] Model triangles: %i", fileName, triangleCount); - - // Once we know the number of vertices to store, we create required arrays - Vector3 *midVertices = (Vector3 *)malloc(vertexCount*sizeof(Vector3)); - Vector3 *midNormals = NULL; - if (normalCount > 0) midNormals = (Vector3 *)malloc(normalCount*sizeof(Vector3)); - Vector2 *midTexCoords = NULL; - if (texcoordCount > 0) midTexCoords = (Vector2 *)malloc(texcoordCount*sizeof(Vector2)); - - int countVertex = 0; - int countNormals = 0; - int countTexCoords = 0; - - rewind(objFile); // Return to the beginning of the file, to read again - - // Second reading pass: Get vertex data to fill intermediate arrays - // NOTE: This second pass is required in case of multiple meshes defined in same OBJ - // TODO: Consider that different meshes can have different vertex data available (position, texcoords, normals) - while (!feof(objFile)) - { - fscanf(objFile, "%c", &dataType); - - switch (dataType) - { - case '#': case 'o': case 'g': case 's': case 'm': case 'u': case 'f': fgets(comments, 200, objFile); break; - case 'v': - { - fscanf(objFile, "%c", &dataType); - - if (dataType == 't') // Read texCoord - { - fscanf(objFile, "%f %f%*[^\n]s\n", &midTexCoords[countTexCoords].x, &midTexCoords[countTexCoords].y); - countTexCoords++; - - fscanf(objFile, "%c", &dataType); - } - else if (dataType == 'n') // Read normals - { - fscanf(objFile, "%f %f %f", &midNormals[countNormals].x, &midNormals[countNormals].y, &midNormals[countNormals].z); - countNormals++; - - fscanf(objFile, "%c", &dataType); - } - else // Read vertex - { - fscanf(objFile, "%f %f %f", &midVertices[countVertex].x, &midVertices[countVertex].y, &midVertices[countVertex].z); - countVertex++; - - fscanf(objFile, "%c", &dataType); - } - } break; - default: break; - } - } - - // At this point all vertex data (v, vt, vn) has been gathered on midVertices, midTexCoords, midNormals - // Now we can organize that data into our Mesh struct - - mesh.vertexCount = triangleCount*3; - - // Additional arrays to store vertex data as floats - mesh.vertices = (float *)malloc(mesh.vertexCount*3*sizeof(float)); - mesh.texcoords = (float *)malloc(mesh.vertexCount*2*sizeof(float)); - mesh.normals = (float *)malloc(mesh.vertexCount*3*sizeof(float)); - mesh.colors = NULL; - - int vCounter = 0; // Used to count vertices float by float - int tcCounter = 0; // Used to count texcoords float by float - int nCounter = 0; // Used to count normals float by float - - int vCount[3], vtCount[3], vnCount[3]; // Used to store triangle indices for v, vt, vn - - rewind(objFile); // Return to the beginning of the file, to read again - - if (normalCount == 0) TraceLog(LOG_INFO, "[%s] No normals data on OBJ, normals will be generated from faces data", fileName); - - // Third reading pass: Get faces (triangles) data and fill VertexArray - while (!feof(objFile)) - { - fscanf(objFile, "%c", &dataType); - - switch (dataType) - { - case '#': case 'o': case 'g': case 's': case 'm': case 'u': case 'v': fgets(comments, 200, objFile); break; - case 'f': - { - // NOTE: It could be that OBJ does not have normals or texcoords defined! - - if ((normalCount == 0) && (texcoordCount == 0)) fscanf(objFile, "%i %i %i", &vCount[0], &vCount[1], &vCount[2]); - else if (normalCount == 0) fscanf(objFile, "%i/%i %i/%i %i/%i", &vCount[0], &vtCount[0], &vCount[1], &vtCount[1], &vCount[2], &vtCount[2]); - else if (texcoordCount == 0) fscanf(objFile, "%i//%i %i//%i %i//%i", &vCount[0], &vnCount[0], &vCount[1], &vnCount[1], &vCount[2], &vnCount[2]); - else fscanf(objFile, "%i/%i/%i %i/%i/%i %i/%i/%i", &vCount[0], &vtCount[0], &vnCount[0], &vCount[1], &vtCount[1], &vnCount[1], &vCount[2], &vtCount[2], &vnCount[2]); - - mesh.vertices[vCounter] = midVertices[vCount[0]-1].x; - mesh.vertices[vCounter + 1] = midVertices[vCount[0]-1].y; - mesh.vertices[vCounter + 2] = midVertices[vCount[0]-1].z; - vCounter += 3; - mesh.vertices[vCounter] = midVertices[vCount[1]-1].x; - mesh.vertices[vCounter + 1] = midVertices[vCount[1]-1].y; - mesh.vertices[vCounter + 2] = midVertices[vCount[1]-1].z; - vCounter += 3; - mesh.vertices[vCounter] = midVertices[vCount[2]-1].x; - mesh.vertices[vCounter + 1] = midVertices[vCount[2]-1].y; - mesh.vertices[vCounter + 2] = midVertices[vCount[2]-1].z; - vCounter += 3; - - if (normalCount > 0) - { - mesh.normals[nCounter] = midNormals[vnCount[0]-1].x; - mesh.normals[nCounter + 1] = midNormals[vnCount[0]-1].y; - mesh.normals[nCounter + 2] = midNormals[vnCount[0]-1].z; - nCounter += 3; - mesh.normals[nCounter] = midNormals[vnCount[1]-1].x; - mesh.normals[nCounter + 1] = midNormals[vnCount[1]-1].y; - mesh.normals[nCounter + 2] = midNormals[vnCount[1]-1].z; - nCounter += 3; - mesh.normals[nCounter] = midNormals[vnCount[2]-1].x; - mesh.normals[nCounter + 1] = midNormals[vnCount[2]-1].y; - mesh.normals[nCounter + 2] = midNormals[vnCount[2]-1].z; - nCounter += 3; - } - else - { - // If normals not defined, they are calculated from the 3 vertices [N = (V2 - V1) x (V3 - V1)] - Vector3 norm = Vector3CrossProduct(Vector3Subtract(midVertices[vCount[1]-1], midVertices[vCount[0]-1]), Vector3Subtract(midVertices[vCount[2]-1], midVertices[vCount[0]-1])); - Vector3Normalize(&norm); - - mesh.normals[nCounter] = norm.x; - mesh.normals[nCounter + 1] = norm.y; - mesh.normals[nCounter + 2] = norm.z; - nCounter += 3; - mesh.normals[nCounter] = norm.x; - mesh.normals[nCounter + 1] = norm.y; - mesh.normals[nCounter + 2] = norm.z; - nCounter += 3; - mesh.normals[nCounter] = norm.x; - mesh.normals[nCounter + 1] = norm.y; - mesh.normals[nCounter + 2] = norm.z; - nCounter += 3; - } - - if (texcoordCount > 0) - { - // NOTE: If using negative texture coordinates with a texture filter of GL_CLAMP_TO_EDGE doesn't work! - // NOTE: Texture coordinates are Y flipped upside-down - mesh.texcoords[tcCounter] = midTexCoords[vtCount[0]-1].x; - mesh.texcoords[tcCounter + 1] = 1.0f - midTexCoords[vtCount[0]-1].y; - tcCounter += 2; - mesh.texcoords[tcCounter] = midTexCoords[vtCount[1]-1].x; - mesh.texcoords[tcCounter + 1] = 1.0f - midTexCoords[vtCount[1]-1].y; - tcCounter += 2; - mesh.texcoords[tcCounter] = midTexCoords[vtCount[2]-1].x; - mesh.texcoords[tcCounter + 1] = 1.0f - midTexCoords[vtCount[2]-1].y; - tcCounter += 2; - } - } break; - default: break; - } - } - - fclose(objFile); - - // Security check, just in case no normals or no texcoords defined in OBJ - if (texcoordCount == 0) for (int i = 0; i < (2*mesh.vertexCount); i++) mesh.texcoords[i] = 0.0f; - else - { - // Attempt to calculate mesh tangents and binormals using positions and texture coordinates - mesh.tangents = (float *)malloc(mesh.vertexCount*3*sizeof(float)); - // mesh.binormals = (float *)malloc(mesh.vertexCount*3*sizeof(float)); - - int vCount = 0; - int uvCount = 0; - while (vCount < mesh.vertexCount*3) - { - // Calculate mesh vertex positions as Vector3 - Vector3 v0 = { mesh.vertices[vCount], mesh.vertices[vCount + 1], mesh.vertices[vCount + 2] }; - Vector3 v1 = { mesh.vertices[vCount + 3], mesh.vertices[vCount + 4], mesh.vertices[vCount + 5] }; - Vector3 v2 = { mesh.vertices[vCount + 6], mesh.vertices[vCount + 7], mesh.vertices[vCount + 8] }; - - // Calculate mesh texture coordinates as Vector2 - Vector2 uv0 = { mesh.texcoords[uvCount + 0], mesh.texcoords[uvCount + 1] }; - Vector2 uv1 = { mesh.texcoords[uvCount + 2], mesh.texcoords[uvCount + 3] }; - Vector2 uv2 = { mesh.texcoords[uvCount + 4], mesh.texcoords[uvCount + 5] }; - - // Calculate edges of the triangle (position delta) - Vector3 deltaPos1 = Vector3Subtract(v1, v0); - Vector3 deltaPos2 = Vector3Subtract(v2, v0); - - // UV delta - Vector2 deltaUV1 = { uv1.x - uv0.x, uv1.y - uv0.y }; - Vector2 deltaUV2 = { uv2.x - uv0.x, uv2.y - uv0.y }; - - float r = 1.0f/(deltaUV1.x*deltaUV2.y - deltaUV1.y*deltaUV2.x); - Vector3 t1 = { deltaPos1.x*deltaUV2.y, deltaPos1.y*deltaUV2.y, deltaPos1.z*deltaUV2.y }; - Vector3 t2 = { deltaPos2.x*deltaUV1.y, deltaPos2.y*deltaUV1.y, deltaPos2.z*deltaUV1.y }; - // Vector3 b1 = { deltaPos2.x*deltaUV1.x, deltaPos2.y*deltaUV1.x, deltaPos2.z*deltaUV1.x }; - // Vector3 b2 = { deltaPos1.x*deltaUV2.x, deltaPos1.y*deltaUV2.x, deltaPos1.z*deltaUV2.x }; - - // Calculate vertex tangent - Vector3 tangent = Vector3Subtract(t1, t2); - Vector3Scale(&tangent, r); - - // Apply calculated tangents data to mesh struct - mesh.tangents[vCount + 0] = tangent.x; - mesh.tangents[vCount + 1] = tangent.y; - mesh.tangents[vCount + 2] = tangent.z; - mesh.tangents[vCount + 3] = tangent.x; - mesh.tangents[vCount + 4] = tangent.y; - mesh.tangents[vCount + 5] = tangent.z; - mesh.tangents[vCount + 6] = tangent.x; - mesh.tangents[vCount + 7] = tangent.y; - mesh.tangents[vCount + 8] = tangent.z; - - // TODO: add binormals to mesh struct and assign buffers id and locations properly - /* // Calculate vertex binormal - Vector3 binormal = Vector3Subtract(b1, b2); - Vector3Scale(&binormal, r); - - // Apply calculated binormals data to mesh struct - mesh.binormals[vCount + 0] = binormal.x; - mesh.binormals[vCount + 1] = binormal.y; - mesh.binormals[vCount + 2] = binormal.z; - mesh.binormals[vCount + 3] = binormal.x; - mesh.binormals[vCount + 4] = binormal.y; - mesh.binormals[vCount + 5] = binormal.z; - mesh.binormals[vCount + 6] = binormal.x; - mesh.binormals[vCount + 7] = binormal.y; - mesh.binormals[vCount + 8] = binormal.z; */ - - // Update vertex position and texture coordinates counters - vCount += 9; - uvCount += 6; - } - } - - // Now we can free temp mid* arrays - free(midVertices); - free(midNormals); - free(midTexCoords); - - // NOTE: At this point we have all vertex, texcoord, normal data for the model in mesh struct - TraceLog(LOG_INFO, "[%s] Model loaded successfully in RAM (CPU)", fileName); - - return mesh; -} -#endif - -#if defined(SUPPORT_FILEFORMAT_MTL) -// Load MTL material data (specs: http://paulbourke.net/dataformats/mtl/) -// NOTE: Texture map parameters are not supported -static Material LoadMTL(const char *fileName) -{ - #define MAX_BUFFER_SIZE 128 - - Material material = { 0 }; - - char buffer[MAX_BUFFER_SIZE]; - Vector3 color = { 1.0f, 1.0f, 1.0f }; - char mapFileName[128]; - int result = 0; - - FILE *mtlFile; - - mtlFile = fopen(fileName, "rt"); - - if (mtlFile == NULL) - { - TraceLog(LOG_WARNING, "[%s] MTL file could not be opened", fileName); - return material; - } - - while (!feof(mtlFile)) - { - fgets(buffer, MAX_BUFFER_SIZE, mtlFile); - - switch (buffer[0]) - { - case 'n': // newmtl string Material name. Begins a new material description. - { - // TODO: Support multiple materials in a single .mtl - sscanf(buffer, "newmtl %s", mapFileName); - - TraceLog(LOG_INFO, "[%s] Loading material...", mapFileName); - } - case 'i': // illum int Illumination model - { - // illum = 1 if specular disabled - // illum = 2 if specular enabled (lambertian model) - // ... - } - case 'K': // Ka, Kd, Ks, Ke - { - switch (buffer[1]) - { - case 'a': // Ka float float float Ambient color (RGB) - { - sscanf(buffer, "Ka %f %f %f", &color.x, &color.y, &color.z); - // TODO: Support ambient color - //material.colAmbient.r = (unsigned char)(color.x*255); - //material.colAmbient.g = (unsigned char)(color.y*255); - //material.colAmbient.b = (unsigned char)(color.z*255); - } break; - case 'd': // Kd float float float Diffuse color (RGB) - { - sscanf(buffer, "Kd %f %f %f", &color.x, &color.y, &color.z); - material.maps[MAP_DIFFUSE].color.r = (unsigned char)(color.x*255); - material.maps[MAP_DIFFUSE].color.g = (unsigned char)(color.y*255); - material.maps[MAP_DIFFUSE].color.b = (unsigned char)(color.z*255); - } break; - case 's': // Ks float float float Specular color (RGB) - { - sscanf(buffer, "Ks %f %f %f", &color.x, &color.y, &color.z); - material.maps[MAP_SPECULAR].color.r = (unsigned char)(color.x*255); - material.maps[MAP_SPECULAR].color.g = (unsigned char)(color.y*255); - material.maps[MAP_SPECULAR].color.b = (unsigned char)(color.z*255); - } break; - case 'e': // Ke float float float Emmisive color (RGB) - { - // TODO: Support Ke ? - } break; - default: break; - } - } break; - case 'N': // Ns, Ni - { - if (buffer[1] == 's') // Ns int Shininess (specular exponent). Ranges from 0 to 1000. - { - int shininess = 0; - sscanf(buffer, "Ns %i", &shininess); - - //material.params[PARAM_GLOSSINES] = (float)shininess; - } - else if (buffer[1] == 'i') // Ni int Refraction index. - { - // Not supported... - } - } break; - case 'm': // map_Kd, map_Ks, map_Ka, map_Bump, map_d - { - switch (buffer[4]) - { - case 'K': // Color texture maps - { - if (buffer[5] == 'd') // map_Kd string Diffuse color texture map. - { - result = sscanf(buffer, "map_Kd %s", mapFileName); - if (result != EOF) material.maps[MAP_DIFFUSE].texture = LoadTexture(mapFileName); - } - else if (buffer[5] == 's') // map_Ks string Specular color texture map. - { - result = sscanf(buffer, "map_Ks %s", mapFileName); - if (result != EOF) material.maps[MAP_SPECULAR].texture = LoadTexture(mapFileName); - } - else if (buffer[5] == 'a') // map_Ka string Ambient color texture map. - { - // Not supported... - } - } break; - case 'B': // map_Bump string Bump texture map. - { - result = sscanf(buffer, "map_Bump %s", mapFileName); - if (result != EOF) material.maps[MAP_NORMAL].texture = LoadTexture(mapFileName); - } break; - case 'b': // map_bump string Bump texture map. - { - result = sscanf(buffer, "map_bump %s", mapFileName); - if (result != EOF) material.maps[MAP_NORMAL].texture = LoadTexture(mapFileName); - } break; - case 'd': // map_d string Opacity texture map. - { - // Not supported... - } break; - default: break; - } - } break; - case 'd': // d, disp - { - if (buffer[1] == ' ') // d float Dissolve factor. d is inverse of Tr - { - float alpha = 1.0f; - sscanf(buffer, "d %f", &alpha); - material.maps[MAP_DIFFUSE].color.a = (unsigned char)(alpha*255); - } - else if (buffer[1] == 'i') // disp string Displacement map - { - // Not supported... - } - } break; - case 'b': // bump string Bump texture map - { - result = sscanf(buffer, "bump %s", mapFileName); - if (result != EOF) material.maps[MAP_NORMAL].texture = LoadTexture(mapFileName); - } break; - case 'T': // Tr float Transparency Tr (alpha). Tr is inverse of d - { - float ialpha = 0.0f; - sscanf(buffer, "Tr %f", &ialpha); - material.maps[MAP_DIFFUSE].color.a = (unsigned char)((1.0f - ialpha)*255); - - } break; - case 'r': // refl string Reflection texture map - default: break; - } - } - - fclose(mtlFile); - - // NOTE: At this point we have all material data - TraceLog(LOG_INFO, "[%s] Material loaded successfully", fileName); - - return material; -} -#endif diff --git a/game/src/libs/raylib/physac.h b/game/src/libs/raylib/physac.h deleted file mode 100644 index 5ecd281..0000000 --- a/game/src/libs/raylib/physac.h +++ /dev/null @@ -1,2034 +0,0 @@ -/********************************************************************************************** -* -* Physac v1.0 - 2D Physics library for videogames -* -* DESCRIPTION: -* -* Physac is a small 2D physics engine written in pure C. The engine uses a fixed time-step thread loop -* to simluate physics. A physics step contains the following phases: get collision information, -* apply dynamics, collision solving and position correction. It uses a very simple struct for physic -* bodies with a position vector to be used in any 3D rendering API. -* -* CONFIGURATION: -* -* #define PHYSAC_IMPLEMENTATION -* Generates the implementation of the library into the included file. -* If not defined, the library is in header only mode and can be included in other headers -* or source files without problems. But only ONE file should hold the implementation. -* -* #define PHYSAC_STATIC (defined by default) -* 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 -* -* #define PHYSAC_MALLOC() -* #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. -* -* -* 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: -* gcc -o physac_sample.exe physac_sample.c -s $(RAYLIB_DIR)\raylib\raylib_icon -static -lraylib -lpthread \ -* -lglfw3 -lopengl32 -lgdi32 -lopenal32 -lwinmm -std=c99 -Wl,--subsystem,windows -Wl,-allow-multiple-definition -* -* VERY THANKS TO: -* Ramón Santamaria (@raysan5) -* -* -* LICENSE: zlib/libpng -* -* Copyright (c) 2016-2017 Victor Fisac -* -* This software is provided "as-is", without any express or implied warranty. In no event -* will the authors be held liable for any damages arising from the use of this software. -* -* Permission is granted to anyone to use this software for any purpose, including commercial -* applications, and to alter it and redistribute it freely, subject to the following restrictions: -* -* 1. The origin of this software must not be misrepresented; you must not claim that you -* wrote the original software. If you use this software in a product, an acknowledgment -* in the product documentation would be appreciated but is not required. -* -* 2. Altered source versions must be plainly marked as such, and must not be misrepresented -* as being the original software. -* -* 3. This notice may not be removed or altered from any source distribution. -* -**********************************************************************************************/ - -#if !defined(PHYSAC_H) -#define PHYSAC_H - -// #define PHYSAC_STATIC -// #define PHYSAC_NO_THREADS -// #define PHYSAC_STANDALONE -// #define PHYSAC_DEBUG - -#if defined(PHYSAC_STATIC) - #define PHYSACDEF static // Functions just visible to module including this file -#else - #if defined(__cplusplus) - #define PHYSACDEF extern "C" // Functions visible from other files (no name mangling of functions in C++) - #else - #define PHYSACDEF extern // Functions visible from other files - #endif -#endif - -//---------------------------------------------------------------------------------- -// 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_DESIRED_DELTATIME 1.0/60.0 -#define PHYSAC_MAX_TIMESTEP 0.02 -#define PHYSAC_COLLISION_ITERATIONS 100 -#define PHYSAC_PENETRATION_ALLOWANCE 0.05f -#define PHYSAC_PENETRATION_CORRECTION 0.4f - -#define PHYSAC_PI 3.14159265358979323846 -#define PHYSAC_DEG2RAD (PHYSAC_PI/180.0f) - -#define PHYSAC_MALLOC(size) malloc(size) -#define PHYSAC_FREE(ptr) free(ptr) - -//---------------------------------------------------------------------------------- -// Types and Structures Definition -// NOTE: Below types are required for PHYSAC_STANDALONE usage -//---------------------------------------------------------------------------------- -#if defined(PHYSAC_STANDALONE) - // Vector2 type - typedef struct Vector2 { - float x; - float y; - } Vector2; - - // Boolean type - #if !defined(_STDBOOL_H) - typedef enum { false, true } bool; - #define _STDBOOL_H - #endif -#endif - -typedef enum PhysicsShapeType { PHYSICS_CIRCLE, PHYSICS_POLYGON } PhysicsShapeType; - -// Previously defined to be used in PhysicsShape struct as circular dependencies -typedef struct PhysicsBodyData *PhysicsBody; - -// Mat2 type (used for polygon shape rotation matrix) -typedef struct Mat2 -{ - float m00; - float m01; - float m10; - float m11; -} Mat2; - -typedef struct PolygonData { - unsigned int vertexCount; // Current used vertex and normals count - Vector2 vertices[PHYSAC_MAX_VERTICES]; // Polygon vertex positions vectors - Vector2 normals[PHYSAC_MAX_VERTICES]; // Polygon vertex normals vectors - Mat2 transform; // Vertices transform matrix 2x2 -} PolygonData; - -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) - PolygonData vertexData; // Polygon shape vertices position and normals data (just used for polygon shapes) -} PhysicsShape; - -typedef struct PhysicsBodyData { - unsigned int id; // Reference 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 - Vector2 force; // Current linear force (reset to 0 every step) - float angularVelocity; // Current angular velocity applied to orient - float torque; // Current angular force (reset to 0 every step) - float orient; // Rotation in radians - float inertia; // Moment of inertia - float inverseInertia; // Inverse value of inertia - float mass; // Physics body mass - float inverseMass; // Inverse value of mass - float staticFriction; // Friction when the body has not movement (0 to 1) - float dynamicFriction; // Friction when the body has movement (0 to 1) - float restitution; // Restitution coefficient of the body (0 to 1) - 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) -} PhysicsBodyData; - -typedef struct PhysicsManifoldData { - unsigned int id; // Reference unique identifier - PhysicsBody bodyA; // Manifold first physics body reference - PhysicsBody bodyB; // Manifold second physics body reference - float penetration; // Depth of penetration from collision - Vector2 normal; // Normal direction vector from 'a' to 'b' - Vector2 contacts[2]; // Points of contact during collision - unsigned int contactsCount; // Current collision number of contacts - float restitution; // Mixed restitution during collision - float dynamicFriction; // Mixed dynamic friction during collision - float staticFriction; // Mixed static friction during collision -} PhysicsManifoldData, *PhysicsManifold; - -#if defined(__cplusplus) -extern "C" { // Prevents name mangling of functions -#endif - -//---------------------------------------------------------------------------------- -// Global Variables Definition -//---------------------------------------------------------------------------------- -//... - -//---------------------------------------------------------------------------------- -// Module Functions Declaration -//---------------------------------------------------------------------------------- -PHYSACDEF void InitPhysics(void); // Initializes physics values, pointers and creates physics loop thread -PHYSACDEF bool IsPhysicsEnabled(void); // Returns true if physics thread is currently enabled -PHYSACDEF void SetPhysicsGravity(float x, float y); // Sets physics global gravity force -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 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 PhysicsBody GetPhysicsBody(int index); // Returns a physics body of the bodies pool at a specific index -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) -} -#endif - -#endif // PHYSAC_H - -/*********************************************************************************** -* -* PHYSAC IMPLEMENTATION -* -************************************************************************************/ - -#if defined(PHYSAC_IMPLEMENTATION) - -#if !defined(PHYSAC_NO_THREADS) - #include // Required for: pthread_t, pthread_create() -#endif - -#if defined(PHYSAC_DEBUG) - #include // Required for: printf() -#endif - -#include // Required for: malloc(), free(), srand(), rand() -#include // Required for: cosf(), sinf(), fabs(), sqrtf() - -#include "raymath.h" // Required for: Vector2Add(), Vector2Subtract() - -#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__) || defined(__APPLE__) || defined(PLATFORM_WEB) - #define _POSIX_C_SOURCE 199309L // Required for CLOCK_MONOTONIC if compiled with c99 without gnu ext. - //#define _DEFAULT_SOURCE // Enables BSD function definitions and C99 POSIX compliance - #include // Required for: timespec - #include // Required for: clock_gettime() - #include -#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 - -//---------------------------------------------------------------------------------- -// Types and Structures Definition -//---------------------------------------------------------------------------------- -// ... - -//---------------------------------------------------------------------------------- -// 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 currentTime = 0; // Current time in milliseconds -#if defined(PLATFORM_ANDROID) || defined(PLATFORM_RPI) || defined(__linux__) || defined(__APPLE__) || defined(PLATFORM_WEB) -static double baseTime = 0; // Android and RPI platforms base time -#endif -static double startTime = 0; // Start time in milliseconds -static double deltaTime = 0; // Delta time used for physics steps -static double accumulator = 0; // Physics time step delta time accumulator -static unsigned int stepsCount = 0; // Total physics steps processed -static Vector2 gravityForce = { 0, 9.81f/1000 }; // Physics world gravity force -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 - -//---------------------------------------------------------------------------------- -// Module Internal Functions Declaration -//---------------------------------------------------------------------------------- -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 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 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 void InitTimer(void); // Initializes hi-resolution timer -static double GetCurrentTime(void); // Get current time in milliseconds -static int GetRandomNumber(int min, int max); // Returns a random number between min and max (both included) - -// Math functions -static void MathClamp(double *value, double min, double max); // Clamp a value in a range -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 Mat2 Mat2Radians(float radians); // Creates a matrix 2x2 from a given radians value -static void Mat2Set(Mat2 *matrix, float radians); // Set values from radians to a created matrix 2x2 -static Mat2 Mat2Transpose(Mat2 matrix); // Returns the transpose of a given matrix 2x2 -static Vector2 Mat2MultiplyVector2(Mat2 matrix, Vector2 vector); // Multiplies a vector by a matrix 2x2 - -//---------------------------------------------------------------------------------- -// Module Functions Definition -//---------------------------------------------------------------------------------- -// Initializes physics values, pointers and creates physics loop thread -PHYSACDEF void InitPhysics(void) -{ - #if defined(PHYSAC_DEBUG) - printf("[PHYSAC] physics module initialized successfully\n"); - #endif - - #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 -} - -// Returns true if physics thread is currently enabled -PHYSACDEF bool IsPhysicsEnabled(void) -{ - return physicsThreadEnabled; -} - -// Sets physics global gravity force -PHYSACDEF void SetPhysicsGravity(float x, float y) -{ - gravityForce.x = x; - gravityForce.y = 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; -} - -// 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)); - usedMemory += sizeof(PhysicsBodyData); - - int newId = -1; - for (int i = 0; i < PHYSAC_MAX_BODIES; i++) - { - int currentId = i; - - // Check if current id already exist in other physics body - for (int k = 0; k < physicsBodiesCount; k++) - { - if (bodies[k]->id == currentId) - { - currentId++; - break; - } - } - - // If it is not used, use it as new physics body id - if (currentId == i) - { - newId = i; - break; - } - } - - if (newId != -1) - { - // Initialize new body with generic values - newBody->id = newId; - newBody->enabled = true; - newBody->position = pos; - newBody->velocity = (Vector2){ 0 }; - newBody->force = (Vector2){ 0 }; - newBody->angularVelocity = 0; - newBody->torque = 0; - newBody->orient = 0; - newBody->shape.type = PHYSICS_POLYGON; - newBody->shape.body = newBody; - newBody->shape.vertexData = CreateRectanglePolygon(pos, (Vector2){ width, height }); - - // Calculate centroid and moment of inertia - Vector2 center = { 0 }; - float area = 0; - float inertia = 0; - const float k = 1.0f/3.0f; - - for (int i = 0; i < newBody->shape.vertexData.vertexCount; i++) - { - // Triangle vertices, third vertex implied as (0, 0) - Vector2 p1 = newBody->shape.vertexData.vertices[i]; - int nextIndex = (((i + 1) < newBody->shape.vertexData.vertexCount) ? (i + 1) : 0); - Vector2 p2 = newBody->shape.vertexData.vertices[nextIndex]; - - float D = MathCrossVector2(p1, p2); - float triangleArea = D/2; - - area += triangleArea; - - // Use area to weight the centroid average, not just vertex position - center.x += triangleArea*k*(p1.x + p2.x); - center.y += triangleArea*k*(p1.y + p2.y); - - float intx2 = p1.x*p1.x + p2.x*p1.x + p2.x*p2.x; - float inty2 = p1.y*p1.y + p2.y*p1.y + p2.y*p2.y; - inertia += (0.25f*k*D)*(intx2 + inty2); - } - - center.x *= 1.0f/area; - center.y *= 1.0f/area; - - // 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++) - { - newBody->shape.vertexData.vertices[i].x -= center.x; - newBody->shape.vertexData.vertices[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; - newBody->useGravity = true; - newBody->isGrounded = false; - newBody->freezeOrient = false; - - // Add new body to bodies pointers array and update bodies count - bodies[physicsBodiesCount] = newBody; - physicsBodiesCount++; - - #if defined(PHYSAC_DEBUG) - printf("[PHYSAC] created polygon physics body id %i\n", newBody->id); - #endif - } - #if defined(PHYSAC_DEBUG) - else printf("[PHYSAC] new physics body creation failed because there is any available id to use\n"); - #endif - - return newBody; -} - -// 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)); - usedMemory += sizeof(PhysicsBodyData); - - int newId = -1; - for (int i = 0; i < PHYSAC_MAX_BODIES; i++) - { - int currentId = i; - - // Check if current id already exist in other physics body - for (int k = 0; k < physicsBodiesCount; k++) - { - if (bodies[k]->id == currentId) - { - currentId++; - break; - } - } - - // If it is not used, use it as new physics body id - if (currentId == i) - { - newId = i; - break; - } - } - - if (newId != -1) - { - // Initialize new body with generic values - newBody->id = newId; - newBody->enabled = true; - newBody->position = pos; - newBody->velocity = (Vector2){ 0 }; - newBody->force = (Vector2){ 0 }; - newBody->angularVelocity = 0; - newBody->torque = 0; - newBody->orient = 0; - newBody->shape.type = PHYSICS_POLYGON; - newBody->shape.body = newBody; - newBody->shape.vertexData = CreateRandomPolygon(radius, sides); - - // Calculate centroid and moment of inertia - Vector2 center = { 0 }; - float area = 0; - float inertia = 0; - const float alpha = 1.0f/3.0f; - - for (int i = 0; i < newBody->shape.vertexData.vertexCount; i++) - { - // Triangle vertices, third vertex implied as (0, 0) - Vector2 position1 = newBody->shape.vertexData.vertices[i]; - int nextIndex = (((i + 1) < newBody->shape.vertexData.vertexCount) ? (i + 1) : 0); - Vector2 position2 = newBody->shape.vertexData.vertices[nextIndex]; - - float cross = MathCrossVector2(position1, position2); - float triangleArea = cross/2; - - area += triangleArea; - - // Use area to weight the centroid average, not just vertex position - center.x += triangleArea*alpha*(position1.x + position2.x); - center.y += triangleArea*alpha*(position1.y + position2.y); - - float intx2 = position1.x*position1.x + position2.x*position1.x + position2.x*position2.x; - float inty2 = position1.y*position1.y + position2.y*position1.y + position2.y*position2.y; - inertia += (0.25f*alpha*cross)*(intx2 + inty2); - } - - center.x *= 1.0f/area; - center.y *= 1.0f/area; - - // 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++) - { - newBody->shape.vertexData.vertices[i].x -= center.x; - newBody->shape.vertexData.vertices[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; - newBody->useGravity = true; - newBody->isGrounded = false; - newBody->freezeOrient = false; - - // Add new body to bodies pointers array and update bodies count - bodies[physicsBodiesCount] = newBody; - physicsBodiesCount++; - - #if defined(PHYSAC_DEBUG) - printf("[PHYSAC] created polygon physics body id %i\n", newBody->id); - #endif - } - #if defined(PHYSAC_DEBUG) - else printf("[PHYSAC] new physics body creation failed because there is any available id to use\n"); - #endif - - return newBody; -} - -// Adds a force to a physics body -PHYSACDEF void PhysicsAddForce(PhysicsBody body, Vector2 force) -{ - if (body != NULL) body->force = Vector2Add(body->force, force); -} - -// Adds an angular force to a physics body -PHYSACDEF void PhysicsAddTorque(PhysicsBody body, float amount) -{ - if (body != NULL) body->torque += amount; -} - -// Shatters a polygon shape physics body to little physics bodies with explosion force -PHYSACDEF void PhysicsShatter(PhysicsBody body, Vector2 position, float force) -{ - if (body != NULL) - { - if (body->shape.type == PHYSICS_POLYGON) - { - PolygonData vertexData = body->shape.vertexData; - bool collision = false; - - for (int i = 0; i < vertexData.vertexCount; i++) - { - Vector2 positionA = body->position; - Vector2 positionB = Mat2MultiplyVector2(vertexData.transform, Vector2Add(body->position, vertexData.vertices[i])); - int nextIndex = (((i + 1) < vertexData.vertexCount) ? (i + 1) : 0); - Vector2 positionC = Mat2MultiplyVector2(vertexData.transform, Vector2Add(body->position, vertexData.vertices[nextIndex])); - - // Check collision between each triangle - float alpha = ((positionB.y - positionC.y)*(position.x - positionC.x) + (positionC.x - positionB.x)*(position.y - positionC.y))/ - ((positionB.y - positionC.y)*(positionA.x - positionC.x) + (positionC.x - positionB.x)*(positionA.y - positionC.y)); - - float beta = ((positionC.y - positionA.y)*(position.x - positionC.x) + (positionA.x - positionC.x)*(position.y - positionC.y))/ - ((positionB.y - positionC.y)*(positionA.x - positionC.x) + (positionC.x - positionB.x)*(positionA.y - positionC.y)); - - float gamma = 1.0f - alpha - beta; - - if ((alpha > 0) && (beta > 0) & (gamma > 0)) - { - collision = true; - break; - } - } - - if (collision) - { - int count = vertexData.vertexCount; - Vector2 bodyPos = body->position; - Vector2 vertices[count]; - Mat2 trans = vertexData.transform; - for (int i = 0; i < count; i++) vertices[i] = vertexData.vertices[i]; - - // Destroy shattered physics body - DestroyPhysicsBody(body); - - for (int i = 0; i < count; i++) - { - int nextIndex = (((i + 1) < count) ? (i + 1) : 0); - Vector2 center = TriangleBarycenter(vertices[i], vertices[nextIndex], (Vector2){ 0, 0 }); - center = Vector2Add(bodyPos, center); - Vector2 offset = Vector2Subtract(center, bodyPos); - - PhysicsBody newBody = CreatePhysicsBodyPolygon(center, 10, 3, 10); // Create polygon physics body with relevant values - - PolygonData newData = { 0 }; - newData.vertexCount = 3; - newData.transform = trans; - - newData.vertices[0] = Vector2Subtract(vertices[i], offset); - newData.vertices[1] = Vector2Subtract(vertices[nextIndex], offset); - newData.vertices[2] = Vector2Subtract(position, center); - - // Separate vertices to avoid unnecessary physics collisions - newData.vertices[0].x *= 0.95f; - newData.vertices[0].y *= 0.95f; - newData.vertices[1].x *= 0.95f; - newData.vertices[1].y *= 0.95f; - newData.vertices[2].x *= 0.95f; - newData.vertices[2].y *= 0.95f; - - // Calculate polygon faces normals - for (int j = 0; j < newData.vertexCount; j++) - { - int nextVertex = (((j + 1) < newData.vertexCount) ? (j + 1) : 0); - Vector2 face = Vector2Subtract(newData.vertices[nextVertex], newData.vertices[j]); - - newData.normals[j] = (Vector2){ face.y, -face.x }; - MathNormalize(&newData.normals[j]); - } - - // Apply computed vertex data to new physics body shape - newBody->shape.vertexData = newData; - - // Calculate centroid and moment of inertia - center = (Vector2){ 0 }; - float area = 0; - float inertia = 0; - const float k = 1.0f/3.0f; - - for (int j = 0; j < newBody->shape.vertexData.vertexCount; j++) - { - // Triangle vertices, third vertex implied as (0, 0) - Vector2 p1 = newBody->shape.vertexData.vertices[j]; - int nextVertex = (((j + 1) < newBody->shape.vertexData.vertexCount) ? (j + 1) : 0); - Vector2 p2 = newBody->shape.vertexData.vertices[nextVertex]; - - float D = MathCrossVector2(p1, p2); - float triangleArea = D/2; - - area += triangleArea; - - // Use area to weight the centroid average, not just vertex position - center.x += triangleArea*k*(p1.x + p2.x); - center.y += triangleArea*k*(p1.y + p2.y); - - float intx2 = p1.x*p1.x + p2.x*p1.x + p2.x*p2.x; - float inty2 = p1.y*p1.y + p2.y*p1.y + p2.y*p2.y; - inertia += (0.25f*k*D)*(intx2 + inty2); - } - - 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); - - // Calculate explosion force direction - Vector2 pointA = newBody->position; - Vector2 pointB = Vector2Subtract(newData.vertices[1], newData.vertices[0]); - pointB.x /= 2; - pointB.y /= 2; - Vector2 forceDirection = Vector2Subtract(Vector2Add(pointA, Vector2Add(newData.vertices[0], pointB)), newBody->position); - MathNormalize(&forceDirection); - forceDirection.x *= force; - forceDirection.y *= force; - - // Apply force to new physics body - PhysicsAddForce(newBody, forceDirection); - } - } - } - } - #if defined(PHYSAC_DEBUG) - else printf("[PHYSAC] error when trying to shatter a null reference physics body"); - #endif -} - -// Returns the current amount of created physics bodies -PHYSACDEF int GetPhysicsBodiesCount(void) -{ - return physicsBodiesCount; -} - -// Returns a physics body of the bodies pool at a specific index -PHYSACDEF PhysicsBody GetPhysicsBody(int index) -{ - PhysicsBody body = NULL; - - if (index < physicsBodiesCount) - { - body = bodies[index]; - - if (body == NULL) - { - #if defined(PHYSAC_DEBUG) - printf("[PHYSAC] error when trying to get a null reference physics body"); - #endif - } - } - #if defined(PHYSAC_DEBUG) - else printf("[PHYSAC] physics body index is out of bounds"); - #endif - - return body; -} - -// Returns the physics body shape type (PHYSICS_CIRCLE or PHYSICS_POLYGON) -PHYSACDEF int GetPhysicsShapeType(int index) -{ - int result = -1; - - if (index < physicsBodiesCount) - { - PhysicsBody body = bodies[index]; - - if (body != NULL) result = body->shape.type; - #if defined(PHYSAC_DEBUG) - else printf("[PHYSAC] error when trying to get a null reference physics body"); - #endif - } - #if defined(PHYSAC_DEBUG) - else printf("[PHYSAC] physics body index is out of bounds"); - #endif - - return result; -} - -// Returns the amount of vertices of a physics body shape -PHYSACDEF int GetPhysicsShapeVerticesCount(int index) -{ - int result = 0; - - if (index < physicsBodiesCount) - { - PhysicsBody body = bodies[index]; - - if (body != NULL) - { - switch (body->shape.type) - { - case PHYSICS_CIRCLE: result = PHYSAC_CIRCLE_VERTICES; break; - case PHYSICS_POLYGON: result = body->shape.vertexData.vertexCount; break; - default: break; - } - } - #if defined(PHYSAC_DEBUG) - else printf("[PHYSAC] error when trying to get a null reference physics body"); - #endif - } - #if defined(PHYSAC_DEBUG) - else printf("[PHYSAC] physics body index is out of bounds"); - #endif - - return result; -} - -// Returns transformed position of a body shape (body position + vertex transformed position) -PHYSACDEF Vector2 GetPhysicsShapeVertex(PhysicsBody body, int vertex) -{ - Vector2 position = { 0 }; - - if (body != NULL) - { - switch (body->shape.type) - { - case PHYSICS_CIRCLE: - { - position.x = body->position.x + cosf(360/PHYSAC_CIRCLE_VERTICES*vertex*PHYSAC_DEG2RAD)*body->shape.radius; - position.y = body->position.y + sinf(360/PHYSAC_CIRCLE_VERTICES*vertex*PHYSAC_DEG2RAD)*body->shape.radius; - } break; - case PHYSICS_POLYGON: - { - PolygonData vertexData = body->shape.vertexData; - position = Vector2Add(body->position, Mat2MultiplyVector2(vertexData.transform, vertexData.vertices[vertex])); - } break; - default: break; - } - } - #if defined(PHYSAC_DEBUG) - else printf("[PHYSAC] error when trying to get a null reference physics body"); - #endif - - return position; -} - -// Sets physics body shape transform based on radians parameter -PHYSACDEF void SetPhysicsBodyRotation(PhysicsBody body, float radians) -{ - if (body != NULL) - { - body->orient = radians; - - if (body->shape.type == PHYSICS_POLYGON) body->shape.vertexData.transform = Mat2Radians(radians); - } -} - -// Unitializes and destroys a physics body -PHYSACDEF void DestroyPhysicsBody(PhysicsBody body) -{ - if (body != NULL) - { - int id = body->id; - int index = -1; - - for (int i = 0; i < physicsBodiesCount; i++) - { - if (bodies[i]->id == id) - { - index = i; - break; - } - } - - #if defined(PHYSAC_DEBUG) - if (index == -1) printf("[PHYSAC] cannot find body id %i in pointers array\n", id); - #endif - - // Free body allocated memory - PHYSAC_FREE(bodies[index]); - usedMemory -= sizeof(PhysicsBodyData); - bodies[index] = NULL; - - // Reorder physics bodies pointers array and its catched index - for (int i = index; i < physicsBodiesCount; i++) - { - if ((i + 1) < physicsBodiesCount) bodies[i] = bodies[i + 1]; - } - - // Update physics bodies count - physicsBodiesCount--; - - #if defined(PHYSAC_DEBUG) - printf("[PHYSAC] destroyed physics body id %i\n", id); - #endif - } - #if defined(PHYSAC_DEBUG) - else printf("[PHYSAC] error trying to destroy a null referenced body\n"); - #endif -} - -// Destroys created physics bodies and manifolds and resets global values -PHYSACDEF void ResetPhysics(void) -{ - // Unitialize physics bodies dynamic memory allocations - for (int i = physicsBodiesCount - 1; i >= 0; i--) - { - PhysicsBody body = bodies[i]; - - if (body != NULL) - { - PHYSAC_FREE(body); - body = NULL; - usedMemory -= sizeof(PhysicsBodyData); - } - } - - physicsBodiesCount = 0; - - // Unitialize physics manifolds dynamic memory allocations - for (int i = physicsManifoldsCount - 1; i >= 0; i--) - { - PhysicsManifold manifold = contacts[i]; - - if (manifold != NULL) - { - PHYSAC_FREE(manifold); - manifold = NULL; - usedMemory -= sizeof(PhysicsManifoldData); - } - } - - physicsManifoldsCount = 0; - - #if defined(PHYSAC_DEBUG) - printf("[PHYSAC] physics module reset successfully\n"); - #endif -} - -// 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 -} - -//---------------------------------------------------------------------------------- -// Module Internal Functions Definition -//---------------------------------------------------------------------------------- -// Creates a random polygon shape with max vertex distance from polygon pivot -static PolygonData CreateRandomPolygon(float radius, int sides) -{ - PolygonData data = { 0 }; - data.vertexCount = sides; - - float orient = GetRandomNumber(0, 360); - data.transform = Mat2Radians(orient*PHYSAC_DEG2RAD); - - // Calculate polygon vertices positions - for (int i = 0; i < data.vertexCount; i++) - { - data.vertices[i].x = cosf(360/sides*i*PHYSAC_DEG2RAD)*radius; - data.vertices[i].y = sinf(360/sides*i*PHYSAC_DEG2RAD)*radius; - } - - // Calculate polygon faces normals - for (int i = 0; i < data.vertexCount; i++) - { - int nextIndex = (((i + 1) < sides) ? (i + 1) : 0); - Vector2 face = Vector2Subtract(data.vertices[nextIndex], data.vertices[i]); - - data.normals[i] = (Vector2){ face.y, -face.x }; - MathNormalize(&data.normals[i]); - } - - return data; -} - -// Creates a rectangle polygon shape based on a min and max positions -static PolygonData CreateRectanglePolygon(Vector2 pos, Vector2 size) -{ - PolygonData data = { 0 }; - - data.vertexCount = 4; - data.transform = Mat2Radians(0); - - // Calculate polygon vertices positions - data.vertices[0] = (Vector2){ pos.x + size.x/2, pos.y - size.y/2 }; - data.vertices[1] = (Vector2){ pos.x + size.x/2, pos.y + size.y/2 }; - data.vertices[2] = (Vector2){ pos.x - size.x/2, pos.y + size.y/2 }; - data.vertices[3] = (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.vertices[nextIndex], data.vertices[i]); - - data.normals[i] = (Vector2){ face.y, -face.x }; - MathNormalize(&data.normals[i]); - } - - return data; -} - -// Physics loop thread function -static void *PhysicsLoop(void *arg) -{ - #if defined(PHYSAC_DEBUG) - printf("[PHYSAC] physics thread created with successfully\n"); - #endif - - // Initialize physics loop thread values - physicsThreadEnabled = true; - accumulator = 0; - - // Initialize high resolution timer - InitTimer(); - - // Physics update loop - while (physicsThreadEnabled) - { - // Calculate current time - currentTime = GetCurrentTime(); - - // Calculate current delta time - deltaTime = currentTime - startTime; - - // Store the time elapsed since the last frame began - accumulator += deltaTime; - - // Clamp accumulator to max time step to avoid bad performance - MathClamp(&accumulator, 0, PHYSAC_MAX_TIMESTEP); - - // Fixed time stepping loop - while (accumulator >= PHYSAC_DESIRED_DELTATIME) - { - PhysicsStep(); - accumulator -= deltaTime; - } - - // Record the starting of this frame - startTime = currentTime; - } - - // 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) printf("[PHYSAC] physics module closed with %i still allocated bodies [MEMORY: %i bytes]\n", physicsBodiesCount, usedMemory); - else if (physicsManifoldsCount > 0 || usedMemory != 0) printf("[PHYSAC] physics module closed with %i still allocated manifolds [MEMORY: %i bytes]\n", physicsManifoldsCount, usedMemory); - else printf("[PHYSAC] physics module closed successfully\n"); - #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--) - { - PhysicsManifold manifold = contacts[i]; - if (manifold != NULL) DestroyPhysicsManifold(manifold); - } - - // Reset physics bodies grounded state - for (int i = 0; i < physicsBodiesCount; i++) - { - PhysicsBody body = bodies[i]; - body->isGrounded = false; - } - - // Generate new collision information - for (int i = 0; i < physicsBodiesCount; i++) - { - PhysicsBody bodyA = bodies[i]; - - if (bodyA != NULL) - { - for (int j = i + 1; j < physicsBodiesCount; j++) - { - PhysicsBody bodyB = bodies[j]; - - if (bodyB != NULL) - { - if ((bodyA->inverseMass == 0) && (bodyB->inverseMass == 0)) continue; - - PhysicsManifold manifold = NULL; - if (bodyA->shape.type == PHYSICS_POLYGON && bodyB->shape.type == PHYSICS_CIRCLE) manifold = CreatePhysicsManifold(bodyB, bodyA); - else manifold = CreatePhysicsManifold(bodyA, bodyB); - SolvePhysicsManifold(manifold); - - 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; - } - } - } - } - } - - // Integrate forces to physics bodies - for (int i = 0; i < physicsBodiesCount; i++) - { - PhysicsBody body = bodies[i]; - if (body != NULL) IntegratePhysicsForces(body); - } - - // Initialize physics manifolds to solve collisions - for (int i = 0; i < physicsManifoldsCount; i++) - { - PhysicsManifold manifold = contacts[i]; - if (manifold != NULL) InitializePhysicsManifolds(manifold); - } - - // Integrate physics collisions impulses to solve collisions - for (int i = 0; i < PHYSAC_COLLISION_ITERATIONS; i++) - { - for (int j = 0; j < physicsManifoldsCount; j++) - { - PhysicsManifold manifold = contacts[i]; - if (manifold != NULL) IntegratePhysicsImpulses(manifold); - } - } - - // Integrate velocity to physics bodies - for (int i = 0; i < physicsBodiesCount; i++) - { - PhysicsBody body = bodies[i]; - if (body != NULL) IntegratePhysicsVelocity(body); - } - - // Correct physics bodies positions based on manifolds collision information - for (int i = 0; i < physicsManifoldsCount; i++) - { - PhysicsManifold manifold = contacts[i]; - if (manifold != NULL) CorrectPhysicsPositions(manifold); - } - - // Clear physics bodies forces - for (int i = 0; i < physicsBodiesCount; i++) - { - PhysicsBody body = bodies[i]; - if (body != NULL) - { - body->force = (Vector2){ 0 }; - body->torque = 0; - } - } -} - -// Creates a new physics manifold to solve collision -static PhysicsManifold CreatePhysicsManifold(PhysicsBody a, PhysicsBody b) -{ - PhysicsManifold newManifold = (PhysicsManifold)PHYSAC_MALLOC(sizeof(PhysicsManifoldData)); - usedMemory += sizeof(PhysicsManifoldData); - - int newId = -1; - for (int i = 0; i < PHYSAC_MAX_MANIFOLDS; i++) - { - int currentId = i; - - // Check if current id already exist in other physics body - for (int k = 0; k < physicsManifoldsCount; k++) - { - if (contacts[k]->id == currentId) - { - currentId++; - break; - } - } - - // If it is not used, use it as new physics body id - if (currentId == i) - { - newId = i; - break; - } - } - - if (newId != -1) - { - // Initialize new manifold with generic values - newManifold->id = newId; - newManifold->bodyA = a; - newManifold->bodyB = b; - newManifold->penetration = 0; - newManifold->normal = (Vector2){ 0 }; - newManifold->contacts[0] = (Vector2){ 0 }; - newManifold->contacts[1] = (Vector2){ 0 }; - newManifold->contactsCount = 0; - newManifold->restitution = 0; - newManifold->dynamicFriction = 0; - newManifold->staticFriction = 0; - - // Add new body to bodies pointers array and update bodies count - contacts[physicsManifoldsCount] = newManifold; - physicsManifoldsCount++; - } - #if defined(PHYSAC_DEBUG) - else printf("[PHYSAC] new physics manifold creation failed because there is any available id to use\n"); - #endif - - return newManifold; -} - -// Unitializes and destroys a physics manifold -static void DestroyPhysicsManifold(PhysicsManifold manifold) -{ - if (manifold != NULL) - { - int id = manifold->id; - int index = -1; - - for (int i = 0; i < physicsManifoldsCount; i++) - { - if (contacts[i]->id == id) - { - index = i; - break; - } - } - - #if defined(PHYSAC_DEBUG) - if (index == -1) printf("[PHYSAC] cannot find manifold id %i in pointers array\n", id); - #endif - - // Free manifold allocated memory - PHYSAC_FREE(contacts[index]); - usedMemory -= sizeof(PhysicsManifoldData); - contacts[index] = NULL; - - // Reorder physics manifolds pointers array and its catched index - for (int i = index; i < physicsManifoldsCount; i++) - { - if ((i + 1) < physicsManifoldsCount) contacts[i] = contacts[i + 1]; - } - - // Update physics manifolds count - physicsManifoldsCount--; - } - #if defined(PHYSAC_DEBUG) - else printf("[PHYSAC] error trying to destroy a null referenced manifold\n"); - #endif -} - -// Solves a created physics manifold between two physics bodies -static void SolvePhysicsManifold(PhysicsManifold manifold) -{ - switch (manifold->bodyA->shape.type) - { - case PHYSICS_CIRCLE: - { - switch (manifold->bodyB->shape.type) - { - case PHYSICS_CIRCLE: SolveCircleToCircle(manifold); break; - case PHYSICS_POLYGON: SolveCircleToPolygon(manifold); break; - default: break; - } - } break; - case PHYSICS_POLYGON: - { - switch (manifold->bodyB->shape.type) - { - case PHYSICS_CIRCLE: SolvePolygonToCircle(manifold); break; - case PHYSICS_POLYGON: SolvePolygonToPolygon(manifold); break; - default: break; - } - } break; - default: break; - } - - // Update physics body grounded state if normal direction is down and grounded state is not set yet in previous manifolds - if (!manifold->bodyB->isGrounded) manifold->bodyB->isGrounded = (manifold->normal.y < 0); -} - -// Solves collision between two circle shape physics bodies -static void SolveCircleToCircle(PhysicsManifold manifold) -{ - PhysicsBody bodyA = manifold->bodyA; - PhysicsBody bodyB = manifold->bodyB; - - // Calculate translational vector, which is normal - Vector2 normal = Vector2Subtract(bodyB->position, bodyA->position); - - float distSqr = MathLenSqr(normal); - float radius = bodyA->shape.radius + bodyB->shape.radius; - - // Check if circles are not in contact - if (distSqr >= radius*radius) - { - manifold->contactsCount = 0; - return; - } - - float distance = sqrtf(distSqr); - manifold->contactsCount = 1; - - if (distance == 0) - { - manifold->penetration = bodyA->shape.radius; - manifold->normal = (Vector2){ 1, 0 }; - 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 }; - } - - // Update physics body grounded state if normal direction is down - if (!bodyA->isGrounded) bodyA->isGrounded = (manifold->normal.y < 0); -} - -// Solves collision between a circle to a polygon shape physics bodies -static void SolveCircleToPolygon(PhysicsManifold manifold) -{ - PhysicsBody bodyA = manifold->bodyA; - PhysicsBody bodyB = manifold->bodyB; - - manifold->contactsCount = 0; - - // Transform circle center to polygon transform space - Vector2 center = bodyA->position; - center = Mat2MultiplyVector2(Mat2Transpose(bodyB->shape.vertexData.transform), Vector2Subtract(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; - - for (int i = 0; i < vertexData.vertexCount; i++) - { - float currentSeparation = MathDot(vertexData.normals[i], Vector2Subtract(center, vertexData.vertices[i])); - - if (currentSeparation > bodyA->shape.radius) return; - - if (currentSeparation > separation) - { - separation = currentSeparation; - faceNormal = i; - } - } - - // Grab face's vertices - Vector2 v1 = vertexData.vertices[faceNormal]; - int nextIndex = (((faceNormal + 1) < vertexData.vertexCount) ? (faceNormal + 1) : 0); - Vector2 v2 = vertexData.vertices[nextIndex]; - - // Check to see if center is within polygon - if (separation < PHYSAC_EPSILON) - { - manifold->contactsCount = 1; - Vector2 normal = Mat2MultiplyVector2(vertexData.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 }; - 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)); - manifold->penetration = bodyA->shape.radius - separation; - - if (dot1 <= 0) // Closest to v1 - { - if (DistSqr(center, v1) > bodyA->shape.radius*bodyA->shape.radius) return; - - manifold->contactsCount = 1; - Vector2 normal = Vector2Subtract(v1, center); - normal = Mat2MultiplyVector2(vertexData.transform, normal); - MathNormalize(&normal); - manifold->normal = normal; - v1 = Mat2MultiplyVector2(vertexData.transform, v1); - v1 = Vector2Add(v1, bodyB->position); - manifold->contacts[0] = v1; - } - else if (dot2 <= 0) // Closest to v2 - { - if (DistSqr(center, v2) > bodyA->shape.radius*bodyA->shape.radius) return; - - manifold->contactsCount = 1; - Vector2 normal = Vector2Subtract(v2, center); - v2 = Mat2MultiplyVector2(vertexData.transform, v2); - v2 = Vector2Add(v2, bodyB->position); - manifold->contacts[0] = v2; - normal = Mat2MultiplyVector2(vertexData.transform, normal); - MathNormalize(&normal); - manifold->normal = normal; - } - else // Closest to face - { - Vector2 normal = vertexData.normals[faceNormal]; - - if (MathDot(Vector2Subtract(center, v1), normal) > bodyA->shape.radius) return; - - normal = Mat2MultiplyVector2(vertexData.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 }; - manifold->contactsCount = 1; - } -} - -// Solves collision between a polygon to a circle shape physics bodies -static void SolvePolygonToCircle(PhysicsManifold manifold) -{ - PhysicsBody bodyA = manifold->bodyA; - PhysicsBody bodyB = manifold->bodyB; - - manifold->bodyA = bodyB; - manifold->bodyB = bodyA; - SolveCircleToPolygon(manifold); - - manifold->normal.x *= -1; - manifold->normal.y *= -1; -} - -// Solves collision between two polygons shape physics bodies -static void SolvePolygonToPolygon(PhysicsManifold manifold) -{ - PhysicsShape bodyA = manifold->bodyA->shape; - PhysicsShape bodyB = manifold->bodyB->shape; - manifold->contactsCount = 0; - - // Check for separating axis with A shape's face planes - int faceA = 0; - float penetrationA = FindAxisLeastPenetration(&faceA, bodyA, bodyB); - if (penetrationA >= 0) return; - - // Check for separating axis with B shape's face planes - int faceB = 0; - float penetrationB = FindAxisLeastPenetration(&faceB, bodyB, bodyA); - if (penetrationB >= 0) return; - - int referenceIndex = 0; - bool flip = false; // Always point from A shape to B shape - - PhysicsShape refPoly; // Reference - PhysicsShape incPoly; // Incident - - // Determine which shape contains reference face - if (BiasGreaterThan(penetrationA, penetrationB)) - { - refPoly = bodyA; - incPoly = bodyB; - referenceIndex = faceA; - } - else - { - refPoly = bodyB; - incPoly = bodyA; - referenceIndex = faceB; - flip = true; - } - - // World space incident face - Vector2 incidentFace[2]; - FindIncidentFace(&incidentFace[0], &incidentFace[1], refPoly, incPoly, referenceIndex); - - // Setup reference face vertices - PolygonData refData = refPoly.vertexData; - Vector2 v1 = refData.vertices[referenceIndex]; - referenceIndex = (((referenceIndex + 1) < refData.vertexCount) ? (referenceIndex + 1) : 0); - Vector2 v2 = refData.vertices[referenceIndex]; - - // Transform vertices to world space - v1 = Mat2MultiplyVector2(refData.transform, v1); - v1 = Vector2Add(v1, refPoly.body->position); - v2 = Mat2MultiplyVector2(refData.transform, v2); - v2 = Vector2Add(v2, refPoly.body->position); - - // Calculate reference face side normal in world space - Vector2 sidePlaneNormal = Vector2Subtract(v2, v1); - MathNormalize(&sidePlaneNormal); - - // Orthogonalize - Vector2 refFaceNormal = { sidePlaneNormal.y, -sidePlaneNormal.x }; - float refC = MathDot(refFaceNormal, v1); - float negSide = MathDot(sidePlaneNormal, v1)*-1; - float posSide = MathDot(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; - - // Flip normal if required - manifold->normal = (flip ? (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; - if (separation <= 0) - { - manifold->contacts[currentPoint] = incidentFace[0]; - manifold->penetration = -separation; - currentPoint++; - } - else manifold->penetration = 0; - - separation = MathDot(refFaceNormal, incidentFace[1]) - refC; - - if (separation <= 0) - { - manifold->contacts[currentPoint] = incidentFace[1]; - manifold->penetration += -separation; - currentPoint++; - - // Calculate total penetration average - manifold->penetration /= currentPoint; - } - - manifold->contactsCount = currentPoint; -} - -// Integrates physics forces into velocity -static void IntegratePhysicsForces(PhysicsBody body) -{ - if (body->inverseMass == 0 || !body->enabled) return; - - body->velocity.x += (body->force.x*body->inverseMass)*(deltaTime/2); - body->velocity.y += (body->force.y*body->inverseMass)*(deltaTime/2); - - if (body->useGravity) - { - body->velocity.x += gravityForce.x*(deltaTime/2); - body->velocity.y += gravityForce.y*(deltaTime/2); - } - - if (!body->freezeOrient) body->angularVelocity += body->torque*body->inverseInertia*(deltaTime/2); -} - -// Initializes physics manifolds to solve collisions -static void InitializePhysicsManifolds(PhysicsManifold manifold) -{ - PhysicsBody bodyA = manifold->bodyA; - PhysicsBody bodyB = manifold->bodyB; - - // Calculate average restitution, static and dynamic friction - manifold->restitution = sqrtf(bodyA->restitution*bodyB->restitution); - manifold->staticFriction = sqrtf(bodyA->staticFriction*bodyB->staticFriction); - manifold->dynamicFriction = sqrtf(bodyA->dynamicFriction*bodyB->dynamicFriction); - - for (int i = 0; i < 2; 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 crossA = MathCross(bodyA->angularVelocity, radiusA); - Vector2 crossB = MathCross(bodyB->angularVelocity, radiusB); - - Vector2 radiusV = { 0 }; - radiusV.x = bodyB->velocity.x + crossB.x - bodyA->velocity.x - crossA.x; - radiusV.y = bodyB->velocity.y + crossB.y - bodyA->velocity.y - crossA.y; - - // 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, gravityForce.y*deltaTime }) + PHYSAC_EPSILON)) manifold->restitution = 0; - } -} - -// Integrates physics collisions impulses to solve collisions -static void IntegratePhysicsImpulses(PhysicsManifold manifold) -{ - PhysicsBody bodyA = manifold->bodyA; - PhysicsBody bodyB = manifold->bodyB; - - // Early out and positional correct if both objects have infinite mass - if (fabs(bodyA->inverseMass + bodyB->inverseMass) <= PHYSAC_EPSILON) - { - bodyA->velocity = (Vector2){ 0 }; - bodyB->velocity = (Vector2){ 0 }; - return; - } - - 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); - - // Calculate relative velocity - Vector2 radiusV = { 0 }; - 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; - - // Relative velocity along the normal - float contactVelocity = MathDot(radiusV, manifold->normal); - - // Do not resolve if velocities are separating - if (contactVelocity > 0) return; - - float raCrossN = MathCrossVector2(radiusA, manifold->normal); - float rbCrossN = MathCrossVector2(radiusB, manifold->normal); - - float inverseMassSum = bodyA->inverseMass + bodyB->inverseMass + (raCrossN*raCrossN)*bodyA->inverseInertia + (rbCrossN*rbCrossN)*bodyB->inverseInertia; - - // Calculate impulse scalar value - float impulse = -(1.0f + manifold->restitution)*contactVelocity; - impulse /= inverseMassSum; - impulse /= (float)manifold->contactsCount; - - // Apply impulse to each physics body - Vector2 impulseV = { manifold->normal.x*impulse, manifold->normal.y*impulse }; - - if (bodyA->enabled) - { - 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 (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); - } - - // 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; - - Vector2 tangent = { radiusV.x - (manifold->normal.x*MathDot(radiusV, manifold->normal)), radiusV.y - (manifold->normal.y*MathDot(radiusV, manifold->normal)) }; - MathNormalize(&tangent); - - // Calculate impulse tangent magnitude - float impulseTangent = -MathDot(radiusV, tangent); - impulseTangent /= inverseMassSum; - impulseTangent /= (float)manifold->contactsCount; - - float absImpulseTangent = fabs(impulseTangent); - - // Don't apply tiny friction impulses - if (absImpulseTangent <= PHYSAC_EPSILON) return; - - // Apply coulumb's law - Vector2 tangentImpulse = { 0 }; - 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 }; - - // Apply friction impulse - if (bodyA->enabled) - { - 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 (bodyB->enabled) - { - bodyB->velocity.x += bodyB->inverseMass*(tangentImpulse.x); - bodyB->velocity.y += bodyB->inverseMass*(tangentImpulse.y); - - if (!bodyB->freezeOrient) bodyB->angularVelocity += bodyB->inverseInertia*MathCrossVector2(radiusB, tangentImpulse); - } - } -} - -// Integrates physics velocity into position and forces -static void IntegratePhysicsVelocity(PhysicsBody body) -{ - if (!body->enabled) return; - - body->position.x += body->velocity.x*deltaTime; - body->position.y += body->velocity.y*deltaTime; - - if (!body->freezeOrient) body->orient += body->angularVelocity*deltaTime; - Mat2Set(&body->shape.vertexData.transform, body->orient); - - IntegratePhysicsForces(body); -} - -// Corrects physics bodies positions based on manifolds collision information -static void CorrectPhysicsPositions(PhysicsManifold manifold) -{ - PhysicsBody bodyA = manifold->bodyA; - PhysicsBody bodyB = manifold->bodyB; - - Vector2 correction = { 0 }; - correction.x = (max(manifold->penetration - PHYSAC_PENETRATION_ALLOWANCE, 0)/(bodyA->inverseMass + bodyB->inverseMass))*manifold->normal.x*PHYSAC_PENETRATION_CORRECTION; - correction.y = (max(manifold->penetration - PHYSAC_PENETRATION_ALLOWANCE, 0)/(bodyA->inverseMass + bodyB->inverseMass))*manifold->normal.y*PHYSAC_PENETRATION_CORRECTION; - - if (bodyA->enabled) - { - bodyA->position.x -= correction.x*bodyA->inverseMass; - bodyA->position.y -= correction.y*bodyA->inverseMass; - } - - if (bodyB->enabled) - { - bodyB->position.x += correction.x*bodyB->inverseMass; - bodyB->position.y += correction.y*bodyB->inverseMass; - } -} - -// Returns the extreme point along a direction within a polygon -static Vector2 GetSupport(PhysicsShape shape, Vector2 dir) -{ - float bestProjection = -PHYSAC_FLT_MAX; - Vector2 bestVertex = { 0 }; - PolygonData data = shape.vertexData; - - for (int i = 0; i < data.vertexCount; i++) - { - Vector2 vertex = data.vertices[i]; - float projection = MathDot(vertex, dir); - - if (projection > bestProjection) - { - bestVertex = vertex; - bestProjection = projection; - } - } - - return bestVertex; -} - -// Finds polygon shapes axis least penetration -static float FindAxisLeastPenetration(int *faceIndex, PhysicsShape shapeA, PhysicsShape shapeB) -{ - float bestDistance = -PHYSAC_FLT_MAX; - int bestIndex = 0; - - PolygonData dataA = shapeA.vertexData; - PolygonData 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(dataA.transform, normal); - - // Transform face normal into B shape's model space - Mat2 buT = Mat2Transpose(dataB.transform); - normal = Mat2MultiplyVector2(buT, transNormal); - - // Retrieve support point from B shape along -n - Vector2 support = GetSupport(shapeB, (Vector2){ -normal.x, -normal.y }); - - // Retrieve vertex on face from A shape, transform into B shape's model space - Vector2 vertex = dataA.vertices[i]; - vertex = Mat2MultiplyVector2(dataA.transform, vertex); - vertex = Vector2Add(vertex, shapeA.body->position); - vertex = Vector2Subtract(vertex, shapeB.body->position); - vertex = Mat2MultiplyVector2(buT, vertex); - - // Compute penetration distance in B shape's model space - float distance = MathDot(normal, Vector2Subtract(support, vertex)); - - // Store greatest distance - if (distance > bestDistance) - { - bestDistance = distance; - bestIndex = i; - } - } - - *faceIndex = bestIndex; - return bestDistance; -} - -// 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; - - Vector2 referenceNormal = refData.normals[index]; - - // Calculate normal in incident's frame of reference - referenceNormal = Mat2MultiplyVector2(refData.transform, referenceNormal); // To world space - referenceNormal = Mat2MultiplyVector2(Mat2Transpose(incData.transform), referenceNormal); // To incident's model space - - // Find most anti-normal face on polygon - int incidentFace = 0; - float minDot = PHYSAC_FLT_MAX; - - for (int i = 0; i < incData.vertexCount; i++) - { - float dot = MathDot(referenceNormal, incData.normals[i]); - - if (dot < minDot) - { - minDot = dot; - incidentFace = i; - } - } - - // Assign face vertices for incident face - *v0 = Mat2MultiplyVector2(incData.transform, incData.vertices[incidentFace]); - *v0 = Vector2Add(*v0, inc.body->position); - incidentFace = (((incidentFace + 1) < incData.vertexCount) ? (incidentFace + 1) : 0); - *v1 = Mat2MultiplyVector2(incData.transform, incData.vertices[incidentFace]); - *v1 = Vector2Add(*v1, inc.body->position); -} - -// Calculates clipping based on a normal and two faces -static int Clip(Vector2 normal, float clip, Vector2 *faceA, Vector2 *faceB) -{ - 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; - - // If negative (behind plane) - if (distanceA <= 0) out[sp++] = *faceA; - if (distanceB <= 0) out[sp++] = *faceB; - - // If the points are on different sides of the plane - if ((distanceA*distanceB) < 0) - { - // Push intersection point - float alpha = distanceA/(distanceA - distanceB); - out[sp] = *faceA; - Vector2 delta = Vector2Subtract(*faceB, *faceA); - delta.x *= alpha; - delta.y *= alpha; - out[sp] = Vector2Add(out[sp], delta); - sp++; - } - - // Assign the new converted values - *faceA = out[0]; - *faceB = out[1]; - - 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) -{ - Vector2 result = { 0 }; - - result.x = (v1.x + v2.x + v3.x)/3; - result.y = (v1.y + v2.y + v3.y)/3; - - return result; -} - -// Initializes hi-resolution timer -static void InitTimer(void) -{ - srand(time(NULL)); // Initialize random seed - - #if defined(PLATFORM_ANDROID) || defined(PLATFORM_RPI) - struct timespec now; - if (clock_gettime(CLOCK_MONOTONIC, &now) == 0) baseTime = (uint64_t)now.tv_sec*1000000000LLU + (uint64_t)now.tv_nsec; - #endif - - startTime = GetCurrentTime(); -} - -// Get current time in milliseconds -static double GetCurrentTime(void) -{ - double time = 0; - - #if defined(_WIN32) - unsigned long long int clockFrequency, currentTime; - - QueryPerformanceFrequency(&clockFrequency); - QueryPerformanceCounter(¤tTime); - - time = (double)((double)currentTime/clockFrequency)*1000; - #endif - - #if defined(PLATFORM_ANDROID) || defined(PLATFORM_RPI) || defined(__linux__) || defined(__APPLE__) || defined(PLATFORM_WEB) - struct timespec ts; - clock_gettime(CLOCK_MONOTONIC, &ts); - uint64_t temp = (uint64_t)ts.tv_sec*1000000000LLU + (uint64_t)ts.tv_nsec; - - time = (double)((double)(temp - baseTime)*1e-6); - #endif - - return time; -} - -// Returns a random number between min and max (both included) -static int GetRandomNumber(int min, int max) -{ - if (min > max) - { - int tmp = max; - max = min; - min = tmp; - } - - return (rand()%(abs(max - min) + 1) + min); -} - -// Clamp a value in a range -static inline void MathClamp(double *value, double min, double max) -{ - if (*value < min) *value = min; - else if (*value > max) *value = max; -} - -// Returns the cross product of a vector and a value -static inline Vector2 MathCross(float value, Vector2 vector) -{ - return (Vector2){ -value*vector.y, value*vector.x }; -} - -// Returns the cross product of two vectors -static inline float MathCrossVector2(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) -{ - return (vector.x*vector.x + vector.y*vector.y); -} - -// Returns the dot product of two vectors -static inline float MathDot(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) -{ - Vector2 dir = Vector2Subtract(v1, v2); - return MathDot(dir, dir); -} - -// Returns the normalized values of a vector -static void MathNormalize(Vector2 *vector) -{ - float length, ilength; - - Vector2 aux = *vector; - length = sqrtf(aux.x*aux.x + aux.y*aux.y); - - if (length == 0) length = 1.0f; - - ilength = 1.0f/length; - - vector->x *= ilength; - vector->y *= ilength; -} - -#if defined(PHYSAC_STANDALONE) -// Returns the sum of two given vectors -static inline Vector2 Vector2Add(Vector2 v1, Vector2 v2) -{ - return (Vector2){ v1.x + v2.x, v1.y + v2.y }; -} - -// Returns the subtract of two given vectors -static inline Vector2 Vector2Subtract(Vector2 v1, Vector2 v2) -{ - return (Vector2){ v1.x - v2.x, v1.y - v2.y }; -#endif - -// Creates a matrix 2x2 from a given radians value -static inline Mat2 Mat2Radians(float radians) -{ - float c = cosf(radians); - float s = sinf(radians); - - return (Mat2){ c, -s, s, c }; -} - -// Set values from radians to a created matrix 2x2 -static void Mat2Set(Mat2 *matrix, float radians) -{ - float cos = cosf(radians); - float sin = sinf(radians); - - matrix->m00 = cos; - matrix->m01 = -sin; - matrix->m10 = sin; - matrix->m11 = cos; -} - -// Returns the transpose of a given matrix 2x2 -static inline Mat2 Mat2Transpose(Mat2 matrix) -{ - return (Mat2){ matrix.m00, matrix.m10, matrix.m01, matrix.m11 }; -} - -// Multiplies a vector by a matrix 2x2 -static inline Vector2 Mat2MultiplyVector2(Mat2 matrix, Vector2 vector) -{ - return (Vector2){ matrix.m00*vector.x + matrix.m01*vector.y, matrix.m10*vector.x + matrix.m11*vector.y }; -} - -#endif // PHYSAC_IMPLEMENTATION diff --git a/game/src/libs/raylib/raylib.h b/game/src/libs/raylib/raylib.h deleted file mode 100644 index 392e0a2..0000000 --- a/game/src/libs/raylib/raylib.h +++ /dev/null @@ -1,1168 +0,0 @@ -/********************************************************************************************** -* -* raylib v1.8.0 -* -* A simple and easy-to-use library to learn videogames programming (www.raylib.com) -* -* FEATURES: -* - Written in plain C code (C99) in PascalCase/camelCase notation -* - Multiple platforms support: Windows, Linux, Mac, Android, Raspberry Pi and HTML5 -* - Hardware accelerated with OpenGL (1.1, 2.1, 3.3 or ES 2.0) -* - Unique OpenGL abstraction layer (usable as standalone module): [rlgl] -* - Powerful fonts module with SpriteFonts support (XNA bitmap fonts, AngelCode fonts, TTF) -* - Outstanding texture formats support, including compressed formats (DXT, ETC, PVRT, ASTC) -* - Basic 3d support for Geometrics, Models, Billboards, Heightmaps and Cubicmaps -* - Flexible Materials system, supporting classic maps and PBR maps -* - Shaders support, including Model shaders and Postprocessing shaders -* - Powerful math module for Vector2, Vector3, Matrix and Quaternion operations: [raymath] -* - Audio loading and playing with streaming support and mixing channels: [audio] -* - VR stereo rendering support with configurable HMD device parameters -* - Minimal external dependencies (GLFW3, OpenGL, OpenAL) -* - Complete bindings to LUA (raylib-lua) and Go (raylib-go) -* -* NOTES: -* One custom font is loaded by default when InitWindow() [core] -* If using OpenGL 3.3 or ES2, one default shader is loaded automatically (internally defined) [rlgl] -* If using OpenGL 3.3 or ES2, several vertex buffers (VAO/VBO) are created to manage lines-triangles-quads -* -* DEPENDENCIES: -* GLFW3 (www.glfw.org) for window/context management and input [core] -* GLAD for OpenGL extensions loading (3.3 Core profile, only PLATFORM_DESKTOP) [rlgl] -* OpenAL Soft for audio device/context management [audio] -* -* OPTIONAL DEPENDENCIES: -* stb_image (Sean Barret) for images loading (JPEG, PNG, BMP, TGA) [textures] -* stb_image_resize (Sean Barret) for image resizing algorythms [textures] -* stb_image_write (Sean Barret) for image writting (PNG) [utils] -* stb_truetype (Sean Barret) for ttf fonts loading [text] -* stb_vorbis (Sean Barret) for ogg audio loading [audio] -* stb_perlin (Sean Barret) for Perlin noise image generation [textures] -* par_shapes (Philip Rideout) for parametric 3d shapes generation [models] -* jar_xm (Joshua Reisenauer) for XM audio module loading [audio] -* jar_mod (Joshua Reisenauer) for MOD audio module loading [audio] -* dr_flac (David Reid) for FLAC audio file loading [audio] -* rgif (Charlie Tangora, Ramon Santamaria) for GIF recording [core] -* tinfl for data decompression (DEFLATE algorithm) [rres] -* -* -* LICENSE: zlib/libpng -* -* raylib is licensed under an unmodified zlib/libpng license, which is an OSI-certified, -* BSD-like license that allows static linking with closed source software: -* -* Copyright (c) 2013-2017 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. -* -* Permission is granted to anyone to use this software for any purpose, including commercial -* applications, and to alter it and redistribute it freely, subject to the following restrictions: -* -* 1. The origin of this software must not be misrepresented; you must not claim that you -* wrote the original software. If you use this software in a product, an acknowledgment -* in the product documentation would be appreciated but is not required. -* -* 2. Altered source versions must be plainly marked as such, and must not be misrepresented -* as being the original software. -* -* 3. This notice may not be removed or altered from any source distribution. -* -**********************************************************************************************/ - -#ifndef RAYLIB_H -#define RAYLIB_H - -// Choose your platform here or just define it at compile time: -DPLATFORM_DESKTOP -//#define PLATFORM_DESKTOP // Windows, Linux or OSX -//#define PLATFORM_ANDROID // Android device -//#define PLATFORM_RPI // Raspberry Pi -//#define PLATFORM_WEB // HTML5 (emscripten, asm.js) - -// Security check in case no PLATFORM_* defined -#if !defined(PLATFORM_DESKTOP) && \ - !defined(PLATFORM_ANDROID) && \ - !defined(PLATFORM_RPI) && \ - !defined(PLATFORM_WEB) - #define PLATFORM_DESKTOP -#endif - -#if defined(_WIN32) && defined(BUILD_LIBTYPE_SHARED) - #define RLAPI __declspec(dllexport) // We are building raylib as a Win32 shared library (.dll) -#elif defined(_WIN32) && defined(USE_LIBTYPE_SHARED) - #define RLAPI __declspec(dllimport) // We are using raylib as a Win32 shared library (.dll) -#else - #define RLAPI // We are building or using raylib as a static library (or Linux shared library) -#endif - -//---------------------------------------------------------------------------------- -// Some basic Defines -//---------------------------------------------------------------------------------- -#ifndef PI - #define PI 3.14159265358979323846f -#endif - -#define DEG2RAD (PI/180.0f) -#define RAD2DEG (180.0f/PI) - -// raylib Config Flags -#define FLAG_SHOW_LOGO 1 // Set to show raylib logo at startup -#define FLAG_FULLSCREEN_MODE 2 // Set to run program in fullscreen -#define FLAG_WINDOW_RESIZABLE 4 // Set to allow resizable window -#define FLAG_WINDOW_DECORATED 8 // Set to show window decoration (frame and buttons) -#define FLAG_WINDOW_TRANSPARENT 16 // Set to allow transparent window -#define FLAG_MSAA_4X_HINT 32 // Set to try enabling MSAA 4X -#define FLAG_VSYNC_HINT 64 // Set to try enabling V-Sync on GPU - -// Keyboard Function Keys -#define KEY_SPACE 32 -#define KEY_ESCAPE 256 -#define KEY_ENTER 257 -#define KEY_BACKSPACE 259 -#define KEY_RIGHT 262 -#define KEY_LEFT 263 -#define KEY_DOWN 264 -#define KEY_UP 265 -#define KEY_F1 290 -#define KEY_F2 291 -#define KEY_F3 292 -#define KEY_F4 293 -#define KEY_F5 294 -#define KEY_F6 295 -#define KEY_F7 296 -#define KEY_F8 297 -#define KEY_F9 298 -#define KEY_F10 299 -#define KEY_F11 300 -#define KEY_F12 301 -#define KEY_LEFT_SHIFT 340 -#define KEY_LEFT_CONTROL 341 -#define KEY_LEFT_ALT 342 -#define KEY_RIGHT_SHIFT 344 -#define KEY_RIGHT_CONTROL 345 -#define KEY_RIGHT_ALT 346 - -// Keyboard Alpha Numeric Keys -#define KEY_ZERO 48 -#define KEY_ONE 49 -#define KEY_TWO 50 -#define KEY_THREE 51 -#define KEY_FOUR 52 -#define KEY_FIVE 53 -#define KEY_SIX 54 -#define KEY_SEVEN 55 -#define KEY_EIGHT 56 -#define KEY_NINE 57 -#define KEY_A 65 -#define KEY_B 66 -#define KEY_C 67 -#define KEY_D 68 -#define KEY_E 69 -#define KEY_F 70 -#define KEY_G 71 -#define KEY_H 72 -#define KEY_I 73 -#define KEY_J 74 -#define KEY_K 75 -#define KEY_L 76 -#define KEY_M 77 -#define KEY_N 78 -#define KEY_O 79 -#define KEY_P 80 -#define KEY_Q 81 -#define KEY_R 82 -#define KEY_S 83 -#define KEY_T 84 -#define KEY_U 85 -#define KEY_V 86 -#define KEY_W 87 -#define KEY_X 88 -#define KEY_Y 89 -#define KEY_Z 90 - -#if defined(PLATFORM_ANDROID) - // Android Physical Buttons - #define KEY_BACK 4 - #define KEY_MENU 82 - #define KEY_VOLUME_UP 24 - #define KEY_VOLUME_DOWN 25 -#endif - -// Mouse Buttons -#define MOUSE_LEFT_BUTTON 0 -#define MOUSE_RIGHT_BUTTON 1 -#define MOUSE_MIDDLE_BUTTON 2 - -// Touch points registered -#define MAX_TOUCH_POINTS 2 - -// Gamepad Number -#define GAMEPAD_PLAYER1 0 -#define GAMEPAD_PLAYER2 1 -#define GAMEPAD_PLAYER3 2 -#define GAMEPAD_PLAYER4 3 - -// Gamepad Buttons/Axis - -// PS3 USB Controller Buttons -#define GAMEPAD_PS3_BUTTON_TRIANGLE 0 -#define GAMEPAD_PS3_BUTTON_CIRCLE 1 -#define GAMEPAD_PS3_BUTTON_CROSS 2 -#define GAMEPAD_PS3_BUTTON_SQUARE 3 -#define GAMEPAD_PS3_BUTTON_L1 6 -#define GAMEPAD_PS3_BUTTON_R1 7 -#define GAMEPAD_PS3_BUTTON_L2 4 -#define GAMEPAD_PS3_BUTTON_R2 5 -#define GAMEPAD_PS3_BUTTON_START 8 -#define GAMEPAD_PS3_BUTTON_SELECT 9 -#define GAMEPAD_PS3_BUTTON_UP 24 -#define GAMEPAD_PS3_BUTTON_RIGHT 25 -#define GAMEPAD_PS3_BUTTON_DOWN 26 -#define GAMEPAD_PS3_BUTTON_LEFT 27 -#define GAMEPAD_PS3_BUTTON_PS 12 - -// PS3 USB Controller Axis -#define GAMEPAD_PS3_AXIS_LEFT_X 0 -#define GAMEPAD_PS3_AXIS_LEFT_Y 1 -#define GAMEPAD_PS3_AXIS_RIGHT_X 2 -#define GAMEPAD_PS3_AXIS_RIGHT_Y 5 -#define GAMEPAD_PS3_AXIS_L2 3 // [1..-1] (pressure-level) -#define GAMEPAD_PS3_AXIS_R2 4 // [1..-1] (pressure-level) - -// Xbox360 USB Controller Buttons -#define GAMEPAD_XBOX_BUTTON_A 0 -#define GAMEPAD_XBOX_BUTTON_B 1 -#define GAMEPAD_XBOX_BUTTON_X 2 -#define GAMEPAD_XBOX_BUTTON_Y 3 -#define GAMEPAD_XBOX_BUTTON_LB 4 -#define GAMEPAD_XBOX_BUTTON_RB 5 -#define GAMEPAD_XBOX_BUTTON_SELECT 6 -#define GAMEPAD_XBOX_BUTTON_START 7 -#define GAMEPAD_XBOX_BUTTON_UP 10 -#define GAMEPAD_XBOX_BUTTON_RIGHT 11 -#define GAMEPAD_XBOX_BUTTON_DOWN 12 -#define GAMEPAD_XBOX_BUTTON_LEFT 13 -#define GAMEPAD_XBOX_BUTTON_HOME 8 - -// Xbox360 USB Controller Axis -// NOTE: For Raspberry Pi, axis must be reconfigured -#if defined(PLATFORM_RPI) - #define GAMEPAD_XBOX_AXIS_LEFT_X 0 // [-1..1] (left->right) - #define GAMEPAD_XBOX_AXIS_LEFT_Y 1 // [-1..1] (up->down) - #define GAMEPAD_XBOX_AXIS_RIGHT_X 3 // [-1..1] (left->right) - #define GAMEPAD_XBOX_AXIS_RIGHT_Y 4 // [-1..1] (up->down) - #define GAMEPAD_XBOX_AXIS_LT 2 // [-1..1] (pressure-level) - #define GAMEPAD_XBOX_AXIS_RT 5 // [-1..1] (pressure-level) -#else - #define GAMEPAD_XBOX_AXIS_LEFT_X 0 // [-1..1] (left->right) - #define GAMEPAD_XBOX_AXIS_LEFT_Y 1 // [1..-1] (up->down) - #define GAMEPAD_XBOX_AXIS_RIGHT_X 2 // [-1..1] (left->right) - #define GAMEPAD_XBOX_AXIS_RIGHT_Y 3 // [1..-1] (up->down) - #define GAMEPAD_XBOX_AXIS_LT 4 // [-1..1] (pressure-level) - #define GAMEPAD_XBOX_AXIS_RT 5 // [-1..1] (pressure-level) -#endif - -// NOTE: MSC C++ compiler does not support compound literals (C99 feature) -// Plain structures in C++ (without constructors) can be initialized from { } initializers. -#ifdef __cplusplus - #define CLITERAL -#else - #define CLITERAL (Color) -#endif - -// Some Basic Colors -// NOTE: Custom raylib color palette for amazing visuals on WHITE background -#define LIGHTGRAY CLITERAL{ 200, 200, 200, 255 } // Light Gray -#define GRAY CLITERAL{ 130, 130, 130, 255 } // Gray -#define DARKGRAY CLITERAL{ 80, 80, 80, 255 } // Dark Gray -#define YELLOW CLITERAL{ 253, 249, 0, 255 } // Yellow -#define GOLD CLITERAL{ 255, 203, 0, 255 } // Gold -#define ORANGE CLITERAL{ 255, 161, 0, 255 } // Orange -#define PINK CLITERAL{ 255, 109, 194, 255 } // Pink -#define RED CLITERAL{ 230, 41, 55, 255 } // Red -#define MAROON CLITERAL{ 190, 33, 55, 255 } // Maroon -#define GREEN CLITERAL{ 0, 228, 48, 255 } // Green -#define LIME CLITERAL{ 0, 158, 47, 255 } // Lime -#define DARKGREEN CLITERAL{ 0, 117, 44, 255 } // Dark Green -#define SKYBLUE CLITERAL{ 102, 191, 255, 255 } // Sky Blue -#define BLUE CLITERAL{ 0, 121, 241, 255 } // Blue -#define DARKBLUE CLITERAL{ 0, 82, 172, 255 } // Dark Blue -#define PURPLE CLITERAL{ 200, 122, 255, 255 } // Purple -#define VIOLET CLITERAL{ 135, 60, 190, 255 } // Violet -#define DARKPURPLE CLITERAL{ 112, 31, 126, 255 } // Dark Purple -#define BEIGE CLITERAL{ 211, 176, 131, 255 } // Beige -#define BROWN CLITERAL{ 127, 106, 79, 255 } // Brown -#define DARKBROWN CLITERAL{ 76, 63, 47, 255 } // Dark Brown - -#define WHITE CLITERAL{ 255, 255, 255, 255 } // White -#define BLACK CLITERAL{ 0, 0, 0, 255 } // Black -#define BLANK CLITERAL{ 0, 0, 0, 0 } // Blank (Transparent) -#define MAGENTA CLITERAL{ 255, 0, 255, 255 } // Magenta -#define RAYWHITE CLITERAL{ 245, 245, 245, 255 } // My own White (raylib logo) - -// Shader and material limits -#define MAX_SHADER_LOCATIONS 32 // Maximum number of predefined locations stored in shader struct -#define MAX_MATERIAL_MAPS 12 // Maximum number of texture maps stored in shader struct - -//---------------------------------------------------------------------------------- -// Structures Definition -//---------------------------------------------------------------------------------- -#ifndef __cplusplus -// Boolean type - #ifndef bool - typedef enum { false, true } bool; - #endif -#endif - -// Vector2 type -typedef struct Vector2 { - float x; - float y; -} Vector2; - -// Vector3 type -typedef struct Vector3 { - float x; - float y; - float z; -} Vector3; - -// Matrix type (OpenGL style 4x4 - right handed, column major) -typedef struct Matrix { - float m0, m4, m8, m12; - float m1, m5, m9, m13; - float m2, m6, m10, m14; - float m3, m7, m11, m15; -} Matrix; - -// Color type, RGBA (32bit) -typedef struct Color { - unsigned char r; - unsigned char g; - unsigned char b; - unsigned char a; -} Color; - -// Rectangle type -typedef struct Rectangle { - int x; - int y; - int width; - int height; -} Rectangle; - -// Image type, bpp always RGBA (32bit) -// NOTE: Data stored in CPU memory (RAM) -typedef struct Image { - void *data; // Image raw data - int width; // Image base width - int height; // Image base height - int mipmaps; // Mipmap levels, 1 by default - int format; // Data format (TextureFormat type) -} Image; - -// Texture2D type -// NOTE: Data stored in GPU memory -typedef struct Texture2D { - unsigned int id; // OpenGL texture id - int width; // Texture base width - int height; // Texture base height - int mipmaps; // Mipmap levels, 1 by default - int format; // Data format (TextureFormat type) -} Texture2D; - -// RenderTexture2D type, for texture rendering -typedef struct RenderTexture2D { - unsigned int id; // OpenGL Framebuffer Object (FBO) id - Texture2D texture; // Color buffer attachment texture - Texture2D depth; // Depth buffer attachment texture -} RenderTexture2D; - -// SpriteFont character info -typedef struct CharInfo { - int value; // Character value (Unicode) - Rectangle rec; // Character rectangle in sprite font - int offsetX; // Character offset X when drawing - int offsetY; // Character offset Y when drawing - int advanceX; // Character advance position X -} CharInfo; - -// SpriteFont type, includes texture and charSet array data -typedef struct SpriteFont { - Texture2D texture; // Font texture - int baseSize; // Base size (default chars height) - int charsCount; // Number of characters - CharInfo *chars; // Characters info data -} SpriteFont; - -// Camera type, defines a camera position/orientation in 3d space -typedef struct Camera { - Vector3 position; // Camera position - Vector3 target; // Camera target it looks-at - Vector3 up; // Camera up vector (rotation over its axis) - float fovy; // Camera field-of-view apperture in Y (degrees) -} Camera; - -// Camera2D type, defines a 2d camera -typedef struct Camera2D { - Vector2 offset; // Camera offset (displacement from target) - Vector2 target; // Camera target (rotation and zoom origin) - float rotation; // Camera rotation in degrees - float zoom; // Camera zoom (scaling), should be 1.0f by default -} Camera2D; - -// Bounding box type -typedef struct BoundingBox { - Vector3 min; // Minimum vertex box-corner - Vector3 max; // Maximum vertex box-corner -} BoundingBox; - -// Vertex data definning a mesh -// NOTE: Data stored in CPU memory (and GPU) -typedef struct Mesh { - int vertexCount; // Number of vertices stored in arrays - int triangleCount; // Number of triangles stored (indexed or not) - - float *vertices; // Vertex position (XYZ - 3 components per vertex) (shader-location = 0) - float *texcoords; // Vertex texture coordinates (UV - 2 components per vertex) (shader-location = 1) - float *texcoords2; // Vertex second texture coordinates (useful for lightmaps) (shader-location = 5) - float *normals; // Vertex normals (XYZ - 3 components per vertex) (shader-location = 2) - float *tangents; // Vertex tangents (XYZ - 3 components per vertex) (shader-location = 4) - unsigned char *colors; // Vertex colors (RGBA - 4 components per vertex) (shader-location = 3) - unsigned short *indices;// Vertex indices (in case vertex data comes indexed) - - unsigned int vaoId; // OpenGL Vertex Array Object id - unsigned int vboId[7]; // OpenGL Vertex Buffer Objects id (7 types of vertex data) -} Mesh; - -// Shader type (generic) -typedef struct Shader { - unsigned int id; // Shader program id - int locs[MAX_SHADER_LOCATIONS]; // Shader locations array -} Shader; - -// Material texture map -typedef struct MaterialMap { - Texture2D texture; // Material map texture - Color color; // Material map color - float value; // Material map value -} MaterialMap; - -// Material type (generic) -typedef struct Material { - Shader shader; // Material shader - MaterialMap maps[MAX_MATERIAL_MAPS]; // Material maps - float *params; // Material generic parameters (if required) -} Material; - -// Model type -typedef struct Model { - Mesh mesh; // Vertex data buffers (RAM and VRAM) - Matrix transform; // Local transform matrix - Material material; // Shader and textures data -} Model; - -// Ray type (useful for raycast) -typedef struct Ray { - Vector3 position; // Ray position (origin) - Vector3 direction; // Ray direction -} Ray; - -// Raycast hit information -typedef struct RayHitInfo { - bool hit; // Did the ray hit something? - float distance; // Distance to nearest hit - Vector3 position; // Position of nearest hit - Vector3 normal; // Surface normal of hit -} RayHitInfo; - -// Wave type, defines audio wave data -typedef struct Wave { - unsigned int sampleCount; // Number of samples - unsigned int sampleRate; // Frequency (samples per second) - unsigned int sampleSize; // Bit depth (bits per sample): 8, 16, 32 (24 not supported) - unsigned int channels; // Number of channels (1-mono, 2-stereo) - void *data; // Buffer data pointer -} Wave; - -// Sound source type -typedef struct Sound { - unsigned int source; // OpenAL audio source id - unsigned int buffer; // OpenAL audio buffer id - int format; // OpenAL audio format specifier -} Sound; - -// Music type (file streaming from memory) -// NOTE: Anything longer than ~10 seconds should be streamed -typedef struct MusicData *Music; - -// Audio stream type -// NOTE: Useful to create custom audio streams not bound to a specific file -typedef struct AudioStream { - unsigned int sampleRate; // Frequency (samples per second) - unsigned int sampleSize; // Bit depth (bits per sample): 8, 16, 32 (24 not supported) - unsigned int channels; // Number of channels (1-mono, 2-stereo) - - int format; // OpenAL audio format specifier - unsigned int source; // OpenAL audio source id - unsigned int buffers[2]; // OpenAL audio buffers (double buffering) -} AudioStream; - -// rRES data returned when reading a resource, -// it contains all required data for user (24 byte) -typedef struct RRESData { - unsigned int type; // Resource type (4 byte) - - unsigned int param1; // Resouce parameter 1 (4 byte) - unsigned int param2; // Resouce parameter 2 (4 byte) - unsigned int param3; // Resouce parameter 3 (4 byte) - unsigned int param4; // Resouce parameter 4 (4 byte) - - void *data; // Resource data pointer (4 byte) -} RRESData; - -// RRES type (pointer to RRESData array) -typedef struct RRESData *RRES; - -// Head-Mounted-Display device parameters -typedef struct VrDeviceInfo { - int hResolution; // HMD horizontal resolution in pixels - int vResolution; // HMD vertical resolution in pixels - float hScreenSize; // HMD horizontal size in meters - float vScreenSize; // HMD vertical size in meters - float vScreenCenter; // HMD screen center in meters - float eyeToScreenDistance; // HMD distance between eye and display in meters - float lensSeparationDistance; // HMD lens separation distance in meters - float interpupillaryDistance; // HMD IPD (distance between pupils) in meters - float lensDistortionValues[4]; // HMD lens distortion constant parameters - float chromaAbCorrection[4]; // HMD chromatic aberration correction parameters -} VrDeviceInfo; - -//---------------------------------------------------------------------------------- -// Enumerators Definition -//---------------------------------------------------------------------------------- -// Trace log type -typedef enum { - LOG_INFO = 0, - LOG_WARNING, - LOG_ERROR, - LOG_DEBUG, - LOG_OTHER -} LogType; - -// Shader location point type -typedef enum { - LOC_VERTEX_POSITION = 0, - LOC_VERTEX_TEXCOORD01, - LOC_VERTEX_TEXCOORD02, - LOC_VERTEX_NORMAL, - LOC_VERTEX_TANGENT, - LOC_VERTEX_COLOR, - LOC_MATRIX_MVP, - LOC_MATRIX_MODEL, - LOC_MATRIX_VIEW, - LOC_MATRIX_PROJECTION, - LOC_VECTOR_VIEW, - LOC_COLOR_DIFFUSE, - LOC_COLOR_SPECULAR, - LOC_COLOR_AMBIENT, - LOC_MAP_ALBEDO, // LOC_MAP_DIFFUSE - LOC_MAP_METALNESS, // LOC_MAP_SPECULAR - LOC_MAP_NORMAL, - LOC_MAP_ROUGHNESS, - LOC_MAP_OCCUSION, - LOC_MAP_EMISSION, - LOC_MAP_HEIGHT, - LOC_MAP_CUBEMAP, - LOC_MAP_IRRADIANCE, - LOC_MAP_PREFILTER, - LOC_MAP_BRDF -} ShaderLocationIndex; - -#define LOC_MAP_DIFFUSE LOC_MAP_ALBEDO -#define LOC_MAP_SPECULAR LOC_MAP_METALNESS - -// Material map type -typedef enum { - MAP_ALBEDO = 0, // MAP_DIFFUSE - MAP_METALNESS = 1, // MAP_SPECULAR - MAP_NORMAL = 2, - MAP_ROUGHNESS = 3, - MAP_OCCLUSION, - MAP_EMISSION, - MAP_HEIGHT, - MAP_CUBEMAP, // NOTE: Uses GL_TEXTURE_CUBE_MAP - MAP_IRRADIANCE, // NOTE: Uses GL_TEXTURE_CUBE_MAP - MAP_PREFILTER, // NOTE: Uses GL_TEXTURE_CUBE_MAP - MAP_BRDF -} TexmapIndex; - -#define MAP_DIFFUSE MAP_ALBEDO -#define MAP_SPECULAR MAP_METALNESS - -// Texture formats -// NOTE: Support depends on OpenGL version and platform -typedef enum { - UNCOMPRESSED_GRAYSCALE = 1, // 8 bit per pixel (no alpha) - UNCOMPRESSED_GRAY_ALPHA, // 16 bpp (2 channels) - UNCOMPRESSED_R5G6B5, // 16 bpp - UNCOMPRESSED_R8G8B8, // 24 bpp - UNCOMPRESSED_R5G5B5A1, // 16 bpp (1 bit alpha) - UNCOMPRESSED_R4G4B4A4, // 16 bpp (4 bit alpha) - UNCOMPRESSED_R8G8B8A8, // 32 bpp - UNCOMPRESSED_R32G32B32, // 32 bit per channel (float) - HDR - COMPRESSED_DXT1_RGB, // 4 bpp (no alpha) - COMPRESSED_DXT1_RGBA, // 4 bpp (1 bit alpha) - COMPRESSED_DXT3_RGBA, // 8 bpp - COMPRESSED_DXT5_RGBA, // 8 bpp - COMPRESSED_ETC1_RGB, // 4 bpp - COMPRESSED_ETC2_RGB, // 4 bpp - COMPRESSED_ETC2_EAC_RGBA, // 8 bpp - COMPRESSED_PVRT_RGB, // 4 bpp - COMPRESSED_PVRT_RGBA, // 4 bpp - COMPRESSED_ASTC_4x4_RGBA, // 8 bpp - COMPRESSED_ASTC_8x8_RGBA // 2 bpp -} TextureFormat; - -// Texture parameters: filter mode -// NOTE 1: Filtering considers mipmaps if available in the texture -// NOTE 2: Filter is accordingly set for minification and magnification -typedef enum { - FILTER_POINT = 0, // No filter, just pixel aproximation - FILTER_BILINEAR, // Linear filtering - FILTER_TRILINEAR, // Trilinear filtering (linear with mipmaps) - FILTER_ANISOTROPIC_4X, // Anisotropic filtering 4x - FILTER_ANISOTROPIC_8X, // Anisotropic filtering 8x - FILTER_ANISOTROPIC_16X, // Anisotropic filtering 16x -} TextureFilterMode; - -// Texture parameters: wrap mode -typedef enum { - WRAP_REPEAT = 0, - WRAP_CLAMP, - WRAP_MIRROR -} TextureWrapMode; - -// Color blending modes (pre-defined) -typedef enum { - BLEND_ALPHA = 0, - BLEND_ADDITIVE, - BLEND_MULTIPLIED -} BlendMode; - -// Gestures type -// NOTE: It could be used as flags to enable only some gestures -typedef enum { - GESTURE_NONE = 0, - GESTURE_TAP = 1, - GESTURE_DOUBLETAP = 2, - GESTURE_HOLD = 4, - GESTURE_DRAG = 8, - GESTURE_SWIPE_RIGHT = 16, - GESTURE_SWIPE_LEFT = 32, - GESTURE_SWIPE_UP = 64, - GESTURE_SWIPE_DOWN = 128, - GESTURE_PINCH_IN = 256, - GESTURE_PINCH_OUT = 512 -} Gestures; - -// Camera system modes -typedef enum { - CAMERA_CUSTOM = 0, - CAMERA_FREE, - CAMERA_ORBITAL, - CAMERA_FIRST_PERSON, - CAMERA_THIRD_PERSON -} CameraMode; - -// Head Mounted Display devices -typedef enum { - HMD_DEFAULT_DEVICE = 0, - HMD_OCULUS_RIFT_DK2, - HMD_OCULUS_RIFT_CV1, - HMD_OCULUS_GO, - HMD_VALVE_HTC_VIVE, - HMD_SONY_PSVR -} VrDeviceType; - -// RRESData type -typedef enum { - RRES_TYPE_RAW = 0, - RRES_TYPE_IMAGE, - RRES_TYPE_WAVE, - RRES_TYPE_VERTEX, - RRES_TYPE_TEXT, - RRES_TYPE_FONT_IMAGE, - RRES_TYPE_FONT_CHARDATA, // CharInfo data array - RRES_TYPE_DIRECTORY -} RRESDataType; - -#ifdef __cplusplus -extern "C" { // Prevents name mangling of functions -#endif - -//------------------------------------------------------------------------------------ -// Global Variables Definition -//------------------------------------------------------------------------------------ -// It's lonely here... - -//------------------------------------------------------------------------------------ -// Window and Graphics Device Functions (Module: core) -//------------------------------------------------------------------------------------ - -// Window-related functions -#if defined(PLATFORM_ANDROID) -RLAPI void InitWindow(int width, int height, void *state); // Initialize Android activity -#elif defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI) || defined(PLATFORM_WEB) -RLAPI void InitWindow(int width, int height, const char *title); // Initialize window and OpenGL context -#endif -RLAPI void CloseWindow(void); // Close window and unload OpenGL context -RLAPI bool WindowShouldClose(void); // Check if KEY_ESCAPE pressed or Close icon pressed -RLAPI bool IsWindowMinimized(void); // Check if window has been minimized (or lost focus) -RLAPI void ToggleFullscreen(void); // Toggle fullscreen mode (only PLATFORM_DESKTOP) -RLAPI void SetWindowIcon(Image image); // Set icon for window (only PLATFORM_DESKTOP) -RLAPI void SetWindowTitle(const char *title); // Set title for window (only PLATFORM_DESKTOP) -RLAPI void SetWindowPosition(int x, int y); // Set window position on screen (only PLATFORM_DESKTOP) -RLAPI void SetWindowMonitor(int monitor); // Set monitor for the current window (fullscreen mode) -RLAPI void SetWindowMinSize(int width, int height); // Set window minimum dimensions (for FLAG_WINDOW_RESIZABLE) -RLAPI int GetScreenWidth(void); // Get current screen width -RLAPI int GetScreenHeight(void); // Get current screen height - -#if !defined(PLATFORM_ANDROID) -// Cursor-related functions -RLAPI void ShowCursor(void); // Shows cursor -RLAPI void HideCursor(void); // Hides cursor -RLAPI bool IsCursorHidden(void); // Check if cursor is not visible -RLAPI void EnableCursor(void); // Enables cursor (unlock cursor) -RLAPI void DisableCursor(void); // Disables cursor (lock cursor) -#endif - -// Drawing-related functions -RLAPI void ClearBackground(Color color); // Set background color (framebuffer clear color) -RLAPI void BeginDrawing(void); // Setup canvas (framebuffer) to start drawing -RLAPI void EndDrawing(void); // End canvas drawing and swap buffers (double buffering) -RLAPI void Begin2dMode(Camera2D camera); // Initialize 2D mode with custom camera (2D) -RLAPI void End2dMode(void); // Ends 2D mode with custom camera -RLAPI void Begin3dMode(Camera camera); // Initializes 3D mode with custom camera (3D) -RLAPI void End3dMode(void); // Ends 3D mode and returns to default 2D orthographic mode -RLAPI void BeginTextureMode(RenderTexture2D target); // Initializes render texture for drawing -RLAPI void EndTextureMode(void); // Ends drawing to render texture - -// Screen-space-related functions -RLAPI Ray GetMouseRay(Vector2 mousePosition, Camera camera); // Returns a ray trace from mouse position -RLAPI Vector2 GetWorldToScreen(Vector3 position, Camera camera); // Returns the screen space position for a 3d world space position -RLAPI Matrix GetCameraMatrix(Camera camera); // Returns camera transform matrix (view matrix) - -// Timming-related functions -RLAPI void SetTargetFPS(int fps); // Set target FPS (maximum) -RLAPI int GetFPS(void); // Returns current FPS -RLAPI float GetFrameTime(void); // Returns time in seconds for last frame drawn - -// Color-related functions -RLAPI int GetHexValue(Color color); // Returns hexadecimal value for a Color -RLAPI Color GetColor(int hexValue); // Returns a Color struct from hexadecimal value -RLAPI Color Fade(Color color, float alpha); // Color fade-in or fade-out, alpha goes from 0.0f to 1.0f -RLAPI float *ColorToFloat(Color color); // Converts Color to float array and normalizes - -// Math useful functions (available from raymath.h) -RLAPI float *VectorToFloat(Vector3 vec); // Returns Vector3 as float array -RLAPI float *MatrixToFloat(Matrix mat); // Returns Matrix as float array -RLAPI Vector3 Vector3Zero(void); // Vector with components value 0.0f -RLAPI Vector3 Vector3One(void); // Vector with components value 1.0f -RLAPI Matrix MatrixIdentity(void); // Returns identity matrix - -// Misc. functions -RLAPI void ShowLogo(void); // Activate raylib logo at startup (can be done with flags) -RLAPI void SetConfigFlags(char flags); // Setup window configuration flags (view FLAGS) -RLAPI void TraceLog(int logType, const char *text, ...); // Show trace log messages (LOG_INFO, LOG_WARNING, LOG_ERROR, LOG_DEBUG) -RLAPI void TakeScreenshot(const char *fileName); // Takes a screenshot of current screen (saved a .png) -RLAPI int GetRandomValue(int min, int max); // Returns a random value between min and max (both included) - -// Files management functions -RLAPI bool IsFileExtension(const char *fileName, const char *ext);// Check file extension -RLAPI const char *GetExtension(const char *fileName); // Get file extension -RLAPI const char *GetDirectoryPath(const char *fileName); // Get directory for a given fileName (with path) -RLAPI const char *GetWorkingDirectory(void); // Get current working directory -RLAPI bool ChangeDirectory(const char *dir); // Change working directory, returns true if success -RLAPI bool IsFileDropped(void); // Check if a file has been dropped into window -RLAPI char **GetDroppedFiles(int *count); // Get dropped files names -RLAPI void ClearDroppedFiles(void); // Clear dropped files paths buffer - -// Persistent storage management -RLAPI void StorageSaveValue(int position, int value); // Save integer value to storage file (to defined position) -RLAPI int StorageLoadValue(int position); // Load integer value from storage file (from defined position) - -//------------------------------------------------------------------------------------ -// Input Handling Functions (Module: core) -//------------------------------------------------------------------------------------ - -// Input-related functions: keyboard -RLAPI bool IsKeyPressed(int key); // Detect if a key has been pressed once -RLAPI bool IsKeyDown(int key); // Detect if a key is being pressed -RLAPI bool IsKeyReleased(int key); // Detect if a key has been released once -RLAPI bool IsKeyUp(int key); // Detect if a key is NOT being pressed -RLAPI int GetKeyPressed(void); // Get latest key pressed -RLAPI void SetExitKey(int key); // Set a custom key to exit program (default is ESC) - -// Input-related functions: gamepads -RLAPI bool IsGamepadAvailable(int gamepad); // Detect if a gamepad is available -RLAPI bool IsGamepadName(int gamepad, const char *name); // Check gamepad name (if available) -RLAPI const char *GetGamepadName(int gamepad); // Return gamepad internal name id -RLAPI bool IsGamepadButtonPressed(int gamepad, int button); // Detect if a gamepad button has been pressed once -RLAPI bool IsGamepadButtonDown(int gamepad, int button); // Detect if a gamepad button is being pressed -RLAPI bool IsGamepadButtonReleased(int gamepad, int button); // Detect if a gamepad button has been released once -RLAPI bool IsGamepadButtonUp(int gamepad, int button); // Detect if a gamepad button is NOT being pressed -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 - -// Input-related functions: mouse -RLAPI bool IsMouseButtonPressed(int button); // Detect if a mouse button has been pressed once -RLAPI bool IsMouseButtonDown(int button); // Detect if a mouse button is being pressed -RLAPI bool IsMouseButtonReleased(int button); // Detect if a mouse button has been released once -RLAPI bool IsMouseButtonUp(int button); // Detect if a mouse button is NOT being pressed -RLAPI int GetMouseX(void); // Returns mouse position X -RLAPI int GetMouseY(void); // Returns mouse position Y -RLAPI Vector2 GetMousePosition(void); // Returns mouse position XY -RLAPI void SetMousePosition(Vector2 position); // Set mouse position XY -RLAPI int GetMouseWheelMove(void); // Returns mouse wheel movement Y - -// Input-related functions: touch -RLAPI int GetTouchX(void); // Returns touch position X for touch point 0 (relative to screen size) -RLAPI int GetTouchY(void); // Returns touch position Y for touch point 0 (relative to screen size) -RLAPI Vector2 GetTouchPosition(int index); // Returns touch position XY for a touch point index (relative to screen size) - -//------------------------------------------------------------------------------------ -// Gestures and Touch Handling Functions (Module: gestures) -//------------------------------------------------------------------------------------ -RLAPI void SetGesturesEnabled(unsigned int gestureFlags); // Enable a set of gestures using flags -RLAPI bool IsGestureDetected(int gesture); // Check if a gesture have been detected -RLAPI int GetGestureDetected(void); // Get latest detected gesture -RLAPI int GetTouchPointsCount(void); // Get touch points count -RLAPI float GetGestureHoldDuration(void); // Get gesture hold time in milliseconds -RLAPI Vector2 GetGestureDragVector(void); // Get gesture drag vector -RLAPI float GetGestureDragAngle(void); // Get gesture drag angle -RLAPI Vector2 GetGesturePinchVector(void); // Get gesture pinch delta -RLAPI float GetGesturePinchAngle(void); // Get gesture pinch angle - -//------------------------------------------------------------------------------------ -// Camera System Functions (Module: camera) -//------------------------------------------------------------------------------------ -RLAPI void SetCameraMode(Camera camera, int mode); // Set camera mode (multiple camera modes available) -RLAPI void UpdateCamera(Camera *camera); // Update camera position for selected mode - -RLAPI void SetCameraPanControl(int panKey); // Set camera pan key to combine with mouse movement (free camera) -RLAPI void SetCameraAltControl(int altKey); // Set camera alt key to combine with mouse movement (free camera) -RLAPI void SetCameraSmoothZoomControl(int szKey); // Set camera smooth zoom key to combine with mouse (free camera) -RLAPI void SetCameraMoveControls(int frontKey, int backKey, - int rightKey, int leftKey, - int upKey, int downKey); // Set camera move controls (1st person and 3rd person cameras) - -//------------------------------------------------------------------------------------ -// Basic Shapes Drawing Functions (Module: shapes) -//------------------------------------------------------------------------------------ - -// Basic shapes drawing functions -RLAPI void DrawPixel(int posX, int posY, Color color); // Draw a pixel -RLAPI void DrawPixelV(Vector2 position, Color color); // Draw a pixel (Vector version) -RLAPI void DrawLine(int startPosX, int startPosY, int endPosX, int endPosY, Color color); // Draw a line -RLAPI void DrawLineV(Vector2 startPos, Vector2 endPos, Color color); // Draw a line (Vector version) -RLAPI void DrawLineEx(Vector2 startPos, Vector2 endPos, float thick, Color color); // Draw a line defining thickness -RLAPI void DrawLineBezier(Vector2 startPos, Vector2 endPos, float thick, Color color); // Draw a line using cubic-bezier curves in-out -RLAPI void DrawCircle(int centerX, int centerY, float radius, Color color); // Draw a color-filled circle -RLAPI void DrawCircleGradient(int centerX, int centerY, float radius, Color color1, Color color2); // Draw a gradient-filled circle -RLAPI void DrawCircleV(Vector2 center, float radius, Color color); // Draw a color-filled circle (Vector version) -RLAPI void DrawCircleLines(int centerX, int centerY, float radius, Color color); // Draw circle outline -RLAPI void DrawRectangle(int posX, int posY, int width, int height, Color color); // Draw a color-filled rectangle -RLAPI void DrawRectangleRec(Rectangle rec, Color color); // Draw a color-filled rectangle -RLAPI void DrawRectanglePro(Rectangle rec, Vector2 origin, float rotation, Color color); // Draw a color-filled rectangle with pro parameters -RLAPI void DrawRectangleGradientV(int posX, int posY, int width, int height, Color color1, Color color2);// Draw a vertical-gradient-filled rectangle -RLAPI void DrawRectangleGradientH(int posX, int posY, int width, int height, Color color1, Color color2);// Draw a horizontal-gradient-filled rectangle -RLAPI void DrawRectangleGradientEx(Rectangle rec, Color col1, Color col2, Color col3, Color col4); // Draw a gradient-filled rectangle with custom vertex colors -RLAPI void DrawRectangleV(Vector2 position, Vector2 size, Color color); // Draw a color-filled rectangle (Vector version) -RLAPI void DrawRectangleLines(int posX, int posY, int width, int height, Color color); // Draw rectangle outline -RLAPI void DrawRectangleT(int posX, int posY, int width, int height, Color color); // Draw rectangle using text character -RLAPI void DrawTriangle(Vector2 v1, Vector2 v2, Vector2 v3, Color color); // Draw a color-filled triangle -RLAPI void DrawTriangleLines(Vector2 v1, Vector2 v2, Vector2 v3, Color color); // Draw triangle outline -RLAPI void DrawPoly(Vector2 center, int sides, float radius, float rotation, Color color); // Draw a regular polygon (Vector version) -RLAPI void DrawPolyEx(Vector2 *points, int numPoints, Color color); // Draw a closed polygon defined by points -RLAPI void DrawPolyExLines(Vector2 *points, int numPoints, Color color); // Draw polygon lines - -// Basic shapes collision detection functions -RLAPI bool CheckCollisionRecs(Rectangle rec1, Rectangle rec2); // Check collision between two rectangles -RLAPI bool CheckCollisionCircles(Vector2 center1, float radius1, Vector2 center2, float radius2); // Check collision between two circles -RLAPI bool CheckCollisionCircleRec(Vector2 center, float radius, Rectangle rec); // Check collision between circle and rectangle -RLAPI Rectangle GetCollisionRec(Rectangle rec1, Rectangle rec2); // Get collision rectangle for two rectangles collision -RLAPI bool CheckCollisionPointRec(Vector2 point, Rectangle rec); // Check if point is inside rectangle -RLAPI bool CheckCollisionPointCircle(Vector2 point, Vector2 center, float radius); // Check if point is inside circle -RLAPI bool CheckCollisionPointTriangle(Vector2 point, Vector2 p1, Vector2 p2, Vector2 p3); // Check if point is inside a triangle - -//------------------------------------------------------------------------------------ -// Texture Loading and Drawing Functions (Module: textures) -//------------------------------------------------------------------------------------ - -// Image/Texture2D data loading/unloading/saving functions -RLAPI Image LoadImage(const char *fileName); // Load image from file into CPU memory (RAM) -RLAPI Image LoadImageEx(Color *pixels, int width, int height); // Load image from Color array data (RGBA - 32bit) -RLAPI Image LoadImagePro(void *data, int width, int height, int format); // Load image from raw data with parameters -RLAPI Image LoadImageRaw(const char *fileName, int width, int height, int format, int headerSize); // Load image from RAW file data -RLAPI Texture2D LoadTexture(const char *fileName); // Load texture from file into GPU memory (VRAM) -RLAPI Texture2D LoadTextureFromImage(Image image); // Load texture from image data -RLAPI RenderTexture2D LoadRenderTexture(int width, int height); // Load texture for rendering (framebuffer) -RLAPI void UnloadImage(Image image); // Unload image from CPU memory (RAM) -RLAPI void UnloadTexture(Texture2D texture); // Unload texture from GPU memory (VRAM) -RLAPI void UnloadRenderTexture(RenderTexture2D target); // Unload render texture from GPU memory (VRAM) -RLAPI Color *GetImageData(Image image); // Get pixel data from image as a Color struct array -RLAPI Image GetTextureData(Texture2D texture); // Get pixel data from GPU texture and return an Image -RLAPI void UpdateTexture(Texture2D texture, const void *pixels); // Update GPU texture with new data -RLAPI void SaveImageAs(const char *fileName, Image image); // Save image to a PNG file - -// Image manipulation functions -RLAPI void ImageToPOT(Image *image, Color fillColor); // Convert image to POT (power-of-two) -RLAPI void ImageFormat(Image *image, int newFormat); // Convert image data to desired format -RLAPI void ImageAlphaMask(Image *image, Image alphaMask); // Apply alpha mask to image -RLAPI void ImageDither(Image *image, int rBpp, int gBpp, int bBpp, int aBpp); // Dither image data to 16bpp or lower (Floyd-Steinberg dithering) -RLAPI Image ImageCopy(Image image); // Create an image duplicate (useful for transformations) -RLAPI void ImageCrop(Image *image, Rectangle crop); // Crop an image to a defined rectangle -RLAPI void ImageResize(Image *image, int newWidth, int newHeight); // Resize and image (bilinear filtering) -RLAPI void ImageResizeNN(Image *image,int newWidth,int newHeight); // Resize and image (Nearest-Neighbor scaling algorithm) -RLAPI Image ImageText(const char *text, int fontSize, Color color); // Create an image from text (default font) -RLAPI Image ImageTextEx(SpriteFont font, const char *text, float fontSize, int spacing, Color tint); // Create an image from text (custom sprite font) -RLAPI void ImageDraw(Image *dst, Image src, Rectangle srcRec, Rectangle dstRec); // Draw a source image within a destination image -RLAPI void ImageDrawText(Image *dst, Vector2 position, const char *text, int fontSize, Color color); // Draw text (default font) within an image (destination) -RLAPI void ImageDrawTextEx(Image *dst, Vector2 position, SpriteFont font, const char *text, - float fontSize, int spacing, Color color); // Draw text (custom sprite font) within an image (destination) -RLAPI void ImageFlipVertical(Image *image); // Flip image vertically -RLAPI void ImageFlipHorizontal(Image *image); // Flip image horizontally -RLAPI void ImageColorTint(Image *image, Color color); // Modify image color: tint -RLAPI void ImageColorInvert(Image *image); // Modify image color: invert -RLAPI void ImageColorGrayscale(Image *image); // Modify image color: grayscale -RLAPI void ImageColorContrast(Image *image, float contrast); // Modify image color: contrast (-100 to 100) -RLAPI void ImageColorBrightness(Image *image, int brightness); // Modify image color: brightness (-255 to 255) - -// Image generation functions -RLAPI Image GenImageGradientV(int width, int height, Color top, Color bottom); // Generate image: vertical gradient -RLAPI Image GenImageGradientH(int width, int height, Color left, Color right); // Generate image: horizontal gradient -RLAPI Image GenImageGradientRadial(int width, int height, float density, Color inner, Color outer); // Generate image: radial gradient -RLAPI Image GenImageChecked(int width, int height, int checksX, int checksY, Color col1, Color col2); // Generate image: checked -RLAPI Image GenImageWhiteNoise(int width, int height, float factor); // Generate image: white noise -RLAPI Image GenImagePerlinNoise(int width, int height, float scale); // Generate image: perlin noise -RLAPI Image GenImageCellular(int width, int height, int tileSize); // Generate image: cellular algorithm. Bigger tileSize means bigger cells - -// Texture2D configuration functions -RLAPI void GenTextureMipmaps(Texture2D *texture); // Generate GPU mipmaps for a texture -RLAPI void SetTextureFilter(Texture2D texture, int filterMode); // Set texture scaling filter mode -RLAPI void SetTextureWrap(Texture2D texture, int wrapMode); // Set texture wrapping mode - -// Texture2D drawing functions -RLAPI void DrawTexture(Texture2D texture, int posX, int posY, Color tint); // Draw a Texture2D -RLAPI void DrawTextureV(Texture2D texture, Vector2 position, Color tint); // Draw a Texture2D with position defined as Vector2 -RLAPI void DrawTextureEx(Texture2D texture, Vector2 position, float rotation, float scale, Color tint); // Draw a Texture2D with extended parameters -RLAPI void DrawTextureRec(Texture2D texture, Rectangle sourceRec, Vector2 position, Color tint); // Draw a part of a texture defined by a rectangle -RLAPI void DrawTexturePro(Texture2D texture, Rectangle sourceRec, Rectangle destRec, Vector2 origin, // Draw a part of a texture defined by a rectangle with 'pro' parameters - float rotation, Color tint); - -//------------------------------------------------------------------------------------ -// Font Loading and Text Drawing Functions (Module: text) -//------------------------------------------------------------------------------------ - -// SpriteFont loading/unloading functions -RLAPI SpriteFont GetDefaultFont(void); // Get the default SpriteFont -RLAPI SpriteFont LoadSpriteFont(const char *fileName); // Load SpriteFont from file into GPU memory (VRAM) -RLAPI SpriteFont LoadSpriteFontEx(const char *fileName, int fontSize, int charsCount, int *fontChars); // Load SpriteFont from file with extended parameters -RLAPI void UnloadSpriteFont(SpriteFont spriteFont); // Unload SpriteFont from GPU memory (VRAM) - -// Text drawing functions -RLAPI void DrawFPS(int posX, int posY); // Shows current FPS -RLAPI void DrawText(const char *text, int posX, int posY, int fontSize, Color color); // Draw text (using default font) -RLAPI void DrawTextEx(SpriteFont spriteFont, const char* text, Vector2 position, // Draw text using SpriteFont and additional parameters - float fontSize, int spacing, Color tint); - -// Text misc. functions -RLAPI int MeasureText(const char *text, int fontSize); // Measure string width for default font -RLAPI Vector2 MeasureTextEx(SpriteFont spriteFont, const char *text, float fontSize, int spacing); // Measure string size for SpriteFont -RLAPI const char *FormatText(const char *text, ...); // Formatting of text with variables to 'embed' -RLAPI const char *SubText(const char *text, int position, int length); // Get a piece of a text string - -//------------------------------------------------------------------------------------ -// Basic 3d Shapes Drawing Functions (Module: models) -//------------------------------------------------------------------------------------ - -// Basic geometric 3D shapes drawing functions -RLAPI void DrawLine3D(Vector3 startPos, Vector3 endPos, Color color); // Draw a line in 3D world space -RLAPI void DrawCircle3D(Vector3 center, float radius, Vector3 rotationAxis, float rotationAngle, Color color); // Draw a circle in 3D world space -RLAPI void DrawCube(Vector3 position, float width, float height, float length, Color color); // Draw cube -RLAPI void DrawCubeV(Vector3 position, Vector3 size, Color color); // Draw cube (Vector version) -RLAPI void DrawCubeWires(Vector3 position, float width, float height, float length, Color color); // Draw cube wires -RLAPI void DrawCubeTexture(Texture2D texture, Vector3 position, float width, float height, float length, Color color); // Draw cube textured -RLAPI void DrawSphere(Vector3 centerPos, float radius, Color color); // Draw sphere -RLAPI void DrawSphereEx(Vector3 centerPos, float radius, int rings, int slices, Color color); // Draw sphere with extended parameters -RLAPI void DrawSphereWires(Vector3 centerPos, float radius, int rings, int slices, Color color); // Draw sphere wires -RLAPI void DrawCylinder(Vector3 position, float radiusTop, float radiusBottom, float height, int slices, Color color); // Draw a cylinder/cone -RLAPI void DrawCylinderWires(Vector3 position, float radiusTop, float radiusBottom, float height, int slices, Color color); // Draw a cylinder/cone wires -RLAPI void DrawPlane(Vector3 centerPos, Vector2 size, Color color); // Draw a plane XZ -RLAPI void DrawRay(Ray ray, Color color); // Draw a ray line -RLAPI void DrawGrid(int slices, float spacing); // Draw a grid (centered at (0, 0, 0)) -RLAPI void DrawGizmo(Vector3 position); // Draw simple gizmo -//DrawTorus(), DrawTeapot() could be useful? - -//------------------------------------------------------------------------------------ -// Model 3d Loading and Drawing Functions (Module: models) -//------------------------------------------------------------------------------------ - -// Model loading/unloading functions -RLAPI Model LoadModel(const char *fileName); // Load model from files (mesh and material) -RLAPI Model LoadModelFromMesh(Mesh mesh); // Load model from generated mesh -RLAPI void UnloadModel(Model model); // Unload model from memory (RAM and/or VRAM) - -// Mesh loading/unloading functions -RLAPI Mesh LoadMesh(const char *fileName); // Load mesh from file -RLAPI void UnloadMesh(Mesh *mesh); // Unload mesh from memory (RAM and/or VRAM) - -// Mesh generation functions -RLAPI Mesh GenMeshPlane(float width, float length, int resX, int resZ); // Generate plane mesh (with subdivisions) -RLAPI Mesh GenMeshCube(float width, float height, float length); // Generate cuboid mesh -RLAPI Mesh GenMeshSphere(float radius, int rings, int slices); // Generate sphere mesh (standard sphere) -RLAPI Mesh GenMeshHemiSphere(float radius, int rings, int slices); // Generate half-sphere mesh (no bottom cap) -RLAPI Mesh GenMeshCylinder(float radius, float height, int slices); // Generate cylinder mesh -RLAPI Mesh GenMeshTorus(float radius, float size, int radSeg, int sides); // Generate torus mesh -RLAPI Mesh GenMeshKnot(float radius, float size, int radSeg, int sides); // Generate trefoil knot mesh -RLAPI Mesh GenMeshHeightmap(Image heightmap, Vector3 size); // Generate heightmap mesh from image data -RLAPI Mesh GenMeshCubicmap(Image cubicmap, Vector3 cubeSize); // Generate cubes-based map mesh from image data - -// Material loading/unloading functions -RLAPI Material LoadMaterial(const char *fileName); // Load material from file -RLAPI Material LoadMaterialDefault(void); // Load default material (Supports: DIFFUSE, SPECULAR, NORMAL maps) -RLAPI void UnloadMaterial(Material material); // Unload material from GPU memory (VRAM) - -// Model drawing functions -RLAPI void DrawModel(Model model, Vector3 position, float scale, Color tint); // Draw a model (with texture if set) -RLAPI void DrawModelEx(Model model, Vector3 position, Vector3 rotationAxis, - float rotationAngle, Vector3 scale, Color tint); // Draw a model with extended parameters -RLAPI void DrawModelWires(Model model, Vector3 position, float scale, Color tint); // Draw a model wires (with texture if set) -RLAPI void DrawModelWiresEx(Model model, Vector3 position, Vector3 rotationAxis, - float rotationAngle, Vector3 scale, Color tint); // Draw a model wires (with texture if set) with extended parameters -RLAPI void DrawBoundingBox(BoundingBox box, Color color); // Draw bounding box (wires) -RLAPI void DrawBillboard(Camera camera, Texture2D texture, Vector3 center, float size, Color tint); // Draw a billboard texture -RLAPI void DrawBillboardRec(Camera camera, Texture2D texture, Rectangle sourceRec, - Vector3 center, float size, Color tint); // Draw a billboard texture defined by sourceRec - -// Collision detection functions -RLAPI BoundingBox CalculateBoundingBox(Mesh mesh); // Calculate mesh bounding box limits -RLAPI bool CheckCollisionSpheres(Vector3 centerA, float radiusA, Vector3 centerB, float radiusB); // Detect collision between two spheres -RLAPI bool CheckCollisionBoxes(BoundingBox box1, BoundingBox box2); // Detect collision between two bounding boxes -RLAPI bool CheckCollisionBoxSphere(BoundingBox box, Vector3 centerSphere, float radiusSphere); // Detect collision between box and sphere -RLAPI bool CheckCollisionRaySphere(Ray ray, Vector3 spherePosition, float sphereRadius); // Detect collision between ray and sphere -RLAPI bool CheckCollisionRaySphereEx(Ray ray, Vector3 spherePosition, float sphereRadius, - Vector3 *collisionPoint); // Detect collision between ray and sphere, returns collision point -RLAPI bool CheckCollisionRayBox(Ray ray, BoundingBox box); // Detect collision between ray and box -RLAPI RayHitInfo GetCollisionRayMesh(Ray ray, Mesh *mesh); // Get collision info between ray and mesh -RLAPI RayHitInfo GetCollisionRayTriangle(Ray ray, Vector3 p1, Vector3 p2, Vector3 p3); // Get collision info between ray and triangle -RLAPI RayHitInfo GetCollisionRayGround(Ray ray, float groundHeight); // Get collision info between ray and ground plane (Y-normal plane) - -//------------------------------------------------------------------------------------ -// Shaders System Functions (Module: rlgl) -// NOTE: This functions are useless when using OpenGL 1.1 -//------------------------------------------------------------------------------------ - -// Shader loading/unloading functions -RLAPI char *LoadText(const char *fileName); // Load chars array from text file -RLAPI Shader LoadShader(char *vsFileName, char *fsFileName); // Load shader from files and bind default locations -RLAPI void UnloadShader(Shader shader); // Unload shader from GPU memory (VRAM) - -RLAPI Shader GetShaderDefault(void); // Get default shader -RLAPI Texture2D GetTextureDefault(void); // Get default texture - -// Shader configuration functions -RLAPI int GetShaderLocation(Shader shader, const char *uniformName); // Get shader uniform location -RLAPI void SetShaderValue(Shader shader, int uniformLoc, float *value, int size); // Set shader uniform value (float) -RLAPI void SetShaderValuei(Shader shader, int uniformLoc, int *value, int size); // Set shader uniform value (int) -RLAPI void SetShaderValueMatrix(Shader shader, int uniformLoc, Matrix mat); // Set shader uniform value (matrix 4x4) -RLAPI void SetMatrixProjection(Matrix proj); // Set a custom projection matrix (replaces internal projection matrix) -RLAPI void SetMatrixModelview(Matrix view); // Set a custom modelview matrix (replaces internal modelview matrix) - -// Texture maps generation (PBR) -// NOTE: Required shaders should be provided -RLAPI Texture2D GenTextureCubemap(Shader shader, Texture2D skyHDR, int size); // Generate cubemap texture from HDR texture -RLAPI Texture2D GenTextureIrradiance(Shader shader, Texture2D cubemap, int size); // Generate irradiance texture using cubemap data -RLAPI Texture2D GenTexturePrefilter(Shader shader, Texture2D cubemap, int size); // Generate prefilter texture using cubemap data -RLAPI Texture2D GenTextureBRDF(Shader shader, Texture2D cubemap, int size); // Generate BRDF texture using cubemap data - -// Shading begin/end functions -RLAPI void BeginShaderMode(Shader shader); // Begin custom shader drawing -RLAPI void EndShaderMode(void); // End custom shader drawing (use default shader) -RLAPI void BeginBlendMode(int mode); // Begin blending mode (alpha, additive, multiplied) -RLAPI void EndBlendMode(void); // End blending mode (reset to default: alpha blending) - -// VR control functions -VrDeviceInfo GetVrDeviceInfo(int vrDeviceType); // Get VR device information for some standard devices -void InitVrSimulator(VrDeviceInfo info); // Init VR simulator for selected device parameters -RLAPI void CloseVrSimulator(void); // Close VR simulator for current device -RLAPI bool IsVrSimulatorReady(void); // Detect if VR simulator is ready -RLAPI void UpdateVrTracking(Camera *camera); // Update VR tracking (position and orientation) and camera -RLAPI void ToggleVrMode(void); // Enable/Disable VR experience -RLAPI void BeginVrDrawing(void); // Begin VR simulator stereo rendering -RLAPI void EndVrDrawing(void); // End VR simulator stereo rendering - -//------------------------------------------------------------------------------------ -// Audio Loading and Playing Functions (Module: audio) -//------------------------------------------------------------------------------------ - -// Audio device management functions -RLAPI void InitAudioDevice(void); // Initialize audio device and context -RLAPI void CloseAudioDevice(void); // Close the audio device and context -RLAPI bool IsAudioDeviceReady(void); // Check if audio device has been initialized successfully -RLAPI void SetMasterVolume(float volume); // Set master volume (listener) - -// Wave/Sound loading/unloading functions -RLAPI Wave LoadWave(const char *fileName); // Load wave data from file -RLAPI Wave LoadWaveEx(void *data, int sampleCount, int sampleRate, int sampleSize, int channels); // Load wave data from raw array data -RLAPI Sound LoadSound(const char *fileName); // Load sound from file -RLAPI Sound LoadSoundFromWave(Wave wave); // Load sound from wave data -RLAPI void UpdateSound(Sound sound, const void *data, int samplesCount);// Update sound buffer with new data -RLAPI void UnloadWave(Wave wave); // Unload wave data -RLAPI void UnloadSound(Sound sound); // Unload sound - -// Wave/Sound management functions -RLAPI void PlaySound(Sound sound); // Play a sound -RLAPI void PauseSound(Sound sound); // Pause a sound -RLAPI void ResumeSound(Sound sound); // Resume a paused sound -RLAPI void StopSound(Sound sound); // Stop playing a sound -RLAPI bool IsSoundPlaying(Sound sound); // Check if a sound is currently playing -RLAPI void SetSoundVolume(Sound sound, float volume); // Set volume for a sound (1.0 is max level) -RLAPI void SetSoundPitch(Sound sound, float pitch); // Set pitch for a sound (1.0 is base level) -RLAPI void WaveFormat(Wave *wave, int sampleRate, int sampleSize, int channels); // Convert wave data to desired format -RLAPI Wave WaveCopy(Wave wave); // Copy a wave to a new wave -RLAPI void WaveCrop(Wave *wave, int initSample, int finalSample); // Crop a wave to defined samples range -RLAPI float *GetWaveData(Wave wave); // Get samples data from wave as a floats array - -// Music management functions -RLAPI Music LoadMusicStream(const char *fileName); // Load music stream from file -RLAPI void UnloadMusicStream(Music music); // Unload music stream -RLAPI void PlayMusicStream(Music music); // Start music playing -RLAPI void UpdateMusicStream(Music music); // Updates buffers for music streaming -RLAPI void StopMusicStream(Music music); // Stop music playing -RLAPI void PauseMusicStream(Music music); // Pause music playing -RLAPI void ResumeMusicStream(Music music); // Resume playing paused music -RLAPI bool IsMusicPlaying(Music music); // Check if music is playing -RLAPI void SetMusicVolume(Music music, float volume); // Set volume for music (1.0 is max level) -RLAPI void SetMusicPitch(Music music, float pitch); // Set pitch for a music (1.0 is base level) -RLAPI void SetMusicLoopCount(Music music, float count); // Set music loop count (loop repeats) -RLAPI float GetMusicTimeLength(Music music); // Get music time length (in seconds) -RLAPI float GetMusicTimePlayed(Music music); // Get current music time played (in seconds) - -// AudioStream management functions -RLAPI AudioStream InitAudioStream(unsigned int sampleRate, unsigned int sampleSize, - unsigned int channels); // Init audio stream (to stream raw audio pcm data) -RLAPI void UpdateAudioStream(AudioStream stream, const void *data, int samplesCount); // Update audio stream buffers with data -RLAPI void CloseAudioStream(AudioStream stream); // Close audio stream and free memory -RLAPI bool IsAudioBufferProcessed(AudioStream stream); // Check if any audio stream buffers requires refill -RLAPI void PlayAudioStream(AudioStream stream); // Play audio stream -RLAPI void PauseAudioStream(AudioStream stream); // Pause audio stream -RLAPI void ResumeAudioStream(AudioStream stream); // Resume audio stream -RLAPI void StopAudioStream(AudioStream stream); // Stop audio stream - -#ifdef __cplusplus -} -#endif - -#endif // RAYLIB_H diff --git a/game/src/libs/raylib/raylib.ico b/game/src/libs/raylib/raylib.ico deleted file mode 100644 index afeb12b..0000000 Binary files a/game/src/libs/raylib/raylib.ico and /dev/null differ diff --git a/game/src/libs/raylib/raylib.rc b/game/src/libs/raylib/raylib.rc deleted file mode 100644 index 89eb8e3..0000000 --- a/game/src/libs/raylib/raylib.rc +++ /dev/null @@ -1,27 +0,0 @@ -GLFW_ICON ICON "raylib.ico" - -1 VERSIONINFO -FILEVERSION 1,8,0,0 -PRODUCTVERSION 1,8,0,0 -BEGIN - BLOCK "StringFileInfo" - BEGIN - //BLOCK "080904E4" // English UK - BLOCK "040904E4" // English US - BEGIN - //VALUE "CompanyName", "My Company Name" - VALUE "FileDescription", "Created using raylib (www.raylib.com)" - VALUE "FileVersion", "1.8.0" - VALUE "InternalName", "raylib" - VALUE "LegalCopyright", "(c) 2017 Ramon Santamaria - @raysan5" - //VALUE "OriginalFilename", "raylib_app.exe" - VALUE "ProductName", "raylib game" - VALUE "ProductVersion", "1.8.0" - END - END - BLOCK "VarFileInfo" - BEGIN - //VALUE "Translation", 0x809, 1252 // English UK - VALUE "Translation", 0x409, 1252 // English US - END -END diff --git a/game/src/libs/raylib/raymath.h b/game/src/libs/raylib/raymath.h deleted file mode 100644 index fe0b894..0000000 --- a/game/src/libs/raylib/raymath.h +++ /dev/null @@ -1,1367 +0,0 @@ -/********************************************************************************************** -* -* raymath v1.1 - Math functions to work with Vector3, Matrix and Quaternions -* -* CONFIGURATION: -* -* #define RAYMATH_IMPLEMENTATION -* Generates the implementation of the library into the included file. -* If not defined, the library is in header only mode and can be included in other headers -* or source files without problems. But only ONE file should hold the implementation. -* -* #define RAYMATH_EXTERN_INLINE -* Inlines all functions code, so it runs faster. This requires lots of memory on system. -* -* #define RAYMATH_STANDALONE -* Avoid raylib.h header inclusion in this file. -* Vector3 and Matrix data types are defined internally in raymath module. -* -* -* LICENSE: zlib/libpng -* -* Copyright (c) 2015-2017 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. -* -* Permission is granted to anyone to use this software for any purpose, including commercial -* applications, and to alter it and redistribute it freely, subject to the following restrictions: -* -* 1. The origin of this software must not be misrepresented; you must not claim that you -* wrote the original software. If you use this software in a product, an acknowledgment -* in the product documentation would be appreciated but is not required. -* -* 2. Altered source versions must be plainly marked as such, and must not be misrepresented -* as being the original software. -* -* 3. This notice may not be removed or altered from any source distribution. -* -**********************************************************************************************/ - -#ifndef RAYMATH_H -#define RAYMATH_H - -//#define RAYMATH_STANDALONE // NOTE: To use raymath as standalone lib, just uncomment this line -//#define RAYMATH_EXTERN_INLINE // NOTE: To compile functions as static inline, uncomment this line - -#ifndef RAYMATH_STANDALONE - #include "raylib.h" // Required for structs: Vector3, Matrix -#endif - -#ifdef __cplusplus - #define RMEXTERN extern "C" // Functions visible from other files (no name mangling of functions in C++) -#else - #define RMEXTERN extern // Functions visible from other files -#endif - -#if defined(RAYMATH_EXTERN_INLINE) - #define RMDEF RMEXTERN inline // Functions are embeded inline (compiler generated code) -#else - #define RMDEF RMEXTERN -#endif - -//---------------------------------------------------------------------------------- -// Defines and Macros -//---------------------------------------------------------------------------------- -#ifndef PI - #define PI 3.14159265358979323846 -#endif - -#ifndef DEG2RAD - #define DEG2RAD (PI/180.0f) -#endif - -#ifndef RAD2DEG - #define RAD2DEG (180.0f/PI) -#endif - -//---------------------------------------------------------------------------------- -// Types and Structures Definition -//---------------------------------------------------------------------------------- - -#if defined(RAYMATH_STANDALONE) - // Vector2 type - typedef struct Vector2 { - float x; - float y; - } Vector2; - - // Vector3 type - typedef struct Vector3 { - float x; - float y; - float z; - } Vector3; - - // Matrix type (OpenGL style 4x4 - right handed, column major) - typedef struct Matrix { - float m0, m4, m8, m12; - float m1, m5, m9, m13; - float m2, m6, m10, m14; - float m3, m7, m11, m15; - } Matrix; -#endif - -// Quaternion type -typedef struct Quaternion { - float x; - float y; - float z; - float w; -} Quaternion; - -#ifndef RAYMATH_EXTERN_INLINE - -//------------------------------------------------------------------------------------ -// Functions Declaration - math utils -//------------------------------------------------------------------------------------ -RMDEF float Clamp(float value, float min, float max); // Clamp float value - -//------------------------------------------------------------------------------------ -// Functions Declaration to work with Vector2 -//------------------------------------------------------------------------------------ -RMDEF Vector2 Vector2Zero(void); // Vector with components value 0.0f -RMDEF Vector2 Vector2One(void); // Vector with components value 1.0f -RMDEF Vector2 Vector2Add(Vector2 v1, Vector2 v2); // Add two vectors (v1 + v2) -RMDEF Vector2 Vector2Subtract(Vector2 v1, Vector2 v2); // Subtract two vectors (v1 - v2) -RMDEF float Vector2Length(Vector2 v); // Calculate vector length -RMDEF float Vector2DotProduct(Vector2 v1, Vector2 v2); // Calculate two vectors dot product -RMDEF float Vector2Distance(Vector2 v1, Vector2 v2); // Calculate distance between two vectors -RMDEF float Vector2Angle(Vector2 v1, Vector2 v2); // Calculate angle between two vectors in X-axis -RMDEF void Vector2Scale(Vector2 *v, float scale); // Scale vector (multiply by value) -RMDEF void Vector2Negate(Vector2 *v); // Negate vector -RMDEF void Vector2Divide(Vector2 *v, float div); // Divide vector by a float value -RMDEF void Vector2Normalize(Vector2 *v); // Normalize provided vector - -//------------------------------------------------------------------------------------ -// Functions Declaration to work with Vector3 -//------------------------------------------------------------------------------------ -RMDEF Vector3 Vector3Zero(void); // Vector with components value 0.0f -RMDEF Vector3 Vector3One(void); // Vector with components value 1.0f -RMDEF Vector3 Vector3Add(Vector3 v1, Vector3 v2); // Add two vectors -RMDEF Vector3 Vector3Multiply(Vector3 v, float scalar); // Multiply vector by scalar -RMDEF Vector3 Vector3MultiplyV(Vector3 v1, Vector3 v2); // Multiply vector by vector -RMDEF Vector3 Vector3Subtract(Vector3 v1, Vector3 v2); // Substract two vectors -RMDEF Vector3 Vector3CrossProduct(Vector3 v1, Vector3 v2); // Calculate two vectors cross product -RMDEF Vector3 Vector3Perpendicular(Vector3 v); // Calculate one vector perpendicular vector -RMDEF float Vector3Length(const Vector3 v); // Calculate vector length -RMDEF float Vector3DotProduct(Vector3 v1, Vector3 v2); // Calculate two vectors dot product -RMDEF float Vector3Distance(Vector3 v1, Vector3 v2); // Calculate distance between two points -RMDEF void Vector3Scale(Vector3 *v, float scale); // Scale provided vector -RMDEF void Vector3Negate(Vector3 *v); // Negate provided vector (invert direction) -RMDEF void Vector3Normalize(Vector3 *v); // Normalize provided vector -RMDEF void Vector3Transform(Vector3 *v, Matrix mat); // Transforms a Vector3 by a given Matrix -RMDEF Vector3 Vector3Lerp(Vector3 v1, Vector3 v2, float amount); // Calculate linear interpolation between two vectors -RMDEF Vector3 Vector3Reflect(Vector3 vector, Vector3 normal); // Calculate reflected vector to normal -RMDEF Vector3 Vector3Min(Vector3 vec1, Vector3 vec2); // Return min value for each pair of components -RMDEF Vector3 Vector3Max(Vector3 vec1, Vector3 vec2); // Return max value for each pair of components -RMDEF Vector3 Vector3Barycenter(Vector3 p, Vector3 a, Vector3 b, Vector3 c); // Barycenter coords for p in triangle abc -RMDEF float *Vector3ToFloat(Vector3 vec); // Returns Vector3 as float array - -//------------------------------------------------------------------------------------ -// Functions Declaration to work with Matrix -//------------------------------------------------------------------------------------ -RMDEF float MatrixDeterminant(Matrix mat); // Compute matrix determinant -RMDEF float MatrixTrace(Matrix mat); // Returns the trace of the matrix (sum of the values along the diagonal) -RMDEF void MatrixTranspose(Matrix *mat); // Transposes provided matrix -RMDEF void MatrixInvert(Matrix *mat); // Invert provided matrix -RMDEF void MatrixNormalize(Matrix *mat); // Normalize provided matrix -RMDEF Matrix MatrixIdentity(void); // Returns identity matrix -RMDEF Matrix MatrixAdd(Matrix left, Matrix right); // Add two matrices -RMDEF Matrix MatrixSubstract(Matrix left, Matrix right); // Substract two matrices (left - right) -RMDEF Matrix MatrixTranslate(float x, float y, float z); // Returns translation matrix -RMDEF Matrix MatrixRotate(Vector3 axis, float angle); // Returns rotation matrix for an angle around an specified axis (angle in radians) -RMDEF Matrix MatrixRotateX(float angle); // Returns x-rotation matrix (angle in radians) -RMDEF Matrix MatrixRotateY(float angle); // Returns y-rotation matrix (angle in radians) -RMDEF Matrix MatrixRotateZ(float angle); // Returns z-rotation matrix (angle in radians) -RMDEF Matrix MatrixScale(float x, float y, float z); // Returns scaling matrix -RMDEF Matrix MatrixMultiply(Matrix left, Matrix right); // Returns two matrix multiplication -RMDEF Matrix MatrixFrustum(double left, double right, double bottom, double top, double near, double far); // Returns perspective projection matrix -RMDEF Matrix MatrixPerspective(double fovy, double aspect, double near, double far); // Returns perspective projection matrix -RMDEF Matrix MatrixOrtho(double left, double right, double bottom, double top, double near, double far); // Returns orthographic projection matrix -RMDEF Matrix MatrixLookAt(Vector3 position, Vector3 target, Vector3 up); // Returns camera look-at matrix (view matrix) -RMDEF float *MatrixToFloat(Matrix mat); // Returns float array of Matrix data - -//------------------------------------------------------------------------------------ -// Functions Declaration to work with Quaternions -//------------------------------------------------------------------------------------ -RMDEF Quaternion QuaternionIdentity(void); // Returns identity quaternion -RMDEF float QuaternionLength(Quaternion quat); // Compute the length of a quaternion -RMDEF void QuaternionNormalize(Quaternion *q); // Normalize provided quaternion -RMDEF void QuaternionInvert(Quaternion *quat); // Invert provided quaternion -RMDEF Quaternion QuaternionMultiply(Quaternion q1, Quaternion q2); // Calculate two quaternion multiplication -RMDEF Quaternion QuaternionLerp(Quaternion q1, Quaternion q2, float amount); // Calculate linear interpolation between two quaternions -RMDEF Quaternion QuaternionSlerp(Quaternion q1, Quaternion q2, float amount); // Calculates spherical linear interpolation between two quaternions -RMDEF Quaternion QuaternionNlerp(Quaternion q1, Quaternion q2, float amount); // Calculate slerp-optimized interpolation between two quaternions -RMDEF Quaternion QuaternionFromVector3ToVector3(Vector3 from, Vector3 to); // Calculate quaternion based on the rotation from one vector to another -RMDEF Quaternion QuaternionFromMatrix(Matrix matrix); // Returns a quaternion for a given rotation matrix -RMDEF Matrix QuaternionToMatrix(Quaternion q); // Returns a matrix for a given quaternion -RMDEF Quaternion QuaternionFromAxisAngle(Vector3 axis, float angle); // Returns rotation quaternion for an angle and axis -RMDEF void QuaternionToAxisAngle(Quaternion q, Vector3 *outAxis, float *outAngle); // Returns the rotation angle and axis for a given quaternion -RMDEF Quaternion QuaternionFromEuler(float roll, float pitch, float yaw); // Returns he quaternion equivalent to Euler angles -RMDEF Vector3 QuaternionToEuler(Quaternion q); // Return the Euler angles equivalent to quaternion (roll, pitch, yaw) -RMDEF void QuaternionTransform(Quaternion *q, Matrix mat); // Transform a quaternion given a transformation matrix - -#endif // notdef RAYMATH_EXTERN_INLINE - -#endif // RAYMATH_H -//////////////////////////////////////////////////////////////////// end of header file - -#if defined(RAYMATH_IMPLEMENTATION) || defined(RAYMATH_EXTERN_INLINE) - -#include // Required for: sinf(), cosf(), tan(), fabs() - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Utils math -//---------------------------------------------------------------------------------- - -// Clamp float value -RMDEF float Clamp(float value, float min, float max) -{ - const float res = value < min ? min : value; - return res > max ? max : res; -} - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Vector2 math -//---------------------------------------------------------------------------------- - -// Vector with components value 0.0f -RMDEF Vector2 Vector2Zero(void) { return (Vector2){ 0.0f, 0.0f }; } - -// Vector with components value 1.0f -RMDEF Vector2 Vector2One(void) { return (Vector2){ 1.0f, 1.0f }; } - -// Add two vectors (v1 + v2) -RMDEF Vector2 Vector2Add(Vector2 v1, Vector2 v2) -{ - return (Vector2){ v1.x + v2.x, v1.y + v2.y }; -} - -// Subtract two vectors (v1 - v2) -RMDEF Vector2 Vector2Subtract(Vector2 v1, Vector2 v2) -{ - return (Vector2){ v1.x - v2.x, v1.y - v2.y }; -} - -// Calculate vector length -RMDEF float Vector2Length(Vector2 v) -{ - return sqrtf((v.x*v.x) + (v.y*v.y)); -} - -// Calculate two vectors dot product -RMDEF float Vector2DotProduct(Vector2 v1, Vector2 v2) -{ - return (v1.x*v2.x + v1.y*v2.y); -} - -// Calculate distance between two vectors -RMDEF float Vector2Distance(Vector2 v1, Vector2 v2) -{ - return sqrtf((v1.x - v2.x)*(v1.x - v2.x) + (v1.y - v2.y)*(v1.y - v2.y)); -} - -// Calculate angle from two vectors in X-axis -RMDEF float Vector2Angle(Vector2 v1, Vector2 v2) -{ - float angle = atan2f(v2.y - v1.y, v2.x - v1.x)*(180.0f/PI); - - if (angle < 0) angle += 360.0f; - - return angle; -} - -// Scale vector (multiply by value) -RMDEF void Vector2Scale(Vector2 *v, float scale) -{ - v->x *= scale; - v->y *= scale; -} - -// Negate vector -RMDEF void Vector2Negate(Vector2 *v) -{ - v->x = -v->x; - v->y = -v->y; -} - -// Divide vector by a float value -RMDEF void Vector2Divide(Vector2 *v, float div) -{ - *v = (Vector2){v->x/div, v->y/div}; -} - -// Normalize provided vector -RMDEF void Vector2Normalize(Vector2 *v) -{ - Vector2Divide(v, Vector2Length(*v)); -} - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Vector3 math -//---------------------------------------------------------------------------------- - -// Vector with components value 0.0f -RMDEF Vector3 Vector3Zero(void) { return (Vector3){ 0.0f, 0.0f, 0.0f }; } - -// Vector with components value 1.0f -RMDEF Vector3 Vector3One(void) { return (Vector3){ 1.0f, 1.0f, 1.0f }; } - -// Add two vectors -RMDEF Vector3 Vector3Add(Vector3 v1, Vector3 v2) -{ - return (Vector3){ v1.x + v2.x, v1.y + v2.y, v1.z + v2.z }; -} - -// Substract two vectors -RMDEF Vector3 Vector3Subtract(Vector3 v1, Vector3 v2) -{ - return (Vector3){ v1.x - v2.x, v1.y - v2.y, v1.z - v2.z }; -} - -// Multiply vector by scalar -RMDEF Vector3 Vector3Multiply(Vector3 v, float scalar) -{ - v.x *= scalar; - v.y *= scalar; - v.z *= scalar; - - return v; -} - -// Multiply vector by vector -RMDEF Vector3 Vector3MultiplyV(Vector3 v1, Vector3 v2) -{ - Vector3 result; - - result.x = v1.x * v2.x; - result.y = v1.y * v2.y; - result.z = v1.z * v2.z; - - return result; -} - -// Calculate two vectors cross product -RMDEF Vector3 Vector3CrossProduct(Vector3 v1, Vector3 v2) -{ - Vector3 result; - - result.x = v1.y*v2.z - v1.z*v2.y; - result.y = v1.z*v2.x - v1.x*v2.z; - result.z = v1.x*v2.y - v1.y*v2.x; - - return result; -} - -// Calculate one vector perpendicular vector -RMDEF Vector3 Vector3Perpendicular(Vector3 v) -{ - Vector3 result; - - float min = fabsf(v.x); - Vector3 cardinalAxis = {1.0f, 0.0f, 0.0f}; - - if (fabsf(v.y) < min) - { - min = fabsf(v.y); - cardinalAxis = (Vector3){0.0f, 1.0f, 0.0f}; - } - - if (fabsf(v.z) < min) - { - cardinalAxis = (Vector3){0.0f, 0.0f, 1.0f}; - } - - result = Vector3CrossProduct(v, cardinalAxis); - - return result; -} - -// Calculate vector length -RMDEF float Vector3Length(const Vector3 v) -{ - return sqrtf(v.x*v.x + v.y*v.y + v.z*v.z); -} - -// Calculate two vectors dot product -RMDEF float Vector3DotProduct(Vector3 v1, Vector3 v2) -{ - return (v1.x*v2.x + v1.y*v2.y + v1.z*v2.z); -} - -// Calculate distance between two vectors -RMDEF float Vector3Distance(Vector3 v1, Vector3 v2) -{ - float dx = v2.x - v1.x; - float dy = v2.y - v1.y; - float dz = v2.z - v1.z; - - return sqrtf(dx*dx + dy*dy + dz*dz); -} - -// Scale provided vector -RMDEF void Vector3Scale(Vector3 *v, float scale) -{ - v->x *= scale; - v->y *= scale; - v->z *= scale; -} - -// Negate provided vector (invert direction) -RMDEF void Vector3Negate(Vector3 *v) -{ - v->x = -v->x; - v->y = -v->y; - v->z = -v->z; -} - -// Normalize provided vector -RMDEF void Vector3Normalize(Vector3 *v) -{ - float length, ilength; - - length = Vector3Length(*v); - - if (length == 0.0f) length = 1.0f; - - ilength = 1.0f/length; - - v->x *= ilength; - v->y *= ilength; - v->z *= ilength; -} - -// Transforms a Vector3 by a given Matrix -RMDEF void Vector3Transform(Vector3 *v, Matrix mat) -{ - float x = v->x; - float y = v->y; - float z = v->z; - - v->x = mat.m0*x + mat.m4*y + mat.m8*z + mat.m12; - v->y = mat.m1*x + mat.m5*y + mat.m9*z + mat.m13; - v->z = mat.m2*x + mat.m6*y + mat.m10*z + mat.m14; -}; - -// Calculate linear interpolation between two vectors -RMDEF Vector3 Vector3Lerp(Vector3 v1, Vector3 v2, float amount) -{ - Vector3 result; - - result.x = v1.x + amount*(v2.x - v1.x); - result.y = v1.y + amount*(v2.y - v1.y); - result.z = v1.z + amount*(v2.z - v1.z); - - return result; -} - -// Calculate reflected vector to normal -RMDEF Vector3 Vector3Reflect(Vector3 vector, Vector3 normal) -{ - // I is the original vector - // N is the normal of the incident plane - // R = I - (2*N*( DotProduct[ I,N] )) - - Vector3 result; - - float dotProduct = Vector3DotProduct(vector, normal); - - result.x = vector.x - (2.0f*normal.x)*dotProduct; - result.y = vector.y - (2.0f*normal.y)*dotProduct; - result.z = vector.z - (2.0f*normal.z)*dotProduct; - - return result; -} - -// Return min value for each pair of components -RMDEF Vector3 Vector3Min(Vector3 vec1, Vector3 vec2) -{ - Vector3 result; - - result.x = fminf(vec1.x, vec2.x); - result.y = fminf(vec1.y, vec2.y); - result.z = fminf(vec1.z, vec2.z); - - return result; -} - -// Return max value for each pair of components -RMDEF Vector3 Vector3Max(Vector3 vec1, Vector3 vec2) -{ - Vector3 result; - - result.x = fmaxf(vec1.x, vec2.x); - result.y = fmaxf(vec1.y, vec2.y); - result.z = fmaxf(vec1.z, vec2.z); - - return result; -} - -// Compute barycenter coordinates (u, v, w) for point p with respect to triangle (a, b, c) -// NOTE: Assumes P is on the plane of the triangle -RMDEF Vector3 Vector3Barycenter(Vector3 p, Vector3 a, Vector3 b, Vector3 c) -{ - //Vector v0 = b - a, v1 = c - a, v2 = p - a; - - Vector3 v0 = Vector3Subtract(b, a); - Vector3 v1 = Vector3Subtract(c, a); - Vector3 v2 = Vector3Subtract(p, a); - float d00 = Vector3DotProduct(v0, v0); - float d01 = Vector3DotProduct(v0, v1); - float d11 = Vector3DotProduct(v1, v1); - float d20 = Vector3DotProduct(v2, v0); - float d21 = Vector3DotProduct(v2, v1); - - float denom = d00*d11 - d01*d01; - - Vector3 result; - - result.y = (d11*d20 - d01*d21)/denom; - result.z = (d00*d21 - d01*d20)/denom; - result.x = 1.0f - (result.z + result.y); - - return result; -} - -// Returns Vector3 as float array -RMDEF float *Vector3ToFloat(Vector3 vec) -{ - static float buffer[3]; - - buffer[0] = vec.x; - buffer[1] = vec.y; - buffer[2] = vec.z; - - return buffer; -} - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Matrix math -//---------------------------------------------------------------------------------- - -// Compute matrix determinant -RMDEF float MatrixDeterminant(Matrix mat) -{ - float result; - - // Cache the matrix values (speed optimization) - float a00 = mat.m0, a01 = mat.m1, a02 = mat.m2, a03 = mat.m3; - float a10 = mat.m4, a11 = mat.m5, a12 = mat.m6, a13 = mat.m7; - float a20 = mat.m8, a21 = mat.m9, a22 = mat.m10, a23 = mat.m11; - float a30 = mat.m12, a31 = mat.m13, a32 = mat.m14, a33 = mat.m15; - - result = a30*a21*a12*a03 - a20*a31*a12*a03 - a30*a11*a22*a03 + a10*a31*a22*a03 + - a20*a11*a32*a03 - a10*a21*a32*a03 - a30*a21*a02*a13 + a20*a31*a02*a13 + - a30*a01*a22*a13 - a00*a31*a22*a13 - a20*a01*a32*a13 + a00*a21*a32*a13 + - a30*a11*a02*a23 - a10*a31*a02*a23 - a30*a01*a12*a23 + a00*a31*a12*a23 + - a10*a01*a32*a23 - a00*a11*a32*a23 - a20*a11*a02*a33 + a10*a21*a02*a33 + - a20*a01*a12*a33 - a00*a21*a12*a33 - a10*a01*a22*a33 + a00*a11*a22*a33; - - return result; -} - -// Returns the trace of the matrix (sum of the values along the diagonal) -RMDEF float MatrixTrace(Matrix mat) -{ - return (mat.m0 + mat.m5 + mat.m10 + mat.m15); -} - -// Transposes provided matrix -RMDEF void MatrixTranspose(Matrix *mat) -{ - Matrix temp; - - temp.m0 = mat->m0; - temp.m1 = mat->m4; - temp.m2 = mat->m8; - temp.m3 = mat->m12; - temp.m4 = mat->m1; - temp.m5 = mat->m5; - temp.m6 = mat->m9; - temp.m7 = mat->m13; - temp.m8 = mat->m2; - temp.m9 = mat->m6; - temp.m10 = mat->m10; - temp.m11 = mat->m14; - temp.m12 = mat->m3; - temp.m13 = mat->m7; - temp.m14 = mat->m11; - temp.m15 = mat->m15; - - *mat = temp; -} - -// Invert provided matrix -RMDEF void MatrixInvert(Matrix *mat) -{ - Matrix temp; - - // Cache the matrix values (speed optimization) - float a00 = mat->m0, a01 = mat->m1, a02 = mat->m2, a03 = mat->m3; - float a10 = mat->m4, a11 = mat->m5, a12 = mat->m6, a13 = mat->m7; - float a20 = mat->m8, a21 = mat->m9, a22 = mat->m10, a23 = mat->m11; - float a30 = mat->m12, a31 = mat->m13, a32 = mat->m14, a33 = mat->m15; - - float b00 = a00*a11 - a01*a10; - float b01 = a00*a12 - a02*a10; - float b02 = a00*a13 - a03*a10; - float b03 = a01*a12 - a02*a11; - float b04 = a01*a13 - a03*a11; - float b05 = a02*a13 - a03*a12; - float b06 = a20*a31 - a21*a30; - float b07 = a20*a32 - a22*a30; - float b08 = a20*a33 - a23*a30; - float b09 = a21*a32 - a22*a31; - float b10 = a21*a33 - a23*a31; - float b11 = a22*a33 - a23*a32; - - // Calculate the invert determinant (inlined to avoid double-caching) - float invDet = 1.0f/(b00*b11 - b01*b10 + b02*b09 + b03*b08 - b04*b07 + b05*b06); - - temp.m0 = (a11*b11 - a12*b10 + a13*b09)*invDet; - temp.m1 = (-a01*b11 + a02*b10 - a03*b09)*invDet; - temp.m2 = (a31*b05 - a32*b04 + a33*b03)*invDet; - temp.m3 = (-a21*b05 + a22*b04 - a23*b03)*invDet; - temp.m4 = (-a10*b11 + a12*b08 - a13*b07)*invDet; - temp.m5 = (a00*b11 - a02*b08 + a03*b07)*invDet; - temp.m6 = (-a30*b05 + a32*b02 - a33*b01)*invDet; - temp.m7 = (a20*b05 - a22*b02 + a23*b01)*invDet; - temp.m8 = (a10*b10 - a11*b08 + a13*b06)*invDet; - temp.m9 = (-a00*b10 + a01*b08 - a03*b06)*invDet; - temp.m10 = (a30*b04 - a31*b02 + a33*b00)*invDet; - temp.m11 = (-a20*b04 + a21*b02 - a23*b00)*invDet; - temp.m12 = (-a10*b09 + a11*b07 - a12*b06)*invDet; - temp.m13 = (a00*b09 - a01*b07 + a02*b06)*invDet; - temp.m14 = (-a30*b03 + a31*b01 - a32*b00)*invDet; - temp.m15 = (a20*b03 - a21*b01 + a22*b00)*invDet; - - *mat = temp; -} - -// Normalize provided matrix -RMDEF void MatrixNormalize(Matrix *mat) -{ - float det = MatrixDeterminant(*mat); - - mat->m0 /= det; - mat->m1 /= det; - mat->m2 /= det; - mat->m3 /= det; - mat->m4 /= det; - mat->m5 /= det; - mat->m6 /= det; - mat->m7 /= det; - mat->m8 /= det; - mat->m9 /= det; - mat->m10 /= det; - mat->m11 /= det; - mat->m12 /= det; - mat->m13 /= det; - mat->m14 /= det; - mat->m15 /= det; -} - -// Returns identity matrix -RMDEF Matrix MatrixIdentity(void) -{ - Matrix result = { 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f }; - - return result; -} - -// Add two matrices -RMDEF Matrix MatrixAdd(Matrix left, Matrix right) -{ - Matrix result = MatrixIdentity(); - - result.m0 = left.m0 + right.m0; - result.m1 = left.m1 + right.m1; - result.m2 = left.m2 + right.m2; - result.m3 = left.m3 + right.m3; - result.m4 = left.m4 + right.m4; - result.m5 = left.m5 + right.m5; - result.m6 = left.m6 + right.m6; - result.m7 = left.m7 + right.m7; - result.m8 = left.m8 + right.m8; - result.m9 = left.m9 + right.m9; - result.m10 = left.m10 + right.m10; - result.m11 = left.m11 + right.m11; - result.m12 = left.m12 + right.m12; - result.m13 = left.m13 + right.m13; - result.m14 = left.m14 + right.m14; - result.m15 = left.m15 + right.m15; - - return result; -} - -// Substract two matrices (left - right) -RMDEF Matrix MatrixSubstract(Matrix left, Matrix right) -{ - Matrix result = MatrixIdentity(); - - result.m0 = left.m0 - right.m0; - result.m1 = left.m1 - right.m1; - result.m2 = left.m2 - right.m2; - result.m3 = left.m3 - right.m3; - result.m4 = left.m4 - right.m4; - result.m5 = left.m5 - right.m5; - result.m6 = left.m6 - right.m6; - result.m7 = left.m7 - right.m7; - result.m8 = left.m8 - right.m8; - result.m9 = left.m9 - right.m9; - result.m10 = left.m10 - right.m10; - result.m11 = left.m11 - right.m11; - result.m12 = left.m12 - right.m12; - result.m13 = left.m13 - right.m13; - result.m14 = left.m14 - right.m14; - result.m15 = left.m15 - right.m15; - - return result; -} - -// Returns translation matrix -RMDEF Matrix MatrixTranslate(float x, float y, float z) -{ - Matrix result = { 1.0f, 0.0f, 0.0f, x, - 0.0f, 1.0f, 0.0f, y, - 0.0f, 0.0f, 1.0f, z, - 0.0f, 0.0f, 0.0f, 1.0f }; - - return result; -} - -// Create rotation matrix from axis and angle -// NOTE: Angle should be provided in radians -RMDEF Matrix MatrixRotate(Vector3 axis, float angle) -{ - Matrix result; - - Matrix mat = MatrixIdentity(); - - float x = axis.x, y = axis.y, z = axis.z; - - float length = sqrtf(x*x + y*y + z*z); - - if ((length != 1.0f) && (length != 0.0f)) - { - length = 1.0f/length; - x *= length; - y *= length; - z *= length; - } - - float sinres = sinf(angle); - float cosres = cosf(angle); - float t = 1.0f - cosres; - - // Cache some matrix values (speed optimization) - float a00 = mat.m0, a01 = mat.m1, a02 = mat.m2, a03 = mat.m3; - float a10 = mat.m4, a11 = mat.m5, a12 = mat.m6, a13 = mat.m7; - float a20 = mat.m8, a21 = mat.m9, a22 = mat.m10, a23 = mat.m11; - - // Construct the elements of the rotation matrix - float b00 = x*x*t + cosres, b01 = y*x*t + z*sinres, b02 = z*x*t - y*sinres; - float b10 = x*y*t - z*sinres, b11 = y*y*t + cosres, b12 = z*y*t + x*sinres; - float b20 = x*z*t + y*sinres, b21 = y*z*t - x*sinres, b22 = z*z*t + cosres; - - // Perform rotation-specific matrix multiplication - result.m0 = a00*b00 + a10*b01 + a20*b02; - result.m1 = a01*b00 + a11*b01 + a21*b02; - result.m2 = a02*b00 + a12*b01 + a22*b02; - result.m3 = a03*b00 + a13*b01 + a23*b02; - result.m4 = a00*b10 + a10*b11 + a20*b12; - result.m5 = a01*b10 + a11*b11 + a21*b12; - result.m6 = a02*b10 + a12*b11 + a22*b12; - result.m7 = a03*b10 + a13*b11 + a23*b12; - result.m8 = a00*b20 + a10*b21 + a20*b22; - result.m9 = a01*b20 + a11*b21 + a21*b22; - result.m10 = a02*b20 + a12*b21 + a22*b22; - result.m11 = a03*b20 + a13*b21 + a23*b22; - result.m12 = mat.m12; - result.m13 = mat.m13; - result.m14 = mat.m14; - result.m15 = mat.m15; - - return result; -} - -// Returns x-rotation matrix (angle in radians) -RMDEF Matrix MatrixRotateX(float angle) -{ - Matrix result = MatrixIdentity(); - - float cosres = cosf(angle); - float sinres = sinf(angle); - - result.m5 = cosres; - result.m6 = -sinres; - result.m9 = sinres; - result.m10 = cosres; - - return result; -} - -// Returns y-rotation matrix (angle in radians) -RMDEF Matrix MatrixRotateY(float angle) -{ - Matrix result = MatrixIdentity(); - - float cosres = cosf(angle); - float sinres = sinf(angle); - - result.m0 = cosres; - result.m2 = sinres; - result.m8 = -sinres; - result.m10 = cosres; - - return result; -} - -// Returns z-rotation matrix (angle in radians) -RMDEF Matrix MatrixRotateZ(float angle) -{ - Matrix result = MatrixIdentity(); - - float cosres = cosf(angle); - float sinres = sinf(angle); - - result.m0 = cosres; - result.m1 = -sinres; - result.m4 = sinres; - result.m5 = cosres; - - return result; -} - -// Returns scaling matrix -RMDEF Matrix MatrixScale(float x, float y, float z) -{ - Matrix result = { x, 0.0f, 0.0f, 0.0f, - 0.0f, y, 0.0f, 0.0f, - 0.0f, 0.0f, z, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f }; - - return result; -} - -// Returns two matrix multiplication -// NOTE: When multiplying matrices... the order matters! -RMDEF Matrix MatrixMultiply(Matrix left, Matrix right) -{ - Matrix result; - - result.m0 = left.m0*right.m0 + left.m1*right.m4 + left.m2*right.m8 + left.m3*right.m12; - result.m1 = left.m0*right.m1 + left.m1*right.m5 + left.m2*right.m9 + left.m3*right.m13; - result.m2 = left.m0*right.m2 + left.m1*right.m6 + left.m2*right.m10 + left.m3*right.m14; - result.m3 = left.m0*right.m3 + left.m1*right.m7 + left.m2*right.m11 + left.m3*right.m15; - result.m4 = left.m4*right.m0 + left.m5*right.m4 + left.m6*right.m8 + left.m7*right.m12; - result.m5 = left.m4*right.m1 + left.m5*right.m5 + left.m6*right.m9 + left.m7*right.m13; - result.m6 = left.m4*right.m2 + left.m5*right.m6 + left.m6*right.m10 + left.m7*right.m14; - result.m7 = left.m4*right.m3 + left.m5*right.m7 + left.m6*right.m11 + left.m7*right.m15; - result.m8 = left.m8*right.m0 + left.m9*right.m4 + left.m10*right.m8 + left.m11*right.m12; - result.m9 = left.m8*right.m1 + left.m9*right.m5 + left.m10*right.m9 + left.m11*right.m13; - result.m10 = left.m8*right.m2 + left.m9*right.m6 + left.m10*right.m10 + left.m11*right.m14; - result.m11 = left.m8*right.m3 + left.m9*right.m7 + left.m10*right.m11 + left.m11*right.m15; - result.m12 = left.m12*right.m0 + left.m13*right.m4 + left.m14*right.m8 + left.m15*right.m12; - result.m13 = left.m12*right.m1 + left.m13*right.m5 + left.m14*right.m9 + left.m15*right.m13; - result.m14 = left.m12*right.m2 + left.m13*right.m6 + left.m14*right.m10 + left.m15*right.m14; - result.m15 = left.m12*right.m3 + left.m13*right.m7 + left.m14*right.m11 + left.m15*right.m15; - - return result; -} - -// Returns perspective projection matrix -RMDEF Matrix MatrixFrustum(double left, double right, double bottom, double top, double near, double far) -{ - Matrix result; - - float rl = (right - left); - float tb = (top - bottom); - float fn = (far - near); - - result.m0 = (near*2.0f)/rl; - result.m1 = 0.0f; - result.m2 = 0.0f; - result.m3 = 0.0f; - - result.m4 = 0.0f; - result.m5 = (near*2.0f)/tb; - result.m6 = 0.0f; - result.m7 = 0.0f; - - result.m8 = (right + left)/rl; - result.m9 = (top + bottom)/tb; - result.m10 = -(far + near)/fn; - result.m11 = -1.0f; - - result.m12 = 0.0f; - result.m13 = 0.0f; - result.m14 = -(far*near*2.0f)/fn; - result.m15 = 0.0f; - - return result; -} - -// Returns perspective projection matrix -// NOTE: Angle should be provided in radians -RMDEF Matrix MatrixPerspective(double fovy, double aspect, double near, double far) -{ - double top = near*tan(fovy*0.5); - double right = top*aspect; - - return MatrixFrustum(-right, right, -top, top, near, far); -} - -// Returns orthographic projection matrix -RMDEF Matrix MatrixOrtho(double left, double right, double bottom, double top, double near, double far) -{ - Matrix result; - - float rl = (right - left); - float tb = (top - bottom); - float fn = (far - near); - - result.m0 = 2.0f/rl; - result.m1 = 0.0f; - result.m2 = 0.0f; - result.m3 = 0.0f; - result.m4 = 0.0f; - result.m5 = 2.0f/tb; - result.m6 = 0.0f; - result.m7 = 0.0f; - result.m8 = 0.0f; - result.m9 = 0.0f; - result.m10 = -2.0f/fn; - result.m11 = 0.0f; - result.m12 = -(left + right)/rl; - result.m13 = -(top + bottom)/tb; - result.m14 = -(far + near)/fn; - result.m15 = 1.0f; - - return result; -} - -// Returns camera look-at matrix (view matrix) -RMDEF Matrix MatrixLookAt(Vector3 eye, Vector3 target, Vector3 up) -{ - Matrix result; - - Vector3 z = Vector3Subtract(eye, target); - Vector3Normalize(&z); - Vector3 x = Vector3CrossProduct(up, z); - Vector3Normalize(&x); - Vector3 y = Vector3CrossProduct(z, x); - Vector3Normalize(&y); - - result.m0 = x.x; - result.m1 = x.y; - result.m2 = x.z; - result.m3 = 0.0f; - result.m4 = y.x; - result.m5 = y.y; - result.m6 = y.z; - result.m7 = 0.0f; - result.m8 = z.x; - result.m9 = z.y; - result.m10 = z.z; - result.m11 = 0.0f; - result.m12 = eye.x; - result.m13 = eye.y; - result.m14 = eye.z; - result.m15 = 1.0f; - - MatrixInvert(&result); - - return result; -} - -// Returns float array of matrix data -RMDEF float *MatrixToFloat(Matrix mat) -{ - static float buffer[16]; - - buffer[0] = mat.m0; - buffer[1] = mat.m1; - buffer[2] = mat.m2; - buffer[3] = mat.m3; - buffer[4] = mat.m4; - buffer[5] = mat.m5; - buffer[6] = mat.m6; - buffer[7] = mat.m7; - buffer[8] = mat.m8; - buffer[9] = mat.m9; - buffer[10] = mat.m10; - buffer[11] = mat.m11; - buffer[12] = mat.m12; - buffer[13] = mat.m13; - buffer[14] = mat.m14; - buffer[15] = mat.m15; - - return buffer; -} - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Quaternion math -//---------------------------------------------------------------------------------- - -// Returns identity quaternion -RMDEF Quaternion QuaternionIdentity(void) -{ - return (Quaternion){ 0.0f, 0.0f, 0.0f, 1.0f }; -} - -// Computes the length of a quaternion -RMDEF float QuaternionLength(Quaternion quat) -{ - return sqrt(quat.x*quat.x + quat.y*quat.y + quat.z*quat.z + quat.w*quat.w); -} - -// Normalize provided quaternion -RMDEF void QuaternionNormalize(Quaternion *q) -{ - float length, ilength; - - length = QuaternionLength(*q); - - if (length == 0.0f) length = 1.0f; - - ilength = 1.0f/length; - - q->x *= ilength; - q->y *= ilength; - q->z *= ilength; - q->w *= ilength; -} - -// Invert provided quaternion -RMDEF void QuaternionInvert(Quaternion *quat) -{ - float length = QuaternionLength(*quat); - float lengthSq = length*length; - - if (lengthSq != 0.0) - { - float i = 1.0f/lengthSq; - - quat->x *= -i; - quat->y *= -i; - quat->z *= -i; - quat->w *= i; - } -} - -// Calculate two quaternion multiplication -RMDEF Quaternion QuaternionMultiply(Quaternion q1, Quaternion q2) -{ - Quaternion result; - - float qax = q1.x, qay = q1.y, qaz = q1.z, qaw = q1.w; - float qbx = q2.x, qby = q2.y, qbz = q2.z, qbw = q2.w; - - result.x = qax*qbw + qaw*qbx + qay*qbz - qaz*qby; - result.y = qay*qbw + qaw*qby + qaz*qbx - qax*qbz; - result.z = qaz*qbw + qaw*qbz + qax*qby - qay*qbx; - result.w = qaw*qbw - qax*qbx - qay*qby - qaz*qbz; - - return result; -} - -// Calculate linear interpolation between two quaternions -RMDEF Quaternion QuaternionLerp(Quaternion q1, Quaternion q2, float amount) -{ - Quaternion result; - - result.x = q1.x + amount*(q2.x - q1.x); - result.y = q1.y + amount*(q2.y - q1.y); - result.z = q1.z + amount*(q2.z - q1.z); - result.w = q1.w + amount*(q2.w - q1.w); - - return result; -} - -// Calculates spherical linear interpolation between two quaternions -RMDEF Quaternion QuaternionSlerp(Quaternion q1, Quaternion q2, float amount) -{ - Quaternion result; - - float cosHalfTheta = q1.x*q2.x + q1.y*q2.y + q1.z*q2.z + q1.w*q2.w; - - if (fabs(cosHalfTheta) >= 1.0f) result = q1; - else if (cosHalfTheta > 0.95f) result = QuaternionNlerp(q1, q2, amount); - else - { - float halfTheta = acos(cosHalfTheta); - float sinHalfTheta = sqrt(1.0f - cosHalfTheta*cosHalfTheta); - - if (fabs(sinHalfTheta) < 0.001f) - { - result.x = (q1.x*0.5f + q2.x*0.5f); - result.y = (q1.y*0.5f + q2.y*0.5f); - result.z = (q1.z*0.5f + q2.z*0.5f); - result.w = (q1.w*0.5f + q2.w*0.5f); - } - else - { - float ratioA = sinf((1 - amount)*halfTheta)/sinHalfTheta; - float ratioB = sinf(amount*halfTheta)/sinHalfTheta; - - result.x = (q1.x*ratioA + q2.x*ratioB); - result.y = (q1.y*ratioA + q2.y*ratioB); - result.z = (q1.z*ratioA + q2.z*ratioB); - result.w = (q1.w*ratioA + q2.w*ratioB); - } - } - - return result; -} - -// Calculate slerp-optimized interpolation between two quaternions -RMDEF Quaternion QuaternionNlerp(Quaternion q1, Quaternion q2, float amount) -{ - Quaternion result = QuaternionLerp(q1, q2, amount); - QuaternionNormalize(&result); - - return result; -} - -// Calculate quaternion based on the rotation from one vector to another -RMDEF Quaternion QuaternionFromVector3ToVector3(Vector3 from, Vector3 to) -{ - Quaternion q = { 0 }; - - float cos2Theta = Vector3DotProduct(from, to); - Vector3 cross = Vector3CrossProduct(from, to); - - q.x = cross.x; - q.y = cross.y; - q.z = cross.y; - q.w = 1.0f + cos2Theta; // NOTE: Added QuaternioIdentity() - - // Normalize to essentially nlerp the original and identity to 0.5 - QuaternionNormalize(&q); - - // Above lines are equivalent to: - //Quaternion result = QuaternionNlerp(q, QuaternionIdentity(), 0.5f); - - return q; -} - -// Returns a quaternion for a given rotation matrix -RMDEF Quaternion QuaternionFromMatrix(Matrix matrix) -{ - Quaternion result; - - float trace = MatrixTrace(matrix); - - if (trace > 0.0f) - { - float s = (float)sqrt(trace + 1)*2.0f; - float invS = 1.0f/s; - - result.w = s*0.25f; - result.x = (matrix.m6 - matrix.m9)*invS; - result.y = (matrix.m8 - matrix.m2)*invS; - result.z = (matrix.m1 - matrix.m4)*invS; - } - else - { - float m00 = matrix.m0, m11 = matrix.m5, m22 = matrix.m10; - - if (m00 > m11 && m00 > m22) - { - float s = (float)sqrt(1.0f + m00 - m11 - m22)*2.0f; - float invS = 1.0f/s; - - result.w = (matrix.m6 - matrix.m9)*invS; - result.x = s*0.25f; - result.y = (matrix.m4 + matrix.m1)*invS; - result.z = (matrix.m8 + matrix.m2)*invS; - } - else if (m11 > m22) - { - float s = (float)sqrt(1.0f + m11 - m00 - m22)*2.0f; - float invS = 1.0f/s; - - result.w = (matrix.m8 - matrix.m2)*invS; - result.x = (matrix.m4 + matrix.m1)*invS; - result.y = s*0.25f; - result.z = (matrix.m9 + matrix.m6)*invS; - } - else - { - float s = (float)sqrt(1.0f + m22 - m00 - m11)*2.0f; - float invS = 1.0f/s; - - result.w = (matrix.m1 - matrix.m4)*invS; - result.x = (matrix.m8 + matrix.m2)*invS; - result.y = (matrix.m9 + matrix.m6)*invS; - result.z = s*0.25f; - } - } - - return result; -} - -// Returns a matrix for a given quaternion -RMDEF Matrix QuaternionToMatrix(Quaternion q) -{ - Matrix result; - - float x = q.x, y = q.y, z = q.z, w = q.w; - - float x2 = x + x; - float y2 = y + y; - float z2 = z + z; - - float length = QuaternionLength(q); - float lengthSquared = length*length; - - float xx = x*x2/lengthSquared; - float xy = x*y2/lengthSquared; - float xz = x*z2/lengthSquared; - - float yy = y*y2/lengthSquared; - float yz = y*z2/lengthSquared; - float zz = z*z2/lengthSquared; - - float wx = w*x2/lengthSquared; - float wy = w*y2/lengthSquared; - float wz = w*z2/lengthSquared; - - result.m0 = 1.0f - (yy + zz); - result.m1 = xy - wz; - result.m2 = xz + wy; - result.m3 = 0.0f; - result.m4 = xy + wz; - result.m5 = 1.0f - (xx + zz); - result.m6 = yz - wx; - result.m7 = 0.0f; - result.m8 = xz - wy; - result.m9 = yz + wx; - result.m10 = 1.0f - (xx + yy); - result.m11 = 0.0f; - result.m12 = 0.0f; - result.m13 = 0.0f; - result.m14 = 0.0f; - result.m15 = 1.0f; - - return result; -} - -// Returns rotation quaternion for an angle and axis -// NOTE: angle must be provided in radians -RMDEF Quaternion QuaternionFromAxisAngle(Vector3 axis, float angle) -{ - Quaternion result = { 0.0f, 0.0f, 0.0f, 1.0f }; - - if (Vector3Length(axis) != 0.0f) - - angle *= 0.5f; - - Vector3Normalize(&axis); - - float sinres = sinf(angle); - float cosres = cosf(angle); - - result.x = axis.x*sinres; - result.y = axis.y*sinres; - result.z = axis.z*sinres; - result.w = cosres; - - QuaternionNormalize(&result); - - return result; -} - -// Returns the rotation angle and axis for a given quaternion -RMDEF void QuaternionToAxisAngle(Quaternion q, Vector3 *outAxis, float *outAngle) -{ - if (fabs(q.w) > 1.0f) QuaternionNormalize(&q); - - Vector3 resAxis = { 0.0f, 0.0f, 0.0f }; - float resAngle = 0.0f; - - resAngle = 2.0f*(float)acos(q.w); - float den = (float)sqrt(1.0f - q.w*q.w); - - if (den > 0.0001f) - { - resAxis.x = q.x/den; - resAxis.y = q.y/den; - resAxis.z = q.z/den; - } - else - { - // This occurs when the angle is zero. - // Not a problem: just set an arbitrary normalized axis. - resAxis.x = 1.0f; - } - - *outAxis = resAxis; - *outAngle = resAngle; -} - -// Returns he quaternion equivalent to Euler angles -RMDEF Quaternion QuaternionFromEuler(float roll, float pitch, float yaw) -{ - Quaternion q = { 0 }; - - float x0 = cosf(roll*0.5f); - float x1 = sinf(roll*0.5f); - float y0 = cosf(pitch*0.5f); - float y1 = sinf(pitch*0.5f); - float z0 = cosf(yaw*0.5f); - float z1 = sinf(yaw*0.5f); - - q.x = x1*y0*z0 - x0*y1*z1; - q.y = x0*y1*z0 + x1*y0*z1; - q.z = x0*y0*z1 - x1*y1*z0; - q.w = x0*y0*z0 + x1*y1*z1; - - return q; -} - -// Return the Euler angles equivalent to quaternion (roll, pitch, yaw) -// NOTE: Angles are returned in a Vector3 struct in degrees -RMDEF Vector3 QuaternionToEuler(Quaternion q) -{ - Vector3 v = { 0 }; - - // roll (x-axis rotation) - float x0 = 2.0f*(q.w*q.x + q.y*q.z); - float x1 = 1.0f - 2.0f*(q.x*q.x + q.y*q.y); - v.x = atan2f(x0, x1)*RAD2DEG; - - // pitch (y-axis rotation) - float y0 = 2.0f*(q.w*q.y - q.z*q.x); - y0 = y0 > 1.0f ? 1.0f : y0; - y0 = y0 < -1.0f ? -1.0f : y0; - v.y = asinf(y0)*RAD2DEG; - - // yaw (z-axis rotation) - float z0 = 2.0f*(q.w*q.z + q.x*q.y); - float z1 = 1.0f - 2.0f*(q.y*q.y + q.z*q.z); - v.z = atan2f(z0, z1)*RAD2DEG; - - return v; -} - -// Transform a quaternion given a transformation matrix -RMDEF void QuaternionTransform(Quaternion *q, Matrix mat) -{ - float x = q->x; - float y = q->y; - float z = q->z; - float w = q->w; - - q->x = mat.m0*x + mat.m4*y + mat.m8*z + mat.m12*w; - q->y = mat.m1*x + mat.m5*y + mat.m9*z + mat.m13*w; - q->z = mat.m2*x + mat.m6*y + mat.m10*z + mat.m14*w; - q->w = mat.m3*x + mat.m7*y + mat.m11*z + mat.m15*w; -} - -#endif // RAYMATH_IMPLEMENTATION diff --git a/game/src/libs/raylib/resources b/game/src/libs/raylib/resources deleted file mode 100644 index ca72504..0000000 Binary files a/game/src/libs/raylib/resources and /dev/null differ diff --git a/game/src/libs/raylib/rlgl.c b/game/src/libs/raylib/rlgl.c deleted file mode 100644 index 9e563ce..0000000 --- a/game/src/libs/raylib/rlgl.c +++ /dev/null @@ -1,4202 +0,0 @@ -/********************************************************************************************** -* -* rlgl - raylib OpenGL abstraction layer -* -* rlgl is a wrapper for multiple OpenGL versions (1.1, 2.1, 3.3 Core, ES 2.0) to -* pseudo-OpenGL 1.1 style functions (rlVertex, rlTranslate, rlRotate...). -* -* When chosing an OpenGL version greater than OpenGL 1.1, rlgl stores vertex data on internal -* VBO buffers (and VAOs if available). It requires calling 3 functions: -* rlglInit() - Initialize internal buffers and auxiliar resources -* rlglDraw() - Process internal buffers and send required draw calls -* rlglClose() - De-initialize internal buffers data and other auxiliar resources -* -* CONFIGURATION: -* -* #define GRAPHICS_API_OPENGL_11 -* #define GRAPHICS_API_OPENGL_21 -* #define GRAPHICS_API_OPENGL_33 -* #define GRAPHICS_API_OPENGL_ES2 -* Use selected OpenGL backend -* -* #define RLGL_STANDALONE -* Use rlgl as standalone library (no raylib dependency) -* -* #define SUPPORT_VR_SIMULATOR -* Support VR simulation functionality (stereo rendering) -* -* #define SUPPORT_DISTORTION_SHADER -* Include stereo rendering distortion shader (shader_distortion.h) -* -* DEPENDENCIES: -* raymath - 3D math functionality (Vector3, Matrix, Quaternion) -* GLAD - OpenGL extensions loading (OpenGL 3.3 Core only) -* -* -* LICENSE: zlib/libpng -* -* Copyright (c) 2014-2017 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. -* -* Permission is granted to anyone to use this software for any purpose, including commercial -* applications, and to alter it and redistribute it freely, subject to the following restrictions: -* -* 1. The origin of this software must not be misrepresented; you must not claim that you -* wrote the original software. If you use this software in a product, an acknowledgment -* in the product documentation would be appreciated but is not required. -* -* 2. Altered source versions must be plainly marked as such, and must not be misrepresented -* as being the original software. -* -* 3. This notice may not be removed or altered from any source distribution. -* -**********************************************************************************************/ - -// Default configuration flags (supported features) -//------------------------------------------------- -#define SUPPORT_VR_SIMULATOR -#define SUPPORT_DISTORTION_SHADER -//------------------------------------------------- - -#include "rlgl.h" - -#include // Required for: fopen(), fclose(), fread()... [Used only on LoadText()] -#include // Required for: malloc(), free(), rand() -#include // Required for: strcmp(), strlen(), strtok() [Used only in extensions loading] -#include // Required for: atan2() - -#if !defined(RLGL_STANDALONE) - #include "raymath.h" // Required for: Vector3 and Matrix functions -#endif - -#if defined(GRAPHICS_API_OPENGL_11) - #if defined(__APPLE__) - #include // OpenGL 1.1 library for OSX - #else - #include // OpenGL 1.1 library - #endif -#endif - -#if defined(GRAPHICS_API_OPENGL_21) - #define GRAPHICS_API_OPENGL_33 -#endif - -#if defined(GRAPHICS_API_OPENGL_33) - #if defined(__APPLE__) - #include // OpenGL 3 library for OSX - #else - #define GLAD_IMPLEMENTATION - #if defined(RLGL_STANDALONE) - #include "glad.h" // GLAD extensions loading library, includes OpenGL headers - #else - #include "external/glad.h" // GLAD extensions loading library, includes OpenGL headers - #endif - #endif -#endif - -#if defined(GRAPHICS_API_OPENGL_ES2) - #include // EGL library - #include // OpenGL ES 2.0 library - #include // OpenGL ES 2.0 extensions library -#endif - -#if defined(RLGL_STANDALONE) - #include // Required for: va_list, va_start(), vfprintf(), va_end() [Used only on TraceLog()] -#endif - -#if !defined(GRAPHICS_API_OPENGL_11) && defined(SUPPORT_DISTORTION_SHADER) - #include "shader_distortion.h" // Distortion shader to be embedded -#endif - -//---------------------------------------------------------------------------------- -// Defines and Macros -//---------------------------------------------------------------------------------- -#define MATRIX_STACK_SIZE 16 // Matrix stack max size -#define MAX_DRAWS_BY_TEXTURE 256 // Draws are organized by texture changes -#define TEMP_VERTEX_BUFFER_SIZE 4096 // Temporal Vertex Buffer (required for vertex-transformations) - // NOTE: Every vertex are 3 floats (12 bytes) - -#ifndef GL_SHADING_LANGUAGE_VERSION - #define GL_SHADING_LANGUAGE_VERSION 0x8B8C -#endif - -#ifndef GL_COMPRESSED_RGB_S3TC_DXT1_EXT - #define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0x83F0 -#endif -#ifndef GL_COMPRESSED_RGBA_S3TC_DXT1_EXT - #define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1 -#endif -#ifndef GL_COMPRESSED_RGBA_S3TC_DXT3_EXT - #define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2 -#endif -#ifndef GL_COMPRESSED_RGBA_S3TC_DXT5_EXT - #define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3 -#endif -#ifndef GL_ETC1_RGB8_OES - #define GL_ETC1_RGB8_OES 0x8D64 -#endif -#ifndef GL_COMPRESSED_RGB8_ETC2 - #define GL_COMPRESSED_RGB8_ETC2 0x9274 -#endif -#ifndef GL_COMPRESSED_RGBA8_ETC2_EAC - #define GL_COMPRESSED_RGBA8_ETC2_EAC 0x9278 -#endif -#ifndef GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG - #define GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG 0x8C00 -#endif -#ifndef GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG - #define GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG 0x8C02 -#endif -#ifndef GL_COMPRESSED_RGBA_ASTC_4x4_KHR - #define GL_COMPRESSED_RGBA_ASTC_4x4_KHR 0x93b0 -#endif -#ifndef GL_COMPRESSED_RGBA_ASTC_8x8_KHR - #define GL_COMPRESSED_RGBA_ASTC_8x8_KHR 0x93b7 -#endif - -#ifndef GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT - #define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF -#endif - -#ifndef GL_TEXTURE_MAX_ANISOTROPY_EXT - #define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE -#endif - -#if defined(GRAPHICS_API_OPENGL_11) - #define GL_UNSIGNED_SHORT_5_6_5 0x8363 - #define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 - #define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 -#endif - -#if defined(GRAPHICS_API_OPENGL_ES2) - #define glClearDepth glClearDepthf - #define GL_READ_FRAMEBUFFER GL_FRAMEBUFFER - #define GL_DRAW_FRAMEBUFFER GL_FRAMEBUFFER -#endif - -// Default vertex attribute names on shader to set location points -#define DEFAULT_ATTRIB_POSITION_NAME "vertexPosition" // shader-location = 0 -#define DEFAULT_ATTRIB_TEXCOORD_NAME "vertexTexCoord" // shader-location = 1 -#define DEFAULT_ATTRIB_NORMAL_NAME "vertexNormal" // shader-location = 2 -#define DEFAULT_ATTRIB_COLOR_NAME "vertexColor" // shader-location = 3 -#define DEFAULT_ATTRIB_TANGENT_NAME "vertexTangent" // shader-location = 4 -#define DEFAULT_ATTRIB_TEXCOORD2_NAME "vertexTexCoord2" // shader-location = 5 - -//---------------------------------------------------------------------------------- -// Types and Structures Definition -//---------------------------------------------------------------------------------- - -// Dynamic vertex buffers (position + texcoords + colors + indices arrays) -typedef struct DynamicBuffer { - int vCounter; // vertex position counter to process (and draw) from full buffer - int tcCounter; // vertex texcoord counter to process (and draw) from full buffer - int cCounter; // vertex color counter to process (and draw) from full buffer - float *vertices; // vertex position (XYZ - 3 components per vertex) (shader-location = 0) - float *texcoords; // vertex texture coordinates (UV - 2 components per vertex) (shader-location = 1) - unsigned char *colors; // vertex colors (RGBA - 4 components per vertex) (shader-location = 3) -#if defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_33) - unsigned int *indices; // vertex indices (in case vertex data comes indexed) (6 indices per quad) -#elif defined(GRAPHICS_API_OPENGL_ES2) - unsigned short *indices; // vertex indices (in case vertex data comes indexed) (6 indices per quad) - // NOTE: 6*2 byte = 12 byte, not alignment problem! -#endif - unsigned int vaoId; // OpenGL Vertex Array Object id - unsigned int vboId[4]; // OpenGL Vertex Buffer Objects id (4 types of vertex data) -} DynamicBuffer; - -// Draw call type -// NOTE: Used to track required draw-calls, organized by texture -typedef struct DrawCall { - int vertexCount; - GLuint vaoId; - GLuint textureId; - GLuint shaderId; - - Matrix projection; - Matrix modelview; - - // TODO: Store additional draw state data - //int blendMode; - //Guint fboId; -} DrawCall; - -#if defined(SUPPORT_VR_SIMULATOR) -// VR Stereo rendering configuration for simulator -typedef struct VrStereoConfig { - RenderTexture2D stereoFbo; // VR stereo rendering framebuffer - Shader distortionShader; // VR stereo rendering distortion shader - //Rectangle eyesViewport[2]; // VR stereo rendering eyes viewports - Matrix eyesProjection[2]; // VR stereo rendering eyes projection matrices - Matrix eyesViewOffset[2]; // VR stereo rendering eyes view offset matrices -} VrStereoConfig; -#endif - -//---------------------------------------------------------------------------------- -// Global Variables Definition -//---------------------------------------------------------------------------------- -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) -static Matrix stack[MATRIX_STACK_SIZE]; -static int stackCounter = 0; - -static Matrix modelview; -static Matrix projection; -static Matrix *currentMatrix; -static int currentMatrixMode; - -static int currentDrawMode; - -static float currentDepth = -1.0f; - -static DynamicBuffer lines; // Default dynamic buffer for lines data -static DynamicBuffer triangles; // Default dynamic buffer for triangles data -static DynamicBuffer quads; // Default dynamic buffer for quads data (used to draw textures) - -// Default buffers draw calls -static DrawCall *draws; -static int drawsCounter; - -// Temp vertex buffer to be used with rlTranslate, rlRotate, rlScale -static Vector3 *tempBuffer; -static int tempBufferCount = 0; -static bool useTempBuffer = false; - -// Shader Programs -static Shader defaultShader; // Basic shader, support vertex color and diffuse texture -static Shader currentShader; // Shader to be used on rendering (by default, defaultShader) - -// Extension supported flag: VAO -static bool vaoSupported = false; // VAO support (OpenGL ES2 could not support VAO extension) - -// Extension supported flag: Compressed textures -static bool texCompETC1Supported = false; // ETC1 texture compression support -static bool texCompETC2Supported = false; // ETC2/EAC texture compression support -static bool texCompPVRTSupported = false; // PVR texture compression support -static bool texCompASTCSupported = false; // ASTC texture compression support - -#if defined(SUPPORT_VR_SIMULATOR) -// VR global variables -static VrStereoConfig vrConfig; // VR stereo configuration for simulator -static bool vrSimulatorReady = false; // VR simulator ready flag -static bool vrStereoRender = false; // VR stereo rendering enabled/disabled flag - // NOTE: This flag is useful to render data over stereo image (i.e. FPS) -#endif // defined(SUPPORT_VR_SIMULATOR) - -#endif // defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - -// Extension supported flag: Anisotropic filtering -static bool texAnisotropicFilterSupported = false; // Anisotropic texture filtering support -static float maxAnisotropicLevel = 0.0f; // Maximum anisotropy level supported (minimum is 2.0f) - -// Extension supported flag: Clamp mirror wrap mode -static bool texClampMirrorSupported = false; // Clamp mirror wrap mode supported - -#if defined(GRAPHICS_API_OPENGL_ES2) -// NOTE: VAO functionality is exposed through extensions (OES) -static PFNGLGENVERTEXARRAYSOESPROC glGenVertexArrays; -static PFNGLBINDVERTEXARRAYOESPROC glBindVertexArray; -static PFNGLDELETEVERTEXARRAYSOESPROC glDeleteVertexArrays; -//static PFNGLISVERTEXARRAYOESPROC glIsVertexArray; // NOTE: Fails in WebGL, omitted -#endif - -// Compressed textures support flags -static bool texCompDXTSupported = false; // DDS texture compression support -static bool texNPOTSupported = false; // NPOT textures full support -static bool texFloatSupported = false; // float textures support (32 bit per channel) - -static int blendMode = 0; // Track current blending mode - -// White texture useful for plain color polys (required by shader) -static unsigned int whiteTexture; - -// Default framebuffer size -static int screenWidth; // Default framebuffer width -static int screenHeight; // Default framebuffer height - -//---------------------------------------------------------------------------------- -// Module specific Functions Declaration -//---------------------------------------------------------------------------------- -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) -static void LoadTextureCompressed(unsigned char *data, int width, int height, int compressedFormat, int mipmapCount); -static unsigned int LoadShaderProgram(const char *vShaderStr, const char *fShaderStr); // Load custom shader strings and return program id - -static Shader LoadShaderDefault(void); // Load default shader (just vertex positioning and texture coloring) -static void SetShaderDefaultLocations(Shader *shader); // Bind default shader locations (attributes and uniforms) -static void UnloadShaderDefault(void); // Unload default shader - -static void LoadBuffersDefault(void); // Load default internal buffers (lines, triangles, quads) -static void UpdateBuffersDefault(void); // Update default internal buffers (VAOs/VBOs) with vertex data -static void DrawBuffersDefault(void); // Draw default internal buffers vertex data -static void UnloadBuffersDefault(void); // Unload default internal buffers vertex data from CPU and GPU - -static void GenDrawCube(void); // Generate and draw cube -static void GenDrawQuad(void); // Generate and draw quad - -#if defined(SUPPORT_VR_SIMULATOR) -static void SetStereoConfig(VrDeviceInfo info); // Configure stereo rendering (including distortion shader) with HMD device parameters -static void SetStereoView(int eye, Matrix matProjection, Matrix matModelView); // Set internal projection and modelview matrix depending on eye -#endif - -#endif // defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - -#if defined(GRAPHICS_API_OPENGL_11) -static int GenerateMipmaps(unsigned char *data, int baseWidth, int baseHeight); -static Color *GenNextMipmap(Color *srcData, int srcWidth, int srcHeight); -#endif - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Matrix operations -//---------------------------------------------------------------------------------- - -#if defined(GRAPHICS_API_OPENGL_11) - -// Fallback to OpenGL 1.1 function calls -//--------------------------------------- -void rlMatrixMode(int mode) -{ - switch (mode) - { - case RL_PROJECTION: glMatrixMode(GL_PROJECTION); break; - case RL_MODELVIEW: glMatrixMode(GL_MODELVIEW); break; - case RL_TEXTURE: glMatrixMode(GL_TEXTURE); break; - default: break; - } -} - -void rlFrustum(double left, double right, double bottom, double top, double zNear, double zFar) -{ - glFrustum(left, right, bottom, top, zNear, zFar); -} - -void rlOrtho(double left, double right, double bottom, double top, double zNear, double zFar) -{ - glOrtho(left, right, bottom, top, zNear, zFar); -} - -void rlPushMatrix(void) { glPushMatrix(); } -void rlPopMatrix(void) { glPopMatrix(); } -void rlLoadIdentity(void) { glLoadIdentity(); } -void rlTranslatef(float x, float y, float z) { glTranslatef(x, y, z); } -void rlRotatef(float angleDeg, float x, float y, float z) { glRotatef(angleDeg, x, y, z); } -void rlScalef(float x, float y, float z) { glScalef(x, y, z); } -void rlMultMatrixf(float *matf) { glMultMatrixf(matf); } - -#elif defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - -// Choose the current matrix to be transformed -void rlMatrixMode(int mode) -{ - if (mode == RL_PROJECTION) currentMatrix = &projection; - else if (mode == RL_MODELVIEW) currentMatrix = &modelview; - //else if (mode == RL_TEXTURE) // Not supported - - currentMatrixMode = mode; -} - -// Push the current matrix to stack -void rlPushMatrix(void) -{ - if (stackCounter == MATRIX_STACK_SIZE - 1) - { - TraceLog(LOG_ERROR, "Stack Buffer Overflow (MAX %i Matrix)", MATRIX_STACK_SIZE); - } - - stack[stackCounter] = *currentMatrix; - rlLoadIdentity(); - stackCounter++; - - if (currentMatrixMode == RL_MODELVIEW) useTempBuffer = true; -} - -// Pop lattest inserted matrix from stack -void rlPopMatrix(void) -{ - if (stackCounter > 0) - { - Matrix mat = stack[stackCounter - 1]; - *currentMatrix = mat; - stackCounter--; - } -} - -// Reset current matrix to identity matrix -void rlLoadIdentity(void) -{ - *currentMatrix = MatrixIdentity(); -} - -// Multiply the current matrix by a translation matrix -void rlTranslatef(float x, float y, float z) -{ - Matrix matTranslation = MatrixTranslate(x, y, z); - - // NOTE: We transpose matrix with multiplication order - *currentMatrix = MatrixMultiply(matTranslation, *currentMatrix); -} - -// Multiply the current matrix by a rotation matrix -void rlRotatef(float angleDeg, float x, float y, float z) -{ - Matrix matRotation = MatrixIdentity(); - - Vector3 axis = (Vector3){ x, y, z }; - Vector3Normalize(&axis); - matRotation = MatrixRotate(axis, angleDeg*DEG2RAD); - - // NOTE: We transpose matrix with multiplication order - *currentMatrix = MatrixMultiply(matRotation, *currentMatrix); -} - -// Multiply the current matrix by a scaling matrix -void rlScalef(float x, float y, float z) -{ - Matrix matScale = MatrixScale(x, y, z); - - // NOTE: We transpose matrix with multiplication order - *currentMatrix = MatrixMultiply(matScale, *currentMatrix); -} - -// Multiply the current matrix by another matrix -void rlMultMatrixf(float *matf) -{ - // Matrix creation from array - Matrix mat = { matf[0], matf[4], matf[8], matf[12], - matf[1], matf[5], matf[9], matf[13], - matf[2], matf[6], matf[10], matf[14], - matf[3], matf[7], matf[11], matf[15] }; - - *currentMatrix = MatrixMultiply(*currentMatrix, mat); -} - -// Multiply the current matrix by a perspective matrix generated by parameters -void rlFrustum(double left, double right, double bottom, double top, double near, double far) -{ - Matrix matPerps = MatrixFrustum(left, right, bottom, top, near, far); - - *currentMatrix = MatrixMultiply(*currentMatrix, matPerps); -} - -// Multiply the current matrix by an orthographic matrix generated by parameters -void rlOrtho(double left, double right, double bottom, double top, double near, double far) -{ - Matrix matOrtho = MatrixOrtho(left, right, bottom, top, near, far); - - *currentMatrix = MatrixMultiply(*currentMatrix, matOrtho); -} - -#endif - -// Set the viewport area (transformation from normalized device coordinates to window coordinates) -// NOTE: Updates global variables: screenWidth, screenHeight -void rlViewport(int x, int y, int width, int height) -{ - glViewport(x, y, width, height); -} - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Vertex level operations -//---------------------------------------------------------------------------------- -#if defined(GRAPHICS_API_OPENGL_11) - -// Fallback to OpenGL 1.1 function calls -//--------------------------------------- -void rlBegin(int mode) -{ - switch (mode) - { - case RL_LINES: glBegin(GL_LINES); break; - case RL_TRIANGLES: glBegin(GL_TRIANGLES); break; - case RL_QUADS: glBegin(GL_QUADS); break; - default: break; - } -} - -void rlEnd() { glEnd(); } -void rlVertex2i(int x, int y) { glVertex2i(x, y); } -void rlVertex2f(float x, float y) { glVertex2f(x, y); } -void rlVertex3f(float x, float y, float z) { glVertex3f(x, y, z); } -void rlTexCoord2f(float x, float y) { glTexCoord2f(x, y); } -void rlNormal3f(float x, float y, float z) { glNormal3f(x, y, z); } -void rlColor4ub(byte r, byte g, byte b, byte a) { glColor4ub(r, g, b, a); } -void rlColor3f(float x, float y, float z) { glColor3f(x, y, z); } -void rlColor4f(float x, float y, float z, float w) { glColor4f(x, y, z, w); } - -#elif defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - -// Initialize drawing mode (how to organize vertex) -void rlBegin(int mode) -{ - // Draw mode can only be RL_LINES, RL_TRIANGLES and RL_QUADS - currentDrawMode = mode; -} - -// Finish vertex providing -void rlEnd(void) -{ - if (useTempBuffer) - { - // NOTE: In this case, *currentMatrix is already transposed because transposing has been applied - // independently to translation-scale-rotation matrices -> t(M1 x M2) = t(M2) x t(M1) - // This way, rlTranslatef(), rlRotatef()... behaviour is the same than OpenGL 1.1 - - // Apply transformation matrix to all temp vertices - for (int i = 0; i < tempBufferCount; i++) Vector3Transform(&tempBuffer[i], *currentMatrix); - - // Deactivate tempBuffer usage to allow rlVertex3f do its job - useTempBuffer = false; - - // Copy all transformed vertices to right VAO - for (int i = 0; i < tempBufferCount; i++) rlVertex3f(tempBuffer[i].x, tempBuffer[i].y, tempBuffer[i].z); - - // Reset temp buffer - tempBufferCount = 0; - } - - // Make sure vertexCount is the same for vertices-texcoords-normals-colors - // NOTE: In OpenGL 1.1, one glColor call can be made for all the subsequent glVertex calls. - switch (currentDrawMode) - { - case RL_LINES: - { - if (lines.vCounter != lines.cCounter) - { - int addColors = lines.vCounter - lines.cCounter; - - for (int i = 0; i < addColors; i++) - { - lines.colors[4*lines.cCounter] = lines.colors[4*lines.cCounter - 4]; - lines.colors[4*lines.cCounter + 1] = lines.colors[4*lines.cCounter - 3]; - lines.colors[4*lines.cCounter + 2] = lines.colors[4*lines.cCounter - 2]; - lines.colors[4*lines.cCounter + 3] = lines.colors[4*lines.cCounter - 1]; - - lines.cCounter++; - } - } - } break; - case RL_TRIANGLES: - { - if (triangles.vCounter != triangles.cCounter) - { - int addColors = triangles.vCounter - triangles.cCounter; - - for (int i = 0; i < addColors; i++) - { - triangles.colors[4*triangles.cCounter] = triangles.colors[4*triangles.cCounter - 4]; - triangles.colors[4*triangles.cCounter + 1] = triangles.colors[4*triangles.cCounter - 3]; - triangles.colors[4*triangles.cCounter + 2] = triangles.colors[4*triangles.cCounter - 2]; - triangles.colors[4*triangles.cCounter + 3] = triangles.colors[4*triangles.cCounter - 1]; - - triangles.cCounter++; - } - } - } break; - case RL_QUADS: - { - // Make sure colors count match vertex count - if (quads.vCounter != quads.cCounter) - { - int addColors = quads.vCounter - quads.cCounter; - - for (int i = 0; i < addColors; i++) - { - quads.colors[4*quads.cCounter] = quads.colors[4*quads.cCounter - 4]; - quads.colors[4*quads.cCounter + 1] = quads.colors[4*quads.cCounter - 3]; - quads.colors[4*quads.cCounter + 2] = quads.colors[4*quads.cCounter - 2]; - quads.colors[4*quads.cCounter + 3] = quads.colors[4*quads.cCounter - 1]; - - quads.cCounter++; - } - } - - // Make sure texcoords count match vertex count - if (quads.vCounter != quads.tcCounter) - { - int addTexCoords = quads.vCounter - quads.tcCounter; - - for (int i = 0; i < addTexCoords; i++) - { - quads.texcoords[2*quads.tcCounter] = 0.0f; - quads.texcoords[2*quads.tcCounter + 1] = 0.0f; - - quads.tcCounter++; - } - } - - // TODO: Make sure normals count match vertex count... if normals support is added in a future... :P - - } break; - default: break; - } - - // NOTE: Depth increment is dependant on rlOrtho(): z-near and z-far values, - // as well as depth buffer bit-depth (16bit or 24bit or 32bit) - // Correct increment formula would be: depthInc = (zfar - znear)/pow(2, bits) - currentDepth += (1.0f/20000.0f); -} - -// Define one vertex (position) -void rlVertex3f(float x, float y, float z) -{ - if (useTempBuffer) - { - tempBuffer[tempBufferCount].x = x; - tempBuffer[tempBufferCount].y = y; - tempBuffer[tempBufferCount].z = z; - tempBufferCount++; - } - else - { - switch (currentDrawMode) - { - case RL_LINES: - { - // Verify that MAX_LINES_BATCH limit not reached - if (lines.vCounter/2 < MAX_LINES_BATCH) - { - lines.vertices[3*lines.vCounter] = x; - lines.vertices[3*lines.vCounter + 1] = y; - lines.vertices[3*lines.vCounter + 2] = z; - - lines.vCounter++; - } - else TraceLog(LOG_ERROR, "MAX_LINES_BATCH overflow"); - - } break; - case RL_TRIANGLES: - { - // Verify that MAX_TRIANGLES_BATCH limit not reached - if (triangles.vCounter/3 < MAX_TRIANGLES_BATCH) - { - triangles.vertices[3*triangles.vCounter] = x; - triangles.vertices[3*triangles.vCounter + 1] = y; - triangles.vertices[3*triangles.vCounter + 2] = z; - - triangles.vCounter++; - } - else TraceLog(LOG_ERROR, "MAX_TRIANGLES_BATCH overflow"); - - } break; - case RL_QUADS: - { - // Verify that MAX_QUADS_BATCH limit not reached - if (quads.vCounter/4 < MAX_QUADS_BATCH) - { - quads.vertices[3*quads.vCounter] = x; - quads.vertices[3*quads.vCounter + 1] = y; - quads.vertices[3*quads.vCounter + 2] = z; - - quads.vCounter++; - - draws[drawsCounter - 1].vertexCount++; - } - else TraceLog(LOG_ERROR, "MAX_QUADS_BATCH overflow"); - - } break; - default: break; - } - } -} - -// Define one vertex (position) -void rlVertex2f(float x, float y) -{ - rlVertex3f(x, y, currentDepth); -} - -// Define one vertex (position) -void rlVertex2i(int x, int y) -{ - rlVertex3f((float)x, (float)y, currentDepth); -} - -// Define one vertex (texture coordinate) -// NOTE: Texture coordinates are limited to QUADS only -void rlTexCoord2f(float x, float y) -{ - if (currentDrawMode == RL_QUADS) - { - quads.texcoords[2*quads.tcCounter] = x; - quads.texcoords[2*quads.tcCounter + 1] = y; - - quads.tcCounter++; - } -} - -// Define one vertex (normal) -// NOTE: Normals limited to TRIANGLES only ? -void rlNormal3f(float x, float y, float z) -{ - // TODO: Normals usage... -} - -// Define one vertex (color) -void rlColor4ub(byte x, byte y, byte z, byte w) -{ - switch (currentDrawMode) - { - case RL_LINES: - { - lines.colors[4*lines.cCounter] = x; - lines.colors[4*lines.cCounter + 1] = y; - lines.colors[4*lines.cCounter + 2] = z; - lines.colors[4*lines.cCounter + 3] = w; - - lines.cCounter++; - - } break; - case RL_TRIANGLES: - { - triangles.colors[4*triangles.cCounter] = x; - triangles.colors[4*triangles.cCounter + 1] = y; - triangles.colors[4*triangles.cCounter + 2] = z; - triangles.colors[4*triangles.cCounter + 3] = w; - - triangles.cCounter++; - - } break; - case RL_QUADS: - { - quads.colors[4*quads.cCounter] = x; - quads.colors[4*quads.cCounter + 1] = y; - quads.colors[4*quads.cCounter + 2] = z; - quads.colors[4*quads.cCounter + 3] = w; - - quads.cCounter++; - - } break; - default: break; - } -} - -// Define one vertex (color) -void rlColor4f(float r, float g, float b, float a) -{ - rlColor4ub((byte)(r*255), (byte)(g*255), (byte)(b*255), (byte)(a*255)); -} - -// Define one vertex (color) -void rlColor3f(float x, float y, float z) -{ - rlColor4ub((byte)(x*255), (byte)(y*255), (byte)(z*255), 255); -} - -#endif - -//---------------------------------------------------------------------------------- -// Module Functions Definition - OpenGL equivalent functions (common to 1.1, 3.3+, ES2) -//---------------------------------------------------------------------------------- - -// Enable texture usage -void rlEnableTexture(unsigned int id) -{ -#if defined(GRAPHICS_API_OPENGL_11) - glEnable(GL_TEXTURE_2D); - glBindTexture(GL_TEXTURE_2D, id); -#endif - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if (draws[drawsCounter - 1].textureId != id) - { - if (draws[drawsCounter - 1].vertexCount > 0) drawsCounter++; - - if (drawsCounter >= MAX_DRAWS_BY_TEXTURE) - { - rlglDraw(); - drawsCounter = 1; - } - - draws[drawsCounter - 1].textureId = id; - draws[drawsCounter - 1].vertexCount = 0; - } -#endif -} - -// Disable texture usage -void rlDisableTexture(void) -{ -#if defined(GRAPHICS_API_OPENGL_11) - glDisable(GL_TEXTURE_2D); - glBindTexture(GL_TEXTURE_2D, 0); -#else - // NOTE: If quads batch limit is reached, - // we force a draw call and next batch starts - if (quads.vCounter/4 >= MAX_QUADS_BATCH) rlglDraw(); -#endif -} - -// Set texture parameters (wrap mode/filter mode) -void rlTextureParameters(unsigned int id, int param, int value) -{ - glBindTexture(GL_TEXTURE_2D, id); - - switch (param) - { - case RL_TEXTURE_WRAP_S: - case RL_TEXTURE_WRAP_T: - { - if ((value == RL_WRAP_CLAMP_MIRROR) && !texClampMirrorSupported) TraceLog(LOG_WARNING, "Clamp mirror wrap mode not supported"); - else glTexParameteri(GL_TEXTURE_2D, param, value); - } break; - case RL_TEXTURE_MAG_FILTER: - case RL_TEXTURE_MIN_FILTER: glTexParameteri(GL_TEXTURE_2D, param, value); break; - case RL_TEXTURE_ANISOTROPIC_FILTER: - { - if (value <= maxAnisotropicLevel) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)value); - else if (maxAnisotropicLevel > 0.0f) - { - TraceLog(LOG_WARNING, "[TEX ID %i] Maximum anisotropic filter level supported is %iX", id, maxAnisotropicLevel); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)value); - } - else TraceLog(LOG_WARNING, "Anisotropic filtering not supported"); - } break; - default: break; - } - - glBindTexture(GL_TEXTURE_2D, 0); -} - -// Enable rendering to texture (fbo) -void rlEnableRenderTexture(unsigned int id) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glBindFramebuffer(GL_FRAMEBUFFER, id); - - //glDisable(GL_CULL_FACE); // Allow double side drawing for texture flipping - //glCullFace(GL_FRONT); -#endif -} - -// Disable rendering to texture -void rlDisableRenderTexture(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glBindFramebuffer(GL_FRAMEBUFFER, 0); - - //glEnable(GL_CULL_FACE); - //glCullFace(GL_BACK); -#endif -} - -// Enable depth test -void rlEnableDepthTest(void) -{ - glEnable(GL_DEPTH_TEST); -} - -// Disable depth test -void rlDisableDepthTest(void) -{ - glDisable(GL_DEPTH_TEST); -} - -// Enable wire mode -void rlEnableWireMode(void) -{ -#if defined (GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_33) - // NOTE: glPolygonMode() not available on OpenGL ES - glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); -#endif -} - -// Disable wire mode -void rlDisableWireMode(void) -{ -#if defined (GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_33) - // NOTE: glPolygonMode() not available on OpenGL ES - glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); -#endif -} - -// Unload texture from GPU memory -void rlDeleteTextures(unsigned int id) -{ - if (id > 0) glDeleteTextures(1, &id); -} - -// Unload render texture from GPU memory -void rlDeleteRenderTextures(RenderTexture2D target) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if (target.id > 0) glDeleteFramebuffers(1, &target.id); - if (target.texture.id > 0) glDeleteTextures(1, &target.texture.id); - if (target.depth.id > 0) glDeleteTextures(1, &target.depth.id); - - TraceLog(LOG_INFO, "[FBO ID %i] Unloaded render texture data from VRAM (GPU)", target.id); -#endif -} - -// Unload shader from GPU memory -void rlDeleteShader(unsigned int id) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if (id != 0) glDeleteProgram(id); -#endif -} - -// Unload vertex data (VAO) from GPU memory -void rlDeleteVertexArrays(unsigned int id) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if (vaoSupported) - { - if (id != 0) glDeleteVertexArrays(1, &id); - TraceLog(LOG_INFO, "[VAO ID %i] Unloaded model data from VRAM (GPU)", id); - } -#endif -} - -// Unload vertex data (VBO) from GPU memory -void rlDeleteBuffers(unsigned int id) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if (id != 0) - { - glDeleteBuffers(1, &id); - if (!vaoSupported) TraceLog(LOG_INFO, "[VBO ID %i] Unloaded model vertex data from VRAM (GPU)", id); - } -#endif -} - -// Clear color buffer with color -void rlClearColor(byte r, byte g, byte b, byte a) -{ - // Color values clamp to 0.0f(0) and 1.0f(255) - float cr = (float)r/255; - float cg = (float)g/255; - float cb = (float)b/255; - float ca = (float)a/255; - - glClearColor(cr, cg, cb, ca); -} - -// Clear used screen buffers (color and depth) -void rlClearScreenBuffers(void) -{ - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear used buffers: Color and Depth (Depth is used for 3D) - //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); // Stencil buffer not used... -} - -//---------------------------------------------------------------------------------- -// Module Functions Definition - rlgl Functions -//---------------------------------------------------------------------------------- - -// Initialize rlgl: OpenGL extensions, default buffers/shaders/textures, OpenGL states -void rlglInit(int width, int height) -{ - // Check OpenGL information and capabilities - //------------------------------------------------------------------------------ - - // Print current OpenGL and GLSL version - TraceLog(LOG_INFO, "GPU: Vendor: %s", glGetString(GL_VENDOR)); - TraceLog(LOG_INFO, "GPU: Renderer: %s", glGetString(GL_RENDERER)); - TraceLog(LOG_INFO, "GPU: Version: %s", glGetString(GL_VERSION)); - TraceLog(LOG_INFO, "GPU: GLSL: %s", glGetString(GL_SHADING_LANGUAGE_VERSION)); - - // NOTE: We can get a bunch of extra information about GPU capabilities (glGet*) - //int maxTexSize; - //glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTexSize); - //TraceLog(LOG_INFO, "GL_MAX_TEXTURE_SIZE: %i", maxTexSize); - - //GL_MAX_TEXTURE_IMAGE_UNITS - //GL_MAX_VIEWPORT_DIMS - - //int numAuxBuffers; - //glGetIntegerv(GL_AUX_BUFFERS, &numAuxBuffers); - //TraceLog(LOG_INFO, "GL_AUX_BUFFERS: %i", numAuxBuffers); - - //GLint numComp = 0; - //GLint format[32] = { 0 }; - //glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, &numComp); - //glGetIntegerv(GL_COMPRESSED_TEXTURE_FORMATS, format); - //for (int i = 0; i < numComp; i++) TraceLog(LOG_INFO, "Supported compressed format: 0x%x", format[i]); - - // NOTE: We don't need that much data on screen... right now... - -#if defined(GRAPHICS_API_OPENGL_11) - //TraceLog(LOG_INFO, "OpenGL 1.1 (or driver default) profile initialized"); -#endif - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // Get supported extensions list - GLint numExt = 0; - -#if defined(GRAPHICS_API_OPENGL_33) - - // NOTE: On OpenGL 3.3 VAO and NPOT are supported by default - vaoSupported = true; - texNPOTSupported = true; - texFloatSupported = true; - - // We get a list of available extensions and we check for some of them (compressed textures) - // NOTE: We don't need to check again supported extensions but we do (GLAD already dealt with that) - glGetIntegerv(GL_NUM_EXTENSIONS, &numExt); - -#ifdef _MSC_VER - const char **extList = malloc(sizeof(const char *)*numExt); -#else - const char *extList[numExt]; -#endif - - for (int i = 0; i < numExt; i++) extList[i] = (char *)glGetStringi(GL_EXTENSIONS, i); - -#elif defined(GRAPHICS_API_OPENGL_ES2) - char *extensions = (char *)glGetString(GL_EXTENSIONS); // One big const string - - // NOTE: We have to duplicate string because glGetString() returns a const value - // If not duplicated, it fails in some systems (Raspberry Pi) - // Equivalent to function: char *strdup(const char *str) - char *extensionsDup; - size_t len = strlen(extensions) + 1; - void *newstr = malloc(len); - if (newstr == NULL) extensionsDup = NULL; - extensionsDup = (char *)memcpy(newstr, extensions, len); - - // NOTE: String could be splitted using strtok() function (string.h) - // NOTE: strtok() modifies the received string, it can not be const - - char *extList[512]; // Allocate 512 strings pointers (2 KB) - - extList[numExt] = strtok(extensionsDup, " "); - - while (extList[numExt] != NULL) - { - numExt++; - extList[numExt] = strtok(NULL, " "); - } - - free(extensionsDup); // Duplicated string must be deallocated - - numExt -= 1; -#endif - - TraceLog(LOG_INFO, "Number of supported extensions: %i", numExt); - - // Show supported extensions - //for (int i = 0; i < numExt; i++) TraceLog(LOG_INFO, "Supported extension: %s", extList[i]); - - // Check required extensions - for (int i = 0; i < numExt; i++) - { -#if defined(GRAPHICS_API_OPENGL_ES2) - // Check VAO support - // NOTE: Only check on OpenGL ES, OpenGL 3.3 has VAO support as core feature - if (strcmp(extList[i], (const char *)"GL_OES_vertex_array_object") == 0) - { - vaoSupported = true; - - // The extension is supported by our hardware and driver, try to get related functions pointers - // NOTE: emscripten does not support VAOs natively, it uses emulation and it reduces overall performance... - glGenVertexArrays = (PFNGLGENVERTEXARRAYSOESPROC)eglGetProcAddress("glGenVertexArraysOES"); - glBindVertexArray = (PFNGLBINDVERTEXARRAYOESPROC)eglGetProcAddress("glBindVertexArrayOES"); - glDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSOESPROC)eglGetProcAddress("glDeleteVertexArraysOES"); - //glIsVertexArray = (PFNGLISVERTEXARRAYOESPROC)eglGetProcAddress("glIsVertexArrayOES"); // NOTE: Fails in WebGL, omitted - } - - // Check NPOT textures support - // NOTE: Only check on OpenGL ES, OpenGL 3.3 has NPOT textures full support as core feature - if (strcmp(extList[i], (const char *)"GL_OES_texture_npot") == 0) texNPOTSupported = true; - - // Check texture float support - if (strcmp(extList[i], (const char *)"OES_texture_float") == 0) texFloatSupported = true; -#endif - - // DDS texture compression support - if ((strcmp(extList[i], (const char *)"GL_EXT_texture_compression_s3tc") == 0) || - (strcmp(extList[i], (const char *)"GL_WEBGL_compressed_texture_s3tc") == 0) || - (strcmp(extList[i], (const char *)"GL_WEBKIT_WEBGL_compressed_texture_s3tc") == 0)) texCompDXTSupported = true; - - // ETC1 texture compression support - if ((strcmp(extList[i], (const char *)"GL_OES_compressed_ETC1_RGB8_texture") == 0) || - (strcmp(extList[i], (const char *)"GL_WEBGL_compressed_texture_etc1") == 0)) texCompETC1Supported = true; - - // ETC2/EAC texture compression support - if (strcmp(extList[i], (const char *)"GL_ARB_ES3_compatibility") == 0) texCompETC2Supported = true; - - // PVR texture compression support - if (strcmp(extList[i], (const char *)"GL_IMG_texture_compression_pvrtc") == 0) texCompPVRTSupported = true; - - // ASTC texture compression support - if (strcmp(extList[i], (const char *)"GL_KHR_texture_compression_astc_hdr") == 0) texCompASTCSupported = true; - - // Anisotropic texture filter support - if (strcmp(extList[i], (const char *)"GL_EXT_texture_filter_anisotropic") == 0) - { - texAnisotropicFilterSupported = true; - glGetFloatv(0x84FF, &maxAnisotropicLevel); // GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT - } - - // Clamp mirror wrap mode supported - if (strcmp(extList[i], (const char *)"GL_EXT_texture_mirror_clamp") == 0) texClampMirrorSupported = true; - } - -#ifdef _MSC_VER - free(extList); -#endif - -#if defined(GRAPHICS_API_OPENGL_ES2) - if (vaoSupported) TraceLog(LOG_INFO, "[EXTENSION] VAO extension detected, VAO functions initialized successfully"); - else TraceLog(LOG_WARNING, "[EXTENSION] VAO extension not found, VAO usage not supported"); - - if (texNPOTSupported) TraceLog(LOG_INFO, "[EXTENSION] NPOT textures extension detected, full NPOT textures supported"); - else TraceLog(LOG_WARNING, "[EXTENSION] NPOT textures extension not found, limited NPOT support (no-mipmaps, no-repeat)"); -#endif - - if (texCompDXTSupported) TraceLog(LOG_INFO, "[EXTENSION] DXT compressed textures supported"); - if (texCompETC1Supported) TraceLog(LOG_INFO, "[EXTENSION] ETC1 compressed textures supported"); - if (texCompETC2Supported) TraceLog(LOG_INFO, "[EXTENSION] ETC2/EAC compressed textures supported"); - if (texCompPVRTSupported) TraceLog(LOG_INFO, "[EXTENSION] PVRT compressed textures supported"); - if (texCompASTCSupported) TraceLog(LOG_INFO, "[EXTENSION] ASTC compressed textures supported"); - - if (texAnisotropicFilterSupported) TraceLog(LOG_INFO, "[EXTENSION] Anisotropic textures filtering supported (max: %.0fX)", maxAnisotropicLevel); - if (texClampMirrorSupported) TraceLog(LOG_INFO, "[EXTENSION] Clamp mirror wrap texture mode supported"); - - // Initialize buffers, default shaders and default textures - //---------------------------------------------------------- - - // Init default white texture - unsigned char pixels[4] = { 255, 255, 255, 255 }; // 1 pixel RGBA (4 bytes) - - whiteTexture = rlLoadTexture(pixels, 1, 1, UNCOMPRESSED_R8G8B8A8, 1); - - if (whiteTexture != 0) TraceLog(LOG_INFO, "[TEX ID %i] Base white texture loaded successfully", whiteTexture); - else TraceLog(LOG_WARNING, "Base white texture could not be loaded"); - - // Init default Shader (customized for GL 3.3 and ES2) - defaultShader = LoadShaderDefault(); - currentShader = defaultShader; - - // Init default vertex arrays buffers (lines, triangles, quads) - LoadBuffersDefault(); - - // Init temp vertex buffer, used when transformation required (translate, rotate, scale) - tempBuffer = (Vector3 *)malloc(sizeof(Vector3)*TEMP_VERTEX_BUFFER_SIZE); - - for (int i = 0; i < TEMP_VERTEX_BUFFER_SIZE; i++) tempBuffer[i] = Vector3Zero(); - - // Init draw calls tracking system - draws = (DrawCall *)malloc(sizeof(DrawCall)*MAX_DRAWS_BY_TEXTURE); - - for (int i = 0; i < MAX_DRAWS_BY_TEXTURE; i++) - { - draws[i].textureId = 0; - draws[i].vertexCount = 0; - } - - drawsCounter = 1; - draws[drawsCounter - 1].textureId = whiteTexture; - currentDrawMode = RL_TRIANGLES; // Set default draw mode - - // Init internal matrix stack (emulating OpenGL 1.1) - for (int i = 0; i < MATRIX_STACK_SIZE; i++) stack[i] = MatrixIdentity(); - - // Init internal projection and modelview matrices - projection = MatrixIdentity(); - modelview = MatrixIdentity(); - currentMatrix = &modelview; -#endif // defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - - // Initialize OpenGL default states - //---------------------------------------------------------- - - // Init state: Depth test - glDepthFunc(GL_LEQUAL); // Type of depth testing to apply - glDisable(GL_DEPTH_TEST); // Disable depth testing for 2D (only used for 3D) - - // Init state: Blending mode - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Color blending function (how colors are mixed) - glEnable(GL_BLEND); // Enable color blending (required to work with transparencies) - - // Init state: Culling - // NOTE: All shapes/models triangles are drawn CCW - glCullFace(GL_BACK); // Cull the back face (default) - glFrontFace(GL_CCW); // Front face are defined counter clockwise (default) - glEnable(GL_CULL_FACE); // Enable backface culling - -#if defined(GRAPHICS_API_OPENGL_11) - // Init state: Color hints (deprecated in OpenGL 3.0+) - glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Improve quality of color and texture coordinate interpolation - glShadeModel(GL_SMOOTH); // Smooth shading between vertex (vertex colors interpolation) -#endif - - // Init state: Color/Depth buffers clear - glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set clear color (black) - glClearDepth(1.0f); // Set clear depth value (default) - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear color and depth buffers (depth buffer required for 3D) - - // Store screen size into global variables - screenWidth = width; - screenHeight = height; - - TraceLog(LOG_INFO, "OpenGL default states initialized successfully"); -} - -// Vertex Buffer Object deinitialization (memory free) -void rlglClose(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - UnloadShaderDefault(); // Unload default shader - UnloadBuffersDefault(); // Unload default buffers (lines, triangles, quads) - glDeleteTextures(1, &whiteTexture); // Unload default texture - - TraceLog(LOG_INFO, "[TEX ID %i] Unloaded texture data (base white texture) from VRAM", whiteTexture); - - free(draws); -#endif -} - -// Drawing batches: triangles, quads, lines -void rlglDraw(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // NOTE: In a future version, models could be stored in a stack... - //for (int i = 0; i < modelsCount; i++) rlDrawMesh(models[i]->mesh, models[i]->material, models[i]->transform); - - // NOTE: Default buffers upload and draw - UpdateBuffersDefault(); - DrawBuffersDefault(); // NOTE: Stereo rendering is checked inside -#endif -} - -// Returns current OpenGL version -int rlGetVersion(void) -{ -#if defined(GRAPHICS_API_OPENGL_11) - return OPENGL_11; -#elif defined(GRAPHICS_API_OPENGL_21) - #if defined(__APPLE__) - return OPENGL_33; // NOTE: Force OpenGL 3.3 on OSX - #else - return OPENGL_21; - #endif -#elif defined(GRAPHICS_API_OPENGL_33) - return OPENGL_33; -#elif defined(GRAPHICS_API_OPENGL_ES2) - return OPENGL_ES_20; -#endif -} - -// Load OpenGL extensions -// NOTE: External loader function could be passed as a pointer -void rlLoadExtensions(void *loader) -{ -#if defined(GRAPHICS_API_OPENGL_21) || defined(GRAPHICS_API_OPENGL_33) - // NOTE: glad is generated and contains only required OpenGL 3.3 Core extensions (and lower versions) - #if !defined(__APPLE__) - if (!gladLoadGLLoader((GLADloadproc)loader)) TraceLog(LOG_WARNING, "GLAD: Cannot load OpenGL extensions"); - else TraceLog(LOG_INFO, "GLAD: OpenGL extensions loaded successfully"); - - #if defined(GRAPHICS_API_OPENGL_21) - if (GLAD_GL_VERSION_2_1) TraceLog(LOG_INFO, "OpenGL 2.1 profile supported"); - #elif defined(GRAPHICS_API_OPENGL_33) - if(GLAD_GL_VERSION_3_3) TraceLog(LOG_INFO, "OpenGL 3.3 Core profile supported"); - else TraceLog(LOG_ERROR, "OpenGL 3.3 Core profile not supported"); - #endif - #endif - - // With GLAD, we can check if an extension is supported using the GLAD_GL_xxx booleans - //if (GLAD_GL_ARB_vertex_array_object) // Use GL_ARB_vertex_array_object -#endif -} - -// Get world coordinates from screen coordinates -Vector3 rlUnproject(Vector3 source, Matrix proj, Matrix view) -{ - Vector3 result = { 0.0f, 0.0f, 0.0f }; - - // Calculate unproject matrix (multiply view patrix by projection matrix) and invert it - Matrix matViewProj = MatrixMultiply(view, proj); - MatrixInvert(&matViewProj); - - // Create quaternion from source point - Quaternion quat = { source.x, source.y, source.z, 1.0f }; - - // Multiply quat point by unproject matrix - QuaternionTransform(&quat, matViewProj); - - // Normalized world points in vectors - result.x = quat.x/quat.w; - result.y = quat.y/quat.w; - result.z = quat.z/quat.w; - - return result; -} - -// Convert image data to OpenGL texture (returns OpenGL valid Id) -unsigned int rlLoadTexture(void *data, int width, int height, int format, int mipmapCount) -{ - glBindTexture(GL_TEXTURE_2D, 0); // Free any old binding - - GLuint id = 0; - - // Check texture format support by OpenGL 1.1 (compressed textures not supported) -#if defined(GRAPHICS_API_OPENGL_11) - if (format >= COMPRESSED_DXT1_RGB) - { - TraceLog(LOG_WARNING, "OpenGL 1.1 does not support GPU compressed texture formats"); - return id; - } -#endif - - if ((!texCompDXTSupported) && ((format == COMPRESSED_DXT1_RGB) || (format == COMPRESSED_DXT1_RGBA) || - (format == COMPRESSED_DXT3_RGBA) || (format == COMPRESSED_DXT5_RGBA))) - { - TraceLog(LOG_WARNING, "DXT compressed texture format not supported"); - return id; - } -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if ((!texCompETC1Supported) && (format == COMPRESSED_ETC1_RGB)) - { - TraceLog(LOG_WARNING, "ETC1 compressed texture format not supported"); - return id; - } - - if ((!texCompETC2Supported) && ((format == COMPRESSED_ETC2_RGB) || (format == COMPRESSED_ETC2_EAC_RGBA))) - { - TraceLog(LOG_WARNING, "ETC2 compressed texture format not supported"); - return id; - } - - if ((!texCompPVRTSupported) && ((format == COMPRESSED_PVRT_RGB) || (format == COMPRESSED_PVRT_RGBA))) - { - TraceLog(LOG_WARNING, "PVRT compressed texture format not supported"); - return id; - } - - if ((!texCompASTCSupported) && ((format == COMPRESSED_ASTC_4x4_RGBA) || (format == COMPRESSED_ASTC_8x8_RGBA))) - { - TraceLog(LOG_WARNING, "ASTC compressed texture format not supported"); - return id; - } -#endif - - glGenTextures(1, &id); // Generate Pointer to the texture - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - //glActiveTexture(GL_TEXTURE0); // If not defined, using GL_TEXTURE0 by default (shader texture) -#endif - - glBindTexture(GL_TEXTURE_2D, id); - -#if defined(GRAPHICS_API_OPENGL_33) - // NOTE: We define internal (GPU) format as GL_RGBA8 (probably BGRA8 in practice, driver takes care) - // NOTE: On embedded systems, we let the driver choose the best internal format - - // Support for multiple color modes (16bit color modes and grayscale) - // (sized)internalFormat format type - // GL_R GL_RED GL_UNSIGNED_BYTE - // GL_RGB565 GL_RGB GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT_5_6_5 - // GL_RGB5_A1 GL_RGBA GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT_5_5_5_1 - // GL_RGBA4 GL_RGBA GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT_4_4_4_4 - // GL_RGBA8 GL_RGBA GL_UNSIGNED_BYTE - // GL_RGB8 GL_RGB GL_UNSIGNED_BYTE - - switch (format) - { - case UNCOMPRESSED_GRAYSCALE: - { - glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, width, height, 0, GL_RED, GL_UNSIGNED_BYTE, (unsigned char *)data); - - // With swizzleMask we define how a one channel texture will be mapped to RGBA - // Required GL >= 3.3 or EXT_texture_swizzle/ARB_texture_swizzle - GLint swizzleMask[] = { GL_RED, GL_RED, GL_RED, GL_ONE }; - glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask); - - TraceLog(LOG_INFO, "[TEX ID %i] Grayscale texture loaded and swizzled", id); - } break; - case UNCOMPRESSED_GRAY_ALPHA: - { - glTexImage2D(GL_TEXTURE_2D, 0, GL_RG8, width, height, 0, GL_RG, GL_UNSIGNED_BYTE, (unsigned char *)data); - - GLint swizzleMask[] = { GL_RED, GL_RED, GL_RED, GL_GREEN }; - glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask); - } break; - - case UNCOMPRESSED_R5G6B5: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB565, width, height, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, (unsigned short *)data); break; - case UNCOMPRESSED_R8G8B8: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, (unsigned char *)data); break; - case UNCOMPRESSED_R5G5B5A1: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB5_A1, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, (unsigned short *)data); break; - case UNCOMPRESSED_R4G4B4A4: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA4, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, (unsigned short *)data); break; - case UNCOMPRESSED_R8G8B8A8: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, (unsigned char *)data); break; - case UNCOMPRESSED_R32G32B32: if (texFloatSupported) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, width, height, 0, GL_RGB, GL_FLOAT, (float *)data); break; - case COMPRESSED_DXT1_RGB: if (texCompDXTSupported) LoadTextureCompressed((unsigned char *)data, width, height, GL_COMPRESSED_RGB_S3TC_DXT1_EXT, mipmapCount); break; - case COMPRESSED_DXT1_RGBA: if (texCompDXTSupported) LoadTextureCompressed((unsigned char *)data, width, height, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, mipmapCount); break; - case COMPRESSED_DXT3_RGBA: if (texCompDXTSupported) LoadTextureCompressed((unsigned char *)data, width, height, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, mipmapCount); break; - case COMPRESSED_DXT5_RGBA: if (texCompDXTSupported) LoadTextureCompressed((unsigned char *)data, width, height, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, mipmapCount); break; - case COMPRESSED_ETC1_RGB: if (texCompETC1Supported) LoadTextureCompressed((unsigned char *)data, width, height, GL_ETC1_RGB8_OES, mipmapCount); break; // NOTE: Requires OpenGL ES 2.0 or OpenGL 4.3 - case COMPRESSED_ETC2_RGB: if (texCompETC2Supported) LoadTextureCompressed((unsigned char *)data, width, height, GL_COMPRESSED_RGB8_ETC2, mipmapCount); break; // NOTE: Requires OpenGL ES 3.0 or OpenGL 4.3 - case COMPRESSED_ETC2_EAC_RGBA: if (texCompETC2Supported) LoadTextureCompressed((unsigned char *)data, width, height, GL_COMPRESSED_RGBA8_ETC2_EAC, mipmapCount); break; // NOTE: Requires OpenGL ES 3.0 or OpenGL 4.3 - case COMPRESSED_PVRT_RGB: if (texCompPVRTSupported) LoadTextureCompressed((unsigned char *)data, width, height, GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG, mipmapCount); break; // NOTE: Requires PowerVR GPU - case COMPRESSED_PVRT_RGBA: if (texCompPVRTSupported) LoadTextureCompressed((unsigned char *)data, width, height, GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, mipmapCount); break; // NOTE: Requires PowerVR GPU - case COMPRESSED_ASTC_4x4_RGBA: if (texCompASTCSupported) LoadTextureCompressed((unsigned char *)data, width, height, GL_COMPRESSED_RGBA_ASTC_4x4_KHR, mipmapCount); break; // NOTE: Requires OpenGL ES 3.1 or OpenGL 4.3 - case COMPRESSED_ASTC_8x8_RGBA: if (texCompASTCSupported) LoadTextureCompressed((unsigned char *)data, width, height, GL_COMPRESSED_RGBA_ASTC_8x8_KHR, mipmapCount); break; // NOTE: Requires OpenGL ES 3.1 or OpenGL 4.3 - default: TraceLog(LOG_WARNING, "Texture format not recognized"); break; - } -#elif defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_ES2) - // NOTE: on OpenGL ES 2.0 (WebGL), internalFormat must match format and options allowed are: GL_LUMINANCE, GL_RGB, GL_RGBA - switch (format) - { - case UNCOMPRESSED_GRAYSCALE: glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, width, height, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, (unsigned char *)data); break; - case UNCOMPRESSED_GRAY_ALPHA: glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA, width, height, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, (unsigned char *)data); break; - case UNCOMPRESSED_R5G6B5: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, (unsigned short *)data); break; - case UNCOMPRESSED_R8G8B8: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, (unsigned char *)data); break; - case UNCOMPRESSED_R5G5B5A1: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, (unsigned short *)data); break; - case UNCOMPRESSED_R4G4B4A4: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, (unsigned short *)data); break; - case UNCOMPRESSED_R8G8B8A8: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, (unsigned char *)data); break; -#if defined(GRAPHICS_API_OPENGL_ES2) - case UNCOMPRESSED_R32G32B32: if (texFloatSupported) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_FLOAT, (float *)data); break; // NOTE: Requires extension OES_texture_float - case COMPRESSED_DXT1_RGB: if (texCompDXTSupported) LoadTextureCompressed((unsigned char *)data, width, height, GL_COMPRESSED_RGB_S3TC_DXT1_EXT, mipmapCount); break; - case COMPRESSED_DXT1_RGBA: if (texCompDXTSupported) LoadTextureCompressed((unsigned char *)data, width, height, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, mipmapCount); break; - case COMPRESSED_DXT3_RGBA: if (texCompDXTSupported) LoadTextureCompressed((unsigned char *)data, width, height, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, mipmapCount); break; // NOTE: Not supported by WebGL - case COMPRESSED_DXT5_RGBA: if (texCompDXTSupported) LoadTextureCompressed((unsigned char *)data, width, height, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, mipmapCount); break; // NOTE: Not supported by WebGL - case COMPRESSED_ETC1_RGB: if (texCompETC1Supported) LoadTextureCompressed((unsigned char *)data, width, height, GL_ETC1_RGB8_OES, mipmapCount); break; // NOTE: Requires OpenGL ES 2.0 or OpenGL 4.3 - case COMPRESSED_ETC2_RGB: if (texCompETC2Supported) LoadTextureCompressed((unsigned char *)data, width, height, GL_COMPRESSED_RGB8_ETC2, mipmapCount); break; // NOTE: Requires OpenGL ES 3.0 or OpenGL 4.3 - case COMPRESSED_ETC2_EAC_RGBA: if (texCompETC2Supported) LoadTextureCompressed((unsigned char *)data, width, height, GL_COMPRESSED_RGBA8_ETC2_EAC, mipmapCount); break; // NOTE: Requires OpenGL ES 3.0 or OpenGL 4.3 - case COMPRESSED_PVRT_RGB: if (texCompPVRTSupported) LoadTextureCompressed((unsigned char *)data, width, height, GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG, mipmapCount); break; // NOTE: Requires PowerVR GPU - case COMPRESSED_PVRT_RGBA: if (texCompPVRTSupported) LoadTextureCompressed((unsigned char *)data, width, height, GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, mipmapCount); break; // NOTE: Requires PowerVR GPU - case COMPRESSED_ASTC_4x4_RGBA: if (texCompASTCSupported) LoadTextureCompressed((unsigned char *)data, width, height, GL_COMPRESSED_RGBA_ASTC_4x4_KHR, mipmapCount); break; // NOTE: Requires OpenGL ES 3.1 or OpenGL 4.3 - case COMPRESSED_ASTC_8x8_RGBA: if (texCompASTCSupported) LoadTextureCompressed((unsigned char *)data, width, height, GL_COMPRESSED_RGBA_ASTC_8x8_KHR, mipmapCount); break; // NOTE: Requires OpenGL ES 3.1 or OpenGL 4.3 -#endif - default: TraceLog(LOG_WARNING, "Texture format not supported"); break; - } -#endif - - // Texture parameters configuration - // NOTE: glTexParameteri does NOT affect texture uploading, just the way it's used -#if defined(GRAPHICS_API_OPENGL_ES2) - // NOTE: OpenGL ES 2.0 with no GL_OES_texture_npot support (i.e. WebGL) has limited NPOT support, so CLAMP_TO_EDGE must be used - if (texNPOTSupported) - { - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // Set texture to repeat on x-axis - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // Set texture to repeat on y-axis - } - else - { - // NOTE: If using negative texture coordinates (LoadOBJ()), it does not work! - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); // Set texture to clamp on x-axis - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // Set texture to clamp on y-axis - } -#else - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // Set texture to repeat on x-axis - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // Set texture to repeat on y-axis -#endif - - // Magnification and minification filters - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // Alternative: GL_LINEAR - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); // Alternative: GL_LINEAR - -#if defined(GRAPHICS_API_OPENGL_33) - if (mipmapCount > 1) - { - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); // Activate Trilinear filtering for mipmaps (must be available) - } -#endif - - // At this point we have the texture loaded in GPU and texture parameters configured - - // NOTE: If mipmaps were not in data, they are not generated automatically - - // Unbind current texture - glBindTexture(GL_TEXTURE_2D, 0); - - if (id > 0) TraceLog(LOG_INFO, "[TEX ID %i] Texture created successfully (%ix%i)", id, width, height); - else TraceLog(LOG_WARNING, "Texture could not be created"); - - return id; -} - -// Update already loaded texture in GPU with new data -void rlUpdateTexture(unsigned int id, int width, int height, int format, const void *data) -{ - glBindTexture(GL_TEXTURE_2D, id); - -#if defined(GRAPHICS_API_OPENGL_33) - switch (format) - { - case UNCOMPRESSED_GRAYSCALE: glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RED, GL_UNSIGNED_BYTE, (unsigned char *)data); break; - case UNCOMPRESSED_GRAY_ALPHA: glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RG, GL_UNSIGNED_BYTE, (unsigned char *)data); break; - case UNCOMPRESSED_R5G6B5: glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, (unsigned short *)data); break; - case UNCOMPRESSED_R8G8B8: glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, (unsigned char *)data); break; - case UNCOMPRESSED_R5G5B5A1: glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, (unsigned short *)data); break; - case UNCOMPRESSED_R4G4B4A4: glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, (unsigned short *)data); break; - case UNCOMPRESSED_R8G8B8A8: glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, (unsigned char *)data); break; - default: TraceLog(LOG_WARNING, "Texture format updating not supported"); break; - } -#elif defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_ES2) - // NOTE: on OpenGL ES 2.0 (WebGL), internalFormat must match format and options allowed are: GL_LUMINANCE, GL_RGB, GL_RGBA - switch (format) - { - case UNCOMPRESSED_GRAYSCALE: glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_LUMINANCE, GL_UNSIGNED_BYTE, (unsigned char *)data); break; - case UNCOMPRESSED_GRAY_ALPHA: glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, (unsigned char *)data); break; - case UNCOMPRESSED_R5G6B5: glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, (unsigned short *)data); break; - case UNCOMPRESSED_R8G8B8: glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, (unsigned char *)data); break; - case UNCOMPRESSED_R5G5B5A1: glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, (unsigned short *)data); break; - case UNCOMPRESSED_R4G4B4A4: glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, (unsigned short *)data); break; - case UNCOMPRESSED_R8G8B8A8: glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, (unsigned char *)data); break; - default: TraceLog(LOG_WARNING, "Texture format updating not supported"); break; - } -#endif -} - -// Unload texture from GPU memory -void rlUnloadTexture(unsigned int id) -{ - if (id > 0) glDeleteTextures(1, &id); -} - - -// Load a texture to be used for rendering (fbo with color and depth attachments) -RenderTexture2D rlLoadRenderTexture(int width, int height) -{ - RenderTexture2D target; - - target.id = 0; - - target.texture.id = 0; - target.texture.width = width; - target.texture.height = height; - target.texture.format = UNCOMPRESSED_R8G8B8A8; - target.texture.mipmaps = 1; - - target.depth.id = 0; - target.depth.width = width; - target.depth.height = height; - target.depth.format = 19; //DEPTH_COMPONENT_24BIT - target.depth.mipmaps = 1; - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // Create the texture that will serve as the color attachment for the framebuffer - glGenTextures(1, &target.texture.id); - glBindTexture(GL_TEXTURE_2D, target.texture.id); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); - glBindTexture(GL_TEXTURE_2D, 0); - -#if defined(GRAPHICS_API_OPENGL_33) - #define USE_DEPTH_TEXTURE -#else - #define USE_DEPTH_RENDERBUFFER -#endif - -#if defined(USE_DEPTH_RENDERBUFFER) - // Create the renderbuffer that will serve as the depth attachment for the framebuffer. - glGenRenderbuffers(1, &target.depth.id); - glBindRenderbuffer(GL_RENDERBUFFER, target.depth.id); - glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, width, height); // GL_DEPTH_COMPONENT24 not supported on Android -#elif defined(USE_DEPTH_TEXTURE) - // NOTE: We can also use a texture for depth buffer (GL_ARB_depth_texture/GL_OES_depth_texture extension required) - // A renderbuffer is simpler than a texture and could offer better performance on embedded devices - glGenTextures(1, &target.depth.id); - glBindTexture(GL_TEXTURE_2D, target.depth.id); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, width, height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL); - glBindTexture(GL_TEXTURE_2D, 0); -#endif - - // Create the framebuffer object - glGenFramebuffers(1, &target.id); - glBindFramebuffer(GL_FRAMEBUFFER, target.id); - - // Attach color texture and depth renderbuffer to FBO - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, target.texture.id, 0); -#if defined(USE_DEPTH_RENDERBUFFER) - glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, target.depth.id); -#elif defined(USE_DEPTH_TEXTURE) - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, target.depth.id, 0); -#endif - - GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); - - if (status != GL_FRAMEBUFFER_COMPLETE) - { - TraceLog(LOG_WARNING, "Framebuffer object could not be created..."); - - switch (status) - { - case GL_FRAMEBUFFER_UNSUPPORTED: TraceLog(LOG_WARNING, "Framebuffer is unsupported"); break; - case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: TraceLog(LOG_WARNING, "Framebuffer incomplete attachment"); break; -#if defined(GRAPHICS_API_OPENGL_ES2) - case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS: TraceLog(LOG_WARNING, "Framebuffer incomplete dimensions"); break; -#endif - case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: TraceLog(LOG_WARNING, "Framebuffer incomplete missing attachment"); break; - default: break; - } - - glDeleteTextures(1, &target.texture.id); - glDeleteTextures(1, &target.depth.id); - glDeleteFramebuffers(1, &target.id); - } - else TraceLog(LOG_INFO, "[FBO ID %i] Framebuffer object created successfully", target.id); - - glBindFramebuffer(GL_FRAMEBUFFER, 0); -#endif - - return target; -} - -// Generate mipmap data for selected texture -void rlGenerateMipmaps(Texture2D *texture) -{ - glBindTexture(GL_TEXTURE_2D, texture->id); - - // Check if texture is power-of-two (POT) - bool texIsPOT = false; - - if (((texture->width > 0) && ((texture->width & (texture->width - 1)) == 0)) && - ((texture->height > 0) && ((texture->height & (texture->height - 1)) == 0))) texIsPOT = true; - - if ((texIsPOT) || (texNPOTSupported)) - { -#if defined(GRAPHICS_API_OPENGL_11) - // Compute required mipmaps - void *data = rlReadTexturePixels(*texture); - - // NOTE: data size is reallocated to fit mipmaps data - // NOTE: CPU mipmap generation only supports RGBA 32bit data - int mipmapCount = GenerateMipmaps(data, texture->width, texture->height); - - int size = texture->width*texture->height*4; // RGBA 32bit only - int offset = size; - - int mipWidth = texture->width/2; - int mipHeight = texture->height/2; - - // Load the mipmaps - for (int level = 1; level < mipmapCount; level++) - { - glTexImage2D(GL_TEXTURE_2D, level, GL_RGBA8, mipWidth, mipHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, data + offset); - - size = mipWidth*mipHeight*4; - offset += size; - - mipWidth /= 2; - mipHeight /= 2; - } - - TraceLog(LOG_WARNING, "[TEX ID %i] Mipmaps generated manually on CPU side", texture->id); - - // NOTE: Once mipmaps have been generated and data has been uploaded to GPU VRAM, we can discard RAM data - free(data); - - texture->mipmaps = mipmapCount + 1; -#endif - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - //glHint(GL_GENERATE_MIPMAP_HINT, GL_DONT_CARE); // Hint for mipmaps generation algorythm: GL_FASTEST, GL_NICEST, GL_DONT_CARE - glGenerateMipmap(GL_TEXTURE_2D); // Generate mipmaps automatically - TraceLog(LOG_INFO, "[TEX ID %i] Mipmaps generated automatically", texture->id); - - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); // Activate Trilinear filtering for mipmaps - - #define MIN(a,b) (((a)<(b))?(a):(b)) - #define MAX(a,b) (((a)>(b))?(a):(b)) - - texture->mipmaps = 1 + (int)floor(log(MAX(texture->width, texture->height))/log(2)); -#endif - } - else TraceLog(LOG_WARNING, "[TEX ID %i] Mipmaps can not be generated", texture->id); - - glBindTexture(GL_TEXTURE_2D, 0); -} - -// Upload vertex data into a VAO (if supported) and VBO -// TODO: Check if mesh has already been loaded in GPU -void rlLoadMesh(Mesh *mesh, bool dynamic) -{ - mesh->vaoId = 0; // Vertex Array Object - mesh->vboId[0] = 0; // Vertex positions VBO - mesh->vboId[1] = 0; // Vertex texcoords VBO - mesh->vboId[2] = 0; // Vertex normals VBO - mesh->vboId[3] = 0; // Vertex colors VBO - mesh->vboId[4] = 0; // Vertex tangents VBO - mesh->vboId[5] = 0; // Vertex texcoords2 VBO - mesh->vboId[6] = 0; // Vertex indices VBO - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - int drawHint = GL_STATIC_DRAW; - if (dynamic) drawHint = GL_DYNAMIC_DRAW; - - if (vaoSupported) - { - // Initialize Quads VAO (Buffer A) - glGenVertexArrays(1, &mesh->vaoId); - glBindVertexArray(mesh->vaoId); - } - - // NOTE: Attributes must be uploaded considering default locations points - - // Enable vertex attributes: position (shader-location = 0) - glGenBuffers(1, &mesh->vboId[0]); - glBindBuffer(GL_ARRAY_BUFFER, mesh->vboId[0]); - glBufferData(GL_ARRAY_BUFFER, sizeof(float)*3*mesh->vertexCount, mesh->vertices, drawHint); - glVertexAttribPointer(0, 3, GL_FLOAT, 0, 0, 0); - glEnableVertexAttribArray(0); - - // Enable vertex attributes: texcoords (shader-location = 1) - glGenBuffers(1, &mesh->vboId[1]); - glBindBuffer(GL_ARRAY_BUFFER, mesh->vboId[1]); - glBufferData(GL_ARRAY_BUFFER, sizeof(float)*2*mesh->vertexCount, mesh->texcoords, drawHint); - glVertexAttribPointer(1, 2, GL_FLOAT, 0, 0, 0); - glEnableVertexAttribArray(1); - - // Enable vertex attributes: normals (shader-location = 2) - if (mesh->normals != NULL) - { - glGenBuffers(1, &mesh->vboId[2]); - glBindBuffer(GL_ARRAY_BUFFER, mesh->vboId[2]); - glBufferData(GL_ARRAY_BUFFER, sizeof(float)*3*mesh->vertexCount, mesh->normals, drawHint); - glVertexAttribPointer(2, 3, GL_FLOAT, 0, 0, 0); - glEnableVertexAttribArray(2); - } - else - { - // Default color vertex attribute set to WHITE - glVertexAttrib3f(2, 1.0f, 1.0f, 1.0f); - glDisableVertexAttribArray(2); - } - - // Default color vertex attribute (shader-location = 3) - if (mesh->colors != NULL) - { - glGenBuffers(1, &mesh->vboId[3]); - glBindBuffer(GL_ARRAY_BUFFER, mesh->vboId[3]); - glBufferData(GL_ARRAY_BUFFER, sizeof(unsigned char)*4*mesh->vertexCount, mesh->colors, drawHint); - glVertexAttribPointer(3, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, 0); - glEnableVertexAttribArray(3); - } - else - { - // Default color vertex attribute set to WHITE - glVertexAttrib4f(3, 1.0f, 1.0f, 1.0f, 1.0f); - glDisableVertexAttribArray(3); - } - - // Default tangent vertex attribute (shader-location = 4) - if (mesh->tangents != NULL) - { - glGenBuffers(1, &mesh->vboId[4]); - glBindBuffer(GL_ARRAY_BUFFER, mesh->vboId[4]); - glBufferData(GL_ARRAY_BUFFER, sizeof(float)*3*mesh->vertexCount, mesh->tangents, drawHint); - glVertexAttribPointer(4, 3, GL_FLOAT, 0, 0, 0); - glEnableVertexAttribArray(4); - } - else - { - // Default tangents vertex attribute - glVertexAttrib3f(4, 0.0f, 0.0f, 0.0f); - glDisableVertexAttribArray(4); - } - - // Default texcoord2 vertex attribute (shader-location = 5) - if (mesh->texcoords2 != NULL) - { - glGenBuffers(1, &mesh->vboId[5]); - glBindBuffer(GL_ARRAY_BUFFER, mesh->vboId[5]); - glBufferData(GL_ARRAY_BUFFER, sizeof(float)*2*mesh->vertexCount, mesh->texcoords2, drawHint); - glVertexAttribPointer(5, 2, GL_FLOAT, 0, 0, 0); - glEnableVertexAttribArray(5); - } - else - { - // Default tangents vertex attribute - glVertexAttrib2f(5, 0.0f, 0.0f); - glDisableVertexAttribArray(5); - } - - if (mesh->indices != NULL) - { - glGenBuffers(1, &mesh->vboId[6]); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->vboId[6]); - glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned short)*mesh->triangleCount*3, mesh->indices, GL_STATIC_DRAW); - } - - if (vaoSupported) - { - if (mesh->vaoId > 0) TraceLog(LOG_INFO, "[VAO ID %i] Mesh uploaded successfully to VRAM (GPU)", mesh->vaoId); - else TraceLog(LOG_WARNING, "Mesh could not be uploaded to VRAM (GPU)"); - } - else - { - TraceLog(LOG_INFO, "[VBOs] Mesh uploaded successfully to VRAM (GPU)"); - } -#endif -} - -// Update vertex data on GPU (upload new data to one buffer) -void rlUpdateMesh(Mesh mesh, int buffer, int numVertex) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // Activate mesh VAO - if (vaoSupported) glBindVertexArray(mesh.vaoId); - - switch (buffer) - { - case 0: // Update vertices (vertex position) - { - glBindBuffer(GL_ARRAY_BUFFER, mesh.vboId[0]); - if (numVertex >= mesh.vertexCount) glBufferData(GL_ARRAY_BUFFER, sizeof(float)*3*numVertex, mesh.vertices, GL_DYNAMIC_DRAW); - else glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(float)*3*numVertex, mesh.vertices); - - } break; - case 1: // Update texcoords (vertex texture coordinates) - { - glBindBuffer(GL_ARRAY_BUFFER, mesh.vboId[1]); - if (numVertex >= mesh.vertexCount) glBufferData(GL_ARRAY_BUFFER, sizeof(float)*2*numVertex, mesh.texcoords, GL_DYNAMIC_DRAW); - else glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(float)*2*numVertex, mesh.texcoords); - - } break; - case 2: // Update normals (vertex normals) - { - glBindBuffer(GL_ARRAY_BUFFER, mesh.vboId[2]); - if (numVertex >= mesh.vertexCount) glBufferData(GL_ARRAY_BUFFER, sizeof(float)*3*numVertex, mesh.normals, GL_DYNAMIC_DRAW); - else glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(float)*3*numVertex, mesh.normals); - - } break; - case 3: // Update colors (vertex colors) - { - glBindBuffer(GL_ARRAY_BUFFER, mesh.vboId[3]); - if (numVertex >= mesh.vertexCount) glBufferData(GL_ARRAY_BUFFER, sizeof(float)*4*numVertex, mesh.colors, GL_DYNAMIC_DRAW); - else glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(unsigned char)*4*numVertex, mesh.colors); - - } break; - case 4: // Update tangents (vertex tangents) - { - glBindBuffer(GL_ARRAY_BUFFER, mesh.vboId[4]); - if (numVertex >= mesh.vertexCount) glBufferData(GL_ARRAY_BUFFER, sizeof(float)*3*numVertex, mesh.tangents, GL_DYNAMIC_DRAW); - else glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(float)*3*numVertex, mesh.tangents); - } break; - case 5: // Update texcoords2 (vertex second texture coordinates) - { - glBindBuffer(GL_ARRAY_BUFFER, mesh.vboId[5]); - if (numVertex >= mesh.vertexCount) glBufferData(GL_ARRAY_BUFFER, sizeof(float)*2*numVertex, mesh.texcoords2, GL_DYNAMIC_DRAW); - else glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(float)*2*numVertex, mesh.texcoords2); - } break; - default: break; - } - - // Unbind the current VAO - if (vaoSupported) glBindVertexArray(0); - - // Another option would be using buffer mapping... - //mesh.vertices = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE); - // Now we can modify vertices - //glUnmapBuffer(GL_ARRAY_BUFFER); -#endif -} - -// Draw a 3d mesh with material and transform -void rlDrawMesh(Mesh mesh, Material material, Matrix transform) -{ -#if defined(GRAPHICS_API_OPENGL_11) - glEnable(GL_TEXTURE_2D); - glBindTexture(GL_TEXTURE_2D, material.maps[MAP_DIFFUSE].texture.id); - - // NOTE: On OpenGL 1.1 we use Vertex Arrays to draw model - glEnableClientState(GL_VERTEX_ARRAY); // Enable vertex array - glEnableClientState(GL_TEXTURE_COORD_ARRAY); // Enable texture coords array - if (mesh.normals != NULL) glEnableClientState(GL_NORMAL_ARRAY); // Enable normals array - if (mesh.colors != NULL) glEnableClientState(GL_COLOR_ARRAY); // Enable colors array - - glVertexPointer(3, GL_FLOAT, 0, mesh.vertices); // Pointer to vertex coords array - glTexCoordPointer(2, GL_FLOAT, 0, mesh.texcoords); // Pointer to texture coords array - if (mesh.normals != NULL) glNormalPointer(GL_FLOAT, 0, mesh.normals); // Pointer to normals array - if (mesh.colors != NULL) glColorPointer(4, GL_UNSIGNED_BYTE, 0, mesh.colors); // Pointer to colors array - - rlPushMatrix(); - rlMultMatrixf(MatrixToFloat(transform)); - rlColor4ub(material.maps[MAP_DIFFUSE].color.r, material.maps[MAP_DIFFUSE].color.g, material.maps[MAP_DIFFUSE].color.b, material.maps[MAP_DIFFUSE].color.a); - - if (mesh.indices != NULL) glDrawElements(GL_TRIANGLES, mesh.triangleCount*3, GL_UNSIGNED_SHORT, mesh.indices); - else glDrawArrays(GL_TRIANGLES, 0, mesh.vertexCount); - rlPopMatrix(); - - glDisableClientState(GL_VERTEX_ARRAY); // Disable vertex array - glDisableClientState(GL_TEXTURE_COORD_ARRAY); // Disable texture coords array - if (mesh.normals != NULL) glDisableClientState(GL_NORMAL_ARRAY); // Disable normals array - if (mesh.colors != NULL) glDisableClientState(GL_NORMAL_ARRAY); // Disable colors array - - glDisable(GL_TEXTURE_2D); - glBindTexture(GL_TEXTURE_2D, 0); -#endif - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // Bind shader program - glUseProgram(material.shader.id); - - // Matrices and other values required by shader - //----------------------------------------------------- - // Calculate and send to shader model matrix (used by PBR shader) - if (material.shader.locs[LOC_MATRIX_MODEL] != -1) SetShaderValueMatrix(material.shader, material.shader.locs[LOC_MATRIX_MODEL], transform); - - // Upload to shader material.colDiffuse - if (material.shader.locs[LOC_COLOR_DIFFUSE] != -1) - glUniform4f(material.shader.locs[LOC_COLOR_DIFFUSE], (float)material.maps[MAP_DIFFUSE].color.r/255, - (float)material.maps[MAP_DIFFUSE].color.g/255, - (float)material.maps[MAP_DIFFUSE].color.b/255, - (float)material.maps[MAP_DIFFUSE].color.a/255); - - // Upload to shader material.colSpecular (if available) - if (material.shader.locs[LOC_COLOR_SPECULAR] != -1) - glUniform4f(material.shader.locs[LOC_COLOR_SPECULAR], (float)material.maps[MAP_SPECULAR].color.r/255, - (float)material.maps[MAP_SPECULAR].color.g/255, - (float)material.maps[MAP_SPECULAR].color.b/255, - (float)material.maps[MAP_SPECULAR].color.a/255); - - if (material.shader.locs[LOC_MATRIX_VIEW] != -1) SetShaderValueMatrix(material.shader, material.shader.locs[LOC_MATRIX_VIEW], modelview); - if (material.shader.locs[LOC_MATRIX_PROJECTION] != -1) SetShaderValueMatrix(material.shader, material.shader.locs[LOC_MATRIX_PROJECTION], projection); - - // At this point the modelview matrix just contains the view matrix (camera) - // That's because Begin3dMode() sets it an no model-drawing function modifies it, all use rlPushMatrix() and rlPopMatrix() - Matrix matView = modelview; // View matrix (camera) - Matrix matProjection = projection; // Projection matrix (perspective) - - // Calculate model-view matrix combining matModel and matView - Matrix matModelView = MatrixMultiply(transform, matView); // Transform to camera-space coordinates - //----------------------------------------------------- - - // Bind active texture maps (if available) - for (int i = 0; i < MAX_MATERIAL_MAPS; i++) - { - if (material.maps[i].texture.id > 0) - { - glActiveTexture(GL_TEXTURE0 + i); - if ((i == MAP_IRRADIANCE) || (i == MAP_PREFILTER) || (i == MAP_CUBEMAP)) glBindTexture(GL_TEXTURE_CUBE_MAP, material.maps[i].texture.id); - else glBindTexture(GL_TEXTURE_2D, material.maps[i].texture.id); - - glUniform1i(material.shader.locs[LOC_MAP_DIFFUSE + i], i); - } - } - - // Bind vertex array objects (or VBOs) - if (vaoSupported) glBindVertexArray(mesh.vaoId); - else - { - // TODO: Simplify VBO binding into a for loop - - // Bind mesh VBO data: vertex position (shader-location = 0) - glBindBuffer(GL_ARRAY_BUFFER, mesh.vboId[0]); - glVertexAttribPointer(material.shader.locs[LOC_VERTEX_POSITION], 3, GL_FLOAT, 0, 0, 0); - glEnableVertexAttribArray(material.shader.locs[LOC_VERTEX_POSITION]); - - // Bind mesh VBO data: vertex texcoords (shader-location = 1) - glBindBuffer(GL_ARRAY_BUFFER, mesh.vboId[1]); - glVertexAttribPointer(material.shader.locs[LOC_VERTEX_TEXCOORD01], 2, GL_FLOAT, 0, 0, 0); - glEnableVertexAttribArray(material.shader.locs[LOC_VERTEX_TEXCOORD01]); - - // Bind mesh VBO data: vertex normals (shader-location = 2, if available) - if (material.shader.locs[LOC_VERTEX_NORMAL] != -1) - { - glBindBuffer(GL_ARRAY_BUFFER, mesh.vboId[2]); - glVertexAttribPointer(material.shader.locs[LOC_VERTEX_NORMAL], 3, GL_FLOAT, 0, 0, 0); - glEnableVertexAttribArray(material.shader.locs[LOC_VERTEX_NORMAL]); - } - - // Bind mesh VBO data: vertex colors (shader-location = 3, if available) - if (material.shader.locs[LOC_VERTEX_COLOR] != -1) - { - if (mesh.vboId[3] != 0) - { - glBindBuffer(GL_ARRAY_BUFFER, mesh.vboId[3]); - glVertexAttribPointer(material.shader.locs[LOC_VERTEX_COLOR], 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, 0); - glEnableVertexAttribArray(material.shader.locs[LOC_VERTEX_COLOR]); - } - else - { - // Set default value for unused attribute - // NOTE: Required when using default shader and no VAO support - glVertexAttrib4f(material.shader.locs[LOC_VERTEX_COLOR], 1.0f, 1.0f, 1.0f, 1.0f); - glDisableVertexAttribArray(material.shader.locs[LOC_VERTEX_COLOR]); - } - } - - // Bind mesh VBO data: vertex tangents (shader-location = 4, if available) - if (material.shader.locs[LOC_VERTEX_TANGENT] != -1) - { - glBindBuffer(GL_ARRAY_BUFFER, mesh.vboId[4]); - glVertexAttribPointer(material.shader.locs[LOC_VERTEX_TANGENT], 3, GL_FLOAT, 0, 0, 0); - glEnableVertexAttribArray(material.shader.locs[LOC_VERTEX_TANGENT]); - } - - // Bind mesh VBO data: vertex texcoords2 (shader-location = 5, if available) - if (material.shader.locs[LOC_VERTEX_TEXCOORD02] != -1) - { - glBindBuffer(GL_ARRAY_BUFFER, mesh.vboId[5]); - glVertexAttribPointer(material.shader.locs[LOC_VERTEX_TEXCOORD02], 2, GL_FLOAT, 0, 0, 0); - glEnableVertexAttribArray(material.shader.locs[LOC_VERTEX_TEXCOORD02]); - } - - if (mesh.indices != NULL) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.vboId[6]); - } - - int eyesCount = 1; -#if defined(SUPPORT_VR_SIMULATOR) - if (vrStereoRender) eyesCount = 2; -#endif - - for (int eye = 0; eye < eyesCount; eye++) - { - if (eyesCount == 1) modelview = matModelView; - #if defined(SUPPORT_VR_SIMULATOR) - else SetStereoView(eye, matProjection, matModelView); - #endif - - // Calculate model-view-projection matrix (MVP) - Matrix matMVP = MatrixMultiply(modelview, projection); // Transform to screen-space coordinates - - // Send combined model-view-projection matrix to shader - glUniformMatrix4fv(material.shader.locs[LOC_MATRIX_MVP], 1, false, MatrixToFloat(matMVP)); - - // Draw call! - if (mesh.indices != NULL) glDrawElements(GL_TRIANGLES, mesh.triangleCount*3, GL_UNSIGNED_SHORT, 0); // Indexed vertices draw - else glDrawArrays(GL_TRIANGLES, 0, mesh.vertexCount); - } - - // Unbind all binded texture maps - for (int i = 0; i < MAX_MATERIAL_MAPS; i++) - { - glActiveTexture(GL_TEXTURE0 + i); // Set shader active texture - if ((i == MAP_IRRADIANCE) || (i == MAP_PREFILTER) || (i == MAP_CUBEMAP)) glBindTexture(GL_TEXTURE_CUBE_MAP, 0); - else glBindTexture(GL_TEXTURE_2D, 0); // Unbind current active texture - } - - // Unind vertex array objects (or VBOs) - if (vaoSupported) glBindVertexArray(0); - else - { - glBindBuffer(GL_ARRAY_BUFFER, 0); - if (mesh.indices != NULL) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); - } - - // Unbind shader program - glUseProgram(0); - - // Restore projection/modelview matrices - // NOTE: In stereo rendering matrices are being modified to fit every eye - projection = matProjection; - modelview = matView; -#endif -} - -// Unload mesh data from CPU and GPU -void rlUnloadMesh(Mesh *mesh) -{ - if (mesh->vertices != NULL) free(mesh->vertices); - if (mesh->texcoords != NULL) free(mesh->texcoords); - if (mesh->normals != NULL) free(mesh->normals); - if (mesh->colors != NULL) free(mesh->colors); - if (mesh->tangents != NULL) free(mesh->tangents); - if (mesh->texcoords2 != NULL) free(mesh->texcoords2); - if (mesh->indices != NULL) free(mesh->indices); - - rlDeleteBuffers(mesh->vboId[0]); // vertex - rlDeleteBuffers(mesh->vboId[1]); // texcoords - rlDeleteBuffers(mesh->vboId[2]); // normals - rlDeleteBuffers(mesh->vboId[3]); // colors - rlDeleteBuffers(mesh->vboId[4]); // tangents - rlDeleteBuffers(mesh->vboId[5]); // texcoords2 - rlDeleteBuffers(mesh->vboId[6]); // indices - - rlDeleteVertexArrays(mesh->vaoId); -} - -// Read screen pixel data (color buffer) -unsigned char *rlReadScreenPixels(int width, int height) -{ - unsigned char *screenData = (unsigned char *)calloc(width*height*4, sizeof(unsigned char)); - - // NOTE: glReadPixels returns image flipped vertically -> (0,0) is the bottom left corner of the framebuffer - glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, screenData); - - // Flip image vertically! - unsigned char *imgData = (unsigned char *)malloc(width*height*sizeof(unsigned char)*4); - - for (int y = height - 1; y >= 0; y--) - { - for (int x = 0; x < (width*4); x++) - { - // Flip line - imgData[((height - 1) - y)*width*4 + x] = screenData[(y*width*4) + x]; - - // Set alpha component value to 255 (no trasparent image retrieval) - // NOTE: Alpha value has already been applied to RGB in framebuffer, we don't need it! - if (((x + 1)%4) == 0) imgData[((height - 1) - y)*width*4 + x] = 255; - } - } - - free(screenData); - - return imgData; // NOTE: image data should be freed -} - -// Read texture pixel data -// NOTE: glGetTexImage() is not available on OpenGL ES 2.0 -// Texture2D width and height are required on OpenGL ES 2.0. There is no way to get it from texture id. -void *rlReadTexturePixels(Texture2D texture) -{ - void *pixels = NULL; - -#if defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_33) - glBindTexture(GL_TEXTURE_2D, texture.id); - - // NOTE: Using texture.id, we can retrieve some texture info (but not on OpenGL ES 2.0) - /* - int width, height, format; - glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &width); - glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &height); - glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_INTERNAL_FORMAT, &format); - // Other texture info: GL_TEXTURE_RED_SIZE, GL_TEXTURE_GREEN_SIZE, GL_TEXTURE_BLUE_SIZE, GL_TEXTURE_ALPHA_SIZE - */ - - int glFormat = 0, glType = 0; - - unsigned int size = texture.width*texture.height; - - // NOTE: GL_LUMINANCE and GL_LUMINANCE_ALPHA are removed since OpenGL 3.1 - // Must be replaced by GL_RED and GL_RG on Core OpenGL 3.3 - - switch (texture.format) - { -#if defined(GRAPHICS_API_OPENGL_11) - case UNCOMPRESSED_GRAYSCALE: pixels = (unsigned char *)malloc(size); glFormat = GL_LUMINANCE; glType = GL_UNSIGNED_BYTE; break; // 8 bit per pixel (no alpha) - case UNCOMPRESSED_GRAY_ALPHA: pixels = (unsigned char *)malloc(size*2); glFormat = GL_LUMINANCE_ALPHA; glType = GL_UNSIGNED_BYTE; break; // 16 bpp (2 channels) -#elif defined(GRAPHICS_API_OPENGL_33) - case UNCOMPRESSED_GRAYSCALE: pixels = (unsigned char *)malloc(size); glFormat = GL_RED; glType = GL_UNSIGNED_BYTE; break; - case UNCOMPRESSED_GRAY_ALPHA: pixels = (unsigned char *)malloc(size*2); glFormat = GL_RG; glType = GL_UNSIGNED_BYTE; break; -#endif - case UNCOMPRESSED_R5G6B5: pixels = (unsigned short *)malloc(size); glFormat = GL_RGB; glType = GL_UNSIGNED_SHORT_5_6_5; break; // 16 bpp - case UNCOMPRESSED_R8G8B8: pixels = (unsigned char *)malloc(size*3); glFormat = GL_RGB; glType = GL_UNSIGNED_BYTE; break; // 24 bpp - case UNCOMPRESSED_R5G5B5A1: pixels = (unsigned short *)malloc(size); glFormat = GL_RGBA; glType = GL_UNSIGNED_SHORT_5_5_5_1; break; // 16 bpp (1 bit alpha) - case UNCOMPRESSED_R4G4B4A4: pixels = (unsigned short *)malloc(size); glFormat = GL_RGBA; glType = GL_UNSIGNED_SHORT_4_4_4_4; break; // 16 bpp (4 bit alpha) - case UNCOMPRESSED_R8G8B8A8: pixels = (unsigned char *)malloc(size*4); glFormat = GL_RGBA; glType = GL_UNSIGNED_BYTE; break; // 32 bpp - default: TraceLog(LOG_WARNING, "Texture data retrieval, format not suported"); break; - } - - // NOTE: Each row written to or read from by OpenGL pixel operations like glGetTexImage are aligned to a 4 byte boundary by default, which may add some padding. - // Use glPixelStorei to modify padding with the GL_[UN]PACK_ALIGNMENT setting. - // GL_PACK_ALIGNMENT affects operations that read from OpenGL memory (glReadPixels, glGetTexImage, etc.) - // GL_UNPACK_ALIGNMENT affects operations that write to OpenGL memory (glTexImage, etc.) - glPixelStorei(GL_PACK_ALIGNMENT, 1); - - glGetTexImage(GL_TEXTURE_2D, 0, glFormat, glType, pixels); - - glBindTexture(GL_TEXTURE_2D, 0); -#endif - -#if defined(GRAPHICS_API_OPENGL_ES2) - - RenderTexture2D fbo = rlLoadRenderTexture(texture.width, texture.height); - - // NOTE: Two possible Options: - // 1 - Bind texture to color fbo attachment and glReadPixels() - // 2 - Create an fbo, activate it, render quad with texture, glReadPixels() - -#define GET_TEXTURE_FBO_OPTION_1 // It works -#if defined(GET_TEXTURE_FBO_OPTION_1) - glBindFramebuffer(GL_FRAMEBUFFER, fbo.id); - glBindTexture(GL_TEXTURE_2D, 0); - - // Attach our texture to FBO -> Texture must be RGB - // NOTE: Previoust attached texture is automatically detached - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture.id, 0); - - pixels = (unsigned char *)malloc(texture.width*texture.height*4*sizeof(unsigned char)); - - // NOTE: We read data as RGBA because FBO texture is configured as RGBA, despite binding a RGB texture... - glReadPixels(0, 0, texture.width, texture.height, GL_RGBA, GL_UNSIGNED_BYTE, pixels); - - // Re-attach internal FBO color texture before deleting it - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fbo.texture.id, 0); - - glBindFramebuffer(GL_FRAMEBUFFER, 0); - -#elif defined(GET_TEXTURE_FBO_OPTION_2) - // Render texture to fbo - glBindFramebuffer(GL_FRAMEBUFFER, fbo.id); - - glClearColor(0.0f, 0.0f, 0.0f, 0.0f); - glClearDepthf(1.0f); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - glViewport(0, 0, width, height); - //glMatrixMode(GL_PROJECTION); - //glLoadIdentity(); - rlOrtho(0.0, width, height, 0.0, 0.0, 1.0); - //glMatrixMode(GL_MODELVIEW); - //glLoadIdentity(); - //glDisable(GL_TEXTURE_2D); - //glDisable(GL_BLEND); - glEnable(GL_DEPTH_TEST); - - Model quad; - //quad.mesh = GenMeshQuad(width, height); - quad.transform = MatrixIdentity(); - quad.shader = defaultShader; - - DrawModel(quad, (Vector3){ 0.0f, 0.0f, 0.0f }, 1.0f, WHITE); - - pixels = (unsigned char *)malloc(texture.width*texture.height*3*sizeof(unsigned char)); - - glReadPixels(0, 0, texture.width, texture.height, GL_RGB, GL_UNSIGNED_BYTE, pixels); - - // Bind framebuffer 0, which means render to back buffer - glBindFramebuffer(GL_FRAMEBUFFER, 0); - - UnloadModel(quad); -#endif // GET_TEXTURE_FBO_OPTION - - // Clean up temporal fbo - rlDeleteRenderTextures(fbo); - -#endif - - return pixels; -} - -/* -// TODO: Record draw calls to be processed in batch -// NOTE: Global state must be kept -void rlRecordDraw(void) -{ - // TODO: Before adding a new draw, check if anything changed from last stored draw -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - draws[drawsCounter].vaoId = currentState.vaoId; // lines.id, trangles.id, quads.id? - draws[drawsCounter].textureId = currentState.textureId; // whiteTexture? - draws[drawsCounter].shaderId = currentState.shaderId; // defaultShader.id - draws[drawsCounter].projection = projection; - draws[drawsCounter].modelview = modelview; - draws[drawsCounter].vertexCount = currentState.vertexCount; - - drawsCounter++; -#endif -} -*/ - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Shaders Functions -// NOTE: Those functions are exposed directly to the user in raylib.h -//---------------------------------------------------------------------------------- - -// Get default internal texture (white texture) -Texture2D GetTextureDefault(void) -{ - Texture2D texture; - - texture.id = whiteTexture; - texture.width = 1; - texture.height = 1; - texture.mipmaps = 1; - texture.format = UNCOMPRESSED_R8G8B8A8; - - return texture; -} - -// Get default shader -Shader GetShaderDefault(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - return defaultShader; -#else - Shader shader = { 0 }; - return shader; -#endif -} - -// Load text data from file -// NOTE: text chars array should be freed manually -char *LoadText(const char *fileName) -{ - FILE *textFile; - char *text = NULL; - - int count = 0; - - if (fileName != NULL) - { - textFile = fopen(fileName,"rt"); - - if (textFile != NULL) - { - fseek(textFile, 0, SEEK_END); - count = ftell(textFile); - rewind(textFile); - - if (count > 0) - { - text = (char *)malloc(sizeof(char)*(count + 1)); - count = fread(text, sizeof(char), count, textFile); - text[count] = '\0'; - } - - fclose(textFile); - } - else TraceLog(LOG_WARNING, "[%s] Text file could not be opened", fileName); - } - - return text; -} - -// Load shader from files and bind default locations -Shader LoadShader(char *vsFileName, char *fsFileName) -{ - Shader shader = { 0 }; - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // Shaders loading from external text file - char *vShaderStr = LoadText(vsFileName); - char *fShaderStr = LoadText(fsFileName); - - if ((vShaderStr != NULL) && (fShaderStr != NULL)) - { - shader.id = LoadShaderProgram(vShaderStr, fShaderStr); - - // After shader loading, we TRY to set default location names - if (shader.id > 0) SetShaderDefaultLocations(&shader); - - // Shader strings must be freed - free(vShaderStr); - free(fShaderStr); - } - - if (shader.id == 0) - { - TraceLog(LOG_WARNING, "Custom shader could not be loaded"); - shader = defaultShader; - } - - - // Get available shader uniforms - // NOTE: This information is useful for debug... - int uniformCount = -1; - - glGetProgramiv(shader.id, GL_ACTIVE_UNIFORMS, &uniformCount); - - for(int i = 0; i < uniformCount; i++) - { - int namelen = -1; - int num = -1; - char name[256]; // Assume no variable names longer than 256 - GLenum type = GL_ZERO; - - // Get the name of the uniforms - glGetActiveUniform(shader.id, i,sizeof(name) - 1, &namelen, &num, &type, name); - - name[namelen] = 0; - - // Get the location of the named uniform - GLuint location = glGetUniformLocation(shader.id, name); - - TraceLog(LOG_DEBUG, "[SHDR ID %i] Active uniform [%s] set at location: %i", shader.id, name, location); - } - -#endif - - return shader; -} - -// Unload shader from GPU memory (VRAM) -void UnloadShader(Shader shader) -{ - if (shader.id > 0) - { - rlDeleteShader(shader.id); - TraceLog(LOG_INFO, "[SHDR ID %i] Unloaded shader program data", shader.id); - } -} - -// Begin custom shader mode -void BeginShaderMode(Shader shader) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if (currentShader.id != shader.id) - { - rlglDraw(); - currentShader = shader; - } -#endif -} - -// End custom shader mode (returns to default shader) -void EndShaderMode(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - BeginShaderMode(defaultShader); -#endif -} - -// Get shader uniform location -int GetShaderLocation(Shader shader, const char *uniformName) -{ - int location = -1; -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - location = glGetUniformLocation(shader.id, uniformName); - - if (location == -1) TraceLog(LOG_WARNING, "[SHDR ID %i] Shader uniform [%s] COULD NOT BE FOUND", shader.id, uniformName); - else TraceLog(LOG_INFO, "[SHDR ID %i] Shader uniform [%s] set at location: %i", shader.id, uniformName, location); -#endif - return location; -} - -// Set shader uniform value (float) -void SetShaderValue(Shader shader, int uniformLoc, float *value, int size) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glUseProgram(shader.id); - - if (size == 1) glUniform1fv(uniformLoc, 1, value); // Shader uniform type: float - else if (size == 2) glUniform2fv(uniformLoc, 1, value); // Shader uniform type: vec2 - else if (size == 3) glUniform3fv(uniformLoc, 1, value); // Shader uniform type: vec3 - else if (size == 4) glUniform4fv(uniformLoc, 1, value); // Shader uniform type: vec4 - else TraceLog(LOG_WARNING, "Shader value float array size not supported"); - - //glUseProgram(0); // Avoid reseting current shader program, in case other uniforms are set -#endif -} - -// Set shader uniform value (int) -void SetShaderValuei(Shader shader, int uniformLoc, int *value, int size) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glUseProgram(shader.id); - - if (size == 1) glUniform1iv(uniformLoc, 1, value); // Shader uniform type: int - else if (size == 2) glUniform2iv(uniformLoc, 1, value); // Shader uniform type: ivec2 - else if (size == 3) glUniform3iv(uniformLoc, 1, value); // Shader uniform type: ivec3 - else if (size == 4) glUniform4iv(uniformLoc, 1, value); // Shader uniform type: ivec4 - else TraceLog(LOG_WARNING, "Shader value int array size not supported"); - - //glUseProgram(0); -#endif -} - -// Set shader uniform value (matrix 4x4) -void SetShaderValueMatrix(Shader shader, int uniformLoc, Matrix mat) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glUseProgram(shader.id); - - glUniformMatrix4fv(uniformLoc, 1, false, MatrixToFloat(mat)); - - //glUseProgram(0); -#endif -} - -// Set a custom projection matrix (replaces internal projection matrix) -void SetMatrixProjection(Matrix proj) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - projection = proj; -#endif -} - -// Set a custom modelview matrix (replaces internal modelview matrix) -void SetMatrixModelview(Matrix view) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - modelview = view; -#endif -} - -// Generate cubemap texture from HDR texture -// TODO: OpenGL ES 2.0 does not support GL_RGB16F texture format, neither GL_DEPTH_COMPONENT24 -Texture2D GenTextureCubemap(Shader shader, Texture2D skyHDR, int size) -{ - Texture2D cubemap = { 0 }; -#if defined(GRAPHICS_API_OPENGL_33) // || defined(GRAPHICS_API_OPENGL_ES2) - // NOTE: SetShaderDefaultLocations() already setups locations for projection and view Matrix in shader - // Other locations should be setup externally in shader before calling the function - - // Set up depth face culling and cubemap seamless - glDisable(GL_CULL_FACE); -#if defined(GRAPHICS_API_OPENGL_33) - glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); // Flag not supported on OpenGL ES 2.0 -#endif - - - // Setup framebuffer - unsigned int fbo, rbo; - glGenFramebuffers(1, &fbo); - glGenRenderbuffers(1, &rbo); - glBindFramebuffer(GL_FRAMEBUFFER, fbo); - glBindRenderbuffer(GL_RENDERBUFFER, rbo); - glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, size, size); - glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rbo); - - // Set up cubemap to render and attach to framebuffer - // NOTE: faces are stored with 16 bit floating point values - glGenTextures(1, &cubemap.id); - glBindTexture(GL_TEXTURE_CUBE_MAP, cubemap.id); - for (unsigned int i = 0; i < 6; i++) - glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB16F, size, size, 0, GL_RGB, GL_FLOAT, NULL); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); -#if defined(GRAPHICS_API_OPENGL_33) - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); // Flag not supported on OpenGL ES 2.0 -#endif - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - - // Create projection (transposed) and different views for each face - Matrix fboProjection = MatrixPerspective(90.0*DEG2RAD, 1.0, 0.01, 1000.0); - //MatrixTranspose(&fboProjection); - Matrix fboViews[6] = { - MatrixLookAt((Vector3){ 0.0f, 0.0f, 0.0f }, (Vector3){ 1.0f, 0.0f, 0.0f }, (Vector3){ 0.0f, -1.0f, 0.0f }), - MatrixLookAt((Vector3){ 0.0f, 0.0f, 0.0f }, (Vector3){ -1.0f, 0.0f, 0.0f }, (Vector3){ 0.0f, -1.0f, 0.0f }), - MatrixLookAt((Vector3){ 0.0f, 0.0f, 0.0f }, (Vector3){ 0.0f, 1.0f, 0.0f }, (Vector3){ 0.0f, 0.0f, 1.0f }), - MatrixLookAt((Vector3){ 0.0f, 0.0f, 0.0f }, (Vector3){ 0.0f, -1.0f, 0.0f }, (Vector3){ 0.0f, 0.0f, -1.0f }), - MatrixLookAt((Vector3){ 0.0f, 0.0f, 0.0f }, (Vector3){ 0.0f, 0.0f, 1.0f }, (Vector3){ 0.0f, -1.0f, 0.0f }), - MatrixLookAt((Vector3){ 0.0f, 0.0f, 0.0f }, (Vector3){ 0.0f, 0.0f, -1.0f }, (Vector3){ 0.0f, -1.0f, 0.0f }) - }; - - // Convert HDR equirectangular environment map to cubemap equivalent - glUseProgram(shader.id); - glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, skyHDR.id); - SetShaderValueMatrix(shader, shader.locs[LOC_MATRIX_PROJECTION], fboProjection); - - // Note: don't forget to configure the viewport to the capture dimensions - glViewport(0, 0, size, size); - glBindFramebuffer(GL_FRAMEBUFFER, fbo); - - for (unsigned int i = 0; i < 6; i++) - { - SetShaderValueMatrix(shader, shader.locs[LOC_MATRIX_VIEW], fboViews[i]); - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, cubemap.id, 0); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - GenDrawCube(); - } - - // Unbind framebuffer and textures - glBindFramebuffer(GL_FRAMEBUFFER, 0); - - // Reset viewport dimensions to default - glViewport(0, 0, screenWidth, screenHeight); - //glEnable(GL_CULL_FACE); - - cubemap.width = size; - cubemap.height = size; -#endif - return cubemap; -} - -// Generate irradiance texture using cubemap data -// TODO: OpenGL ES 2.0 does not support GL_RGB16F texture format, neither GL_DEPTH_COMPONENT24 -Texture2D GenTextureIrradiance(Shader shader, Texture2D cubemap, int size) -{ - Texture2D irradiance = { 0 }; - -#if defined(GRAPHICS_API_OPENGL_33) // || defined(GRAPHICS_API_OPENGL_ES2) - // NOTE: SetShaderDefaultLocations() already setups locations for projection and view Matrix in shader - // Other locations should be setup externally in shader before calling the function - - // Setup framebuffer - unsigned int fbo, rbo; - glGenFramebuffers(1, &fbo); - glGenRenderbuffers(1, &rbo); - glBindFramebuffer(GL_FRAMEBUFFER, fbo); - glBindRenderbuffer(GL_RENDERBUFFER, rbo); - glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, size, size); - glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rbo); - - // Create an irradiance cubemap, and re-scale capture FBO to irradiance scale - glGenTextures(1, &irradiance.id); - glBindTexture(GL_TEXTURE_CUBE_MAP, irradiance.id); - for (unsigned int i = 0; i < 6; i++) - glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB16F, size, size, 0, GL_RGB, GL_FLOAT, NULL); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - - // Create projection (transposed) and different views for each face - Matrix fboProjection = MatrixPerspective(90.0*DEG2RAD, 1.0, 0.01, 1000.0); - //MatrixTranspose(&fboProjection); - Matrix fboViews[6] = { - MatrixLookAt((Vector3){ 0.0f, 0.0f, 0.0f }, (Vector3){ 1.0f, 0.0f, 0.0f }, (Vector3){ 0.0f, -1.0f, 0.0f }), - MatrixLookAt((Vector3){ 0.0f, 0.0f, 0.0f }, (Vector3){ -1.0f, 0.0f, 0.0f }, (Vector3){ 0.0f, -1.0f, 0.0f }), - MatrixLookAt((Vector3){ 0.0f, 0.0f, 0.0f }, (Vector3){ 0.0f, 1.0f, 0.0f }, (Vector3){ 0.0f, 0.0f, 1.0f }), - MatrixLookAt((Vector3){ 0.0f, 0.0f, 0.0f }, (Vector3){ 0.0f, -1.0f, 0.0f }, (Vector3){ 0.0f, 0.0f, -1.0f }), - MatrixLookAt((Vector3){ 0.0f, 0.0f, 0.0f }, (Vector3){ 0.0f, 0.0f, 1.0f }, (Vector3){ 0.0f, -1.0f, 0.0f }), - MatrixLookAt((Vector3){ 0.0f, 0.0f, 0.0f }, (Vector3){ 0.0f, 0.0f, -1.0f }, (Vector3){ 0.0f, -1.0f, 0.0f }) - }; - - // Solve diffuse integral by convolution to create an irradiance cubemap - glUseProgram(shader.id); - glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_CUBE_MAP, cubemap.id); - SetShaderValueMatrix(shader, shader.locs[LOC_MATRIX_PROJECTION], fboProjection); - - // Note: don't forget to configure the viewport to the capture dimensions - glViewport(0, 0, size, size); - glBindFramebuffer(GL_FRAMEBUFFER, fbo); - - for (unsigned int i = 0; i < 6; i++) - { - SetShaderValueMatrix(shader, shader.locs[LOC_MATRIX_VIEW], fboViews[i]); - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, irradiance.id, 0); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - GenDrawCube(); - } - - // Unbind framebuffer and textures - glBindFramebuffer(GL_FRAMEBUFFER, 0); - - // Reset viewport dimensions to default - glViewport(0, 0, screenWidth, screenHeight); - - irradiance.width = size; - irradiance.height = size; -#endif - return irradiance; -} - -// Generate prefilter texture using cubemap data -// TODO: OpenGL ES 2.0 does not support GL_RGB16F texture format, neither GL_DEPTH_COMPONENT24 -Texture2D GenTexturePrefilter(Shader shader, Texture2D cubemap, int size) -{ - Texture2D prefilter = { 0 }; - -#if defined(GRAPHICS_API_OPENGL_33) // || defined(GRAPHICS_API_OPENGL_ES2) - // NOTE: SetShaderDefaultLocations() already setups locations for projection and view Matrix in shader - // Other locations should be setup externally in shader before calling the function - // TODO: Locations should be taken out of this function... too shader dependant... - int roughnessLoc = GetShaderLocation(shader, "roughness"); - - // Setup framebuffer - unsigned int fbo, rbo; - glGenFramebuffers(1, &fbo); - glGenRenderbuffers(1, &rbo); - glBindFramebuffer(GL_FRAMEBUFFER, fbo); - glBindRenderbuffer(GL_RENDERBUFFER, rbo); - glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, size, size); - glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rbo); - - // Create a prefiltered HDR environment map - glGenTextures(1, &prefilter.id); - glBindTexture(GL_TEXTURE_CUBE_MAP, prefilter.id); - for (unsigned int i = 0; i < 6; i++) - glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB16F, size, size, 0, GL_RGB, GL_FLOAT, NULL); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - - // Generate mipmaps for the prefiltered HDR texture - glGenerateMipmap(GL_TEXTURE_CUBE_MAP); - - // Create projection (transposed) and different views for each face - Matrix fboProjection = MatrixPerspective(90.0*DEG2RAD, 1.0, 0.01, 1000.0); - //MatrixTranspose(&fboProjection); - Matrix fboViews[6] = { - MatrixLookAt((Vector3){ 0.0f, 0.0f, 0.0f }, (Vector3){ 1.0f, 0.0f, 0.0f }, (Vector3){ 0.0f, -1.0f, 0.0f }), - MatrixLookAt((Vector3){ 0.0f, 0.0f, 0.0f }, (Vector3){ -1.0f, 0.0f, 0.0f }, (Vector3){ 0.0f, -1.0f, 0.0f }), - MatrixLookAt((Vector3){ 0.0f, 0.0f, 0.0f }, (Vector3){ 0.0f, 1.0f, 0.0f }, (Vector3){ 0.0f, 0.0f, 1.0f }), - MatrixLookAt((Vector3){ 0.0f, 0.0f, 0.0f }, (Vector3){ 0.0f, -1.0f, 0.0f }, (Vector3){ 0.0f, 0.0f, -1.0f }), - MatrixLookAt((Vector3){ 0.0f, 0.0f, 0.0f }, (Vector3){ 0.0f, 0.0f, 1.0f }, (Vector3){ 0.0f, -1.0f, 0.0f }), - MatrixLookAt((Vector3){ 0.0f, 0.0f, 0.0f }, (Vector3){ 0.0f, 0.0f, -1.0f }, (Vector3){ 0.0f, -1.0f, 0.0f }) - }; - - // Prefilter HDR and store data into mipmap levels - glUseProgram(shader.id); - glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_CUBE_MAP, cubemap.id); - SetShaderValueMatrix(shader, shader.locs[LOC_MATRIX_PROJECTION], fboProjection); - - glBindFramebuffer(GL_FRAMEBUFFER, fbo); - - #define MAX_MIPMAP_LEVELS 5 // Max number of prefilter texture mipmaps - - for (unsigned int mip = 0; mip < MAX_MIPMAP_LEVELS; mip++) - { - // Resize framebuffer according to mip-level size. - unsigned int mipWidth = size*powf(0.5f, mip); - unsigned int mipHeight = size*powf(0.5f, mip); - - glBindRenderbuffer(GL_RENDERBUFFER, rbo); - glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, mipWidth, mipHeight); - glViewport(0, 0, mipWidth, mipHeight); - - float roughness = (float)mip/(float)(MAX_MIPMAP_LEVELS - 1); - glUniform1f(roughnessLoc, roughness); - - for (unsigned int i = 0; i < 6; ++i) - { - SetShaderValueMatrix(shader, shader.locs[LOC_MATRIX_VIEW], fboViews[i]); - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, prefilter.id, mip); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - GenDrawCube(); - } - } - - // Unbind framebuffer and textures - glBindFramebuffer(GL_FRAMEBUFFER, 0); - - // Reset viewport dimensions to default - glViewport(0, 0, screenWidth, screenHeight); - - prefilter.width = size; - prefilter.height = size; -#endif - return prefilter; -} - -// Generate BRDF texture using cubemap data -// TODO: OpenGL ES 2.0 does not support GL_RGB16F texture format, neither GL_DEPTH_COMPONENT24 -Texture2D GenTextureBRDF(Shader shader, Texture2D cubemap, int size) -{ - Texture2D brdf = { 0 }; -#if defined(GRAPHICS_API_OPENGL_33) // || defined(GRAPHICS_API_OPENGL_ES2) - // Generate BRDF convolution texture - glGenTextures(1, &brdf.id); - glBindTexture(GL_TEXTURE_2D, brdf.id); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RG16F, size, size, 0, GL_RG, GL_FLOAT, 0); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - - // Render BRDF LUT into a quad using FBO - unsigned int fbo, rbo; - glGenFramebuffers(1, &fbo); - glGenRenderbuffers(1, &rbo); - glBindFramebuffer(GL_FRAMEBUFFER, fbo); - glBindRenderbuffer(GL_RENDERBUFFER, rbo); - glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, size, size); - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, brdf.id, 0); - - glViewport(0, 0, size, size); - glUseProgram(shader.id); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - GenDrawQuad(); - - // Unbind framebuffer and textures - glBindFramebuffer(GL_FRAMEBUFFER, 0); - - // Reset viewport dimensions to default - glViewport(0, 0, screenWidth, screenHeight); - - brdf.width = size; - brdf.height = size; -#endif - return brdf; -} - -// Begin blending mode (alpha, additive, multiplied) -// NOTE: Only 3 blending modes supported, default blend mode is alpha -void BeginBlendMode(int mode) -{ - if ((blendMode != mode) && (mode < 3)) - { - rlglDraw(); - - switch (mode) - { - case BLEND_ALPHA: glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); break; - case BLEND_ADDITIVE: glBlendFunc(GL_SRC_ALPHA, GL_ONE); break; // Alternative: glBlendFunc(GL_ONE, GL_ONE); - case BLEND_MULTIPLIED: glBlendFunc(GL_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA); break; - default: break; - } - - blendMode = mode; - } -} - -// End blending mode (reset to default: alpha blending) -void EndBlendMode(void) -{ - BeginBlendMode(BLEND_ALPHA); -} - -#if defined(SUPPORT_VR_SIMULATOR) -// Get VR device information for some standard devices -VrDeviceInfo GetVrDeviceInfo(int vrDeviceType) -{ - VrDeviceInfo hmd = { 0 }; // Current VR device info - - switch (vrDeviceType) - { - case HMD_DEFAULT_DEVICE: - case HMD_OCULUS_RIFT_CV1: - { - // Oculus Rift CV1 parameters - // NOTE: CV1 represents a complete HMD redesign compared to previous versions, - // new Fresnel-hybrid-asymmetric lenses have been added and, consequently, - // previous parameters (DK2) and distortion shader (DK2) doesn't work any more. - // I just defined a set of parameters for simulator that approximate to CV1 stereo rendering - // but result is not the same obtained with Oculus PC SDK. - hmd.hResolution = 2160; // HMD horizontal resolution in pixels - hmd.vResolution = 1200; // HMD vertical resolution in pixels - hmd.hScreenSize = 0.133793f; // HMD horizontal size in meters - hmd.vScreenSize = 0.0669f; // HMD vertical size in meters - hmd.vScreenCenter = 0.04678f; // HMD screen center in meters - hmd.eyeToScreenDistance = 0.041f; // HMD distance between eye and display in meters - hmd.lensSeparationDistance = 0.07f; // HMD lens separation distance in meters - hmd.interpupillaryDistance = 0.07f; // HMD IPD (distance between pupils) in meters - hmd.lensDistortionValues[0] = 1.0f; // HMD lens distortion constant parameter 0 - hmd.lensDistortionValues[1] = 0.22f; // HMD lens distortion constant parameter 1 - hmd.lensDistortionValues[2] = 0.24f; // HMD lens distortion constant parameter 2 - hmd.lensDistortionValues[3] = 0.0f; // HMD lens distortion constant parameter 3 - hmd.chromaAbCorrection[0] = 0.996f; // HMD chromatic aberration correction parameter 0 - hmd.chromaAbCorrection[1] = -0.004f; // HMD chromatic aberration correction parameter 1 - hmd.chromaAbCorrection[2] = 1.014f; // HMD chromatic aberration correction parameter 2 - hmd.chromaAbCorrection[3] = 0.0f; // HMD chromatic aberration correction parameter 3 - - TraceLog(LOG_INFO, "Initializing VR Simulator (Oculus Rift CV1)"); - } break; - case HMD_OCULUS_RIFT_DK2: - { - // Oculus Rift DK2 parameters - hmd.hResolution = 1280; // HMD horizontal resolution in pixels - hmd.vResolution = 800; // HMD vertical resolution in pixels - hmd.hScreenSize = 0.14976f; // HMD horizontal size in meters - hmd.vScreenSize = 0.09356f; // HMD vertical size in meters - hmd.vScreenCenter = 0.04678f; // HMD screen center in meters - hmd.eyeToScreenDistance = 0.041f; // HMD distance between eye and display in meters - hmd.lensSeparationDistance = 0.0635f; // HMD lens separation distance in meters - hmd.interpupillaryDistance = 0.064f; // HMD IPD (distance between pupils) in meters - hmd.lensDistortionValues[0] = 1.0f; // HMD lens distortion constant parameter 0 - hmd.lensDistortionValues[1] = 0.22f; // HMD lens distortion constant parameter 1 - hmd.lensDistortionValues[2] = 0.24f; // HMD lens distortion constant parameter 2 - hmd.lensDistortionValues[3] = 0.0f; // HMD lens distortion constant parameter 3 - hmd.chromaAbCorrection[0] = 0.996f; // HMD chromatic aberration correction parameter 0 - hmd.chromaAbCorrection[1] = -0.004f; // HMD chromatic aberration correction parameter 1 - hmd.chromaAbCorrection[2] = 1.014f; // HMD chromatic aberration correction parameter 2 - hmd.chromaAbCorrection[3] = 0.0f; // HMD chromatic aberration correction parameter 3 - - TraceLog(LOG_INFO, "Initializing VR Simulator (Oculus Rift DK2)"); - } break; - case HMD_OCULUS_GO: - { - // TODO: Provide device display and lens parameters - } - case HMD_VALVE_HTC_VIVE: - { - // TODO: Provide device display and lens parameters - } - case HMD_SONY_PSVR: - { - // TODO: Provide device display and lens parameters - } - default: break; - } - - return hmd; -} - -// Init VR simulator for selected device parameters -// NOTE: It modifies the global variable: VrStereoConfig vrConfig -void InitVrSimulator(VrDeviceInfo info) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // Initialize framebuffer and textures for stereo rendering - // NOTE: Screen size should match HMD aspect ratio - vrConfig.stereoFbo = rlLoadRenderTexture(screenWidth, screenHeight); - -#if defined(SUPPORT_DISTORTION_SHADER) - // Load distortion shader (initialized by default with Oculus Rift CV1 parameters) - vrConfig.distortionShader.id = LoadShaderProgram(vDistortionShaderStr, fDistortionShaderStr); - if (vrConfig.distortionShader.id > 0) SetShaderDefaultLocations(&vrConfig.distortionShader); -#endif - - SetStereoConfig(info); - - vrSimulatorReady = true; -#endif - -#if defined(GRAPHICS_API_OPENGL_11) - TraceLog(LOG_WARNING, "VR Simulator not supported on OpenGL 1.1"); -#endif -} - -// Close VR simulator for current device -void CloseVrSimulator(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if (vrSimulatorReady) - { - rlDeleteRenderTextures(vrConfig.stereoFbo); // Unload stereo framebuffer and texture - #if defined(SUPPORT_DISTORTION_SHADER) - UnloadShader(vrConfig.distortionShader); // Unload distortion shader - #endif - } -#endif -} - -// TODO: Review VR system to be more flexible, -// move distortion shader to user side, -// SetStereoConfig() must be reviewed... -/* -// Set VR view distortion shader -void SetVrDistortionShader(Shader shader) -{ - vrConfig.distortionShader = shader; - SetStereoConfig(info); -} -*/ - -// Detect if VR simulator is running -bool IsVrSimulatorReady(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - return vrSimulatorReady; -#else - return false; -#endif -} - -// Enable/Disable VR experience (device or simulator) -void ToggleVrMode(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - vrSimulatorReady = !vrSimulatorReady; - - if (!vrSimulatorReady) - { - vrStereoRender = false; - - // Reset viewport and default projection-modelview matrices - rlViewport(0, 0, screenWidth, screenHeight); - projection = MatrixOrtho(0.0, screenWidth, screenHeight, 0.0, 0.0, 1.0); - modelview = MatrixIdentity(); - } - else vrStereoRender = true; -#endif -} - -// Update VR tracking (position and orientation) and camera -// NOTE: Camera (position, target, up) gets update with head tracking information -void UpdateVrTracking(Camera *camera) -{ - // TODO: Simulate 1st person camera system -} - -// Begin Oculus drawing configuration -void BeginVrDrawing(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if (vrSimulatorReady) - { - // Setup framebuffer for stereo rendering - rlEnableRenderTexture(vrConfig.stereoFbo.id); - - // NOTE: If your application is configured to treat the texture as a linear format (e.g. GL_RGBA) - // and performs linear-to-gamma conversion in GLSL or does not care about gamma-correction, then: - // - Require OculusBuffer format to be OVR_FORMAT_R8G8B8A8_UNORM_SRGB - // - Do NOT enable GL_FRAMEBUFFER_SRGB - //glEnable(GL_FRAMEBUFFER_SRGB); - - //glViewport(0, 0, buffer.width, buffer.height); // Useful if rendering to separate framebuffers (every eye) - rlClearScreenBuffers(); // Clear current framebuffer(s) - - vrStereoRender = true; - } -#endif -} - -// End Oculus drawing process (and desktop mirror) -void EndVrDrawing(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if (vrSimulatorReady) - { - vrStereoRender = false; // Disable stereo render - - rlDisableRenderTexture(); // Unbind current framebuffer - - rlClearScreenBuffers(); // Clear current framebuffer - - // Set viewport to default framebuffer size (screen size) - rlViewport(0, 0, screenWidth, screenHeight); - - // Let rlgl reconfigure internal matrices - rlMatrixMode(RL_PROJECTION); // Enable internal projection matrix - rlLoadIdentity(); // Reset internal projection matrix - rlOrtho(0.0, screenWidth, screenHeight, 0.0, 0.0, 1.0); // Recalculate internal projection matrix - rlMatrixMode(RL_MODELVIEW); // Enable internal modelview matrix - rlLoadIdentity(); // Reset internal modelview matrix - -#if defined(SUPPORT_DISTORTION_SHADER) - // Draw RenderTexture (stereoFbo) using distortion shader - currentShader = vrConfig.distortionShader; -#else - currentShader = GetShaderDefault(); -#endif - - rlEnableTexture(vrConfig.stereoFbo.texture.id); - - rlPushMatrix(); - rlBegin(RL_QUADS); - rlColor4ub(255, 255, 255, 255); - rlNormal3f(0.0f, 0.0f, 1.0f); - - // Bottom-left corner for texture and quad - rlTexCoord2f(0.0f, 1.0f); - rlVertex2f(0.0f, 0.0f); - - // Bottom-right corner for texture and quad - rlTexCoord2f(0.0f, 0.0f); - rlVertex2f(0.0f, vrConfig.stereoFbo.texture.height); - - // Top-right corner for texture and quad - rlTexCoord2f(1.0f, 0.0f); - rlVertex2f(vrConfig.stereoFbo.texture.width, vrConfig.stereoFbo.texture.height); - - // Top-left corner for texture and quad - rlTexCoord2f(1.0f, 1.0f); - rlVertex2f(vrConfig.stereoFbo.texture.width, 0.0f); - rlEnd(); - rlPopMatrix(); - - rlDisableTexture(); - - // Update and draw render texture fbo with distortion to backbuffer - UpdateBuffersDefault(); - DrawBuffersDefault(); - - // Restore defaultShader - currentShader = defaultShader; - - // Reset viewport and default projection-modelview matrices - rlViewport(0, 0, screenWidth, screenHeight); - projection = MatrixOrtho(0.0, screenWidth, screenHeight, 0.0, 0.0, 1.0); - modelview = MatrixIdentity(); - - rlDisableDepthTest(); - } -#endif -} -#endif // SUPPORT_VR_SIMULATOR - -//---------------------------------------------------------------------------------- -// Module specific Functions Definition -//---------------------------------------------------------------------------------- - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) -// Convert image data to OpenGL texture (returns OpenGL valid Id) -// NOTE: Expected compressed image data and POT image -static void LoadTextureCompressed(unsigned char *data, int width, int height, int compressedFormat, int mipmapCount) -{ - glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - - int blockSize = 0; // Bytes every block - int offset = 0; - - if ((compressedFormat == GL_COMPRESSED_RGB_S3TC_DXT1_EXT) || - (compressedFormat == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT) || -#if defined(GRAPHICS_API_OPENGL_ES2) - (compressedFormat == GL_ETC1_RGB8_OES) || -#endif - (compressedFormat == GL_COMPRESSED_RGB8_ETC2)) blockSize = 8; - else blockSize = 16; - - // Load the mipmap levels - for (int level = 0; level < mipmapCount && (width || height); level++) - { - unsigned int size = 0; - - size = ((width + 3)/4)*((height + 3)/4)*blockSize; - - glCompressedTexImage2D(GL_TEXTURE_2D, level, compressedFormat, width, height, 0, size, data + offset); - - offset += size; - width /= 2; - height /= 2; - - // Security check for NPOT textures - if (width < 1) width = 1; - if (height < 1) height = 1; - } -} - -// Load custom shader strings and return program id -static unsigned int LoadShaderProgram(const char *vShaderStr, const char *fShaderStr) -{ - unsigned int program = 0; - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - GLuint vertexShader; - GLuint fragmentShader; - - vertexShader = glCreateShader(GL_VERTEX_SHADER); - fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); - - const char *pvs = vShaderStr; - const char *pfs = fShaderStr; - - glShaderSource(vertexShader, 1, &pvs, NULL); - glShaderSource(fragmentShader, 1, &pfs, NULL); - - GLint success = 0; - - glCompileShader(vertexShader); - - glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success); - - if (success != GL_TRUE) - { - TraceLog(LOG_WARNING, "[VSHDR ID %i] Failed to compile vertex shader...", vertexShader); - - int maxLength = 0; - int length; - - glGetShaderiv(vertexShader, GL_INFO_LOG_LENGTH, &maxLength); - -#ifdef _MSC_VER - char *log = malloc(maxLength); -#else - char log[maxLength]; -#endif - glGetShaderInfoLog(vertexShader, maxLength, &length, log); - - TraceLog(LOG_INFO, "%s", log); - -#ifdef _MSC_VER - free(log); -#endif - } - else TraceLog(LOG_INFO, "[VSHDR ID %i] Vertex shader compiled successfully", vertexShader); - - glCompileShader(fragmentShader); - - glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success); - - if (success != GL_TRUE) - { - TraceLog(LOG_WARNING, "[FSHDR ID %i] Failed to compile fragment shader...", fragmentShader); - - int maxLength = 0; - int length; - - glGetShaderiv(fragmentShader, GL_INFO_LOG_LENGTH, &maxLength); - -#ifdef _MSC_VER - char *log = malloc(maxLength); -#else - char log[maxLength]; -#endif - glGetShaderInfoLog(fragmentShader, maxLength, &length, log); - - TraceLog(LOG_INFO, "%s", log); - -#ifdef _MSC_VER - free(log); -#endif - } - else TraceLog(LOG_INFO, "[FSHDR ID %i] Fragment shader compiled successfully", fragmentShader); - - program = glCreateProgram(); - - glAttachShader(program, vertexShader); - glAttachShader(program, fragmentShader); - - // NOTE: Default attribute shader locations must be binded before linking - glBindAttribLocation(program, 0, DEFAULT_ATTRIB_POSITION_NAME); - glBindAttribLocation(program, 1, DEFAULT_ATTRIB_TEXCOORD_NAME); - glBindAttribLocation(program, 2, DEFAULT_ATTRIB_NORMAL_NAME); - glBindAttribLocation(program, 3, DEFAULT_ATTRIB_COLOR_NAME); - glBindAttribLocation(program, 4, DEFAULT_ATTRIB_TANGENT_NAME); - glBindAttribLocation(program, 5, DEFAULT_ATTRIB_TEXCOORD2_NAME); - - // NOTE: If some attrib name is no found on the shader, it locations becomes -1 - - glLinkProgram(program); - - // NOTE: All uniform variables are intitialised to 0 when a program links - - glGetProgramiv(program, GL_LINK_STATUS, &success); - - if (success == GL_FALSE) - { - TraceLog(LOG_WARNING, "[SHDR ID %i] Failed to link shader program...", program); - - int maxLength = 0; - int length; - - glGetProgramiv(program, GL_INFO_LOG_LENGTH, &maxLength); - -#ifdef _MSC_VER - char *log = malloc(maxLength); -#else - char log[maxLength]; -#endif - glGetProgramInfoLog(program, maxLength, &length, log); - - TraceLog(LOG_INFO, "%s", log); - -#ifdef _MSC_VER - free(log); -#endif - glDeleteProgram(program); - - program = 0; - } - else TraceLog(LOG_INFO, "[SHDR ID %i] Shader program loaded successfully", program); - - glDeleteShader(vertexShader); - glDeleteShader(fragmentShader); -#endif - return program; -} - - -// Load default shader (just vertex positioning and texture coloring) -// NOTE: This shader program is used for batch buffers (lines, triangles, quads) -static Shader LoadShaderDefault(void) -{ - Shader shader; - - // Vertex shader directly defined, no external file required - char vDefaultShaderStr[] = -#if defined(GRAPHICS_API_OPENGL_21) - "#version 120 \n" -#elif defined(GRAPHICS_API_OPENGL_ES2) - "#version 100 \n" -#endif -#if defined(GRAPHICS_API_OPENGL_ES2) || defined(GRAPHICS_API_OPENGL_21) - "attribute vec3 vertexPosition; \n" - "attribute vec2 vertexTexCoord; \n" - "attribute vec4 vertexColor; \n" - "varying vec2 fragTexCoord; \n" - "varying vec4 fragColor; \n" -#elif defined(GRAPHICS_API_OPENGL_33) - "#version 330 \n" - "in vec3 vertexPosition; \n" - "in vec2 vertexTexCoord; \n" - "in vec4 vertexColor; \n" - "out vec2 fragTexCoord; \n" - "out vec4 fragColor; \n" -#endif - "uniform mat4 mvp; \n" - "void main() \n" - "{ \n" - " fragTexCoord = vertexTexCoord; \n" - " fragColor = vertexColor; \n" - " gl_Position = mvp*vec4(vertexPosition, 1.0); \n" - "} \n"; - - // Fragment shader directly defined, no external file required - char fDefaultShaderStr[] = -#if defined(GRAPHICS_API_OPENGL_21) - "#version 120 \n" -#elif defined(GRAPHICS_API_OPENGL_ES2) - "#version 100 \n" - "precision mediump float; \n" // precision required for OpenGL ES2 (WebGL) -#endif -#if defined(GRAPHICS_API_OPENGL_ES2) || defined(GRAPHICS_API_OPENGL_21) - "varying vec2 fragTexCoord; \n" - "varying vec4 fragColor; \n" -#elif defined(GRAPHICS_API_OPENGL_33) - "#version 330 \n" - "in vec2 fragTexCoord; \n" - "in vec4 fragColor; \n" - "out vec4 finalColor; \n" -#endif - "uniform sampler2D texture0; \n" - "uniform vec4 colDiffuse; \n" - "void main() \n" - "{ \n" -#if defined(GRAPHICS_API_OPENGL_ES2) || defined(GRAPHICS_API_OPENGL_21) - " vec4 texelColor = texture2D(texture0, fragTexCoord); \n" // NOTE: texture2D() is deprecated on OpenGL 3.3 and ES 3.0 - " gl_FragColor = texelColor*colDiffuse*fragColor; \n" -#elif defined(GRAPHICS_API_OPENGL_33) - " vec4 texelColor = texture(texture0, fragTexCoord); \n" - " finalColor = texelColor*colDiffuse*fragColor; \n" -#endif - "} \n"; - - shader.id = LoadShaderProgram(vDefaultShaderStr, fDefaultShaderStr); - - if (shader.id > 0) - { - TraceLog(LOG_INFO, "[SHDR ID %i] Default shader loaded successfully", shader.id); - - // Set default shader locations - // Get handles to GLSL input attibute locations - shader.locs[LOC_VERTEX_POSITION] = glGetAttribLocation(shader.id, "vertexPosition"); - shader.locs[LOC_VERTEX_TEXCOORD01] = glGetAttribLocation(shader.id, "vertexTexCoord"); - shader.locs[LOC_VERTEX_COLOR] = glGetAttribLocation(shader.id, "vertexColor"); - - // Get handles to GLSL uniform locations - shader.locs[LOC_MATRIX_MVP] = glGetUniformLocation(shader.id, "mvp"); - shader.locs[LOC_COLOR_DIFFUSE] = glGetUniformLocation(shader.id, "colDiffuse"); - shader.locs[LOC_MAP_DIFFUSE] = glGetUniformLocation(shader.id, "texture0"); - } - else TraceLog(LOG_WARNING, "[SHDR ID %i] Default shader could not be loaded", shader.id); - - return shader; -} - -// Get location handlers to for shader attributes and uniforms -// NOTE: If any location is not found, loc point becomes -1 -static void SetShaderDefaultLocations(Shader *shader) -{ - // NOTE: Default shader attrib locations have been fixed before linking: - // vertex position location = 0 - // vertex texcoord location = 1 - // vertex normal location = 2 - // vertex color location = 3 - // vertex tangent location = 4 - // vertex texcoord2 location = 5 - - // Get handles to GLSL input attibute locations - shader->locs[LOC_VERTEX_POSITION] = glGetAttribLocation(shader->id, DEFAULT_ATTRIB_POSITION_NAME); - shader->locs[LOC_VERTEX_TEXCOORD01] = glGetAttribLocation(shader->id, DEFAULT_ATTRIB_TEXCOORD_NAME); - shader->locs[LOC_VERTEX_TEXCOORD02] = glGetAttribLocation(shader->id, DEFAULT_ATTRIB_TEXCOORD2_NAME); - shader->locs[LOC_VERTEX_NORMAL] = glGetAttribLocation(shader->id, DEFAULT_ATTRIB_NORMAL_NAME); - shader->locs[LOC_VERTEX_TANGENT] = glGetAttribLocation(shader->id, DEFAULT_ATTRIB_TANGENT_NAME); - shader->locs[LOC_VERTEX_COLOR] = glGetAttribLocation(shader->id, DEFAULT_ATTRIB_COLOR_NAME); - - // Get handles to GLSL uniform locations (vertex shader) - shader->locs[LOC_MATRIX_MVP] = glGetUniformLocation(shader->id, "mvp"); - shader->locs[LOC_MATRIX_PROJECTION] = glGetUniformLocation(shader->id, "projection"); - shader->locs[LOC_MATRIX_VIEW] = glGetUniformLocation(shader->id, "view"); - - // Get handles to GLSL uniform locations (fragment shader) - shader->locs[LOC_COLOR_DIFFUSE] = glGetUniformLocation(shader->id, "colDiffuse"); - shader->locs[LOC_MAP_DIFFUSE] = glGetUniformLocation(shader->id, "texture0"); - shader->locs[LOC_MAP_NORMAL] = glGetUniformLocation(shader->id, "texture1"); - shader->locs[LOC_MAP_SPECULAR] = glGetUniformLocation(shader->id, "texture2"); -} - -// Unload default shader -static void UnloadShaderDefault(void) -{ - glUseProgram(0); - - //glDetachShader(defaultShader, vertexShader); - //glDetachShader(defaultShader, fragmentShader); - //glDeleteShader(vertexShader); // Already deleted on shader compilation - //glDeleteShader(fragmentShader); // Already deleted on shader compilation - glDeleteProgram(defaultShader.id); -} - -// Load default internal buffers (lines, triangles, quads) -static void LoadBuffersDefault(void) -{ - // [CPU] Allocate and initialize float array buffers to store vertex data (lines, triangles, quads) - //-------------------------------------------------------------------------------------------- - - // Lines - Initialize arrays (vertex position and color data) - lines.vertices = (float *)malloc(sizeof(float)*3*2*MAX_LINES_BATCH); // 3 float by vertex, 2 vertex by line - lines.colors = (unsigned char *)malloc(sizeof(unsigned char)*4*2*MAX_LINES_BATCH); // 4 float by color, 2 colors by line - lines.texcoords = NULL; - lines.indices = NULL; - - for (int i = 0; i < (3*2*MAX_LINES_BATCH); i++) lines.vertices[i] = 0.0f; - for (int i = 0; i < (4*2*MAX_LINES_BATCH); i++) lines.colors[i] = 0; - - lines.vCounter = 0; - lines.cCounter = 0; - lines.tcCounter = 0; - - // Triangles - Initialize arrays (vertex position and color data) - triangles.vertices = (float *)malloc(sizeof(float)*3*3*MAX_TRIANGLES_BATCH); // 3 float by vertex, 3 vertex by triangle - triangles.colors = (unsigned char *)malloc(sizeof(unsigned char)*4*3*MAX_TRIANGLES_BATCH); // 4 float by color, 3 colors by triangle - triangles.texcoords = NULL; - triangles.indices = NULL; - - for (int i = 0; i < (3*3*MAX_TRIANGLES_BATCH); i++) triangles.vertices[i] = 0.0f; - for (int i = 0; i < (4*3*MAX_TRIANGLES_BATCH); i++) triangles.colors[i] = 0; - - triangles.vCounter = 0; - triangles.cCounter = 0; - triangles.tcCounter = 0; - - // Quads - Initialize arrays (vertex position, texcoord, color data and indexes) - quads.vertices = (float *)malloc(sizeof(float)*3*4*MAX_QUADS_BATCH); // 3 float by vertex, 4 vertex by quad - quads.texcoords = (float *)malloc(sizeof(float)*2*4*MAX_QUADS_BATCH); // 2 float by texcoord, 4 texcoord by quad - quads.colors = (unsigned char *)malloc(sizeof(unsigned char)*4*4*MAX_QUADS_BATCH); // 4 float by color, 4 colors by quad -#if defined(GRAPHICS_API_OPENGL_33) - quads.indices = (unsigned int *)malloc(sizeof(int)*6*MAX_QUADS_BATCH); // 6 int by quad (indices) -#elif defined(GRAPHICS_API_OPENGL_ES2) - quads.indices = (unsigned short *)malloc(sizeof(short)*6*MAX_QUADS_BATCH); // 6 int by quad (indices) -#endif - - for (int i = 0; i < (3*4*MAX_QUADS_BATCH); i++) quads.vertices[i] = 0.0f; - for (int i = 0; i < (2*4*MAX_QUADS_BATCH); i++) quads.texcoords[i] = 0.0f; - for (int i = 0; i < (4*4*MAX_QUADS_BATCH); i++) quads.colors[i] = 0; - - int k = 0; - - // Indices can be initialized right now - for (int i = 0; i < (6*MAX_QUADS_BATCH); i+=6) - { - quads.indices[i] = 4*k; - quads.indices[i+1] = 4*k+1; - quads.indices[i+2] = 4*k+2; - quads.indices[i+3] = 4*k; - quads.indices[i+4] = 4*k+2; - quads.indices[i+5] = 4*k+3; - - k++; - } - - quads.vCounter = 0; - quads.tcCounter = 0; - quads.cCounter = 0; - - TraceLog(LOG_INFO, "[CPU] Default buffers initialized successfully (lines, triangles, quads)"); - //-------------------------------------------------------------------------------------------- - - // [GPU] Upload vertex data and initialize VAOs/VBOs (lines, triangles, quads) - // NOTE: Default buffers are linked to use currentShader (defaultShader) - //-------------------------------------------------------------------------------------------- - - // Upload and link lines vertex buffers - if (vaoSupported) - { - // Initialize Lines VAO - glGenVertexArrays(1, &lines.vaoId); - glBindVertexArray(lines.vaoId); - } - - // Lines - Vertex buffers binding and attributes enable - // Vertex position buffer (shader-location = 0) - glGenBuffers(2, &lines.vboId[0]); - glBindBuffer(GL_ARRAY_BUFFER, lines.vboId[0]); - glBufferData(GL_ARRAY_BUFFER, sizeof(float)*3*2*MAX_LINES_BATCH, lines.vertices, GL_DYNAMIC_DRAW); - glEnableVertexAttribArray(currentShader.locs[LOC_VERTEX_POSITION]); - glVertexAttribPointer(currentShader.locs[LOC_VERTEX_POSITION], 3, GL_FLOAT, 0, 0, 0); - - // Vertex color buffer (shader-location = 3) - glGenBuffers(2, &lines.vboId[1]); - glBindBuffer(GL_ARRAY_BUFFER, lines.vboId[1]); - glBufferData(GL_ARRAY_BUFFER, sizeof(unsigned char)*4*2*MAX_LINES_BATCH, lines.colors, GL_DYNAMIC_DRAW); - glEnableVertexAttribArray(currentShader.locs[LOC_VERTEX_COLOR]); - glVertexAttribPointer(currentShader.locs[LOC_VERTEX_COLOR], 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, 0); - - if (vaoSupported) TraceLog(LOG_INFO, "[VAO ID %i] Default buffers VAO initialized successfully (lines)", lines.vaoId); - else TraceLog(LOG_INFO, "[VBO ID %i][VBO ID %i] Default buffers VBOs initialized successfully (lines)", lines.vboId[0], lines.vboId[1]); - - // Upload and link triangles vertex buffers - if (vaoSupported) - { - // Initialize Triangles VAO - glGenVertexArrays(1, &triangles.vaoId); - glBindVertexArray(triangles.vaoId); - } - - // Triangles - Vertex buffers binding and attributes enable - // Vertex position buffer (shader-location = 0) - glGenBuffers(1, &triangles.vboId[0]); - glBindBuffer(GL_ARRAY_BUFFER, triangles.vboId[0]); - glBufferData(GL_ARRAY_BUFFER, sizeof(float)*3*3*MAX_TRIANGLES_BATCH, triangles.vertices, GL_DYNAMIC_DRAW); - glEnableVertexAttribArray(currentShader.locs[LOC_VERTEX_POSITION]); - glVertexAttribPointer(currentShader.locs[LOC_VERTEX_POSITION], 3, GL_FLOAT, 0, 0, 0); - - // Vertex color buffer (shader-location = 3) - glGenBuffers(1, &triangles.vboId[1]); - glBindBuffer(GL_ARRAY_BUFFER, triangles.vboId[1]); - glBufferData(GL_ARRAY_BUFFER, sizeof(unsigned char)*4*3*MAX_TRIANGLES_BATCH, triangles.colors, GL_DYNAMIC_DRAW); - glEnableVertexAttribArray(currentShader.locs[LOC_VERTEX_COLOR]); - glVertexAttribPointer(currentShader.locs[LOC_VERTEX_COLOR], 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, 0); - - if (vaoSupported) TraceLog(LOG_INFO, "[VAO ID %i] Default buffers VAO initialized successfully (triangles)", triangles.vaoId); - else TraceLog(LOG_INFO, "[VBO ID %i][VBO ID %i] Default buffers VBOs initialized successfully (triangles)", triangles.vboId[0], triangles.vboId[1]); - - // Upload and link quads vertex buffers - if (vaoSupported) - { - // Initialize Quads VAO - glGenVertexArrays(1, &quads.vaoId); - glBindVertexArray(quads.vaoId); - } - - // Quads - Vertex buffers binding and attributes enable - // Vertex position buffer (shader-location = 0) - glGenBuffers(1, &quads.vboId[0]); - glBindBuffer(GL_ARRAY_BUFFER, quads.vboId[0]); - glBufferData(GL_ARRAY_BUFFER, sizeof(float)*3*4*MAX_QUADS_BATCH, quads.vertices, GL_DYNAMIC_DRAW); - glEnableVertexAttribArray(currentShader.locs[LOC_VERTEX_POSITION]); - glVertexAttribPointer(currentShader.locs[LOC_VERTEX_POSITION], 3, GL_FLOAT, 0, 0, 0); - - // Vertex texcoord buffer (shader-location = 1) - glGenBuffers(1, &quads.vboId[1]); - glBindBuffer(GL_ARRAY_BUFFER, quads.vboId[1]); - glBufferData(GL_ARRAY_BUFFER, sizeof(float)*2*4*MAX_QUADS_BATCH, quads.texcoords, GL_DYNAMIC_DRAW); - glEnableVertexAttribArray(currentShader.locs[LOC_VERTEX_TEXCOORD01]); - glVertexAttribPointer(currentShader.locs[LOC_VERTEX_TEXCOORD01], 2, GL_FLOAT, 0, 0, 0); - - // Vertex color buffer (shader-location = 3) - glGenBuffers(1, &quads.vboId[2]); - glBindBuffer(GL_ARRAY_BUFFER, quads.vboId[2]); - glBufferData(GL_ARRAY_BUFFER, sizeof(unsigned char)*4*4*MAX_QUADS_BATCH, quads.colors, GL_DYNAMIC_DRAW); - glEnableVertexAttribArray(currentShader.locs[LOC_VERTEX_COLOR]); - glVertexAttribPointer(currentShader.locs[LOC_VERTEX_COLOR], 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, 0); - - // Fill index buffer - glGenBuffers(1, &quads.vboId[3]); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, quads.vboId[3]); -#if defined(GRAPHICS_API_OPENGL_33) - glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(int)*6*MAX_QUADS_BATCH, quads.indices, GL_STATIC_DRAW); -#elif defined(GRAPHICS_API_OPENGL_ES2) - glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(short)*6*MAX_QUADS_BATCH, quads.indices, GL_STATIC_DRAW); -#endif - - if (vaoSupported) TraceLog(LOG_INFO, "[VAO ID %i] Default buffers VAO initialized successfully (quads)", quads.vaoId); - else TraceLog(LOG_INFO, "[VBO ID %i][VBO ID %i][VBO ID %i][VBO ID %i] Default buffers VBOs initialized successfully (quads)", quads.vboId[0], quads.vboId[1], quads.vboId[2], quads.vboId[3]); - - // Unbind the current VAO - if (vaoSupported) glBindVertexArray(0); - //-------------------------------------------------------------------------------------------- -} - -// Update default internal buffers (VAOs/VBOs) with vertex array data -// NOTE: If there is not vertex data, buffers doesn't need to be updated (vertexCount > 0) -// TODO: If no data changed on the CPU arrays --> No need to re-update GPU arrays (change flag required) -static void UpdateBuffersDefault(void) -{ - // Update lines vertex buffers - if (lines.vCounter > 0) - { - // Activate Lines VAO - if (vaoSupported) glBindVertexArray(lines.vaoId); - - // Lines - vertex positions buffer - glBindBuffer(GL_ARRAY_BUFFER, lines.vboId[0]); - //glBufferData(GL_ARRAY_BUFFER, sizeof(float)*3*2*MAX_LINES_BATCH, lines.vertices, GL_DYNAMIC_DRAW); - glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(float)*3*lines.vCounter, lines.vertices); // target - offset (in bytes) - size (in bytes) - data pointer - - // Lines - colors buffer - glBindBuffer(GL_ARRAY_BUFFER, lines.vboId[1]); - //glBufferData(GL_ARRAY_BUFFER, sizeof(float)*4*2*MAX_LINES_BATCH, lines.colors, GL_DYNAMIC_DRAW); - glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(unsigned char)*4*lines.cCounter, lines.colors); - } - - // Update triangles vertex buffers - if (triangles.vCounter > 0) - { - // Activate Triangles VAO - if (vaoSupported) glBindVertexArray(triangles.vaoId); - - // Triangles - vertex positions buffer - glBindBuffer(GL_ARRAY_BUFFER, triangles.vboId[0]); - //glBufferData(GL_ARRAY_BUFFER, sizeof(float)*3*3*MAX_TRIANGLES_BATCH, triangles.vertices, GL_DYNAMIC_DRAW); - glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(float)*3*triangles.vCounter, triangles.vertices); - - // Triangles - colors buffer - glBindBuffer(GL_ARRAY_BUFFER, triangles.vboId[1]); - //glBufferData(GL_ARRAY_BUFFER, sizeof(float)*4*3*MAX_TRIANGLES_BATCH, triangles.colors, GL_DYNAMIC_DRAW); - glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(unsigned char)*4*triangles.cCounter, triangles.colors); - } - - // Update quads vertex buffers - if (quads.vCounter > 0) - { - // Activate Quads VAO - if (vaoSupported) glBindVertexArray(quads.vaoId); - - // Quads - vertex positions buffer - glBindBuffer(GL_ARRAY_BUFFER, quads.vboId[0]); - //glBufferData(GL_ARRAY_BUFFER, sizeof(float)*3*4*MAX_QUADS_BATCH, quads.vertices, GL_DYNAMIC_DRAW); - glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(float)*3*quads.vCounter, quads.vertices); - - // Quads - texture coordinates buffer - glBindBuffer(GL_ARRAY_BUFFER, quads.vboId[1]); - //glBufferData(GL_ARRAY_BUFFER, sizeof(float)*2*4*MAX_QUADS_BATCH, quads.texcoords, GL_DYNAMIC_DRAW); - glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(float)*2*quads.vCounter, quads.texcoords); - - // Quads - colors buffer - glBindBuffer(GL_ARRAY_BUFFER, quads.vboId[2]); - //glBufferData(GL_ARRAY_BUFFER, sizeof(float)*4*4*MAX_QUADS_BATCH, quads.colors, GL_DYNAMIC_DRAW); - glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(unsigned char)*4*quads.vCounter, quads.colors); - - // Another option would be using buffer mapping... - //quads.vertices = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE); - // Now we can modify vertices - //glUnmapBuffer(GL_ARRAY_BUFFER); - } - //-------------------------------------------------------------- - - // Unbind the current VAO - if (vaoSupported) glBindVertexArray(0); -} - -// Draw default internal buffers vertex data -// NOTE: We draw in this order: lines, triangles, quads -static void DrawBuffersDefault(void) -{ - Matrix matProjection = projection; - Matrix matModelView = modelview; - - int eyesCount = 1; -#if defined(SUPPORT_VR_SIMULATOR) - if (vrStereoRender) eyesCount = 2; -#endif - - for (int eye = 0; eye < eyesCount; eye++) - { - #if defined(SUPPORT_VR_SIMULATOR) - if (eyesCount == 2) SetStereoView(eye, matProjection, matModelView); - #endif - - // Set current shader and upload current MVP matrix - if ((lines.vCounter > 0) || (triangles.vCounter > 0) || (quads.vCounter > 0)) - { - glUseProgram(currentShader.id); - - // Create modelview-projection matrix - Matrix matMVP = MatrixMultiply(modelview, projection); - - glUniformMatrix4fv(currentShader.locs[LOC_MATRIX_MVP], 1, false, MatrixToFloat(matMVP)); - glUniform4f(currentShader.locs[LOC_COLOR_DIFFUSE], 1.0f, 1.0f, 1.0f, 1.0f); - glUniform1i(currentShader.locs[LOC_MAP_DIFFUSE], 0); - - // NOTE: Additional map textures not considered for default buffers drawing - } - - // Draw lines buffers - if (lines.vCounter > 0) - { - glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, whiteTexture); - - if (vaoSupported) - { - glBindVertexArray(lines.vaoId); - } - else - { - // Bind vertex attrib: position (shader-location = 0) - glBindBuffer(GL_ARRAY_BUFFER, lines.vboId[0]); - glVertexAttribPointer(currentShader.locs[LOC_VERTEX_POSITION], 3, GL_FLOAT, 0, 0, 0); - glEnableVertexAttribArray(currentShader.locs[LOC_VERTEX_POSITION]); - - // Bind vertex attrib: color (shader-location = 3) - glBindBuffer(GL_ARRAY_BUFFER, lines.vboId[1]); - glVertexAttribPointer(currentShader.locs[LOC_VERTEX_COLOR], 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, 0); - glEnableVertexAttribArray(currentShader.locs[LOC_VERTEX_COLOR]); - } - - glDrawArrays(GL_LINES, 0, lines.vCounter); - - if (!vaoSupported) glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindTexture(GL_TEXTURE_2D, 0); - } - - // Draw triangles buffers - if (triangles.vCounter > 0) - { - glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, whiteTexture); - - if (vaoSupported) - { - glBindVertexArray(triangles.vaoId); - } - else - { - // Bind vertex attrib: position (shader-location = 0) - glBindBuffer(GL_ARRAY_BUFFER, triangles.vboId[0]); - glVertexAttribPointer(currentShader.locs[LOC_VERTEX_POSITION], 3, GL_FLOAT, 0, 0, 0); - glEnableVertexAttribArray(currentShader.locs[LOC_VERTEX_POSITION]); - - // Bind vertex attrib: color (shader-location = 3) - glBindBuffer(GL_ARRAY_BUFFER, triangles.vboId[1]); - glVertexAttribPointer(currentShader.locs[LOC_VERTEX_COLOR], 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, 0); - glEnableVertexAttribArray(currentShader.locs[LOC_VERTEX_COLOR]); - } - - glDrawArrays(GL_TRIANGLES, 0, triangles.vCounter); - - if (!vaoSupported) glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindTexture(GL_TEXTURE_2D, 0); - } - - // Draw quads buffers - if (quads.vCounter > 0) - { - int quadsCount = 0; - int numIndicesToProcess = 0; - int indicesOffset = 0; - - if (vaoSupported) - { - glBindVertexArray(quads.vaoId); - } - else - { - // Bind vertex attrib: position (shader-location = 0) - glBindBuffer(GL_ARRAY_BUFFER, quads.vboId[0]); - glVertexAttribPointer(currentShader.locs[LOC_VERTEX_POSITION], 3, GL_FLOAT, 0, 0, 0); - glEnableVertexAttribArray(currentShader.locs[LOC_VERTEX_POSITION]); - - // Bind vertex attrib: texcoord (shader-location = 1) - glBindBuffer(GL_ARRAY_BUFFER, quads.vboId[1]); - glVertexAttribPointer(currentShader.locs[LOC_VERTEX_TEXCOORD01], 2, GL_FLOAT, 0, 0, 0); - glEnableVertexAttribArray(currentShader.locs[LOC_VERTEX_TEXCOORD01]); - - // Bind vertex attrib: color (shader-location = 3) - glBindBuffer(GL_ARRAY_BUFFER, quads.vboId[2]); - glVertexAttribPointer(currentShader.locs[LOC_VERTEX_COLOR], 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, 0); - glEnableVertexAttribArray(currentShader.locs[LOC_VERTEX_COLOR]); - - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, quads.vboId[3]); - } - - //TraceLog(LOG_DEBUG, "Draws required per frame: %i", drawsCounter); - - for (int i = 0; i < drawsCounter; i++) - { - quadsCount = draws[i].vertexCount/4; - numIndicesToProcess = quadsCount*6; // Get number of Quads*6 index by Quad - - //TraceLog(LOG_DEBUG, "Quads to render: %i - Vertex Count: %i", quadsCount, draws[i].vertexCount); - - glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, draws[i].textureId); - - // NOTE: The final parameter tells the GPU the offset in bytes from the start of the index buffer to the location of the first index to process - #if defined(GRAPHICS_API_OPENGL_33) - glDrawElements(GL_TRIANGLES, numIndicesToProcess, GL_UNSIGNED_INT, (GLvoid *)(sizeof(GLuint)*indicesOffset)); - #elif defined(GRAPHICS_API_OPENGL_ES2) - glDrawElements(GL_TRIANGLES, numIndicesToProcess, GL_UNSIGNED_SHORT, (GLvoid *)(sizeof(GLushort)*indicesOffset)); - #endif - //GLenum err; - //if ((err = glGetError()) != GL_NO_ERROR) TraceLog(LOG_INFO, "OpenGL error: %i", (int)err); //GL_INVALID_ENUM! - - indicesOffset += draws[i].vertexCount/4*6; - } - - if (!vaoSupported) - { - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); - } - - glBindTexture(GL_TEXTURE_2D, 0); // Unbind textures - } - - if (vaoSupported) glBindVertexArray(0); // Unbind VAO - - glUseProgram(0); // Unbind shader program - } - - // Reset draws counter - drawsCounter = 1; - draws[0].textureId = whiteTexture; - draws[0].vertexCount = 0; - - // Reset vertex counters for next frame - lines.vCounter = 0; - lines.cCounter = 0; - triangles.vCounter = 0; - triangles.cCounter = 0; - quads.vCounter = 0; - quads.tcCounter = 0; - quads.cCounter = 0; - - // Reset depth for next draw - currentDepth = -1.0f; - - // Restore projection/modelview matrices - projection = matProjection; - modelview = matModelView; -} - -// Unload default internal buffers vertex data from CPU and GPU -static void UnloadBuffersDefault(void) -{ - // Unbind everything - if (vaoSupported) glBindVertexArray(0); - glDisableVertexAttribArray(0); - glDisableVertexAttribArray(1); - glDisableVertexAttribArray(2); - glDisableVertexAttribArray(3); - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); - - // Delete VBOs from GPU (VRAM) - glDeleteBuffers(1, &lines.vboId[0]); - glDeleteBuffers(1, &lines.vboId[1]); - glDeleteBuffers(1, &triangles.vboId[0]); - glDeleteBuffers(1, &triangles.vboId[1]); - glDeleteBuffers(1, &quads.vboId[0]); - glDeleteBuffers(1, &quads.vboId[1]); - glDeleteBuffers(1, &quads.vboId[2]); - glDeleteBuffers(1, &quads.vboId[3]); - - if (vaoSupported) - { - // Delete VAOs from GPU (VRAM) - glDeleteVertexArrays(1, &lines.vaoId); - glDeleteVertexArrays(1, &triangles.vaoId); - glDeleteVertexArrays(1, &quads.vaoId); - } - - // Free vertex arrays memory from CPU (RAM) - free(lines.vertices); - free(lines.colors); - - free(triangles.vertices); - free(triangles.colors); - - free(quads.vertices); - free(quads.texcoords); - free(quads.colors); - free(quads.indices); -} - -// Renders a 1x1 XY quad in NDC -static void GenDrawQuad(void) -{ - unsigned int quadVAO = 0; - unsigned int quadVBO = 0; - - float vertices[] = { - // Positions // Texture Coords - -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, - -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, - 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, - 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, - }; - - // Set up plane VAO - glGenVertexArrays(1, &quadVAO); - glGenBuffers(1, &quadVBO); - glBindVertexArray(quadVAO); - - // Fill buffer - glBindBuffer(GL_ARRAY_BUFFER, quadVBO); - glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), &vertices, GL_STATIC_DRAW); - - // Link vertex attributes - glEnableVertexAttribArray(0); - glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5*sizeof(float), (void *)0); - glEnableVertexAttribArray(1); - glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5*sizeof(float), (void *)(3*sizeof(float))); - - // Draw quad - glBindVertexArray(quadVAO); - glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); - glBindVertexArray(0); - - glDeleteBuffers(1, &quadVBO); - glDeleteVertexArrays(1, &quadVAO); -} - -// Renders a 1x1 3D cube in NDC -static void GenDrawCube(void) -{ - unsigned int cubeVAO = 0; - unsigned int cubeVBO = 0; - - float vertices[] = { - -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, - 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, - 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, - 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, - -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, - -1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, - -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, - 1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, - 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, - -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, - -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, - -1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, - -1.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f, - -1.0f, -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, - -1.0f, -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, - -1.0f, -1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, - -1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, - 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, - 1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, - 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, - 1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, - 1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, - -1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, - 1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f, - 1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, - 1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, - -1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, - -1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, - -1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, - 1.0f, 1.0f , 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, - 1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, - -1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, - -1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f - }; - - // Set up cube VAO - glGenVertexArrays(1, &cubeVAO); - glGenBuffers(1, &cubeVBO); - - // Fill buffer - glBindBuffer(GL_ARRAY_BUFFER, cubeVBO); - glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); - - // Link vertex attributes - glBindVertexArray(cubeVAO); - glEnableVertexAttribArray(0); - glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8*sizeof(float), (void *)0); - glEnableVertexAttribArray(1); - glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8*sizeof(float), (void *)(3*sizeof(float))); - glEnableVertexAttribArray(2); - glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8*sizeof(float), (void *)(6*sizeof(float))); - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindVertexArray(0); - - // Draw cube - glBindVertexArray(cubeVAO); - glDrawArrays(GL_TRIANGLES, 0, 36); - glBindVertexArray(0); - - glDeleteBuffers(1, &cubeVBO); - glDeleteVertexArrays(1, &cubeVAO); -} - -#if defined(SUPPORT_VR_SIMULATOR) -// Configure stereo rendering (including distortion shader) with HMD device parameters -// NOTE: It modifies the global variable: VrStereoConfig vrConfig -static void SetStereoConfig(VrDeviceInfo hmd) -{ - // Compute aspect ratio - float aspect = ((float)hmd.hResolution*0.5f)/(float)hmd.vResolution; - - // Compute lens parameters - float lensShift = (hmd.hScreenSize*0.25f - hmd.lensSeparationDistance*0.5f)/hmd.hScreenSize; - float leftLensCenter[2] = { 0.25f + lensShift, 0.5f }; - float rightLensCenter[2] = { 0.75f - lensShift, 0.5f }; - float leftScreenCenter[2] = { 0.25f, 0.5f }; - float rightScreenCenter[2] = { 0.75f, 0.5f }; - - // Compute distortion scale parameters - // NOTE: To get lens max radius, lensShift must be normalized to [-1..1] - float lensRadius = fabsf(-1.0f - 4.0f*lensShift); - float lensRadiusSq = lensRadius*lensRadius; - float distortionScale = hmd.lensDistortionValues[0] + - hmd.lensDistortionValues[1]*lensRadiusSq + - hmd.lensDistortionValues[2]*lensRadiusSq*lensRadiusSq + - hmd.lensDistortionValues[3]*lensRadiusSq*lensRadiusSq*lensRadiusSq; - - TraceLog(LOG_DEBUG, "VR: Distortion Scale: %f", distortionScale); - - float normScreenWidth = 0.5f; - float normScreenHeight = 1.0f; - float scaleIn[2] = { 2.0f/normScreenWidth, 2.0f/normScreenHeight/aspect }; - float scale[2] = { normScreenWidth*0.5f/distortionScale, normScreenHeight*0.5f*aspect/distortionScale }; - - TraceLog(LOG_DEBUG, "VR: Distortion Shader: LeftLensCenter = { %f, %f }", leftLensCenter[0], leftLensCenter[1]); - TraceLog(LOG_DEBUG, "VR: Distortion Shader: RightLensCenter = { %f, %f }", rightLensCenter[0], rightLensCenter[1]); - TraceLog(LOG_DEBUG, "VR: Distortion Shader: Scale = { %f, %f }", scale[0], scale[1]); - TraceLog(LOG_DEBUG, "VR: Distortion Shader: ScaleIn = { %f, %f }", scaleIn[0], scaleIn[1]); - -#if defined(SUPPORT_DISTORTION_SHADER) - // Update distortion shader with lens and distortion-scale parameters - SetShaderValue(vrConfig.distortionShader, GetShaderLocation(vrConfig.distortionShader, "leftLensCenter"), leftLensCenter, 2); - SetShaderValue(vrConfig.distortionShader, GetShaderLocation(vrConfig.distortionShader, "rightLensCenter"), rightLensCenter, 2); - SetShaderValue(vrConfig.distortionShader, GetShaderLocation(vrConfig.distortionShader, "leftScreenCenter"), leftScreenCenter, 2); - SetShaderValue(vrConfig.distortionShader, GetShaderLocation(vrConfig.distortionShader, "rightScreenCenter"), rightScreenCenter, 2); - - SetShaderValue(vrConfig.distortionShader, GetShaderLocation(vrConfig.distortionShader, "scale"), scale, 2); - SetShaderValue(vrConfig.distortionShader, GetShaderLocation(vrConfig.distortionShader, "scaleIn"), scaleIn, 2); - SetShaderValue(vrConfig.distortionShader, GetShaderLocation(vrConfig.distortionShader, "hmdWarpParam"), hmd.lensDistortionValues, 4); - SetShaderValue(vrConfig.distortionShader, GetShaderLocation(vrConfig.distortionShader, "chromaAbParam"), hmd.chromaAbCorrection, 4); -#endif - - // Fovy is normally computed with: 2*atan2(hmd.vScreenSize, 2*hmd.eyeToScreenDistance) - // ...but with lens distortion it is increased (see Oculus SDK Documentation) - //float fovy = 2.0f*atan2(hmd.vScreenSize*0.5f*distortionScale, hmd.eyeToScreenDistance); // Really need distortionScale? - float fovy = 2.0f*(float)atan2(hmd.vScreenSize*0.5f, hmd.eyeToScreenDistance); - - // Compute camera projection matrices - float projOffset = 4.0f*lensShift; // Scaled to projection space coordinates [-1..1] - Matrix proj = MatrixPerspective(fovy, aspect, 0.01, 1000.0); - vrConfig.eyesProjection[0] = MatrixMultiply(proj, MatrixTranslate(projOffset, 0.0f, 0.0f)); - vrConfig.eyesProjection[1] = MatrixMultiply(proj, MatrixTranslate(-projOffset, 0.0f, 0.0f)); - - // Compute camera transformation matrices - // NOTE: Camera movement might seem more natural if we model the head. - // Our axis of rotation is the base of our head, so we might want to add - // some y (base of head to eye level) and -z (center of head to eye protrusion) to the camera positions. - vrConfig.eyesViewOffset[0] = MatrixTranslate(-hmd.interpupillaryDistance*0.5f, 0.075f, 0.045f); - vrConfig.eyesViewOffset[1] = MatrixTranslate(hmd.interpupillaryDistance*0.5f, 0.075f, 0.045f); - - // Compute eyes Viewports - //vrConfig.eyesViewport[0] = (Rectangle){ 0, 0, hmd.hResolution/2, hmd.vResolution }; - //vrConfig.eyesViewport[1] = (Rectangle){ hmd.hResolution/2, 0, hmd.hResolution/2, hmd.vResolution }; -} - -// Set internal projection and modelview matrix depending on eyes tracking data -static void SetStereoView(int eye, Matrix matProjection, Matrix matModelView) -{ - Matrix eyeProjection = matProjection; - Matrix eyeModelView = matModelView; - - // Setup viewport and projection/modelview matrices using tracking data - rlViewport(eye*screenWidth/2, 0, screenWidth/2, screenHeight); - - // Apply view offset to modelview matrix - eyeModelView = MatrixMultiply(matModelView, vrConfig.eyesViewOffset[eye]); - - // Set current eye projection matrix - eyeProjection = vrConfig.eyesProjection[eye]; - - SetMatrixModelview(eyeModelView); - SetMatrixProjection(eyeProjection); -} -#endif // defined(SUPPORT_VR_SIMULATOR) - -#endif //defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - -#if defined(GRAPHICS_API_OPENGL_11) -// Mipmaps data is generated after image data -static int GenerateMipmaps(unsigned char *data, int baseWidth, int baseHeight) -{ - int mipmapCount = 1; // Required mipmap levels count (including base level) - int width = baseWidth; - int height = baseHeight; - int size = baseWidth*baseHeight*4; // Size in bytes (will include mipmaps...), RGBA only - - // Count mipmap levels required - while ((width != 1) && (height != 1)) - { - if (width != 1) width /= 2; - if (height != 1) height /= 2; - - TraceLog(LOG_DEBUG, "Next mipmap size: %i x %i", width, height); - - mipmapCount++; - - size += (width*height*4); // Add mipmap size (in bytes) - } - - TraceLog(LOG_DEBUG, "Total mipmaps required: %i", mipmapCount); - TraceLog(LOG_DEBUG, "Total size of data required: %i", size); - - unsigned char *temp = realloc(data, size); - - if (temp != NULL) data = temp; - else TraceLog(LOG_WARNING, "Mipmaps required memory could not be allocated"); - - width = baseWidth; - height = baseHeight; - size = (width*height*4); - - // Generate mipmaps - // NOTE: Every mipmap data is stored after data - Color *image = (Color *)malloc(width*height*sizeof(Color)); - Color *mipmap = NULL; - int offset = 0; - int j = 0; - - for (int i = 0; i < size; i += 4) - { - image[j].r = data[i]; - image[j].g = data[i + 1]; - image[j].b = data[i + 2]; - image[j].a = data[i + 3]; - j++; - } - - TraceLog(LOG_DEBUG, "Mipmap base (%ix%i)", width, height); - - for (int mip = 1; mip < mipmapCount; mip++) - { - mipmap = GenNextMipmap(image, width, height); - - offset += (width*height*4); // Size of last mipmap - j = 0; - - width /= 2; - height /= 2; - size = (width*height*4); // Mipmap size to store after offset - - // Add mipmap to data - for (int i = 0; i < size; i += 4) - { - data[offset + i] = mipmap[j].r; - data[offset + i + 1] = mipmap[j].g; - data[offset + i + 2] = mipmap[j].b; - data[offset + i + 3] = mipmap[j].a; - j++; - } - - free(image); - - image = mipmap; - mipmap = NULL; - } - - free(mipmap); // free mipmap data - - return mipmapCount; -} - -// Manual mipmap generation (basic scaling algorithm) -static Color *GenNextMipmap(Color *srcData, int srcWidth, int srcHeight) -{ - int x2, y2; - Color prow, pcol; - - int width = srcWidth/2; - int height = srcHeight/2; - - Color *mipmap = (Color *)malloc(width*height*sizeof(Color)); - - // Scaling algorithm works perfectly (box-filter) - for (int y = 0; y < height; y++) - { - y2 = 2*y; - - for (int x = 0; x < width; x++) - { - x2 = 2*x; - - prow.r = (srcData[y2*srcWidth + x2].r + srcData[y2*srcWidth + x2 + 1].r)/2; - prow.g = (srcData[y2*srcWidth + x2].g + srcData[y2*srcWidth + x2 + 1].g)/2; - prow.b = (srcData[y2*srcWidth + x2].b + srcData[y2*srcWidth + x2 + 1].b)/2; - prow.a = (srcData[y2*srcWidth + x2].a + srcData[y2*srcWidth + x2 + 1].a)/2; - - pcol.r = (srcData[(y2+1)*srcWidth + x2].r + srcData[(y2+1)*srcWidth + x2 + 1].r)/2; - pcol.g = (srcData[(y2+1)*srcWidth + x2].g + srcData[(y2+1)*srcWidth + x2 + 1].g)/2; - pcol.b = (srcData[(y2+1)*srcWidth + x2].b + srcData[(y2+1)*srcWidth + x2 + 1].b)/2; - pcol.a = (srcData[(y2+1)*srcWidth + x2].a + srcData[(y2+1)*srcWidth + x2 + 1].a)/2; - - mipmap[y*width + x].r = (prow.r + pcol.r)/2; - mipmap[y*width + x].g = (prow.g + pcol.g)/2; - mipmap[y*width + x].b = (prow.b + pcol.b)/2; - mipmap[y*width + x].a = (prow.a + pcol.a)/2; - } - } - - TraceLog(LOG_DEBUG, "Mipmap generated successfully (%ix%i)", width, height); - - return mipmap; -} -#endif - -#if defined(RLGL_STANDALONE) -// Show trace log messages (LOG_INFO, LOG_WARNING, LOG_ERROR, LOG_DEBUG) -void TraceLog(int msgType, const char *text, ...) -{ - va_list args; - va_start(args, text); - - switch (msgType) - { - case LOG_INFO: fprintf(stdout, "INFO: "); break; - case LOG_ERROR: fprintf(stdout, "ERROR: "); break; - case LOG_WARNING: fprintf(stdout, "WARNING: "); break; - case LOG_DEBUG: fprintf(stdout, "DEBUG: "); break; - default: break; - } - - vfprintf(stdout, text, args); - fprintf(stdout, "\n"); - - va_end(args); - - if (msgType == LOG_ERROR) exit(1); -} -#endif diff --git a/game/src/libs/raylib/rlgl.h b/game/src/libs/raylib/rlgl.h deleted file mode 100644 index 3f06a69..0000000 --- a/game/src/libs/raylib/rlgl.h +++ /dev/null @@ -1,486 +0,0 @@ -/********************************************************************************************** -* -* rlgl - raylib OpenGL abstraction layer -* -* rlgl is a wrapper for multiple OpenGL versions (1.1, 2.1, 3.3 Core, ES 2.0) to -* pseudo-OpenGL 1.1 style functions (rlVertex, rlTranslate, rlRotate...). -* -* When chosing an OpenGL version greater than OpenGL 1.1, rlgl stores vertex data on internal -* VBO buffers (and VAOs if available). It requires calling 3 functions: -* rlglInit() - Initialize internal buffers and auxiliar resources -* rlglDraw() - Process internal buffers and send required draw calls -* rlglClose() - De-initialize internal buffers data and other auxiliar resources -* -* CONFIGURATION: -* -* #define GRAPHICS_API_OPENGL_11 -* #define GRAPHICS_API_OPENGL_21 -* #define GRAPHICS_API_OPENGL_33 -* #define GRAPHICS_API_OPENGL_ES2 -* Use selected OpenGL graphics backend, should be supported by platform -* Those preprocessor defines are only used on rlgl module, if OpenGL version is -* required by any other module, use rlGetVersion() tocheck it -* -* #define RLGL_STANDALONE -* Use rlgl as standalone library (no raylib dependency) -* -* #define SUPPORT_VR_SIMULATION / SUPPORT_STEREO_RENDERING -* Support VR simulation functionality (stereo rendering) -* -* #define SUPPORT_DISTORTION_SHADER -* Include stereo rendering distortion shader (shader_distortion.h) -* -* DEPENDENCIES: -* raymath - 3D math functionality (Vector3, Matrix, Quaternion) -* GLAD - OpenGL extensions loading (OpenGL 3.3 Core only) -* -* -* LICENSE: zlib/libpng -* -* Copyright (c) 2014-2017 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. -* -* Permission is granted to anyone to use this software for any purpose, including commercial -* applications, and to alter it and redistribute it freely, subject to the following restrictions: -* -* 1. The origin of this software must not be misrepresented; you must not claim that you -* wrote the original software. If you use this software in a product, an acknowledgment -* in the product documentation would be appreciated but is not required. -* -* 2. Altered source versions must be plainly marked as such, and must not be misrepresented -* as being the original software. -* -* 3. This notice may not be removed or altered from any source distribution. -* -**********************************************************************************************/ - -#ifndef RLGL_H -#define RLGL_H - -#if defined(RLGL_STANDALONE) - #define RAYMATH_STANDALONE -#else - #include "raylib.h" // Required for: Model, Shader, Texture2D, TraceLog() -#endif - -#include "raymath.h" // Required for: Vector3, Matrix - -// Security check in case no GRAPHICS_API_OPENGL_* defined -#if !defined(GRAPHICS_API_OPENGL_11) && !defined(GRAPHICS_API_OPENGL_21) && !defined(GRAPHICS_API_OPENGL_33) && !defined(GRAPHICS_API_OPENGL_ES2) - #define GRAPHICS_API_OPENGL_11 -#endif - -// Security check in case multiple GRAPHICS_API_OPENGL_* defined -#if defined(GRAPHICS_API_OPENGL_11) - #if defined(GRAPHICS_API_OPENGL_21) - #undef GRAPHICS_API_OPENGL_21 - #endif - #if defined(GRAPHICS_API_OPENGL_33) - #undef GRAPHICS_API_OPENGL_33 - #endif - #if defined(GRAPHICS_API_OPENGL_ES2) - #undef GRAPHICS_API_OPENGL_ES2 - #endif -#endif - -#if defined(GRAPHICS_API_OPENGL_21) - #define GRAPHICS_API_OPENGL_33 -#endif - -//---------------------------------------------------------------------------------- -// Defines and Macros -//---------------------------------------------------------------------------------- -#if defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_33) - // NOTE: This is the maximum amount of lines, triangles and quads per frame, be careful! - #define MAX_LINES_BATCH 8192 - #define MAX_TRIANGLES_BATCH 4096 - #define MAX_QUADS_BATCH 8192 -#elif defined(GRAPHICS_API_OPENGL_ES2) - // NOTE: Reduce memory sizes for embedded systems (RPI and HTML5) - // NOTE: On HTML5 (emscripten) this is allocated on heap, by default it's only 16MB!...just take care... - #define MAX_LINES_BATCH 1024 // Critical for wire shapes (sphere) - #define MAX_TRIANGLES_BATCH 2048 // Critical for some shapes (sphere) - #define MAX_QUADS_BATCH 1024 // Be careful with text, every letter maps a quad -#endif - -// Texture parameters (equivalent to OpenGL defines) -#define RL_TEXTURE_WRAP_S 0x2802 // GL_TEXTURE_WRAP_S -#define RL_TEXTURE_WRAP_T 0x2803 // GL_TEXTURE_WRAP_T -#define RL_TEXTURE_MAG_FILTER 0x2800 // GL_TEXTURE_MAG_FILTER -#define RL_TEXTURE_MIN_FILTER 0x2801 // GL_TEXTURE_MIN_FILTER -#define RL_TEXTURE_ANISOTROPIC_FILTER 0x3000 // Anisotropic filter (custom identifier) - -#define RL_FILTER_NEAREST 0x2600 // GL_NEAREST -#define RL_FILTER_LINEAR 0x2601 // GL_LINEAR -#define RL_FILTER_MIP_NEAREST 0x2700 // GL_NEAREST_MIPMAP_NEAREST -#define RL_FILTER_NEAREST_MIP_LINEAR 0x2702 // GL_NEAREST_MIPMAP_LINEAR -#define RL_FILTER_LINEAR_MIP_NEAREST 0x2701 // GL_LINEAR_MIPMAP_NEAREST -#define RL_FILTER_MIP_LINEAR 0x2703 // GL_LINEAR_MIPMAP_LINEAR - -#define RL_WRAP_REPEAT 0x2901 // GL_REPEAT -#define RL_WRAP_CLAMP 0x812F // GL_CLAMP_TO_EDGE -#define RL_WRAP_CLAMP_MIRROR 0x8742 // GL_MIRROR_CLAMP_EXT - -// Matrix modes (equivalent to OpenGL) -#define RL_MODELVIEW 0x1700 // GL_MODELVIEW -#define RL_PROJECTION 0x1701 // GL_PROJECTION -#define RL_TEXTURE 0x1702 // GL_TEXTURE - -// Primitive assembly draw modes -#define RL_LINES 0x0001 // GL_LINES -#define RL_TRIANGLES 0x0004 // GL_TRIANGLES -#define RL_QUADS 0x0007 // GL_QUADS - -//---------------------------------------------------------------------------------- -// Types and Structures Definition -//---------------------------------------------------------------------------------- -typedef enum { OPENGL_11 = 1, OPENGL_21, OPENGL_33, OPENGL_ES_20 } GlVersion; - -typedef unsigned char byte; - -#if defined(RLGL_STANDALONE) - #ifndef __cplusplus - // Boolean type - typedef enum { false, true } bool; - #endif - - // Shader location point type - typedef enum { - LOC_VERTEX_POSITION = 0, - LOC_VERTEX_TEXCOORD01, - LOC_VERTEX_TEXCOORD02, - LOC_VERTEX_NORMAL, - LOC_VERTEX_TANGENT, - LOC_VERTEX_COLOR, - LOC_MATRIX_MVP, - LOC_MATRIX_MODEL, - LOC_MATRIX_VIEW, - LOC_MATRIX_PROJECTION, - LOC_VECTOR_VIEW, - LOC_COLOR_DIFFUSE, - LOC_COLOR_SPECULAR, - LOC_COLOR_AMBIENT, - LOC_MAP_ALBEDO, // LOC_MAP_DIFFUSE - LOC_MAP_METALNESS, // LOC_MAP_SPECULAR - LOC_MAP_NORMAL, - LOC_MAP_ROUGHNESS, - LOC_MAP_OCCUSION, - LOC_MAP_EMISSION, - LOC_MAP_HEIGHT, - LOC_MAP_CUBEMAP, - LOC_MAP_IRRADIANCE, - LOC_MAP_PREFILTER, - LOC_MAP_BRDF - } ShaderLocationIndex; - - #define LOC_MAP_DIFFUSE LOC_MAP_ALBEDO - #define LOC_MAP_SPECULAR LOC_MAP_METALNESS - - // Material map type - typedef enum { - MAP_ALBEDO = 0, // MAP_DIFFUSE - MAP_METALNESS = 1, // MAP_SPECULAR - MAP_NORMAL = 2, - MAP_ROUGHNESS = 3, - MAP_OCCLUSION, - MAP_EMISSION, - MAP_HEIGHT, - MAP_CUBEMAP, // NOTE: Uses GL_TEXTURE_CUBE_MAP - MAP_IRRADIANCE, // NOTE: Uses GL_TEXTURE_CUBE_MAP - MAP_PREFILTER, // NOTE: Uses GL_TEXTURE_CUBE_MAP - MAP_BRDF - } TexmapIndex; - - #define MAP_DIFFUSE MAP_ALBEDO - #define MAP_SPECULAR MAP_METALNESS - - // Color type, RGBA (32bit) - typedef struct Color { - unsigned char r; - unsigned char g; - unsigned char b; - unsigned char a; - } Color; - - // Texture2D type - // NOTE: Data stored in GPU memory - typedef struct Texture2D { - unsigned int id; // OpenGL texture id - int width; // Texture base width - int height; // Texture base height - int mipmaps; // Mipmap levels, 1 by default - int format; // Data format (TextureFormat) - } Texture2D; - - // RenderTexture2D type, for texture rendering - typedef struct RenderTexture2D { - unsigned int id; // Render texture (fbo) id - Texture2D texture; // Color buffer attachment texture - Texture2D depth; // Depth buffer attachment texture - } RenderTexture2D; - - // Vertex data definning a mesh - typedef struct Mesh { - int vertexCount; // number of vertices stored in arrays - int triangleCount; // number of triangles stored (indexed or not) - float *vertices; // vertex position (XYZ - 3 components per vertex) (shader-location = 0) - float *texcoords; // vertex texture coordinates (UV - 2 components per vertex) (shader-location = 1) - float *texcoords2; // vertex second texture coordinates (useful for lightmaps) (shader-location = 5) - float *normals; // vertex normals (XYZ - 3 components per vertex) (shader-location = 2) - float *tangents; // vertex tangents (XYZ - 3 components per vertex) (shader-location = 4) - unsigned char *colors; // vertex colors (RGBA - 4 components per vertex) (shader-location = 3) - unsigned short *indices;// vertex indices (in case vertex data comes indexed) - - unsigned int vaoId; // OpenGL Vertex Array Object id - unsigned int vboId[7]; // OpenGL Vertex Buffer Objects id (7 types of vertex data) - } Mesh; - - // Shader and material limits - #define MAX_SHADER_LOCATIONS 32 - #define MAX_MATERIAL_MAPS 12 - - // Shader type (generic) - typedef struct Shader { - unsigned int id; // Shader program id - int locs[MAX_SHADER_LOCATIONS]; // Shader locations array - } Shader; - - // Material texture map - typedef struct MaterialMap { - Texture2D texture; // Material map texture - Color color; // Material map color - float value; // Material map value - } MaterialMap; - - // Material type (generic) - typedef struct Material { - Shader shader; // Material shader - MaterialMap maps[MAX_MATERIAL_MAPS]; // Material maps - float *params; // Material generic parameters (if required) - } Material; - - // Camera type, defines a camera position/orientation in 3d space - typedef struct Camera { - Vector3 position; // Camera position - Vector3 target; // Camera target it looks-at - Vector3 up; // Camera up vector (rotation over its axis) - float fovy; // Camera field-of-view apperture in Y (degrees) - } Camera; - - // Head-Mounted-Display device parameters - typedef struct VrDeviceInfo { - int hResolution; // HMD horizontal resolution in pixels - int vResolution; // HMD vertical resolution in pixels - float hScreenSize; // HMD horizontal size in meters - float vScreenSize; // HMD vertical size in meters - float vScreenCenter; // HMD screen center in meters - float eyeToScreenDistance; // HMD distance between eye and display in meters - float lensSeparationDistance; // HMD lens separation distance in meters - float interpupillaryDistance; // HMD IPD (distance between pupils) in meters - float lensDistortionValues[4]; // HMD lens distortion constant parameters - float chromaAbCorrection[4]; // HMD chromatic aberration correction parameters - } VrDeviceInfo; - - // TraceLog message types - typedef enum { - LOG_INFO = 0, - LOG_ERROR, - LOG_WARNING, - LOG_DEBUG, - LOG_OTHER - } TraceLogType; - - // Texture formats (support depends on OpenGL version) - typedef enum { - UNCOMPRESSED_GRAYSCALE = 1, // 8 bit per pixel (no alpha) - UNCOMPRESSED_GRAY_ALPHA, - UNCOMPRESSED_R5G6B5, // 16 bpp - UNCOMPRESSED_R8G8B8, // 24 bpp - UNCOMPRESSED_R5G5B5A1, // 16 bpp (1 bit alpha) - UNCOMPRESSED_R4G4B4A4, // 16 bpp (4 bit alpha) - UNCOMPRESSED_R8G8B8A8, // 32 bpp - UNCOMPRESSED_R32G32B32, // 32 bit per channel (float) - HDR - COMPRESSED_DXT1_RGB, // 4 bpp (no alpha) - COMPRESSED_DXT1_RGBA, // 4 bpp (1 bit alpha) - COMPRESSED_DXT3_RGBA, // 8 bpp - COMPRESSED_DXT5_RGBA, // 8 bpp - COMPRESSED_ETC1_RGB, // 4 bpp - COMPRESSED_ETC2_RGB, // 4 bpp - COMPRESSED_ETC2_EAC_RGBA, // 8 bpp - COMPRESSED_PVRT_RGB, // 4 bpp - COMPRESSED_PVRT_RGBA, // 4 bpp - COMPRESSED_ASTC_4x4_RGBA, // 8 bpp - COMPRESSED_ASTC_8x8_RGBA // 2 bpp - } TextureFormat; - - // Texture parameters: filter mode - // NOTE 1: Filtering considers mipmaps if available in the texture - // NOTE 2: Filter is accordingly set for minification and magnification - typedef enum { - FILTER_POINT = 0, // No filter, just pixel aproximation - FILTER_BILINEAR, // Linear filtering - FILTER_TRILINEAR, // Trilinear filtering (linear with mipmaps) - FILTER_ANISOTROPIC_4X, // Anisotropic filtering 4x - FILTER_ANISOTROPIC_8X, // Anisotropic filtering 8x - FILTER_ANISOTROPIC_16X, // Anisotropic filtering 16x - } TextureFilterMode; - - // Texture parameters: wrap mode - typedef enum { - WRAP_REPEAT = 0, - WRAP_CLAMP, - WRAP_MIRROR - } TextureWrapMode; - - // Color blending modes (pre-defined) - typedef enum { - BLEND_ALPHA = 0, - BLEND_ADDITIVE, - BLEND_MULTIPLIED - } BlendMode; - - // VR Head Mounted Display devices - typedef enum { - HMD_DEFAULT_DEVICE = 0, - HMD_OCULUS_RIFT_DK2, - HMD_OCULUS_RIFT_CV1, - HMD_OCULUS_GO, - HMD_VALVE_HTC_VIVE, - HMD_SONY_PSVR - } VrDevice; -#endif - -#ifdef __cplusplus -extern "C" { // Prevents name mangling of functions -#endif - -//------------------------------------------------------------------------------------ -// Functions Declaration - Matrix operations -//------------------------------------------------------------------------------------ -void rlMatrixMode(int mode); // Choose the current matrix to be transformed -void rlPushMatrix(void); // Push the current matrix to stack -void rlPopMatrix(void); // Pop lattest inserted matrix from stack -void rlLoadIdentity(void); // Reset current matrix to identity matrix -void rlTranslatef(float x, float y, float z); // Multiply the current matrix by a translation matrix -void rlRotatef(float angleDeg, float x, float y, float z); // Multiply the current matrix by a rotation matrix -void rlScalef(float x, float y, float z); // Multiply the current matrix by a scaling matrix -void rlMultMatrixf(float *matf); // Multiply the current matrix by another matrix -void rlFrustum(double left, double right, double bottom, double top, double near, double far); -void rlOrtho(double left, double right, double bottom, double top, double near, double far); -void rlViewport(int x, int y, int width, int height); // Set the viewport area - -//------------------------------------------------------------------------------------ -// Functions Declaration - Vertex level operations -//------------------------------------------------------------------------------------ -void rlBegin(int mode); // Initialize drawing mode (how to organize vertex) -void rlEnd(void); // Finish vertex providing -void rlVertex2i(int x, int y); // Define one vertex (position) - 2 int -void rlVertex2f(float x, float y); // Define one vertex (position) - 2 float -void rlVertex3f(float x, float y, float z); // Define one vertex (position) - 3 float -void rlTexCoord2f(float x, float y); // Define one vertex (texture coordinate) - 2 float -void rlNormal3f(float x, float y, float z); // Define one vertex (normal) - 3 float -void rlColor4ub(byte r, byte g, byte b, byte a); // Define one vertex (color) - 4 byte -void rlColor3f(float x, float y, float z); // Define one vertex (color) - 3 float -void rlColor4f(float x, float y, float z, float w); // Define one vertex (color) - 4 float - -//------------------------------------------------------------------------------------ -// Functions Declaration - OpenGL equivalent functions (common to 1.1, 3.3+, ES2) -// NOTE: This functions are used to completely abstract raylib code from OpenGL layer -//------------------------------------------------------------------------------------ -void rlEnableTexture(unsigned int id); // Enable texture usage -void rlDisableTexture(void); // Disable texture usage -void rlTextureParameters(unsigned int id, int param, int value); // Set texture parameters (filter, wrap) -void rlEnableRenderTexture(unsigned int id); // Enable render texture (fbo) -void rlDisableRenderTexture(void); // Disable render texture (fbo), return to default framebuffer -void rlEnableDepthTest(void); // Enable depth test -void rlDisableDepthTest(void); // Disable depth test -void rlEnableWireMode(void); // Enable wire mode -void rlDisableWireMode(void); // Disable wire mode -void rlDeleteTextures(unsigned int id); // Delete OpenGL texture from GPU -void rlDeleteRenderTextures(RenderTexture2D target); // Delete render textures (fbo) from GPU -void rlDeleteShader(unsigned int id); // Delete OpenGL shader program from GPU -void rlDeleteVertexArrays(unsigned int id); // Unload vertex data (VAO) from GPU memory -void rlDeleteBuffers(unsigned int id); // Unload vertex data (VBO) from GPU memory -void rlClearColor(byte r, byte g, byte b, byte a); // Clear color buffer with color -void rlClearScreenBuffers(void); // Clear used screen buffers (color and depth) - -//------------------------------------------------------------------------------------ -// Functions Declaration - rlgl functionality -//------------------------------------------------------------------------------------ -void rlglInit(int width, int height); // Initialize rlgl (buffers, shaders, textures, states) -void rlglClose(void); // De-inititialize rlgl (buffers, shaders, textures) -void rlglDraw(void); // Update and Draw default buffers (lines, triangles, quads) - -int rlGetVersion(void); // Returns current OpenGL version -void rlLoadExtensions(void *loader); // Load OpenGL extensions -Vector3 rlUnproject(Vector3 source, Matrix proj, Matrix view); // Get world coordinates from screen coordinates - -// Textures data management -unsigned int rlLoadTexture(void *data, int width, int height, int format, int mipmapCount); // Load texture in GPU -void rlUpdateTexture(unsigned int id, int width, int height, int format, const void *data); // Update GPU texture with new data -void rlUnloadTexture(unsigned int id); -void rlGenerateMipmaps(Texture2D *texture); // Generate mipmap data for selected texture -void *rlReadTexturePixels(Texture2D texture); // Read texture pixel data -unsigned char *rlReadScreenPixels(int width, int height); // Read screen pixel data (color buffer) -RenderTexture2D rlLoadRenderTexture(int width, int height); // Load a texture to be used for rendering (fbo with color and depth attachments) - -// Vertex data management -void rlLoadMesh(Mesh *mesh, bool dynamic); // Upload vertex data into GPU and provided VAO/VBO ids -void rlUpdateMesh(Mesh mesh, int buffer, int numVertex); // Update vertex data on GPU (upload new data to one buffer) -void rlDrawMesh(Mesh mesh, Material material, Matrix transform); // Draw a 3d mesh with material and transform -void rlUnloadMesh(Mesh *mesh); // Unload mesh data from CPU and GPU - -// NOTE: There is a set of shader related functions that are available to end user, -// to avoid creating function wrappers through core module, they have been directly declared in raylib.h - -#if defined(RLGL_STANDALONE) -//------------------------------------------------------------------------------------ -// Shaders System Functions (Module: rlgl) -// NOTE: This functions are useless when using OpenGL 1.1 -//------------------------------------------------------------------------------------ -Shader LoadShader(char *vsFileName, char *fsFileName); // Load a custom shader and bind default locations -void UnloadShader(Shader shader); // Unload a custom shader from memory - -Shader GetShaderDefault(void); // Get default shader -Texture2D GetTextureDefault(void); // Get default texture - -// Shader configuration functions -int GetShaderLocation(Shader shader, const char *uniformName); // Get shader uniform location -void SetShaderValue(Shader shader, int uniformLoc, float *value, int size); // Set shader uniform value (float) -void SetShaderValuei(Shader shader, int uniformLoc, int *value, int size); // Set shader uniform value (int) -void SetShaderValueMatrix(Shader shader, int uniformLoc, Matrix mat); // Set shader uniform value (matrix 4x4) -void SetMatrixProjection(Matrix proj); // Set a custom projection matrix (replaces internal projection matrix) -void SetMatrixModelview(Matrix view); // Set a custom modelview matrix (replaces internal modelview matrix) - -// Texture maps generation (PBR) -// NOTE: Required shaders should be provided -Texture2D GenTextureCubemap(Shader shader, Texture2D skyHDR, int size); // Generate cubemap texture from HDR texture -Texture2D GenTextureIrradiance(Shader shader, Texture2D cubemap, int size); // Generate irradiance texture using cubemap data -Texture2D GenTexturePrefilter(Shader shader, Texture2D cubemap, int size); // Generate prefilter texture using cubemap data -Texture2D GenTextureBRDF(Shader shader, Texture2D cubemap, int size); // Generate BRDF texture using cubemap data - -// Shading and blending -void BeginShaderMode(Shader shader); // Begin custom shader drawing -void EndShaderMode(void); // End custom shader drawing (use default shader) -void BeginBlendMode(int mode); // Begin blending mode (alpha, additive, multiplied) -void EndBlendMode(void); // End blending mode (reset to default: alpha blending) - -// VR simulator functionality -VrDeviceInfo GetVrDeviceInfo(int vrDeviceType); // Get VR device information for some standard devices -void InitVrSimulator(VrDeviceInfo info); // Init VR simulator for selected device parameters -void CloseVrSimulator(void); // Close VR simulator for current device -void UpdateVrTracking(Camera *camera); // Update VR tracking (position and orientation) and camera -void ToggleVrMode(void); // Enable/Disable VR experience (device or simulator) -void BeginVrDrawing(void); // Begin VR stereo rendering -void EndVrDrawing(void); // End VR stereo rendering - -void TraceLog(int msgType, const char *text, ...); // Show trace log messages (LOG_INFO, LOG_WARNING, LOG_ERROR, LOG_DEBUG) -#endif - -#ifdef __cplusplus -} -#endif - -#endif // RLGL_H \ No newline at end of file diff --git a/game/src/libs/raylib/rres.h b/game/src/libs/raylib/rres.h deleted file mode 100644 index 75faf64..0000000 --- a/game/src/libs/raylib/rres.h +++ /dev/null @@ -1,483 +0,0 @@ -/********************************************************************************************** -* -* rres v1.0 - raylib resource (rRES) custom fileformat management functions -* -* CONFIGURATION: -* -* #define RREM_IMPLEMENTATION -* Generates the implementation of the library into the included file. -* If not defined, the library is in header only mode and can be included in other headers -* or source files without problems. But only ONE file should hold the implementation. -* -* DEPENDENCIES: -* tinfl - DEFLATE decompression functions -* -* -* LICENSE: zlib/libpng -* -* Copyright (c) 2016-2017 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. -* -* Permission is granted to anyone to use this software for any purpose, including commercial -* applications, and to alter it and redistribute it freely, subject to the following restrictions: -* -* 1. The origin of this software must not be misrepresented; you must not claim that you -* wrote the original software. If you use this software in a product, an acknowledgment -* in the product documentation would be appreciated but is not required. -* -* 2. Altered source versions must be plainly marked as such, and must not be misrepresented -* as being the original software. -* -* 3. This notice may not be removed or altered from any source distribution. -* -**********************************************************************************************/ - -/* -References: - RIFF file-format: http://www.johnloomis.org/cpe102/asgn/asgn1/riff.html - ZIP file-format: https://en.wikipedia.org/wiki/Zip_(file_format) - http://www.onicos.com/staff/iz/formats/zip.html - XNB file-format: http://xbox.create.msdn.com/en-US/sample/xnb_format -*/ - -#ifndef RRES_H -#define RRES_H - -#if !defined(RRES_STANDALONE) - #include "raylib.h" -#endif - -//#define RRES_STATIC -#ifdef RRES_STATIC - #define RRESDEF static // Functions just visible to module including this file -#else - #ifdef __cplusplus - #define RRESDEF extern "C" // Functions visible from other files (no name mangling of functions in C++) - #else - #define RRESDEF extern // Functions visible from other files - #endif -#endif - -//---------------------------------------------------------------------------------- -// Defines and Macros -//---------------------------------------------------------------------------------- -#define MAX_RESOURCES_SUPPORTED 256 - -//---------------------------------------------------------------------------------- -// Types and Structures Definition -// NOTE: Some types are required for RAYGUI_STANDALONE usage -//---------------------------------------------------------------------------------- -#if defined(RRES_STANDALONE) - // rRES data returned when reading a resource, it contains all required data for user (24 byte) - // NOTE: Using void *data pointer, so we can load to image.data, wave.data, mesh.*, (unsigned char *) - typedef struct RRESData { - unsigned int type; // Resource type (4 byte) - - unsigned int param1; // Resouce parameter 1 (4 byte) - unsigned int param2; // Resouce parameter 2 (4 byte) - unsigned int param3; // Resouce parameter 3 (4 byte) - unsigned int param4; // Resouce parameter 4 (4 byte) - - void *data; // Resource data pointer (4 byte) - } RRESData; - - // RRES type (pointer to RRESData array) - typedef struct RRESData *RRES; // Resource pointer - - // RRESData type - typedef enum { - RRES_TYPE_RAW = 0, - RRES_TYPE_IMAGE, - RRES_TYPE_WAVE, - RRES_TYPE_VERTEX, - RRES_TYPE_TEXT, - RRES_TYPE_FONT_IMAGE, - RRES_TYPE_FONT_CHARDATA, // CharInfo { int value, recX, recY, recWidth, recHeight, offsetX, offsetY, xAdvance } - RRES_TYPE_DIRECTORY - } RRESDataType; - -// Parameters information depending on resource type - -// RRES_TYPE_RAW params: -// RRES_TYPE_IMAGE params: width, height, mipmaps, format -// RRES_TYPE_WAVE params: sampleCount, sampleRate, sampleSize, channels -// RRES_TYPE_VERTEX params: vertexCount, vertexType, vertexFormat // Use masks instead? -// RRES_TYPE_TEXT params: charsCount, cultureCode -// RRES_TYPE_FONT_IMAGE params: width, height, format, mipmaps; -// RRES_TYPE_FONT_CHARDATA params: charsCount, baseSize -// RRES_TYPE_DIRECTORY params: fileCount, directoryCount - -// SpriteFont = RRES_TYPE_FONT_IMAGE chunk + RRES_TYPE_FONT_DATA chunk -// Mesh = multiple RRES_TYPE_VERTEX chunks - - -#endif - -//---------------------------------------------------------------------------------- -// Global variables -//---------------------------------------------------------------------------------- -//... - -//---------------------------------------------------------------------------------- -// Module Functions Declaration -//---------------------------------------------------------------------------------- -//RRESDEF RRESData LoadResourceData(const char *rresFileName, int rresId, int part); -RRESDEF RRES LoadResource(const char *fileName, int rresId); -RRESDEF void UnloadResource(RRES rres); - -/* -QUESTION: How to load each type of data from RRES ? - -rres->type == RRES_TYPE_RAW -unsigned char data = (unsigned char *)rres[0]->data; - -rres->type == RRES_TYPE_IMAGE -Image image; -image.data = rres[0]->data; // Be careful, duplicate pointer -image.width = rres[0]->param1; -image.height = rres[0]->param2; -image.mipmaps = rres[0]->param3; -image.format = rres[0]->format; - -rres->type == RRES_TYPE_WAVE -Wave wave; -wave.data = rres[0]->data; -wave.sampleCount = rres[0]->param1; -wave.sampleRate = rres[0]->param2; -wave.sampleSize = rres[0]->param3; -wave.channels = rres[0]->param4; - -rres->type == RRES_TYPE_VERTEX (multiple parts) -Mesh mesh; -mesh.vertexCount = rres[0]->param1; -mesh.vertices = (float *)rres[0]->data; -mesh.texcoords = (float *)rres[1]->data; -mesh.normals = (float *)rres[2]->data; -mesh.tangents = (float *)rres[3]->data; -mesh.tangents = (unsigned char *)rres[4]->data; - -rres->type == RRES_TYPE_TEXT -unsigned char *text = (unsigned char *)rres->data; -Shader shader = LoadShaderText(text, rres->param1); Shader LoadShaderText(const char *shdrText, int length); - -rres->type == RRES_TYPE_FONT_IMAGE (multiple parts) -rres->type == RRES_TYPE_FONT_CHARDATA -SpriteFont font; -font.texture = LoadTextureFromImage(image); // rres[0] -font.chars = (CharInfo *)rres[1]->data; -font.charsCount = rres[1]->param1; -font.baseSize = rres[1]->param2; - -rres->type == RRES_TYPE_DIRECTORY -unsigned char *fileNames = (unsigned char *)rres[0]->data; // fileNames separed by \n -int filesCount = rres[0]->param1; -*/ - -#endif // RRES_H - - -/*********************************************************************************** -* -* RRES IMPLEMENTATION -* -************************************************************************************/ - -#if defined(RRES_IMPLEMENTATION) - -#include // Required for: FILE, fopen(), fclose() - -// Check if custom malloc/free functions defined, if not, using standard ones -#if !defined(RRES_MALLOC) - #include // Required for: malloc(), free() - - #define RRES_MALLOC(size) malloc(size) - #define RRES_FREE(ptr) free(ptr) -#endif - -#include "external/tinfl.c" // Required for: tinfl_decompress_mem_to_mem() - // NOTE: DEFLATE algorythm data decompression - -//---------------------------------------------------------------------------------- -// Defines and Macros -//---------------------------------------------------------------------------------- -//... - -//---------------------------------------------------------------------------------- -// Types and Structures Definition -//---------------------------------------------------------------------------------- - -// rRES file header (8 byte) -typedef struct { - char id[4]; // File identifier: rRES (4 byte) - unsigned short version; // File version and subversion (2 byte) - unsigned short count; // Number of resources in this file (2 byte) -} RRESFileHeader; - -// rRES info header, every resource includes this header (16 byte + 16 byte) -typedef struct { - unsigned int id; // Resource unique identifier (4 byte) - unsigned char dataType; // Resource data type (1 byte) - unsigned char compType; // Resource data compression type (1 byte) - unsigned char cryptoType; // Resource data encryption type (1 byte) - unsigned char partsCount; // Resource data parts count, used for splitted data (1 byte) - unsigned int dataSize; // Resource data size (compressed or not, only DATA) (4 byte) - unsigned int uncompSize; // Resource data size (uncompressed, only DATA) (4 byte) - - unsigned int param1; // Resouce parameter 1 (4 byte) - unsigned int param2; // Resouce parameter 2 (4 byte) - unsigned int param3; // Resouce parameter 3 (4 byte) - unsigned int param4; // Resouce parameter 4 (4 byte) -} RRESInfoHeader; - -// Compression types -typedef enum { - RRES_COMP_NONE = 0, // No data compression - RRES_COMP_DEFLATE, // DEFLATE compression - RRES_COMP_LZ4, // LZ4 compression - RRES_COMP_LZMA, // LZMA compression - RRES_COMP_BROTLI, // BROTLI compression - // gzip, zopfli, lzo, zstd // Other compression algorythms... -} RRESCompressionType; - -// Encryption types -typedef enum { - RRES_CRYPTO_NONE = 0, // No data encryption - RRES_CRYPTO_XOR, // XOR (128 bit) encryption - RRES_CRYPTO_AES, // RIJNDAEL (128 bit) encryption (AES) - RRES_CRYPTO_TDES, // Triple DES encryption - RRES_CRYPTO_BLOWFISH, // BLOWFISH encryption - RRES_CRYPTO_XTEA, // XTEA encryption - // twofish, RC5, RC6 // Other encryption algorythm... -} RRESEncryptionType; - -// Image/Texture data type -typedef enum { - RRES_IM_UNCOMP_GRAYSCALE = 1, // 8 bit per pixel (no alpha) - RRES_IM_UNCOMP_GRAY_ALPHA, // 16 bpp (2 channels) - RRES_IM_UNCOMP_R5G6B5, // 16 bpp - RRES_IM_UNCOMP_R8G8B8, // 24 bpp - RRES_IM_UNCOMP_R5G5B5A1, // 16 bpp (1 bit alpha) - RRES_IM_UNCOMP_R4G4B4A4, // 16 bpp (4 bit alpha) - RRES_IM_UNCOMP_R8G8B8A8, // 32 bpp - RRES_IM_COMP_DXT1_RGB, // 4 bpp (no alpha) - RRES_IM_COMP_DXT1_RGBA, // 4 bpp (1 bit alpha) - RRES_IM_COMP_DXT3_RGBA, // 8 bpp - RRES_IM_COMP_DXT5_RGBA, // 8 bpp - RRES_IM_COMP_ETC1_RGB, // 4 bpp - RRES_IM_COMP_ETC2_RGB, // 4 bpp - RRES_IM_COMP_ETC2_EAC_RGBA, // 8 bpp - RRES_IM_COMP_PVRT_RGB, // 4 bpp - RRES_IM_COMP_PVRT_RGBA, // 4 bpp - RRES_IM_COMP_ASTC_4x4_RGBA, // 8 bpp - RRES_IM_COMP_ASTC_8x8_RGBA // 2 bpp - //... -} RRESImageFormat; - -// Vertex data type -typedef enum { - RRES_VERT_POSITION, - RRES_VERT_TEXCOORD1, - RRES_VERT_TEXCOORD2, - RRES_VERT_TEXCOORD3, - RRES_VERT_TEXCOORD4, - RRES_VERT_NORMAL, - RRES_VERT_TANGENT, - RRES_VERT_COLOR, - RRES_VERT_INDEX, - //... -} RRESVertexType; - -// Vertex data format type -typedef enum { - RRES_VERT_BYTE, - RRES_VERT_SHORT, - RRES_VERT_INT, - RRES_VERT_HFLOAT, - RRES_VERT_FLOAT, - //... -} RRESVertexFormat; - -#if defined(RRES_STANDALONE) -typedef enum { LOG_INFO = 0, LOG_ERROR, LOG_WARNING, LOG_DEBUG, LOG_OTHER } TraceLogType; -#endif - -//---------------------------------------------------------------------------------- -// Global Variables Definition -//---------------------------------------------------------------------------------- -//... - -//---------------------------------------------------------------------------------- -// Module specific Functions Declaration -//---------------------------------------------------------------------------------- -static void *DecompressData(const unsigned char *data, unsigned long compSize, int uncompSize); - -//---------------------------------------------------------------------------------- -// Module Functions Definition -//---------------------------------------------------------------------------------- - -// Load resource from file by id (could be multiple parts) -// NOTE: Returns uncompressed data with parameters, search resource by id -RRESDEF RRES LoadResource(const char *fileName, int rresId) -{ - RRES rres = { 0 }; - - RRESFileHeader fileHeader; - RRESInfoHeader infoHeader; - - FILE *rresFile = fopen(fileName, "rb"); - - if (rresFile == NULL) TraceLog(LOG_WARNING, "[%s] rRES raylib resource file could not be opened", fileName); - else - { - // Read rres file info header - fread(&fileHeader.id[0], sizeof(char), 1, rresFile); - fread(&fileHeader.id[1], sizeof(char), 1, rresFile); - fread(&fileHeader.id[2], sizeof(char), 1, rresFile); - fread(&fileHeader.id[3], sizeof(char), 1, rresFile); - fread(&fileHeader.version, sizeof(short), 1, rresFile); - fread(&fileHeader.count, sizeof(short), 1, rresFile); - - // Verify "rRES" identifier - if ((fileHeader.id[0] != 'r') && (fileHeader.id[1] != 'R') && (fileHeader.id[2] != 'E') && (fileHeader.id[3] != 'S')) - { - TraceLog(LOG_WARNING, "[%s] This is not a valid raylib resource file", fileName); - } - else - { - for (int i = 0; i < fileHeader.count; i++) - { - // Read resource info and parameters - fread(&infoHeader, sizeof(RRESInfoHeader), 1, rresFile); - - if (infoHeader.id == rresId) - { - rres = (RRES)malloc(sizeof(RRESData)*infoHeader.partsCount); - - // Load all required resources parts - for (int k = 0; k < infoHeader.partsCount; k++) - { - // TODO: Verify again that rresId is the same in every part - - // Register data type and parameters - rres[k].type = infoHeader.dataType; - rres[k].param1 = infoHeader.param1; - rres[k].param2 = infoHeader.param2; - rres[k].param3 = infoHeader.param3; - rres[k].param4 = infoHeader.param4; - - // Read resource data block - void *data = RRES_MALLOC(infoHeader.dataSize); - fread(data, infoHeader.dataSize, 1, rresFile); - - if (infoHeader.compType == RRES_COMP_DEFLATE) - { - void *uncompData = DecompressData(data, infoHeader.dataSize, infoHeader.uncompSize); - - rres[k].data = uncompData; - - RRES_FREE(data); - } - else rres[k].data = data; - - if (rres[k].data != NULL) TraceLog(LOG_INFO, "[%s][ID %i] Resource data loaded successfully", fileName, (int)infoHeader.id); - - // Read next part - fread(&infoHeader, sizeof(RRESInfoHeader), 1, rresFile); - } - } - else - { - // Skip required data to read next resource infoHeader - fseek(rresFile, infoHeader.dataSize, SEEK_CUR); - } - } - - if (rres[0].data == NULL) TraceLog(LOG_WARNING, "[%s][ID %i] Requested resource could not be found", fileName, (int)rresId); - } - - fclose(rresFile); - } - - return rres; -} - -// Unload resource data -RRESDEF void UnloadResource(RRES rres) -{ - // TODO: When you load resource... how many parts conform it? depends on type? --> Not clear... - - if (rres[0].data != NULL) free(rres[0].data); -} - -//---------------------------------------------------------------------------------- -// Module specific Functions Definition -//---------------------------------------------------------------------------------- - -// Data decompression function -// NOTE: Allocated data MUST be freed by user -static void *DecompressData(const unsigned char *data, unsigned long compSize, int uncompSize) -{ - int tempUncompSize; - void *uncompData; - - // Allocate buffer to hold decompressed data - uncompData = (mz_uint8 *)RRES_MALLOC((size_t)uncompSize); - - // Check correct memory allocation - if (uncompData == NULL) - { - TraceLog(LOG_WARNING, "Out of memory while decompressing data"); - } - else - { - // Decompress data - tempUncompSize = tinfl_decompress_mem_to_mem(uncompData, (size_t)uncompSize, data, compSize, 1); - - if (tempUncompSize == -1) - { - TraceLog(LOG_WARNING, "Data decompression failed"); - RRES_FREE(uncompData); - } - - if (uncompSize != (int)tempUncompSize) - { - TraceLog(LOG_WARNING, "Expected uncompressed size do not match, data may be corrupted"); - TraceLog(LOG_WARNING, " -- Expected uncompressed size: %i", uncompSize); - TraceLog(LOG_WARNING, " -- Returned uncompressed size: %i", tempUncompSize); - } - - TraceLog(LOG_INFO, "Data decompressed successfully from %u bytes to %u bytes", (mz_uint32)compSize, (mz_uint32)tempUncompSize); - } - - return uncompData; -} - -// Some required functions for rres standalone module version -#if defined(RRES_STANDALONE) -// Show trace log messages (LOG_INFO, LOG_WARNING, LOG_ERROR, LOG_DEBUG) -void TraceLog(int logType, const char *text, ...) -{ - va_list args; - va_start(args, text); - - switch (msgType) - { - case LOG_INFO: fprintf(stdout, "INFO: "); break; - case LOG_ERROR: fprintf(stdout, "ERROR: "); break; - case LOG_WARNING: fprintf(stdout, "WARNING: "); break; - case LOG_DEBUG: fprintf(stdout, "DEBUG: "); break; - default: break; - } - - vfprintf(stdout, text, args); - fprintf(stdout, "\n"); - - va_end(args); - - if (msgType == LOG_ERROR) exit(1); -} -#endif - -#endif // RRES_IMPLEMENTATION diff --git a/game/src/libs/raylib/shader_distortion.h b/game/src/libs/raylib/shader_distortion.h deleted file mode 100644 index 7a2c994..0000000 --- a/game/src/libs/raylib/shader_distortion.h +++ /dev/null @@ -1,106 +0,0 @@ - -// Vertex shader definition to embed, no external file required -static const char vDistortionShaderStr[] = -#if defined(GRAPHICS_API_OPENGL_21) -"#version 120 \n" -#elif defined(GRAPHICS_API_OPENGL_ES2) -"#version 100 \n" -#endif -#if defined(GRAPHICS_API_OPENGL_ES2) || defined(GRAPHICS_API_OPENGL_21) -"attribute vec3 vertexPosition; \n" -"attribute vec2 vertexTexCoord; \n" -"attribute vec4 vertexColor; \n" -"varying vec2 fragTexCoord; \n" -"varying vec4 fragColor; \n" -#elif defined(GRAPHICS_API_OPENGL_33) -"#version 330 \n" -"in vec3 vertexPosition; \n" -"in vec2 vertexTexCoord; \n" -"in vec4 vertexColor; \n" -"out vec2 fragTexCoord; \n" -"out vec4 fragColor; \n" -#endif -"uniform mat4 mvp; \n" -"void main() \n" -"{ \n" -" fragTexCoord = vertexTexCoord; \n" -" fragColor = vertexColor; \n" -" gl_Position = mvp*vec4(vertexPosition, 1.0); \n" -"} \n"; - -// Fragment shader definition to embed, no external file required -static const char fDistortionShaderStr[] = -#if defined(GRAPHICS_API_OPENGL_21) -"#version 120 \n" -#elif defined(GRAPHICS_API_OPENGL_ES2) -"#version 100 \n" -"precision mediump float; \n" // precision required for OpenGL ES2 (WebGL) -#endif -#if defined(GRAPHICS_API_OPENGL_ES2) || defined(GRAPHICS_API_OPENGL_21) -"varying vec2 fragTexCoord; \n" -"varying vec4 fragColor; \n" -#elif defined(GRAPHICS_API_OPENGL_33) -"#version 330 \n" -"in vec2 fragTexCoord; \n" -"in vec4 fragColor; \n" -"out vec4 finalColor; \n" -#endif -"uniform sampler2D texture0; \n" -#if defined(GRAPHICS_API_OPENGL_ES2) || defined(GRAPHICS_API_OPENGL_21) -"uniform vec2 leftLensCenter; \n" -"uniform vec2 rightLensCenter; \n" -"uniform vec2 leftScreenCenter; \n" -"uniform vec2 rightScreenCenter; \n" -"uniform vec2 scale; \n" -"uniform vec2 scaleIn; \n" -"uniform vec4 hmdWarpParam; \n" -"uniform vec4 chromaAbParam; \n" -#elif defined(GRAPHICS_API_OPENGL_33) -"uniform vec2 leftLensCenter = vec2(0.288, 0.5); \n" -"uniform vec2 rightLensCenter = vec2(0.712, 0.5); \n" -"uniform vec2 leftScreenCenter = vec2(0.25, 0.5); \n" -"uniform vec2 rightScreenCenter = vec2(0.75, 0.5); \n" -"uniform vec2 scale = vec2(0.25, 0.45); \n" -"uniform vec2 scaleIn = vec2(4, 2.2222); \n" -"uniform vec4 hmdWarpParam = vec4(1, 0.22, 0.24, 0); \n" -"uniform vec4 chromaAbParam = vec4(0.996, -0.004, 1.014, 0.0); \n" -#endif -"void main() \n" -"{ \n" -" vec2 lensCenter = fragTexCoord.x < 0.5 ? leftLensCenter : rightLensCenter; \n" -" vec2 screenCenter = fragTexCoord.x < 0.5 ? leftScreenCenter : rightScreenCenter; \n" -" vec2 theta = (fragTexCoord - lensCenter)*scaleIn; \n" -" float rSq = theta.x*theta.x + theta.y*theta.y; \n" -" vec2 theta1 = theta*(hmdWarpParam.x + hmdWarpParam.y*rSq + hmdWarpParam.z*rSq*rSq + hmdWarpParam.w*rSq*rSq*rSq); \n" -" vec2 thetaBlue = theta1*(chromaAbParam.z + chromaAbParam.w*rSq); \n" -" vec2 tcBlue = lensCenter + scale*thetaBlue; \n" -" if (any(bvec2(clamp(tcBlue, screenCenter - vec2(0.25, 0.5), screenCenter + vec2(0.25, 0.5)) - tcBlue))) \n" -" { \n" -#if defined(GRAPHICS_API_OPENGL_ES2) || defined(GRAPHICS_API_OPENGL_21) -" gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0); \n" -#elif defined(GRAPHICS_API_OPENGL_33) -" finalColor = vec4(0.0, 0.0, 0.0, 1.0); \n" -#endif -" } \n" -" else \n" -" { \n" -#if defined(GRAPHICS_API_OPENGL_ES2) || defined(GRAPHICS_API_OPENGL_21) -" float blue = texture2D(texture0, tcBlue).b; \n" -" vec2 tcGreen = lensCenter + scale*theta1; \n" -" float green = texture2D(texture0, tcGreen).g; \n" -#elif defined(GRAPHICS_API_OPENGL_33) -" float blue = texture(texture0, tcBlue).b; \n" -" vec2 tcGreen = lensCenter + scale*theta1; \n" -" float green = texture(texture0, tcGreen).g; \n" -#endif -" vec2 thetaRed = theta1*(chromaAbParam.x + chromaAbParam.y*rSq); \n" -" vec2 tcRed = lensCenter + scale*thetaRed; \n" -#if defined(GRAPHICS_API_OPENGL_ES2) || defined(GRAPHICS_API_OPENGL_21) -" float red = texture2D(texture0, tcRed).r; \n" -" gl_FragColor = vec4(red, green, blue, 1.0); \n" -#elif defined(GRAPHICS_API_OPENGL_33) -" float red = texture(texture0, tcRed).r; \n" -" finalColor = vec4(red, green, blue, 1.0); \n" -#endif -" } \n" -"} \n"; diff --git a/game/src/libs/raylib/shapes.c b/game/src/libs/raylib/shapes.c deleted file mode 100644 index 0b34f92..0000000 --- a/game/src/libs/raylib/shapes.c +++ /dev/null @@ -1,689 +0,0 @@ -/********************************************************************************************** -* -* raylib.shapes - Basic functions to draw 2d Shapes and check collisions -* -* CONFIGURATION: -* -* #define SUPPORT_QUADS_ONLY -* Draw shapes using only QUADS, vertex are accumulated in QUADS arrays (like textures) -* -* #define SUPPORT_TRIANGLES_ONLY -* Draw shapes using only TRIANGLES, vertex are accumulated in TRIANGLES arrays -* -* -* LICENSE: zlib/libpng -* -* Copyright (c) 2014-2017 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. -* -* Permission is granted to anyone to use this software for any purpose, including commercial -* applications, and to alter it and redistribute it freely, subject to the following restrictions: -* -* 1. The origin of this software must not be misrepresented; you must not claim that you -* wrote the original software. If you use this software in a product, an acknowledgment -* in the product documentation would be appreciated but is not required. -* -* 2. Altered source versions must be plainly marked as such, and must not be misrepresented -* as being the original software. -* -* 3. This notice may not be removed or altered from any source distribution. -* -**********************************************************************************************/ - -#include "raylib.h" - -#include "rlgl.h" // raylib OpenGL abstraction layer to OpenGL 1.1, 2.1, 3.3+ or ES2 - -#include // Required for: abs() -#include // Required for: sinf(), cosf(), sqrtf() - -//---------------------------------------------------------------------------------- -// Defines and Macros -//---------------------------------------------------------------------------------- -// Nop... - -//---------------------------------------------------------------------------------- -// Types and Structures Definition -//---------------------------------------------------------------------------------- -// Not here... - -//---------------------------------------------------------------------------------- -// Global Variables Definition -//---------------------------------------------------------------------------------- -// ... - -//---------------------------------------------------------------------------------- -// Module specific Functions Declaration -//---------------------------------------------------------------------------------- -static float EaseCubicInOut(float t, float b, float c, float d); // Cubic easing - -//---------------------------------------------------------------------------------- -// Module Functions Definition -//---------------------------------------------------------------------------------- - -// Draw a pixel -void DrawPixel(int posX, int posY, Color color) -{ - rlBegin(RL_LINES); - rlColor4ub(color.r, color.g, color.b, color.a); - rlVertex2i(posX, posY); - rlVertex2i(posX + 1, posY + 1); - rlEnd(); -} - -// Draw a pixel (Vector version) -void DrawPixelV(Vector2 position, Color color) -{ - rlBegin(RL_LINES); - rlColor4ub(color.r, color.g, color.b, color.a); - rlVertex2f(position.x, position.y); - rlVertex2f(position.x + 1.0f, position.y + 1.0f); - rlEnd(); -} - -// Draw a line -void DrawLine(int startPosX, int startPosY, int endPosX, int endPosY, Color color) -{ - rlBegin(RL_LINES); - rlColor4ub(color.r, color.g, color.b, color.a); - rlVertex2i(startPosX, startPosY); - rlVertex2i(endPosX, endPosY); - rlEnd(); -} - -// Draw a line (Vector version) -void DrawLineV(Vector2 startPos, Vector2 endPos, Color color) -{ - rlBegin(RL_LINES); - rlColor4ub(color.r, color.g, color.b, color.a); - rlVertex2f(startPos.x, startPos.y); - rlVertex2f(endPos.x, endPos.y); - rlEnd(); -} - -// Draw a line defining thickness -void DrawLineEx(Vector2 startPos, Vector2 endPos, float thick, Color color) -{ - if (startPos.x > endPos.x) - { - Vector2 tempPos = startPos; - startPos = endPos; - endPos = tempPos; - } - - float dx = endPos.x - startPos.x; - float dy = endPos.y - startPos.y; - - float d = sqrtf(dx*dx + dy*dy); - float angle = asinf(dy/d); - - rlEnableTexture(GetTextureDefault().id); - - rlPushMatrix(); - rlTranslatef((float)startPos.x, (float)startPos.y, 0); - rlRotatef(RAD2DEG*angle, 0, 0, 1); - rlTranslatef(0, -thick/2.0f, 0); - - rlBegin(RL_QUADS); - rlColor4ub(color.r, color.g, color.b, color.a); - rlNormal3f(0.0f, 0.0f, 1.0f); - - rlVertex2f(0.0f, 0.0f); - rlVertex2f(0.0f, thick); - rlVertex2f(d, thick); - rlVertex2f(d, 0.0f); - rlEnd(); - rlPopMatrix(); - - rlDisableTexture(); -} - -// Draw line using cubic-bezier curves in-out -void DrawLineBezier(Vector2 startPos, Vector2 endPos, float thick, Color color) -{ - #define LINE_DIVISIONS 24 // Bezier line divisions - - Vector2 previous = startPos; - Vector2 current; - - for (int i = 1; i <= LINE_DIVISIONS; i++) - { - // Cubic easing in-out - // NOTE: Easing is calcutated only for y position value - current.y = EaseCubicInOut(i, startPos.y, endPos.y - startPos.y, LINE_DIVISIONS); - current.x = previous.x + (endPos.x - startPos.x)/LINE_DIVISIONS; - - DrawLineEx(previous, current, thick, color); - - previous = current; - } -} - -// Draw a color-filled circle -void DrawCircle(int centerX, int centerY, float radius, Color color) -{ - DrawCircleV((Vector2){ (float)centerX, (float)centerY }, radius, color); -} - -// Draw a gradient-filled circle -// NOTE: Gradient goes from center (color1) to border (color2) -void DrawCircleGradient(int centerX, int centerY, float radius, Color color1, Color color2) -{ - rlBegin(RL_TRIANGLES); - for (int i = 0; i < 360; i += 10) - { - rlColor4ub(color1.r, color1.g, color1.b, color1.a); - rlVertex2i(centerX, centerY); - rlColor4ub(color2.r, color2.g, color2.b, color2.a); - rlVertex2f(centerX + sinf(DEG2RAD*i)*radius, centerY + cosf(DEG2RAD*i)*radius); - rlColor4ub(color2.r, color2.g, color2.b, color2.a); - rlVertex2f(centerX + sinf(DEG2RAD*(i + 10))*radius, centerY + cosf(DEG2RAD*(i + 10))*radius); - } - rlEnd(); -} - -// Draw a color-filled circle (Vector version) -// NOTE: On OpenGL 3.3 and ES2 we use QUADS to avoid drawing order issues (view rlglDraw) -void DrawCircleV(Vector2 center, float radius, Color color) -{ - if (rlGetVersion() == OPENGL_11) - { - rlBegin(RL_TRIANGLES); - for (int i = 0; i < 360; i += 10) - { - rlColor4ub(color.r, color.g, color.b, color.a); - - rlVertex2f(center.x, center.y); - rlVertex2f(center.x + sinf(DEG2RAD*i)*radius, center.y + cosf(DEG2RAD*i)*radius); - rlVertex2f(center.x + sinf(DEG2RAD*(i + 10))*radius, center.y + cosf(DEG2RAD*(i + 10))*radius); - } - rlEnd(); - } - else if ((rlGetVersion() == OPENGL_21) || (rlGetVersion() == OPENGL_33) || (rlGetVersion() == OPENGL_ES_20)) - { - rlEnableTexture(GetTextureDefault().id); // Default white texture - - rlBegin(RL_QUADS); - for (int i = 0; i < 360; i += 20) - { - rlColor4ub(color.r, color.g, color.b, color.a); - - rlVertex2f(center.x, center.y); - rlVertex2f(center.x + sinf(DEG2RAD*i)*radius, center.y + cosf(DEG2RAD*i)*radius); - rlVertex2f(center.x + sinf(DEG2RAD*(i + 10))*radius, center.y + cosf(DEG2RAD*(i + 10))*radius); - rlVertex2f(center.x + sinf(DEG2RAD*(i + 20))*radius, center.y + cosf(DEG2RAD*(i + 20))*radius); - } - rlEnd(); - - rlDisableTexture(); - } -} - -// Draw circle outline -void DrawCircleLines(int centerX, int centerY, float radius, Color color) -{ - rlBegin(RL_LINES); - rlColor4ub(color.r, color.g, color.b, color.a); - - // NOTE: Circle outline is drawn pixel by pixel every degree (0 to 360) - for (int i = 0; i < 360; i += 10) - { - rlVertex2f(centerX + sinf(DEG2RAD*i)*radius, centerY + cosf(DEG2RAD*i)*radius); - rlVertex2f(centerX + sinf(DEG2RAD*(i + 10))*radius, centerY + cosf(DEG2RAD*(i + 10))*radius); - } - rlEnd(); -} - -// Draw a color-filled rectangle -void DrawRectangle(int posX, int posY, int width, int height, Color color) -{ - Vector2 position = { (float)posX, (float)posY }; - Vector2 size = { (float)width, (float)height }; - - DrawRectangleV(position, size, color); -} - -// Draw a color-filled rectangle -void DrawRectangleRec(Rectangle rec, Color color) -{ - DrawRectangle(rec.x, rec.y, rec.width, rec.height, color); -} - -void DrawRectanglePro(Rectangle rec, Vector2 origin, float rotation, Color color) -{ - rlEnableTexture(GetTextureDefault().id); - - rlPushMatrix(); - rlTranslatef((float)rec.x, (float)rec.y, 0); - rlRotatef(rotation, 0, 0, 1); - rlTranslatef(-origin.x, -origin.y, 0); - - rlBegin(RL_QUADS); - rlColor4ub(color.r, color.g, color.b, color.a); - rlNormal3f(0.0f, 0.0f, 1.0f); // Normal vector pointing towards viewer - - rlVertex2f(0.0f, 0.0f); - rlVertex2f(0.0f, (float)rec.height); - rlVertex2f((float)rec.width, (float)rec.height); - rlVertex2f((float)rec.width, 0.0f); - rlEnd(); - rlPopMatrix(); - - rlDisableTexture(); -} - -// Draw a vertical-gradient-filled rectangle -// NOTE: Gradient goes from bottom (color1) to top (color2) -void DrawRectangleGradientV(int posX, int posY, int width, int height, Color color1, Color color2) -{ - DrawRectangleGradientEx((Rectangle){ posX, posY, width, height }, color1, color2, color2, color1); -} - -// Draw a horizontal-gradient-filled rectangle -// NOTE: Gradient goes from bottom (color1) to top (color2) -void DrawRectangleGradientH(int posX, int posY, int width, int height, Color color1, Color color2) -{ - DrawRectangleGradientEx((Rectangle){ posX, posY, width, height }, color1, color1, color2, color2); -} - -// Draw a gradient-filled rectangle -// NOTE: Colors refer to corners, starting at top-lef corner and counter-clockwise -void DrawRectangleGradientEx(Rectangle rec, Color col1, Color col2, Color col3, Color col4) -{ - rlEnableTexture(GetTextureDefault().id); // Default white texture - - rlBegin(RL_QUADS); - rlNormal3f(0.0f, 0.0f, 1.0f); - - rlColor4ub(col1.r, col1.g, col1.b, col1.a); - rlTexCoord2f(0.0f, 0.0f); - rlVertex2f(rec.x, rec.y); - - rlColor4ub(col2.r, col2.g, col2.b, col2.a); - rlTexCoord2f(0.0f, 1.0f); - rlVertex2f(rec.x, rec.y + rec.height); - - rlColor4ub(col3.r, col3.g, col3.b, col3.a); - rlTexCoord2f(1.0f, 1.0f); - rlVertex2f(rec.x + rec.width, rec.y + rec.height); - - rlColor4ub(col4.r, col4.g, col4.b, col4.a); - rlTexCoord2f(1.0f, 0.0f); - rlVertex2f(rec.x + rec.width, rec.y); - rlEnd(); - - // Draw rectangle using font texture white character - /* - rlTexCoord2f((float)GetDefaultFont().chars[95].rec.x/GetDefaultFont().texture.width, - (float)GetDefaultFont().chars[95].rec.y/GetDefaultFont().texture.height); - rlVertex2f(rec.x, rec.y); - - rlTexCoord2f((float)GetDefaultFont().chars[95].rec.x/GetDefaultFont().texture.width, - (float)(GetDefaultFont().chars[95].rec.y + GetDefaultFont().chars[95].rec.height)/GetDefaultFont().texture.height); - rlVertex2f(rec.x, rec.y + rec.height); - - rlTexCoord2f((float)(GetDefaultFont().chars[95].rec.x + GetDefaultFont().chars[95].rec.width)/GetDefaultFont().texture.width, - (float)(GetDefaultFont().chars[95].rec.y + GetDefaultFont().chars[95].rec.height)/GetDefaultFont().texture.height); - rlVertex2f(rec.x + rec.width, rec.y + rec.height); - - rlTexCoord2f((float)(GetDefaultFont().chars[95].rec.x + GetDefaultFont().chars[95].rec.width)/GetDefaultFont().texture.width, - (float)GetDefaultFont().chars[95].rec.y/GetDefaultFont().texture.height); - rlVertex2f(rec.x + rec.width, rec.y); - */ - - rlDisableTexture(); -} - -// Draw a color-filled rectangle (Vector version) -// NOTE: On OpenGL 3.3 and ES2 we use QUADS to avoid drawing order issues (view rlglDraw) -void DrawRectangleV(Vector2 position, Vector2 size, Color color) -{ - if (rlGetVersion() == OPENGL_11) - { - rlBegin(RL_TRIANGLES); - rlColor4ub(color.r, color.g, color.b, color.a); - - rlVertex2i(position.x, position.y); - rlVertex2i(position.x, position.y + size.y); - rlVertex2i(position.x + size.x, position.y + size.y); - - rlVertex2i(position.x, position.y); - rlVertex2i(position.x + size.x, position.y + size.y); - rlVertex2i(position.x + size.x, position.y); - rlEnd(); - } - else if ((rlGetVersion() == OPENGL_21) || (rlGetVersion() == OPENGL_33) || (rlGetVersion() == OPENGL_ES_20)) - { - rlEnableTexture(GetTextureDefault().id); // Default white texture - - rlBegin(RL_QUADS); - rlColor4ub(color.r, color.g, color.b, color.a); - rlNormal3f(0.0f, 0.0f, 1.0f); - - rlTexCoord2f(0.0f, 0.0f); - rlVertex2f(position.x, position.y); - - rlTexCoord2f(0.0f, 1.0f); - rlVertex2f(position.x, position.y + size.y); - - rlTexCoord2f(1.0f, 1.0f); - rlVertex2f(position.x + size.x, position.y + size.y); - - rlTexCoord2f(1.0f, 0.0f); - rlVertex2f(position.x + size.x, position.y); - rlEnd(); - - rlDisableTexture(); - } -} - -// Draw rectangle outline -// NOTE: On OpenGL 3.3 and ES2 we use QUADS to avoid drawing order issues (view rlglDraw) -void DrawRectangleLines(int posX, int posY, int width, int height, Color color) -{ - if (rlGetVersion() == OPENGL_11) - { - rlBegin(RL_LINES); - rlColor4ub(color.r, color.g, color.b, color.a); - rlVertex2i(posX + 1, posY + 1); - rlVertex2i(posX + width, posY + 1); - - rlVertex2i(posX + width, posY + 1); - rlVertex2i(posX + width, posY + height); - - rlVertex2i(posX + width, posY + height); - rlVertex2i(posX + 1, posY + height); - - rlVertex2i(posX + 1, posY + height); - rlVertex2i(posX + 1, posY + 1); - rlEnd(); - } - else if ((rlGetVersion() == OPENGL_21) || (rlGetVersion() == OPENGL_33) || (rlGetVersion() == OPENGL_ES_20)) - { - DrawRectangle(posX, posY, width, 1, color); - DrawRectangle(posX + width - 1, posY + 1, 1, height - 2, color); - DrawRectangle(posX, posY + height - 1, width, 1, color); - DrawRectangle(posX, posY + 1, 1, height - 2, color); - } -} - -// Draw rectangle using text character (char: 127) -// NOTE: Useful to avoid changing to default white texture -void DrawRectangleT(int posX, int posY, int width, int height, Color color) -{ - DrawTexturePro(GetDefaultFont().texture, GetDefaultFont().chars[95].rec, - (Rectangle){ posX, posY, width, height }, (Vector2){ 0, 0 }, 0.0f, color); -} - -// Draw a triangle -void DrawTriangle(Vector2 v1, Vector2 v2, Vector2 v3, Color color) -{ - if (rlGetVersion() == OPENGL_11) - { - rlBegin(RL_TRIANGLES); - rlColor4ub(color.r, color.g, color.b, color.a); - rlVertex2f(v1.x, v1.y); - rlVertex2f(v2.x, v2.y); - rlVertex2f(v3.x, v3.y); - rlEnd(); - } - else if ((rlGetVersion() == OPENGL_21) || (rlGetVersion() == OPENGL_33) || (rlGetVersion() == OPENGL_ES_20)) - { - rlEnableTexture(GetTextureDefault().id); // Default white texture - - rlBegin(RL_QUADS); - rlColor4ub(color.r, color.g, color.b, color.a); - rlVertex2f(v1.x, v1.y); - rlVertex2f(v2.x, v2.y); - rlVertex2f(v2.x, v2.y); - rlVertex2f(v3.x, v3.y); - rlEnd(); - - rlDisableTexture(); - } -} - -void DrawTriangleLines(Vector2 v1, Vector2 v2, Vector2 v3, Color color) -{ - rlBegin(RL_LINES); - rlColor4ub(color.r, color.g, color.b, color.a); - rlVertex2f(v1.x, v1.y); - rlVertex2f(v2.x, v2.y); - - rlVertex2f(v2.x, v2.y); - rlVertex2f(v3.x, v3.y); - - rlVertex2f(v3.x, v3.y); - rlVertex2f(v1.x, v1.y); - rlEnd(); -} - -// Draw a regular polygon of n sides (Vector version) -void DrawPoly(Vector2 center, int sides, float radius, float rotation, Color color) -{ - if (sides < 3) sides = 3; - - rlPushMatrix(); - rlTranslatef(center.x, center.y, 0.0); - rlRotatef(rotation, 0, 0, 1); - - rlBegin(RL_TRIANGLES); - for (int i = 0; i < 360; i += 360/sides) - { - rlColor4ub(color.r, color.g, color.b, color.a); - - rlVertex2f(0, 0); - rlVertex2f(sinf(DEG2RAD*i)*radius, cosf(DEG2RAD*i)*radius); - rlVertex2f(sinf(DEG2RAD*(i + 360/sides))*radius, cosf(DEG2RAD*(i + 360/sides))*radius); - } - rlEnd(); - rlPopMatrix(); -} - -// Draw a closed polygon defined by points -// NOTE: Array num elements MUST be passed as parameter to function -void DrawPolyEx(Vector2 *points, int numPoints, Color color) -{ - if (numPoints >= 3) - { - rlBegin(RL_TRIANGLES); - rlColor4ub(color.r, color.g, color.b, color.a); - - for (int i = 1; i < numPoints - 1; i++) - { - rlVertex2f(points[0].x, points[0].y); - rlVertex2f(points[i].x, points[i].y); - rlVertex2f(points[i + 1].x, points[i + 1].y); - } - rlEnd(); - } -} - -// Draw polygon lines -// NOTE: Array num elements MUST be passed as parameter to function -void DrawPolyExLines(Vector2 *points, int numPoints, Color color) -{ - if (numPoints >= 2) - { - rlBegin(RL_LINES); - rlColor4ub(color.r, color.g, color.b, color.a); - - for (int i = 0; i < numPoints - 1; i++) - { - rlVertex2f(points[i].x, points[i].y); - rlVertex2f(points[i + 1].x, points[i + 1].y); - } - rlEnd(); - } -} - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Collision Detection functions -//---------------------------------------------------------------------------------- - -// Check if point is inside rectangle -bool CheckCollisionPointRec(Vector2 point, Rectangle rec) -{ - bool collision = false; - - if ((point.x >= rec.x) && (point.x <= (rec.x + rec.width)) && (point.y >= rec.y) && (point.y <= (rec.y + rec.height))) collision = true; - - return collision; -} - -// Check if point is inside circle -bool CheckCollisionPointCircle(Vector2 point, Vector2 center, float radius) -{ - return CheckCollisionCircles(point, 0, center, radius); -} - -// Check if point is inside a triangle defined by three points (p1, p2, p3) -bool CheckCollisionPointTriangle(Vector2 point, Vector2 p1, Vector2 p2, Vector2 p3) -{ - bool collision = false; - - float alpha = ((p2.y - p3.y)*(point.x - p3.x) + (p3.x - p2.x)*(point.y - p3.y)) / - ((p2.y - p3.y)*(p1.x - p3.x) + (p3.x - p2.x)*(p1.y - p3.y)); - - float beta = ((p3.y - p1.y)*(point.x - p3.x) + (p1.x - p3.x)*(point.y - p3.y)) / - ((p2.y - p3.y)*(p1.x - p3.x) + (p3.x - p2.x)*(p1.y - p3.y)); - - float gamma = 1.0f - alpha - beta; - - if ((alpha > 0) && (beta > 0) & (gamma > 0)) collision = true; - - return collision; -} - -// Check collision between two rectangles -bool CheckCollisionRecs(Rectangle rec1, Rectangle rec2) -{ - bool collision = false; - - int dx = abs((rec1.x + rec1.width/2) - (rec2.x + rec2.width/2)); - int dy = abs((rec1.y + rec1.height/2) - (rec2.y + rec2.height/2)); - - if ((dx <= (rec1.width/2 + rec2.width/2)) && ((dy <= (rec1.height/2 + rec2.height/2)))) collision = true; - - return collision; -} - -// Check collision between two circles -bool CheckCollisionCircles(Vector2 center1, float radius1, Vector2 center2, float radius2) -{ - bool collision = false; - - float dx = center2.x - center1.x; // X distance between centers - float dy = center2.y - center1.y; // Y distance between centers - - float distance = sqrtf(dx*dx + dy*dy); // Distance between centers - - if (distance <= (radius1 + radius2)) collision = true; - - return collision; -} - -// Check collision between circle and rectangle -// NOTE: Reviewed version to take into account corner limit case -bool CheckCollisionCircleRec(Vector2 center, float radius, Rectangle rec) -{ - int recCenterX = rec.x + rec.width/2; - int recCenterY = rec.y + rec.height/2; - - float dx = fabsf(center.x - recCenterX); - float dy = fabsf(center.y - recCenterY); - - if (dx > ((float)rec.width/2.0f + radius)) { return false; } - if (dy > ((float)rec.height/2.0f + radius)) { return false; } - - if (dx <= ((float)rec.width/2.0f)) { return true; } - if (dy <= ((float)rec.height/2.0f)) { return true; } - - float cornerDistanceSq = (dx - (float)rec.width/2.0f)*(dx - (float)rec.width/2.0f) + - (dy - (float)rec.height/2.0f)*(dy - (float)rec.height/2.0f); - - return (cornerDistanceSq <= (radius*radius)); -} - -// Get collision rectangle for two rectangles collision -Rectangle GetCollisionRec(Rectangle rec1, Rectangle rec2) -{ - Rectangle retRec = { 0, 0, 0, 0 }; - - if (CheckCollisionRecs(rec1, rec2)) - { - int dxx = abs(rec1.x - rec2.x); - int dyy = abs(rec1.y - rec2.y); - - if (rec1.x <= rec2.x) - { - if (rec1.y <= rec2.y) - { - retRec.x = rec2.x; - retRec.y = rec2.y; - retRec.width = rec1.width - dxx; - retRec.height = rec1.height - dyy; - } - else - { - retRec.x = rec2.x; - retRec.y = rec1.y; - retRec.width = rec1.width - dxx; - retRec.height = rec2.height - dyy; - } - } - else - { - if (rec1.y <= rec2.y) - { - retRec.x = rec1.x; - retRec.y = rec2.y; - retRec.width = rec2.width - dxx; - retRec.height = rec1.height - dyy; - } - else - { - retRec.x = rec1.x; - retRec.y = rec1.y; - retRec.width = rec2.width - dxx; - retRec.height = rec2.height - dyy; - } - } - - if (rec1.width > rec2.width) - { - if (retRec.width >= rec2.width) retRec.width = rec2.width; - } - else - { - if (retRec.width >= rec1.width) retRec.width = rec1.width; - } - - if (rec1.height > rec2.height) - { - if (retRec.height >= rec2.height) retRec.height = rec2.height; - } - else - { - if (retRec.height >= rec1.height) retRec.height = rec1.height; - } - } - - return retRec; -} - -//---------------------------------------------------------------------------------- -// Module specific Functions Definition -//---------------------------------------------------------------------------------- - -// Cubic easing in-out -// NOTE: Required for DrawLineBezier() -static float EaseCubicInOut(float t, float b, float c, float d) -{ - if ((t /= 0.5*d) < 1) - return 0.5*c*t*t*t + b; - t -= 2; - return 0.5*c*(t*t*t + 2) + b; -} diff --git a/game/src/libs/raylib/text.c b/game/src/libs/raylib/text.c deleted file mode 100644 index 465e454..0000000 --- a/game/src/libs/raylib/text.c +++ /dev/null @@ -1,935 +0,0 @@ -/********************************************************************************************** -* -* raylib.text - Basic functions to load SpriteFonts and draw Text -* -* CONFIGURATION: -* -* #define SUPPORT_FILEFORMAT_FNT -* #define SUPPORT_FILEFORMAT_TTF -* Selected desired fileformats to be supported for loading. Some of those formats are -* supported by default, to remove support, just comment unrequired #define in this module -* -* #define SUPPORT_DEFAULT_FONT -* -* DEPENDENCIES: -* stb_truetype - Load TTF file and rasterize characters data -* -* -* LICENSE: zlib/libpng -* -* Copyright (c) 2014-2017 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. -* -* Permission is granted to anyone to use this software for any purpose, including commercial -* applications, and to alter it and redistribute it freely, subject to the following restrictions: -* -* 1. The origin of this software must not be misrepresented; you must not claim that you -* wrote the original software. If you use this software in a product, an acknowledgment -* in the product documentation would be appreciated but is not required. -* -* 2. Altered source versions must be plainly marked as such, and must not be misrepresented -* as being the original software. -* -* 3. This notice may not be removed or altered from any source distribution. -* -**********************************************************************************************/ - -// Default supported features -//------------------------------------- -#define SUPPORT_DEFAULT_FONT -#define SUPPORT_FILEFORMAT_FNT -#define SUPPORT_FILEFORMAT_TTF -//------------------------------------- - -#include "raylib.h" - -#include // Required for: malloc(), free() -#include // Required for: strlen() -#include // Required for: va_list, va_start(), vfprintf(), va_end() -#include // Required for: FILE, fopen(), fclose(), fscanf(), feof(), rewind(), fgets() - -#include "utils.h" // Required for: fopen() Android mapping - -#if defined(SUPPORT_FILEFORMAT_TTF) - // Following libs are used on LoadTTF() - #define STBTT_STATIC // Define stb_truetype functions static to this module - #define STB_TRUETYPE_IMPLEMENTATION - #include "external/stb_truetype.h" // Required for: stbtt_BakeFontBitmap() -#endif - -// Rectangle packing functions (not used at the moment) -//#define STB_RECT_PACK_IMPLEMENTATION -//#include "stb_rect_pack.h" - -//---------------------------------------------------------------------------------- -// Defines and Macros -//---------------------------------------------------------------------------------- -#define MAX_FORMATTEXT_LENGTH 64 -#define MAX_SUBTEXT_LENGTH 64 - -//---------------------------------------------------------------------------------- -// Types and Structures Definition -//---------------------------------------------------------------------------------- -// ... - -//---------------------------------------------------------------------------------- -// Global variables -//---------------------------------------------------------------------------------- -#if defined(SUPPORT_DEFAULT_FONT) -static SpriteFont defaultFont; // Default font provided by raylib -// NOTE: defaultFont is loaded on InitWindow and disposed on CloseWindow [module: core] -#endif - -//---------------------------------------------------------------------------------- -// Other Modules Functions Declaration (required by text) -//---------------------------------------------------------------------------------- -//... - -//---------------------------------------------------------------------------------- -// Module specific Functions Declaration -//---------------------------------------------------------------------------------- -static int GetCharIndex(SpriteFont font, int letter); - -static SpriteFont LoadImageFont(Image image, Color key, int firstChar); // Load a Image font file (XNA style) -#if defined(SUPPORT_FILEFORMAT_FNT) -static SpriteFont LoadBMFont(const char *fileName); // Load a BMFont file (AngelCode font file) -#endif -#if defined(SUPPORT_FILEFORMAT_TTF) -static SpriteFont LoadTTF(const char *fileName, int fontSize, int charsCount, int *fontChars); // Load spritefont from TTF data -#endif - -#if defined(SUPPORT_DEFAULT_FONT) -extern void LoadDefaultFont(void); -extern void UnloadDefaultFont(void); -#endif - -//---------------------------------------------------------------------------------- -// Module Functions Definition -//---------------------------------------------------------------------------------- -#if defined(SUPPORT_DEFAULT_FONT) - -// Load raylib default font -extern void LoadDefaultFont(void) -{ - #define BIT_CHECK(a,b) ((a) & (1 << (b))) - - // NOTE: Using UTF8 encoding table for Unicode U+0000..U+00FF Basic Latin + Latin-1 Supplement - // http://www.utf8-chartable.de/unicode-utf8-table.pl - - defaultFont.charsCount = 224; // Number of chars included in our default font - - // Default font is directly defined here (data generated from a sprite font image) - // This way, we reconstruct SpriteFont without creating large global variables - // This data is automatically allocated to Stack and automatically deallocated at the end of this function - int defaultFontData[512] = { - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00200020, 0x0001b000, 0x00000000, 0x00000000, 0x8ef92520, 0x00020a00, 0x7dbe8000, 0x1f7df45f, - 0x4a2bf2a0, 0x0852091e, 0x41224000, 0x10041450, 0x2e292020, 0x08220812, 0x41222000, 0x10041450, 0x10f92020, 0x3efa084c, 0x7d22103c, 0x107df7de, - 0xe8a12020, 0x08220832, 0x05220800, 0x10450410, 0xa4a3f000, 0x08520832, 0x05220400, 0x10450410, 0xe2f92020, 0x0002085e, 0x7d3e0281, 0x107df41f, - 0x00200000, 0x8001b000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xc0000fbe, 0xfbf7e00f, 0x5fbf7e7d, 0x0050bee8, 0x440808a2, 0x0a142fe8, 0x50810285, 0x0050a048, - 0x49e428a2, 0x0a142828, 0x40810284, 0x0048a048, 0x10020fbe, 0x09f7ebaf, 0xd89f3e84, 0x0047a04f, 0x09e48822, 0x0a142aa1, 0x50810284, 0x0048a048, - 0x04082822, 0x0a142fa0, 0x50810285, 0x0050a248, 0x00008fbe, 0xfbf42021, 0x5f817e7d, 0x07d09ce8, 0x00008000, 0x00000fe0, 0x00000000, 0x00000000, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x000c0180, - 0xdfbf4282, 0x0bfbf7ef, 0x42850505, 0x004804bf, 0x50a142c6, 0x08401428, 0x42852505, 0x00a808a0, 0x50a146aa, 0x08401428, 0x42852505, 0x00081090, - 0x5fa14a92, 0x0843f7e8, 0x7e792505, 0x00082088, 0x40a15282, 0x08420128, 0x40852489, 0x00084084, 0x40a16282, 0x0842022a, 0x40852451, 0x00088082, - 0xc0bf4282, 0xf843f42f, 0x7e85fc21, 0x3e0900bf, 0x00000000, 0x00000004, 0x00000000, 0x000c0180, 0x00000000, 0x00000000, 0x00000000, 0x00000000, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x04000402, 0x41482000, 0x00000000, 0x00000800, - 0x04000404, 0x4100203c, 0x00000000, 0x00000800, 0xf7df7df0, 0x514bef85, 0xbefbefbe, 0x04513bef, 0x14414500, 0x494a2885, 0xa28a28aa, 0x04510820, - 0xf44145f0, 0x474a289d, 0xa28a28aa, 0x04510be0, 0x14414510, 0x494a2884, 0xa28a28aa, 0x02910a00, 0xf7df7df0, 0xd14a2f85, 0xbefbe8aa, 0x011f7be0, - 0x00000000, 0x00400804, 0x20080000, 0x00000000, 0x00000000, 0x00600f84, 0x20080000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, - 0xac000000, 0x00000f01, 0x00000000, 0x00000000, 0x24000000, 0x00000f01, 0x00000000, 0x06000000, 0x24000000, 0x00000f01, 0x00000000, 0x09108000, - 0x24fa28a2, 0x00000f01, 0x00000000, 0x013e0000, 0x2242252a, 0x00000f52, 0x00000000, 0x038a8000, 0x2422222a, 0x00000f29, 0x00000000, 0x010a8000, - 0x2412252a, 0x00000f01, 0x00000000, 0x010a8000, 0x24fbe8be, 0x00000f01, 0x00000000, 0x0ebe8000, 0xac020000, 0x00000f01, 0x00000000, 0x00048000, - 0x0003e000, 0x00000f00, 0x00000000, 0x00008000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000038, 0x8443b80e, 0x00203a03, - 0x02bea080, 0xf0000020, 0xc452208a, 0x04202b02, 0xf8029122, 0x07f0003b, 0xe44b388e, 0x02203a02, 0x081e8a1c, 0x0411e92a, 0xf4420be0, 0x01248202, - 0xe8140414, 0x05d104ba, 0xe7c3b880, 0x00893a0a, 0x283c0e1c, 0x04500902, 0xc4400080, 0x00448002, 0xe8208422, 0x04500002, 0x80400000, 0x05200002, - 0x083e8e00, 0x04100002, 0x804003e0, 0x07000042, 0xf8008400, 0x07f00003, 0x80400000, 0x04000022, 0x00000000, 0x00000000, 0x80400000, 0x04000002, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00800702, 0x1848a0c2, 0x84010000, 0x02920921, 0x01042642, 0x00005121, 0x42023f7f, 0x00291002, - 0xefc01422, 0x7efdfbf7, 0xefdfa109, 0x03bbbbf7, 0x28440f12, 0x42850a14, 0x20408109, 0x01111010, 0x28440408, 0x42850a14, 0x2040817f, 0x01111010, - 0xefc78204, 0x7efdfbf7, 0xe7cf8109, 0x011111f3, 0x2850a932, 0x42850a14, 0x2040a109, 0x01111010, 0x2850b840, 0x42850a14, 0xefdfbf79, 0x03bbbbf7, - 0x001fa020, 0x00000000, 0x00001000, 0x00000000, 0x00002070, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, - 0x08022800, 0x00012283, 0x02430802, 0x01010001, 0x8404147c, 0x20000144, 0x80048404, 0x00823f08, 0xdfbf4284, 0x7e03f7ef, 0x142850a1, 0x0000210a, - 0x50a14684, 0x528a1428, 0x142850a1, 0x03efa17a, 0x50a14a9e, 0x52521428, 0x142850a1, 0x02081f4a, 0x50a15284, 0x4a221428, 0xf42850a1, 0x03efa14b, - 0x50a16284, 0x4a521428, 0x042850a1, 0x0228a17a, 0xdfbf427c, 0x7e8bf7ef, 0xf7efdfbf, 0x03efbd0b, 0x00000000, 0x04000000, 0x00000000, 0x00000008, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00200508, 0x00840400, 0x11458122, 0x00014210, - 0x00514294, 0x51420800, 0x20a22a94, 0x0050a508, 0x00200000, 0x00000000, 0x00050000, 0x08000000, 0xfefbefbe, 0xfbefbefb, 0xfbeb9114, 0x00fbefbe, - 0x20820820, 0x8a28a20a, 0x8a289114, 0x3e8a28a2, 0xfefbefbe, 0xfbefbe0b, 0x8a289114, 0x008a28a2, 0x228a28a2, 0x08208208, 0x8a289114, 0x088a28a2, - 0xfefbefbe, 0xfbefbefb, 0xfa2f9114, 0x00fbefbe, 0x00000000, 0x00000040, 0x00000000, 0x00000000, 0x00000000, 0x00000020, 0x00000000, 0x00000000, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00210100, 0x00000004, 0x00000000, 0x00000000, 0x14508200, 0x00001402, 0x00000000, 0x00000000, - 0x00000010, 0x00000020, 0x00000000, 0x00000000, 0xa28a28be, 0x00002228, 0x00000000, 0x00000000, 0xa28a28aa, 0x000022e8, 0x00000000, 0x00000000, - 0xa28a28aa, 0x000022a8, 0x00000000, 0x00000000, 0xa28a28aa, 0x000022e8, 0x00000000, 0x00000000, 0xbefbefbe, 0x00003e2f, 0x00000000, 0x00000000, - 0x00000004, 0x00002028, 0x00000000, 0x00000000, 0x80000000, 0x00003e0f, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }; - - int charsHeight = 10; - int charsDivisor = 1; // Every char is separated from the consecutive by a 1 pixel divisor, horizontally and vertically - - int charsWidth[224] = { 3, 1, 4, 6, 5, 7, 6, 2, 3, 3, 5, 5, 2, 4, 1, 7, 5, 2, 5, 5, 5, 5, 5, 5, 5, 5, 1, 1, 3, 4, 3, 6, - 7, 6, 6, 6, 6, 6, 6, 6, 6, 3, 5, 6, 5, 7, 6, 6, 6, 6, 6, 6, 7, 6, 7, 7, 6, 6, 6, 2, 7, 2, 3, 5, - 2, 5, 5, 5, 5, 5, 4, 5, 5, 1, 2, 5, 2, 5, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 3, 1, 3, 4, 4, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 5, 5, 5, 7, 1, 5, 3, 7, 3, 5, 4, 1, 7, 4, 3, 5, 3, 3, 2, 5, 6, 1, 2, 2, 3, 5, 6, 6, 6, 6, - 6, 6, 6, 6, 6, 6, 7, 6, 6, 6, 6, 6, 3, 3, 3, 3, 7, 6, 6, 6, 6, 6, 6, 5, 6, 6, 6, 6, 6, 6, 4, 6, - 5, 5, 5, 5, 5, 5, 9, 5, 5, 5, 5, 5, 2, 2, 3, 3, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 3, 5 }; - - // Re-construct image from defaultFontData and generate OpenGL texture - //---------------------------------------------------------------------- - int imWidth = 128; - int imHeight = 128; - - Color *imagePixels = (Color *)malloc(imWidth*imHeight*sizeof(Color)); - - for (int i = 0; i < imWidth*imHeight; i++) imagePixels[i] = BLANK; // Initialize array - - int counter = 0; // Font data elements counter - - // Fill imgData with defaultFontData (convert from bit to pixel!) - for (int i = 0; i < imWidth*imHeight; i += 32) - { - for (int j = 31; j >= 0; j--) - { - if (BIT_CHECK(defaultFontData[counter], j)) imagePixels[i+j] = WHITE; - } - - counter++; - - if (counter > 512) counter = 0; // Security check... - } - - //FILE *myimage = fopen("default_font.raw", "wb"); - //fwrite(image.pixels, 1, 128*128*4, myimage); - //fclose(myimage); - - Image image = LoadImageEx(imagePixels, imWidth, imHeight); - ImageFormat(&image, UNCOMPRESSED_GRAY_ALPHA); - - free(imagePixels); - - defaultFont.texture = LoadTextureFromImage(image); - UnloadImage(image); - - // Reconstruct charSet using charsWidth[], charsHeight, charsDivisor, charsCount - //------------------------------------------------------------------------------ - - // Allocate space for our characters info data - // NOTE: This memory should be freed at end! --> CloseWindow() - defaultFont.chars = (CharInfo *)malloc(defaultFont.charsCount*sizeof(CharInfo)); - - int currentLine = 0; - int currentPosX = charsDivisor; - int testPosX = charsDivisor; - - for (int i = 0; i < defaultFont.charsCount; i++) - { - defaultFont.chars[i].value = 32 + i; // First char is 32 - - defaultFont.chars[i].rec.x = currentPosX; - defaultFont.chars[i].rec.y = charsDivisor + currentLine*(charsHeight + charsDivisor); - defaultFont.chars[i].rec.width = charsWidth[i]; - defaultFont.chars[i].rec.height = charsHeight; - - testPosX += (defaultFont.chars[i].rec.width + charsDivisor); - - if (testPosX >= defaultFont.texture.width) - { - currentLine++; - currentPosX = 2*charsDivisor + charsWidth[i]; - testPosX = currentPosX; - - defaultFont.chars[i].rec.x = charsDivisor; - defaultFont.chars[i].rec.y = charsDivisor + currentLine*(charsHeight + charsDivisor); - } - else currentPosX = testPosX; - - // NOTE: On default font character offsets and xAdvance are not required - defaultFont.chars[i].offsetX = 0; - defaultFont.chars[i].offsetY = 0; - defaultFont.chars[i].advanceX = 0; - } - - defaultFont.baseSize = defaultFont.chars[0].rec.height; - - TraceLog(LOG_INFO, "[TEX ID %i] Default font loaded successfully", defaultFont.texture.id); -} - -// Unload raylib default font -extern void UnloadDefaultFont(void) -{ - UnloadTexture(defaultFont.texture); - free(defaultFont.chars); -} -#endif // SUPPORT_DEFAULT_FONT - -// Get the default font, useful to be used with extended parameters -SpriteFont GetDefaultFont() -{ -#if defined(SUPPORT_DEFAULT_FONT) - return defaultFont; -#else - SpriteFont font = { 0 }; - return font; -#endif -} - -// Load SpriteFont from file into GPU memory (VRAM) -SpriteFont LoadSpriteFont(const char *fileName) -{ - // Default hardcoded values for ttf file loading - #define DEFAULT_TTF_FONTSIZE 32 // Font first character (32 - space) - #define DEFAULT_TTF_NUMCHARS 95 // ASCII 32..126 is 95 glyphs - #define DEFAULT_FIRST_CHAR 32 // Expected first char for image spritefont - - SpriteFont spriteFont = { 0 }; - - // Check file extension - if (IsFileExtension(fileName, ".rres")) - { - // TODO: Read multiple resource blocks from file (RRES_FONT_IMAGE, RRES_FONT_CHARDATA) - RRES rres = LoadResource(fileName, 0); - - // Load sprite font texture - if (rres[0].type == RRES_TYPE_FONT_IMAGE) - { - // NOTE: Parameters for RRES_FONT_IMAGE type are: width, height, format, mipmaps - Image image = LoadImagePro(rres[0].data, rres[0].param1, rres[0].param2, rres[0].param3); - spriteFont.texture = LoadTextureFromImage(image); - UnloadImage(image); - } - - // Load sprite characters data - if (rres[1].type == RRES_TYPE_FONT_CHARDATA) - { - // NOTE: Parameters for RRES_FONT_CHARDATA type are: fontSize, charsCount - spriteFont.baseSize = rres[1].param1; - spriteFont.charsCount = rres[1].param2; - spriteFont.chars = rres[1].data; - } - - // TODO: Do not free rres.data memory (chars info data!) - //UnloadResource(rres[0]); - } -#if defined(SUPPORT_FILEFORMAT_TTF) - else if (IsFileExtension(fileName, ".ttf")) spriteFont = LoadSpriteFontEx(fileName, DEFAULT_TTF_FONTSIZE, 0, NULL); -#endif -#if defined(SUPPORT_FILEFORMAT_FNT) - else if (IsFileExtension(fileName, ".fnt")) spriteFont = LoadBMFont(fileName); -#endif - else - { - Image image = LoadImage(fileName); - if (image.data != NULL) spriteFont = LoadImageFont(image, MAGENTA, DEFAULT_FIRST_CHAR); - UnloadImage(image); - } - - if (spriteFont.texture.id == 0) - { - TraceLog(LOG_WARNING, "[%s] SpriteFont could not be loaded, using default font", fileName); - spriteFont = GetDefaultFont(); - } - else SetTextureFilter(spriteFont.texture, FILTER_POINT); // By default we set point filter (best performance) - - return spriteFont; -} - -// Load SpriteFont from TTF font file with generation parameters -// NOTE: You can pass an array with desired characters, those characters should be available in the font -// if array is NULL, default char set is selected 32..126 -SpriteFont LoadSpriteFontEx(const char *fileName, int fontSize, int charsCount, int *fontChars) -{ - SpriteFont spriteFont = { 0 }; - -#if defined(SUPPORT_FILEFORMAT_TTF) - if (IsFileExtension(fileName, ".ttf")) - { - if ((fontChars == NULL) || (charsCount == 0)) - { - int totalChars = 95; // Default charset [32..126] - - int *defaultFontChars = (int *)malloc(totalChars*sizeof(int)); - - for (int i = 0; i < totalChars; i++) defaultFontChars[i] = i + 32; // Default first character: SPACE[32] - - spriteFont = LoadTTF(fileName, fontSize, totalChars, defaultFontChars); - } - else spriteFont = LoadTTF(fileName, fontSize, charsCount, fontChars); - } -#endif - - if (spriteFont.texture.id == 0) - { - TraceLog(LOG_WARNING, "[%s] SpriteFont could not be generated, using default font", fileName); - spriteFont = GetDefaultFont(); - } - - return spriteFont; -} - -// Unload SpriteFont from GPU memory (VRAM) -void UnloadSpriteFont(SpriteFont spriteFont) -{ - // NOTE: Make sure spriteFont is not default font (fallback) - if (spriteFont.texture.id != GetDefaultFont().texture.id) - { - UnloadTexture(spriteFont.texture); - free(spriteFont.chars); - - TraceLog(LOG_DEBUG, "Unloaded sprite font data"); - } -} - -// Draw text (using default font) -// NOTE: fontSize work like in any drawing program but if fontSize is lower than font-base-size, then font-base-size is used -// NOTE: chars spacing is proportional to fontSize -void DrawText(const char *text, int posX, int posY, int fontSize, Color color) -{ - // Check if default font has been loaded - if (GetDefaultFont().texture.id != 0) - { - Vector2 position = { (float)posX, (float)posY }; - - int defaultFontSize = 10; // Default Font chars height in pixel - if (fontSize < defaultFontSize) fontSize = defaultFontSize; - int spacing = fontSize/defaultFontSize; - - DrawTextEx(GetDefaultFont(), text, position, (float)fontSize, spacing, color); - } -} - -// Draw text using SpriteFont -// NOTE: chars spacing is NOT proportional to fontSize -void DrawTextEx(SpriteFont spriteFont, const char *text, Vector2 position, float fontSize, int spacing, Color tint) -{ - int length = strlen(text); - int textOffsetX = 0; // Offset between characters - int textOffsetY = 0; // Required for line break! - float scaleFactor; - - unsigned char letter; // Current character - int index; // Index position in sprite font - - scaleFactor = fontSize/spriteFont.baseSize; - - // NOTE: Some ugly hacks are made to support Latin-1 Extended characters directly - // written in C code files (codified by default as UTF-8) - - for (int i = 0; i < length; i++) - { - if ((unsigned char)text[i] == '\n') - { - // NOTE: Fixed line spacing of 1.5 lines - textOffsetY += (int)((spriteFont.baseSize + spriteFont.baseSize/2)*scaleFactor); - textOffsetX = 0; - } - else - { - if ((unsigned char)text[i] == 0xc2) // UTF-8 encoding identification HACK! - { - // Support UTF-8 encoded values from [0xc2 0x80] -> [0xc2 0xbf](¿) - letter = (unsigned char)text[i + 1]; - index = GetCharIndex(spriteFont, (int)letter); - i++; - } - else if ((unsigned char)text[i] == 0xc3) // UTF-8 encoding identification HACK! - { - // Support UTF-8 encoded values from [0xc3 0x80](À) -> [0xc3 0xbf](ÿ) - letter = (unsigned char)text[i + 1]; - index = GetCharIndex(spriteFont, (int)letter + 64); - i++; - } - else index = GetCharIndex(spriteFont, (unsigned char)text[i]); - - DrawTexturePro(spriteFont.texture, spriteFont.chars[index].rec, - (Rectangle){ position.x + textOffsetX + spriteFont.chars[index].offsetX*scaleFactor, - position.y + textOffsetY + spriteFont.chars[index].offsetY*scaleFactor, - spriteFont.chars[index].rec.width*scaleFactor, - spriteFont.chars[index].rec.height*scaleFactor }, (Vector2){ 0, 0 }, 0.0f, tint); - - if (spriteFont.chars[index].advanceX == 0) textOffsetX += (int)(spriteFont.chars[index].rec.width*scaleFactor + spacing); - else textOffsetX += (int)(spriteFont.chars[index].advanceX*scaleFactor + spacing); - } - } -} - -// Formatting of text with variables to 'embed' -const char *FormatText(const char *text, ...) -{ - static char buffer[MAX_FORMATTEXT_LENGTH]; - - va_list args; - va_start(args, text); - vsprintf(buffer, text, args); - va_end(args); - - return buffer; -} - -// Get a piece of a text string -const char *SubText(const char *text, int position, int length) -{ - static char buffer[MAX_SUBTEXT_LENGTH]; - int textLength = strlen(text); - - if (position >= textLength) - { - position = textLength - 1; - length = 0; - } - - if (length >= textLength) length = textLength; - - for (int c = 0 ; c < length ; c++) - { - *(buffer+c) = *(text+position); - text++; - } - - *(buffer+length) = '\0'; - - return buffer; -} - -// Measure string width for default font -int MeasureText(const char *text, int fontSize) -{ - Vector2 vec = { 0.0f, 0.0f }; - - // Check if default font has been loaded - if (GetDefaultFont().texture.id != 0) - { - int defaultFontSize = 10; // Default Font chars height in pixel - if (fontSize < defaultFontSize) fontSize = defaultFontSize; - int spacing = fontSize/defaultFontSize; - - vec = MeasureTextEx(GetDefaultFont(), text, (float)fontSize, spacing); - } - - return (int)vec.x; -} - -// Measure string size for SpriteFont -Vector2 MeasureTextEx(SpriteFont spriteFont, const char *text, float fontSize, int spacing) -{ - int len = strlen(text); - int tempLen = 0; // Used to count longer text line num chars - int lenCounter = 0; - - float textWidth = 0; - float tempTextWidth = 0; // Used to count longer text line width - - float textHeight = (float)spriteFont.baseSize; - float scaleFactor = fontSize/(float)spriteFont.baseSize; - - for (int i = 0; i < len; i++) - { - lenCounter++; - - if (text[i] != '\n') - { - int index = GetCharIndex(spriteFont, (int)text[i]); - - if (spriteFont.chars[index].advanceX != 0) textWidth += spriteFont.chars[index].advanceX; - else textWidth += (spriteFont.chars[index].rec.width + spriteFont.chars[index].offsetX); - } - else - { - if (tempTextWidth < textWidth) tempTextWidth = textWidth; - lenCounter = 0; - textWidth = 0; - textHeight += ((float)spriteFont.baseSize*1.5f); // NOTE: Fixed line spacing of 1.5 lines - } - - if (tempLen < lenCounter) tempLen = lenCounter; - } - - if (tempTextWidth < textWidth) tempTextWidth = textWidth; - - Vector2 vec; - vec.x = tempTextWidth*scaleFactor + (float)((tempLen - 1)*spacing); // Adds chars spacing to measure - vec.y = textHeight*scaleFactor; - - return vec; -} - -// Shows current FPS on top-left corner -// NOTE: Uses default font -void DrawFPS(int posX, int posY) -{ - // NOTE: We are rendering fps every second for better viewing on high framerates - - static int fps = 0; - static int counter = 0; - static int refreshRate = 20; - - if (counter < refreshRate) counter++; - else - { - fps = GetFPS(); - refreshRate = fps; - counter = 0; - } - - // NOTE: We have rounding errors every frame, so it oscillates a lot - DrawText(FormatText("%2i FPS", fps), posX, posY, 20, LIME); -} - -//---------------------------------------------------------------------------------- -// Module specific Functions Definition -//---------------------------------------------------------------------------------- - -static int GetCharIndex(SpriteFont font, int letter) -{ -#define UNORDERED_CHARSET -#if defined(UNORDERED_CHARSET) - int index = 0; - - for (int i = 0; i < font.charsCount; i++) - { - if (font.chars[i].value == letter) - { - index = i; - break; - } - } - - return index; -#else - return (letter - 32); -#endif -} - -// Load an Image font file (XNA style) -static SpriteFont LoadImageFont(Image image, Color key, int firstChar) -{ - #define COLOR_EQUAL(col1, col2) ((col1.r == col2.r)&&(col1.g == col2.g)&&(col1.b == col2.b)&&(col1.a == col2.a)) - - int charSpacing = 0; - int lineSpacing = 0; - - int x = 0; - int y = 0; - - // Default number of characters supported - #define MAX_FONTCHARS 256 - - // We allocate a temporal arrays for chars data measures, - // once we get the actual number of chars, we copy data to a sized arrays - int tempCharValues[MAX_FONTCHARS]; - Rectangle tempCharRecs[MAX_FONTCHARS]; - - Color *pixels = GetImageData(image); - - // Parse image data to get charSpacing and lineSpacing - for (y = 0; y < image.height; y++) - { - for (x = 0; x < image.width; x++) - { - if (!COLOR_EQUAL(pixels[y*image.width + x], key)) break; - } - - if (!COLOR_EQUAL(pixels[y*image.width + x], key)) break; - } - - charSpacing = x; - lineSpacing = y; - - int charHeight = 0; - int j = 0; - - while (!COLOR_EQUAL(pixels[(lineSpacing + j)*image.width + charSpacing], key)) j++; - - charHeight = j; - - // Check array values to get characters: value, x, y, w, h - int index = 0; - int lineToRead = 0; - int xPosToRead = charSpacing; - - // Parse image data to get rectangle sizes - while ((lineSpacing + lineToRead*(charHeight + lineSpacing)) < image.height) - { - while ((xPosToRead < image.width) && - !COLOR_EQUAL((pixels[(lineSpacing + (charHeight+lineSpacing)*lineToRead)*image.width + xPosToRead]), key)) - { - tempCharValues[index] = firstChar + index; - - tempCharRecs[index].x = xPosToRead; - tempCharRecs[index].y = lineSpacing + lineToRead*(charHeight + lineSpacing); - tempCharRecs[index].height = charHeight; - - int charWidth = 0; - - while (!COLOR_EQUAL(pixels[(lineSpacing + (charHeight+lineSpacing)*lineToRead)*image.width + xPosToRead + charWidth], key)) charWidth++; - - tempCharRecs[index].width = charWidth; - - index++; - - xPosToRead += (charWidth + charSpacing); - } - - lineToRead++; - xPosToRead = charSpacing; - } - - TraceLog(LOG_DEBUG, "SpriteFont data parsed correctly from image"); - - // NOTE: We need to remove key color borders from image to avoid weird - // artifacts on texture scaling when using FILTER_BILINEAR or FILTER_TRILINEAR - for (int i = 0; i < image.height*image.width; i++) if (COLOR_EQUAL(pixels[i], key)) pixels[i] = BLANK; - - // Create a new image with the processed color data (key color replaced by BLANK) - Image fontClear = LoadImageEx(pixels, image.width, image.height); - - free(pixels); // Free pixels array memory - - // Create spritefont with all data parsed from image - SpriteFont spriteFont = { 0 }; - - spriteFont.texture = LoadTextureFromImage(fontClear); // Convert processed image to OpenGL texture - spriteFont.charsCount = index; - - UnloadImage(fontClear); // Unload processed image once converted to texture - - // We got tempCharValues and tempCharsRecs populated with chars data - // Now we move temp data to sized charValues and charRecs arrays - spriteFont.chars = (CharInfo *)malloc(spriteFont.charsCount*sizeof(CharInfo)); - - for (int i = 0; i < spriteFont.charsCount; i++) - { - spriteFont.chars[i].value = tempCharValues[i]; - spriteFont.chars[i].rec = tempCharRecs[i]; - - // NOTE: On image based fonts (XNA style), character offsets and xAdvance are not required (set to 0) - spriteFont.chars[i].offsetX = 0; - spriteFont.chars[i].offsetY = 0; - spriteFont.chars[i].advanceX = 0; - } - - spriteFont.baseSize = spriteFont.chars[0].rec.height; - - TraceLog(LOG_INFO, "Image file loaded correctly as SpriteFont"); - - return spriteFont; -} - -#if defined(SUPPORT_FILEFORMAT_FNT) -// Load a BMFont file (AngelCode font file) -static SpriteFont LoadBMFont(const char *fileName) -{ - #define MAX_BUFFER_SIZE 256 - - SpriteFont font = { 0 }; - font.texture.id = 0; - - char buffer[MAX_BUFFER_SIZE]; - char *searchPoint = NULL; - - int fontSize = 0; - int texWidth, texHeight; - char texFileName[128]; - int charsCount = 0; - - int base; // Useless data - - FILE *fntFile; - - fntFile = fopen(fileName, "rt"); - - if (fntFile == NULL) - { - TraceLog(LOG_WARNING, "[%s] FNT file could not be opened", fileName); - return font; - } - - // NOTE: We skip first line, it contains no useful information - fgets(buffer, MAX_BUFFER_SIZE, fntFile); - //searchPoint = strstr(buffer, "size"); - //sscanf(searchPoint, "size=%i", &fontSize); - - fgets(buffer, MAX_BUFFER_SIZE, fntFile); - searchPoint = strstr(buffer, "lineHeight"); - sscanf(searchPoint, "lineHeight=%i base=%i scaleW=%i scaleH=%i", &fontSize, &base, &texWidth, &texHeight); - - TraceLog(LOG_DEBUG, "[%s] Font size: %i", fileName, fontSize); - TraceLog(LOG_DEBUG, "[%s] Font texture scale: %ix%i", fileName, texWidth, texHeight); - - fgets(buffer, MAX_BUFFER_SIZE, fntFile); - searchPoint = strstr(buffer, "file"); - sscanf(searchPoint, "file=\"%128[^\"]\"", texFileName); - - TraceLog(LOG_DEBUG, "[%s] Font texture filename: %s", fileName, texFileName); - - fgets(buffer, MAX_BUFFER_SIZE, fntFile); - searchPoint = strstr(buffer, "count"); - sscanf(searchPoint, "count=%i", &charsCount); - - TraceLog(LOG_DEBUG, "[%s] Font num chars: %i", fileName, charsCount); - - // Compose correct path using route of .fnt file (fileName) and texFileName - char *texPath = NULL; - char *lastSlash = NULL; - - lastSlash = strrchr(fileName, '/'); - - // NOTE: We need some extra space to avoid memory corruption on next allocations! - texPath = malloc(strlen(fileName) - strlen(lastSlash) + strlen(texFileName) + 4); - - // NOTE: strcat() and strncat() required a '\0' terminated string to work! - *texPath = '\0'; - strncat(texPath, fileName, strlen(fileName) - strlen(lastSlash) + 1); - strncat(texPath, texFileName, strlen(texFileName)); - - TraceLog(LOG_DEBUG, "[%s] Font texture loading path: %s", fileName, texPath); - - Image imFont = LoadImage(texPath); - - if (imFont.format == UNCOMPRESSED_GRAYSCALE) - { - Image imCopy = ImageCopy(imFont); - - for (int i = 0; i < imCopy.width*imCopy.height; i++) ((unsigned char *)imCopy.data)[i] = 0xff; // WHITE pixel - - ImageAlphaMask(&imCopy, imFont); - font.texture = LoadTextureFromImage(imCopy); - UnloadImage(imCopy); - } - else font.texture = LoadTextureFromImage(imFont); - - font.baseSize = fontSize; - font.charsCount = charsCount; - font.chars = (CharInfo *)malloc(charsCount*sizeof(CharInfo)); - - UnloadImage(imFont); - - free(texPath); - - int charId, charX, charY, charWidth, charHeight, charOffsetX, charOffsetY, charAdvanceX; - - for (int i = 0; i < charsCount; i++) - { - fgets(buffer, MAX_BUFFER_SIZE, fntFile); - sscanf(buffer, "char id=%i x=%i y=%i width=%i height=%i xoffset=%i yoffset=%i xadvance=%i", - &charId, &charX, &charY, &charWidth, &charHeight, &charOffsetX, &charOffsetY, &charAdvanceX); - - // Save data properly in sprite font - font.chars[i].value = charId; - font.chars[i].rec = (Rectangle){ charX, charY, charWidth, charHeight }; - font.chars[i].offsetX = charOffsetX; - font.chars[i].offsetY = charOffsetY; - font.chars[i].advanceX = charAdvanceX; - } - - fclose(fntFile); - - if (font.texture.id == 0) - { - UnloadSpriteFont(font); - font = GetDefaultFont(); - } - else TraceLog(LOG_INFO, "[%s] SpriteFont loaded successfully", fileName); - - return font; -} -#endif - -#if defined(SUPPORT_FILEFORMAT_TTF) -// Generate a sprite font from TTF file data (font size required) -// TODO: Review texture packing method and generation (use oversampling) -static SpriteFont LoadTTF(const char *fileName, int fontSize, int charsCount, int *fontChars) -{ - #define MAX_TTF_SIZE 16 // Maximum ttf file size in MB - - // NOTE: Font texture size is predicted (being as much conservative as possible) - // Predictive method consist of supposing same number of chars by line-column (sqrtf) - // and a maximum character width of 3/4 of fontSize... it worked ok with all my tests... - - // Calculate next power-of-two value - float guessSize = ceilf((float)fontSize*3/4)*ceilf(sqrtf((float)charsCount)); - int textureSize = (int)powf(2, ceilf(logf((float)guessSize)/logf(2))); // Calculate next POT - - TraceLog(LOG_INFO, "TTF spritefont loading: Predicted texture size: %ix%i", textureSize, textureSize); - - unsigned char *ttfBuffer = (unsigned char *)malloc(MAX_TTF_SIZE*1024*1024); - unsigned char *dataBitmap = (unsigned char *)malloc(textureSize*textureSize*sizeof(unsigned char)); // One channel bitmap returned! - stbtt_bakedchar *charData = (stbtt_bakedchar *)malloc(sizeof(stbtt_bakedchar)*charsCount); - - SpriteFont font = { 0 }; - - FILE *ttfFile = fopen(fileName, "rb"); - - if (ttfFile == NULL) - { - TraceLog(LOG_WARNING, "[%s] TTF file could not be opened", fileName); - return font; - } - - // NOTE: We try reading up to 16 MB of elements of 1 byte - fread(ttfBuffer, 1, MAX_TTF_SIZE*1024*1024, ttfFile); - - if (fontChars[0] != 32) TraceLog(LOG_WARNING, "TTF spritefont loading: first character is not SPACE(32) character"); - - // NOTE: Using stb_truetype crappy packing method, no guarante the font fits the image... - // TODO: Replace this function by a proper packing method and support random chars order, - // we already receive a list (fontChars) with the ordered expected characters - int result = stbtt_BakeFontBitmap(ttfBuffer, 0, fontSize, dataBitmap, textureSize, textureSize, fontChars[0], charsCount, charData); - - //if (result > 0) TraceLog(LOG_INFO, "TTF spritefont loading: first unused row of generated bitmap: %i", result); - if (result < 0) TraceLog(LOG_WARNING, "TTF spritefont loading: Not all the characters fit in the font"); - - free(ttfBuffer); - - // Convert image data from grayscale to to UNCOMPRESSED_GRAY_ALPHA - unsigned char *dataGrayAlpha = (unsigned char *)malloc(textureSize*textureSize*sizeof(unsigned char)*2); // Two channels - - for (int i = 0, k = 0; i < textureSize*textureSize; i++, k += 2) - { - dataGrayAlpha[k] = 255; - dataGrayAlpha[k + 1] = dataBitmap[i]; - } - - free(dataBitmap); - - // Sprite font generation from TTF extracted data - Image image; - image.width = textureSize; - image.height = textureSize; - image.mipmaps = 1; - image.format = UNCOMPRESSED_GRAY_ALPHA; - image.data = dataGrayAlpha; - - font.texture = LoadTextureFromImage(image); - - //SavePNG("generated_ttf_image.png", (unsigned char *)image.data, image.width, image.height, 2); - - UnloadImage(image); // Unloads dataGrayAlpha - - font.baseSize = fontSize; - font.charsCount = charsCount; - font.chars = (CharInfo *)malloc(font.charsCount*sizeof(CharInfo)); - - for (int i = 0; i < font.charsCount; i++) - { - font.chars[i].value = fontChars[i]; - - font.chars[i].rec.x = (int)charData[i].x0; - font.chars[i].rec.y = (int)charData[i].y0; - font.chars[i].rec.width = (int)charData[i].x1 - (int)charData[i].x0; - font.chars[i].rec.height = (int)charData[i].y1 - (int)charData[i].y0; - - font.chars[i].offsetX = charData[i].xoff; - font.chars[i].offsetY = charData[i].yoff; - font.chars[i].advanceX = (int)charData[i].xadvance; - } - - free(charData); - - return font; -} -#endif diff --git a/game/src/libs/raylib/textures.c b/game/src/libs/raylib/textures.c deleted file mode 100644 index b9fc5c1..0000000 --- a/game/src/libs/raylib/textures.c +++ /dev/null @@ -1,2446 +0,0 @@ -/********************************************************************************************** -* -* raylib.textures - Basic functions to load and draw Textures (2d) -* -* CONFIGURATION: -* -* #define SUPPORT_FILEFORMAT_BMP -* #define SUPPORT_FILEFORMAT_PNG -* #define SUPPORT_FILEFORMAT_TGA -* #define SUPPORT_FILEFORMAT_JPG -* #define SUPPORT_FILEFORMAT_GIF -* #define SUPPORT_FILEFORMAT_PSD -* #define SUPPORT_FILEFORMAT_HDR -* #define SUPPORT_FILEFORMAT_DDS -* #define SUPPORT_FILEFORMAT_PKM -* #define SUPPORT_FILEFORMAT_KTX -* #define SUPPORT_FILEFORMAT_PVR -* #define SUPPORT_FILEFORMAT_ASTC -* Selecte desired fileformats to be supported for image data loading. Some of those formats are -* supported by default, to remove support, just comment unrequired #define in this module -* -* #define 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() -* -* #define SUPPORT_IMAGE_GENERATION -* Support proedural image generation functionality (gradient, spot, perlin-noise, cellular) -* -* DEPENDENCIES: -* stb_image - Multiple image formats loading (JPEG, PNG, BMP, TGA, PSD, GIF, PIC) -* NOTE: stb_image has been slightly modified to support Android platform. -* stb_image_resize - Multiple image resize algorythms -* -* -* LICENSE: zlib/libpng -* -* Copyright (c) 2014-2017 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. -* -* Permission is granted to anyone to use this software for any purpose, including commercial -* applications, and to alter it and redistribute it freely, subject to the following restrictions: -* -* 1. The origin of this software must not be misrepresented; you must not claim that you -* wrote the original software. If you use this software in a product, an acknowledgment -* in the product documentation would be appreciated but is not required. -* -* 2. Altered source versions must be plainly marked as such, and must not be misrepresented -* as being the original software. -* -* 3. This notice may not be removed or altered from any source distribution. -* -**********************************************************************************************/ - -// Default configuration flags (supported features) -//------------------------------------------------- -#define SUPPORT_FILEFORMAT_PNG -#define SUPPORT_FILEFORMAT_DDS -#define SUPPORT_FILEFORMAT_HDR -#define SUPPORT_IMAGE_MANIPULATION -#define SUPPORT_IMAGE_GENERATION -//------------------------------------------------- - -#include "raylib.h" - -#include // Required for: malloc(), free() -#include // Required for: strcmp(), strrchr(), strncmp() - -#include "rlgl.h" // raylib OpenGL abstraction layer to OpenGL 1.1, 3.3 or ES2 - // Required for: rlLoadTexture() rlDeleteTextures(), - // rlGenerateMipmaps(), some funcs for DrawTexturePro() - -#include "utils.h" // Required for: fopen() Android mapping - -#define STB_PERLIN_IMPLEMENTATION -#include "external/stb_perlin.h"// Required for: stb_perlin_fbm_noise3 - -// Support only desired texture formats on stb_image -#if !defined(SUPPORT_FILEFORMAT_BMP) - #define STBI_NO_BMP -#endif -#if !defined(SUPPORT_FILEFORMAT_PNG) - #define STBI_NO_PNG -#endif -#if !defined(SUPPORT_FILEFORMAT_TGA) - #define STBI_NO_TGA -#endif -#if !defined(SUPPORT_FILEFORMAT_JPG) - #define STBI_NO_JPEG // Image format .jpg and .jpeg -#endif -#if !defined(SUPPORT_FILEFORMAT_PSD) - #define STBI_NO_PSD -#endif -#if !defined(SUPPORT_FILEFORMAT_GIF) - #define STBI_NO_GIF -#endif -#if !defined(SUPPORT_FILEFORMAT_HDR) - #define STBI_NO_HDR -#endif - -// Image fileformats not supported by default -#define STBI_NO_PIC -#define STBI_NO_PNM // Image format .ppm and .pgm - -#if (defined(SUPPORT_FILEFORMAT_BMP) || defined(SUPPORT_FILEFORMAT_PNG) || defined(SUPPORT_FILEFORMAT_TGA) || \ - defined(SUPPORT_FILEFORMAT_JPG) || defined(SUPPORT_FILEFORMAT_PSD) || defined(SUPPORT_FILEFORMAT_GIF) || \ - defined(SUPPORT_FILEFORMAT_HDR)) - #define STB_IMAGE_IMPLEMENTATION - #include "external/stb_image.h" // Required for: stbi_load_from_file() - // NOTE: Used to read image data (multiple formats support) -#endif - -#if defined(SUPPORT_IMAGE_MANIPULATION) - #define STB_IMAGE_RESIZE_IMPLEMENTATION - #include "external/stb_image_resize.h" // Required for: stbir_resize_uint8() - // NOTE: Used for image scaling on ImageResize() -#endif - -//---------------------------------------------------------------------------------- -// Defines and Macros -//---------------------------------------------------------------------------------- -// Nop... - -//---------------------------------------------------------------------------------- -// Types and Structures Definition -//---------------------------------------------------------------------------------- -// ... - -//---------------------------------------------------------------------------------- -// Global Variables Definition -//---------------------------------------------------------------------------------- -// It's lonely here... - -//---------------------------------------------------------------------------------- -// Other Modules Functions Declaration (required by text) -//---------------------------------------------------------------------------------- -// ... - -//---------------------------------------------------------------------------------- -// Module specific Functions Declaration -//---------------------------------------------------------------------------------- -#if defined(SUPPORT_FILEFORMAT_DDS) -static Image LoadDDS(const char *fileName); // Load DDS file -#endif -#if defined(SUPPORT_FILEFORMAT_PKM) -static Image LoadPKM(const char *fileName); // Load PKM file -#endif -#if defined(SUPPORT_FILEFORMAT_KTX) -static Image LoadKTX(const char *fileName); // Load KTX file -#endif -#if defined(SUPPORT_FILEFORMAT_PVR) -static Image LoadPVR(const char *fileName); // Load PVR file -#endif -#if defined(SUPPORT_FILEFORMAT_ASTC) -static Image LoadASTC(const char *fileName); // Load ASTC file -#endif - -//---------------------------------------------------------------------------------- -// Module Functions Definition -//---------------------------------------------------------------------------------- - -// Load image from file into CPU memory (RAM) -Image LoadImage(const char *fileName) -{ - Image image = { 0 }; - - if (IsFileExtension(fileName, ".rres")) - { - RRES rres = LoadResource(fileName, 0); - - // NOTE: Parameters for RRES_TYPE_IMAGE are: width, height, format, mipmaps - - if (rres[0].type == RRES_TYPE_IMAGE) image = LoadImagePro(rres[0].data, rres[0].param1, rres[0].param2, rres[0].param3); - else TraceLog(LOG_WARNING, "[%s] Resource file does not contain image data", fileName); - - UnloadResource(rres); - } - else if ((IsFileExtension(fileName, ".png")) -#if defined(SUPPORT_FILEFORMAT_BMP) - || (IsFileExtension(fileName, ".bmp")) -#endif -#if defined(SUPPORT_FILEFORMAT_TGA) - || (IsFileExtension(fileName, ".tga")) -#endif -#if defined(SUPPORT_FILEFORMAT_JPG) - || (IsFileExtension(fileName, ".jpg")) -#endif -#if defined(SUPPORT_FILEFORMAT_DDS) - || (IsFileExtension(fileName, ".gif")) -#endif -#if defined(SUPPORT_FILEFORMAT_PSD) - || (IsFileExtension(fileName, ".psd")) -#endif - ) - { - int imgWidth = 0; - int imgHeight = 0; - int imgBpp = 0; - - FILE *imFile = fopen(fileName, "rb"); - - if (imFile != NULL) - { - // NOTE: Using stb_image to load images (Supports: BMP, TGA, PNG, JPG, ...) - image.data = stbi_load_from_file(imFile, &imgWidth, &imgHeight, &imgBpp, 0); - - fclose(imFile); - - image.width = imgWidth; - image.height = imgHeight; - image.mipmaps = 1; - - if (imgBpp == 1) image.format = UNCOMPRESSED_GRAYSCALE; - else if (imgBpp == 2) image.format = UNCOMPRESSED_GRAY_ALPHA; - else if (imgBpp == 3) image.format = UNCOMPRESSED_R8G8B8; - else if (imgBpp == 4) image.format = UNCOMPRESSED_R8G8B8A8; - } - } -#if defined(SUPPORT_FILEFORMAT_HDR) - else if (IsFileExtension(fileName, ".hdr")) - { - int imgBpp = 0; - - FILE *imFile = fopen(fileName, "rb"); - - stbi_set_flip_vertically_on_load(true); - - // Load 32 bit per channel floats data - image.data = stbi_loadf_from_file(imFile, &image.width, &image.height, &imgBpp, 0); - - stbi_set_flip_vertically_on_load(false); - - fclose(imFile); - - image.mipmaps = 1; - - if (imgBpp == 3) image.format = UNCOMPRESSED_R32G32B32; - else - { - // TODO: Support different number of channels at 32 bit float - TraceLog(LOG_WARNING, "[%s] Image fileformat not supported (only 3 channel 32 bit floats)", fileName); - UnloadImage(image); - } - } -#endif -#if defined(SUPPORT_FILEFORMAT_DDS) - else if (IsFileExtension(fileName, ".dds")) image = LoadDDS(fileName); -#endif -#if defined(SUPPORT_FILEFORMAT_PKM) - else if (IsFileExtension(fileName, ".pkm")) image = LoadPKM(fileName); -#endif -#if defined(SUPPORT_FILEFORMAT_KTX) - else if (IsFileExtension(fileName, ".ktx")) image = LoadKTX(fileName); -#endif -#if defined(SUPPORT_FILEFORMAT_PVR) - else if (IsFileExtension(fileName, ".pvr")) image = LoadPVR(fileName); -#endif -#if defined(SUPPORT_FILEFORMAT_ASTC) - else if (IsFileExtension(fileName, ".astc")) image = LoadASTC(fileName); -#endif - else TraceLog(LOG_WARNING, "[%s] Image fileformat not supported", fileName); - - if (image.data != NULL) TraceLog(LOG_INFO, "[%s] Image loaded successfully (%ix%i)", fileName, image.width, image.height); - else TraceLog(LOG_WARNING, "[%s] Image could not be loaded", fileName); - - return image; -} - -// Load image from Color array data (RGBA - 32bit) -// NOTE: Creates a copy of pixels data array -Image LoadImageEx(Color *pixels, int width, int height) -{ - Image image; - image.data = NULL; - image.width = width; - image.height = height; - image.mipmaps = 1; - image.format = UNCOMPRESSED_R8G8B8A8; - - int k = 0; - - image.data = (unsigned char *)malloc(image.width*image.height*4*sizeof(unsigned char)); - - for (int i = 0; i < image.width*image.height*4; i += 4) - { - ((unsigned char *)image.data)[i] = pixels[k].r; - ((unsigned char *)image.data)[i + 1] = pixels[k].g; - ((unsigned char *)image.data)[i + 2] = pixels[k].b; - ((unsigned char *)image.data)[i + 3] = pixels[k].a; - k++; - } - - return image; -} - -// Load image from raw data with parameters -// NOTE: This functions makes a copy of provided data -Image LoadImagePro(void *data, int width, int height, int format) -{ - Image srcImage = { 0 }; - - srcImage.data = data; - srcImage.width = width; - srcImage.height = height; - srcImage.mipmaps = 1; - srcImage.format = format; - - Image dstImage = ImageCopy(srcImage); - - return dstImage; -} - -// Load an image from RAW file data -Image LoadImageRaw(const char *fileName, int width, int height, int format, int headerSize) -{ - Image image = { 0 }; - - FILE *rawFile = fopen(fileName, "rb"); - - if (rawFile == NULL) - { - TraceLog(LOG_WARNING, "[%s] RAW image file could not be opened", fileName); - } - else - { - if (headerSize > 0) fseek(rawFile, headerSize, SEEK_SET); - - unsigned int size = width*height; - - switch (format) - { - case UNCOMPRESSED_GRAYSCALE: image.data = (unsigned char *)malloc(size); break; // 8 bit per pixel (no alpha) - case UNCOMPRESSED_GRAY_ALPHA: image.data = (unsigned char *)malloc(size*2); size *= 2; break; // 16 bpp (2 channels) - case UNCOMPRESSED_R5G6B5: image.data = (unsigned short *)malloc(size); break; // 16 bpp - case UNCOMPRESSED_R8G8B8: image.data = (unsigned char *)malloc(size*3); size *= 3; break; // 24 bpp - case UNCOMPRESSED_R5G5B5A1: image.data = (unsigned short *)malloc(size); break; // 16 bpp (1 bit alpha) - case UNCOMPRESSED_R4G4B4A4: image.data = (unsigned short *)malloc(size); break; // 16 bpp (4 bit alpha) - case UNCOMPRESSED_R8G8B8A8: image.data = (unsigned char *)malloc(size*4); size *= 4; break; // 32 bpp - case UNCOMPRESSED_R32G32B32: image.data = (float *)malloc(size*12); size *= 12; break; // 4 byte per channel (12 byte) - default: TraceLog(LOG_WARNING, "Image format not suported"); break; - } - - // NOTE: fread() returns num read elements instead of bytes, - // to get bytes we need to read (1 byte size, elements) instead of (x byte size, 1 element) - int bytes = fread(image.data, 1, size, rawFile); - - // Check if data has been read successfully - if (bytes < size) - { - TraceLog(LOG_WARNING, "[%s] RAW image data can not be read, wrong requested format or size", fileName); - - if (image.data != NULL) free(image.data); - } - else - { - image.width = width; - image.height = height; - image.mipmaps = 1; - image.format = format; - } - - fclose(rawFile); - } - - return image; -} - -// Load texture from file into GPU memory (VRAM) -Texture2D LoadTexture(const char *fileName) -{ - Texture2D texture = { 0 }; - - Image image = LoadImage(fileName); - - if (image.data != NULL) - { - texture = LoadTextureFromImage(image); - UnloadImage(image); - } - else TraceLog(LOG_WARNING, "Texture could not be created"); - - return texture; -} - -// Load a texture from image data -// NOTE: image is not unloaded, it must be done manually -Texture2D LoadTextureFromImage(Image image) -{ - Texture2D texture = { 0 }; - - texture.id = rlLoadTexture(image.data, image.width, image.height, image.format, image.mipmaps); - - texture.width = image.width; - texture.height = image.height; - texture.mipmaps = image.mipmaps; - texture.format = image.format; - - TraceLog(LOG_DEBUG, "[TEX ID %i] Parameters: %ix%i, %i mips, format %i", texture.id, texture.width, texture.height, texture.mipmaps, texture.format); - - return texture; -} - -// Load texture for rendering (framebuffer) -RenderTexture2D LoadRenderTexture(int width, int height) -{ - RenderTexture2D target = rlLoadRenderTexture(width, height); - - return target; -} - -// Unload image from CPU memory (RAM) -void UnloadImage(Image image) -{ - if (image.data != NULL) free(image.data); - - // NOTE: It becomes anoying every time a texture is loaded - //TraceLog(LOG_INFO, "Unloaded image data"); -} - -// Unload texture from GPU memory (VRAM) -void UnloadTexture(Texture2D texture) -{ - if (texture.id > 0) - { - rlDeleteTextures(texture.id); - - TraceLog(LOG_INFO, "[TEX ID %i] Unloaded texture data from VRAM (GPU)", texture.id); - } -} - -// Unload render texture from GPU memory (VRAM) -void UnloadRenderTexture(RenderTexture2D target) -{ - if (target.id > 0) rlDeleteRenderTextures(target); -} - -// Get pixel data from image in the form of Color struct array -Color *GetImageData(Image image) -{ - Color *pixels = (Color *)malloc(image.width*image.height*sizeof(Color)); - - int k = 0; - - for (int i = 0; i < image.width*image.height; i++) - { - switch (image.format) - { - case UNCOMPRESSED_GRAYSCALE: - { - pixels[i].r = ((unsigned char *)image.data)[k]; - pixels[i].g = ((unsigned char *)image.data)[k]; - pixels[i].b = ((unsigned char *)image.data)[k]; - pixels[i].a = 255; - - k++; - } break; - case UNCOMPRESSED_GRAY_ALPHA: - { - pixels[i].r = ((unsigned char *)image.data)[k]; - pixels[i].g = ((unsigned char *)image.data)[k]; - pixels[i].b = ((unsigned char *)image.data)[k]; - pixels[i].a = ((unsigned char *)image.data)[k + 1]; - - k += 2; - } break; - case UNCOMPRESSED_R5G5B5A1: - { - unsigned short pixel = ((unsigned short *)image.data)[k]; - - pixels[i].r = (unsigned char)((float)((pixel & 0b1111100000000000) >> 11)*(255/31)); - pixels[i].g = (unsigned char)((float)((pixel & 0b0000011111000000) >> 6)*(255/31)); - pixels[i].b = (unsigned char)((float)((pixel & 0b0000000000111110) >> 1)*(255/31)); - pixels[i].a = (unsigned char)((pixel & 0b0000000000000001)*255); - - k++; - } break; - case UNCOMPRESSED_R5G6B5: - { - unsigned short pixel = ((unsigned short *)image.data)[k]; - - pixels[i].r = (unsigned char)((float)((pixel & 0b1111100000000000) >> 11)*(255/31)); - pixels[i].g = (unsigned char)((float)((pixel & 0b0000011111100000) >> 5)*(255/63)); - pixels[i].b = (unsigned char)((float)(pixel & 0b0000000000011111)*(255/31)); - pixels[i].a = 255; - - k++; - } break; - case UNCOMPRESSED_R4G4B4A4: - { - unsigned short pixel = ((unsigned short *)image.data)[k]; - - pixels[i].r = (unsigned char)((float)((pixel & 0b1111000000000000) >> 12)*(255/15)); - pixels[i].g = (unsigned char)((float)((pixel & 0b0000111100000000) >> 8)*(255/15)); - pixels[i].b = (unsigned char)((float)((pixel & 0b0000000011110000) >> 4)*(255/15)); - pixels[i].a = (unsigned char)((float)(pixel & 0b0000000000001111)*(255/15)); - - k++; - } break; - case UNCOMPRESSED_R8G8B8A8: - { - pixels[i].r = ((unsigned char *)image.data)[k]; - pixels[i].g = ((unsigned char *)image.data)[k + 1]; - pixels[i].b = ((unsigned char *)image.data)[k + 2]; - pixels[i].a = ((unsigned char *)image.data)[k + 3]; - - k += 4; - } break; - case UNCOMPRESSED_R8G8B8: - { - pixels[i].r = (unsigned char)((unsigned char *)image.data)[k]; - pixels[i].g = (unsigned char)((unsigned char *)image.data)[k + 1]; - pixels[i].b = (unsigned char)((unsigned char *)image.data)[k + 2]; - pixels[i].a = 255; - - k += 3; - } break; - default: TraceLog(LOG_WARNING, "Format not supported for pixel data retrieval"); break; - } - } - - return pixels; -} - -// Get pixel data from GPU texture and return an Image -// NOTE: Compressed texture formats not supported -Image GetTextureData(Texture2D texture) -{ - Image image = { 0 }; - - if (texture.format < 8) - { - image.data = rlReadTexturePixels(texture); - - if (image.data != NULL) - { - image.width = texture.width; - image.height = texture.height; - image.mipmaps = 1; - - if (rlGetVersion() == OPENGL_ES_20) - { - // NOTE: Data retrieved on OpenGL ES 2.0 comes as RGBA (from framebuffer) - image.format = UNCOMPRESSED_R8G8B8A8; - } - else image.format = texture.format; - - TraceLog(LOG_INFO, "Texture pixel data obtained successfully"); - } - else TraceLog(LOG_WARNING, "Texture pixel data could not be obtained"); - } - else TraceLog(LOG_WARNING, "Compressed texture data could not be obtained"); - - return image; -} - -// Update GPU texture with new data -// NOTE: pixels data must match texture.format -void UpdateTexture(Texture2D texture, const void *pixels) -{ - rlUpdateTexture(texture.id, texture.width, texture.height, texture.format, pixels); -} - -// Save image to a PNG file -void SaveImageAs(const char* fileName, Image image) -{ -#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI) - unsigned char* imgData = (unsigned char*)GetImageData(image); // this works since Color is just a container for the RGBA values - SavePNG(fileName, imgData, image.width, image.height, 4); - free(imgData); - - TraceLog(LOG_INFO, "Image saved: %s", fileName); -#endif -} - -// Convert image data to desired format -void ImageFormat(Image *image, int newFormat) -{ - if (image->format != newFormat) - { - if ((image->format < COMPRESSED_DXT1_RGB) && (newFormat < COMPRESSED_DXT1_RGB)) - { - Color *pixels = GetImageData(*image); - - free(image->data); - - image->format = newFormat; - - int k = 0; - - switch (image->format) - { - case UNCOMPRESSED_GRAYSCALE: - { - image->data = (unsigned char *)malloc(image->width*image->height*sizeof(unsigned char)); - - for (int i = 0; i < image->width*image->height; i++) - { - ((unsigned char *)image->data)[i] = (unsigned char)((float)pixels[i].r*0.299f + (float)pixels[i].g*0.587f + (float)pixels[i].b*0.114f); - } - - } break; - case UNCOMPRESSED_GRAY_ALPHA: - { - image->data = (unsigned char *)malloc(image->width*image->height*2*sizeof(unsigned char)); - - for (int i = 0; i < image->width*image->height*2; i += 2) - { - ((unsigned char *)image->data)[i] = (unsigned char)((float)pixels[k].r*0.299f + (float)pixels[k].g*0.587f + (float)pixels[k].b*0.114f); - ((unsigned char *)image->data)[i + 1] = pixels[k].a; - k++; - } - - } break; - case UNCOMPRESSED_R5G6B5: - { - image->data = (unsigned short *)malloc(image->width*image->height*sizeof(unsigned short)); - - unsigned char r = 0; - unsigned char g = 0; - unsigned char b = 0; - - for (int i = 0; i < image->width*image->height; i++) - { - r = (unsigned char)(round((float)pixels[k].r*31/255)); - g = (unsigned char)(round((float)pixels[k].g*63/255)); - b = (unsigned char)(round((float)pixels[k].b*31/255)); - - ((unsigned short *)image->data)[i] = (unsigned short)r << 11 | (unsigned short)g << 5 | (unsigned short)b; - } - - } break; - case UNCOMPRESSED_R8G8B8: - { - image->data = (unsigned char *)malloc(image->width*image->height*3*sizeof(unsigned char)); - - for (int i = 0; i < image->width*image->height*3; i += 3) - { - ((unsigned char *)image->data)[i] = pixels[k].r; - ((unsigned char *)image->data)[i + 1] = pixels[k].g; - ((unsigned char *)image->data)[i + 2] = pixels[k].b; - k++; - } - } break; - case UNCOMPRESSED_R5G5B5A1: - { - #define ALPHA_THRESHOLD 50 - - image->data = (unsigned short *)malloc(image->width*image->height*sizeof(unsigned short)); - - unsigned char r = 0; - unsigned char g = 0; - unsigned char b = 0; - unsigned char a = 0; - - for (int i = 0; i < image->width*image->height; i++) - { - r = (unsigned char)(round((float)pixels[i].r*31/255)); - g = (unsigned char)(round((float)pixels[i].g*31/255)); - b = (unsigned char)(round((float)pixels[i].b*31/255)); - a = (pixels[i].a > ALPHA_THRESHOLD) ? 1 : 0; - - ((unsigned short *)image->data)[i] = (unsigned short)r << 11 | (unsigned short)g << 6 | (unsigned short)b << 1 | (unsigned short)a; - } - - } break; - case UNCOMPRESSED_R4G4B4A4: - { - image->data = (unsigned short *)malloc(image->width*image->height*sizeof(unsigned short)); - - unsigned char r = 0; - unsigned char g = 0; - unsigned char b = 0; - unsigned char a = 0; - - for (int i = 0; i < image->width*image->height; i++) - { - r = (unsigned char)(round((float)pixels[i].r*15/255)); - g = (unsigned char)(round((float)pixels[i].g*15/255)); - b = (unsigned char)(round((float)pixels[i].b*15/255)); - a = (unsigned char)(round((float)pixels[i].a*15/255)); - - ((unsigned short *)image->data)[i] = (unsigned short)r << 12 | (unsigned short)g << 8| (unsigned short)b << 4| (unsigned short)a; - } - - } break; - case UNCOMPRESSED_R8G8B8A8: - { - image->data = (unsigned char *)malloc(image->width*image->height*4*sizeof(unsigned char)); - - for (int i = 0; i < image->width*image->height*4; i += 4) - { - ((unsigned char *)image->data)[i] = pixels[k].r; - ((unsigned char *)image->data)[i + 1] = pixels[k].g; - ((unsigned char *)image->data)[i + 2] = pixels[k].b; - ((unsigned char *)image->data)[i + 3] = pixels[k].a; - k++; - } - } break; - default: break; - } - - free(pixels); - } - else TraceLog(LOG_WARNING, "Image data format is compressed, can not be converted"); - } -} - -// Apply alpha mask to image -// NOTE 1: Returned image is GRAY_ALPHA (16bit) or RGBA (32bit) -// NOTE 2: alphaMask should be same size as image -void ImageAlphaMask(Image *image, Image alphaMask) -{ - if ((image->width != alphaMask.width) || (image->height != alphaMask.height)) - { - TraceLog(LOG_WARNING, "Alpha mask must be same size as image"); - } - else if (image->format >= COMPRESSED_DXT1_RGB) - { - TraceLog(LOG_WARNING, "Alpha mask can not be applied to compressed data formats"); - } - else - { - // Force mask to be Grayscale - Image mask = ImageCopy(alphaMask); - if (mask.format != UNCOMPRESSED_GRAYSCALE) ImageFormat(&mask, UNCOMPRESSED_GRAYSCALE); - - // In case image is only grayscale, we just add alpha channel - if (image->format == UNCOMPRESSED_GRAYSCALE) - { - ImageFormat(image, UNCOMPRESSED_GRAY_ALPHA); - - // Apply alpha mask to alpha channel - for (int i = 0, k = 1; (i < mask.width*mask.height) || (i < image->width*image->height); i++, k += 2) - { - ((unsigned char *)image->data)[k] = ((unsigned char *)mask.data)[i]; - } - } - else - { - // Convert image to RGBA - if (image->format != UNCOMPRESSED_R8G8B8A8) ImageFormat(image, UNCOMPRESSED_R8G8B8A8); - - // Apply alpha mask to alpha channel - for (int i = 0, k = 3; (i < mask.width*mask.height) || (i < image->width*image->height); i++, k += 4) - { - ((unsigned char *)image->data)[k] = ((unsigned char *)mask.data)[i]; - } - } - - UnloadImage(mask); - } -} - -// Convert image to POT (power-of-two) -// NOTE: It could be useful on OpenGL ES 2.0 (RPI, HTML5) -void ImageToPOT(Image *image, Color fillColor) -{ - Color *pixels = GetImageData(*image); // Get pixels data - - // Calculate next power-of-two values - // NOTE: Just add the required amount of pixels at the right and bottom sides of image... - int potWidth = (int)powf(2, ceilf(logf((float)image->width)/logf(2))); - int potHeight = (int)powf(2, ceilf(logf((float)image->height)/logf(2))); - - // Check if POT texture generation is required (if texture is not already POT) - if ((potWidth != image->width) || (potHeight != image->height)) - { - Color *pixelsPOT = NULL; - - // Generate POT array from NPOT data - pixelsPOT = (Color *)malloc(potWidth*potHeight*sizeof(Color)); - - for (int j = 0; j < potHeight; j++) - { - for (int i = 0; i < potWidth; i++) - { - if ((j < image->height) && (i < image->width)) pixelsPOT[j*potWidth + i] = pixels[j*image->width + i]; - else pixelsPOT[j*potWidth + i] = fillColor; - } - } - - TraceLog(LOG_WARNING, "Image converted to POT: (%ix%i) -> (%ix%i)", image->width, image->height, potWidth, potHeight); - - free(pixels); // Free pixels data - free(image->data); // Free old image data - - int format = image->format; // Store image data format to reconvert later - - // TODO: Image width and height changes... do we want to store new values or keep the old ones? - // NOTE: Issues when using image.width and image.height for sprite animations... - *image = LoadImageEx(pixelsPOT, potWidth, potHeight); - - free(pixelsPOT); // Free POT pixels data - - ImageFormat(image, format); // Reconvert image to previous format - } -} - -#if defined(SUPPORT_IMAGE_MANIPULATION) -// Copy an image to a new image -Image ImageCopy(Image image) -{ - Image newImage; - - int byteSize = image.width*image.height; - - switch (image.format) - { - case UNCOMPRESSED_GRAYSCALE: break; // 8 bpp (1 byte) - case UNCOMPRESSED_GRAY_ALPHA: // 16 bpp - case UNCOMPRESSED_R5G6B5: // 16 bpp - case UNCOMPRESSED_R5G5B5A1: // 16 bpp - case UNCOMPRESSED_R4G4B4A4: byteSize *= 2; break; // 16 bpp (2 bytes) - case UNCOMPRESSED_R8G8B8: byteSize *= 3; break; // 24 bpp (3 bytes) - case UNCOMPRESSED_R8G8B8A8: byteSize *= 4; break; // 32 bpp (4 bytes) - case UNCOMPRESSED_R32G32B32: byteSize *= 12; break; // 4 byte per channel (12 bytes) - case COMPRESSED_DXT3_RGBA: - case COMPRESSED_DXT5_RGBA: - case COMPRESSED_ETC2_EAC_RGBA: - case COMPRESSED_ASTC_4x4_RGBA: break; // 8 bpp (1 byte) - case COMPRESSED_DXT1_RGB: - case COMPRESSED_DXT1_RGBA: - case COMPRESSED_ETC1_RGB: - case COMPRESSED_ETC2_RGB: - case COMPRESSED_PVRT_RGB: - case COMPRESSED_PVRT_RGBA: byteSize /= 2; break; // 4 bpp - case COMPRESSED_ASTC_8x8_RGBA: byteSize /= 4; break;// 2 bpp - default: TraceLog(LOG_WARNING, "Image format not recognized"); break; - } - - newImage.data = malloc(byteSize); - - if (newImage.data != NULL) - { - // NOTE: Size must be provided in bytes - memcpy(newImage.data, image.data, byteSize); - - newImage.width = image.width; - newImage.height = image.height; - newImage.mipmaps = image.mipmaps; - newImage.format = image.format; - } - - return newImage; -} - -// Crop an image to area defined by a rectangle -// NOTE: Security checks are performed in case rectangle goes out of bounds -void ImageCrop(Image *image, Rectangle crop) -{ - // Security checks to make sure cropping rectangle is inside margins - if ((crop.x + crop.width) > image->width) - { - crop.width = image->width - crop.x; - TraceLog(LOG_WARNING, "Crop rectangle width out of bounds, rescaled crop width: %i", crop.width); - } - - if ((crop.y + crop.height) > image->height) - { - crop.height = image->height - crop.y; - TraceLog(LOG_WARNING, "Crop rectangle height out of bounds, rescaled crop height: %i", crop.height); - } - - if ((crop.x < image->width) && (crop.y < image->height)) - { - // Start the cropping process - Color *pixels = GetImageData(*image); // Get data as Color pixels array - Color *cropPixels = (Color *)malloc(crop.width*crop.height*sizeof(Color)); - - for (int j = crop.y; j < (crop.y + crop.height); j++) - { - for (int i = crop.x; i < (crop.x + crop.width); i++) - { - cropPixels[(j - crop.y)*crop.width + (i - crop.x)] = pixels[j*image->width + i]; - } - } - - free(pixels); - - int format = image->format; - - UnloadImage(*image); - - *image = LoadImageEx(cropPixels, crop.width, crop.height); - - free(cropPixels); - - // Reformat 32bit RGBA image to original format - ImageFormat(image, format); - } - else - { - TraceLog(LOG_WARNING, "Image can not be cropped, crop rectangle out of bounds"); - } -} - -// Resize and image to new size -// NOTE: Uses stb default scaling filters (both bicubic): -// STBIR_DEFAULT_FILTER_UPSAMPLE STBIR_FILTER_CATMULLROM -// STBIR_DEFAULT_FILTER_DOWNSAMPLE STBIR_FILTER_MITCHELL (high-quality Catmull-Rom) -void ImageResize(Image *image, int newWidth, int newHeight) -{ - // Get data as Color pixels array to work with it - Color *pixels = GetImageData(*image); - Color *output = (Color *)malloc(newWidth*newHeight*sizeof(Color)); - - // NOTE: Color data is casted to (unsigned char *), there shouldn't been any problem... - stbir_resize_uint8((unsigned char *)pixels, image->width, image->height, 0, (unsigned char *)output, newWidth, newHeight, 0, 4); - - int format = image->format; - - UnloadImage(*image); - - *image = LoadImageEx(output, newWidth, newHeight); - ImageFormat(image, format); // Reformat 32bit RGBA image to original format - - free(output); - free(pixels); -} - -// Resize and image to new size using Nearest-Neighbor scaling algorithm -void ImageResizeNN(Image *image,int newWidth,int newHeight) -{ - Color *pixels = GetImageData(*image); - Color *output = (Color *)malloc(newWidth*newHeight*sizeof(Color)); - - // EDIT: added +1 to account for an early rounding problem - int xRatio = (int)((image->width << 16)/newWidth) + 1; - int yRatio = (int)((image->height << 16)/newHeight) + 1; - - int x2, y2; - for (int y = 0; y < newHeight; y++) - { - for (int x = 0; x < newWidth; x++) - { - x2 = ((x*xRatio) >> 16); - y2 = ((y*yRatio) >> 16); - - output[(y*newWidth) + x] = pixels[(y2*image->width) + x2] ; - } - } - - int format = image->format; - - UnloadImage(*image); - - *image = LoadImageEx(output, newWidth, newHeight); - ImageFormat(image, format); // Reformat 32bit RGBA image to original format - - free(output); - free(pixels); -} - -// Draw an image (source) within an image (destination) -// TODO: Feel this function could be simplified... -void ImageDraw(Image *dst, Image src, Rectangle srcRec, Rectangle dstRec) -{ - bool cropRequired = false; - - // Security checks to avoid size and rectangle issues (out of bounds) - // Check that srcRec is inside src image - if (srcRec.x < 0) srcRec.x = 0; - if (srcRec.y < 0) srcRec.y = 0; - - if ((srcRec.x + srcRec.width) > src.width) - { - srcRec.width = src.width - srcRec.x; - TraceLog(LOG_WARNING, "Source rectangle width out of bounds, rescaled width: %i", srcRec.width); - } - - if ((srcRec.y + srcRec.height) > src.height) - { - srcRec.height = src.height - srcRec.y; - TraceLog(LOG_WARNING, "Source rectangle height out of bounds, rescaled height: %i", srcRec.height); - cropRequired = true; - } - - Image srcCopy = ImageCopy(src); // Make a copy of source image to work with it - ImageCrop(&srcCopy, srcRec); // Crop source image to desired source rectangle - - // Check that dstRec is inside dst image - // TODO: Allow negative position within destination with cropping - if (dstRec.x < 0) dstRec.x = 0; - if (dstRec.y < 0) dstRec.y = 0; - - // Scale source image in case destination rec size is different than source rec size - if ((dstRec.width != srcRec.width) || (dstRec.height != srcRec.height)) - { - ImageResize(&srcCopy, dstRec.width, dstRec.height); - } - - if ((dstRec.x + dstRec.width) > dst->width) - { - dstRec.width = dst->width - dstRec.x; - TraceLog(LOG_WARNING, "Destination rectangle width out of bounds, rescaled width: %i", dstRec.width); - cropRequired = true; - } - - if ((dstRec.y + dstRec.height) > dst->height) - { - dstRec.height = dst->height - dstRec.y; - TraceLog(LOG_WARNING, "Destination rectangle height out of bounds, rescaled height: %i", dstRec.height); - cropRequired = true; - } - - if (cropRequired) - { - // Crop destination rectangle if out of bounds - Rectangle crop = { 0, 0, dstRec.width, dstRec.height }; - ImageCrop(&srcCopy, crop); - } - - // Get image data as Color pixels array to work with it - Color *dstPixels = GetImageData(*dst); - Color *srcPixels = GetImageData(srcCopy); - - UnloadImage(srcCopy); // Source copy not required any more... - - Color srcCol, dstCol; - - // Blit pixels, copy source image into destination - // TODO: Probably out-of-bounds blitting could be considered here instead of so much cropping... - for (int j = dstRec.y; j < (dstRec.y + dstRec.height); j++) - { - for (int i = dstRec.x; i < (dstRec.x + dstRec.width); i++) - { - // Alpha blending implementation - dstCol = dstPixels[j*dst->width + i]; - srcCol = srcPixels[(j - dstRec.y)*dstRec.width + (i - dstRec.x)]; - - dstCol.r = ((srcCol.a*(srcCol.r - dstCol.r)) >> 8) + dstCol.r; - dstCol.g = ((srcCol.a*(srcCol.g - dstCol.g)) >> 8) + dstCol.g; - dstCol.b = ((srcCol.a*(srcCol.b - dstCol.b)) >> 8) + dstCol.b; - - dstPixels[j*dst->width + i] = dstCol; - - // TODO: Support other blending options - } - } - - UnloadImage(*dst); // NOTE: Only dst->data is unloaded - - *dst = LoadImageEx(dstPixels, dst->width, dst->height); - ImageFormat(dst, dst->format); - - free(srcPixels); - free(dstPixels); -} - -// Create an image from text (default font) -Image ImageText(const char *text, int fontSize, Color color) -{ - int defaultFontSize = 10; // Default Font chars height in pixel - if (fontSize < defaultFontSize) fontSize = defaultFontSize; - int spacing = fontSize/defaultFontSize; - - Image imText = ImageTextEx(GetDefaultFont(), text, (float)fontSize, spacing, color); - - return imText; -} - -// Create an image from text (custom sprite font) -Image ImageTextEx(SpriteFont font, const char *text, float fontSize, int spacing, Color tint) -{ - int length = strlen(text); - int posX = 0; - - Vector2 imSize = MeasureTextEx(font, text, font.baseSize, spacing); - - // NOTE: glGetTexImage() not available in OpenGL ES - Image imFont = GetTextureData(font.texture); - - ImageFormat(&imFont, UNCOMPRESSED_R8G8B8A8); // Convert to 32 bit for color tint - ImageColorTint(&imFont, tint); // Apply color tint to font - - Color *fontPixels = GetImageData(imFont); - - // Create image to store text - // NOTE: Pixels are initialized to BLANK color (0, 0, 0, 0) - Color *pixels = (Color *)calloc((int)imSize.x*(int)imSize.y, sizeof(Color)); - - for (int i = 0; i < length; i++) - { - Rectangle letterRec = font.chars[(int)text[i] - 32].rec; - - for (int y = letterRec.y; y < (letterRec.y + letterRec.height); y++) - { - for (int x = posX; x < (posX + letterRec.width); x++) - { - pixels[(y - letterRec.y)*(int)imSize.x + x] = fontPixels[y*font.texture.width + (x - posX + letterRec.x)]; - } - } - - posX += letterRec.width + spacing; - } - - UnloadImage(imFont); - - Image imText = LoadImageEx(pixels, (int)imSize.x, (int)imSize.y); - - // Scale image depending on text size - if (fontSize > imSize.y) - { - float scaleFactor = fontSize/imSize.y; - TraceLog(LOG_INFO, "Scalefactor: %f", scaleFactor); - - // Using nearest-neighbor scaling algorithm for default font - if (font.texture.id == GetDefaultFont().texture.id) ImageResizeNN(&imText, (int)(imSize.x*scaleFactor), (int)(imSize.y*scaleFactor)); - else ImageResize(&imText, (int)(imSize.x*scaleFactor), (int)(imSize.y*scaleFactor)); - } - - free(pixels); - free(fontPixels); - - return imText; -} - -// Draw text (default font) within an image (destination) -void ImageDrawText(Image *dst, Vector2 position, const char *text, int fontSize, Color color) -{ - // NOTE: For default font, sapcing is set to desired font size / default font size (10) - ImageDrawTextEx(dst, position, GetDefaultFont(), text, (float)fontSize, fontSize/10, color); -} - -// Draw text (custom sprite font) within an image (destination) -void ImageDrawTextEx(Image *dst, Vector2 position, SpriteFont font, const char *text, float fontSize, int spacing, Color color) -{ - Image imText = ImageTextEx(font, text, fontSize, spacing, color); - - Rectangle srcRec = { 0, 0, imText.width, imText.height }; - Rectangle dstRec = { (int)position.x, (int)position.y, imText.width, imText.height }; - - ImageDraw(dst, imText, srcRec, dstRec); - - UnloadImage(imText); -} - -// Flip image vertically -void ImageFlipVertical(Image *image) -{ - Color *srcPixels = GetImageData(*image); - Color *dstPixels = (Color *)malloc(sizeof(Color)*image->width*image->height); - - for (int y = 0; y < image->height; y++) - { - for (int x = 0; x < image->width; x++) - { - dstPixels[y*image->width + x] = srcPixels[(image->height - 1 - y)*image->width + x]; - } - } - - Image processed = LoadImageEx(dstPixels, image->width, image->height); - ImageFormat(&processed, image->format); - UnloadImage(*image); - - free(srcPixels); - free(dstPixels); - - image->data = processed.data; -} - -// Flip image horizontally -void ImageFlipHorizontal(Image *image) -{ - Color *srcPixels = GetImageData(*image); - Color *dstPixels = (Color *)malloc(sizeof(Color)*image->width*image->height); - - for (int y = 0; y < image->height; y++) - { - for (int x = 0; x < image->width; x++) - { - dstPixels[y*image->width + x] = srcPixels[y*image->width + (image->width - 1 - x)]; - } - } - - Image processed = LoadImageEx(dstPixels, image->width, image->height); - ImageFormat(&processed, image->format); - UnloadImage(*image); - - free(srcPixels); - free(dstPixels); - - image->data = processed.data; -} - -// Dither image data to 16bpp or lower (Floyd-Steinberg dithering) -// NOTE: In case selected bpp do not represent an known 16bit format, -// dithered data is stored in the LSB part of the unsigned short -void ImageDither(Image *image, int rBpp, int gBpp, int bBpp, int aBpp) -{ - if (image->format >= COMPRESSED_DXT1_RGB) - { - TraceLog(LOG_WARNING, "Compressed data formats can not be dithered"); - return; - } - - if ((rBpp+gBpp+bBpp+aBpp) > 16) - { - TraceLog(LOG_WARNING, "Unsupported dithering bpps (%ibpp), only 16bpp or lower modes supported", (rBpp+gBpp+bBpp+aBpp)); - } - else - { - Color *pixels = GetImageData(*image); - - free(image->data); // free old image data - - if ((image->format != UNCOMPRESSED_R8G8B8) && (image->format != UNCOMPRESSED_R8G8B8A8)) - { - TraceLog(LOG_WARNING, "Image format is already 16bpp or lower, dithering could have no effect"); - } - - // Define new image format, check if desired bpp match internal known format - if ((rBpp == 5) && (gBpp == 6) && (bBpp == 5) && (aBpp == 0)) image->format = UNCOMPRESSED_R5G6B5; - else if ((rBpp == 5) && (gBpp == 5) && (bBpp == 5) && (aBpp == 1)) image->format = UNCOMPRESSED_R5G5B5A1; - else if ((rBpp == 4) && (gBpp == 4) && (bBpp == 4) && (aBpp == 4)) image->format = UNCOMPRESSED_R4G4B4A4; - else - { - image->format = 0; - TraceLog(LOG_WARNING, "Unsupported dithered OpenGL internal format: %ibpp (R%iG%iB%iA%i)", (rBpp+gBpp+bBpp+aBpp), rBpp, gBpp, bBpp, aBpp); - } - - // NOTE: We will store the dithered data as unsigned short (16bpp) - image->data = (unsigned short *)malloc(image->width*image->height*sizeof(unsigned short)); - - Color oldPixel = WHITE; - Color newPixel = WHITE; - - int rError, gError, bError; - unsigned short rPixel, gPixel, bPixel, aPixel; // Used for 16bit pixel composition - - #define MIN(a,b) (((a)<(b))?(a):(b)) - - for (int y = 0; y < image->height; y++) - { - for (int x = 0; x < image->width; x++) - { - oldPixel = pixels[y*image->width + x]; - - // NOTE: New pixel obtained by bits truncate, it would be better to round values (check ImageFormat()) - newPixel.r = oldPixel.r >> (8 - rBpp); // R bits - newPixel.g = oldPixel.g >> (8 - gBpp); // G bits - newPixel.b = oldPixel.b >> (8 - bBpp); // B bits - newPixel.a = oldPixel.a >> (8 - aBpp); // A bits (not used on dithering) - - // NOTE: Error must be computed between new and old pixel but using same number of bits! - // We want to know how much color precision we have lost... - rError = (int)oldPixel.r - (int)(newPixel.r << (8 - rBpp)); - gError = (int)oldPixel.g - (int)(newPixel.g << (8 - gBpp)); - bError = (int)oldPixel.b - (int)(newPixel.b << (8 - bBpp)); - - pixels[y*image->width + x] = newPixel; - - // NOTE: Some cases are out of the array and should be ignored - if (x < (image->width - 1)) - { - pixels[y*image->width + x+1].r = MIN((int)pixels[y*image->width + x+1].r + (int)((float)rError*7.0f/16), 0xff); - pixels[y*image->width + x+1].g = MIN((int)pixels[y*image->width + x+1].g + (int)((float)gError*7.0f/16), 0xff); - pixels[y*image->width + x+1].b = MIN((int)pixels[y*image->width + x+1].b + (int)((float)bError*7.0f/16), 0xff); - } - - if ((x > 0) && (y < (image->height - 1))) - { - pixels[(y+1)*image->width + x-1].r = MIN((int)pixels[(y+1)*image->width + x-1].r + (int)((float)rError*3.0f/16), 0xff); - pixels[(y+1)*image->width + x-1].g = MIN((int)pixels[(y+1)*image->width + x-1].g + (int)((float)gError*3.0f/16), 0xff); - pixels[(y+1)*image->width + x-1].b = MIN((int)pixels[(y+1)*image->width + x-1].b + (int)((float)bError*3.0f/16), 0xff); - } - - if (y < (image->height - 1)) - { - pixels[(y+1)*image->width + x].r = MIN((int)pixels[(y+1)*image->width + x].r + (int)((float)rError*5.0f/16), 0xff); - pixels[(y+1)*image->width + x].g = MIN((int)pixels[(y+1)*image->width + x].g + (int)((float)gError*5.0f/16), 0xff); - pixels[(y+1)*image->width + x].b = MIN((int)pixels[(y+1)*image->width + x].b + (int)((float)bError*5.0f/16), 0xff); - } - - if ((x < (image->width - 1)) && (y < (image->height - 1))) - { - pixels[(y+1)*image->width + x+1].r = MIN((int)pixels[(y+1)*image->width + x+1].r + (int)((float)rError*1.0f/16), 0xff); - pixels[(y+1)*image->width + x+1].g = MIN((int)pixels[(y+1)*image->width + x+1].g + (int)((float)gError*1.0f/16), 0xff); - pixels[(y+1)*image->width + x+1].b = MIN((int)pixels[(y+1)*image->width + x+1].b + (int)((float)bError*1.0f/16), 0xff); - } - - rPixel = (unsigned short)newPixel.r; - gPixel = (unsigned short)newPixel.g; - bPixel = (unsigned short)newPixel.b; - aPixel = (unsigned short)newPixel.a; - - ((unsigned short *)image->data)[y*image->width + x] = (rPixel << (gBpp + bBpp + aBpp)) | (gPixel << (bBpp + aBpp)) | (bPixel << aBpp) | aPixel; - } - } - - free(pixels); - } -} - -// Modify image color: tint -void ImageColorTint(Image *image, Color color) -{ - Color *pixels = GetImageData(*image); - - float cR = (float)color.r/255; - float cG = (float)color.g/255; - float cB = (float)color.b/255; - float cA = (float)color.a/255; - - for (int y = 0; y < image->height; y++) - { - for (int x = 0; x < image->width; x++) - { - unsigned char r = 255*((float)pixels[y*image->width + x].r/255*cR); - unsigned char g = 255*((float)pixels[y*image->width + x].g/255*cG); - unsigned char b = 255*((float)pixels[y*image->width + x].b/255*cB); - unsigned char a = 255*((float)pixels[y*image->width + x].a/255*cA); - - pixels[y*image->width + x].r = r; - pixels[y*image->width + x].g = g; - pixels[y*image->width + x].b = b; - pixels[y*image->width + x].a = a; - } - } - - Image processed = LoadImageEx(pixels, image->width, image->height); - ImageFormat(&processed, image->format); - UnloadImage(*image); - free(pixels); - - image->data = processed.data; -} - -// Modify image color: invert -void ImageColorInvert(Image *image) -{ - Color *pixels = GetImageData(*image); - - for (int y = 0; y < image->height; y++) - { - for (int x = 0; x < image->width; x++) - { - pixels[y*image->width + x].r = 255 - pixels[y*image->width + x].r; - pixels[y*image->width + x].g = 255 - pixels[y*image->width + x].g; - pixels[y*image->width + x].b = 255 - pixels[y*image->width + x].b; - } - } - - Image processed = LoadImageEx(pixels, image->width, image->height); - ImageFormat(&processed, image->format); - UnloadImage(*image); - free(pixels); - - image->data = processed.data; -} - -// Modify image color: grayscale -void ImageColorGrayscale(Image *image) -{ - ImageFormat(image, UNCOMPRESSED_GRAYSCALE); -} - -// Modify image color: contrast -// NOTE: Contrast values between -100 and 100 -void ImageColorContrast(Image *image, float contrast) -{ - if (contrast < -100) contrast = -100; - if (contrast > 100) contrast = 100; - - contrast = (100.0f + contrast)/100.0f; - contrast *= contrast; - - Color *pixels = GetImageData(*image); - - for (int y = 0; y < image->height; y++) - { - for (int x = 0; x < image->width; x++) - { - float pR = (float)pixels[y*image->width + x].r/255.0f; - pR -= 0.5; - pR *= contrast; - pR += 0.5; - pR *= 255; - if (pR < 0) pR = 0; - if (pR > 255) pR = 255; - - float pG = (float)pixels[y*image->width + x].g/255.0f; - pG -= 0.5; - pG *= contrast; - pG += 0.5; - pG *= 255; - if (pG < 0) pG = 0; - if (pG > 255) pG = 255; - - float pB = (float)pixels[y*image->width + x].b/255.0f; - pB -= 0.5; - pB *= contrast; - pB += 0.5; - pB *= 255; - if (pB < 0) pB = 0; - if (pB > 255) pB = 255; - - pixels[y*image->width + x].r = (unsigned char)pR; - pixels[y*image->width + x].g = (unsigned char)pG; - pixels[y*image->width + x].b = (unsigned char)pB; - } - } - - Image processed = LoadImageEx(pixels, image->width, image->height); - ImageFormat(&processed, image->format); - UnloadImage(*image); - free(pixels); - - image->data = processed.data; -} - -// Modify image color: brightness -// NOTE: Brightness values between -255 and 255 -void ImageColorBrightness(Image *image, int brightness) -{ - if (brightness < -255) brightness = -255; - if (brightness > 255) brightness = 255; - - Color *pixels = GetImageData(*image); - - for (int y = 0; y < image->height; y++) - { - for (int x = 0; x < image->width; x++) - { - int cR = pixels[y*image->width + x].r + brightness; - int cG = pixels[y*image->width + x].g + brightness; - int cB = pixels[y*image->width + x].b + brightness; - - if (cR < 0) cR = 1; - if (cR > 255) cR = 255; - - if (cG < 0) cG = 1; - if (cG > 255) cG = 255; - - if (cB < 0) cB = 1; - if (cB > 255) cB = 255; - - pixels[y*image->width + x].r = (unsigned char)cR; - pixels[y*image->width + x].g = (unsigned char)cG; - pixels[y*image->width + x].b = (unsigned char)cB; - } - } - - Image processed = LoadImageEx(pixels, image->width, image->height); - ImageFormat(&processed, image->format); - UnloadImage(*image); - free(pixels); - - image->data = processed.data; -} -#endif // SUPPORT_IMAGE_MANIPULATION - -#if defined(SUPPORT_IMAGE_GENERATION) -// Generate image: vertical gradient -Image GenImageGradientV(int width, int height, Color top, Color bottom) -{ - Color *pixels = (Color *)malloc(width*height*sizeof(Color)); - - for (int j = 0; j < height; j++) - { - float factor = (float)j/(float)height; - for (int i = 0; i < width; i++) - { - pixels[j*width + i].r = (int)((float)bottom.r*factor + (float)top.r*(1.f - factor)); - pixels[j*width + i].g = (int)((float)bottom.g*factor + (float)top.g*(1.f - factor)); - pixels[j*width + i].b = (int)((float)bottom.b*factor + (float)top.b*(1.f - factor)); - pixels[j*width + i].a = (int)((float)bottom.a*factor + (float)top.a*(1.f - factor)); - } - } - - Image image = LoadImageEx(pixels, width, height); - free(pixels); - - return image; -} - -// Generate image: horizontal gradient -Image GenImageGradientH(int width, int height, Color left, Color right) -{ - Color *pixels = (Color *)malloc(width*height*sizeof(Color)); - - for (int i = 0; i < width; i++) - { - float factor = (float)i/(float)width; - for (int j = 0; j < height; j++) - { - pixels[j*width + i].r = (int)((float)right.r*factor + (float)left.r*(1.f - factor)); - pixels[j*width + i].g = (int)((float)right.g*factor + (float)left.g*(1.f - factor)); - pixels[j*width + i].b = (int)((float)right.b*factor + (float)left.b*(1.f - factor)); - pixels[j*width + i].a = (int)((float)right.a*factor + (float)left.a*(1.f - factor)); - } - } - - Image image = LoadImageEx(pixels, width, height); - free(pixels); - - return image; -} - -// Generate image: radial gradient -Image GenImageGradientRadial(int width, int height, float density, Color inner, Color outer) -{ - Color *pixels = (Color *)malloc(width*height*sizeof(Color)); - float radius = (width < height) ? (float)width/2.0f : (float)height/2.0f; - - float centerX = (float)width/2.0f; - float centerY = (float)height/2.0f; - - for (int y = 0; y < height; y++) - { - for (int x = 0; x < width; x++) - { - float dist = hypotf((float)x - centerX, (float)y - centerY); - float factor = (dist - radius*density)/(radius*(1.0f - density)); - - factor = fmax(factor, 0.f); - factor = fmin(factor, 1.f); // dist can be bigger than radius so we have to check - - pixels[y*width + x].r = (int)((float)outer.r*factor + (float)inner.r*(1.0f - factor)); - pixels[y*width + x].g = (int)((float)outer.g*factor + (float)inner.g*(1.0f - factor)); - pixels[y*width + x].b = (int)((float)outer.b*factor + (float)inner.b*(1.0f - factor)); - pixels[y*width + x].a = (int)((float)outer.a*factor + (float)inner.a*(1.0f - factor)); - } - } - - Image image = LoadImageEx(pixels, width, height); - free(pixels); - - return image; -} - -// Generate image: checked -Image GenImageChecked(int width, int height, int checksX, int checksY, Color col1, Color col2) -{ - Color *pixels = (Color *)malloc(width*height*sizeof(Color)); - - for (int y = 0; y < height; y++) - { - for (int x = 0; x < width; x++) - { - if ((x/checksX + y/checksY)%2 == 0) pixels[y*width + x] = col1; - else pixels[y*width + x] = col2; - } - } - - Image image = LoadImageEx(pixels, width, height); - free(pixels); - - return image; -} - -// Generate image: white noise -Image GenImageWhiteNoise(int width, int height, float factor) -{ - Color *pixels = (Color *)malloc(width*height*sizeof(Color)); - - for (int i = 0; i < width*height; i++) - { - if (GetRandomValue(0, 99) < (int)(factor*100.0f)) pixels[i] = WHITE; - else pixels[i] = BLACK; - } - - Image image = LoadImageEx(pixels, width, height); - free(pixels); - - return image; -} - -// Generate image: perlin noise -Image GenImagePerlinNoise(int width, int height, float scale) -{ - Color *pixels = (Color *)malloc(width*height*sizeof(Color)); - - for (int y = 0; y < height; y++) - { - for (int x = 0; x < width; x++) - { - float nx = (float)x*scale/(float)width; - float ny = (float)y*scale/(float)height; - - // we need to translate the data from [-1; 1] to [0; 1] - float p = (stb_perlin_fbm_noise3(nx, ny, 1.0f, 2.0f, 0.5f, 6, 0, 0, 0) + 1.0f) / 2.0f; - - int intensity = (int)(p * 255.0f); - pixels[y*width + x] = (Color){intensity, intensity, intensity, 255}; - } - } - - Image image = LoadImageEx(pixels, width, height); - free(pixels); - - return image; -} - -// Generate image: cellular algorithm. Bigger tileSize means bigger cells -Image GenImageCellular(int width, int height, int tileSize) -{ - Color *pixels = (Color *)malloc(width*height*sizeof(Color)); - - int seedsPerRow = width/tileSize; - int seedsPerCol = height/tileSize; - int seedsCount = seedsPerRow * seedsPerCol; - - Vector2 *seeds = (Vector2 *)malloc(seedsCount*sizeof(Vector2)); - - for (int i = 0; i < seedsCount; i++) - { - int y = (i/seedsPerRow)*tileSize + GetRandomValue(0, tileSize - 1); - int x = (i%seedsPerRow)*tileSize + GetRandomValue(0, tileSize - 1); - seeds[i] = (Vector2){x, y}; - } - - for (int y = 0; y < height; y++) - { - int tileY = y/tileSize; - - for (int x = 0; x < width; x++) - { - int tileX = x/tileSize; - - float minDistance = strtod("Inf", NULL); - - // Check all adjacent tiles - for (int i = -1; i < 2; i++) - { - if ((tileX + i < 0) || (tileX + i >= seedsPerRow)) continue; - - for (int j = -1; j < 2; j++) - { - if ((tileY + j < 0) || (tileY + j >= seedsPerCol)) continue; - - Vector2 neighborSeed = seeds[(tileY + j)*seedsPerRow + tileX + i]; - - float dist = hypot(x - (int)neighborSeed.x, y - (int)neighborSeed.y); - minDistance = fmin(minDistance, dist); - } - } - - // I made this up but it seems to give good results at all tile sizes - int intensity = (int)(minDistance*256.0f/tileSize); - if (intensity > 255) intensity = 255; - - pixels[y*width + x] = (Color){ intensity, intensity, intensity, 255 }; - } - } - - free(seeds); - - Image image = LoadImageEx(pixels, width, height); - free(pixels); - - return image; -} -#endif // SUPPORT_IMAGE_GENERATION - -// Generate GPU mipmaps for a texture -void GenTextureMipmaps(Texture2D *texture) -{ -#if PLATFORM_WEB - // Calculate next power-of-two values - int potWidth = (int)powf(2, ceilf(logf((float)texture->width)/logf(2))); - int potHeight = (int)powf(2, ceilf(logf((float)texture->height)/logf(2))); - - // Check if texture is POT - if ((potWidth != texture->width) || (potHeight != texture->height)) - { - TraceLog(LOG_WARNING, "Limited NPOT support, no mipmaps available for NPOT textures"); - } - else rlGenerateMipmaps(texture); -#else - rlGenerateMipmaps(texture); -#endif -} - -// Set texture scaling filter mode -void SetTextureFilter(Texture2D texture, int filterMode) -{ - switch (filterMode) - { - case FILTER_POINT: - { - if (texture.mipmaps > 1) - { - // RL_FILTER_MIP_NEAREST - tex filter: POINT, mipmaps filter: POINT (sharp switching between mipmaps) - rlTextureParameters(texture.id, RL_TEXTURE_MIN_FILTER, RL_FILTER_MIP_NEAREST); - - // RL_FILTER_NEAREST - tex filter: POINT (no filter), no mipmaps - rlTextureParameters(texture.id, RL_TEXTURE_MAG_FILTER, RL_FILTER_NEAREST); - } - else - { - // RL_FILTER_NEAREST - tex filter: POINT (no filter), no mipmaps - rlTextureParameters(texture.id, RL_TEXTURE_MIN_FILTER, RL_FILTER_NEAREST); - rlTextureParameters(texture.id, RL_TEXTURE_MAG_FILTER, RL_FILTER_NEAREST); - } - } break; - case FILTER_BILINEAR: - { - if (texture.mipmaps > 1) - { - // RL_FILTER_LINEAR_MIP_NEAREST - tex filter: BILINEAR, mipmaps filter: POINT (sharp switching between mipmaps) - // Alternative: RL_FILTER_NEAREST_MIP_LINEAR - tex filter: POINT, mipmaps filter: BILINEAR (smooth transition between mipmaps) - rlTextureParameters(texture.id, RL_TEXTURE_MIN_FILTER, RL_FILTER_LINEAR_MIP_NEAREST); - - // RL_FILTER_LINEAR - tex filter: BILINEAR, no mipmaps - rlTextureParameters(texture.id, RL_TEXTURE_MAG_FILTER, RL_FILTER_LINEAR); - } - else - { - // RL_FILTER_LINEAR - tex filter: BILINEAR, no mipmaps - rlTextureParameters(texture.id, RL_TEXTURE_MIN_FILTER, RL_FILTER_LINEAR); - rlTextureParameters(texture.id, RL_TEXTURE_MAG_FILTER, RL_FILTER_LINEAR); - } - } break; - case FILTER_TRILINEAR: - { - if (texture.mipmaps > 1) - { - // RL_FILTER_MIP_LINEAR - tex filter: BILINEAR, mipmaps filter: BILINEAR (smooth transition between mipmaps) - rlTextureParameters(texture.id, RL_TEXTURE_MIN_FILTER, RL_FILTER_MIP_LINEAR); - - // RL_FILTER_LINEAR - tex filter: BILINEAR, no mipmaps - rlTextureParameters(texture.id, RL_TEXTURE_MAG_FILTER, RL_FILTER_LINEAR); - } - else - { - TraceLog(LOG_WARNING, "[TEX ID %i] No mipmaps available for TRILINEAR texture filtering", texture.id); - - // RL_FILTER_LINEAR - tex filter: BILINEAR, no mipmaps - rlTextureParameters(texture.id, RL_TEXTURE_MIN_FILTER, RL_FILTER_LINEAR); - rlTextureParameters(texture.id, RL_TEXTURE_MAG_FILTER, RL_FILTER_LINEAR); - } - } break; - case FILTER_ANISOTROPIC_4X: rlTextureParameters(texture.id, RL_TEXTURE_ANISOTROPIC_FILTER, 4); break; - case FILTER_ANISOTROPIC_8X: rlTextureParameters(texture.id, RL_TEXTURE_ANISOTROPIC_FILTER, 8); break; - case FILTER_ANISOTROPIC_16X: rlTextureParameters(texture.id, RL_TEXTURE_ANISOTROPIC_FILTER, 16); break; - default: break; - } -} - -// Set texture wrapping mode -void SetTextureWrap(Texture2D texture, int wrapMode) -{ - switch (wrapMode) - { - case WRAP_REPEAT: - { - rlTextureParameters(texture.id, RL_TEXTURE_WRAP_S, RL_WRAP_REPEAT); - rlTextureParameters(texture.id, RL_TEXTURE_WRAP_T, RL_WRAP_REPEAT); - } break; - case WRAP_CLAMP: - { - rlTextureParameters(texture.id, RL_TEXTURE_WRAP_S, RL_WRAP_CLAMP); - rlTextureParameters(texture.id, RL_TEXTURE_WRAP_T, RL_WRAP_CLAMP); - } break; - case WRAP_MIRROR: - { - rlTextureParameters(texture.id, RL_TEXTURE_WRAP_S, RL_WRAP_CLAMP_MIRROR); - rlTextureParameters(texture.id, RL_TEXTURE_WRAP_T, RL_WRAP_CLAMP_MIRROR); - } break; - default: break; - } -} - -// Draw a Texture2D -void DrawTexture(Texture2D texture, int posX, int posY, Color tint) -{ - DrawTextureEx(texture, (Vector2){ (float)posX, (float)posY }, 0.0f, 1.0f, tint); -} - -// Draw a Texture2D with position defined as Vector2 -void DrawTextureV(Texture2D texture, Vector2 position, Color tint) -{ - DrawTextureEx(texture, position, 0, 1.0f, tint); -} - -// Draw a Texture2D with extended parameters -void DrawTextureEx(Texture2D texture, Vector2 position, float rotation, float scale, Color tint) -{ - Rectangle sourceRec = { 0, 0, texture.width, texture.height }; - Rectangle destRec = { (int)position.x, (int)position.y, texture.width*scale, texture.height*scale }; - Vector2 origin = { 0, 0 }; - - DrawTexturePro(texture, sourceRec, destRec, origin, rotation, tint); -} - -// Draw a part of a texture (defined by a rectangle) -void DrawTextureRec(Texture2D texture, Rectangle sourceRec, Vector2 position, Color tint) -{ - Rectangle destRec = { (int)position.x, (int)position.y, abs(sourceRec.width), abs(sourceRec.height) }; - Vector2 origin = { 0, 0 }; - - DrawTexturePro(texture, sourceRec, destRec, origin, 0.0f, tint); -} - -// Draw a part of a texture (defined by a rectangle) with 'pro' parameters -// NOTE: origin is relative to destination rectangle size -void DrawTexturePro(Texture2D texture, Rectangle sourceRec, Rectangle destRec, Vector2 origin, float rotation, Color tint) -{ - // Check if texture is valid - if (texture.id > 0) - { - if (sourceRec.width < 0) sourceRec.x -= sourceRec.width; - if (sourceRec.height < 0) sourceRec.y -= sourceRec.height; - - rlEnableTexture(texture.id); - - rlPushMatrix(); - rlTranslatef((float)destRec.x, (float)destRec.y, 0); - rlRotatef(rotation, 0, 0, 1); - rlTranslatef(-origin.x, -origin.y, 0); - - rlBegin(RL_QUADS); - rlColor4ub(tint.r, tint.g, tint.b, tint.a); - rlNormal3f(0.0f, 0.0f, 1.0f); // Normal vector pointing towards viewer - - // Bottom-left corner for texture and quad - rlTexCoord2f((float)sourceRec.x/texture.width, (float)sourceRec.y/texture.height); - rlVertex2f(0.0f, 0.0f); - - // Bottom-right corner for texture and quad - rlTexCoord2f((float)sourceRec.x/texture.width, (float)(sourceRec.y + sourceRec.height)/texture.height); - rlVertex2f(0.0f, (float)destRec.height); - - // Top-right corner for texture and quad - rlTexCoord2f((float)(sourceRec.x + sourceRec.width)/texture.width, (float)(sourceRec.y + sourceRec.height)/texture.height); - rlVertex2f((float)destRec.width, (float)destRec.height); - - // Top-left corner for texture and quad - rlTexCoord2f((float)(sourceRec.x + sourceRec.width)/texture.width, (float)sourceRec.y/texture.height); - rlVertex2f((float)destRec.width, 0.0f); - rlEnd(); - rlPopMatrix(); - - rlDisableTexture(); - } -} - -//---------------------------------------------------------------------------------- -// Module specific Functions Definition -//---------------------------------------------------------------------------------- - -#if defined(SUPPORT_FILEFORMAT_DDS) -// Loading DDS image data (compressed or uncompressed) -static Image LoadDDS(const char *fileName) -{ - // Required extension: - // GL_EXT_texture_compression_s3tc - - // Supported tokens (defined by extensions) - // GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0x83F0 - // GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1 - // GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2 - // GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3 - - #define FOURCC_DXT1 0x31545844 // Equivalent to "DXT1" in ASCII - #define FOURCC_DXT3 0x33545844 // Equivalent to "DXT3" in ASCII - #define FOURCC_DXT5 0x35545844 // Equivalent to "DXT5" in ASCII - - // DDS Pixel Format - typedef struct { - unsigned int size; - unsigned int flags; - unsigned int fourCC; - unsigned int rgbBitCount; - unsigned int rBitMask; - unsigned int gBitMask; - unsigned int bBitMask; - unsigned int aBitMask; - } DDSPixelFormat; - - // DDS Header (124 bytes) - typedef struct { - unsigned int size; - unsigned int flags; - unsigned int height; - unsigned int width; - unsigned int pitchOrLinearSize; - unsigned int depth; - unsigned int mipmapCount; - unsigned int reserved1[11]; - DDSPixelFormat ddspf; - unsigned int caps; - unsigned int caps2; - unsigned int caps3; - unsigned int caps4; - unsigned int reserved2; - } DDSHeader; - - Image image = { 0 }; - - FILE *ddsFile = fopen(fileName, "rb"); - - if (ddsFile == NULL) - { - TraceLog(LOG_WARNING, "[%s] DDS file could not be opened", fileName); - } - else - { - // Verify the type of file - char filecode[4]; - - fread(filecode, 4, 1, ddsFile); - - if (strncmp(filecode, "DDS ", 4) != 0) - { - TraceLog(LOG_WARNING, "[%s] DDS file does not seem to be a valid image", fileName); - } - else - { - DDSHeader ddsHeader; - - // Get the image header - fread(&ddsHeader, sizeof(DDSHeader), 1, ddsFile); - - TraceLog(LOG_DEBUG, "[%s] DDS file header size: %i", fileName, sizeof(DDSHeader)); - TraceLog(LOG_DEBUG, "[%s] DDS file pixel format size: %i", fileName, ddsHeader.ddspf.size); - TraceLog(LOG_DEBUG, "[%s] DDS file pixel format flags: 0x%x", fileName, ddsHeader.ddspf.flags); - TraceLog(LOG_DEBUG, "[%s] DDS file format: 0x%x", fileName, ddsHeader.ddspf.fourCC); - TraceLog(LOG_DEBUG, "[%s] DDS file bit count: 0x%x", fileName, ddsHeader.ddspf.rgbBitCount); - - image.width = ddsHeader.width; - image.height = ddsHeader.height; - - if (ddsHeader.mipmapCount == 0) image.mipmaps = 1; // Parameter not used - else image.mipmaps = ddsHeader.mipmapCount; - - if (ddsHeader.ddspf.rgbBitCount == 16) // 16bit mode, no compressed - { - if (ddsHeader.ddspf.flags == 0x40) // no alpha channel - { - image.data = (unsigned short *)malloc(image.width*image.height*sizeof(unsigned short)); - fread(image.data, image.width*image.height*sizeof(unsigned short), 1, ddsFile); - - image.format = UNCOMPRESSED_R5G6B5; - } - else if (ddsHeader.ddspf.flags == 0x41) // with alpha channel - { - if (ddsHeader.ddspf.aBitMask == 0x8000) // 1bit alpha - { - image.data = (unsigned short *)malloc(image.width*image.height*sizeof(unsigned short)); - fread(image.data, image.width*image.height*sizeof(unsigned short), 1, ddsFile); - - unsigned char alpha = 0; - - // NOTE: Data comes as A1R5G5B5, it must be reordered to R5G5B5A1 - for (int i = 0; i < image.width*image.height; i++) - { - alpha = ((unsigned short *)image.data)[i] >> 15; - ((unsigned short *)image.data)[i] = ((unsigned short *)image.data)[i] << 1; - ((unsigned short *)image.data)[i] += alpha; - } - - image.format = UNCOMPRESSED_R5G5B5A1; - } - else if (ddsHeader.ddspf.aBitMask == 0xf000) // 4bit alpha - { - image.data = (unsigned short *)malloc(image.width*image.height*sizeof(unsigned short)); - fread(image.data, image.width*image.height*sizeof(unsigned short), 1, ddsFile); - - unsigned char alpha = 0; - - // NOTE: Data comes as A4R4G4B4, it must be reordered R4G4B4A4 - for (int i = 0; i < image.width*image.height; i++) - { - alpha = ((unsigned short *)image.data)[i] >> 12; - ((unsigned short *)image.data)[i] = ((unsigned short *)image.data)[i] << 4; - ((unsigned short *)image.data)[i] += alpha; - } - - image.format = UNCOMPRESSED_R4G4B4A4; - } - } - } - if (ddsHeader.ddspf.flags == 0x40 && ddsHeader.ddspf.rgbBitCount == 24) // DDS_RGB, no compressed - { - // NOTE: not sure if this case exists... - image.data = (unsigned char *)malloc(image.width*image.height*3*sizeof(unsigned char)); - fread(image.data, image.width*image.height*3, 1, ddsFile); - - image.format = UNCOMPRESSED_R8G8B8; - } - else if (ddsHeader.ddspf.flags == 0x41 && ddsHeader.ddspf.rgbBitCount == 32) // DDS_RGBA, no compressed - { - image.data = (unsigned char *)malloc(image.width*image.height*4*sizeof(unsigned char)); - fread(image.data, image.width*image.height*4, 1, ddsFile); - - unsigned char blue = 0; - - // NOTE: Data comes as A8R8G8B8, it must be reordered R8G8B8A8 (view next comment) - // DirecX understand ARGB as a 32bit DWORD but the actual memory byte alignment is BGRA - // So, we must realign B8G8R8A8 to R8G8B8A8 - for (int i = 0; i < image.width*image.height*4; i += 4) - { - blue = ((unsigned char *)image.data)[i]; - ((unsigned char *)image.data)[i] = ((unsigned char *)image.data)[i + 2]; - ((unsigned char *)image.data)[i + 2] = blue; - } - - image.format = UNCOMPRESSED_R8G8B8A8; - } - else if (((ddsHeader.ddspf.flags == 0x04) || (ddsHeader.ddspf.flags == 0x05)) && (ddsHeader.ddspf.fourCC > 0)) // Compressed - { - int size; // DDS image data size - - // Calculate data size, including all mipmaps - if (ddsHeader.mipmapCount > 1) size = ddsHeader.pitchOrLinearSize*2; - else size = ddsHeader.pitchOrLinearSize; - - TraceLog(LOG_DEBUG, "Pitch or linear size: %i", ddsHeader.pitchOrLinearSize); - - image.data = (unsigned char*)malloc(size*sizeof(unsigned char)); - - fread(image.data, size, 1, ddsFile); - - switch (ddsHeader.ddspf.fourCC) - { - case FOURCC_DXT1: - { - if (ddsHeader.ddspf.flags == 0x04) image.format = COMPRESSED_DXT1_RGB; - else image.format = COMPRESSED_DXT1_RGBA; - } break; - case FOURCC_DXT3: image.format = COMPRESSED_DXT3_RGBA; break; - case FOURCC_DXT5: image.format = COMPRESSED_DXT5_RGBA; break; - default: break; - } - } - } - - fclose(ddsFile); // Close file pointer - } - - return image; -} -#endif - -#if defined(SUPPORT_FILEFORMAT_PKM) -// Loading PKM image data (ETC1/ETC2 compression) -// NOTE: KTX is the standard Khronos Group compression format (ETC1/ETC2, mipmaps) -// PKM is a much simpler file format used mainly to contain a single ETC1/ETC2 compressed image (no mipmaps) -static Image LoadPKM(const char *fileName) -{ - // Required extensions: - // GL_OES_compressed_ETC1_RGB8_texture (ETC1) (OpenGL ES 2.0) - // GL_ARB_ES3_compatibility (ETC2/EAC) (OpenGL ES 3.0) - - // Supported tokens (defined by extensions) - // GL_ETC1_RGB8_OES 0x8D64 - // GL_COMPRESSED_RGB8_ETC2 0x9274 - // GL_COMPRESSED_RGBA8_ETC2_EAC 0x9278 - - // PKM file (ETC1) Header (16 bytes) - typedef struct { - char id[4]; // "PKM " - char version[2]; // "10" or "20" - unsigned short format; // Data format (big-endian) (Check list below) - unsigned short width; // Texture width (big-endian) (origWidth rounded to multiple of 4) - unsigned short height; // Texture height (big-endian) (origHeight rounded to multiple of 4) - unsigned short origWidth; // Original width (big-endian) - unsigned short origHeight; // Original height (big-endian) - } PKMHeader; - - // Formats list - // version 10: format: 0=ETC1_RGB, [1=ETC1_RGBA, 2=ETC1_RGB_MIP, 3=ETC1_RGBA_MIP] (not used) - // version 20: format: 0=ETC1_RGB, 1=ETC2_RGB, 2=ETC2_RGBA_OLD, 3=ETC2_RGBA, 4=ETC2_RGBA1, 5=ETC2_R, 6=ETC2_RG, 7=ETC2_SIGNED_R, 8=ETC2_SIGNED_R - - // NOTE: The extended width and height are the widths rounded up to a multiple of 4. - // NOTE: ETC is always 4bit per pixel (64 bit for each 4x4 block of pixels) - - Image image = { 0 }; - - FILE *pkmFile = fopen(fileName, "rb"); - - if (pkmFile == NULL) - { - TraceLog(LOG_WARNING, "[%s] PKM file could not be opened", fileName); - } - else - { - PKMHeader pkmHeader; - - // Get the image header - fread(&pkmHeader, sizeof(PKMHeader), 1, pkmFile); - - if (strncmp(pkmHeader.id, "PKM ", 4) != 0) - { - TraceLog(LOG_WARNING, "[%s] PKM file does not seem to be a valid image", fileName); - } - else - { - // NOTE: format, width and height come as big-endian, data must be swapped to little-endian - pkmHeader.format = ((pkmHeader.format & 0x00FF) << 8) | ((pkmHeader.format & 0xFF00) >> 8); - pkmHeader.width = ((pkmHeader.width & 0x00FF) << 8) | ((pkmHeader.width & 0xFF00) >> 8); - pkmHeader.height = ((pkmHeader.height & 0x00FF) << 8) | ((pkmHeader.height & 0xFF00) >> 8); - - TraceLog(LOG_DEBUG, "PKM (ETC) image width: %i", pkmHeader.width); - TraceLog(LOG_DEBUG, "PKM (ETC) image height: %i", pkmHeader.height); - TraceLog(LOG_DEBUG, "PKM (ETC) image format: %i", pkmHeader.format); - - image.width = pkmHeader.width; - image.height = pkmHeader.height; - image.mipmaps = 1; - - int bpp = 4; - if (pkmHeader.format == 3) bpp = 8; - - int size = image.width*image.height*bpp/8; // Total data size in bytes - - image.data = (unsigned char*)malloc(size*sizeof(unsigned char)); - - fread(image.data, size, 1, pkmFile); - - if (pkmHeader.format == 0) image.format = COMPRESSED_ETC1_RGB; - else if (pkmHeader.format == 1) image.format = COMPRESSED_ETC2_RGB; - else if (pkmHeader.format == 3) image.format = COMPRESSED_ETC2_EAC_RGBA; - } - - fclose(pkmFile); // Close file pointer - } - - return image; -} -#endif - -#if defined(SUPPORT_FILEFORMAT_KTX) -// Load KTX compressed image data (ETC1/ETC2 compression) -static Image LoadKTX(const char *fileName) -{ - // Required extensions: - // GL_OES_compressed_ETC1_RGB8_texture (ETC1) - // GL_ARB_ES3_compatibility (ETC2/EAC) - - // Supported tokens (defined by extensions) - // GL_ETC1_RGB8_OES 0x8D64 - // GL_COMPRESSED_RGB8_ETC2 0x9274 - // GL_COMPRESSED_RGBA8_ETC2_EAC 0x9278 - - // KTX file Header (64 bytes) - // https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/ - typedef struct { - char id[12]; // Identifier: "«KTX 11»\r\n\x1A\n" - unsigned int endianness; // Little endian: 0x01 0x02 0x03 0x04 - unsigned int glType; // For compressed textures, glType must equal 0 - unsigned int glTypeSize; // For compressed texture data, usually 1 - unsigned int glFormat; // For compressed textures is 0 - unsigned int glInternalFormat; // Compressed internal format - unsigned int glBaseInternalFormat; // Same as glFormat (RGB, RGBA, ALPHA...) - unsigned int width; // Texture image width in pixels - unsigned int height; // Texture image height in pixels - unsigned int depth; // For 2D textures is 0 - unsigned int elements; // Number of array elements, usually 0 - unsigned int faces; // Cubemap faces, for no-cubemap = 1 - unsigned int mipmapLevels; // Non-mipmapped textures = 1 - unsigned int keyValueDataSize; // Used to encode any arbitrary data... - } KTXHeader; - - // NOTE: Before start of every mipmap data block, we have: unsigned int dataSize - - Image image = { 0 }; - - FILE *ktxFile = fopen(fileName, "rb"); - - if (ktxFile == NULL) - { - TraceLog(LOG_WARNING, "[%s] KTX image file could not be opened", fileName); - } - else - { - KTXHeader ktxHeader; - - // Get the image header - fread(&ktxHeader, sizeof(KTXHeader), 1, ktxFile); - - if ((ktxHeader.id[1] != 'K') || (ktxHeader.id[2] != 'T') || (ktxHeader.id[3] != 'X') || - (ktxHeader.id[4] != ' ') || (ktxHeader.id[5] != '1') || (ktxHeader.id[6] != '1')) - { - TraceLog(LOG_WARNING, "[%s] KTX file does not seem to be a valid file", fileName); - } - else - { - image.width = ktxHeader.width; - image.height = ktxHeader.height; - image.mipmaps = ktxHeader.mipmapLevels; - - TraceLog(LOG_DEBUG, "KTX (ETC) image width: %i", ktxHeader.width); - TraceLog(LOG_DEBUG, "KTX (ETC) image height: %i", ktxHeader.height); - TraceLog(LOG_DEBUG, "KTX (ETC) image format: 0x%x", ktxHeader.glInternalFormat); - - unsigned char unused; - - if (ktxHeader.keyValueDataSize > 0) - { - for (int i = 0; i < ktxHeader.keyValueDataSize; i++) fread(&unused, sizeof(unsigned char), 1, ktxFile); - } - - int dataSize; - fread(&dataSize, sizeof(unsigned int), 1, ktxFile); - - image.data = (unsigned char*)malloc(dataSize*sizeof(unsigned char)); - - fread(image.data, dataSize, 1, ktxFile); - - if (ktxHeader.glInternalFormat == 0x8D64) image.format = COMPRESSED_ETC1_RGB; - else if (ktxHeader.glInternalFormat == 0x9274) image.format = COMPRESSED_ETC2_RGB; - else if (ktxHeader.glInternalFormat == 0x9278) image.format = COMPRESSED_ETC2_EAC_RGBA; - } - - fclose(ktxFile); // Close file pointer - } - - return image; -} -#endif - -#if defined(SUPPORT_FILEFORMAT_PVR) -// Loading PVR image data (uncompressed or PVRT compression) -// NOTE: PVR v2 not supported, use PVR v3 instead -static Image LoadPVR(const char *fileName) -{ - // Required extension: - // GL_IMG_texture_compression_pvrtc - - // Supported tokens (defined by extensions) - // GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG 0x8C00 - // GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG 0x8C02 - -#if 0 // Not used... - // PVR file v2 Header (52 bytes) - typedef struct { - unsigned int headerLength; - unsigned int height; - unsigned int width; - unsigned int numMipmaps; - unsigned int flags; - unsigned int dataLength; - unsigned int bpp; - unsigned int bitmaskRed; - unsigned int bitmaskGreen; - unsigned int bitmaskBlue; - unsigned int bitmaskAlpha; - unsigned int pvrTag; - unsigned int numSurfs; - } PVRHeaderV2; -#endif - - // PVR file v3 Header (52 bytes) - // NOTE: After it could be metadata (15 bytes?) - typedef struct { - char id[4]; - unsigned int flags; - unsigned char channels[4]; // pixelFormat high part - unsigned char channelDepth[4]; // pixelFormat low part - unsigned int colourSpace; - unsigned int channelType; - unsigned int height; - unsigned int width; - unsigned int depth; - unsigned int numSurfaces; - unsigned int numFaces; - unsigned int numMipmaps; - unsigned int metaDataSize; - } PVRHeaderV3; - -#if 0 // Not used... - // Metadata (usually 15 bytes) - typedef struct { - unsigned int devFOURCC; - unsigned int key; - unsigned int dataSize; // Not used? - unsigned char *data; // Not used? - } PVRMetadata; -#endif - - Image image = { 0 }; - - FILE *pvrFile = fopen(fileName, "rb"); - - if (pvrFile == NULL) - { - TraceLog(LOG_WARNING, "[%s] PVR file could not be opened", fileName); - } - else - { - // Check PVR image version - unsigned char pvrVersion = 0; - fread(&pvrVersion, sizeof(unsigned char), 1, pvrFile); - fseek(pvrFile, 0, SEEK_SET); - - // Load different PVR data formats - if (pvrVersion == 0x50) - { - PVRHeaderV3 pvrHeader; - - // Get PVR image header - fread(&pvrHeader, sizeof(PVRHeaderV3), 1, pvrFile); - - if ((pvrHeader.id[0] != 'P') || (pvrHeader.id[1] != 'V') || (pvrHeader.id[2] != 'R') || (pvrHeader.id[3] != 3)) - { - TraceLog(LOG_WARNING, "[%s] PVR file does not seem to be a valid image", fileName); - } - else - { - image.width = pvrHeader.width; - image.height = pvrHeader.height; - image.mipmaps = pvrHeader.numMipmaps; - - // Check data format - if (((pvrHeader.channels[0] == 'l') && (pvrHeader.channels[1] == 0)) && (pvrHeader.channelDepth[0] == 8)) - image.format = UNCOMPRESSED_GRAYSCALE; - else if (((pvrHeader.channels[0] == 'l') && (pvrHeader.channels[1] == 'a')) && ((pvrHeader.channelDepth[0] == 8) && (pvrHeader.channelDepth[1] == 8))) - image.format = UNCOMPRESSED_GRAY_ALPHA; - else if ((pvrHeader.channels[0] == 'r') && (pvrHeader.channels[1] == 'g') && (pvrHeader.channels[2] == 'b')) - { - if (pvrHeader.channels[3] == 'a') - { - if ((pvrHeader.channelDepth[0] == 5) && (pvrHeader.channelDepth[1] == 5) && (pvrHeader.channelDepth[2] == 5) && (pvrHeader.channelDepth[3] == 1)) - image.format = UNCOMPRESSED_R5G5B5A1; - else if ((pvrHeader.channelDepth[0] == 4) && (pvrHeader.channelDepth[1] == 4) && (pvrHeader.channelDepth[2] == 4) && (pvrHeader.channelDepth[3] == 4)) - image.format = UNCOMPRESSED_R4G4B4A4; - else if ((pvrHeader.channelDepth[0] == 8) && (pvrHeader.channelDepth[1] == 8) && (pvrHeader.channelDepth[2] == 8) && (pvrHeader.channelDepth[3] == 8)) - image.format = UNCOMPRESSED_R8G8B8A8; - } - else if (pvrHeader.channels[3] == 0) - { - if ((pvrHeader.channelDepth[0] == 5) && (pvrHeader.channelDepth[1] == 6) && (pvrHeader.channelDepth[2] == 5)) image.format = UNCOMPRESSED_R5G6B5; - else if ((pvrHeader.channelDepth[0] == 8) && (pvrHeader.channelDepth[1] == 8) && (pvrHeader.channelDepth[2] == 8)) image.format = UNCOMPRESSED_R8G8B8; - } - } - else if (pvrHeader.channels[0] == 2) image.format = COMPRESSED_PVRT_RGB; - else if (pvrHeader.channels[0] == 3) image.format = COMPRESSED_PVRT_RGBA; - - // Skip meta data header - unsigned char unused = 0; - for (int i = 0; i < pvrHeader.metaDataSize; i++) fread(&unused, sizeof(unsigned char), 1, pvrFile); - - // Calculate data size (depends on format) - int bpp = 0; - - switch (image.format) - { - case UNCOMPRESSED_GRAYSCALE: bpp = 8; break; - case UNCOMPRESSED_GRAY_ALPHA: - case UNCOMPRESSED_R5G5B5A1: - case UNCOMPRESSED_R5G6B5: - case UNCOMPRESSED_R4G4B4A4: bpp = 16; break; - case UNCOMPRESSED_R8G8B8A8: bpp = 32; break; - case UNCOMPRESSED_R8G8B8: bpp = 24; break; - case COMPRESSED_PVRT_RGB: - case COMPRESSED_PVRT_RGBA: bpp = 4; break; - default: break; - } - - int dataSize = image.width*image.height*bpp/8; // Total data size in bytes - image.data = (unsigned char*)malloc(dataSize*sizeof(unsigned char)); - - // Read data from file - fread(image.data, dataSize, 1, pvrFile); - } - } - else if (pvrVersion == 52) TraceLog(LOG_INFO, "PVR v2 not supported, update your files to PVR v3"); - - fclose(pvrFile); // Close file pointer - } - - return image; -} -#endif - -#if defined(SUPPORT_FILEFORMAT_ASTC) -// Load ASTC compressed image data (ASTC compression) -static Image LoadASTC(const char *fileName) -{ - // Required extensions: - // GL_KHR_texture_compression_astc_hdr - // GL_KHR_texture_compression_astc_ldr - - // Supported tokens (defined by extensions) - // GL_COMPRESSED_RGBA_ASTC_4x4_KHR 0x93b0 - // GL_COMPRESSED_RGBA_ASTC_8x8_KHR 0x93b7 - - // ASTC file Header (16 bytes) - typedef struct { - unsigned char id[4]; // Signature: 0x13 0xAB 0xA1 0x5C - unsigned char blockX; // Block X dimensions - unsigned char blockY; // Block Y dimensions - unsigned char blockZ; // Block Z dimensions (1 for 2D images) - unsigned char width[3]; // Image width in pixels (24bit value) - unsigned char height[3]; // Image height in pixels (24bit value) - unsigned char length[3]; // Image Z-size (1 for 2D images) - } ASTCHeader; - - Image image = { 0 }; - - FILE *astcFile = fopen(fileName, "rb"); - - if (astcFile == NULL) - { - TraceLog(LOG_WARNING, "[%s] ASTC file could not be opened", fileName); - } - else - { - ASTCHeader astcHeader; - - // Get ASTC image header - fread(&astcHeader, sizeof(ASTCHeader), 1, astcFile); - - if ((astcHeader.id[3] != 0x5c) || (astcHeader.id[2] != 0xa1) || (astcHeader.id[1] != 0xab) || (astcHeader.id[0] != 0x13)) - { - TraceLog(LOG_WARNING, "[%s] ASTC file does not seem to be a valid image", fileName); - } - else - { - // NOTE: Assuming Little Endian (could it be wrong?) - image.width = 0x00000000 | ((int)astcHeader.width[2] << 16) | ((int)astcHeader.width[1] << 8) | ((int)astcHeader.width[0]); - image.height = 0x00000000 | ((int)astcHeader.height[2] << 16) | ((int)astcHeader.height[1] << 8) | ((int)astcHeader.height[0]); - - TraceLog(LOG_DEBUG, "ASTC image width: %i", image.width); - TraceLog(LOG_DEBUG, "ASTC image height: %i", image.height); - TraceLog(LOG_DEBUG, "ASTC image blocks: %ix%i", astcHeader.blockX, astcHeader.blockY); - - image.mipmaps = 1; // NOTE: ASTC format only contains one mipmap level - - // NOTE: Each block is always stored in 128bit so we can calculate the bpp - int bpp = 128/(astcHeader.blockX*astcHeader.blockY); - - // NOTE: Currently we only support 2 blocks configurations: 4x4 and 8x8 - if ((bpp == 8) || (bpp == 2)) - { - int dataSize = image.width*image.height*bpp/8; // Data size in bytes - - image.data = (unsigned char *)malloc(dataSize*sizeof(unsigned char)); - fread(image.data, dataSize, 1, astcFile); - - if (bpp == 8) image.format = COMPRESSED_ASTC_4x4_RGBA; - else if (bpp == 2) image.format = COMPRESSED_ASTC_4x4_RGBA; - } - else TraceLog(LOG_WARNING, "[%s] ASTC block size configuration not supported", fileName); - } - - fclose(astcFile); - } - - return image; -} -#endif diff --git a/game/src/libs/raylib/utils.c b/game/src/libs/raylib/utils.c deleted file mode 100644 index 967ed91..0000000 --- a/game/src/libs/raylib/utils.c +++ /dev/null @@ -1,214 +0,0 @@ -/********************************************************************************************** -* -* raylib.utils - Some common utility functions -* -* CONFIGURATION: -* -* #define SUPPORT_SAVE_PNG (defined by default) -* Support saving image data as PNG fileformat -* NOTE: Requires stb_image_write library -* -* #define SUPPORT_SAVE_BMP -* Support saving image data as BMP fileformat -* NOTE: Requires stb_image_write library -* -* #define SUPPORT_TRACELOG -* Show TraceLog() output messages -* NOTE: By default LOG_DEBUG traces not shown -* -* #define SUPPORT_TRACELOG_DEBUG -* Show TraceLog() LOG_DEBUG messages -* -* DEPENDENCIES: -* stb_image_write - BMP/PNG writting functions -* -* -* LICENSE: zlib/libpng -* -* Copyright (c) 2014-2017 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. -* -* Permission is granted to anyone to use this software for any purpose, including commercial -* applications, and to alter it and redistribute it freely, subject to the following restrictions: -* -* 1. The origin of this software must not be misrepresented; you must not claim that you -* wrote the original software. If you use this software in a product, an acknowledgment -* in the product documentation would be appreciated but is not required. -* -* 2. Altered source versions must be plainly marked as such, and must not be misrepresented -* as being the original software. -* -* 3. This notice may not be removed or altered from any source distribution. -* -**********************************************************************************************/ - -#define SUPPORT_TRACELOG // Output tracelog messages -//#define SUPPORT_TRACELOG_DEBUG // Avoid LOG_DEBUG messages tracing - -#include "raylib.h" // WARNING: Required for: LogType enum -#include "utils.h" - -#if defined(PLATFORM_ANDROID) - #include - #include - #include -#endif - -#include // Required for: malloc(), free() -#include // Required for: fopen(), fclose(), fputc(), fwrite(), printf(), fprintf(), funopen() -#include // Required for: va_list, va_start(), vfprintf(), va_end() -#include // Required for: strlen(), strrchr(), strcmp() - -#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI) - #define STB_IMAGE_WRITE_IMPLEMENTATION - #include "external/stb_image_write.h" // Required for: stbi_write_bmp(), stbi_write_png() -#endif - -#define RRES_IMPLEMENTATION -#include "rres.h" - -//---------------------------------------------------------------------------------- -// Global Variables Definition -//---------------------------------------------------------------------------------- -#if defined(PLATFORM_ANDROID) -AAssetManager *assetManager; -#endif - -//---------------------------------------------------------------------------------- -// Module specific Functions Declaration -//---------------------------------------------------------------------------------- -#if defined(PLATFORM_ANDROID) -static int android_read(void *cookie, char *buf, int size); -static int android_write(void *cookie, const char *buf, int size); -static fpos_t android_seek(void *cookie, fpos_t offset, int whence); -static int android_close(void *cookie); -#endif - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Utilities -//---------------------------------------------------------------------------------- - -// Show trace log messages (LOG_INFO, LOG_WARNING, LOG_ERROR, LOG_DEBUG) -void TraceLog(int msgType, const char *text, ...) -{ -#if defined(SUPPORT_TRACELOG) - static char buffer[128]; - int traceDebugMsgs = 0; - -#if defined(SUPPORT_TRACELOG_DEBUG) - traceDebugMsgs = 1; -#endif - - switch(msgType) - { - case LOG_INFO: strcpy(buffer, "INFO: "); break; - case LOG_ERROR: strcpy(buffer, "ERROR: "); break; - case LOG_WARNING: strcpy(buffer, "WARNING: "); break; - case LOG_DEBUG: strcpy(buffer, "DEBUG: "); break; - default: break; - } - - strcat(buffer, text); - strcat(buffer, "\n"); - - va_list args; - va_start(args, text); - -#if defined(PLATFORM_ANDROID) - switch(msgType) - { - case LOG_INFO: __android_log_vprint(ANDROID_LOG_INFO, "raylib", buffer, args); break; - case LOG_ERROR: __android_log_vprint(ANDROID_LOG_ERROR, "raylib", buffer, args); break; - case LOG_WARNING: __android_log_vprint(ANDROID_LOG_WARN, "raylib", buffer, args); break; - case LOG_DEBUG: if (traceDebugMsgs) __android_log_vprint(ANDROID_LOG_DEBUG, "raylib", buffer, args); break; - default: break; - } -#else - if ((msgType != LOG_DEBUG) || ((msgType == LOG_DEBUG) && (traceDebugMsgs))) vprintf(buffer, args); -#endif - - va_end(args); - - if (msgType == LOG_ERROR) exit(1); // If LOG_ERROR message, exit program - -#endif // SUPPORT_TRACELOG -} - -#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI) - -#if defined(SUPPORT_SAVE_BMP) -// Creates a BMP image file from an array of pixel data -void SaveBMP(const char *fileName, unsigned char *imgData, int width, int height, int compSize) -{ - stbi_write_bmp(fileName, width, height, compSize, imgData); -} -#endif - -#if defined(SUPPORT_SAVE_PNG) -// Creates a PNG image file from an array of pixel data -void SavePNG(const char *fileName, unsigned char *imgData, int width, int height, int compSize) -{ - stbi_write_png(fileName, width, height, compSize, imgData, width*compSize); -} -#endif -#endif - -// Keep track of memory allocated -// NOTE: mallocType defines the type of data allocated -/* -void RecordMalloc(int mallocType, int mallocSize, const char *msg) -{ - // TODO: Investigate how to record memory allocation data... - // Maybe creating my own malloc function... -} -*/ - -#if defined(PLATFORM_ANDROID) -// Initialize asset manager from android app -void InitAssetManager(AAssetManager *manager) -{ - assetManager = manager; -} - -// Replacement for fopen -FILE *android_fopen(const char *fileName, const char *mode) -{ - if (mode[0] == 'w') return NULL; - - AAsset *asset = AAssetManager_open(assetManager, fileName, 0); - - if (!asset) return NULL; - - return funopen(asset, android_read, android_write, android_seek, android_close); -} -#endif - -//---------------------------------------------------------------------------------- -// Module specific Functions Definition -//---------------------------------------------------------------------------------- -#if defined(PLATFORM_ANDROID) -static int android_read(void *cookie, char *buf, int size) -{ - return AAsset_read((AAsset *)cookie, buf, size); -} - -static int android_write(void *cookie, const char *buf, int size) -{ - TraceLog(LOG_ERROR, "Can't provide write access to the APK"); - - return EACCES; -} - -static fpos_t android_seek(void *cookie, fpos_t offset, int whence) -{ - return AAsset_seek((AAsset *)cookie, offset, whence); -} - -static int android_close(void *cookie) -{ - AAsset_close((AAsset *)cookie); - return 0; -} -#endif diff --git a/game/src/libs/raylib/utils.h b/game/src/libs/raylib/utils.h deleted file mode 100644 index 64592c7..0000000 --- a/game/src/libs/raylib/utils.h +++ /dev/null @@ -1,79 +0,0 @@ -/********************************************************************************************** -* -* raylib.utils - Some common utility functions -* -* -* LICENSE: zlib/libpng -* -* Copyright (c) 2014-2017 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. -* -* Permission is granted to anyone to use this software for any purpose, including commercial -* applications, and to alter it and redistribute it freely, subject to the following restrictions: -* -* 1. The origin of this software must not be misrepresented; you must not claim that you -* wrote the original software. If you use this software in a product, an acknowledgment -* in the product documentation would be appreciated but is not required. -* -* 2. Altered source versions must be plainly marked as such, and must not be misrepresented -* as being the original software. -* -* 3. This notice may not be removed or altered from any source distribution. -* -**********************************************************************************************/ - -#ifndef UTILS_H -#define UTILS_H - -#if defined(PLATFORM_ANDROID) - #include // Required for: FILE - #include // Required for: AAssetManager -#endif - -#include "rres.h" - -#define SUPPORT_SAVE_PNG - -//---------------------------------------------------------------------------------- -// Some basic Defines -//---------------------------------------------------------------------------------- -#if defined(PLATFORM_ANDROID) - #define fopen(name, mode) android_fopen(name, mode) -#endif - -//---------------------------------------------------------------------------------- -// Types and Structures Definition -//---------------------------------------------------------------------------------- -#ifdef __cplusplus -extern "C" { // Prevents name mangling of functions -#endif - -//---------------------------------------------------------------------------------- -// Global Variables Definition -//---------------------------------------------------------------------------------- -// Nop... - -//---------------------------------------------------------------------------------- -// Module Functions Declaration -//---------------------------------------------------------------------------------- -#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI) -#if defined(SUPPORT_SAVE_BMP) -void SaveBMP(const char *fileName, unsigned char *imgData, int width, int height, int compSize); -#endif -#if defined(SUPPORT_SAVE_PNG) -void SavePNG(const char *fileName, unsigned char *imgData, int width, int height, int compSize); -#endif -#endif - -#if defined(PLATFORM_ANDROID) -void InitAssetManager(AAssetManager *manager); // Initialize asset manager from android app -FILE *android_fopen(const char *fileName, const char *mode); // Replacement for fopen() -#endif - -#ifdef __cplusplus -} -#endif - -#endif // UTILS_H \ No newline at end of file