aboutsummaryrefslogtreecommitdiff
path: root/test/140_appendsolution/appendsolution_tests.c
diff options
context:
space:
mode:
Diffstat (limited to 'test/140_appendsolution/appendsolution_tests.c')
0 files changed, 0 insertions, 0 deletions

Generated with cgit - Back to sebastiano.tronto.net

an class='decoration'>HEADmaster
Diffstat (limited to 'raylib/src')
-rw-r--r--raylib/src/CMakeLists.txt132
-rw-r--r--raylib/src/LICENSE16
-rw-r--r--raylib/src/Makefile873
-rw-r--r--raylib/src/config.h303
-rw-r--r--raylib/src/external/RGFW.h9015
-rw-r--r--raylib/src/external/cgltf.h7081
-rw-r--r--raylib/src/external/dirent.h183
-rw-r--r--raylib/src/external/dr_flac.h12536
-rw-r--r--raylib/src/external/dr_mp3.h4837
-rw-r--r--raylib/src/external/dr_wav.h8815
-rw-r--r--raylib/src/external/glad.h8682
-rw-r--r--raylib/src/external/glad_gles2.h4774
-rw-r--r--raylib/src/external/glfw/.mailmap10
-rw-r--r--raylib/src/external/glfw/CMake/GenerateMappings.cmake48
-rw-r--r--raylib/src/external/glfw/CMake/Info.plist.in38
-rw-r--r--raylib/src/external/glfw/CMake/cmake_uninstall.cmake.in29
-rw-r--r--raylib/src/external/glfw/CMake/glfw3.pc.in13
-rw-r--r--raylib/src/external/glfw/CMake/glfw3Config.cmake.in3
-rw-r--r--raylib/src/external/glfw/CMake/i686-w64-mingw32-clang.cmake13
-rw-r--r--raylib/src/external/glfw/CMake/i686-w64-mingw32.cmake13
-rw-r--r--raylib/src/external/glfw/CMake/modules/FindEpollShim.cmake17
-rw-r--r--raylib/src/external/glfw/CMake/modules/FindOSMesa.cmake18
-rw-r--r--raylib/src/external/glfw/CMake/x86_64-w64-mingw32-clang.cmake13
-rw-r--r--raylib/src/external/glfw/CMake/x86_64-w64-mingw32.cmake13
-rw-r--r--raylib/src/external/glfw/CMakeLists.txt165
-rw-r--r--raylib/src/external/glfw/CONTRIBUTORS.md297
-rw-r--r--raylib/src/external/glfw/LICENSE.md23
-rw-r--r--raylib/src/external/glfw/README.md18
-rw-r--r--raylib/src/external/glfw/deps/getopt.c230
-rw-r--r--raylib/src/external/glfw/deps/getopt.h57
-rw-r--r--raylib/src/external/glfw/deps/glad/gl.h5996
-rw-r--r--raylib/src/external/glfw/deps/glad/gles2.h1805
-rw-r--r--raylib/src/external/glfw/deps/glad/vulkan.h6330
-rw-r--r--raylib/src/external/glfw/deps/mingw/_mingw_dxhelper.h117
-rw-r--r--raylib/src/external/glfw/deps/mingw/dinput.h2467
-rw-r--r--raylib/src/external/glfw/deps/mingw/xinput.h239
-rw-r--r--raylib/src/external/glfw/deps/wayland/fractional-scale-v1.xml102
-rw-r--r--raylib/src/external/glfw/deps/wayland/idle-inhibit-unstable-v1.xml83
-rw-r--r--raylib/src/external/glfw/deps/wayland/pointer-constraints-unstable-v1.xml339
-rw-r--r--raylib/src/external/glfw/deps/wayland/relative-pointer-unstable-v1.xml136
-rw-r--r--raylib/src/external/glfw/deps/wayland/viewporter.xml180
-rw-r--r--raylib/src/external/glfw/deps/wayland/wayland.xml3151
-rw-r--r--raylib/src/external/glfw/deps/wayland/xdg-activation-v1.xml200
-rw-r--r--raylib/src/external/glfw/deps/wayland/xdg-decoration-unstable-v1.xml156
-rw-r--r--raylib/src/external/glfw/deps/wayland/xdg-shell.xml1370
-rw-r--r--raylib/src/external/glfw/include/GLFW/glfw3.h6547
-rw-r--r--raylib/src/external/glfw/include/GLFW/glfw3native.h663
-rw-r--r--raylib/src/external/glfw/src/CMakeLists.txt368
-rw-r--r--raylib/src/external/glfw/src/cocoa_init.m696
-rw-r--r--raylib/src/external/glfw/src/cocoa_joystick.h49
-rw-r--r--raylib/src/external/glfw/src/cocoa_joystick.m485
-rw-r--r--raylib/src/external/glfw/src/cocoa_monitor.m644
-rw-r--r--raylib/src/external/glfw/src/cocoa_platform.h302
-rw-r--r--raylib/src/external/glfw/src/cocoa_time.c57
-rw-r--r--raylib/src/external/glfw/src/cocoa_time.h35
-rw-r--r--raylib/src/external/glfw/src/cocoa_window.m2072
-rw-r--r--raylib/src/external/glfw/src/context.c765
-rw-r--r--raylib/src/external/glfw/src/egl_context.c911
-rw-r--r--raylib/src/external/glfw/src/glfw.rc.in30
-rw-r--r--raylib/src/external/glfw/src/glx_context.c719
-rw-r--r--raylib/src/external/glfw/src/init.c528
-rw-r--r--raylib/src/external/glfw/src/input.c1505
-rw-r--r--raylib/src/external/glfw/src/internal.h1009
-rw-r--r--raylib/src/external/glfw/src/linux_joystick.c436
-rw-r--r--raylib/src/external/glfw/src/linux_joystick.h64
-rw-r--r--raylib/src/external/glfw/src/mappings.h1002
-rw-r--r--raylib/src/external/glfw/src/mappings.h.in82
-rw-r--r--raylib/src/external/glfw/src/monitor.c548
-rw-r--r--raylib/src/external/glfw/src/nsgl_context.m384
-rw-r--r--raylib/src/external/glfw/src/null_init.c264
-rw-r--r--raylib/src/external/glfw/src/null_joystick.c56
-rw-r--r--raylib/src/external/glfw/src/null_joystick.h32
-rw-r--r--raylib/src/external/glfw/src/null_monitor.c160
-rw-r--r--raylib/src/external/glfw/src/null_platform.h271
-rw-r--r--raylib/src/external/glfw/src/null_window.c720
-rw-r--r--raylib/src/external/glfw/src/osmesa_context.c383
-rw-r--r--raylib/src/external/glfw/src/platform.c204
-rw-r--r--raylib/src/external/glfw/src/platform.h212
-rw-r--r--raylib/src/external/glfw/src/posix_module.c53
-rw-r--r--raylib/src/external/glfw/src/posix_poll.c83
-rw-r--r--raylib/src/external/glfw/src/posix_poll.h30
-rw-r--r--raylib/src/external/glfw/src/posix_thread.c107
-rw-r--r--raylib/src/external/glfw/src/posix_thread.h49
-rw-r--r--raylib/src/external/glfw/src/posix_time.c65
-rw-r--r--raylib/src/external/glfw/src/posix_time.h41
-rw-r--r--raylib/src/external/glfw/src/vulkan.c328
-rw-r--r--raylib/src/external/glfw/src/wgl_context.c798
-rw-r--r--raylib/src/external/glfw/src/win32_init.c732
-rw-r--r--raylib/src/external/glfw/src/win32_joystick.c767
-rw-r--r--raylib/src/external/glfw/src/win32_joystick.h51
-rw-r--r--raylib/src/external/glfw/src/win32_module.c51
-rw-r--r--raylib/src/external/glfw/src/win32_monitor.c569
-rw-r--r--raylib/src/external/glfw/src/win32_platform.h627
-rw-r--r--raylib/src/external/glfw/src/win32_thread.c100
-rw-r--r--raylib/src/external/glfw/src/win32_thread.h53
-rw-r--r--raylib/src/external/glfw/src/win32_time.c54
-rw-r--r--raylib/src/external/glfw/src/win32_time.h43
-rw-r--r--raylib/src/external/glfw/src/win32_window.c2594
-rw-r--r--raylib/src/external/glfw/src/window.c1172
-rw-r--r--raylib/src/external/glfw/src/wl_init.c1004
-rw-r--r--raylib/src/external/glfw/src/wl_monitor.c274
-rw-r--r--raylib/src/external/glfw/src/wl_platform.h691
-rw-r--r--raylib/src/external/glfw/src/wl_window.c3309
-rw-r--r--raylib/src/external/glfw/src/x11_init.c1657
-rw-r--r--raylib/src/external/glfw/src/x11_monitor.c641
-rw-r--r--raylib/src/external/glfw/src/x11_platform.h1004
-rw-r--r--raylib/src/external/glfw/src/x11_window.c3358
-rw-r--r--raylib/src/external/glfw/src/xkb_unicode.c943
-rw-r--r--raylib/src/external/glfw/src/xkb_unicode.h30
-rw-r--r--raylib/src/external/jar_mod.h1596
-rw-r--r--raylib/src/external/jar_xm.h2471
-rw-r--r--raylib/src/external/m3d.h6547
-rw-r--r--raylib/src/external/miniaudio.h92633
-rw-r--r--raylib/src/external/msf_gif.h717
-rw-r--r--raylib/src/external/par_shapes.h2155
-rw-r--r--raylib/src/external/qoa.h742
-rw-r--r--raylib/src/external/qoaplay.c278
-rw-r--r--raylib/src/external/qoi.h649
-rw-r--r--raylib/src/external/rl_gputex.h826
-rw-r--r--raylib/src/external/rprand.h311
-rw-r--r--raylib/src/external/sdefl.h790
-rw-r--r--raylib/src/external/sinfl.h629
-rw-r--r--raylib/src/external/stb_image.h7988
-rw-r--r--raylib/src/external/stb_image_resize2.h10601
-rw-r--r--raylib/src/external/stb_image_write.h1724
-rw-r--r--raylib/src/external/stb_perlin.h428
-rw-r--r--raylib/src/external/stb_rect_pack.h623
-rw-r--r--raylib/src/external/stb_truetype.h5079
-rw-r--r--raylib/src/external/stb_vorbis.c5584
-rw-r--r--raylib/src/external/tinyobj_loader_c.h1594
-rw-r--r--raylib/src/external/vox_loader.h727
-rw-r--r--raylib/src/external/win32_clipboard.h374
-rw-r--r--raylib/src/minshell.html89
-rw-r--r--raylib/src/platforms/rcore_android.c1339
-rw-r--r--raylib/src/platforms/rcore_desktop_glfw.c1933
-rw-r--r--raylib/src/platforms/rcore_desktop_rgfw.c1387
-rw-r--r--raylib/src/platforms/rcore_desktop_sdl.c1978
-rw-r--r--raylib/src/platforms/rcore_drm.c1942
-rw-r--r--raylib/src/platforms/rcore_template.c597
-rw-r--r--raylib/src/platforms/rcore_web.c1792
-rw-r--r--raylib/src/raudio.c2879
-rw-r--r--raylib/src/raylib.dll.rc27
-rw-r--r--raylib/src/raylib.dll.rc.databin0 -> 11318 bytes
-rw-r--r--raylib/src/raylib.h1708
-rw-r--r--raylib/src/raylib.icobin0 -> 6177 bytes
-rw-r--r--raylib/src/raylib.rc27
-rw-r--r--raylib/src/raylib.rc.databin0 -> 11302 bytes
-rw-r--r--raylib/src/raymath.h2941
-rw-r--r--raylib/src/rcamera.h555
-rw-r--r--raylib/src/rcore.c4070
-rw-r--r--raylib/src/rgestures.h555
-rw-r--r--raylib/src/rglfw.c148
-rw-r--r--raylib/src/rlgl.h5262
-rw-r--r--raylib/src/rmodels.c6796
-rw-r--r--raylib/src/rshapes.c2414
-rw-r--r--raylib/src/rtext.c2573
-rw-r--r--raylib/src/rtextures.c5548
-rw-r--r--raylib/src/shell.html338
-rw-r--r--raylib/src/utils.c510
-rw-r--r--raylib/src/utils.h81
160 files changed, 316972 insertions, 0 deletions
diff --git a/raylib/src/CMakeLists.txt b/raylib/src/CMakeLists.txt
new file mode 100644
index 0000000..9735e26
--- /dev/null
+++ b/raylib/src/CMakeLists.txt
@@ -0,0 +1,132 @@
1# Setup the project and settings
2project(raylib C)
3set(PROJECT_VERSION 5.5.0)
4set(API_VERSION 550)
5
6include(GNUInstallDirs)
7include(JoinPaths)
8
9# Sets build type if not set by now
10if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
11 if(RAYLIB_IS_MAIN)
12 set(default_build_type Debug)
13 else()
14 message(WARNING "Default build type is not set (CMAKE_BUILD_TYPE)")
15 endif()
16
17 message(STATUS "Setting build type to '${default_build_type}' as none was specified.")
18
19 set(CMAKE_BUILD_TYPE "${default_build_type}" CACHE STRING "Choose the type of build." FORCE)
20 set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release" "MinSizeRel" "RelWithDebInfo")
21endif()
22
23# Used as public API to be included into other projects
24set(raylib_public_headers
25 raylib.h
26 rlgl.h
27 raymath.h
28 )
29
30# Sources to be compiled
31set(raylib_sources
32 raudio.c
33 rcore.c
34 rmodels.c
35 rshapes.c
36 rtext.c
37 rtextures.c
38 utils.c
39 )
40
41# <root>/cmake/GlfwImport.cmake handles the details around the inclusion of glfw
42if (NOT ${PLATFORM} MATCHES "Web")
43 include(GlfwImport)
44endif ()
45
46# Sets additional platform options and link libraries for each platform
47# also selects the proper graphics API and version for that platform
48# Produces a variable LIBS_PRIVATE that will be used later
49include(LibraryConfigurations)
50
51if (SUPPORT_MODULE_RAUDIO)
52 MESSAGE(STATUS "Audio Backend: miniaudio")
53else ()
54 MESSAGE(STATUS "Audio Backend: None (-DCUSTOMIZE_BUILD=ON -DSUPPORT_MODULE_RAUDIO=OFF)")
55endif ()
56
57add_library(raylib ${raylib_sources} ${raylib_public_headers})
58
59if (NOT BUILD_SHARED_LIBS)
60 MESSAGE(STATUS "Building raylib static library")
61 add_library(raylib_static ALIAS raylib)
62else()
63 MESSAGE(STATUS "Building raylib shared library")
64 target_compile_definitions(raylib
65 PRIVATE $<BUILD_INTERFACE:BUILD_LIBTYPE_SHARED>
66 INTERFACE $<INSTALL_INTERFACE:USE_LIBTYPE_SHARED>
67 )
68endif()
69
70if (${PLATFORM} MATCHES "Web")
71 target_link_options(raylib PUBLIC "-sUSE_GLFW=3")
72 if(${GRAPHICS} MATCHES "GRAPHICS_API_OPENGL_ES3")
73 target_link_options(raylib PUBLIC "-sMIN_WEBGL_VERSION=2")
74 target_link_options(raylib PUBLIC "-sMAX_WEBGL_VERSION=2")
75 endif()
76endif()
77
78set_target_properties(raylib PROPERTIES
79 PUBLIC_HEADER "${raylib_public_headers}"
80 VERSION ${PROJECT_VERSION}
81 SOVERSION ${API_VERSION}
82 )
83
84if (WITH_PIC OR BUILD_SHARED_LIBS)
85 set_property(TARGET raylib PROPERTY POSITION_INDEPENDENT_CODE ON)
86endif ()
87
88if (BUILD_SHARED_LIBS)
89 # Hide raylib's symbols by default so RLAPI can expose them
90 set_property(TARGET raylib PROPERTY C_VISIBILITY_PRESET hidden)
91endif ()
92
93target_link_libraries(raylib "${LIBS_PRIVATE}")
94
95# Sets some compile time definitions for the pre-processor
96# If CUSTOMIZE_BUILD option is on you will not use config.h by default
97# and you will be able to select more build options
98include(CompileDefinitions)
99
100# Registering include directories
101target_include_directories(raylib
102 PUBLIC
103 $<INSTALL_INTERFACE:include>
104 $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>
105 PRIVATE
106 ${CMAKE_CURRENT_SOURCE_DIR}
107 ${OPENGL_INCLUDE_DIR}
108 ${OPENAL_INCLUDE_DIR}
109 )
110
111# Copy the header files to the build directory for convenience
112file(COPY ${raylib_public_headers} DESTINATION "include")
113
114# Includes information on how the library will be installed on the system
115# when cmake --install is run
116include(InstallConfigurations)
117
118# Print the flags for the user
119if (DEFINED CMAKE_BUILD_TYPE)
120 message(STATUS "Generated build type: ${CMAKE_BUILD_TYPE}")
121else ()
122 message(STATUS "Generated config types: ${CMAKE_CONFIGURATION_TYPES}")
123endif ()
124
125message(STATUS "Compiling with the flags:")
126message(STATUS " PLATFORM=" ${PLATFORM_CPP})
127message(STATUS " GRAPHICS=" ${GRAPHICS})
128
129# Options if you want to create an installer using CPack
130include(PackConfigurations)
131
132enable_testing()
diff --git a/raylib/src/LICENSE b/raylib/src/LICENSE
new file mode 100644
index 0000000..e96f876
--- /dev/null
+++ b/raylib/src/LICENSE
@@ -0,0 +1,16 @@
1Copyright (c) 2013-2025 Ramon Santamaria (@raysan5)
2
3This software is provided "as-is", without any express or implied warranty. In no event
4will the authors be held liable for any damages arising from the use of this software.
5
6Permission is granted to anyone to use this software for any purpose, including commercial
7applications, and to alter it and redistribute it freely, subject to the following restrictions:
8
9 1. The origin of this software must not be misrepresented; you must not claim that you
10 wrote the original software. If you use this software in a product, an acknowledgment
11 in the product documentation would be appreciated but is not required.
12
13 2. Altered source versions must be plainly marked as such, and must not be misrepresented
14 as being the original software.
15
16 3. This notice may not be removed or altered from any source distribution.
diff --git a/raylib/src/Makefile b/raylib/src/Makefile
new file mode 100644
index 0000000..7dde52f
--- /dev/null
+++ b/raylib/src/Makefile
@@ -0,0 +1,873 @@
1#******************************************************************************
2#
3# raylib makefile
4#
5# This file supports building raylib library for the following platforms:
6#
7# > PLATFORM_DESKTOP
8# - Defaults to PLATFORM_DESKTOP_GLFW
9# > PLATFORM_DESKTOP_GLFW (GLFW backend):
10# - Windows (Win32, Win64)
11# - Linux (X11/Wayland desktop mode)
12# - macOS/OSX (x64, arm64)
13# - FreeBSD, OpenBSD, NetBSD, DragonFly (X11 desktop)
14# > PLATFORM_DESKTOP_SDL (SDL backend):
15# - Windows (Win32, Win64)
16# - Linux (X11/Wayland desktop mode)
17# - Others (not tested)
18# > PLATFORM_DESKTOP_RGFW (RGFW backend):
19# - Windows (Win32, Win64)
20# - Linux (X11 desktop mode)
21# - macOS/OSX (x64, arm64 (not tested))
22# - Others (not tested)
23# > PLATFORM_WEB:
24# - HTML5 (WebAssembly)
25# > PLATFORM_DRM:
26# - Raspberry Pi 0-5 (DRM/KMS)
27# - Linux DRM subsystem (KMS mode)
28# > PLATFORM_ANDROID:
29# - Android (ARM, ARM64)
30#
31# Many thanks to Milan Nikolic (@gen2brain) for implementing Android platform pipeline.
32# Many thanks to Emanuele Petriglia for his contribution on GNU/Linux pipeline.
33#
34# Copyright (c) 2013-2024 Ramon Santamaria (@raysan5)
35#
36# This software is provided "as-is", without any express or implied warranty. In no event
37# will the authors be held liable for any damages arising from the use of this software.
38#
39# Permission is granted to anyone to use this software for any purpose, including commercial
40# applications, and to alter it and redistribute it freely, subject to the following restrictions:
41#
42# 1. The origin of this software must not be misrepresented; you must not claim that you
43# wrote the original software. If you use this software in a product, an acknowledgment
44# in the product documentation would be appreciated but is not required.
45#
46# 2. Altered source versions must be plainly marked as such, and must not be misrepresented
47# as being the original software.
48#
49# 3. This notice may not be removed or altered from any source distribution.
50#
51#**************************************************************************************************
52
53# NOTE: Highly recommended to read the raylib Wiki to know how to compile raylib for different platforms
54# https://github.com/raysan5/raylib/wiki
55
56.PHONY: all clean install uninstall
57
58# Define required environment variables
59#------------------------------------------------------------------------------------------------
60# Define target platform
61PLATFORM ?= PLATFORM_DESKTOP
62
63ifeq ($(PLATFORM), PLATFORM_DESKTOP)
64 TARGET_PLATFORM = PLATFORM_DESKTOP_GLFW
65else
66 TARGET_PLATFORM = $(PLATFORM)
67endif
68
69# Define required raylib variables
70RAYLIB_VERSION = 5.5.0
71RAYLIB_API_VERSION = 550
72
73# Define raylib source code path
74RAYLIB_SRC_PATH ?= ../src
75
76# Define output directory for compiled library, defaults to src directory
77# NOTE: If externally provided, make sure directory exists
78RAYLIB_RELEASE_PATH ?= $(RAYLIB_SRC_PATH)
79
80# Library type used for raylib: STATIC (.a) or SHARED (.so/.dll)
81RAYLIB_LIBTYPE ?= STATIC
82
83# Build mode for library: DEBUG or RELEASE
84RAYLIB_BUILD_MODE ?= RELEASE
85
86# Build output name for the library
87RAYLIB_LIB_NAME ?= raylib
88
89# Define resource file for DLL properties
90RAYLIB_RES_FILE ?= ./raylib.dll.rc.data
91
92# Define external config flags
93# NOTE: It will override config.h flags with the provided ones,
94# if NONE, default config.h flags are used
95RAYLIB_CONFIG_FLAGS ?= NONE
96
97# To define additional cflags: Use make CUSTOM_CFLAGS=""
98
99# Include raylib modules on compilation
100# NOTE: Some programs like tools could not require those modules
101RAYLIB_MODULE_AUDIO ?= TRUE
102RAYLIB_MODULE_MODELS ?= TRUE
103RAYLIB_MODULE_RAYGUI ?= FALSE
104
105# NOTE: Additional libraries have been moved to their own repos:
106# raygui: https://github.com/raysan5/raygui
107RAYLIB_MODULE_RAYGUI_PATH ?= $(RAYLIB_SRC_PATH)/../../raygui/src
108
109# Use external GLFW library instead of rglfw module
110USE_EXTERNAL_GLFW ?= FALSE
111
112# Enable support for X11 by default on Linux when using GLFW
113# NOTE: Wayland is disabled by default, only enable if you are sure
114GLFW_LINUX_ENABLE_WAYLAND ?= FALSE
115GLFW_LINUX_ENABLE_X11 ?= TRUE
116
117# PLATFORM_DESKTOP_SDL: It requires SDL library to be provided externally
118# WARNING: Library is not included in raylib, it MUST be configured by users
119SDL_INCLUDE_PATH ?= $(RAYLIB_SRC_PATH)/external/SDL2/include
120SDL_LIBRARY_PATH ?= $(RAYLIB_SRC_PATH)/external/SDL2/lib
121SDL_LIBRARIES ?= -lSDL2 -lSDL2main
122
123
124# Determine if the file has root access (only required to install raylib)
125# "whoami" prints the name of the user that calls him (so, if it is the root user, "whoami" prints "root")
126ROOT = $(shell whoami)
127
128# By default we suppose we are working on Windows
129HOST_PLATFORM_OS ?= WINDOWS
130PLATFORM_OS ?= WINDOWS
131
132# Determine PLATFORM_OS when required
133ifeq ($(TARGET_PLATFORM),$(filter $(TARGET_PLATFORM),PLATFORM_DESKTOP_GLFW PLATFORM_DESKTOP_SDL PLATFORM_DESKTOP_RGFW PLATFORM_WEB PLATFORM_ANDROID))
134 # No uname.exe on MinGW!, but OS=Windows_NT on Windows!
135 # ifeq ($(UNAME),Msys) -> Windows
136 ifeq ($(OS),Windows_NT)
137 PLATFORM_OS = WINDOWS
138 ifndef PLATFORM_SHELL
139 PLATFORM_SHELL = cmd
140 endif
141 else
142 UNAMEOS = $(shell uname)
143 ifeq ($(UNAMEOS),Linux)
144 PLATFORM_OS = LINUX
145 endif
146 ifeq ($(UNAMEOS),FreeBSD)
147 PLATFORM_OS = BSD
148 endif
149 ifeq ($(UNAMEOS),OpenBSD)
150 PLATFORM_OS = BSD
151 endif
152 ifeq ($(UNAMEOS),NetBSD)
153 PLATFORM_OS = BSD
154 endif
155 ifeq ($(UNAMEOS),DragonFly)
156 PLATFORM_OS = BSD
157 endif
158 ifeq ($(UNAMEOS),Darwin)
159 PLATFORM_OS = OSX
160 endif
161 ifndef PLATFORM_SHELL
162 PLATFORM_SHELL = sh
163 endif
164 endif
165endif
166ifeq ($(TARGET_PLATFORM),PLATFORM_DRM)
167 UNAMEOS = $(shell uname)
168 ifeq ($(UNAMEOS),Linux)
169 PLATFORM_OS = LINUX
170 endif
171 ifndef PLATFORM_SHELL
172 PLATFORM_SHELL = sh
173 endif
174endif
175ifeq ($(TARGET_PLATFORM),PLATFORM_WEB)
176 ifeq ($(PLATFORM_OS),LINUX)
177 ifndef PLATFORM_SHELL
178 PLATFORM_SHELL = sh
179 endif
180 endif
181endif
182
183ifeq ($(TARGET_PLATFORM),PLATFORM_WEB)
184 ifeq ($(PLATFORM_OS), WINDOWS)
185 # Emscripten required variables
186 EMSDK_PATH ?= C:/raylib/emsdk
187 EMSCRIPTEN_PATH ?= $(EMSDK_PATH)/upstream/emscripten
188 CLANG_PATH := $(EMSDK_PATH)/upstream/bin
189 PYTHON_PATH := $(EMSDK_PATH)/python/3.9.2-nuget_64bit
190 NODE_PATH := $(EMSDK_PATH)/node/20.18.0_64bit/bin
191 export PATH := $(EMSDK_PATH);$(EMSCRIPTEN_PATH);$(CLANG_PATH);$(NODE_PATH);$(PYTHON_PATH);C:/raylib/MinGW/bin;$(PATH)
192 endif
193endif
194
195ifeq ($(TARGET_PLATFORM),PLATFORM_ANDROID)
196 # Android architecture
197 # Starting at 2019 using arm64 is mandatory for published apps,
198 # Starting on August 2020, minimum required target API is Android 10 (API level 29)
199 ANDROID_ARCH ?= arm64
200 ANDROID_API_VERSION ?= 29
201
202 # Android required path variables
203 # NOTE: Starting with Android NDK r21, no more toolchain generation is required, NDK is the toolchain on itself
204 ifeq ($(OS),Windows_NT)
205 ANDROID_NDK ?= C:/android-ndk
206 ANDROID_TOOLCHAIN = $(ANDROID_NDK)/toolchains/llvm/prebuilt/windows-x86_64
207 else
208 ANDROID_NDK ?= /usr/lib/android/ndk
209 ifeq ($(PLATFORM_OS), OSX)
210 ANDROID_TOOLCHAIN = $(ANDROID_NDK)/toolchains/llvm/prebuilt/darwin-x86_64
211 else
212 ANDROID_TOOLCHAIN = $(ANDROID_NDK)/toolchains/llvm/prebuilt/linux-x86_64
213 endif
214 endif
215
216 # NOTE: Sysroot can also be reference from $(ANDROID_NDK)/sysroot
217 ANDROID_SYSROOT ?= $(ANDROID_TOOLCHAIN)/sysroot
218
219 ifeq ($(ANDROID_ARCH),arm)
220 ANDROID_COMPILER_ARCH = armv7a
221 endif
222 ifeq ($(ANDROID_ARCH),arm64)
223 ANDROID_COMPILER_ARCH = aarch64
224 endif
225 ifeq ($(ANDROID_ARCH),x86)
226 ANDROID_COMPILER_ARCH = i686
227 endif
228 ifeq ($(ANDROID_ARCH),x86_64)
229 ANDROID_COMPILER_ARCH = x86_64
230 endif
231
232endif
233
234# Define raylib graphics api depending on selected platform
235# NOTE: By default use OpenGL 3.3 on desktop platforms
236ifeq ($(TARGET_PLATFORM),PLATFORM_DESKTOP_GLFW)
237 GRAPHICS ?= GRAPHICS_API_OPENGL_33
238 #GRAPHICS = GRAPHICS_API_OPENGL_11 # Uncomment to use OpenGL 1.1
239 #GRAPHICS = GRAPHICS_API_OPENGL_21 # Uncomment to use OpenGL 2.1
240 #GRAPHICS = GRAPHICS_API_OPENGL_43 # Uncomment to use OpenGL 4.3
241 #GRAPHICS = GRAPHICS_API_OPENGL_ES2 # Uncomment to use OpenGL ES 2.0 (ANGLE)
242endif
243ifeq ($(TARGET_PLATFORM),PLATFORM_DESKTOP_SDL)
244 GRAPHICS ?= GRAPHICS_API_OPENGL_33
245endif
246ifeq ($(TARGET_PLATFORM),PLATFORM_DESKTOP_RGFW)
247 GRAPHICS ?= GRAPHICS_API_OPENGL_33
248 #GRAPHICS = GRAPHICS_API_OPENGL_11 # Uncomment to use OpenGL 1.1
249 #GRAPHICS = GRAPHICS_API_OPENGL_21 # Uncomment to use OpenGL 2.1
250 #GRAPHICS = GRAPHICS_API_OPENGL_43 # Uncomment to use OpenGL 4.3
251 #GRAPHICS = GRAPHICS_API_OPENGL_ES2 # Uncomment to use OpenGL ES 2.0 (ANGLE)
252endif
253ifeq ($(TARGET_PLATFORM),PLATFORM_DRM)
254 # On DRM OpenGL ES 2.0 must be used
255 GRAPHICS = GRAPHICS_API_OPENGL_ES2
256endif
257ifeq ($(TARGET_PLATFORM),PLATFORM_WEB)
258 # On HTML5 OpenGL ES 2.0 is used, emscripten translates it to WebGL 1.0
259 GRAPHICS = GRAPHICS_API_OPENGL_ES2
260 #GRAPHICS = GRAPHICS_API_OPENGL_ES3
261endif
262ifeq ($(TARGET_PLATFORM),PLATFORM_ANDROID)
263 # By default use OpenGL ES 2.0 on Android
264 GRAPHICS = GRAPHICS_API_OPENGL_ES2
265endif
266
267# Define default C compiler and archiver to pack library: CC, AR
268#------------------------------------------------------------------------------------------------
269CC = gcc
270AR = ar
271
272ifeq ($(TARGET_PLATFORM),PLATFORM_DESKTOP_GLFW)
273 ifeq ($(PLATFORM_OS),OSX)
274 # OSX default compiler
275 CC = clang
276 GLFW_OSX = -x objective-c
277 endif
278 ifeq ($(PLATFORM_OS),BSD)
279 # FreeBSD, OpenBSD, NetBSD, DragonFly default compiler
280 CC = clang
281 endif
282endif
283ifeq ($(TARGET_PLATFORM),PLATFORM_DRM)
284 ifeq ($(USE_RPI_CROSS_COMPILER),TRUE)
285 # Define RPI cross-compiler
286 #CC = armv6j-hardfloat-linux-gnueabi-gcc
287 CC = $(RPI_TOOLCHAIN)/bin/$(RPI_TOOLCHAIN_NAME)-gcc
288 AR = $(RPI_TOOLCHAIN)/bin/$(RPI_TOOLCHAIN_NAME)-ar
289 endif
290endif
291ifeq ($(TARGET_PLATFORM),PLATFORM_WEB)
292 # HTML5 emscripten compiler
293 CC = emcc
294 AR = emar
295endif
296ifeq ($(TARGET_PLATFORM),PLATFORM_ANDROID)
297 # Android toolchain (must be provided for desired architecture and compiler)
298 ifeq ($(ANDROID_ARCH),arm)
299 CC = $(ANDROID_TOOLCHAIN)/bin/$(ANDROID_COMPILER_ARCH)-linux-androideabi$(ANDROID_API_VERSION)-clang
300 endif
301 ifeq ($(ANDROID_ARCH),arm64)
302 CC = $(ANDROID_TOOLCHAIN)/bin/$(ANDROID_COMPILER_ARCH)-linux-android$(ANDROID_API_VERSION)-clang
303 endif
304 ifeq ($(ANDROID_ARCH),x86)
305 CC = $(ANDROID_TOOLCHAIN)/bin/$(ANDROID_COMPILER_ARCH)-linux-android$(ANDROID_API_VERSION)-clang
306 endif
307 ifeq ($(ANDROID_ARCH),x86_64)
308 CC = $(ANDROID_TOOLCHAIN)/bin/$(ANDROID_COMPILER_ARCH)-linux-android$(ANDROID_API_VERSION)-clang
309 endif
310 # It seems from Android NDK r22 onwards we need to use llvm-ar
311 AR = $(ANDROID_TOOLCHAIN)/bin/llvm-ar
312endif
313
314# Define compiler flags: CFLAGS
315#------------------------------------------------------------------------------------------------
316# -O1 defines optimization level
317# -g include debug information on compilation
318# -s strip unnecessary data from build --> linker
319# -Wall turns on most, but not all, compiler warnings
320# -std=c99 defines C language mode (standard C from 1999 revision)
321# -std=gnu99 defines C language mode (GNU C from 1999 revision)
322# -Wno-missing-braces ignore invalid warning (GCC bug 53119)
323# -Wno-unused-value ignore unused return values of some functions (i.e. fread())
324# -D_DEFAULT_SOURCE use with -std=c99 on Linux and PLATFORM_WEB, required for timespec
325# -D_GNU_SOURCE access to lots of nonstandard GNU/Linux extension functions
326# -Werror=pointer-arith catch unportable code that does direct arithmetic on void pointers
327# -fno-strict-aliasing jar_xm.h does shady stuff (breaks strict aliasing)
328CFLAGS = -Wall -D_GNU_SOURCE -D$(TARGET_PLATFORM) -D$(GRAPHICS) -Wno-missing-braces -Werror=pointer-arith -fno-strict-aliasing
329
330ifneq ($(RAYLIB_CONFIG_FLAGS), NONE)
331 CFLAGS += -DEXTERNAL_CONFIG_FLAGS $(RAYLIB_CONFIG_FLAGS)
332endif
333
334ifeq ($(TARGET_PLATFORM), PLATFORM_WEB)
335 # NOTE: When using multi-threading in the user code, it requires -pthread enabled
336 CFLAGS += -std=gnu99
337else
338 CFLAGS += -std=c99
339endif
340
341ifeq ($(PLATFORM_OS), LINUX)
342 CFLAGS += -fPIC
343endif
344
345ifeq ($(RAYLIB_BUILD_MODE),DEBUG)
346 CFLAGS += -g -D_DEBUG
347endif
348
349ifeq ($(RAYLIB_BUILD_MODE),RELEASE)
350 ifeq ($(TARGET_PLATFORM),PLATFORM_WEB)
351 CFLAGS += -Os
352 endif
353 ifeq ($(TARGET_PLATFORM),PLATFORM_DESKTOP_GLFW)
354 CFLAGS += -O1
355 endif
356 ifeq ($(TARGET_PLATFORM),PLATFORM_ANDROID)
357 CFLAGS += -O2
358 endif
359endif
360
361# Additional flags for compiler (if desired)
362# -Wextra enables some extra warning flags that are not enabled by -Wall
363# -Wmissing-prototypes warn if a global function is defined without a previous prototype declaration
364# -Wstrict-prototypes warn if a function is declared or defined without specifying the argument types
365# -Werror=implicit-function-declaration catch function calls without prior declaration
366ifeq ($(TARGET_PLATFORM),PLATFORM_DESKTOP_GLFW)
367 CFLAGS += -Werror=implicit-function-declaration
368endif
369ifeq ($(TARGET_PLATFORM),PLATFORM_WEB)
370 # -Os # size optimization
371 # -O2 # optimization level 2, if used, also set --memory-init-file 0
372 # -sUSE_GLFW=3 # Use glfw3 library (context/input management) -> Only for linker!
373 # -sALLOW_MEMORY_GROWTH=1 # to allow memory resizing -> WARNING: Audio buffers could FAIL!
374 # -sTOTAL_MEMORY=16777216 # to specify heap memory size (default = 16MB)
375 # -sUSE_PTHREADS=1 # multithreading support
376 # -sFORCE_FILESYSTEM=1 # force filesystem to load/save files data
377 # -sASSERTIONS=1 # enable runtime checks for common memory allocation errors (-O1 and above turn it off)
378 # -sGL_ENABLE_GET_PROC_ADDRESS # enable using the *glGetProcAddress() family of functions, required for extensions loading
379 # --profiling # include information for code profiling
380 # --memory-init-file 0 # to avoid an external memory initialization code file (.mem)
381 # --preload-file resources # specify a resources folder for data compilation
382 ifeq ($(RAYLIB_BUILD_MODE),DEBUG)
383 CFLAGS += -sASSERTIONS=1 --profiling
384 endif
385 #CFLAGS += -sGL_ENABLE_GET_PROC_ADDRESS
386endif
387ifeq ($(TARGET_PLATFORM),PLATFORM_ANDROID)
388 # Compiler flags for arquitecture
389 ifeq ($(ANDROID_ARCH),arm)
390 CFLAGS += -march=armv7-a -mfloat-abi=softfp -mfpu=vfpv3-d16
391 endif
392 ifeq ($(ANDROID_ARCH),arm64)
393 CFLAGS += -target aarch64 -mfix-cortex-a53-835769
394 endif
395 ifeq ($(ANDROID_ARCH),x86)
396 CFLAGS += -march=i686
397 endif
398 ifeq ($(ANDROID_ARCH),x86_64)
399 CFLAGS += -march=x86-64
400 endif
401 # Compilation functions attributes options
402 CFLAGS += -ffunction-sections -funwind-tables -fstack-protector-strong -fPIE -fPIC
403 # Compiler options for the linker
404 # -Werror=format-security
405 CFLAGS += -Wa,--noexecstack -Wformat -no-canonical-prefixes
406 # Preprocessor macro definitions
407 CFLAGS += -D__ANDROID__ -DPLATFORM_ANDROID -D__ANDROID_API__=$(ANDROID_API_VERSION)
408endif
409
410# Define required compilation flags for raylib SHARED lib
411ifeq ($(RAYLIB_LIBTYPE),SHARED)
412 # make sure code is compiled as position independent
413 # BE CAREFUL: It seems that for gcc -fpic is not the same as -fPIC
414 # MinGW32 just doesn't need -fPIC, it shows warnings
415 CFLAGS += -fPIC -DBUILD_LIBTYPE_SHARED
416
417 # hide all symbols by default, so RLAPI can expose them
418 ifeq ($(PLATFORM_OS),$(filter $(PLATFORM_OS), LINUX BSD OSX))
419 CFLAGS += -fvisibility=hidden
420 endif
421endif
422
423ifeq ($(TARGET_PLATFORM),PLATFORM_DRM)
424 # without EGL_NO_X11 eglplatform.h tears Xlib.h in which tears X.h in
425 # which contains a conflicting type Font
426 CFLAGS += -DEGL_NO_X11
427 CFLAGS += -Werror=implicit-function-declaration
428endif
429# Use Wayland display on Linux desktop
430ifeq ($(TARGET_PLATFORM),PLATFORM_DESKTOP_GLFW)
431 ifeq ($(PLATFORM_OS), LINUX)
432 ifeq ($(GLFW_LINUX_ENABLE_X11),TRUE)
433 CFLAGS += -D_GLFW_X11
434 endif
435 ifeq ($(GLFW_LINUX_ENABLE_WAYLAND),TRUE)
436 CFLAGS += -D_GLFW_WAYLAND
437 LDFLAGS += $(shell pkg-config wayland-client wayland-cursor wayland-egl xkbcommon --libs)
438
439 WL_PROTOCOLS_DIR := external/glfw/deps/wayland
440
441 wl_generate = \
442 $(eval protocol=$(1)) \
443 $(eval basename=$(2)) \
444 $(shell wayland-scanner client-header $(protocol) $(RAYLIB_SRC_PATH)/$(basename).h) \
445 $(shell wayland-scanner private-code $(protocol) $(RAYLIB_SRC_PATH)/$(basename)-code.h)
446
447 $(call wl_generate, $(WL_PROTOCOLS_DIR)/wayland.xml, wayland-client-protocol)
448 $(call wl_generate, $(WL_PROTOCOLS_DIR)/xdg-shell.xml, xdg-shell-client-protocol)
449 $(call wl_generate, $(WL_PROTOCOLS_DIR)/xdg-decoration-unstable-v1.xml, xdg-decoration-unstable-v1-client-protocol)
450 $(call wl_generate, $(WL_PROTOCOLS_DIR)/viewporter.xml, viewporter-client-protocol)
451 $(call wl_generate, $(WL_PROTOCOLS_DIR)/relative-pointer-unstable-v1.xml, relative-pointer-unstable-v1-client-protocol)
452 $(call wl_generate, $(WL_PROTOCOLS_DIR)/pointer-constraints-unstable-v1.xml, pointer-constraints-unstable-v1-client-protocol)
453 $(call wl_generate, $(WL_PROTOCOLS_DIR)/fractional-scale-v1.xml, fractional-scale-v1-client-protocol)
454 $(call wl_generate, $(WL_PROTOCOLS_DIR)/xdg-activation-v1.xml, xdg-activation-v1-client-protocol)
455 $(call wl_generate, $(WL_PROTOCOLS_DIR)/idle-inhibit-unstable-v1.xml, idle-inhibit-unstable-v1-client-protocol)
456 endif
457 endif
458endif
459
460CFLAGS += $(CUSTOM_CFLAGS)
461
462# Define include paths for required headers: INCLUDE_PATHS
463# NOTE: Several external required libraries (stb and others)
464#------------------------------------------------------------------------------------------------
465INCLUDE_PATHS = -I. $(EXTRA_INCLUDE_PATHS)
466
467# Define additional directories containing required header files
468ifeq ($(TARGET_PLATFORM),PLATFORM_DESKTOP_GLFW)
469 INCLUDE_PATHS += -Iexternal/glfw/include
470 ifeq ($(PLATFORM_OS),BSD)
471 INCLUDE_PATHS += -I/usr/local/include -I/usr/pkg/include -I/usr/X11R7/include
472 endif
473endif
474ifeq ($(TARGET_PLATFORM),PLATFORM_DESKTOP_SDL)
475 INCLUDE_PATHS += -I$(SDL_INCLUDE_PATH)
476endif
477ifeq ($(TARGET_PLATFORM),PLATFORM_WEB)
478 INCLUDE_PATHS += -Iexternal/glfw/include
479endif
480ifeq ($(TARGET_PLATFORM),PLATFORM_DRM)
481 INCLUDE_PATHS += -I/usr/include/libdrm
482 ifeq ($(USE_RPI_CROSSCOMPILER), TRUE)
483 INCLUDE_PATHS += -I$(RPI_TOOLCHAIN_SYSROOT)/usr/include
484 INCLUDE_PATHS += -I$(RPI_TOOLCHAIN_SYSROOT)/opt/vc/include
485 endif
486endif
487ifeq ($(TARGET_PLATFORM),PLATFORM_ANDROID)
488 NATIVE_APP_GLUE = $(ANDROID_NDK)/sources/android/native_app_glue
489 # Include android_native_app_glue.h
490 INCLUDE_PATHS += -I$(NATIVE_APP_GLUE)
491
492 # Android required libraries
493 INCLUDE_PATHS += -I$(ANDROID_SYSROOT)/usr/include
494 ifeq ($(ANDROID_ARCH),arm)
495 INCLUDE_PATHS += -I$(ANDROID_SYSROOT)/usr/include/arm-linux-androideabi
496 endif
497 ifeq ($(ANDROID_ARCH),arm64)
498 INCLUDE_PATHS += -I$(ANDROID_SYSROOT)/usr/include/aarch64-linux-android
499 endif
500 ifeq ($(ANDROID_ARCH),x86)
501 INCLUDE_PATHS += -I$(ANDROID_SYSROOT)/usr/include/i686-linux-android
502 endif
503 ifeq ($(ANDROID_ARCH),x86_64)
504 INCLUDE_PATHS += -I$(ANDROID_SYSROOT)/usr/include/x86_64-linux-android
505 endif
506endif
507
508# Define library paths containing required libs: LDFLAGS
509# NOTE: This is only required for dynamic library generation
510#------------------------------------------------------------------------------------------------
511LDFLAGS = $(CUSTOM_LDFLAGS) -L. -L$(RAYLIB_RELEASE_PATH)
512
513ifeq ($(TARGET_PLATFORM),PLATFORM_DESKTOP_GLFW)
514 ifeq ($(PLATFORM_OS),WINDOWS)
515 ifneq ($(CC), tcc)
516 LDFLAGS += -Wl,--out-implib,$(RAYLIB_RELEASE_PATH)/lib$(RAYLIB_LIB_NAME)dll.a
517 endif
518 endif
519 ifeq ($(PLATFORM_OS),OSX)
520 LDFLAGS += -compatibility_version $(RAYLIB_API_VERSION) -current_version $(RAYLIB_VERSION)
521 endif
522 ifeq ($(PLATFORM_OS),LINUX)
523 LDFLAGS += -Wl,-soname,lib$(RAYLIB_LIB_NAME).so.$(RAYLIB_API_VERSION)
524 endif
525 ifeq ($(PLATFORM_OS),BSD)
526 LDFLAGS += -Wl,-soname,lib$(RAYLIB_LIB_NAME).$(RAYLIB_API_VERSION).so -Lsrc -L/usr/local/lib -L/usr/pkg/lib -Wl,-R/usr/pkg/lib
527 endif
528endif
529ifeq ($(TARGET_PLATFORM),PLATFORM_DESKTOP_SDL)
530 LDFLAGS += -Wl,-soname,lib$(RAYLIB_LIB_NAME).so.$(RAYLIB_API_VERSION)
531 LDFLAGS += -L$(SDL_LIBRARY_PATH)
532endif
533ifeq ($(TARGET_PLATFORM),PLATFORM_DRM)
534 LDFLAGS += -Wl,-soname,lib$(RAYLIB_LIB_NAME).so.$(RAYLIB_API_VERSION)
535 ifeq ($(USE_RPI_CROSSCOMPILER), TRUE)
536 LDFLAGS += -L$(RPI_TOOLCHAIN_SYSROOT)/opt/vc/lib -L$(RPI_TOOLCHAIN_SYSROOT)/usr/lib
537 endif
538endif
539ifeq ($(TARGET_PLATFORM),PLATFORM_ANDROID)
540 LDFLAGS += -Wl,-soname,libraylib.$(RAYLIB_API_VERSION).so -Wl,--exclude-libs,libatomic.a
541 LDFLAGS += -Wl,--build-id -Wl,-z,noexecstack -Wl,-z,relro -Wl,-z,now -Wl,--warn-shared-textrel -Wl,--fatal-warnings
542 # Force linking of library module to define symbol
543 LDFLAGS += -u ANativeActivity_onCreate
544 # Library paths containing required libs
545 LDFLAGS += -Lsrc
546 # Avoid unresolved symbol pointing to external main()
547 LDFLAGS += -Wl,-undefined,dynamic_lookup
548endif
549
550# Define libraries required on linking: LDLIBS
551# NOTE: This is only required for dynamic library generation
552#------------------------------------------------------------------------------------------------
553ifeq ($(TARGET_PLATFORM),PLATFORM_DESKTOP_GLFW)
554 ifeq ($(PLATFORM_OS),WINDOWS)
555 ifeq ($(CC), tcc)
556 LDLIBS = -lopengl32 -lgdi32 -lwinmm -lshell32
557 else
558 LDLIBS = -static-libgcc -lopengl32 -lgdi32 -lwinmm
559 endif
560 endif
561 ifeq ($(PLATFORM_OS),LINUX)
562 LDLIBS = -lGL -lc -lm -lpthread -ldl -lrt
563 ifeq ($(GLFW_LINUX_ENABLE_X11),TRUE)
564 LDLIBS += -lX11
565 endif
566 # TODO: On ARM 32bit arch, miniaudio requires atomics library
567 #LDLIBS += -latomic
568 endif
569 ifeq ($(PLATFORM_OS),OSX)
570 LDLIBS = -framework OpenGL -framework Cocoa -framework IOKit -framework CoreAudio -framework CoreVideo
571 endif
572 ifeq ($(PLATFORM_OS),BSD)
573 LDLIBS = -lGL -lpthread
574 endif
575 ifeq ($(USE_EXTERNAL_GLFW),TRUE)
576 # Check the version name. If GLFW3 was built manually, it may have produced
577 # a static library known as libglfw3.a. In that case, the name should be -lglfw3
578 LDLIBS = -lglfw
579 endif
580endif
581ifeq ($(TARGET_PLATFORM),PLATFORM_DESKTOP_SDL)
582 ifeq ($(PLATFORM_OS),WINDOWS)
583 LDLIBS = -static-libgcc -lopengl32 -lgdi32
584 endif
585 ifeq ($(PLATFORM_OS),LINUX)
586 LDLIBS = -lGL -lc -lm -lpthread -ldl -lrt
587 ifeq ($(USE_WAYLAND_DISPLAY),FALSE)
588 LDLIBS += -lX11
589 endif
590 endif
591 LDLIBS += $(SDL_LIBRARIES)
592endif
593ifeq ($(TARGET_PLATFORM),PLATFORM_DESKTOP_RGFW)
594 ifeq ($(PLATFORM_OS),WINDOWS)
595 # Libraries for Windows desktop compilation
596 LDLIBS = -lgdi32 -lwinmm -lopengl32
597 endif
598 ifeq ($(PLATFORM_OS),LINUX)
599 # Libraries for Debian GNU/Linux desktop compipling
600 # NOTE: Required packages: libegl1-mesa-dev
601 LDLIBS = -lGL -lX11 -lXrandr -lXinerama -lXi -lXcursor -lm -lpthread -ldl -lrt
602
603 # Explicit link to libc
604 ifeq ($(RAYLIB_LIBTYPE),SHARED)
605 LDLIBS += -lc
606 endif
607
608 # NOTE: On ARM 32bit arch, miniaudio requires atomics library
609 LDLIBS += -latomic
610 endif
611 ifeq ($(PLATFORM_OS),OSX)
612 # Libraries for Debian MacOS desktop compiling
613 # NOTE: Required packages: libegl1-mesa-dev
614 LDLIBS += -lm -framework Foundation -framework AppKit -framework OpenGL -framework CoreVideo
615 endif
616endif
617ifeq ($(TARGET_PLATFORM),PLATFORM_DRM)
618 LDLIBS = -lGLESv2 -lEGL -ldrm -lgbm -lpthread -lrt -lm -ldl
619 ifeq ($(RAYLIB_MODULE_AUDIO),TRUE)
620 LDLIBS += -latomic
621 endif
622endif
623ifeq ($(TARGET_PLATFORM),PLATFORM_ANDROID)
624 LDLIBS = -llog -landroid -lEGL -lGLESv2 -lOpenSLES -lc -lm
625endif
626
627# Define source code object files required
628#------------------------------------------------------------------------------------------------
629OBJS = rcore.o \
630 rshapes.o \
631 rtextures.o \
632 rtext.o \
633 utils.o
634
635ifeq ($(TARGET_PLATFORM),PLATFORM_DESKTOP_GLFW)
636 ifeq ($(USE_EXTERNAL_GLFW),FALSE)
637 OBJS += rglfw.o
638 endif
639endif
640ifeq ($(RAYLIB_MODULE_MODELS),TRUE)
641 OBJS += rmodels.o
642endif
643ifeq ($(RAYLIB_MODULE_AUDIO),TRUE)
644 OBJS += raudio.o
645endif
646ifeq ($(RAYLIB_MODULE_RAYGUI),TRUE)
647 OBJS += raygui.o
648endif
649
650ifeq ($(TARGET_PLATFORM),PLATFORM_ANDROID)
651 OBJS += android_native_app_glue.o
652endif
653
654# Define processes to execute
655#------------------------------------------------------------------------------------------------
656# Default target entry
657all: raylib
658
659# Compile raylib library
660# NOTE: Release directory is created if not exist
661raylib: $(OBJS)
662ifeq ($(TARGET_PLATFORM),PLATFORM_WEB)
663 # Compile raylib libray for web
664 #$(CC) $(OBJS) -r -o $(RAYLIB_RELEASE_PATH)/lib$(RAYLIB_LIB_NAME).bc
665 $(AR) rcs $(RAYLIB_RELEASE_PATH)/lib$(RAYLIB_LIB_NAME).a $(OBJS)
666 @echo "raylib library generated (lib$(RAYLIB_LIB_NAME).a)!"
667else
668 ifeq ($(RAYLIB_LIBTYPE),SHARED)
669 ifeq ($(TARGET_PLATFORM),$(filter $(TARGET_PLATFORM),PLATFORM_DESKTOP_GLFW PLATFORM_DESKTOP_SDL PLATFORM_DESKTOP_RGFW))
670 ifeq ($(PLATFORM_OS),WINDOWS)
671 # NOTE: Linking with provided resource file
672 $(CC) -shared -o $(RAYLIB_RELEASE_PATH)/$(RAYLIB_LIB_NAME).dll $(OBJS) $(RAYLIB_RES_FILE) $(LDFLAGS) $(LDLIBS)
673 @echo "raylib dynamic library ($(RAYLIB_LIB_NAME).dll) and import library (lib$(RAYLIB_LIB_NAME)dll.a) generated!"
674 endif
675 ifeq ($(PLATFORM_OS),LINUX)
676 # Compile raylib shared library version $(RAYLIB_VERSION).
677 # WARNING: you should type "make clean" before doing this target
678 $(CC) -shared -o $(RAYLIB_RELEASE_PATH)/lib$(RAYLIB_LIB_NAME).so.$(RAYLIB_VERSION) $(OBJS) $(LDFLAGS) $(LDLIBS)
679 @echo "raylib shared library generated (lib$(RAYLIB_LIB_NAME).so.$(RAYLIB_VERSION)) in $(RAYLIB_RELEASE_PATH)!"
680 cd $(RAYLIB_RELEASE_PATH) && ln -fsv lib$(RAYLIB_LIB_NAME).so.$(RAYLIB_VERSION) lib$(RAYLIB_LIB_NAME).so.$(RAYLIB_API_VERSION)
681 cd $(RAYLIB_RELEASE_PATH) && ln -fsv lib$(RAYLIB_LIB_NAME).so.$(RAYLIB_API_VERSION) lib$(RAYLIB_LIB_NAME).so
682 endif
683 ifeq ($(PLATFORM_OS),OSX)
684 $(CC) -dynamiclib -o $(RAYLIB_RELEASE_PATH)/lib$(RAYLIB_LIB_NAME).$(RAYLIB_VERSION).dylib $(OBJS) $(LDFLAGS) $(LDLIBS)
685 install_name_tool -id "@rpath/lib$(RAYLIB_LIB_NAME).$(RAYLIB_API_VERSION).dylib" $(RAYLIB_RELEASE_PATH)/lib$(RAYLIB_LIB_NAME).$(RAYLIB_VERSION).dylib
686 @echo "raylib shared library generated (lib$(RAYLIB_LIB_NAME).$(RAYLIB_VERSION).dylib)!"
687 cd $(RAYLIB_RELEASE_PATH) && ln -fs lib$(RAYLIB_LIB_NAME).$(RAYLIB_VERSION).dylib lib$(RAYLIB_LIB_NAME).$(RAYLIB_API_VERSION).dylib
688 cd $(RAYLIB_RELEASE_PATH) && ln -fs lib$(RAYLIB_LIB_NAME).$(RAYLIB_VERSION).dylib lib$(RAYLIB_LIB_NAME).dylib
689 endif
690 ifeq ($(PLATFORM_OS),BSD)
691 # WARNING: you should type "gmake clean" before doing this target
692 $(CC) -shared -o $(RAYLIB_RELEASE_PATH)/lib$(RAYLIB_LIB_NAME).$(RAYLIB_VERSION).so $(OBJS) $(LDFLAGS) $(LDLIBS)
693 @echo "raylib shared library generated (lib$(RAYLIB_LIB_NAME).$(RAYLIB_VERSION).so)!"
694 cd $(RAYLIB_RELEASE_PATH) && ln -fs lib$(RAYLIB_LIB_NAME).$(RAYLIB_VERSION).so lib$(RAYLIB_LIB_NAME).$(RAYLIB_API_VERSION).so
695 cd $(RAYLIB_RELEASE_PATH) && ln -fs lib$(RAYLIB_LIB_NAME).$(RAYLIB_VERSION).so lib$(RAYLIB_LIB_NAME).so
696 endif
697 endif
698 ifeq ($(TARGET_PLATFORM),PLATFORM_DRM)
699 # Compile raylib shared library version $(RAYLIB_VERSION).
700 # WARNING: you should type "make clean" before doing this target
701 $(CC) -shared -o $(RAYLIB_RELEASE_PATH)/lib$(RAYLIB_LIB_NAME).so.$(RAYLIB_VERSION) $(OBJS) $(LDFLAGS) $(LDLIBS)
702 @echo "raylib shared library generated (lib$(RAYLIB_LIB_NAME).so.$(RAYLIB_VERSION)) in $(RAYLIB_RELEASE_PATH)!"
703 cd $(RAYLIB_RELEASE_PATH) && ln -fsv lib$(RAYLIB_LIB_NAME).so.$(RAYLIB_VERSION) lib$(RAYLIB_LIB_NAME).so.$(RAYLIB_API_VERSION)
704 cd $(RAYLIB_RELEASE_PATH) && ln -fsv lib$(RAYLIB_LIB_NAME).so.$(RAYLIB_API_VERSION) lib$(RAYLIB_LIB_NAME).so
705 endif
706 ifeq ($(TARGET_PLATFORM),PLATFORM_ANDROID)
707 $(CC) -shared -o $(RAYLIB_RELEASE_PATH)/lib$(RAYLIB_LIB_NAME).$(RAYLIB_VERSION).so $(OBJS) $(LDFLAGS) $(LDLIBS)
708 @echo "raylib shared library generated (lib$(RAYLIB_LIB_NAME).$(RAYLIB_VERSION).so)!"
709 # WARNING: symbolic links creation on Windows should be done using mklink command, no ln available
710 ifeq ($(HOST_PLATFORM_OS),LINUX)
711 cd $(RAYLIB_RELEASE_PATH) && ln -fs lib$(RAYLIB_LIB_NAME).$(RAYLIB_VERSION).so lib$(RAYLIB_LIB_NAME).$(RAYLIB_API_VERSION).so
712 cd $(RAYLIB_RELEASE_PATH) && ln -fs lib$(RAYLIB_LIB_NAME).$(RAYLIB_VERSION).so lib$(RAYLIB_LIB_NAME).so
713 endif
714 endif
715 else
716 # Compile raylib static library version $(RAYLIB_VERSION)
717 # WARNING: You should type "make clean" before doing this target.
718 $(AR) rcs $(RAYLIB_RELEASE_PATH)/lib$(RAYLIB_LIB_NAME).a $(OBJS)
719 @echo "raylib static library generated (lib$(RAYLIB_LIB_NAME).a) in $(RAYLIB_RELEASE_PATH)!"
720 endif
721endif
722
723# Compile all modules with their prerequisites
724
725# Prerequisites of core module
726rcore.o : platforms/*.c
727
728# Compile core module
729rcore.o : rcore.c raylib.h rlgl.h utils.h raymath.h rcamera.h rgestures.h
730 $(CC) -c $< $(CFLAGS) $(INCLUDE_PATHS)
731
732# Compile rglfw module
733rglfw.o : rglfw.c
734 $(CC) $(GLFW_OSX) -c $< $(CFLAGS) $(INCLUDE_PATHS)
735
736# Compile shapes module
737rshapes.o : rshapes.c raylib.h rlgl.h
738 $(CC) -c $< $(CFLAGS) $(INCLUDE_PATHS)
739
740# Compile textures module
741rtextures.o : rtextures.c raylib.h rlgl.h utils.h
742 $(CC) -c $< $(CFLAGS) $(INCLUDE_PATHS)
743
744# Compile text module
745rtext.o : rtext.c raylib.h utils.h
746 $(CC) -c $< $(CFLAGS) $(INCLUDE_PATHS)
747
748# Compile utils module
749utils.o : utils.c utils.h
750 $(CC) -c $< $(CFLAGS) $(INCLUDE_PATHS)
751
752# Compile models module
753rmodels.o : rmodels.c raylib.h rlgl.h raymath.h
754 $(CC) -c $< $(CFLAGS) $(INCLUDE_PATHS)
755
756# Compile audio module
757raudio.o : raudio.c raylib.h
758 $(CC) -c $< $(CFLAGS) $(INCLUDE_PATHS)
759
760# Compile raygui module
761# NOTE: raygui header should be distributed with raylib.h
762raygui.o : raygui.c
763 $(CC) -c $< $(CFLAGS) $(INCLUDE_PATHS)
764raygui.c:
765ifeq ($(PLATFORM_SHELL), cmd)
766 @echo #define RAYGUI_IMPLEMENTATION > raygui.c
767 @echo #include "$(RAYLIB_MODULE_RAYGUI_PATH)/raygui.h" >> raygui.c
768else
769 @echo "#define RAYGUI_IMPLEMENTATION" > raygui.c
770 @echo "#include \"$(RAYLIB_MODULE_RAYGUI_PATH)/raygui.h\"" >> raygui.c
771endif
772
773# Compile android_native_app_glue module
774android_native_app_glue.o : $(NATIVE_APP_GLUE)/android_native_app_glue.c
775 $(CC) -c $< $(CFLAGS) $(INCLUDE_PATHS)
776
777# Install generated and needed files to desired directories.
778# On GNU/Linux and BSDs, there are some standard directories that contain extra
779# libraries and header files. These directories (often /usr/local/lib and
780# /usr/local/include) are for libraries that are installed manually
781# (without a package manager). We'll use /usr/local/lib/raysan5 and /usr/local/include/raysan5
782# for our -L and -I specification to simplify management of the raylib source package.
783# Customize these locations if you like but don't forget to pass them to make
784# for compilation and enable runtime linking with -rpath, LD_LIBRARY_PATH, or ldconfig.
785# HINT: Add -L$(RAYLIB_INSTALL_PATH) -I$(RAYLIB_H_INSTALL_PATH) to your own makefiles.
786# See below and ../examples/Makefile for more information.
787
788# RAYLIB_INSTALL_PATH should be the desired full path to libraylib. No relative paths.
789DESTDIR ?= /usr/local
790RAYLIB_INSTALL_PATH ?= $(DESTDIR)/lib
791# RAYLIB_H_INSTALL_PATH locates the installed raylib header and associated source files.
792RAYLIB_H_INSTALL_PATH ?= $(DESTDIR)/include
793
794install :
795ifeq ($(ROOT),root)
796 ifeq ($(PLATFORM_OS),LINUX)
797 # Attention! You are root, writing files to $(RAYLIB_INSTALL_PATH)
798 # and $(RAYLIB_H_INSTALL_PATH). Consult this Makefile for more information.
799 # Prepare the environment as needed.
800 mkdir --parents --verbose $(RAYLIB_INSTALL_PATH)
801 mkdir --parents --verbose $(RAYLIB_H_INSTALL_PATH)
802 ifeq ($(RAYLIB_LIBTYPE),SHARED)
803 # Installing raylib to $(RAYLIB_INSTALL_PATH).
804 cp --update --verbose $(RAYLIB_RELEASE_PATH)/libraylib.so.$(RAYLIB_VERSION) $(RAYLIB_INSTALL_PATH)/lib$(RAYLIB_LIB_NAME).so.$(RAYLIB_VERSION)
805 cd $(RAYLIB_INSTALL_PATH); ln -fsv lib$(RAYLIB_LIB_NAME).so.$(RAYLIB_VERSION) lib$(RAYLIB_LIB_NAME).so.$(RAYLIB_API_VERSION)
806 cd $(RAYLIB_INSTALL_PATH); ln -fsv lib$(RAYLIB_LIB_NAME).so.$(RAYLIB_API_VERSION) lib$(RAYLIB_LIB_NAME).so
807 # Uncomment to update the runtime linker cache with RAYLIB_INSTALL_PATH.
808 # Not necessary if later embedding RPATH in your executable. See examples/Makefile.
809 ldconfig $(RAYLIB_INSTALL_PATH)
810 else
811 # Installing raylib to $(RAYLIB_INSTALL_PATH).
812 cp --update --verbose $(RAYLIB_RELEASE_PATH)/lib$(RAYLIB_LIB_NAME).a $(RAYLIB_INSTALL_PATH)/lib$(RAYLIB_LIB_NAME).a
813 endif
814 # Copying raylib development files to $(RAYLIB_H_INSTALL_PATH).
815 cp --update raylib.h $(RAYLIB_H_INSTALL_PATH)/raylib.h
816 cp --update raymath.h $(RAYLIB_H_INSTALL_PATH)/raymath.h
817 cp --update rlgl.h $(RAYLIB_H_INSTALL_PATH)/rlgl.h
818 @echo "raylib development files installed/updated!"
819 else
820 @echo "This function currently works on GNU/Linux systems. Add yours today (^;"
821 endif
822else
823 @echo "Error: Root permissions needed for installation. Try sudo make install"
824endif
825
826# Remove raylib dev files installed on the system
827# NOTE: see 'install' target.
828uninstall :
829ifeq ($(ROOT),root)
830 # WARNING: You are root, about to delete items from $(RAYLIB_INSTALL_PATH).
831 # and $(RAYLIB_H_INSTALL_PATH). Please confirm each item.
832 ifeq ($(PLATFORM_OS),LINUX)
833 ifeq ($(RAYLIB_LIBTYPE),SHARED)
834 rm --force --interactive --verbose $(RAYLIB_INSTALL_PATH)/libraylib.so
835 rm --force --interactive --verbose $(RAYLIB_INSTALL_PATH)/libraylib.so.$(RAYLIB_API_VERSION)
836 rm --force --interactive --verbose $(RAYLIB_INSTALL_PATH)/libraylib.so.$(RAYLIB_VERSION)
837 # Uncomment to clean up the runtime linker cache. See install target.
838 ldconfig
839 else
840 rm --force --interactive --verbose $(RAYLIB_INSTALL_PATH)/libraylib.a
841 endif
842 rm --force --interactive --verbose $(RAYLIB_H_INSTALL_PATH)/raylib.h
843 rm --force --interactive --verbose $(RAYLIB_H_INSTALL_PATH)/raymath.h
844 rm --force --interactive --verbose $(RAYLIB_H_INSTALL_PATH)/rlgl.h
845 @echo "raylib development files removed!"
846 else
847 @echo "This function currently works on GNU/Linux systems. Add yours today (^;"
848 endif
849else
850 @echo "Error: Root permissions needed for uninstallation. Try sudo make uninstall"
851endif
852
853.PHONY: clean_shell_cmd clean_shell_sh
854
855# Clean everything
856clean: clean_shell_$(PLATFORM_SHELL)
857 @echo "removed all generated files!"
858
859clean_shell_sh:
860 rm -fv *.o $(RAYLIB_RELEASE_PATH)/lib$(RAYLIB_LIB_NAME).a $(RAYLIB_RELEASE_PATH)/lib$(RAYLIB_LIB_NAME).bc $(RAYLIB_RELEASE_PATH)/lib$(RAYLIB_LIB_NAME).so* raygui.c $(RAYLIB_RELEASE_PATH)/*-protocol.h $(RAYLIB_RELEASE_PATH)/*-protocol-code.h
861ifeq ($(TARGET_PLATFORM),PLATFORM_ANDROID)
862 rm -fv $(NATIVE_APP_GLUE)/android_native_app_glue.o
863endif
864
865# Set specific target variable
866clean_shell_cmd: SHELL=cmd
867clean_shell_cmd:
868 del *.o /s
869 cd $(RAYLIB_RELEASE_PATH) & \
870 del lib$(RAYLIB_LIB_NAME).a /s & \
871 del lib$(RAYLIB_LIB_NAME)dll.a /s & \
872 del $(RAYLIB_LIB_NAME).dll /s & \
873 del raygui.c /s & \
diff --git a/raylib/src/config.h b/raylib/src/config.h
new file mode 100644
index 0000000..e3749c5
--- /dev/null
+++ b/raylib/src/config.h
@@ -0,0 +1,303 @@
1/**********************************************************************************************
2*
3* raylib configuration flags
4*
5* This file defines all the configuration flags for the different raylib modules
6*
7* LICENSE: zlib/libpng
8*
9* Copyright (c) 2018-2024 Ahmad Fatoum & Ramon Santamaria (@raysan5)
10*
11* This software is provided "as-is", without any express or implied warranty. In no event
12* will the authors be held liable for any damages arising from the use of this software.
13*
14* Permission is granted to anyone to use this software for any purpose, including commercial
15* applications, and to alter it and redistribute it freely, subject to the following restrictions:
16*
17* 1. The origin of this software must not be misrepresented; you must not claim that you
18* wrote the original software. If you use this software in a product, an acknowledgment
19* in the product documentation would be appreciated but is not required.
20*
21* 2. Altered source versions must be plainly marked as such, and must not be misrepresented
22* as being the original software.
23*
24* 3. This notice may not be removed or altered from any source distribution.
25*
26**********************************************************************************************/
27
28#ifndef CONFIG_H
29#define CONFIG_H
30
31//------------------------------------------------------------------------------------
32// Module selection - Some modules could be avoided
33// Mandatory modules: rcore, rlgl, utils
34//------------------------------------------------------------------------------------
35#define SUPPORT_MODULE_RSHAPES 1
36#define SUPPORT_MODULE_RTEXTURES 1
37#define SUPPORT_MODULE_RTEXT 1 // WARNING: It requires SUPPORT_MODULE_RTEXTURES to load sprite font textures
38#define SUPPORT_MODULE_RMODELS 1
39#define SUPPORT_MODULE_RAUDIO 1
40
41//------------------------------------------------------------------------------------
42// Module: rcore - Configuration Flags
43//------------------------------------------------------------------------------------
44// Camera module is included (rcamera.h) and multiple predefined cameras are available: free, 1st/3rd person, orbital
45#define SUPPORT_CAMERA_SYSTEM 1
46// Gestures module is included (rgestures.h) to support gestures detection: tap, hold, swipe, drag
47#define SUPPORT_GESTURES_SYSTEM 1
48// Include pseudo-random numbers generator (rprand.h), based on Xoshiro128** and SplitMix64
49#define SUPPORT_RPRAND_GENERATOR 1
50// Mouse gestures are directly mapped like touches and processed by gestures system
51#define SUPPORT_MOUSE_GESTURES 1
52// Reconfigure standard input to receive key inputs, works with SSH connection.
53#define SUPPORT_SSH_KEYBOARD_RPI 1
54// Setting a higher resolution can improve the accuracy of time-out intervals in wait functions.
55// However, it can also reduce overall system performance, because the thread scheduler switches tasks more often.
56#define SUPPORT_WINMM_HIGHRES_TIMER 1
57// Use busy wait loop for timing sync, if not defined, a high-resolution timer is set up and used
58//#define SUPPORT_BUSY_WAIT_LOOP 1
59// Use a partial-busy wait loop, in this case frame sleeps for most of the time, but then runs a busy loop at the end for accuracy
60#define SUPPORT_PARTIALBUSY_WAIT_LOOP 1
61// Allow automatic screen capture of current screen pressing F12, defined in KeyCallback()
62#define SUPPORT_SCREEN_CAPTURE 1
63// Allow automatic gif recording of current screen pressing CTRL+F12, defined in KeyCallback()
64#define SUPPORT_GIF_RECORDING 1
65// Support CompressData() and DecompressData() functions
66#define SUPPORT_COMPRESSION_API 1
67// Support automatic generated events, loading and recording of those events when required
68#define SUPPORT_AUTOMATION_EVENTS 1
69// Support custom frame control, only for advanced users
70// By default EndDrawing() does this job: draws everything + SwapScreenBuffer() + manage frame timing + PollInputEvents()
71// Enabling this flag allows manual control of the frame processes, use at your own risk
72//#define SUPPORT_CUSTOM_FRAME_CONTROL 1
73
74
75// rcore: Configuration values
76//------------------------------------------------------------------------------------
77#define MAX_FILEPATH_CAPACITY 8192 // Maximum file paths capacity
78#define MAX_FILEPATH_LENGTH 4096 // Maximum length for filepaths (Linux PATH_MAX default value)
79
80#define MAX_KEYBOARD_KEYS 512 // Maximum number of keyboard keys supported
81#define MAX_MOUSE_BUTTONS 8 // Maximum number of mouse buttons supported
82#define MAX_GAMEPADS 4 // Maximum number of gamepads supported
83#define MAX_GAMEPAD_AXIS 8 // Maximum number of axis supported (per gamepad)
84#define MAX_GAMEPAD_BUTTONS 32 // Maximum number of buttons supported (per gamepad)
85#define MAX_GAMEPAD_VIBRATION_TIME 2.0f // Maximum vibration time in seconds
86#define MAX_TOUCH_POINTS 8 // Maximum number of touch points supported
87#define MAX_KEY_PRESSED_QUEUE 16 // Maximum number of keys in the key input queue
88#define MAX_CHAR_PRESSED_QUEUE 16 // Maximum number of characters in the char input queue
89
90#define MAX_DECOMPRESSION_SIZE 64 // Max size allocated for decompression in MB
91
92#define MAX_AUTOMATION_EVENTS 16384 // Maximum number of automation events to record
93
94//------------------------------------------------------------------------------------
95// Module: rlgl - Configuration values
96//------------------------------------------------------------------------------------
97
98// Enable OpenGL Debug Context (only available on OpenGL 4.3)
99//#define RLGL_ENABLE_OPENGL_DEBUG_CONTEXT 1
100
101// Show OpenGL extensions and capabilities detailed logs on init
102//#define RLGL_SHOW_GL_DETAILS_INFO 1
103
104#define RL_SUPPORT_MESH_GPU_SKINNING 1 // GPU skinning, comment if your GPU does not support more than 8 VBOs
105
106//#define RL_DEFAULT_BATCH_BUFFER_ELEMENTS 4096 // Default internal render batch elements limits
107#define RL_DEFAULT_BATCH_BUFFERS 1 // Default number of batch buffers (multi-buffering)
108#define RL_DEFAULT_BATCH_DRAWCALLS 256 // Default number of batch draw calls (by state changes: mode, texture)
109#define RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS 4 // Maximum number of textures units that can be activated on batch drawing (SetShaderValueTexture())
110
111#define RL_MAX_MATRIX_STACK_SIZE 32 // Maximum size of internal Matrix stack
112
113#define RL_MAX_SHADER_LOCATIONS 32 // Maximum number of shader locations supported
114
115#define RL_CULL_DISTANCE_NEAR 0.01 // Default projection matrix near cull distance
116#define RL_CULL_DISTANCE_FAR 1000.0 // Default projection matrix far cull distance
117
118// Default shader vertex attribute locations
119#define RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION 0
120#define RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD 1
121#define RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL 2
122#define RL_DEFAULT_SHADER_ATTRIB_LOCATION_COLOR 3
123#define RL_DEFAULT_SHADER_ATTRIB_LOCATION_TANGENT 4
124#define RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD2 5
125#define RL_DEFAULT_SHADER_ATTRIB_LOCATION_INDICES 6
126#if defined(RL_SUPPORT_MESH_GPU_SKINNING)
127 #define RL_DEFAULT_SHADER_ATTRIB_LOCATION_BONEIDS 7
128 #define RL_DEFAULT_SHADER_ATTRIB_LOCATION_BONEWEIGHTS 8
129#endif
130
131// Default shader vertex attribute names to set location points
132// NOTE: When a new shader is loaded, the following locations are tried to be set for convenience
133#define RL_DEFAULT_SHADER_ATTRIB_NAME_POSITION "vertexPosition" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION
134#define RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD "vertexTexCoord" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD
135#define RL_DEFAULT_SHADER_ATTRIB_NAME_NORMAL "vertexNormal" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL
136#define RL_DEFAULT_SHADER_ATTRIB_NAME_COLOR "vertexColor" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_LOCATION_COLOR
137#define RL_DEFAULT_SHADER_ATTRIB_NAME_TANGENT "vertexTangent" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_LOCATION_TANGENT
138#define RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD2 "vertexTexCoord2" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD2
139
140#define RL_DEFAULT_SHADER_UNIFORM_NAME_MVP "mvp" // model-view-projection matrix
141#define RL_DEFAULT_SHADER_UNIFORM_NAME_VIEW "matView" // view matrix
142#define RL_DEFAULT_SHADER_UNIFORM_NAME_PROJECTION "matProjection" // projection matrix
143#define RL_DEFAULT_SHADER_UNIFORM_NAME_MODEL "matModel" // model matrix
144#define RL_DEFAULT_SHADER_UNIFORM_NAME_NORMAL "matNormal" // normal matrix (transpose(inverse(matModelView))
145#define RL_DEFAULT_SHADER_UNIFORM_NAME_COLOR "colDiffuse" // color diffuse (base tint color, multiplied by texture color)
146#define RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE0 "texture0" // texture0 (texture slot active 0)
147#define RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE1 "texture1" // texture1 (texture slot active 1)
148#define RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE2 "texture2" // texture2 (texture slot active 2)
149
150
151//------------------------------------------------------------------------------------
152// Module: rshapes - Configuration Flags
153//------------------------------------------------------------------------------------
154// Use QUADS instead of TRIANGLES for drawing when possible
155// Some lines-based shapes could still use lines
156#define SUPPORT_QUADS_DRAW_MODE 1
157
158// rshapes: Configuration values
159//------------------------------------------------------------------------------------
160#define SPLINE_SEGMENT_DIVISIONS 24 // Spline segments subdivisions
161
162
163//------------------------------------------------------------------------------------
164// Module: rtextures - Configuration Flags
165//------------------------------------------------------------------------------------
166// Selecte desired fileformats to be supported for image data loading
167#define SUPPORT_FILEFORMAT_PNG 1
168//#define SUPPORT_FILEFORMAT_BMP 1
169//#define SUPPORT_FILEFORMAT_TGA 1
170//#define SUPPORT_FILEFORMAT_JPG 1
171#define SUPPORT_FILEFORMAT_GIF 1
172#define SUPPORT_FILEFORMAT_QOI 1
173//#define SUPPORT_FILEFORMAT_PSD 1
174#define SUPPORT_FILEFORMAT_DDS 1
175//#define SUPPORT_FILEFORMAT_HDR 1
176//#define SUPPORT_FILEFORMAT_PIC 1
177//#define SUPPORT_FILEFORMAT_KTX 1
178//#define SUPPORT_FILEFORMAT_ASTC 1
179//#define SUPPORT_FILEFORMAT_PKM 1
180//#define SUPPORT_FILEFORMAT_PVR 1
181
182// Support image export functionality (.png, .bmp, .tga, .jpg, .qoi)
183#define SUPPORT_IMAGE_EXPORT 1
184// Support procedural image generation functionality (gradient, spot, perlin-noise, cellular)
185#define SUPPORT_IMAGE_GENERATION 1
186// Support multiple image editing functions to scale, adjust colors, flip, draw on images, crop...
187// If not defined, still some functions are supported: ImageFormat(), ImageCrop(), ImageToPOT()
188#define SUPPORT_IMAGE_MANIPULATION 1
189
190
191//------------------------------------------------------------------------------------
192// Module: rtext - Configuration Flags
193//------------------------------------------------------------------------------------
194// Default font is loaded on window initialization to be available for the user to render simple text
195// NOTE: If enabled, uses external module functions to load default raylib font
196#define SUPPORT_DEFAULT_FONT 1
197// Selected desired font fileformats to be supported for loading
198#define SUPPORT_FILEFORMAT_TTF 1
199#define SUPPORT_FILEFORMAT_FNT 1
200//#define SUPPORT_FILEFORMAT_BDF 1
201
202// Support text management functions
203// If not defined, still some functions are supported: TextLength(), TextFormat()
204#define SUPPORT_TEXT_MANIPULATION 1
205
206// On font atlas image generation [GenImageFontAtlas()], add a 3x3 pixels white rectangle
207// at the bottom-right corner of the atlas. It can be useful to for shapes drawing, to allow
208// drawing text and shapes with a single draw call [SetShapesTexture()].
209#define SUPPORT_FONT_ATLAS_WHITE_REC 1
210
211// rtext: Configuration values
212//------------------------------------------------------------------------------------
213#define MAX_TEXT_BUFFER_LENGTH 1024 // Size of internal static buffers used on some functions:
214 // TextFormat(), TextSubtext(), TextToUpper(), TextToLower(), TextToPascal(), TextSplit()
215#define MAX_TEXTSPLIT_COUNT 128 // Maximum number of substrings to split: TextSplit()
216
217
218//------------------------------------------------------------------------------------
219// Module: rmodels - Configuration Flags
220//------------------------------------------------------------------------------------
221// Selected desired model fileformats to be supported for loading
222#define SUPPORT_FILEFORMAT_OBJ 1
223#define SUPPORT_FILEFORMAT_MTL 1
224#define SUPPORT_FILEFORMAT_IQM 1
225#define SUPPORT_FILEFORMAT_GLTF 1
226#define SUPPORT_FILEFORMAT_VOX 1
227#define SUPPORT_FILEFORMAT_M3D 1
228// Support procedural mesh generation functions, uses external par_shapes.h library
229// NOTE: Some generated meshes DO NOT include generated texture coordinates
230#define SUPPORT_MESH_GENERATION 1
231
232// rmodels: Configuration values
233//------------------------------------------------------------------------------------
234#define MAX_MATERIAL_MAPS 12 // Maximum number of shader maps supported
235
236#ifdef RL_SUPPORT_MESH_GPU_SKINNING
237#define MAX_MESH_VERTEX_BUFFERS 9 // Maximum vertex buffers (VBO) per mesh
238#else
239#define MAX_MESH_VERTEX_BUFFERS 7 // Maximum vertex buffers (VBO) per mesh
240#endif
241
242//------------------------------------------------------------------------------------
243// Module: raudio - Configuration Flags
244//------------------------------------------------------------------------------------
245// Desired audio fileformats to be supported for loading
246#define SUPPORT_FILEFORMAT_WAV 1
247#define SUPPORT_FILEFORMAT_OGG 1
248#define SUPPORT_FILEFORMAT_MP3 1
249#define SUPPORT_FILEFORMAT_QOA 1
250//#define SUPPORT_FILEFORMAT_FLAC 1
251#define SUPPORT_FILEFORMAT_XM 1
252#define SUPPORT_FILEFORMAT_MOD 1
253
254// raudio: Configuration values
255//------------------------------------------------------------------------------------
256#define AUDIO_DEVICE_FORMAT ma_format_f32 // Device output format (miniaudio: float-32bit)
257#define AUDIO_DEVICE_CHANNELS 2 // Device output channels: stereo
258#define AUDIO_DEVICE_SAMPLE_RATE 0 // Device sample rate (device default)
259
260#define MAX_AUDIO_BUFFER_POOL_CHANNELS 16 // Maximum number of audio pool channels
261
262//------------------------------------------------------------------------------------
263// Module: utils - Configuration Flags
264//------------------------------------------------------------------------------------
265// Standard file io library (stdio.h) included
266#define SUPPORT_STANDARD_FILEIO 1
267// Show TRACELOG() output messages
268// NOTE: By default LOG_DEBUG traces not shown
269#define SUPPORT_TRACELOG 1
270//#define SUPPORT_TRACELOG_DEBUG 1
271
272// utils: Configuration values
273//------------------------------------------------------------------------------------
274#define MAX_TRACELOG_MSG_LENGTH 256 // Max length of one trace-log message
275
276
277// Enable partial support for clipboard image, only working on SDL3 or
278// being on both Windows OS + GLFW or Windows OS + RGFW
279#define SUPPORT_CLIPBOARD_IMAGE 1
280
281#if defined(SUPPORT_CLIPBOARD_IMAGE)
282 #ifndef STBI_REQUIRED
283 #define STBI_REQUIRED
284 #endif
285
286 #ifndef SUPPORT_FILEFORMAT_BMP // For clipboard image on Windows
287 #define SUPPORT_FILEFORMAT_BMP 1
288 #endif
289
290 #ifndef SUPPORT_FILEFORMAT_PNG // Wayland uses png for prints, at least it was on 22 LTS ubuntu
291 #define SUPPORT_FILEFORMAT_PNG 1
292 #endif
293
294 #ifndef SUPPORT_FILEFORMAT_JPG
295 #define SUPPORT_FILEFORMAT_JPG 1
296 #endif
297
298 #ifndef SUPPORT_MODULE_RTEXTURES
299 #define SUPPORT_MODULE_RTEXTURES 1
300 #endif
301#endif
302
303#endif // CONFIG_H
diff --git a/raylib/src/external/RGFW.h b/raylib/src/external/RGFW.h
new file mode 100644
index 0000000..978536f
--- /dev/null
+++ b/raylib/src/external/RGFW.h
@@ -0,0 +1,9015 @@
1/*
2* Copyright (C) 2023-24 ColleagueRiley
3*
4* libpng license
5*
6* This software is provided 'as-is', without any express or implied
7* warranty. In no event will the authors be held liable for any damages
8* arising from the use of this software.
9*
10* Permission is granted to anyone to use this software for any purpose,
11* including commercial applications, and to alter it and redistribute it
12* freely, subject to the following restrictions:
13*
14* 1. The origin of this software must not be misrepresented; you must not
15* claim that you wrote the original software. If you use this software
16* in a product, an acknowledgment in the product documentation would be
17* appreciated but is not required.
18* 2. Altered source versions must be plainly marked as such, and must not be
19* misrepresented as being the original software.
20* 3. This notice may not be removed or altered from any source distribution.
21*
22*
23*/
24
25/*
26 (MAKE SURE RGFW_IMPLEMENTATION is in exactly one header or you use -D RGFW_IMPLEMENTATION)
27 #define RGFW_IMPLEMENTATION - makes it so source code is included with header
28*/
29
30/*
31 #define RGFW_IMPLEMENTATION - (required) makes it so the source code is included
32 #define RGFW_PRINT_ERRORS - (optional) makes it so RGFW prints errors when they're found
33 #define RGFW_OSMESA - (optional) use OSmesa as backend (instead of system's opengl api + regular opengl)
34 #define RGFW_BUFFER - (optional) just draw directly to (RGFW) window pixel buffer that is drawn to screen (the buffer is in the RGBA format)
35 #define RGFW_EGL - (optional) use EGL for loading an OpenGL context (instead of the system's opengl api)
36 #define RGFW_OPENGL_ES1 - (optional) use EGL to load and use Opengl ES (version 1) for backend rendering (instead of the system's opengl api)
37 This version doesn't work for desktops (I'm pretty sure)
38 #define RGFW_OPENGL_ES2 - (optional) use OpenGL ES (version 2)
39 #define RGFW_OPENGL_ES3 - (optional) use OpenGL ES (version 3)
40 #define RGFW_DIRECTX - (optional) use directX for the rendering backend (rather than opengl) (windows only, defaults to opengl for unix)
41 #define RGFW_WEBGPU - (optional) use webGPU for rendering (Web ONLY)
42 #define RGFW_NO_API - (optional) don't use any rendering API (no opengl, no vulkan, no directX)
43
44 #define RGFW_LINK_EGL (optional) (windows only) if EGL is being used, if EGL functions should be defined dymanically (using GetProcAddress)
45 #define RGFW_LINK_OSMESA (optional) (windows only) if EGL is being used, if OS Mesa functions should be defined dymanically (using GetProcAddress)
46
47 #define RGFW_X11 (optional) (unix only) if X11 should be used. This option is turned on by default by unix systems except for MacOS
48 #define RGFW_WGL_LOAD (optional) (windows only) if WGL should be loaded dynamically during runtime
49 #define RGFW_NO_X11_CURSOR (optional) (unix only) don't use XCursor
50 #define RGFW_NO_X11_CURSOR_PRELOAD (optional) (unix only) Use XCursor, but don't link it in code, (you'll have to link it with -lXcursor)
51
52 #define RGFW_NO_DPI - Do not include calculate DPI (no XRM nor libShcore included)
53
54 #define RGFW_ALLOC_DROPFILES (optional) if room should be allocating for drop files (by default it's global data)
55 #define RGFW_MALLOC x - choose what function to use to allocate, by default the standard malloc is used
56 #define RGFW_CALLOC x - choose what function to use to allocate (calloc), by default the standard calloc is used
57 #define RGFW_FREE x - choose what function to use to allocated memory, by default the standard free is used
58
59 #define RGFW_EXPORT - Use when building RGFW
60 #define RGFW_IMPORT - Use when linking with RGFW (not as a single-header)
61
62 #define RGFW_STD_INT - force the use stdint.h (for systems that might not have stdint.h (msvc))
63*/
64
65/*
66 Credits :
67 EimaMei/Sacode : Much of the code for creating windows using winapi, Wrote the Silicon library, helped with MacOS Support, siliapp.h -> referencing
68
69 stb - This project is heavily inspired by the stb single header files
70
71 GLFW:
72 certain parts of winapi and X11 are very poorly documented,
73 GLFW's source code was referenced and used throughout the project (used code is marked in some way),
74 this mainly includes, code for drag and drops, code for setting the icon to a bitmap and the code for managing the clipboard for X11 (as these parts are not documented very well)
75
76 GLFW Copyright, https::/github.com/GLFW/GLFW
77
78 Copyright (c) 2002-2006 Marcus Geelnard
79 Copyright (c) 2006-2019 Camilla Löwy
80
81 contributors : (feel free to put yourself here if you contribute)
82 krisvers -> code review
83 EimaMei (SaCode) -> code review
84 Code-Nycticebus -> bug fixes
85 Rob Rohan -> X11 bugs and missing features, MacOS/Cocoa fixing memory issues/bugs
86 AICDG (@THISISAGOODNAME) -> vulkan support (example)
87 @Easymode -> support, testing/debugging, bug fixes and reviews
88 Joshua Rowe (omnisci3nce) - bug fix, review (macOS)
89 @lesleyrs -> bug fix, review (OpenGL)
90 Nick Porcino (meshula) - testing, organization, review (MacOS, examples)
91*/
92
93#if _MSC_VER
94 #pragma comment(lib, "gdi32")
95 #pragma comment(lib, "shell32")
96 #pragma comment(lib, "opengl32")
97 #pragma comment(lib, "winmm")
98 #pragma comment(lib, "user32")
99#endif
100
101#ifndef RGFW_MALLOC
102 #include <stdlib.h>
103
104 #ifndef __USE_POSIX199309
105 #define __USE_POSIX199309
106 #endif
107
108 #include <time.h>
109 #define RGFW_MALLOC malloc
110 #define RGFW_CALLOC calloc
111 #define RGFW_FREE free
112#endif
113
114#if !_MSC_VER
115 #ifndef inline
116 #ifndef __APPLE__
117 #define inline __inline
118 #endif
119 #endif
120#endif
121
122#ifdef RGFW_WIN95 /* for windows 95 testing (not that it really works) */
123 #define RGFW_NO_MONITOR
124 #define RGFW_NO_PASSTHROUGH
125#endif
126
127#if defined(RGFW_EXPORT) || defined(RGFW_IMPORT)
128 #if defined(_WIN32)
129 #if defined(__TINYC__) && (defined(RGFW_EXPORT) || defined(RGFW_IMPORT))
130 #define __declspec(x) __attribute__((x))
131 #endif
132
133 #if defined(RGFW_EXPORT)
134 #define RGFWDEF __declspec(dllexport)
135 #else
136 #define RGFWDEF __declspec(dllimport)
137 #endif
138 #else
139 #if defined(RGFW_EXPORT)
140 #define RGFWDEF __attribute__((visibility("default")))
141 #endif
142 #endif
143#endif
144
145#ifndef RGFWDEF
146 #ifdef __clang__
147 #define RGFWDEF static inline
148 #else
149 #define RGFWDEF inline
150 #endif
151#endif
152
153#ifndef RGFW_ENUM
154 #define RGFW_ENUM(type, name) type name; enum
155#endif
156
157#ifndef RGFW_UNUSED
158 #define RGFW_UNUSED(x) (void)(x);
159#endif
160
161#if defined(__cplusplus) && !defined(__EMSCRIPTEN__)
162 extern "C" {
163#endif
164
165 /* makes sure the header file part is only defined once by default */
166#ifndef RGFW_HEADER
167
168#define RGFW_HEADER
169
170#if !defined(u8)
171 #if ((defined(_MSC_VER) || defined(__SYMBIAN32__)) && !defined(RGFW_STD_INT)) /* MSVC might not have stdint.h */
172 typedef unsigned char u8;
173 typedef signed char i8;
174 typedef unsigned short u16;
175 typedef signed short i16;
176 typedef unsigned int u32;
177 typedef signed int i32;
178 typedef unsigned long u64;
179 typedef signed long i64;
180 #else /* use stdint standard types instead of c ""standard"" types */
181 #include <stdint.h>
182
183 typedef uint8_t u8;
184 typedef int8_t i8;
185 typedef uint16_t u16;
186 typedef int16_t i16;
187 typedef uint32_t u32;
188 typedef int32_t i32;
189 typedef uint64_t u64;
190 typedef int64_t i64;
191 #endif
192#endif
193
194#if !defined(b8) /* RGFW bool type */
195 typedef u8 b8;
196 typedef u32 b32;
197#endif
198
199#define RGFW_TRUE (!(0))
200#define RGFW_FALSE 0
201
202/* thse OS macros looks better & are standardized */
203/* plus it helps with cross-compiling */
204
205#ifdef __EMSCRIPTEN__
206 #define RGFW_WEBASM
207
208 #if !defined(RGFW_NO_API) && !defined(RGFW_WEBGPU)
209 #define RGFW_OPENGL
210 #endif
211
212 #ifdef RGFW_EGL
213 #undef RGFW_EGL
214 #endif
215
216 #include <emscripten/html5.h>
217 #include <emscripten/key_codes.h>
218
219 #ifdef RGFW_WEBGPU
220 #include <emscripten/html5_webgpu.h>
221 #endif
222#endif
223
224#if defined(RGFW_X11) && defined(__APPLE__)
225 #define RGFW_MACOS_X11
226 #undef __APPLE__
227#endif
228
229#if defined(_WIN32) && !defined(RGFW_X11) && !defined(RGFW_WEBASM) /* (if you're using X11 on windows some how) */
230 #define RGFW_WINDOWS
231
232 /* make sure the correct architecture is defined */
233 #if defined(_WIN64)
234 #define _AMD64_
235 #undef _X86_
236 #else
237 #undef _AMD64_
238 #ifndef _X86_
239 #define _X86_
240 #endif
241 #endif
242
243 #ifndef RGFW_NO_XINPUT
244 #ifdef __MINGW32__ /* try to find the right header */
245 #include <xinput.h>
246 #else
247 #include <XInput.h>
248 #endif
249 #endif
250
251 #if defined(RGFW_DIRECTX)
252 #include <d3d11.h>
253 #include <dxgi.h>
254 #include <dxgi.h>
255 #include <d3dcompiler.h>
256
257 #ifndef __cplusplus
258 #define __uuidof(T) IID_##T
259 #endif
260 #endif
261
262#elif defined(RGFW_WAYLAND)
263 #if !defined(RGFW_NO_API) && (!defined(RGFW_BUFFER) || defined(RGFW_OPENGL))
264 #define RGFW_EGL
265 #define RGFW_OPENGL
266 #include <wayland-egl.h>
267 #endif
268
269 #include <wayland-client.h>
270#elif (defined(__unix__) || defined(RGFW_MACOS_X11) || defined(RGFW_X11)) && !defined(RGFW_WEBASM)
271 #define RGFW_MACOS_X11
272 #define RGFW_X11
273 #include <X11/Xlib.h>
274#elif defined(__APPLE__) && !defined(RGFW_MACOS_X11) && !defined(RGFW_X11) && !defined(RGFW_WEBASM)
275 #define RGFW_MACOS
276#endif
277
278#if (defined(RGFW_OPENGL_ES1) || defined(RGFW_OPENGL_ES2) || defined(RGFW_OPENGL_ES3)) && !defined(RGFW_EGL)
279 #define RGFW_EGL
280#endif
281
282#if !defined(RGFW_OSMESA) && !defined(RGFW_EGL) && !defined(RGFW_OPENGL) && !defined(RGFW_DIRECTX) && !defined(RGFW_BUFFER) && !defined(RGFW_NO_API)
283 #define RGFW_OPENGL
284#endif
285
286#ifdef RGFW_EGL
287 #include <EGL/egl.h>
288#elif defined(RGFW_OSMESA)
289 #ifndef __APPLE__
290 #include <GL/osmesa.h>
291 #else
292 #include <OpenGL/osmesa.h>
293 #endif
294#endif
295
296#if defined(RGFW_OPENGL) && defined(RGFW_X11)
297 #ifndef GLX_MESA_swap_control
298 #define GLX_MESA_swap_control
299 #endif
300 #include <GL/glx.h> /* GLX defs, xlib.h, gl.h */
301#endif
302
303#ifndef RGFW_ALPHA
304 #define RGFW_ALPHA 128 /* alpha value for RGFW_TRANSPARENT_WINDOW (WINAPI ONLY, macOS + linux don't need this) */
305#endif
306
307/*! Optional arguments for making a windows */
308#define RGFW_TRANSPARENT_WINDOW (1L<<9) /*!< the window is transparent (only properly works on X11 and MacOS, although it's although for windows) */
309#define RGFW_NO_BORDER (1L<<3) /*!< the window doesn't have border */
310#define RGFW_NO_RESIZE (1L<<4) /*!< the window cannot be resized by the user */
311#define RGFW_ALLOW_DND (1L<<5) /*!< the window supports drag and drop*/
312#define RGFW_HIDE_MOUSE (1L<<6) /*! the window should hide the mouse or not (can be toggled later on) using `RGFW_window_mouseShow*/
313#define RGFW_FULLSCREEN (1L<<8) /* the window is fullscreen by default or not */
314#define RGFW_CENTER (1L<<10) /*! center the window on the screen */
315#define RGFW_OPENGL_SOFTWARE (1L<<11) /*! use OpenGL software rendering */
316#define RGFW_COCOA_MOVE_TO_RESOURCE_DIR (1L << 12) /* (cocoa only), move to resource folder */
317#define RGFW_SCALE_TO_MONITOR (1L << 13) /* scale the window to the screen */
318#define RGFW_NO_INIT_API (1L << 2) /* DO not init an API (mostly for bindings, you should use `#define RGFW_NO_API` in C */
319
320#define RGFW_NO_GPU_RENDER (1L<<14) /* don't render (using the GPU based API)*/
321#define RGFW_NO_CPU_RENDER (1L<<15) /* don't render (using the CPU based buffer rendering)*/
322#define RGFW_WINDOW_HIDE (1L << 16)/* the window is hidden */
323
324typedef RGFW_ENUM(u8, RGFW_event_types) {
325 /*! event codes */
326 RGFW_keyPressed = 1, /* a key has been pressed */
327 RGFW_keyReleased, /*!< a key has been released*/
328 /*! key event note
329 the code of the key pressed is stored in
330 RGFW_Event.keyCode
331 !!Keycodes defined at the bottom of the RGFW_HEADER part of this file!!
332
333 while a string version is stored in
334 RGFW_Event.KeyString
335
336 RGFW_Event.lockState holds the current lockState
337 this means if CapsLock, NumLock are active or not
338 */
339 RGFW_mouseButtonPressed, /*!< a mouse button has been pressed (left,middle,right)*/
340 RGFW_mouseButtonReleased, /*!< a mouse button has been released (left,middle,right)*/
341 RGFW_mousePosChanged, /*!< the position of the mouse has been changed*/
342 /*! mouse event note
343 the x and y of the mouse can be found in the vector, RGFW_Event.point
344
345 RGFW_Event.button holds which mouse button was pressed
346 */
347 RGFW_jsButtonPressed, /*!< a joystick button was pressed */
348 RGFW_jsButtonReleased, /*!< a joystick button was released */
349 RGFW_jsAxisMove, /*!< an axis of a joystick was moved*/
350 /*! joystick event note
351 RGFW_Event.joystick holds which joystick was altered, if any
352 RGFW_Event.button holds which joystick button was pressed
353
354 RGFW_Event.axis holds the data of all the axis
355 RGFW_Event.axisCount says how many axis there are
356 */
357 RGFW_windowMoved, /*!< the window was moved (by the user) */
358 RGFW_windowResized, /*!< the window was resized (by the user), [on webASM this means the browser was resized] */
359 RGFW_focusIn, /*!< window is in focus now */
360 RGFW_focusOut, /*!< window is out of focus now */
361 RGFW_mouseEnter, /* mouse entered the window */
362 RGFW_mouseLeave, /* mouse left the window */
363 RGFW_windowRefresh, /* The window content needs to be refreshed */
364
365 /* attribs change event note
366 The event data is sent straight to the window structure
367 with win->r.x, win->r.y, win->r.w and win->r.h
368 */
369 RGFW_quit, /*!< the user clicked the quit button*/
370 RGFW_dnd, /*!< a file has been dropped into the window*/
371 RGFW_dnd_init /*!< the start of a dnd event, when the place where the file drop is known */
372 /* dnd data note
373 The x and y coords of the drop are stored in the vector RGFW_Event.point
374
375 RGFW_Event.droppedFilesCount holds how many files were dropped
376
377 This is also the size of the array which stores all the dropped file string,
378 RGFW_Event.droppedFiles
379 */
380};
381
382/*! mouse button codes (RGFW_Event.button) */
383#define RGFW_mouseLeft 1 /*!< left mouse button is pressed*/
384#define RGFW_mouseMiddle 2 /*!< mouse-wheel-button is pressed*/
385#define RGFW_mouseRight 3 /*!< right mouse button is pressed*/
386#define RGFW_mouseScrollUp 4 /*!< mouse wheel is scrolling up*/
387#define RGFW_mouseScrollDown 5 /*!< mouse wheel is scrolling down*/
388
389#ifndef RGFW_MAX_PATH
390#define RGFW_MAX_PATH 260 /* max length of a path (for dnd) */
391#endif
392#ifndef RGFW_MAX_DROPS
393#define RGFW_MAX_DROPS 260 /* max items you can drop at once */
394#endif
395
396
397/* for RGFW_Event.lockstate */
398#define RGFW_CAPSLOCK (1L << 1)
399#define RGFW_NUMLOCK (1L << 2)
400
401/*! joystick button codes (based on xbox/playstation), you may need to change these values per controller */
402#ifndef RGFW_joystick_codes
403 typedef RGFW_ENUM(u8, RGFW_joystick_codes) {
404 RGFW_JS_A = 0, /*!< or PS X button */
405 RGFW_JS_B = 1, /*!< or PS circle button */
406 RGFW_JS_Y = 2, /*!< or PS triangle button */
407 RGFW_JS_X = 3, /*!< or PS square button */
408 RGFW_JS_START = 9, /*!< start button */
409 RGFW_JS_SELECT = 8, /*!< select button */
410 RGFW_JS_HOME = 10, /*!< home button */
411 RGFW_JS_UP = 13, /*!< dpad up */
412 RGFW_JS_DOWN = 14, /*!< dpad down*/
413 RGFW_JS_LEFT = 15, /*!< dpad left */
414 RGFW_JS_RIGHT = 16, /*!< dpad right */
415 RGFW_JS_L1 = 4, /*!< left bump */
416 RGFW_JS_L2 = 5, /*!< left trigger*/
417 RGFW_JS_R1 = 6, /*!< right bumper */
418 RGFW_JS_R2 = 7, /*!< right trigger */
419 };
420#endif
421
422/*! basic vector type, if there's not already a point/vector type of choice */
423#ifndef RGFW_point
424 typedef struct { i32 x, y; } RGFW_point;
425#endif
426
427/*! basic rect type, if there's not already a rect type of choice */
428#ifndef RGFW_rect
429 typedef struct { i32 x, y, w, h; } RGFW_rect;
430#endif
431
432/*! basic area type, if there's not already a area type of choice */
433#ifndef RGFW_area
434 typedef struct { u32 w, h; } RGFW_area;
435#endif
436
437#ifndef __cplusplus
438#define RGFW_POINT(x, y) (RGFW_point){(i32)(x), (i32)(y)}
439#define RGFW_RECT(x, y, w, h) (RGFW_rect){(i32)(x), (i32)(y), (i32)(w), (i32)(h)}
440#define RGFW_AREA(w, h) (RGFW_area){(u32)(w), (u32)(h)}
441#else
442#define RGFW_POINT(x, y) {(i32)(x), (i32)(y)}
443#define RGFW_RECT(x, y, w, h) {(i32)(x), (i32)(y), (i32)(w), (i32)(h)}
444#define RGFW_AREA(w, h) {(u32)(w), (u32)(h)}
445#endif
446
447#ifndef RGFW_NO_MONITOR
448 /*! structure for monitor data */
449 typedef struct RGFW_monitor {
450 char name[128]; /*!< monitor name */
451 RGFW_rect rect; /*!< monitor Workarea */
452 float scaleX, scaleY; /*!< monitor content scale*/
453 float physW, physH; /*!< monitor physical size */
454 } RGFW_monitor;
455
456 /*
457 NOTE : Monitor functions should be ran only as many times as needed (not in a loop)
458 */
459
460 /*! get an array of all the monitors (max 6) */
461 RGFWDEF RGFW_monitor* RGFW_getMonitors(void);
462 /*! get the primary monitor */
463 RGFWDEF RGFW_monitor RGFW_getPrimaryMonitor(void);
464#endif
465
466/* NOTE: some parts of the data can represent different things based on the event (read comments in RGFW_Event struct) */
467/*! Event structure for checking/getting events */
468typedef struct RGFW_Event {
469 char keyName[16]; /*!< key name of event*/
470
471 /*! drag and drop data */
472 /* 260 max paths with a max length of 260 */
473#ifdef RGFW_ALLOC_DROPFILES
474 char** droppedFiles;
475#else
476 char droppedFiles[RGFW_MAX_DROPS][RGFW_MAX_PATH]; /*!< dropped files*/
477#endif
478 u32 droppedFilesCount; /*!< house many files were dropped */
479
480 u32 type; /*!< which event has been sent?*/
481 RGFW_point point; /*!< mouse x, y of event (or drop point) */
482
483 u8 keyCode; /*!< keycode of event !!Keycodes defined at the bottom of the RGFW_HEADER part of this file!! */
484
485 b8 repeat; /*!< key press event repeated (the key is being held) */
486 b8 inFocus; /*!< if the window is in focus or not (this is always true for MacOS windows due to the api being weird) */
487
488 u8 lockState;
489
490 u8 button; /* !< which mouse button was pressed */
491 double scroll; /*!< the raw mouse scroll value */
492
493 u16 joystick; /*! which joystick this event applies to (if applicable to any) */
494 u8 axisesCount; /*!< number of axises */
495 RGFW_point axis[2]; /*!< x, y of axises (-100 to 100) */
496
497 u64 frameTime, frameTime2; /*!< this is used for counting the fps */
498} RGFW_Event;
499
500/*! source data for the window (used by the APIs) */
501typedef struct RGFW_window_src {
502#ifdef RGFW_WINDOWS
503 HWND window; /*!< source window */
504 HDC hdc; /*!< source HDC */
505 u32 hOffset; /*!< height offset for window */
506 #if (defined(RGFW_OPENGL)) && !defined(RGFW_OSMESA) && !defined(RGFW_EGL)
507 HGLRC ctx; /*!< source graphics context */
508 #elif defined(RGFW_OSMESA)
509 OSMesaContext ctx;
510 #elif defined(RGFW_DIRECTX)
511 IDXGISwapChain* swapchain;
512 ID3D11RenderTargetView* renderTargetView;
513 ID3D11DepthStencilView* pDepthStencilView;
514 #elif defined(RGFW_EGL)
515 EGLSurface EGL_surface;
516 EGLDisplay EGL_display;
517 EGLContext EGL_context;
518 #endif
519
520 #if defined(RGFW_OSMESA) || defined(RGFW_BUFFER)
521 HDC hdcMem;
522 HBITMAP bitmap;
523 #endif
524 RGFW_area maxSize, minSize; /*!< for setting max/min resize (RGFW_WINDOWS) */
525#elif defined(RGFW_X11)
526 Display* display; /*!< source display */
527 Window window; /*!< source window */
528 #if (defined(RGFW_OPENGL)) && !defined(RGFW_OSMESA) && !defined(RGFW_EGL)
529 GLXContext ctx; /*!< source graphics context */
530 #elif defined(RGFW_OSMESA)
531 OSMesaContext ctx;
532 #elif defined(RGFW_EGL)
533 EGLSurface EGL_surface;
534 EGLDisplay EGL_display;
535 EGLContext EGL_context;
536 #endif
537
538#if defined(RGFW_OSMESA) || defined(RGFW_BUFFER)
539 XImage* bitmap;
540 GC gc;
541#endif
542#elif defined(RGFW_WAYLAND)
543 struct wl_display* display;
544 struct wl_surface* surface;
545 struct wl_buffer* wl_buffer;
546 struct wl_keyboard* keyboard;
547
548 struct xdg_surface* xdg_surface;
549 struct xdg_toplevel* xdg_toplevel;
550 struct zxdg_toplevel_decoration_v1* decoration;
551 RGFW_Event events[20];
552 i32 eventLen;
553 size_t eventIndex;
554 #if defined(RGFW_EGL)
555 struct wl_egl_window* window;
556 EGLSurface EGL_surface;
557 EGLDisplay EGL_display;
558 EGLContext EGL_context;
559 #elif defined(RGFW_OSMESA)
560 OSMesaContext ctx;
561 #endif
562#elif defined(RGFW_MACOS)
563 u32 display;
564 void* displayLink;
565 void* window;
566 b8 dndPassed;
567#if (defined(RGFW_OPENGL)) && !defined(RGFW_OSMESA) && !defined(RGFW_EGL)
568 void* ctx; /*!< source graphics context */
569#elif defined(RGFW_OSMESA)
570 OSMesaContext ctx;
571#elif defined(RGFW_EGL)
572 EGLSurface EGL_surface;
573 EGLDisplay EGL_display;
574 EGLContext EGL_context;
575#endif
576
577 void* view; /*apple viewpoint thingy*/
578
579#if defined(RGFW_OSMESA) || defined(RGFW_BUFFER)
580 void* bitmap; /*!< API's bitmap for storing or managing */
581 void* image;
582#endif
583#elif defined(RGFW_WEBASM)
584 #ifdef RGFW_WEBGPU
585 WGPUInstance ctx;
586 WGPUDevice device;
587 WGPUQueue queue;
588 #else
589 EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx;
590 #endif
591#endif
592} RGFW_window_src;
593
594
595
596typedef struct RGFW_window {
597 RGFW_window_src src; /*!< src window data */
598
599#if defined(RGFW_OSMESA) || defined(RGFW_BUFFER)
600 u8* buffer; /*!< buffer for non-GPU systems (OSMesa, basic software rendering) */
601 /* when rendering using RGFW_BUFFER, the buffer is in the RGBA format */
602#endif
603 void* userPtr; /* ptr for usr data */
604
605 RGFW_Event event; /*!< current event */
606
607 RGFW_rect r; /*!< the x, y, w and h of the struct */
608
609 RGFW_point _lastMousePoint; /*!< last cusor point (for raw mouse data) */
610
611 u32 _winArgs; /*!< windows args (for RGFW to check) */
612} RGFW_window; /*!< Window structure for managing the window */
613
614#if defined(RGFW_X11) || defined(RGFW_MACOS)
615 typedef u64 RGFW_thread; /*!< thread type unix */
616#else
617 typedef void* RGFW_thread; /*!< thread type for window */
618#endif
619
620/** * @defgroup Window_management
621* @{ */
622
623
624/*!
625 * the class name for X11 and WinAPI. apps with the same class will be grouped by the WM
626 * by default the class name will == the root window's name
627*/
628RGFWDEF void RGFW_setClassName(char* name);
629
630/*! this has to be set before createWindow is called, else the fulscreen size is used */
631RGFWDEF void RGFW_setBufferSize(RGFW_area size); /*!< the buffer cannot be resized (by RGFW) */
632
633RGFWDEF RGFW_window* RGFW_createWindow(
634 const char* name, /* name of the window */
635 RGFW_rect rect, /* rect of window */
636 u16 args /* extra arguments (NULL / (u16)0 means no args used)*/
637); /*!< function to create a window struct */
638
639/*! get the size of the screen to an area struct */
640RGFWDEF RGFW_area RGFW_getScreenSize(void);
641
642/*!
643 this function checks an *individual* event (and updates window structure attributes)
644 this means, using this function without a while loop may cause event lag
645
646 ex.
647
648 while (RGFW_window_checkEvent(win) != NULL) [this keeps checking events until it reaches the last one]
649
650 this function is optional if you choose to use event callbacks,
651 although you still need some way to tell RGFW to process events eg. `RGFW_window_checkEvents`
652*/
653
654RGFWDEF RGFW_Event* RGFW_window_checkEvent(RGFW_window* win); /*!< check current event (returns a pointer to win->event or NULL if there is no event)*/
655
656/*!
657 for RGFW_window_eventWait and RGFW_window_checkEvents
658 waitMS -> Allows th e function to keep checking for events even after `RGFW_window_checkEvent == NULL`
659 if waitMS == 0, the loop will not wait for events
660 if waitMS == a positive integer, the loop will wait that many miliseconds after there are no more events until it returns
661 if waitMS == a negative integer, the loop will not return until it gets another event
662*/
663typedef RGFW_ENUM(i32, RGFW_eventWait) {
664 RGFW_NEXT = -1,
665 RGFW_NO_WAIT = 0
666};
667
668/*! sleep until RGFW gets an event or the timer ends (defined by OS) */
669RGFWDEF void RGFW_window_eventWait(RGFW_window* win, i32 waitMS);
670
671/*!
672 check all the events until there are none left,
673 this should only be used if you're using callbacks only
674*/
675RGFWDEF void RGFW_window_checkEvents(RGFW_window* win, i32 waitMS);
676
677/*!
678 Tell RGFW_window_eventWait to stop waiting, to be ran from another thread
679*/
680RGFWDEF void RGFW_stopCheckEvents(void);
681
682/*! window managment functions*/
683RGFWDEF void RGFW_window_close(RGFW_window* win); /*!< close the window and free leftover data */
684
685/*! moves window to a given point */
686RGFWDEF void RGFW_window_move(RGFW_window* win,
687 RGFW_point v/*!< new pos*/
688);
689
690#ifndef RGFW_NO_MONITOR
691 /*! move to a specific monitor */
692 RGFWDEF void RGFW_window_moveToMonitor(RGFW_window* win, RGFW_monitor m /* monitor */);
693#endif
694
695/*! resize window to a current size/area */
696RGFWDEF void RGFW_window_resize(RGFW_window* win, /*!< source window */
697 RGFW_area a/*!< new size*/
698);
699
700/*! set the minimum size a user can shrink a window to a given size/area */
701RGFWDEF void RGFW_window_setMinSize(RGFW_window* win, RGFW_area a);
702/*! set the minimum size a user can extend a window to a given size/area */
703RGFWDEF void RGFW_window_setMaxSize(RGFW_window* win, RGFW_area a);
704
705RGFWDEF void RGFW_window_maximize(RGFW_window* win); /*!< maximize the window size */
706RGFWDEF void RGFW_window_minimize(RGFW_window* win); /*!< minimize the window (in taskbar (per OS))*/
707RGFWDEF void RGFW_window_restore(RGFW_window* win); /*!< restore the window from minimized (per OS)*/
708
709/*! if the window should have a border or not (borderless) based on bool value of `border` */
710RGFWDEF void RGFW_window_setBorder(RGFW_window* win, b8 border);
711
712/*! turn on / off dnd (RGFW_ALLOW_DND stil must be passed to the window)*/
713RGFWDEF void RGFW_window_setDND(RGFW_window* win, b8 allow);
714
715#ifndef RGFW_NO_PASSTHROUGH
716 /*!! turn on / off mouse passthrough */
717 RGFWDEF void RGFW_window_setMousePassthrough(RGFW_window* win, b8 passthrough);
718#endif
719
720/*! rename window to a given string */
721RGFWDEF void RGFW_window_setName(RGFW_window* win,
722 char* name
723);
724
725RGFWDEF void RGFW_window_setIcon(RGFW_window* win, /*!< source window */
726 u8* icon /*!< icon bitmap */,
727 RGFW_area a /*!< width and height of the bitmap*/,
728 i32 channels /*!< how many channels the bitmap has (rgb : 3, rgba : 4) */
729); /*!< image resized by default */
730
731/*!< sets mouse to bitmap (very simular to RGFW_window_setIcon), image NOT resized by default*/
732RGFWDEF void RGFW_window_setMouse(RGFW_window* win, u8* image, RGFW_area a, i32 channels);
733
734/*!< sets the mouse to a standard API cursor (based on RGFW_MOUSE, as seen at the end of the RGFW_HEADER part of this file) */
735RGFWDEF void RGFW_window_setMouseStandard(RGFW_window* win, u8 mouse);
736
737RGFWDEF void RGFW_window_setMouseDefault(RGFW_window* win); /*!< sets the mouse to the default mouse icon */
738/*
739 Locks cursor at the center of the window
740 win->event.point become raw mouse movement data
741
742 this is useful for a 3D camera
743*/
744RGFWDEF void RGFW_window_mouseHold(RGFW_window* win, RGFW_area area);
745/*! stop holding the mouse and let it move freely */
746RGFWDEF void RGFW_window_mouseUnhold(RGFW_window* win);
747
748/*! hide the window */
749RGFWDEF void RGFW_window_hide(RGFW_window* win);
750/*! show the window */
751RGFWDEF void RGFW_window_show(RGFW_window* win);
752
753/*
754 makes it so `RGFW_window_shouldClose` returns true
755 by setting the window event.type to RGFW_quit
756*/
757RGFWDEF void RGFW_window_setShouldClose(RGFW_window* win);
758
759/*! where the mouse is on the screen */
760RGFWDEF RGFW_point RGFW_getGlobalMousePoint(void);
761
762/*! where the mouse is on the window */
763RGFWDEF RGFW_point RGFW_window_getMousePoint(RGFW_window* win);
764
765/*! show the mouse or hide the mouse*/
766RGFWDEF void RGFW_window_showMouse(RGFW_window* win, i8 show);
767/*! move the mouse to a set x, y pos*/
768RGFWDEF void RGFW_window_moveMouse(RGFW_window* win, RGFW_point v);
769
770/*! if the window should close (RGFW_close was sent or escape was pressed) */
771RGFWDEF b8 RGFW_window_shouldClose(RGFW_window* win);
772/*! if window is fullscreen'd */
773RGFWDEF b8 RGFW_window_isFullscreen(RGFW_window* win);
774/*! if window is hidden */
775RGFWDEF b8 RGFW_window_isHidden(RGFW_window* win);
776/*! if window is minimized */
777RGFWDEF b8 RGFW_window_isMinimized(RGFW_window* win);
778/*! if window is maximized */
779RGFWDEF b8 RGFW_window_isMaximized(RGFW_window* win);
780
781/** @} */
782
783/** * @defgroup Monitor
784* @{ */
785
786#ifndef RGFW_NO_MONITOR
787/*
788scale the window to the monitor,
789this is run by default if the user uses the arg `RGFW_SCALE_TO_MONITOR` during window creation
790*/
791RGFWDEF void RGFW_window_scaleToMonitor(RGFW_window* win);
792/*! get the struct of the window's monitor */
793RGFWDEF RGFW_monitor RGFW_window_getMonitor(RGFW_window* win);
794#endif
795
796/** @} */
797
798/** * @defgroup Input
799* @{ */
800
801/*error handling*/
802RGFWDEF b8 RGFW_Error(void); /*!< returns true if an error has occurred (doesn't print errors itself) */
803
804/*! returns true if the key should be shifted */
805RGFWDEF b8 RGFW_shouldShift(u32 keycode, u8 lockState);
806
807/*! get char from RGFW keycode (using a LUT), uses shift'd version if shift = true */
808RGFWDEF char RGFW_keyCodeToChar(u32 keycode, b8 shift);
809/*! get char from RGFW keycode (using a LUT), uses lockState for shouldShift) */
810RGFWDEF char RGFW_keyCodeToCharAuto(u32 keycode, u8 lockState);
811
812/*! if window == NULL, it checks if the key is pressed globally. Otherwise, it checks only if the key is pressed while the window in focus.*/
813RGFWDEF b8 RGFW_isPressed(RGFW_window* win, u8 key); /*!< if key is pressed (key code)*/
814
815RGFWDEF b8 RGFW_wasPressed(RGFW_window* win, u8 key); /*!< if key was pressed (checks previous state only) (key code)*/
816
817RGFWDEF b8 RGFW_isHeld(RGFW_window* win, u8 key); /*!< if key is held (key code)*/
818RGFWDEF b8 RGFW_isReleased(RGFW_window* win, u8 key); /*!< if key is released (key code)*/
819
820/* if a key is pressed and then released, pretty much the same as RGFW_isReleased */
821RGFWDEF b8 RGFW_isClicked(RGFW_window* win, u8 key /*!< key code*/);
822
823/*! if a mouse button is pressed */
824RGFWDEF b8 RGFW_isMousePressed(RGFW_window* win, u8 button /*!< mouse button code */ );
825/*! if a mouse button is held */
826RGFWDEF b8 RGFW_isMouseHeld(RGFW_window* win, u8 button /*!< mouse button code */ );
827/*! if a mouse button was released */
828RGFWDEF b8 RGFW_isMouseReleased(RGFW_window* win, u8 button /*!< mouse button code */ );
829/*! if a mouse button was pressed (checks previous state only) */
830RGFWDEF b8 RGFW_wasMousePressed(RGFW_window* win, u8 button /*!< mouse button code */ );
831/** @} */
832
833/** * @defgroup Clipboard
834* @{ */
835RGFWDEF char* RGFW_readClipboard(size_t* size); /*!< read clipboard data */
836RGFWDEF void RGFW_clipboardFree(char* str); /*!< the string returned from RGFW_readClipboard must be freed */
837
838RGFWDEF void RGFW_writeClipboard(const char* text, u32 textLen); /*!< write text to the clipboard */
839/** @} */
840
841/**
842
843
844 Event callbacks,
845 these are completely optional, you can use the normal
846 RGFW_checkEvent() method if you prefer that
847
848* @defgroup Callbacks
849* @{
850*/
851
852/*! RGFW_windowMoved, the window and its new rect value */
853typedef void (* RGFW_windowmovefunc)(RGFW_window* win, RGFW_rect r);
854/*! RGFW_windowResized, the window and its new rect value */
855typedef void (* RGFW_windowresizefunc)(RGFW_window* win, RGFW_rect r);
856/*! RGFW_quit, the window that was closed */
857typedef void (* RGFW_windowquitfunc)(RGFW_window* win);
858/*! RGFW_focusIn / RGFW_focusOut, the window who's focus has changed and if its inFocus */
859typedef void (* RGFW_focusfunc)(RGFW_window* win, b8 inFocus);
860/*! RGFW_mouseEnter / RGFW_mouseLeave, the window that changed, the point of the mouse (enter only) and if the mouse has entered */
861typedef void (* RGFW_mouseNotifyfunc)(RGFW_window* win, RGFW_point point, b8 status);
862/*! RGFW_mousePosChanged, the window that the move happened on and the new point of the mouse */
863typedef void (* RGFW_mouseposfunc)(RGFW_window* win, RGFW_point point);
864/*! RGFW_dnd_init, the window, the point of the drop on the windows */
865typedef void (* RGFW_dndInitfunc)(RGFW_window* win, RGFW_point point);
866/*! RGFW_windowRefresh, the window that needs to be refreshed */
867typedef void (* RGFW_windowrefreshfunc)(RGFW_window* win);
868/*! RGFW_keyPressed / RGFW_keyReleased, the window that got the event, the keycode, the string version, the state of mod keys, if it was a press (else it's a release) */
869typedef void (* RGFW_keyfunc)(RGFW_window* win, u32 keycode, char keyName[16], u8 lockState, b8 pressed);
870/*! RGFW_mouseButtonPressed / RGFW_mouseButtonReleased, the window that got the event, the button that was pressed, the scroll value, if it was a press (else it's a release) */
871typedef void (* RGFW_mousebuttonfunc)(RGFW_window* win, u8 button, double scroll, b8 pressed);
872/*! RGFW_jsButtonPressed / RGFW_jsButtonReleased, the window that got the event, the button that was pressed, the scroll value, if it was a press (else it's a release) */
873typedef void (* RGFW_jsButtonfunc)(RGFW_window* win, u16 joystick, u8 button, b8 pressed);
874/*! RGFW_jsAxisMove, the window that got the event, the joystick in question, the axis values and the amount of axises */
875typedef void (* RGFW_jsAxisfunc)(RGFW_window* win, u16 joystick, RGFW_point axis[2], u8 axisesCount);
876
877
878/*! RGFW_dnd, the window that had the drop, the drop data and the amount files dropped returns previous callback function (if it was set) */
879#ifdef RGFW_ALLOC_DROPFILES
880 typedef void (* RGFW_dndfunc)(RGFW_window* win, char** droppedFiles, u32 droppedFilesCount);
881#else
882 typedef void (* RGFW_dndfunc)(RGFW_window* win, char droppedFiles[RGFW_MAX_DROPS][RGFW_MAX_PATH], u32 droppedFilesCount);
883#endif
884/*! set callback for a window move event returns previous callback function (if it was set) */
885RGFWDEF RGFW_windowmovefunc RGFW_setWindowMoveCallback(RGFW_windowmovefunc func);
886/*! set callback for a window resize event returns previous callback function (if it was set) */
887RGFWDEF RGFW_windowresizefunc RGFW_setWindowResizeCallback(RGFW_windowresizefunc func);
888/*! set callback for a window quit event returns previous callback function (if it was set) */
889RGFWDEF RGFW_windowquitfunc RGFW_setWindowQuitCallback(RGFW_windowquitfunc func);
890/*! set callback for a mouse move event returns previous callback function (if it was set) */
891RGFWDEF RGFW_mouseposfunc RGFW_setMousePosCallback(RGFW_mouseposfunc func);
892/*! set callback for a window refresh event returns previous callback function (if it was set) */
893RGFWDEF RGFW_windowrefreshfunc RGFW_setWindowRefreshCallback(RGFW_windowrefreshfunc func);
894/*! set callback for a window focus change event returns previous callback function (if it was set) */
895RGFWDEF RGFW_focusfunc RGFW_setFocusCallback(RGFW_focusfunc func);
896/*! set callback for a mouse notify event returns previous callback function (if it was set) */
897RGFWDEF RGFW_mouseNotifyfunc RGFW_setMouseNotifyCallBack(RGFW_mouseNotifyfunc func);
898/*! set callback for a drop event event returns previous callback function (if it was set) */
899RGFWDEF RGFW_dndfunc RGFW_setDndCallback(RGFW_dndfunc func);
900/*! set callback for a start of a drop event returns previous callback function (if it was set) */
901RGFWDEF RGFW_dndInitfunc RGFW_setDndInitCallback(RGFW_dndInitfunc func);
902/*! set callback for a key (press / release ) event returns previous callback function (if it was set) */
903RGFWDEF RGFW_keyfunc RGFW_setKeyCallback(RGFW_keyfunc func);
904/*! set callback for a mouse button (press / release ) event returns previous callback function (if it was set) */
905RGFWDEF RGFW_mousebuttonfunc RGFW_setMouseButtonCallback(RGFW_mousebuttonfunc func);
906/*! set callback for a controller button (press / release ) event returns previous callback function (if it was set) */
907RGFWDEF RGFW_jsButtonfunc RGFW_setjsButtonCallback(RGFW_jsButtonfunc func);
908/*! set callback for a joystick axis mov event returns previous callback function (if it was set) */
909RGFWDEF RGFW_jsAxisfunc RGFW_setjsAxisCallback(RGFW_jsAxisfunc func);
910
911/** @} */
912
913/** * @defgroup Threads
914* @{ */
915
916#ifndef RGFW_NO_THREADS
917 /*! threading functions*/
918
919 /*! NOTE! (for X11/linux) : if you define a window in a thread, it must be run after the original thread's window is created or else there will be a memory error */
920 /*
921 I'd suggest you use sili's threading functions instead
922 if you're going to use sili
923 which is a good idea generally
924 */
925
926 #if defined(__unix__) || defined(__APPLE__) || defined(RGFW_WEBASM)
927 typedef void* (* RGFW_threadFunc_ptr)(void*);
928 #else
929 typedef DWORD (__stdcall *RGFW_threadFunc_ptr) (LPVOID lpThreadParameter);
930 #endif
931
932 RGFWDEF RGFW_thread RGFW_createThread(RGFW_threadFunc_ptr ptr, void* args); /*!< create a thread*/
933 RGFWDEF void RGFW_cancelThread(RGFW_thread thread); /*!< cancels a thread*/
934 RGFWDEF void RGFW_joinThread(RGFW_thread thread); /*!< join thread to current thread */
935 RGFWDEF void RGFW_setThreadPriority(RGFW_thread thread, u8 priority); /*!< sets the priority priority */
936#endif
937
938/** @} */
939
940/** * @defgroup joystick
941* @{ */
942
943/*! joystick count starts at 0*/
944/*!< register joystick to window based on a number (the number is based on when it was connected eg. /dev/js0)*/
945RGFWDEF u16 RGFW_registerJoystick(RGFW_window* win, i32 jsNumber);
946RGFWDEF u16 RGFW_registerJoystickF(RGFW_window* win, char* file);
947
948RGFWDEF u32 RGFW_isPressedJS(RGFW_window* win, u16 controller, u8 button);
949
950/** @} */
951
952/** * @defgroup graphics_API
953* @{ */
954
955/*!< make the window the current opengl drawing context
956
957 NOTE:
958 if you want to switch the graphics context's thread,
959 you have to run RGFW_window_makeCurrent(NULL); on the old thread
960 then RGFW_window_makeCurrent(valid_window) on the new thread
961*/
962RGFWDEF void RGFW_window_makeCurrent(RGFW_window* win);
963
964/*< updates fps / sets fps to cap (must by ran manually by the user at the end of a frame), returns current fps */
965RGFWDEF u32 RGFW_window_checkFPS(RGFW_window* win, u32 fpsCap);
966
967/* supports openGL, directX, OSMesa, EGL and software rendering */
968RGFWDEF void RGFW_window_swapBuffers(RGFW_window* win); /*!< swap the rendering buffer */
969RGFWDEF void RGFW_window_swapInterval(RGFW_window* win, i32 swapInterval);
970
971RGFWDEF void RGFW_window_setGPURender(RGFW_window* win, i8 set);
972RGFWDEF void RGFW_window_setCPURender(RGFW_window* win, i8 set);
973
974/*! native API functions */
975#if defined(RGFW_OPENGL) || defined(RGFW_EGL)
976 /*! OpenGL init hints */
977 RGFWDEF void RGFW_setGLStencil(i32 stencil); /*!< set stencil buffer bit size (8 by default) */
978 RGFWDEF void RGFW_setGLSamples(i32 samples); /*!< set number of sampiling buffers (4 by default) */
979 RGFWDEF void RGFW_setGLStereo(i32 stereo); /*!< use GL_STEREO (GL_FALSE by default) */
980 RGFWDEF void RGFW_setGLAuxBuffers(i32 auxBuffers); /*!< number of aux buffers (0 by default) */
981
982 /*! which profile to use for the opengl verion */
983 typedef RGFW_ENUM(u8, RGFW_GL_profile) { RGFW_GL_CORE = 0, RGFW_GL_COMPATIBILITY };
984 /*! Set OpenGL version hint (core or compatibility profile)*/
985 RGFWDEF void RGFW_setGLVersion(RGFW_GL_profile profile, i32 major, i32 minor);
986 RGFWDEF void RGFW_setDoubleBuffer(b8 useDoubleBuffer);
987 RGFWDEF void* RGFW_getProcAddress(const char* procname); /*!< get native opengl proc address */
988 RGFWDEF void RGFW_window_makeCurrent_OpenGL(RGFW_window* win); /*!< to be called by RGFW_window_makeCurrent */
989#elif defined(RGFW_DIRECTX)
990 typedef struct {
991 IDXGIFactory* pFactory;
992 IDXGIAdapter* pAdapter;
993 ID3D11Device* pDevice;
994 ID3D11DeviceContext* pDeviceContext;
995 } RGFW_directXinfo;
996
997 /*
998 RGFW stores a global instance of RGFW_directXinfo,
999 you can use this function to get a pointer the instance
1000 */
1001 RGFWDEF RGFW_directXinfo* RGFW_getDirectXInfo(void);
1002#endif
1003
1004/** @} */
1005
1006/** * @defgroup Supporting
1007* @{ */
1008RGFWDEF u64 RGFW_getTime(void); /*!< get time in seconds */
1009RGFWDEF u64 RGFW_getTimeNS(void); /*!< get time in nanoseconds */
1010RGFWDEF void RGFW_sleep(u64 milisecond); /*!< sleep for a set time */
1011
1012/*!
1013 key codes and mouse icon enums
1014*/
1015
1016typedef RGFW_ENUM(u8, RGFW_Key) {
1017 RGFW_KEY_NULL = 0,
1018 RGFW_Escape,
1019 RGFW_F1,
1020 RGFW_F2,
1021 RGFW_F3,
1022 RGFW_F4,
1023 RGFW_F5,
1024 RGFW_F6,
1025 RGFW_F7,
1026 RGFW_F8,
1027 RGFW_F9,
1028 RGFW_F10,
1029 RGFW_F11,
1030 RGFW_F12,
1031
1032 RGFW_Backtick,
1033
1034 RGFW_0,
1035 RGFW_1,
1036 RGFW_2,
1037 RGFW_3,
1038 RGFW_4,
1039 RGFW_5,
1040 RGFW_6,
1041 RGFW_7,
1042 RGFW_8,
1043 RGFW_9,
1044
1045 RGFW_Minus,
1046 RGFW_Equals,
1047 RGFW_BackSpace,
1048 RGFW_Tab,
1049 RGFW_CapsLock,
1050 RGFW_ShiftL,
1051 RGFW_ControlL,
1052 RGFW_AltL,
1053 RGFW_SuperL,
1054 RGFW_ShiftR,
1055 RGFW_ControlR,
1056 RGFW_AltR,
1057 RGFW_SuperR,
1058 RGFW_Space,
1059
1060 RGFW_a,
1061 RGFW_b,
1062 RGFW_c,
1063 RGFW_d,
1064 RGFW_e,
1065 RGFW_f,
1066 RGFW_g,
1067 RGFW_h,
1068 RGFW_i,
1069 RGFW_j,
1070 RGFW_k,
1071 RGFW_l,
1072 RGFW_m,
1073 RGFW_n,
1074 RGFW_o,
1075 RGFW_p,
1076 RGFW_q,
1077 RGFW_r,
1078 RGFW_s,
1079 RGFW_t,
1080 RGFW_u,
1081 RGFW_v,
1082 RGFW_w,
1083 RGFW_x,
1084 RGFW_y,
1085 RGFW_z,
1086
1087 RGFW_Period,
1088 RGFW_Comma,
1089 RGFW_Slash,
1090 RGFW_Bracket,
1091 RGFW_CloseBracket,
1092 RGFW_Semicolon,
1093 RGFW_Return,
1094 RGFW_Quote,
1095 RGFW_BackSlash,
1096
1097 RGFW_Up,
1098 RGFW_Down,
1099 RGFW_Left,
1100 RGFW_Right,
1101
1102 RGFW_Delete,
1103 RGFW_Insert,
1104 RGFW_End,
1105 RGFW_Home,
1106 RGFW_PageUp,
1107 RGFW_PageDown,
1108
1109 RGFW_Numlock,
1110 RGFW_KP_Slash,
1111 RGFW_Multiply,
1112 RGFW_KP_Minus,
1113 RGFW_KP_1,
1114 RGFW_KP_2,
1115 RGFW_KP_3,
1116 RGFW_KP_4,
1117 RGFW_KP_5,
1118 RGFW_KP_6,
1119 RGFW_KP_7,
1120 RGFW_KP_8,
1121 RGFW_KP_9,
1122 RGFW_KP_0,
1123 RGFW_KP_Period,
1124 RGFW_KP_Return,
1125
1126 final_key,
1127};
1128
1129
1130typedef RGFW_ENUM(u8, RGFW_mouseIcons) {
1131 RGFW_MOUSE_NORMAL = 0,
1132 RGFW_MOUSE_ARROW,
1133 RGFW_MOUSE_IBEAM,
1134 RGFW_MOUSE_CROSSHAIR,
1135 RGFW_MOUSE_POINTING_HAND,
1136 RGFW_MOUSE_RESIZE_EW,
1137 RGFW_MOUSE_RESIZE_NS,
1138 RGFW_MOUSE_RESIZE_NWSE,
1139 RGFW_MOUSE_RESIZE_NESW,
1140 RGFW_MOUSE_RESIZE_ALL,
1141 RGFW_MOUSE_NOT_ALLOWED,
1142};
1143
1144/** @} */
1145
1146#endif /* RGFW_HEADER */
1147
1148/*
1149Example to get you started :
1150
1151linux : gcc main.c -lX11 -lXcursor -lGL
1152windows : gcc main.c -lopengl32 -lshell32 -lgdi32
1153macos : gcc main.c -framework Foundation -framework AppKit -framework OpenGL -framework CoreVideo
1154
1155#define RGFW_IMPLEMENTATION
1156#include "RGFW.h"
1157
1158u8 icon[4 * 3 * 3] = {0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF};
1159
1160int main() {
1161 RGFW_window* win = RGFW_createWindow("name", RGFW_RECT(500, 500, 500, 500), (u64)0);
1162
1163 RGFW_window_setIcon(win, icon, RGFW_AREA(3, 3), 4);
1164
1165 for (;;) {
1166 RGFW_window_checkEvent(win); // NOTE: checking events outside of a while loop may cause input lag
1167 if (win->event.type == RGFW_quit || RGFW_isPressed(win, RGFW_Escape))
1168 break;
1169
1170 RGFW_window_swapBuffers(win);
1171
1172 glClearColor(0xFF, 0XFF, 0xFF, 0xFF);
1173 glClear(GL_COLOR_BUFFER_BIT);
1174 }
1175
1176 RGFW_window_close(win);
1177}
1178
1179 compiling :
1180
1181 if you wish to compile the library all you have to do is create a new file with this in it
1182
1183 rgfw.c
1184 #define RGFW_IMPLEMENTATION
1185 #include "RGFW.h"
1186
1187 then you can use gcc (or whatever compile you wish to use) to compile the library into object file
1188
1189 ex. gcc -c RGFW.c -fPIC
1190
1191 after you compile the library into an object file, you can also turn the object file into an static or shared library
1192
1193 (commands ar and gcc can be replaced with whatever equivalent your system uses)
1194 static : ar rcs RGFW.a RGFW.o
1195 shared :
1196 windows:
1197 gcc -shared RGFW.o -lwinmm -lopengl32 -lshell32 -lgdi32 -o RGFW.dll
1198 linux:
1199 gcc -shared RGFW.o -lX11 -lXcursor -lGL -lXrandr -o RGFW.so
1200 macos:
1201 gcc -shared RGFW.o -framework Foundation -framework AppKit -framework OpenGL -framework CoreVideo
1202*/
1203
1204#ifdef RGFW_X11
1205 #define RGFW_OS_BASED_VALUE(l, w, m, h, ww) l
1206#elif defined(RGFW_WINDOWS)
1207 #define RGFW_OS_BASED_VALUE(l, w, m, h, ww) w
1208#elif defined(RGFW_MACOS)
1209 #define RGFW_OS_BASED_VALUE(l, w, m, h, ww) m
1210#elif defined(RGFW_WEBASM)
1211 #define RGFW_OS_BASED_VALUE(l, w, m, h, ww) h
1212#elif defined(RGFW_WAYLAND)
1213 #define RGFW_OS_BASED_VALUE(l, w, m, h, ww) ww
1214#endif
1215
1216
1217#ifdef RGFW_IMPLEMENTATION
1218
1219#include <stdio.h>
1220#include <string.h>
1221#include <math.h>
1222#include <assert.h>
1223
1224/*
1225RGFW_IMPLEMENTATION starts with generic RGFW defines
1226
1227This is the start of keycode data
1228
1229 Why not use macros instead of the numbers itself?
1230 Windows -> Not all virtual keys are macros (VK_0 - VK_1, VK_a - VK_z)
1231 Linux -> Only symcodes are values, (XK_0 - XK_1, XK_a - XK_z) are larger than 0xFF00, I can't find any way to work with them without making the array an unreasonable size
1232 MacOS -> windows and linux already don't have keycodes as macros, so there's no point
1233*/
1234
1235
1236
1237/*
1238 the c++ compiler doesn't support setting up an array like,
1239 we'll have to do it during runtime using a function & this messy setup
1240*/
1241#ifndef __cplusplus
1242#define RGFW_NEXT ,
1243#define RGFW_MAP
1244#else
1245#define RGFW_NEXT ;
1246#define RGFW_MAP RGFW_keycodes
1247#endif
1248
1249#ifdef RGFW_WAYLAND
1250#include <linux/input-event-codes.h>
1251#endif
1252
1253u8 RGFW_keycodes [RGFW_OS_BASED_VALUE(136, 337, 128, DOM_VK_WIN_OEM_CLEAR + 1, 130)] = {
1254#ifdef __cplusplus
1255 0
1256};
1257void RGFW_init_keys(void) {
1258#endif
1259 RGFW_MAP [RGFW_OS_BASED_VALUE(49, 192, 50, DOM_VK_BACK_QUOTE, KEY_GRAVE)] = RGFW_Backtick RGFW_NEXT
1260
1261 RGFW_MAP [RGFW_OS_BASED_VALUE(19, 0x30, 29, DOM_VK_0, KEY_0)] = RGFW_0 RGFW_NEXT
1262 RGFW_MAP [RGFW_OS_BASED_VALUE(10, 0x31, 18, DOM_VK_1, KEY_1)] = RGFW_1 RGFW_NEXT
1263 RGFW_MAP [RGFW_OS_BASED_VALUE(11, 0x32, 19, DOM_VK_2, KEY_2)] = RGFW_2 RGFW_NEXT
1264 RGFW_MAP [RGFW_OS_BASED_VALUE(12, 0x33, 20, DOM_VK_3, KEY_3)] = RGFW_3 RGFW_NEXT
1265 RGFW_MAP [RGFW_OS_BASED_VALUE(13, 0x34, 21, DOM_VK_4, KEY_4)] = RGFW_4 RGFW_NEXT
1266 RGFW_MAP [RGFW_OS_BASED_VALUE(14, 0x35, 23, DOM_VK_5, KEY_5)] = RGFW_5 RGFW_NEXT
1267 RGFW_MAP [RGFW_OS_BASED_VALUE(15, 0x36, 22, DOM_VK_6, KEY_6)] = RGFW_6 RGFW_NEXT
1268 RGFW_MAP [RGFW_OS_BASED_VALUE(16, 0x37, 26, DOM_VK_7, KEY_7)] = RGFW_7 RGFW_NEXT
1269 RGFW_MAP [RGFW_OS_BASED_VALUE(17, 0x38, 28, DOM_VK_8, KEY_8)] = RGFW_8 RGFW_NEXT
1270 RGFW_MAP [RGFW_OS_BASED_VALUE(18, 0x39, 25, DOM_VK_9, KEY_9)] = RGFW_9,
1271
1272 RGFW_MAP [RGFW_OS_BASED_VALUE(65, 0x20, 49, DOM_VK_SPACE, KEY_SPACE)] = RGFW_Space,
1273
1274 RGFW_MAP [RGFW_OS_BASED_VALUE(38, 0x41, 0, DOM_VK_A, KEY_A)] = RGFW_a RGFW_NEXT
1275 RGFW_MAP [RGFW_OS_BASED_VALUE(56, 0x42, 11, DOM_VK_B, KEY_B)] = RGFW_b RGFW_NEXT
1276 RGFW_MAP [RGFW_OS_BASED_VALUE(54, 0x43, 8, DOM_VK_C, KEY_C)] = RGFW_c RGFW_NEXT
1277 RGFW_MAP [RGFW_OS_BASED_VALUE(40, 0x44, 2, DOM_VK_D, KEY_D)] = RGFW_d RGFW_NEXT
1278 RGFW_MAP [RGFW_OS_BASED_VALUE(26, 0x45, 14, DOM_VK_E, KEY_E)] = RGFW_e RGFW_NEXT
1279 RGFW_MAP [RGFW_OS_BASED_VALUE(41, 0x46, 3, DOM_VK_F, KEY_F)] = RGFW_f RGFW_NEXT
1280 RGFW_MAP [RGFW_OS_BASED_VALUE(42, 0x47, 5, DOM_VK_G, KEY_G)] = RGFW_g RGFW_NEXT
1281 RGFW_MAP [RGFW_OS_BASED_VALUE(43, 0x48, 4, DOM_VK_H, KEY_H)] = RGFW_h RGFW_NEXT
1282 RGFW_MAP [RGFW_OS_BASED_VALUE(31, 0x49, 34, DOM_VK_I, KEY_I)] = RGFW_i RGFW_NEXT
1283 RGFW_MAP [RGFW_OS_BASED_VALUE(44, 0x4A, 38, DOM_VK_J, KEY_J)] = RGFW_j RGFW_NEXT
1284 RGFW_MAP [RGFW_OS_BASED_VALUE(45, 0x4B, 40, DOM_VK_K, KEY_K)] = RGFW_k RGFW_NEXT
1285 RGFW_MAP [RGFW_OS_BASED_VALUE(46, 0x4C, 37, DOM_VK_L, KEY_L)] = RGFW_l RGFW_NEXT
1286 RGFW_MAP [RGFW_OS_BASED_VALUE(58, 0x4D, 46, DOM_VK_M, KEY_M)] = RGFW_m RGFW_NEXT
1287 RGFW_MAP [RGFW_OS_BASED_VALUE(57, 0x4E, 45, DOM_VK_N, KEY_N)] = RGFW_n RGFW_NEXT
1288 RGFW_MAP [RGFW_OS_BASED_VALUE(32, 0x4F, 31, DOM_VK_O, KEY_O)] = RGFW_o RGFW_NEXT
1289 RGFW_MAP [RGFW_OS_BASED_VALUE(33, 0x50, 35, DOM_VK_P, KEY_P)] = RGFW_p RGFW_NEXT
1290 RGFW_MAP [RGFW_OS_BASED_VALUE(24, 0x51, 12, DOM_VK_Q, KEY_Q)] = RGFW_q RGFW_NEXT
1291 RGFW_MAP [RGFW_OS_BASED_VALUE(27, 0x52, 15, DOM_VK_R, KEY_R)] = RGFW_r RGFW_NEXT
1292 RGFW_MAP [RGFW_OS_BASED_VALUE(39, 0x53, 1, DOM_VK_S, KEY_S)] = RGFW_s RGFW_NEXT
1293 RGFW_MAP [RGFW_OS_BASED_VALUE(28, 0x54, 17, DOM_VK_T, KEY_T)] = RGFW_t RGFW_NEXT
1294 RGFW_MAP [RGFW_OS_BASED_VALUE(30, 0x55, 32, DOM_VK_U, KEY_U)] = RGFW_u RGFW_NEXT
1295 RGFW_MAP [RGFW_OS_BASED_VALUE(55, 0x56, 9, DOM_VK_V, KEY_V)] = RGFW_v RGFW_NEXT
1296 RGFW_MAP [RGFW_OS_BASED_VALUE(25, 0x57, 13, DOM_VK_W, KEY_W)] = RGFW_w RGFW_NEXT
1297 RGFW_MAP [RGFW_OS_BASED_VALUE(53, 0x58, 7, DOM_VK_X, KEY_X)] = RGFW_x RGFW_NEXT
1298 RGFW_MAP [RGFW_OS_BASED_VALUE(29, 0x59, 16, DOM_VK_Y, KEY_Y)] = RGFW_y RGFW_NEXT
1299 RGFW_MAP [RGFW_OS_BASED_VALUE(52, 0x5A, 6, DOM_VK_Z, KEY_Z)] = RGFW_z,
1300
1301 RGFW_MAP [RGFW_OS_BASED_VALUE(60, 190, 47, DOM_VK_PERIOD, KEY_DOT)] = RGFW_Period RGFW_NEXT
1302 RGFW_MAP [RGFW_OS_BASED_VALUE(59, 188, 43, DOM_VK_COMMA, KEY_COMMA)] = RGFW_Comma RGFW_NEXT
1303 RGFW_MAP [RGFW_OS_BASED_VALUE(61, 191, 44, DOM_VK_SLASH, KEY_SLASH)] = RGFW_Slash RGFW_NEXT
1304 RGFW_MAP [RGFW_OS_BASED_VALUE(34, 219, 33, DOM_VK_OPEN_BRACKET, KEY_LEFTBRACE)] = RGFW_Bracket RGFW_NEXT
1305 RGFW_MAP [RGFW_OS_BASED_VALUE(35, 221, 30, DOM_VK_CLOSE_BRACKET, KEY_RIGHTBRACE)] = RGFW_CloseBracket RGFW_NEXT
1306 RGFW_MAP [RGFW_OS_BASED_VALUE(47, 186, 41, DOM_VK_SEMICOLON, KEY_SEMICOLON)] = RGFW_Semicolon RGFW_NEXT
1307 RGFW_MAP [RGFW_OS_BASED_VALUE(48, 222, 39, DOM_VK_QUOTE, KEY_APOSTROPHE)] = RGFW_Quote RGFW_NEXT
1308 RGFW_MAP [RGFW_OS_BASED_VALUE(51, 322, 42, DOM_VK_BACK_SLASH, KEY_BACKSLASH)] = RGFW_BackSlash,
1309
1310 RGFW_MAP [RGFW_OS_BASED_VALUE(36, 0x0D, 36, DOM_VK_RETURN, KEY_ENTER)] = RGFW_Return RGFW_NEXT
1311 RGFW_MAP [RGFW_OS_BASED_VALUE(119, 0x2E, 118, DOM_VK_DELETE, KEY_DELETE)] = RGFW_Delete RGFW_NEXT
1312 RGFW_MAP [RGFW_OS_BASED_VALUE(77, 0x90, 72, DOM_VK_NUM_LOCK, KEY_NUMLOCK)] = RGFW_Numlock RGFW_NEXT
1313 RGFW_MAP [RGFW_OS_BASED_VALUE(106, 0x6F, 82, DOM_VK_DIVIDE, KEY_KPSLASH)] = RGFW_KP_Slash RGFW_NEXT
1314 RGFW_MAP [RGFW_OS_BASED_VALUE(63, 0x6A, 76, DOM_VK_MULTIPLY, KEY_KPASTERISK)] = RGFW_Multiply RGFW_NEXT
1315 RGFW_MAP [RGFW_OS_BASED_VALUE(82, 0x6D, 67, DOM_VK_SUBTRACT, KEY_KPMINUS)] = RGFW_KP_Minus RGFW_NEXT
1316 RGFW_MAP [RGFW_OS_BASED_VALUE(87, 0x61, 84, DOM_VK_NUMPAD1, KEY_KP1)] = RGFW_KP_1 RGFW_NEXT
1317 RGFW_MAP [RGFW_OS_BASED_VALUE(88, 0x62, 85, DOM_VK_NUMPAD2, KEY_KP2)] = RGFW_KP_2 RGFW_NEXT
1318 RGFW_MAP [RGFW_OS_BASED_VALUE(89, 0x63, 86, DOM_VK_NUMPAD3, KEY_KP3)] = RGFW_KP_3 RGFW_NEXT
1319 RGFW_MAP [RGFW_OS_BASED_VALUE(83, 0x64, 87, DOM_VK_NUMPAD4, KEY_KP4)] = RGFW_KP_4 RGFW_NEXT
1320 RGFW_MAP [RGFW_OS_BASED_VALUE(84, 0x65, 88, DOM_VK_NUMPAD5, KEY_KP5)] = RGFW_KP_5 RGFW_NEXT
1321 RGFW_MAP [RGFW_OS_BASED_VALUE(85, 0x66, 89, DOM_VK_NUMPAD6, KEY_KP6)] = RGFW_KP_6 RGFW_NEXT
1322 RGFW_MAP [RGFW_OS_BASED_VALUE(79, 0x67, 90, DOM_VK_NUMPAD7, KEY_KP7)] = RGFW_KP_7 RGFW_NEXT
1323 RGFW_MAP [RGFW_OS_BASED_VALUE(80, 0x68, 92, DOM_VK_NUMPAD8, KEY_KP8)] = RGFW_KP_8 RGFW_NEXT
1324 RGFW_MAP [RGFW_OS_BASED_VALUE(81, 0x69, 93, DOM_VK_NUMPAD9, KEY_KP9)] = RGFW_KP_9 RGFW_NEXT
1325 RGFW_MAP [RGFW_OS_BASED_VALUE(90, 0x60, 83, DOM_VK_NUMPAD0, KEY_KP0)] = RGFW_KP_0 RGFW_NEXT
1326 RGFW_MAP [RGFW_OS_BASED_VALUE(91, 0x6E, 65, DOM_VK_DECIMAL, KEY_KPDOT)] = RGFW_KP_Period RGFW_NEXT
1327 RGFW_MAP [RGFW_OS_BASED_VALUE(104, 0x92, 77, 0, KEY_KPENTER)] = RGFW_KP_Return,
1328
1329 RGFW_MAP [RGFW_OS_BASED_VALUE(20, 189, 27, DOM_VK_HYPHEN_MINUS, KEY_MINUS)] = RGFW_Minus RGFW_NEXT
1330 RGFW_MAP [RGFW_OS_BASED_VALUE(21, 187, 24, DOM_VK_EQUALS, KEY_EQUAL)] = RGFW_Equals RGFW_NEXT
1331 RGFW_MAP [RGFW_OS_BASED_VALUE(22, 8, 51, DOM_VK_BACK_SPACE, KEY_BACKSPACE)] = RGFW_BackSpace RGFW_NEXT
1332 RGFW_MAP [RGFW_OS_BASED_VALUE(23, 0x09, 48, DOM_VK_TAB, KEY_TAB)] = RGFW_Tab RGFW_NEXT
1333 RGFW_MAP [RGFW_OS_BASED_VALUE(66, 20, 57, DOM_VK_CAPS_LOCK, KEY_CAPSLOCK)] = RGFW_CapsLock RGFW_NEXT
1334 RGFW_MAP [RGFW_OS_BASED_VALUE(50, 0x10, 56, DOM_VK_SHIFT, KEY_LEFTSHIFT)] = RGFW_ShiftL RGFW_NEXT
1335 RGFW_MAP [RGFW_OS_BASED_VALUE(37, 0x11, 59, DOM_VK_CONTROL, KEY_LEFTCTRL)] = RGFW_ControlL RGFW_NEXT
1336 RGFW_MAP [RGFW_OS_BASED_VALUE(64,0x12, 58, DOM_VK_ALT, KEY_LEFTALT)] = RGFW_AltL RGFW_NEXT
1337 RGFW_MAP [RGFW_OS_BASED_VALUE(133, 0x5B, 55, DOM_VK_WIN, KEY_LEFTMETA)] = RGFW_SuperL,
1338
1339 #if !defined(RGFW_WINDOWS) && !defined(RGFW_MACOS) && !defined(RGFW_WEBASM)
1340 RGFW_MAP [RGFW_OS_BASED_VALUE(105, 0x11, 59, 0, KEY_RIGHTCTRL)] = RGFW_ControlR RGFW_NEXT
1341 RGFW_MAP [RGFW_OS_BASED_VALUE(135, 0xA4, 55, 0, KEY_RIGHTMETA)] = RGFW_SuperR,
1342 RGFW_MAP [RGFW_OS_BASED_VALUE(62, 0x5C, 56, 0, KEY_RIGHTSHIFT)] = RGFW_ShiftR RGFW_NEXT
1343 RGFW_MAP [RGFW_OS_BASED_VALUE(108, 165, 58, 0, KEY_RIGHTALT)] = RGFW_AltR,
1344 #endif
1345
1346 RGFW_MAP [RGFW_OS_BASED_VALUE(67, 0x70, 127, DOM_VK_F1, KEY_F1)] = RGFW_F1 RGFW_NEXT
1347 RGFW_MAP [RGFW_OS_BASED_VALUE(68, 0x71, 121, DOM_VK_F2, KEY_F2)] = RGFW_F2 RGFW_NEXT
1348 RGFW_MAP [RGFW_OS_BASED_VALUE(69, 0x72, 100, DOM_VK_F3, KEY_F3)] = RGFW_F3 RGFW_NEXT
1349 RGFW_MAP [RGFW_OS_BASED_VALUE(70, 0x73, 119, DOM_VK_F4, KEY_F4)] = RGFW_F4 RGFW_NEXT
1350 RGFW_MAP [RGFW_OS_BASED_VALUE(71, 0x74, 97, DOM_VK_F5, KEY_F5)] = RGFW_F5 RGFW_NEXT
1351 RGFW_MAP [RGFW_OS_BASED_VALUE(72, 0x75, 98, DOM_VK_F6, KEY_F6)] = RGFW_F6 RGFW_NEXT
1352 RGFW_MAP [RGFW_OS_BASED_VALUE(73, 0x76, 99, DOM_VK_F7, KEY_F7)] = RGFW_F7 RGFW_NEXT
1353 RGFW_MAP [RGFW_OS_BASED_VALUE(74, 0x77, 101, DOM_VK_F8, KEY_F8)] = RGFW_F8 RGFW_NEXT
1354 RGFW_MAP [RGFW_OS_BASED_VALUE(75, 0x78, 102, DOM_VK_F9, KEY_F9)] = RGFW_F9 RGFW_NEXT
1355 RGFW_MAP [RGFW_OS_BASED_VALUE(76, 0x79, 110, DOM_VK_F10, KEY_F10)] = RGFW_F10 RGFW_NEXT
1356 RGFW_MAP [RGFW_OS_BASED_VALUE(95, 0x7A, 104, DOM_VK_F11, KEY_F11)] = RGFW_F11 RGFW_NEXT
1357 RGFW_MAP [RGFW_OS_BASED_VALUE(96, 0x7B, 112, DOM_VK_F12, KEY_F12)] = RGFW_F12 RGFW_NEXT
1358 RGFW_MAP [RGFW_OS_BASED_VALUE(111, 0x26, 126, DOM_VK_UP, KEY_UP)] = RGFW_Up RGFW_NEXT
1359 RGFW_MAP [RGFW_OS_BASED_VALUE(116, 0x28, 125, DOM_VK_DOWN, KEY_DOWN)] = RGFW_Down RGFW_NEXT
1360 RGFW_MAP [RGFW_OS_BASED_VALUE(113, 0x25, 123, DOM_VK_LEFT, KEY_LEFT)] = RGFW_Left RGFW_NEXT
1361 RGFW_MAP [RGFW_OS_BASED_VALUE(114, 0x27, 124, DOM_VK_RIGHT, KEY_RIGHT)] = RGFW_Right RGFW_NEXT
1362 RGFW_MAP [RGFW_OS_BASED_VALUE(118, 0x2D, 115, DOM_VK_INSERT, KEY_INSERT)] = RGFW_Insert RGFW_NEXT
1363 RGFW_MAP [RGFW_OS_BASED_VALUE(115, 0x23, 120, DOM_VK_END, KEY_END)] = RGFW_End RGFW_NEXT
1364 RGFW_MAP [RGFW_OS_BASED_VALUE(112, 336, 117, DOM_VK_PAGE_UP, KEY_PAGEUP)] = RGFW_PageUp RGFW_NEXT
1365 RGFW_MAP [RGFW_OS_BASED_VALUE(117, 325, 122, DOM_VK_PAGE_DOWN, KEY_PAGEDOWN)] = RGFW_PageDown RGFW_NEXT
1366 RGFW_MAP [RGFW_OS_BASED_VALUE(9, 0x1B, 53, DOM_VK_ESCAPE, KEY_ESC)] = RGFW_Escape RGFW_NEXT
1367 RGFW_MAP [RGFW_OS_BASED_VALUE(110, 0x24, 116, DOM_VK_HOME, KEY_HOME)] = RGFW_Home RGFW_NEXT
1368#ifndef __cplusplus
1369};
1370#else
1371}
1372#endif
1373
1374#undef RGFW_NEXT
1375#undef RGFW_MAP
1376
1377typedef struct {
1378 b8 current : 1;
1379 b8 prev : 1;
1380} RGFW_keyState;
1381
1382RGFW_keyState RGFW_keyboard[final_key] = { {0, 0} };
1383
1384RGFWDEF u32 RGFW_apiKeyCodeToRGFW(u32 keycode);
1385
1386u32 RGFW_apiKeyCodeToRGFW(u32 keycode) {
1387 #ifdef __cplusplus
1388 if (RGFW_OS_BASED_VALUE(49, 192, 50, DOM_VK_BACK_QUOTE, KEY_GRAVE) != RGFW_Backtick) {
1389 RGFW_init_keys();
1390 }
1391 #endif
1392
1393 /* make sure the key isn't out of bounds */
1394 if (keycode > sizeof(RGFW_keycodes) / sizeof(u8))
1395 return 0;
1396
1397 return RGFW_keycodes[keycode];
1398}
1399
1400RGFWDEF void RGFW_resetKey(void);
1401void RGFW_resetKey(void) {
1402 size_t len = final_key; /*!< last_key == length */
1403
1404 size_t i; /*!< reset each previous state */
1405 for (i = 0; i < len; i++)
1406 RGFW_keyboard[i].prev = 0;
1407}
1408
1409b8 RGFW_shouldShift(u32 keycode, u8 lockState) {
1410 #define RGFW_xor(x, y) (( (x) && (!(y)) ) || ((y) && (!(x)) ))
1411 b8 caps4caps = (lockState & RGFW_CAPSLOCK) && ((keycode >= RGFW_a) && (keycode <= RGFW_z));
1412 b8 shouldShift = RGFW_xor((RGFW_isPressed(NULL, RGFW_ShiftL) || RGFW_isPressed(NULL, RGFW_ShiftR)), caps4caps);
1413 #undef RGFW_xor
1414
1415 return shouldShift;
1416}
1417
1418char RGFW_keyCodeToChar(u32 keycode, b8 shift) {
1419 static const char map[] = {
1420 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '`', '0', '1', '2', '3', '4', '5', '6', '7', '8',
1421 '9', '-', '=', 0, '\t', 0, 0, 0, 0, 0, 0, 0, 0, 0, ' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
1422 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '.', ',', '/', '[', ']', ';', '\n', '\'', '\\',
1423 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '/', '*', '-', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '\n'
1424 };
1425
1426 static const char mapCaps[] = {
1427 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '~', ')', '!', '@', '#', '$', '%', '^', '&', '*',
1428 '(', '_', '+', 0, '0', 0, 0, 0, 0, 0, 0, 0, 0, 0, ' ', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
1429 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
1430 'X', 'Y', 'Z', '>', '<', '?', '{', '}', ':', '\n', '"', '|',
1431 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '?', '*', '-', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
1432 };
1433
1434 if (shift == RGFW_FALSE)
1435 return map[keycode];
1436 return mapCaps[keycode];
1437}
1438
1439char RGFW_keyCodeToCharAuto(u32 keycode, u8 lockState) { return RGFW_keyCodeToChar(keycode, RGFW_shouldShift(keycode, lockState)); }
1440
1441/*
1442 this is the end of keycode data
1443*/
1444
1445/* joystick data */
1446u8 RGFW_jsPressed[4][16]; /*!< if a key is currently pressed or not (per joystick) */
1447
1448i32 RGFW_joysticks[4]; /*!< limit of 4 joysticks at a time */
1449u16 RGFW_joystickCount; /*!< the actual amount of joysticks */
1450
1451/*
1452 event callback defines start here
1453*/
1454
1455
1456/*
1457 These exist to avoid the
1458 if (func == NULL) check
1459 for (allegedly) better performance
1460*/
1461void RGFW_windowmovefuncEMPTY(RGFW_window* win, RGFW_rect r) { RGFW_UNUSED(win); RGFW_UNUSED(r); }
1462void RGFW_windowresizefuncEMPTY(RGFW_window* win, RGFW_rect r) { RGFW_UNUSED(win); RGFW_UNUSED(r); }
1463void RGFW_windowquitfuncEMPTY(RGFW_window* win) { RGFW_UNUSED(win); }
1464void RGFW_focusfuncEMPTY(RGFW_window* win, b8 inFocus) {RGFW_UNUSED(win); RGFW_UNUSED(inFocus);}
1465void RGFW_mouseNotifyfuncEMPTY(RGFW_window* win, RGFW_point point, b8 status) {RGFW_UNUSED(win); RGFW_UNUSED(point); RGFW_UNUSED(status);}
1466void RGFW_mouseposfuncEMPTY(RGFW_window* win, RGFW_point point) {RGFW_UNUSED(win); RGFW_UNUSED(point);}
1467void RGFW_dndInitfuncEMPTY(RGFW_window* win, RGFW_point point) {RGFW_UNUSED(win); RGFW_UNUSED(point);}
1468void RGFW_windowrefreshfuncEMPTY(RGFW_window* win) {RGFW_UNUSED(win); }
1469void RGFW_keyfuncEMPTY(RGFW_window* win, u32 keycode, char keyName[16], u8 lockState, b8 pressed) {RGFW_UNUSED(win); RGFW_UNUSED(keycode); RGFW_UNUSED(keyName); RGFW_UNUSED(lockState); RGFW_UNUSED(pressed);}
1470void RGFW_mousebuttonfuncEMPTY(RGFW_window* win, u8 button, double scroll, b8 pressed) {RGFW_UNUSED(win); RGFW_UNUSED(button); RGFW_UNUSED(scroll); RGFW_UNUSED(pressed);}
1471void RGFW_jsButtonfuncEMPTY(RGFW_window* win, u16 joystick, u8 button, b8 pressed){RGFW_UNUSED(win); RGFW_UNUSED(joystick); RGFW_UNUSED(button); RGFW_UNUSED(pressed); }
1472void RGFW_jsAxisfuncEMPTY(RGFW_window* win, u16 joystick, RGFW_point axis[2], u8 axisesCount){RGFW_UNUSED(win); RGFW_UNUSED(joystick); RGFW_UNUSED(axis); RGFW_UNUSED(axisesCount); }
1473
1474#ifdef RGFW_ALLOC_DROPFILES
1475void RGFW_dndfuncEMPTY(RGFW_window* win, char** droppedFiles, u32 droppedFilesCount) {RGFW_UNUSED(win); RGFW_UNUSED(droppedFiles); RGFW_UNUSED(droppedFilesCount);}
1476#else
1477void RGFW_dndfuncEMPTY(RGFW_window* win, char droppedFiles[RGFW_MAX_DROPS][RGFW_MAX_PATH], u32 droppedFilesCount) {RGFW_UNUSED(win); RGFW_UNUSED(droppedFiles); RGFW_UNUSED(droppedFilesCount);}
1478#endif
1479
1480RGFW_windowmovefunc RGFW_windowMoveCallback = RGFW_windowmovefuncEMPTY;
1481RGFW_windowresizefunc RGFW_windowResizeCallback = RGFW_windowresizefuncEMPTY;
1482RGFW_windowquitfunc RGFW_windowQuitCallback = RGFW_windowquitfuncEMPTY;
1483RGFW_mouseposfunc RGFW_mousePosCallback = RGFW_mouseposfuncEMPTY;
1484RGFW_windowrefreshfunc RGFW_windowRefreshCallback = RGFW_windowrefreshfuncEMPTY;
1485RGFW_focusfunc RGFW_focusCallback = RGFW_focusfuncEMPTY;
1486RGFW_mouseNotifyfunc RGFW_mouseNotifyCallBack = RGFW_mouseNotifyfuncEMPTY;
1487RGFW_dndfunc RGFW_dndCallback = RGFW_dndfuncEMPTY;
1488RGFW_dndInitfunc RGFW_dndInitCallback = RGFW_dndInitfuncEMPTY;
1489RGFW_keyfunc RGFW_keyCallback = RGFW_keyfuncEMPTY;
1490RGFW_mousebuttonfunc RGFW_mouseButtonCallback = RGFW_mousebuttonfuncEMPTY;
1491RGFW_jsButtonfunc RGFW_jsButtonCallback = RGFW_jsButtonfuncEMPTY;
1492RGFW_jsAxisfunc RGFW_jsAxisCallback = RGFW_jsAxisfuncEMPTY;
1493
1494void RGFW_window_checkEvents(RGFW_window* win, i32 waitMS) {
1495 RGFW_window_eventWait(win, waitMS);
1496
1497 while (RGFW_window_checkEvent(win) != NULL && RGFW_window_shouldClose(win) == 0) {
1498 if (win->event.type == RGFW_quit) return;
1499 }
1500
1501 #ifdef RGFW_WEBASM /* webasm needs to run the sleep function for asyncify */
1502 RGFW_sleep(0);
1503 #endif
1504}
1505
1506RGFW_windowmovefunc RGFW_setWindowMoveCallback(RGFW_windowmovefunc func) {
1507 RGFW_windowmovefunc prev = (RGFW_windowMoveCallback == RGFW_windowmovefuncEMPTY) ? NULL : RGFW_windowMoveCallback;
1508 RGFW_windowMoveCallback = func;
1509 return prev;
1510}
1511RGFW_windowresizefunc RGFW_setWindowResizeCallback(RGFW_windowresizefunc func) {
1512 RGFW_windowresizefunc prev = (RGFW_windowResizeCallback == RGFW_windowresizefuncEMPTY) ? NULL : RGFW_windowResizeCallback;
1513 RGFW_windowResizeCallback = func;
1514 return prev;
1515}
1516RGFW_windowquitfunc RGFW_setWindowQuitCallback(RGFW_windowquitfunc func) {
1517 RGFW_windowquitfunc prev = (RGFW_windowQuitCallback == RGFW_windowquitfuncEMPTY) ? NULL : RGFW_windowQuitCallback;
1518 RGFW_windowQuitCallback = func;
1519 return prev;
1520}
1521
1522RGFW_mouseposfunc RGFW_setMousePosCallback(RGFW_mouseposfunc func) {
1523 RGFW_mouseposfunc prev = (RGFW_mousePosCallback == RGFW_mouseposfuncEMPTY) ? NULL : RGFW_mousePosCallback;
1524 RGFW_mousePosCallback = func;
1525 return prev;
1526}
1527RGFW_windowrefreshfunc RGFW_setWindowRefreshCallback(RGFW_windowrefreshfunc func) {
1528 RGFW_windowrefreshfunc prev = (RGFW_windowRefreshCallback == RGFW_windowrefreshfuncEMPTY) ? NULL : RGFW_windowRefreshCallback;
1529 RGFW_windowRefreshCallback = func;
1530 return prev;
1531}
1532RGFW_focusfunc RGFW_setFocusCallback(RGFW_focusfunc func) {
1533 RGFW_focusfunc prev = (RGFW_focusCallback == RGFW_focusfuncEMPTY) ? NULL : RGFW_focusCallback;
1534 RGFW_focusCallback = func;
1535 return prev;
1536}
1537
1538RGFW_mouseNotifyfunc RGFW_setMouseNotifyCallBack(RGFW_mouseNotifyfunc func) {
1539 RGFW_mouseNotifyfunc prev = (RGFW_mouseNotifyCallBack == RGFW_mouseNotifyfuncEMPTY) ? NULL : RGFW_mouseNotifyCallBack;
1540 RGFW_mouseNotifyCallBack = func;
1541 return prev;
1542}
1543RGFW_dndfunc RGFW_setDndCallback(RGFW_dndfunc func) {
1544 RGFW_dndfunc prev = (RGFW_dndCallback == RGFW_dndfuncEMPTY) ? NULL : RGFW_dndCallback;
1545 RGFW_dndCallback = func;
1546 return prev;
1547}
1548RGFW_dndInitfunc RGFW_setDndInitCallback(RGFW_dndInitfunc func) {
1549 RGFW_dndInitfunc prev = (RGFW_dndInitCallback == RGFW_dndInitfuncEMPTY) ? NULL : RGFW_dndInitCallback;
1550 RGFW_dndInitCallback = func;
1551 return prev;
1552}
1553RGFW_keyfunc RGFW_setKeyCallback(RGFW_keyfunc func) {
1554 RGFW_keyfunc prev = (RGFW_keyCallback == RGFW_keyfuncEMPTY) ? NULL : RGFW_keyCallback;
1555 RGFW_keyCallback = func;
1556 return prev;
1557}
1558RGFW_mousebuttonfunc RGFW_setMouseButtonCallback(RGFW_mousebuttonfunc func) {
1559 RGFW_mousebuttonfunc prev = (RGFW_mouseButtonCallback == RGFW_mousebuttonfuncEMPTY) ? NULL : RGFW_mouseButtonCallback;
1560 RGFW_mouseButtonCallback = func;
1561 return prev;
1562}
1563RGFW_jsButtonfunc RGFW_setjsButtonCallback(RGFW_jsButtonfunc func) {
1564 RGFW_jsButtonfunc prev = (RGFW_jsButtonCallback == RGFW_jsButtonfuncEMPTY) ? NULL : RGFW_jsButtonCallback;
1565 RGFW_jsButtonCallback = func;
1566 return prev;
1567}
1568RGFW_jsAxisfunc RGFW_setjsAxisCallback(RGFW_jsAxisfunc func) {
1569 RGFW_jsAxisfunc prev = (RGFW_jsAxisCallback == RGFW_jsAxisfuncEMPTY) ? NULL : RGFW_jsAxisCallback;
1570 RGFW_jsAxisCallback = func;
1571 return prev;
1572}
1573/*
1574no more event call back defines
1575*/
1576
1577#define RGFW_ASSERT(check, str) {\
1578 if (!(check)) { \
1579 printf(str); \
1580 assert(check); \
1581 } \
1582}
1583
1584b8 RGFW_error = 0;
1585b8 RGFW_Error(void) { return RGFW_error; }
1586
1587#define SET_ATTRIB(a, v) { \
1588 assert(((size_t) index + 1) < sizeof(attribs) / sizeof(attribs[0])); \
1589 attribs[index++] = a; \
1590 attribs[index++] = v; \
1591}
1592
1593RGFW_area RGFW_bufferSize = {0, 0};
1594void RGFW_setBufferSize(RGFW_area size) {
1595 RGFW_bufferSize = size;
1596}
1597
1598
1599RGFWDEF RGFW_window* RGFW_window_basic_init(RGFW_rect rect, u16 args);
1600
1601/* do a basic initialization for RGFW_window, this is to standard it for each OS */
1602RGFW_window* RGFW_window_basic_init(RGFW_rect rect, u16 args) {
1603 RGFW_window* win = (RGFW_window*) RGFW_MALLOC(sizeof(RGFW_window)); /*!< make a new RGFW struct */
1604
1605 /* clear out dnd info */
1606#ifdef RGFW_ALLOC_DROPFILES
1607 win->event.droppedFiles = (char**) RGFW_MALLOC(sizeof(char*) * RGFW_MAX_DROPS);
1608 u32 i;
1609 for (i = 0; i < RGFW_MAX_DROPS; i++)
1610 win->event.droppedFiles[i] = (char*) RGFW_CALLOC(RGFW_MAX_PATH, sizeof(char));
1611#endif
1612
1613 /* X11 requires us to have a display to get the screen size */
1614 #ifndef RGFW_X11
1615 RGFW_area screenR = RGFW_getScreenSize();
1616 #else
1617 win->src.display = XOpenDisplay(NULL);
1618 assert(win->src.display != NULL);
1619
1620 Screen* scrn = DefaultScreenOfDisplay((Display*)win->src.display);
1621 RGFW_area screenR = RGFW_AREA((u32)scrn->width, (u32)scrn->height);
1622 #endif
1623
1624 /* rect based the requested args */
1625 if (args & RGFW_FULLSCREEN)
1626 rect = RGFW_RECT(0, 0, screenR.w, screenR.h);
1627
1628 /* set and init the new window's data */
1629 win->r = rect;
1630 win->event.inFocus = 1;
1631 win->event.droppedFilesCount = 0;
1632 RGFW_joystickCount = 0;
1633 win->_winArgs = 0;
1634 win->event.lockState = 0;
1635
1636 return win;
1637}
1638
1639#ifndef RGFW_NO_MONITOR
1640void RGFW_window_scaleToMonitor(RGFW_window* win) {
1641 RGFW_monitor monitor = RGFW_window_getMonitor(win);
1642
1643 RGFW_window_resize(win, RGFW_AREA((u32)(monitor.scaleX * (float)win->r.w), (u32)(monitor.scaleX * (float)win->r.h)));
1644}
1645#endif
1646
1647RGFW_window* RGFW_root = NULL;
1648
1649
1650#define RGFW_HOLD_MOUSE (1L<<2) /*!< hold the moues still */
1651#define RGFW_MOUSE_LEFT (1L<<3) /* if mouse left the window */
1652
1653#ifdef RGFW_MACOS
1654RGFWDEF void RGFW_window_cocoaSetLayer(RGFW_window* win, void* layer);
1655RGFWDEF void* RGFW_cocoaGetLayer(void);
1656#endif
1657
1658char* RGFW_className = NULL;
1659void RGFW_setClassName(char* name) {
1660 RGFW_className = name;
1661}
1662
1663void RGFW_clipboardFree(char* str) { RGFW_FREE(str); }
1664
1665RGFW_keyState RGFW_mouseButtons[5] = { {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0} };
1666
1667b8 RGFW_isMousePressed(RGFW_window* win, u8 button) {
1668 assert(win != NULL);
1669 return RGFW_mouseButtons[button].current && (win != NULL) && win->event.inFocus;
1670}
1671b8 RGFW_wasMousePressed(RGFW_window* win, u8 button) {
1672 assert(win != NULL);
1673 return RGFW_mouseButtons[button].prev && (win != NULL) && win->event.inFocus;
1674}
1675b8 RGFW_isMouseHeld(RGFW_window* win, u8 button) {
1676 return (RGFW_isMousePressed(win, button) && RGFW_wasMousePressed(win, button));
1677}
1678b8 RGFW_isMouseReleased(RGFW_window* win, u8 button) {
1679 return (!RGFW_isMousePressed(win, button) && RGFW_wasMousePressed(win, button));
1680}
1681
1682b8 RGFW_isPressed(RGFW_window* win, u8 key) {
1683 return RGFW_keyboard[key].current && (win == NULL || win->event.inFocus);
1684}
1685
1686b8 RGFW_wasPressed(RGFW_window* win, u8 key) {
1687 return RGFW_keyboard[key].prev && (win == NULL || win->event.inFocus);
1688}
1689
1690b8 RGFW_isHeld(RGFW_window* win, u8 key) {
1691 return (RGFW_isPressed(win, key) && RGFW_wasPressed(win, key));
1692}
1693
1694b8 RGFW_isClicked(RGFW_window* win, u8 key) {
1695 return (RGFW_wasPressed(win, key) && !RGFW_isPressed(win, key));
1696}
1697
1698b8 RGFW_isReleased(RGFW_window* win, u8 key) {
1699 return (!RGFW_isPressed(win, key) && RGFW_wasPressed(win, key));
1700}
1701
1702#if defined(RGFW_WINDOWS) && defined(RGFW_DIRECTX) /* defines for directX context*/
1703 RGFW_directXinfo RGFW_dxInfo;
1704 RGFW_directXinfo* RGFW_getDirectXInfo(void) { return &RGFW_dxInfo; }
1705#endif
1706
1707void RGFW_window_makeCurrent(RGFW_window* win) {
1708#if defined(RGFW_WINDOWS) && defined(RGFW_DIRECTX)
1709 if (win == NULL)
1710 RGFW_dxInfo.pDeviceContext->lpVtbl->OMSetRenderTargets(RGFW_dxInfo.pDeviceContext, 1, NULL, NULL);
1711 else
1712 RGFW_dxInfo.pDeviceContext->lpVtbl->OMSetRenderTargets(RGFW_dxInfo.pDeviceContext, 1, &win->src.renderTargetView, NULL);
1713#elif defined(RGFW_OPENGL)
1714 RGFW_window_makeCurrent_OpenGL(win);
1715#else
1716 RGFW_UNUSED(win)
1717#endif
1718}
1719
1720void RGFW_window_setGPURender(RGFW_window* win, i8 set) {
1721 if (!set && !(win->_winArgs & RGFW_NO_GPU_RENDER))
1722 win->_winArgs |= RGFW_NO_GPU_RENDER;
1723
1724 else if (set && win->_winArgs & RGFW_NO_GPU_RENDER)
1725 win->_winArgs ^= RGFW_NO_GPU_RENDER;
1726}
1727
1728void RGFW_window_setCPURender(RGFW_window* win, i8 set) {
1729 if (!set && !(win->_winArgs & RGFW_NO_CPU_RENDER))
1730 win->_winArgs |= RGFW_NO_CPU_RENDER;
1731
1732 else if (set && win->_winArgs & RGFW_NO_CPU_RENDER)
1733 win->_winArgs ^= RGFW_NO_CPU_RENDER;
1734}
1735
1736void RGFW_window_maximize(RGFW_window* win) {
1737 assert(win != NULL);
1738
1739 RGFW_area screen = RGFW_getScreenSize();
1740
1741 RGFW_window_move(win, RGFW_POINT(0, 0));
1742 RGFW_window_resize(win, screen);
1743}
1744
1745b8 RGFW_window_shouldClose(RGFW_window* win) {
1746 assert(win != NULL);
1747 return (win->event.type == RGFW_quit || RGFW_isPressed(win, RGFW_Escape));
1748}
1749
1750void RGFW_window_setShouldClose(RGFW_window* win) { win->event.type = RGFW_quit; RGFW_windowQuitCallback(win); }
1751
1752#ifndef RGFW_NO_MONITOR
1753 void RGFW_window_moveToMonitor(RGFW_window* win, RGFW_monitor m) {
1754 RGFW_window_move(win, RGFW_POINT(m.rect.x + win->r.x, m.rect.y + win->r.y));
1755 }
1756#endif
1757
1758RGFWDEF void RGFW_captureCursor(RGFW_window* win, RGFW_rect);
1759RGFWDEF void RGFW_releaseCursor(RGFW_window* win);
1760
1761void RGFW_window_mouseHold(RGFW_window* win, RGFW_area area) {
1762 if ((win->_winArgs & RGFW_HOLD_MOUSE))
1763 return;
1764
1765
1766 if (!area.w && !area.h)
1767 area = RGFW_AREA(win->r.w / 2, win->r.h / 2);
1768
1769 win->_winArgs |= RGFW_HOLD_MOUSE;
1770 RGFW_captureCursor(win, win->r);
1771 RGFW_window_moveMouse(win, RGFW_POINT(win->r.x + (win->r.w / 2), win->r.y + (win->r.h / 2)));
1772}
1773
1774void RGFW_window_mouseUnhold(RGFW_window* win) {
1775 if ((win->_winArgs & RGFW_HOLD_MOUSE)) {
1776 win->_winArgs ^= RGFW_HOLD_MOUSE;
1777
1778 RGFW_releaseCursor(win);
1779 }
1780}
1781
1782u32 RGFW_window_checkFPS(RGFW_window* win, u32 fpsCap) {
1783 u64 deltaTime = RGFW_getTimeNS() - win->event.frameTime;
1784
1785 u32 output_fps = 0;
1786 u64 fps = round(1e+9 / deltaTime);
1787 output_fps= fps;
1788
1789 if (fpsCap && fps > fpsCap) {
1790 u64 frameTimeNS = 1e+9 / fpsCap;
1791 u64 sleepTimeMS = (frameTimeNS - deltaTime) / 1e6;
1792
1793 if (sleepTimeMS > 0) {
1794 RGFW_sleep(sleepTimeMS);
1795 win->event.frameTime = 0;
1796 }
1797 }
1798
1799 win->event.frameTime = RGFW_getTimeNS();
1800
1801 if (fpsCap == 0)
1802 return (u32) output_fps;
1803
1804 deltaTime = RGFW_getTimeNS() - win->event.frameTime2;
1805 output_fps = round(1e+9 / deltaTime);
1806 win->event.frameTime2 = RGFW_getTimeNS();
1807
1808 return output_fps;
1809}
1810
1811u32 RGFW_isPressedJS(RGFW_window* win, u16 c, u8 button) {
1812 RGFW_UNUSED(win);
1813 return RGFW_jsPressed[c][button];
1814}
1815
1816#if defined(RGFW_X11) || defined(RGFW_WINDOWS)
1817 void RGFW_window_showMouse(RGFW_window* win, i8 show) {
1818 static u8 RGFW_blk[] = { 0, 0, 0, 0 };
1819 if (show == 0)
1820 RGFW_window_setMouse(win, RGFW_blk, RGFW_AREA(1, 1), 4);
1821 else
1822 RGFW_window_setMouseDefault(win);
1823 }
1824#endif
1825
1826RGFWDEF void RGFW_updateLockState(RGFW_window* win, b8 capital, b8 numlock);
1827void RGFW_updateLockState(RGFW_window* win, b8 capital, b8 numlock) {
1828 if (capital && !(win->event.lockState & RGFW_CAPSLOCK))
1829 win->event.lockState |= RGFW_CAPSLOCK;
1830 else if (!capital && (win->event.lockState & RGFW_CAPSLOCK))
1831 win->event.lockState ^= RGFW_CAPSLOCK;
1832
1833 if (numlock && !(win->event.lockState & RGFW_NUMLOCK))
1834 win->event.lockState |= RGFW_NUMLOCK;
1835 else if (!numlock && (win->event.lockState & RGFW_NUMLOCK))
1836 win->event.lockState ^= RGFW_NUMLOCK;
1837}
1838
1839#if defined(RGFW_X11) || defined(RGFW_MACOS) || defined(RGFW_WEBASM) || defined(RGFW_WAYLAND)
1840 struct timespec;
1841
1842 int nanosleep(const struct timespec* duration, struct timespec* rem);
1843 int clock_gettime(clockid_t clk_id, struct timespec* tp);
1844 int setenv(const char *name, const char *value, int overwrite);
1845
1846 void RGFW_window_setDND(RGFW_window* win, b8 allow) {
1847 if (allow && !(win->_winArgs & RGFW_ALLOW_DND))
1848 win->_winArgs |= RGFW_ALLOW_DND;
1849
1850 else if (!allow && (win->_winArgs & RGFW_ALLOW_DND))
1851 win->_winArgs ^= RGFW_ALLOW_DND;
1852 }
1853#endif
1854
1855/*
1856 graphics API specific code (end of generic code)
1857 starts here
1858*/
1859
1860
1861/*
1862 OpenGL defines start here (Normal, EGL, OSMesa)
1863*/
1864
1865#if defined(RGFW_OPENGL) || defined(RGFW_EGL) || defined(RGFW_OSMESA)
1866 #ifdef RGFW_WINDOWS
1867 #define WIN32_LEAN_AND_MEAN
1868 #define OEMRESOURCE
1869 #include <windows.h>
1870 #endif
1871
1872 #if !defined(__APPLE__) && !defined(RGFW_NO_GL_HEADER)
1873 #include <GL/gl.h>
1874 #elif defined(__APPLE__)
1875 #ifndef GL_SILENCE_DEPRECATION
1876 #define GL_SILENCE_DEPRECATION
1877 #endif
1878 #include <OpenGL/gl.h>
1879 #include <OpenGL/OpenGL.h>
1880 #endif
1881
1882/* EGL, normal OpenGL only */
1883#if !defined(RGFW_OSMESA)
1884 i32 RGFW_majorVersion = 0, RGFW_minorVersion = 0;
1885 b8 RGFW_profile = RGFW_GL_CORE;
1886
1887 #ifndef RGFW_EGL
1888 i32 RGFW_STENCIL = 8, RGFW_SAMPLES = 4, RGFW_STEREO = 0, RGFW_AUX_BUFFERS = 0, RGFW_DOUBLE_BUFFER = 1;
1889 #else
1890 i32 RGFW_STENCIL = 0, RGFW_SAMPLES = 0, RGFW_STEREO = 0, RGFW_AUX_BUFFERS = 0, RGFW_DOUBLE_BUFFER = 1;
1891 #endif
1892
1893
1894 void RGFW_setGLStencil(i32 stencil) { RGFW_STENCIL = stencil; }
1895 void RGFW_setGLSamples(i32 samples) { RGFW_SAMPLES = samples; }
1896 void RGFW_setGLStereo(i32 stereo) { RGFW_STEREO = stereo; }
1897 void RGFW_setGLAuxBuffers(i32 auxBuffers) { RGFW_AUX_BUFFERS = auxBuffers; }
1898 void RGFW_setDoubleBuffer(b8 useDoubleBuffer) { RGFW_DOUBLE_BUFFER = useDoubleBuffer; }
1899
1900 void RGFW_setGLVersion(b8 profile, i32 major, i32 minor) {
1901 RGFW_profile = profile;
1902 RGFW_majorVersion = major;
1903 RGFW_minorVersion = minor;
1904 }
1905
1906/* OPENGL normal only (no EGL / OSMesa) */
1907#ifndef RGFW_EGL
1908
1909#define RGFW_GL_RENDER_TYPE RGFW_OS_BASED_VALUE(GLX_X_VISUAL_TYPE, 0x2003, 73, 0, 0)
1910 #define RGFW_GL_ALPHA_SIZE RGFW_OS_BASED_VALUE(GLX_ALPHA_SIZE, 0x201b, 11, 0, 0)
1911 #define RGFW_GL_DEPTH_SIZE RGFW_OS_BASED_VALUE(GLX_DEPTH_SIZE, 0x2022, 12, 0, 0)
1912 #define RGFW_GL_DOUBLEBUFFER RGFW_OS_BASED_VALUE(GLX_DOUBLEBUFFER, 0x2011, 5, 0, 0)
1913 #define RGFW_GL_STENCIL_SIZE RGFW_OS_BASED_VALUE(GLX_STENCIL_SIZE, 0x2023, 13, 0, 0)
1914 #define RGFW_GL_SAMPLES RGFW_OS_BASED_VALUE(GLX_SAMPLES, 0x2042, 55, 0, 0)
1915 #define RGFW_GL_STEREO RGFW_OS_BASED_VALUE(GLX_STEREO, 0x2012, 6, 0, 0)
1916 #define RGFW_GL_AUX_BUFFERS RGFW_OS_BASED_VALUE(GLX_AUX_BUFFERS, 0x2024, 7, 0, 0)
1917
1918#if defined(RGFW_X11) || defined(RGFW_WINDOWS)
1919 #define RGFW_GL_DRAW RGFW_OS_BASED_VALUE(GLX_X_RENDERABLE, 0x2001, 0, 0, 0)
1920 #define RGFW_GL_DRAW_TYPE RGFW_OS_BASED_VALUE(GLX_RENDER_TYPE, 0x2013, 0, 0, 0)
1921 #define RGFW_GL_FULL_FORMAT RGFW_OS_BASED_VALUE(GLX_TRUE_COLOR, 0x2027, 0, 0, 0)
1922 #define RGFW_GL_RED_SIZE RGFW_OS_BASED_VALUE(GLX_RED_SIZE, 0x2015, 0, 0, 0)
1923 #define RGFW_GL_GREEN_SIZE RGFW_OS_BASED_VALUE(GLX_GREEN_SIZE, 0x2017, 0, 0, 0)
1924 #define RGFW_GL_BLUE_SIZE RGFW_OS_BASED_VALUE(GLX_BLUE_SIZE, 0x2019, 0, 0, 0)
1925 #define RGFW_GL_USE_RGBA RGFW_OS_BASED_VALUE(GLX_RGBA_BIT, 0x202B, 0, 0, 0)
1926#endif
1927
1928#ifdef RGFW_WINDOWS
1929 #define WGL_SUPPORT_OPENGL_ARB 0x2010
1930 #define WGL_COLOR_BITS_ARB 0x2014
1931 #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
1932 #define WGL_CONTEXT_MAJOR_VERSION_ARB 0x2091
1933 #define WGL_CONTEXT_MINOR_VERSION_ARB 0x2092
1934 #define WGL_CONTEXT_PROFILE_MASK_ARB 0x9126
1935 #define WGL_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001
1936 #define WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x00000002
1937 #define WGL_SAMPLE_BUFFERS_ARB 0x2041
1938 #define WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB 0x20a9
1939 #define WGL_PIXEL_TYPE_ARB 0x2013
1940 #define WGL_TYPE_RGBA_ARB 0x202B
1941
1942 #define WGL_TRANSPARENT_ARB 0x200A
1943#endif
1944
1945/* The window'ing api needs to know how to render the data we (or opengl) give it
1946 MacOS and Windows do this using a structure called a "pixel format"
1947 X11 calls it a "Visual"
1948 This function returns the attributes for the format we want */
1949 static u32* RGFW_initFormatAttribs(u32 useSoftware) {
1950 RGFW_UNUSED(useSoftware);
1951 static u32 attribs[] = {
1952 #if defined(RGFW_X11) || defined(RGFW_WINDOWS)
1953 RGFW_GL_RENDER_TYPE,
1954 RGFW_GL_FULL_FORMAT,
1955 #endif
1956 RGFW_GL_ALPHA_SIZE , 8,
1957 RGFW_GL_DEPTH_SIZE , 24,
1958 #if defined(RGFW_X11) || defined(RGFW_WINDOWS)
1959 RGFW_GL_DRAW, 1,
1960 RGFW_GL_RED_SIZE , 8,
1961 RGFW_GL_GREEN_SIZE , 8,
1962 RGFW_GL_BLUE_SIZE , 8,
1963 RGFW_GL_DRAW_TYPE , RGFW_GL_USE_RGBA,
1964 #endif
1965
1966 #ifdef RGFW_X11
1967 GLX_DRAWABLE_TYPE , GLX_WINDOW_BIT,
1968 #endif
1969
1970 #ifdef RGFW_MACOS
1971 72,
1972 8, 24,
1973 #endif
1974
1975 #ifdef RGFW_WINDOWS
1976 WGL_SUPPORT_OPENGL_ARB, 1,
1977 WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,
1978 WGL_COLOR_BITS_ARB, 32,
1979 #endif
1980
1981 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
1982 };
1983
1984 size_t index = (sizeof(attribs) / sizeof(attribs[0])) - 13;
1985
1986 #define RGFW_GL_ADD_ATTRIB(attrib, attVal) \
1987 if (attVal) { \
1988 attribs[index] = attrib;\
1989 attribs[index + 1] = attVal;\
1990 index += 2;\
1991 }
1992
1993 RGFW_GL_ADD_ATTRIB(RGFW_GL_DOUBLEBUFFER, 1);
1994
1995 RGFW_GL_ADD_ATTRIB(RGFW_GL_STENCIL_SIZE, RGFW_STENCIL);
1996 RGFW_GL_ADD_ATTRIB(RGFW_GL_STEREO, RGFW_STEREO);
1997 RGFW_GL_ADD_ATTRIB(RGFW_GL_AUX_BUFFERS, RGFW_AUX_BUFFERS);
1998
1999#ifndef RGFW_X11
2000 RGFW_GL_ADD_ATTRIB(RGFW_GL_SAMPLES, RGFW_SAMPLES);
2001#endif
2002
2003#ifdef RGFW_MACOS
2004 if (useSoftware) {
2005 RGFW_GL_ADD_ATTRIB(70, kCGLRendererGenericFloatID);
2006 } else {
2007 attribs[index] = RGFW_GL_RENDER_TYPE;
2008 index += 1;
2009 }
2010#endif
2011
2012#ifdef RGFW_MACOS
2013 /* macOS has the surface attribs and the opengl attribs connected for some reason
2014 maybe this is to give macOS more control to limit openGL/the opengl version? */
2015
2016 attribs[index] = 99;
2017 attribs[index + 1] = 0x1000;
2018
2019 if (RGFW_majorVersion >= 4 || RGFW_majorVersion >= 3) {
2020 attribs[index + 1] = (u32) ((RGFW_majorVersion >= 4) ? 0x4100 : 0x3200);
2021 }
2022#endif
2023
2024 RGFW_GL_ADD_ATTRIB(0, 0);
2025
2026 return attribs;
2027 }
2028
2029/* EGL only (no OSMesa nor normal OPENGL) */
2030#elif defined(RGFW_EGL)
2031
2032#include <EGL/egl.h>
2033
2034#if defined(RGFW_LINK_EGL)
2035 typedef EGLBoolean(EGLAPIENTRY* PFN_eglInitialize)(EGLDisplay, EGLint*, EGLint*);
2036
2037 PFNEGLINITIALIZEPROC eglInitializeSource;
2038 PFNEGLGETCONFIGSPROC eglGetConfigsSource;
2039 PFNEGLCHOOSECONFIGPROC eglChooseConfigSource;
2040 PFNEGLCREATEWINDOWSURFACEPROC eglCreateWindowSurfaceSource;
2041 PFNEGLCREATECONTEXTPROC eglCreateContextSource;
2042 PFNEGLMAKECURRENTPROC eglMakeCurrentSource;
2043 PFNEGLGETDISPLAYPROC eglGetDisplaySource;
2044 PFNEGLSWAPBUFFERSPROC eglSwapBuffersSource;
2045 PFNEGLSWAPINTERVALPROC eglSwapIntervalSource;
2046 PFNEGLBINDAPIPROC eglBindAPISource;
2047 PFNEGLDESTROYCONTEXTPROC eglDestroyContextSource;
2048 PFNEGLTERMINATEPROC eglTerminateSource;
2049 PFNEGLDESTROYSURFACEPROC eglDestroySurfaceSource;
2050
2051#define eglInitialize eglInitializeSource
2052#define eglGetConfigs eglGetConfigsSource
2053#define eglChooseConfig eglChooseConfigSource
2054#define eglCreateWindowSurface eglCreateWindowSurfaceSource
2055#define eglCreateContext eglCreateContextSource
2056#define eglMakeCurrent eglMakeCurrentSource
2057#define eglGetDisplay eglGetDisplaySource
2058#define eglSwapBuffers eglSwapBuffersSource
2059#define eglSwapInterval eglSwapIntervalSource
2060#define eglBindAPI eglBindAPISource
2061#define eglDestroyContext eglDestroyContextSource
2062#define eglTerminate eglTerminateSource
2063#define eglDestroySurface eglDestroySurfaceSource;
2064#endif
2065
2066
2067#define EGL_SURFACE_MAJOR_VERSION_KHR 0x3098
2068#define EGL_SURFACE_MINOR_VERSION_KHR 0x30fb
2069
2070#ifndef RGFW_GL_ADD_ATTRIB
2071#define RGFW_GL_ADD_ATTRIB(attrib, attVal) \
2072 if (attVal) { \
2073 attribs[index] = attrib;\
2074 attribs[index + 1] = attVal;\
2075 index += 2;\
2076 }
2077#endif
2078
2079
2080 void RGFW_createOpenGLContext(RGFW_window* win) {
2081#if defined(RGFW_LINK_EGL)
2082 eglInitializeSource = (PFNEGLINITIALIZEPROC) eglGetProcAddress("eglInitialize");
2083 eglGetConfigsSource = (PFNEGLGETCONFIGSPROC) eglGetProcAddress("eglGetConfigs");
2084 eglChooseConfigSource = (PFNEGLCHOOSECONFIGPROC) eglGetProcAddress("eglChooseConfig");
2085 eglCreateWindowSurfaceSource = (PFNEGLCREATEWINDOWSURFACEPROC) eglGetProcAddress("eglCreateWindowSurface");
2086 eglCreateContextSource = (PFNEGLCREATECONTEXTPROC) eglGetProcAddress("eglCreateContext");
2087 eglMakeCurrentSource = (PFNEGLMAKECURRENTPROC) eglGetProcAddress("eglMakeCurrent");
2088 eglGetDisplaySource = (PFNEGLGETDISPLAYPROC) eglGetProcAddress("eglGetDisplay");
2089 eglSwapBuffersSource = (PFNEGLSWAPBUFFERSPROC) eglGetProcAddress("eglSwapBuffers");
2090 eglSwapIntervalSource = (PFNEGLSWAPINTERVALPROC) eglGetProcAddress("eglSwapInterval");
2091 eglBindAPISource = (PFNEGLBINDAPIPROC) eglGetProcAddress("eglBindAPI");
2092 eglDestroyContextSource = (PFNEGLDESTROYCONTEXTPROC) eglGetProcAddress("eglDestroyContext");
2093 eglTerminateSource = (PFNEGLTERMINATEPROC) eglGetProcAddress("eglTerminate");
2094 eglDestroySurfaceSource = (PFNEGLDESTROYSURFACEPROC) eglGetProcAddress("eglDestroySurface");
2095#endif /* RGFW_LINK_EGL */
2096
2097 #ifdef RGFW_WINDOWS
2098 win->src.EGL_display = eglGetDisplay((EGLNativeDisplayType) win->src.hdc);
2099 #elif defined(RGFW_MACOS)
2100 win->src.EGL_display = eglGetDisplay((EGLNativeDisplayType)0);
2101 #else
2102 win->src.EGL_display = eglGetDisplay((EGLNativeDisplayType) win->src.display);
2103 #endif
2104
2105 EGLint major, minor;
2106
2107 eglInitialize(win->src.EGL_display, &major, &minor);
2108
2109 #ifndef EGL_OPENGL_ES1_BIT
2110 #define EGL_OPENGL_ES1_BIT 0x1
2111 #endif
2112
2113 EGLint egl_config[] = {
2114 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
2115 EGL_RENDERABLE_TYPE,
2116 #ifdef RGFW_OPENGL_ES1
2117 EGL_OPENGL_ES1_BIT,
2118 #elif defined(RGFW_OPENGL_ES3)
2119 EGL_OPENGL_ES3_BIT,
2120 #elif defined(RGFW_OPENGL_ES2)
2121 EGL_OPENGL_ES2_BIT,
2122 #else
2123 EGL_OPENGL_BIT,
2124 #endif
2125 EGL_NONE, EGL_NONE
2126 };
2127
2128 EGLConfig config;
2129 EGLint numConfigs;
2130 eglChooseConfig(win->src.EGL_display, egl_config, &config, 1, &numConfigs);
2131
2132 #if defined(RGFW_MACOS)
2133 void* layer = RGFW_cocoaGetLayer();
2134
2135 RGFW_window_cocoaSetLayer(win, layer);
2136
2137 win->src.EGL_surface = eglCreateWindowSurface(win->src.EGL_display, config, (EGLNativeWindowType) layer, NULL);
2138 #else
2139 win->src.EGL_surface = eglCreateWindowSurface(win->src.EGL_display, config, (EGLNativeWindowType) win->src.window, NULL);
2140 #endif
2141
2142 EGLint attribs[] = {
2143 EGL_CONTEXT_CLIENT_VERSION,
2144 #ifdef RGFW_OPENGL_ES1
2145 1,
2146 #else
2147 2,
2148 #endif
2149 EGL_NONE, EGL_NONE, EGL_NONE, EGL_NONE, EGL_NONE, EGL_NONE, EGL_NONE, EGL_NONE, EGL_NONE
2150 };
2151
2152 size_t index = 4;
2153 RGFW_GL_ADD_ATTRIB(EGL_STENCIL_SIZE, RGFW_STENCIL);
2154 RGFW_GL_ADD_ATTRIB(EGL_SAMPLES, RGFW_SAMPLES);
2155
2156 if (RGFW_DOUBLE_BUFFER)
2157 RGFW_GL_ADD_ATTRIB(EGL_RENDER_BUFFER, EGL_BACK_BUFFER);
2158
2159 if (RGFW_majorVersion) {
2160 attribs[1] = RGFW_majorVersion;
2161
2162 RGFW_GL_ADD_ATTRIB(EGL_CONTEXT_MAJOR_VERSION, RGFW_majorVersion);
2163 RGFW_GL_ADD_ATTRIB(EGL_CONTEXT_MINOR_VERSION, RGFW_minorVersion);
2164
2165 if (RGFW_profile == RGFW_GL_CORE) {
2166 RGFW_GL_ADD_ATTRIB(EGL_CONTEXT_OPENGL_PROFILE_MASK, EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT);
2167 }
2168 else {
2169 RGFW_GL_ADD_ATTRIB(EGL_CONTEXT_OPENGL_PROFILE_MASK, EGL_CONTEXT_OPENGL_COMPATIBILITY_PROFILE_BIT);
2170 }
2171
2172 }
2173
2174 #if defined(RGFW_OPENGL_ES1) || defined(RGFW_OPENGL_ES2) || defined(RGFW_OPENGL_ES3)
2175 eglBindAPI(EGL_OPENGL_ES_API);
2176 #else
2177 eglBindAPI(EGL_OPENGL_API);
2178 #endif
2179
2180 win->src.EGL_context = eglCreateContext(win->src.EGL_display, config, EGL_NO_CONTEXT, attribs);
2181
2182 if (win->src.EGL_context == NULL)
2183 fprintf(stderr, "failed to create an EGL opengl context\n");
2184
2185 eglMakeCurrent(win->src.EGL_display, win->src.EGL_surface, win->src.EGL_surface, win->src.EGL_context);
2186 eglSwapBuffers(win->src.EGL_display, win->src.EGL_surface);
2187 }
2188
2189 void RGFW_window_makeCurrent_OpenGL(RGFW_window* win) {
2190 eglMakeCurrent(win->src.EGL_display, win->src.EGL_surface, win->src.EGL_surface, win->src.EGL_context);
2191 }
2192
2193 #ifdef RGFW_APPLE
2194 void* RGFWnsglFramework = NULL;
2195 #elif defined(RGFW_WINDOWS)
2196 static HMODULE wglinstance = NULL;
2197 #endif
2198
2199 void* RGFW_getProcAddress(const char* procname) {
2200 #if defined(RGFW_WINDOWS)
2201 void* proc = (void*) GetProcAddress(wglinstance, procname);
2202
2203 if (proc)
2204 return proc;
2205 #endif
2206
2207 return (void*) eglGetProcAddress(procname);
2208 }
2209
2210 void RGFW_closeEGL(RGFW_window* win) {
2211 eglDestroySurface(win->src.EGL_display, win->src.EGL_surface);
2212 eglDestroyContext(win->src.EGL_display, win->src.EGL_context);
2213
2214 eglTerminate(win->src.EGL_display);
2215 }
2216
2217 void RGFW_window_swapInterval(RGFW_window* win, i32 swapInterval) {
2218 assert(win != NULL);
2219
2220 eglSwapInterval(win->src.EGL_display, swapInterval);
2221
2222 }
2223#endif /* RGFW_EGL */
2224
2225/*
2226 end of RGFW_EGL defines
2227*/
2228
2229/* OPENGL Normal / EGL defines only (no OS MESA) Ends here */
2230
2231#elif defined(RGFW_OSMESA) /* OSmesa only */
2232RGFWDEF void RGFW_OSMesa_reorganize(void);
2233
2234/* reorganize buffer for osmesa */
2235void RGFW_OSMesa_reorganize(void) {
2236 u8* row = (u8*) RGFW_MALLOC(win->r.w * 3);
2237
2238 i32 half_height = win->r.h / 2;
2239 i32 stride = win->r.w * 3;
2240
2241 i32 y;
2242 for (y = 0; y < half_height; ++y) {
2243 i32 top_offset = y * stride;
2244 i32 bottom_offset = (win->r.h - y - 1) * stride;
2245 memcpy(row, win->buffer + top_offset, stride);
2246 memcpy(win->buffer + top_offset, win->buffer + bottom_offset, stride);
2247 memcpy(win->buffer + bottom_offset, row, stride);
2248 }
2249
2250 RGFW_FREE(row);
2251}
2252#endif /* RGFW_OSMesa */
2253
2254#endif /* RGFW_GL (OpenGL, EGL, OSMesa )*/
2255
2256/*
2257This is where OS specific stuff starts
2258*/
2259
2260
2261#if defined(RGFW_WAYLAND) || defined(RGFW_X11)
2262 int RGFW_eventWait_forceStop[] = {0, 0, 0}; /* for wait events */
2263
2264 #ifdef __linux__
2265 #include <linux/joystick.h>
2266 #include <fcntl.h>
2267 #include <unistd.h>
2268
2269 RGFW_Event* RGFW_linux_updateJoystick(RGFW_window* win) {
2270 static int xAxis = 0, yAxis = 0;
2271 u8 i;
2272 for (i = 0; i < RGFW_joystickCount; i++) {
2273 struct js_event e;
2274
2275
2276 if (RGFW_joysticks[i] == 0)
2277 continue;
2278
2279 i32 flags = fcntl(RGFW_joysticks[i], F_GETFL, 0);
2280 fcntl(RGFW_joysticks[i], F_SETFL, flags | O_NONBLOCK);
2281
2282 ssize_t bytes;
2283 while ((bytes = read(RGFW_joysticks[i], &e, sizeof(e))) > 0) {
2284 switch (e.type) {
2285 case JS_EVENT_BUTTON:
2286 win->event.type = e.value ? RGFW_jsButtonPressed : RGFW_jsButtonReleased;
2287 win->event.button = e.number;
2288 RGFW_jsPressed[i][e.number] = e.value;
2289 RGFW_jsButtonCallback(win, i, e.number, e.value);
2290 return &win->event;
2291 case JS_EVENT_AXIS:
2292 ioctl(RGFW_joysticks[i], JSIOCGAXES, &win->event.axisesCount);
2293
2294 if ((e.number == 0 || e.number % 2) && e.number != 1)
2295 xAxis = e.value;
2296 else
2297 yAxis = e.value;
2298
2299 win->event.axis[e.number / 2].x = xAxis;
2300 win->event.axis[e.number / 2].y = yAxis;
2301 win->event.type = RGFW_jsAxisMove;
2302 win->event.joystick = i;
2303 RGFW_jsAxisCallback(win, i, win->event.axis, win->event.axisesCount);
2304 return &win->event;
2305
2306 default: break;
2307 }
2308 }
2309 }
2310
2311 return NULL;
2312 }
2313
2314 #endif
2315#endif
2316
2317/*
2318
2319
2320Start of Linux / Unix defines
2321
2322
2323*/
2324
2325#ifdef RGFW_X11
2326#ifndef RGFW_NO_X11_CURSOR
2327#include <X11/Xcursor/Xcursor.h>
2328#endif
2329#include <dlfcn.h>
2330
2331#ifndef RGFW_NO_DPI
2332#include <X11/extensions/Xrandr.h>
2333#include <X11/Xresource.h>
2334#endif
2335
2336#include <X11/Xutil.h>
2337#include <X11/Xatom.h>
2338#include <X11/keysymdef.h>
2339#include <unistd.h>
2340
2341#include <X11/XKBlib.h> /* for converting keycode to string */
2342#include <X11/cursorfont.h> /* for hiding */
2343#include <X11/extensions/shapeconst.h>
2344#include <X11/extensions/shape.h>
2345#include <X11/extensions/XInput2.h>
2346
2347#include <limits.h> /* for data limits (mainly used in drag and drop functions) */
2348#include <poll.h>
2349
2350
2351#ifdef __linux__
2352#include <linux/joystick.h>
2353#endif
2354
2355 u8 RGFW_mouseIconSrc[] = { XC_arrow, XC_left_ptr, XC_xterm, XC_crosshair, XC_hand2, XC_sb_h_double_arrow, XC_sb_v_double_arrow, XC_bottom_left_corner, XC_bottom_right_corner, XC_fleur, XC_X_cursor};
2356 /*atoms needed for drag and drop*/
2357 Atom XdndAware, XdndTypeList, XdndSelection, XdndEnter, XdndPosition, XdndStatus, XdndLeave, XdndDrop, XdndFinished, XdndActionCopy, XtextPlain, XtextUriList;
2358
2359 Atom wm_delete_window = 0;
2360
2361#if !defined(RGFW_NO_X11_CURSOR) && !defined(RGFW_NO_X11_CURSOR_PRELOAD)
2362 typedef XcursorImage* (*PFN_XcursorImageCreate)(int, int);
2363 typedef void (*PFN_XcursorImageDestroy)(XcursorImage*);
2364 typedef Cursor(*PFN_XcursorImageLoadCursor)(Display*, const XcursorImage*);
2365#endif
2366#ifdef RGFW_OPENGL
2367 typedef GLXContext(*glXCreateContextAttribsARBProc)(Display*, GLXFBConfig, GLXContext, Bool, const int*);
2368#endif
2369
2370#if !defined(RGFW_NO_X11_XI_PRELOAD)
2371 typedef int (* PFN_XISelectEvents)(Display*,Window,XIEventMask*,int);
2372 PFN_XISelectEvents XISelectEventsSrc = NULL;
2373 #define XISelectEvents XISelectEventsSrc
2374
2375 void* X11Xihandle = NULL;
2376#endif
2377
2378#if !defined(RGFW_NO_X11_CURSOR) && !defined(RGFW_NO_X11_CURSOR_PRELOAD)
2379 PFN_XcursorImageLoadCursor XcursorImageLoadCursorSrc = NULL;
2380 PFN_XcursorImageCreate XcursorImageCreateSrc = NULL;
2381 PFN_XcursorImageDestroy XcursorImageDestroySrc = NULL;
2382
2383#define XcursorImageLoadCursor XcursorImageLoadCursorSrc
2384#define XcursorImageCreate XcursorImageCreateSrc
2385#define XcursorImageDestroy XcursorImageDestroySrc
2386
2387 void* X11Cursorhandle = NULL;
2388#endif
2389
2390 u32 RGFW_windowsOpen = 0;
2391
2392#ifdef RGFW_OPENGL
2393 void* RGFW_getProcAddress(const char* procname) { return (void*) glXGetProcAddress((GLubyte*) procname); }
2394#endif
2395
2396 RGFWDEF void RGFW_init_buffer(RGFW_window* win, XVisualInfo* vi);
2397 void RGFW_init_buffer(RGFW_window* win, XVisualInfo* vi) {
2398#if defined(RGFW_OSMESA) || defined(RGFW_BUFFER)
2399 if (RGFW_bufferSize.w == 0 && RGFW_bufferSize.h == 0)
2400 RGFW_bufferSize = RGFW_getScreenSize();
2401
2402 win->buffer = (u8*)RGFW_MALLOC(RGFW_bufferSize.w * RGFW_bufferSize.h * 4);
2403
2404 #ifdef RGFW_OSMESA
2405 win->src.ctx = OSMesaCreateContext(OSMESA_RGBA, NULL);
2406 OSMesaMakeCurrent(win->src.ctx, win->buffer, GL_UNSIGNED_BYTE, win->r.w, win->r.h);
2407 #endif
2408
2409 win->src.bitmap = XCreateImage(
2410 win->src.display, XDefaultVisual(win->src.display, vi->screen),
2411 vi->depth,
2412 ZPixmap, 0, NULL, RGFW_bufferSize.w, RGFW_bufferSize.h,
2413 32, 0
2414 );
2415
2416 win->src.gc = XCreateGC(win->src.display, win->src.window, 0, NULL);
2417
2418 #else
2419 RGFW_UNUSED(win); /*!< if buffer rendering is not being used */
2420 RGFW_UNUSED(vi)
2421 #endif
2422 }
2423
2424
2425
2426 void RGFW_window_setBorder(RGFW_window* win, u8 border) {
2427 static Atom _MOTIF_WM_HINTS = 0;
2428 if (_MOTIF_WM_HINTS == 0 )
2429 _MOTIF_WM_HINTS = XInternAtom(win->src.display, "_MOTIF_WM_HINTS", False);
2430
2431 struct __x11WindowHints {
2432 unsigned long flags, functions, decorations, status;
2433 long input_mode;
2434 } hints;
2435 hints.flags = (1L << 1);
2436 hints.decorations = border;
2437
2438 XChangeProperty(
2439 win->src.display, win->src.window,
2440 _MOTIF_WM_HINTS, _MOTIF_WM_HINTS,
2441 32, PropModeReplace, (u8*)&hints, 5
2442 );
2443 }
2444
2445 void RGFW_releaseCursor(RGFW_window* win) {
2446 XUngrabPointer(win->src.display, CurrentTime);
2447
2448 /* disable raw input */
2449 unsigned char mask[] = { 0 };
2450 XIEventMask em;
2451 em.deviceid = XIAllMasterDevices;
2452 em.mask_len = sizeof(mask);
2453 em.mask = mask;
2454
2455 XISelectEvents(win->src.display, XDefaultRootWindow(win->src.display), &em, 1);
2456 }
2457
2458 void RGFW_captureCursor(RGFW_window* win, RGFW_rect r) {
2459 /* enable raw input */
2460 unsigned char mask[XIMaskLen(XI_RawMotion)] = { 0 };
2461 XISetMask(mask, XI_RawMotion);
2462
2463 XIEventMask em;
2464 em.deviceid = XIAllMasterDevices;
2465 em.mask_len = sizeof(mask);
2466 em.mask = mask;
2467
2468 XISelectEvents(win->src.display, XDefaultRootWindow(win->src.display), &em, 1);
2469
2470 XGrabPointer(win->src.display, win->src.window, True, PointerMotionMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
2471
2472 RGFW_window_moveMouse(win, RGFW_POINT(win->r.x + (i32)(r.w / 2), win->r.y + (i32)(r.h / 2)));
2473 }
2474
2475 RGFW_window* RGFW_createWindow(const char* name, RGFW_rect rect, u16 args) {
2476#if !defined(RGFW_NO_X11_CURSOR) && !defined(RGFW_NO_X11_CURSOR_PRELOAD)
2477 if (X11Cursorhandle == NULL) {
2478#if defined(__CYGWIN__)
2479 X11Cursorhandle = dlopen("libXcursor-1.so", RTLD_LAZY | RTLD_LOCAL);
2480#elif defined(__OpenBSD__) || defined(__NetBSD__)
2481 X11Cursorhandle = dlopen("libXcursor.so", RTLD_LAZY | RTLD_LOCAL);
2482#else
2483 X11Cursorhandle = dlopen("libXcursor.so.1", RTLD_LAZY | RTLD_LOCAL);
2484#endif
2485
2486 XcursorImageCreateSrc = (PFN_XcursorImageCreate) dlsym(X11Cursorhandle, "XcursorImageCreate");
2487 XcursorImageDestroySrc = (PFN_XcursorImageDestroy) dlsym(X11Cursorhandle, "XcursorImageDestroy");
2488 XcursorImageLoadCursorSrc = (PFN_XcursorImageLoadCursor) dlsym(X11Cursorhandle, "XcursorImageLoadCursor");
2489 }
2490#endif
2491
2492#if !defined(RGFW_NO_X11_XI_PRELOAD)
2493 if (X11Xihandle == NULL) {
2494#if defined(__CYGWIN__)
2495 X11Xihandle = dlopen("libXi-6.so", RTLD_LAZY | RTLD_LOCAL);
2496#elif defined(__OpenBSD__) || defined(__NetBSD__)
2497 X11Xihandle = dlopen("libXi.so", RTLD_LAZY | RTLD_LOCAL);
2498#else
2499 X11Xihandle = dlopen("libXi.so.6", RTLD_LAZY | RTLD_LOCAL);
2500#endif
2501
2502 XISelectEventsSrc = (PFN_XISelectEvents) dlsym(X11Xihandle, "XISelectEvents");
2503 }
2504#endif
2505
2506 XInitThreads(); /*!< init X11 threading*/
2507
2508 if (args & RGFW_OPENGL_SOFTWARE)
2509 setenv("LIBGL_ALWAYS_SOFTWARE", "1", 1);
2510
2511 RGFW_window* win = RGFW_window_basic_init(rect, args);
2512
2513 u64 event_mask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | StructureNotifyMask | FocusChangeMask | LeaveWindowMask | EnterWindowMask | ExposureMask; /*!< X11 events accepted*/
2514
2515#ifdef RGFW_OPENGL
2516 u32* visual_attribs = RGFW_initFormatAttribs(args & RGFW_OPENGL_SOFTWARE);
2517 i32 fbcount;
2518 GLXFBConfig* fbc = glXChooseFBConfig((Display*) win->src.display, DefaultScreen(win->src.display), (i32*) visual_attribs, &fbcount);
2519
2520 i32 best_fbc = -1;
2521
2522 if (fbcount == 0) {
2523 printf("Failed to find any valid GLX visual configs\n");
2524 return NULL;
2525 }
2526
2527 u32 i;
2528 for (i = 0; i < (u32)fbcount; i++) {
2529 XVisualInfo* vi = glXGetVisualFromFBConfig((Display*) win->src.display, fbc[i]);
2530 if (vi == NULL)
2531 continue;
2532
2533 XFree(vi);
2534
2535 i32 samp_buf, samples;
2536 glXGetFBConfigAttrib((Display*) win->src.display, fbc[i], GLX_SAMPLE_BUFFERS, &samp_buf);
2537 glXGetFBConfigAttrib((Display*) win->src.display, fbc[i], GLX_SAMPLES, &samples);
2538
2539 if ((!(args & RGFW_TRANSPARENT_WINDOW) || vi->depth == 32) &&
2540 (best_fbc < 0 || samp_buf) && (samples == RGFW_SAMPLES || best_fbc == -1)) {
2541 best_fbc = i;
2542 }
2543 }
2544
2545 if (best_fbc == -1) {
2546 printf("Failed to get a valid GLX visual\n");
2547 return NULL;
2548 }
2549
2550 GLXFBConfig bestFbc = fbc[best_fbc];
2551
2552 /* Get a visual */
2553 XVisualInfo* vi = glXGetVisualFromFBConfig((Display*) win->src.display, bestFbc);
2554
2555 XFree(fbc);
2556#else
2557 XVisualInfo viNorm;
2558
2559 viNorm.visual = DefaultVisual((Display*) win->src.display, DefaultScreen((Display*) win->src.display));
2560
2561 viNorm.depth = 0;
2562 XVisualInfo* vi = &viNorm;
2563
2564 XMatchVisualInfo((Display*) win->src.display, DefaultScreen((Display*) win->src.display), 32, TrueColor, vi); /*!< for RGBA backgrounds*/
2565#endif
2566 /* make X window attrubutes*/
2567 XSetWindowAttributes swa;
2568 Colormap cmap;
2569
2570 swa.colormap = cmap = XCreateColormap((Display*) win->src.display,
2571 DefaultRootWindow(win->src.display),
2572 vi->visual, AllocNone);
2573
2574 swa.background_pixmap = None;
2575 swa.border_pixel = 0;
2576 swa.event_mask = event_mask;
2577
2578 swa.background_pixel = 0;
2579
2580 /* create the window*/
2581 win->src.window = XCreateWindow((Display*) win->src.display, DefaultRootWindow((Display*) win->src.display), win->r.x, win->r.y, win->r.w, win->r.h,
2582 0, vi->depth, InputOutput, vi->visual,
2583 CWColormap | CWBorderPixel | CWBackPixel | CWEventMask, &swa);
2584
2585 XFreeColors((Display*) win->src.display, cmap, NULL, 0, 0);
2586
2587 #ifdef RGFW_OPENGL
2588 XFree(vi);
2589 #endif
2590
2591 // In your .desktop app, if you set the property
2592 // StartupWMClass=RGFW that will assoicate the launcher icon
2593 // with your application - robrohan
2594
2595 if (RGFW_className == NULL)
2596 RGFW_className = (char*)name;
2597
2598 XClassHint *hint = XAllocClassHint();
2599 assert(hint != NULL);
2600 hint->res_class = (char*)RGFW_className;
2601 hint->res_name = (char*)name; // just use the window name as the app name
2602 XSetClassHint((Display*) win->src.display, win->src.window, hint);
2603 XFree(hint);
2604
2605 if ((args & RGFW_NO_INIT_API) == 0) {
2606#ifdef RGFW_OPENGL /* This is the second part of setting up opengl. This is where we ask OpenGL for a specific version. */
2607 i32 context_attribs[7] = { 0, 0, 0, 0, 0, 0, 0 };
2608 context_attribs[0] = GLX_CONTEXT_PROFILE_MASK_ARB;
2609 if (RGFW_profile == RGFW_GL_CORE)
2610 context_attribs[1] = GLX_CONTEXT_CORE_PROFILE_BIT_ARB;
2611 else
2612 context_attribs[1] = GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB;
2613
2614 if (RGFW_majorVersion || RGFW_minorVersion) {
2615 context_attribs[2] = GLX_CONTEXT_MAJOR_VERSION_ARB;
2616 context_attribs[3] = RGFW_majorVersion;
2617 context_attribs[4] = GLX_CONTEXT_MINOR_VERSION_ARB;
2618 context_attribs[5] = RGFW_minorVersion;
2619 }
2620
2621 glXCreateContextAttribsARBProc glXCreateContextAttribsARB = 0;
2622 glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc)
2623 glXGetProcAddressARB((GLubyte*) "glXCreateContextAttribsARB");
2624
2625 GLXContext ctx = NULL;
2626
2627 if (RGFW_root != NULL)
2628 ctx = RGFW_root->src.ctx;
2629
2630 win->src.ctx = glXCreateContextAttribsARB((Display*) win->src.display, bestFbc, ctx, True, context_attribs);
2631#endif
2632 if (RGFW_root == NULL)
2633 RGFW_root = win;
2634
2635 RGFW_init_buffer(win, vi);
2636 }
2637
2638
2639 #ifndef RGFW_NO_MONITOR
2640 if (args & RGFW_SCALE_TO_MONITOR)
2641 RGFW_window_scaleToMonitor(win);
2642 #endif
2643
2644 if (args & RGFW_CENTER) {
2645 RGFW_area screenR = RGFW_getScreenSize();
2646 RGFW_window_move(win, RGFW_POINT((screenR.w - win->r.w) / 2, (screenR.h - win->r.h) / 2));
2647 }
2648
2649 if (args & RGFW_NO_RESIZE) { /* make it so the user can't resize the window*/
2650 XSizeHints* sh = XAllocSizeHints();
2651 sh->flags = (1L << 4) | (1L << 5);
2652 sh->min_width = sh->max_width = win->r.w;
2653 sh->min_height = sh->max_height = win->r.h;
2654
2655 XSetWMSizeHints((Display*) win->src.display, (Drawable) win->src.window, sh, XA_WM_NORMAL_HINTS);
2656 XFree(sh);
2657 }
2658
2659 if (args & RGFW_NO_BORDER) {
2660 RGFW_window_setBorder(win, 0);
2661 }
2662
2663 XSelectInput((Display*) win->src.display, (Drawable) win->src.window, event_mask); /*!< tell X11 what events we want*/
2664
2665 /* make it so the user can't close the window until the program does*/
2666 if (wm_delete_window == 0)
2667 wm_delete_window = XInternAtom((Display*) win->src.display, "WM_DELETE_WINDOW", False);
2668
2669 XSetWMProtocols((Display*) win->src.display, (Drawable) win->src.window, &wm_delete_window, 1);
2670
2671 /* connect the context to the window*/
2672#ifdef RGFW_OPENGL
2673 if ((args & RGFW_NO_INIT_API) == 0)
2674 glXMakeCurrent((Display*) win->src.display, (Drawable) win->src.window, (GLXContext) win->src.ctx);
2675#endif
2676
2677 /* set the background*/
2678 XStoreName((Display*) win->src.display, (Drawable) win->src.window, name); /*!< set the name*/
2679
2680 XMapWindow((Display*) win->src.display, (Drawable) win->src.window); /* draw the window*/
2681 XMoveWindow((Display*) win->src.display, (Drawable) win->src.window, win->r.x, win->r.y); /*!< move the window to it's proper cords*/
2682
2683 if (args & RGFW_ALLOW_DND) { /* init drag and drop atoms and turn on drag and drop for this window */
2684 win->_winArgs |= RGFW_ALLOW_DND;
2685
2686 XdndTypeList = XInternAtom((Display*) win->src.display, "XdndTypeList", False);
2687 XdndSelection = XInternAtom((Display*) win->src.display, "XdndSelection", False);
2688
2689 /* client messages */
2690 XdndEnter = XInternAtom((Display*) win->src.display, "XdndEnter", False);
2691 XdndPosition = XInternAtom((Display*) win->src.display, "XdndPosition", False);
2692 XdndStatus = XInternAtom((Display*) win->src.display, "XdndStatus", False);
2693 XdndLeave = XInternAtom((Display*) win->src.display, "XdndLeave", False);
2694 XdndDrop = XInternAtom((Display*) win->src.display, "XdndDrop", False);
2695 XdndFinished = XInternAtom((Display*) win->src.display, "XdndFinished", False);
2696
2697 /* actions */
2698 XdndActionCopy = XInternAtom((Display*) win->src.display, "XdndActionCopy", False);
2699
2700 XtextUriList = XInternAtom((Display*) win->src.display, "text/uri-list", False);
2701 XtextPlain = XInternAtom((Display*) win->src.display, "text/plain", False);
2702
2703 XdndAware = XInternAtom((Display*) win->src.display, "XdndAware", False);
2704 const u8 version = 5;
2705
2706 XChangeProperty((Display*) win->src.display, (Window) win->src.window,
2707 XdndAware, 4, 32,
2708 PropModeReplace, &version, 1); /*!< turns on drag and drop */
2709 }
2710
2711 #ifdef RGFW_EGL
2712 if ((args & RGFW_NO_INIT_API) == 0)
2713 RGFW_createOpenGLContext(win);
2714 #endif
2715
2716 RGFW_window_setMouseDefault(win);
2717
2718 RGFW_windowsOpen++;
2719
2720 return win; /*return newly created window*/
2721 }
2722
2723 RGFW_area RGFW_getScreenSize(void) {
2724 assert(RGFW_root != NULL);
2725
2726 Screen* scrn = DefaultScreenOfDisplay((Display*) RGFW_root->src.display);
2727 return RGFW_AREA(scrn->width, scrn->height);
2728 }
2729
2730 RGFW_point RGFW_getGlobalMousePoint(void) {
2731 assert(RGFW_root != NULL);
2732
2733 RGFW_point RGFWMouse;
2734
2735 i32 x, y;
2736 u32 z;
2737 Window window1, window2;
2738 XQueryPointer((Display*) RGFW_root->src.display, XDefaultRootWindow((Display*) RGFW_root->src.display), &window1, &window2, &RGFWMouse.x, &RGFWMouse.y, &x, &y, &z);
2739
2740 return RGFWMouse;
2741 }
2742
2743 RGFW_point RGFW_window_getMousePoint(RGFW_window* win) {
2744 assert(win != NULL);
2745
2746 RGFW_point RGFWMouse;
2747
2748 i32 x, y;
2749 u32 z;
2750 Window window1, window2;
2751 XQueryPointer((Display*) win->src.display, win->src.window, &window1, &window2, &x, &y, &RGFWMouse.x, &RGFWMouse.y, &z);
2752
2753 return RGFWMouse;
2754 }
2755
2756 int xAxis = 0, yAxis = 0;
2757
2758 RGFW_Event* RGFW_window_checkEvent(RGFW_window* win) {
2759 assert(win != NULL);
2760
2761 static struct {
2762 long source, version;
2763 i32 format;
2764 } xdnd;
2765
2766 if (win->event.type == 0)
2767 RGFW_resetKey();
2768
2769 if (win->event.type == RGFW_quit) {
2770 return NULL;
2771 }
2772
2773 win->event.type = 0;
2774
2775#ifdef __linux__
2776 RGFW_Event* event = RGFW_linux_updateJoystick(win);
2777 if (event != NULL)
2778 return event;
2779#endif
2780
2781 XPending(win->src.display);
2782
2783 XEvent E; /*!< raw X11 event */
2784
2785 /* if there is no unread qued events, get a new one */
2786 if ((QLength(win->src.display) || XEventsQueued((Display*) win->src.display, QueuedAlready) + XEventsQueued((Display*) win->src.display, QueuedAfterReading))
2787 && win->event.type != RGFW_quit
2788 )
2789 XNextEvent((Display*) win->src.display, &E);
2790 else {
2791 return NULL;
2792 }
2793
2794 u32 i;
2795 win->event.type = 0;
2796
2797
2798 switch (E.type) {
2799 case KeyPress:
2800 case KeyRelease: {
2801 win->event.repeat = RGFW_FALSE;
2802 /* check if it's a real key release */
2803 if (E.type == KeyRelease && XEventsQueued((Display*) win->src.display, QueuedAfterReading)) { /* get next event if there is one*/
2804 XEvent NE;
2805 XPeekEvent((Display*) win->src.display, &NE);
2806
2807 if (E.xkey.time == NE.xkey.time && E.xkey.keycode == NE.xkey.keycode) /* check if the current and next are both the same*/
2808 win->event.repeat = RGFW_TRUE;
2809 }
2810
2811 /* set event key data */
2812 KeySym sym = (KeySym)XkbKeycodeToKeysym((Display*) win->src.display, E.xkey.keycode, 0, E.xkey.state & ShiftMask ? 1 : 0);
2813 win->event.keyCode = RGFW_apiKeyCodeToRGFW(E.xkey.keycode);
2814
2815 char* str = (char*)XKeysymToString(sym);
2816 if (str != NULL)
2817 strncpy(win->event.keyName, str, 16);
2818
2819 win->event.keyName[15] = '\0';
2820
2821 RGFW_keyboard[win->event.keyCode].prev = RGFW_isPressed(win, win->event.keyCode);
2822
2823 /* get keystate data */
2824 win->event.type = (E.type == KeyPress) ? RGFW_keyPressed : RGFW_keyReleased;
2825
2826 XKeyboardState keystate;
2827 XGetKeyboardControl((Display*) win->src.display, &keystate);
2828
2829 RGFW_updateLockState(win, (keystate.led_mask & 1), (keystate.led_mask & 2));
2830 RGFW_keyboard[win->event.keyCode].current = (E.type == KeyPress);
2831 RGFW_keyCallback(win, win->event.keyCode, win->event.keyName, win->event.lockState, (E.type == KeyPress));
2832 break;
2833 }
2834 case ButtonPress:
2835 case ButtonRelease:
2836 win->event.type = RGFW_mouseButtonPressed + (E.type == ButtonRelease); // the events match
2837
2838 switch(win->event.button) {
2839 case RGFW_mouseScrollUp:
2840 win->event.scroll = 1;
2841 break;
2842 case RGFW_mouseScrollDown:
2843 win->event.scroll = -1;
2844 break;
2845 default: break;
2846 }
2847
2848 win->event.button = E.xbutton.button;
2849 RGFW_mouseButtons[win->event.button].prev = RGFW_mouseButtons[win->event.button].current;
2850
2851 if (win->event.repeat == RGFW_FALSE)
2852 win->event.repeat = RGFW_isPressed(win, win->event.keyCode);
2853
2854 RGFW_mouseButtons[win->event.button].current = (E.type == ButtonPress);
2855 RGFW_mouseButtonCallback(win, win->event.button, win->event.scroll, (E.type == ButtonPress));
2856 break;
2857
2858 case MotionNotify:
2859 win->event.point.x = E.xmotion.x;
2860 win->event.point.y = E.xmotion.y;
2861
2862 if ((win->_winArgs & RGFW_HOLD_MOUSE)) {
2863 win->event.point.y = E.xmotion.y;
2864
2865 win->event.point.x = win->_lastMousePoint.x - abs(win->event.point.x);
2866 win->event.point.y = win->_lastMousePoint.y - abs(win->event.point.y);
2867 }
2868
2869 win->_lastMousePoint = RGFW_POINT(E.xmotion.x, E.xmotion.y);
2870
2871 win->event.type = RGFW_mousePosChanged;
2872 RGFW_mousePosCallback(win, win->event.point);
2873 break;
2874
2875 case GenericEvent: {
2876 /* MotionNotify is used for mouse events if the mouse isn't held */
2877 if (!(win->_winArgs & RGFW_HOLD_MOUSE)) {
2878 XFreeEventData(win->src.display, &E.xcookie);
2879 break;
2880 }
2881
2882 XGetEventData(win->src.display, &E.xcookie);
2883 if (E.xcookie.evtype == XI_RawMotion) {
2884 XIRawEvent *raw = (XIRawEvent *)E.xcookie.data;
2885 if (raw->valuators.mask_len == 0) {
2886 XFreeEventData(win->src.display, &E.xcookie);
2887 break;
2888 }
2889
2890 double deltaX = 0.0f;
2891 double deltaY = 0.0f;
2892
2893 /* check if relative motion data exists where we think it does */
2894 if (XIMaskIsSet(raw->valuators.mask, 0) != 0)
2895 deltaX += raw->raw_values[0];
2896 if (XIMaskIsSet(raw->valuators.mask, 1) != 0)
2897 deltaY += raw->raw_values[1];
2898
2899 win->event.point = RGFW_POINT((i32)deltaX, (i32)deltaY);
2900
2901 RGFW_window_moveMouse(win, RGFW_POINT(win->r.x + (win->r.w / 2), win->r.y + (win->r.h / 2)));
2902
2903 win->event.type = RGFW_mousePosChanged;
2904 RGFW_mousePosCallback(win, win->event.point);
2905 }
2906
2907 XFreeEventData(win->src.display, &E.xcookie);
2908 break;
2909 }
2910
2911 case Expose:
2912 win->event.type = RGFW_windowRefresh;
2913 RGFW_windowRefreshCallback(win);
2914 break;
2915
2916 case ClientMessage:
2917 /* if the client closed the window*/
2918 if (E.xclient.data.l[0] == (i64) wm_delete_window) {
2919 win->event.type = RGFW_quit;
2920 RGFW_windowQuitCallback(win);
2921 break;
2922 }
2923
2924 /* reset DND values */
2925 if (win->event.droppedFilesCount) {
2926 for (i = 0; i < win->event.droppedFilesCount; i++)
2927 win->event.droppedFiles[i][0] = '\0';
2928 }
2929
2930 win->event.droppedFilesCount = 0;
2931
2932 if ((win->_winArgs & RGFW_ALLOW_DND) == 0)
2933 break;
2934
2935 XEvent reply = { ClientMessage };
2936 reply.xclient.window = xdnd.source;
2937 reply.xclient.format = 32;
2938 reply.xclient.data.l[0] = (long) win->src.window;
2939 reply.xclient.data.l[1] = 0;
2940 reply.xclient.data.l[2] = None;
2941
2942 if (E.xclient.message_type == XdndEnter) {
2943 unsigned long count;
2944 Atom* formats;
2945 Atom real_formats[6];
2946
2947 Bool list = E.xclient.data.l[1] & 1;
2948
2949 xdnd.source = E.xclient.data.l[0];
2950 xdnd.version = E.xclient.data.l[1] >> 24;
2951 xdnd.format = None;
2952
2953 if (xdnd.version > 5)
2954 break;
2955
2956 if (list) {
2957 Atom actualType;
2958 i32 actualFormat;
2959 unsigned long bytesAfter;
2960
2961 XGetWindowProperty((Display*) win->src.display,
2962 xdnd.source,
2963 XdndTypeList,
2964 0,
2965 LONG_MAX,
2966 False,
2967 4,
2968 &actualType,
2969 &actualFormat,
2970 &count,
2971 &bytesAfter,
2972 (u8**) &formats);
2973 } else {
2974 count = 0;
2975
2976 if (E.xclient.data.l[2] != None)
2977 real_formats[count++] = E.xclient.data.l[2];
2978 if (E.xclient.data.l[3] != None)
2979 real_formats[count++] = E.xclient.data.l[3];
2980 if (E.xclient.data.l[4] != None)
2981 real_formats[count++] = E.xclient.data.l[4];
2982
2983 formats = real_formats;
2984 }
2985
2986 unsigned long i;
2987 for (i = 0; i < count; i++) {
2988 if (formats[i] == XtextUriList || formats[i] == XtextPlain) {
2989 xdnd.format = formats[i];
2990 break;
2991 }
2992 }
2993
2994 if (list) {
2995 XFree(formats);
2996 }
2997
2998 break;
2999 }
3000 if (E.xclient.message_type == XdndPosition) {
3001 const i32 xabs = (E.xclient.data.l[2] >> 16) & 0xffff;
3002 const i32 yabs = (E.xclient.data.l[2]) & 0xffff;
3003 Window dummy;
3004 i32 xpos, ypos;
3005
3006 if (xdnd.version > 5)
3007 break;
3008
3009 XTranslateCoordinates((Display*) win->src.display,
3010 XDefaultRootWindow((Display*) win->src.display),
3011 (Window) win->src.window,
3012 xabs, yabs,
3013 &xpos, &ypos,
3014 &dummy);
3015
3016 win->event.point.x = xpos;
3017 win->event.point.y = ypos;
3018
3019 reply.xclient.window = xdnd.source;
3020 reply.xclient.message_type = XdndStatus;
3021
3022 if (xdnd.format) {
3023 reply.xclient.data.l[1] = 1;
3024 if (xdnd.version >= 2)
3025 reply.xclient.data.l[4] = XdndActionCopy;
3026 }
3027
3028 XSendEvent((Display*) win->src.display, xdnd.source, False, NoEventMask, &reply);
3029 XFlush((Display*) win->src.display);
3030 break;
3031 }
3032
3033 if (E.xclient.message_type != XdndDrop)
3034 break;
3035
3036 if (xdnd.version > 5)
3037 break;
3038
3039 win->event.type = RGFW_dnd_init;
3040
3041 if (xdnd.format) {
3042 Time time = CurrentTime;
3043
3044 if (xdnd.version >= 1)
3045 time = E.xclient.data.l[2];
3046
3047 XConvertSelection((Display*) win->src.display,
3048 XdndSelection,
3049 xdnd.format,
3050 XdndSelection,
3051 (Window) win->src.window,
3052 time);
3053 } else if (xdnd.version >= 2) {
3054 XEvent reply = { ClientMessage };
3055
3056 XSendEvent((Display*) win->src.display, xdnd.source,
3057 False, NoEventMask, &reply);
3058 XFlush((Display*) win->src.display);
3059 }
3060
3061 RGFW_dndInitCallback(win, win->event.point);
3062 break;
3063 case SelectionNotify: {
3064 /* this is only for checking for xdnd drops */
3065 if (E.xselection.property != XdndSelection || !(win->_winArgs | RGFW_ALLOW_DND))
3066 break;
3067
3068 char* data;
3069 unsigned long result;
3070
3071 Atom actualType;
3072 i32 actualFormat;
3073 unsigned long bytesAfter;
3074
3075 XGetWindowProperty((Display*) win->src.display, E.xselection.requestor, E.xselection.property, 0, LONG_MAX, False, E.xselection.target, &actualType, &actualFormat, &result, &bytesAfter, (u8**) &data);
3076
3077 if (result == 0)
3078 break;
3079
3080 /*
3081 SOURCED FROM GLFW _glfwParseUriList
3082 Copyright (c) 2002-2006 Marcus Geelnard
3083 Copyright (c) 2006-2019 Camilla Löwy
3084 */
3085
3086 const char* prefix = (const char*)"file://";
3087
3088 char* line;
3089
3090 win->event.droppedFilesCount = 0;
3091
3092 win->event.type = RGFW_dnd;
3093
3094 while ((line = strtok(data, "\r\n"))) {
3095 char path[RGFW_MAX_PATH];
3096
3097 data = NULL;
3098
3099 if (line[0] == '#')
3100 continue;
3101
3102 char* l;
3103 for (l = line; 1; l++) {
3104 if ((l - line) > 7)
3105 break;
3106 else if (*l != prefix[(l - line)])
3107 break;
3108 else if (*l == '\0' && prefix[(l - line)] == '\0') {
3109 line += 7;
3110 while (*line != '/')
3111 line++;
3112 break;
3113 } else if (*l == '\0')
3114 break;
3115 }
3116
3117 win->event.droppedFilesCount++;
3118
3119 size_t index = 0;
3120 while (*line) {
3121 if (line[0] == '%' && line[1] && line[2]) {
3122 const char digits[3] = { line[1], line[2], '\0' };
3123 path[index] = (char) strtol(digits, NULL, 16);
3124 line += 2;
3125 } else
3126 path[index] = *line;
3127
3128 index++;
3129 line++;
3130 }
3131 path[index] = '\0';
3132 strncpy(win->event.droppedFiles[win->event.droppedFilesCount - 1], path, index + 1);
3133 }
3134
3135 if (data)
3136 XFree(data);
3137
3138 if (xdnd.version >= 2) {
3139 reply.xclient.message_type = XdndFinished;
3140 reply.xclient.data.l[1] = result;
3141 reply.xclient.data.l[2] = XdndActionCopy;
3142
3143 XSendEvent((Display*) win->src.display, xdnd.source, False, NoEventMask, &reply);
3144 XFlush((Display*) win->src.display);
3145 }
3146
3147 RGFW_dndCallback(win, win->event.droppedFiles, win->event.droppedFilesCount);
3148 break;
3149 }
3150 case FocusIn:
3151 win->event.inFocus = 1;
3152 win->event.type = RGFW_focusIn;
3153 RGFW_focusCallback(win, 1);
3154 break;
3155
3156 break;
3157 case FocusOut:
3158 win->event.inFocus = 0;
3159 win->event.type = RGFW_focusOut;
3160 RGFW_focusCallback(win, 0);
3161 break;
3162
3163 case EnterNotify: {
3164 win->event.type = RGFW_mouseEnter;
3165 win->event.point.x = E.xcrossing.x;
3166 win->event.point.y = E.xcrossing.y;
3167 RGFW_mouseNotifyCallBack(win, win->event.point, 1);
3168 break;
3169 }
3170
3171 case LeaveNotify: {
3172 win->event.type = RGFW_mouseLeave;
3173 RGFW_mouseNotifyCallBack(win, win->event.point, 0);
3174 break;
3175 }
3176
3177 case ConfigureNotify: {
3178 /* detect resize */
3179 if (E.xconfigure.width != win->r.w || E.xconfigure.height != win->r.h) {
3180 win->event.type = RGFW_windowResized;
3181 win->r = RGFW_RECT(win->r.x, win->r.y, E.xconfigure.width, E.xconfigure.height);
3182 RGFW_windowResizeCallback(win, win->r);
3183 break;
3184 }
3185
3186 /* detect move */
3187 if (E.xconfigure.x != win->r.x || E.xconfigure.y != win->r.y) {
3188 win->event.type = RGFW_windowMoved;
3189 win->r = RGFW_RECT(E.xconfigure.x, E.xconfigure.y, win->r.w, win->r.h);
3190 RGFW_windowMoveCallback(win, win->r);
3191 break;
3192 }
3193
3194 break;
3195 }
3196 default: {
3197 break;
3198 }
3199 }
3200
3201 XFlush((Display*) win->src.display);
3202
3203 if (win->event.type)
3204 return &win->event;
3205 else
3206 return NULL;
3207 }
3208
3209 void RGFW_window_move(RGFW_window* win, RGFW_point v) {
3210 assert(win != NULL);
3211 win->r.x = v.x;
3212 win->r.y = v.y;
3213
3214 XMoveWindow((Display*) win->src.display, (Window) win->src.window, v.x, v.y);
3215 }
3216
3217
3218 void RGFW_window_resize(RGFW_window* win, RGFW_area a) {
3219 assert(win != NULL);
3220 win->r.w = a.w;
3221 win->r.h = a.h;
3222
3223 XResizeWindow((Display*) win->src.display, (Window) win->src.window, a.w, a.h);
3224 }
3225
3226 void RGFW_window_setMinSize(RGFW_window* win, RGFW_area a) {
3227 assert(win != NULL);
3228
3229 if (a.w == 0 && a.h == 0)
3230 return;
3231
3232 XSizeHints hints;
3233 long flags;
3234
3235 XGetWMNormalHints(win->src.display, (Window) win->src.window, &hints, &flags);
3236
3237 hints.flags |= PMinSize;
3238
3239 hints.min_width = a.w;
3240 hints.min_height = a.h;
3241
3242 XSetWMNormalHints(win->src.display, (Window) win->src.window, &hints);
3243 }
3244
3245 void RGFW_window_setMaxSize(RGFW_window* win, RGFW_area a) {
3246 assert(win != NULL);
3247
3248 if (a.w == 0 && a.h == 0)
3249 return;
3250
3251 XSizeHints hints;
3252 long flags;
3253
3254 XGetWMNormalHints(win->src.display, (Window) win->src.window, &hints, &flags);
3255
3256 hints.flags |= PMaxSize;
3257
3258 hints.max_width = a.w;
3259 hints.max_height = a.h;
3260
3261 XSetWMNormalHints(win->src.display, (Window) win->src.window, &hints);
3262 }
3263
3264
3265 void RGFW_window_minimize(RGFW_window* win) {
3266 assert(win != NULL);
3267
3268 XIconifyWindow(win->src.display, (Window) win->src.window, DefaultScreen(win->src.display));
3269 XFlush(win->src.display);
3270 }
3271
3272 void RGFW_window_restore(RGFW_window* win) {
3273 assert(win != NULL);
3274
3275 XMapWindow(win->src.display, (Window) win->src.window);
3276 XFlush(win->src.display);
3277 }
3278
3279 void RGFW_window_setName(RGFW_window* win, char* name) {
3280 assert(win != NULL);
3281
3282 XStoreName((Display*) win->src.display, (Window) win->src.window, name);
3283 }
3284
3285 void* RGFW_libxshape = NULL;
3286
3287 #ifndef RGFW_NO_PASSTHROUGH
3288 void RGFW_window_setMousePassthrough(RGFW_window* win, b8 passthrough) {
3289 assert(win != NULL);
3290
3291 #if defined(__CYGWIN__)
3292 RGFW_libxshape = dlopen("libXext-6.so", RTLD_LAZY | RTLD_LOCAL);
3293 #elif defined(__OpenBSD__) || defined(__NetBSD__)
3294 RGFW_libxshape = dlopen("libXext.so", RTLD_LAZY | RTLD_LOCAL);
3295 #else
3296 RGFW_libxshape = dlopen("libXext.so.6", RTLD_LAZY | RTLD_LOCAL);
3297 #endif
3298
3299 typedef void (* PFN_XShapeCombineMask)(Display*,Window,int,int,int,Pixmap,int);
3300 static PFN_XShapeCombineMask XShapeCombineMask;
3301
3302 typedef void (* PFN_XShapeCombineRegion)(Display*,Window,int,int,int,Region,int);
3303 static PFN_XShapeCombineRegion XShapeCombineRegion;
3304
3305 if (XShapeCombineMask != NULL)
3306 XShapeCombineMask = (PFN_XShapeCombineMask) dlsym(RGFW_libxshape, "XShapeCombineMask");
3307
3308 if (XShapeCombineRegion != NULL)
3309 XShapeCombineRegion = (PFN_XShapeCombineRegion) dlsym(RGFW_libxshape, "XShapeCombineMask");
3310
3311 if (passthrough) {
3312 Region region = XCreateRegion();
3313 XShapeCombineRegion(win->src.display, win->src.window, ShapeInput, 0, 0, region, ShapeSet);
3314 XDestroyRegion(region);
3315
3316 return;
3317 }
3318
3319 XShapeCombineMask(win->src.display, win->src.window, ShapeInput, 0, 0, None, ShapeSet);
3320 }
3321 #endif
3322
3323 /*
3324 the majority function is sourced from GLFW
3325 */
3326
3327 void RGFW_window_setIcon(RGFW_window* win, u8* icon, RGFW_area a, i32 channels) {
3328 assert(win != NULL);
3329
3330 i32 longCount = 2 + a.w * a.h;
3331
3332 u64* X11Icon = (u64*) RGFW_MALLOC(longCount * sizeof(u64));
3333 u64* target = X11Icon;
3334
3335 *target++ = a.w;
3336 *target++ = a.h;
3337
3338 u32 i;
3339
3340 for (i = 0; i < a.w * a.h; i++) {
3341 if (channels == 3)
3342 *target++ = ((icon[i * 3 + 0]) << 16) |
3343 ((icon[i * 3 + 1]) << 8) |
3344 ((icon[i * 3 + 2]) << 0) |
3345 (0xFF << 24);
3346
3347 else if (channels == 4)
3348 *target++ = ((icon[i * 4 + 0]) << 16) |
3349 ((icon[i * 4 + 1]) << 8) |
3350 ((icon[i * 4 + 2]) << 0) |
3351 ((icon[i * 4 + 3]) << 24);
3352 }
3353
3354 static Atom NET_WM_ICON = 0;
3355 if (NET_WM_ICON == 0)
3356 NET_WM_ICON = XInternAtom((Display*) win->src.display, "_NET_WM_ICON", False);
3357
3358 XChangeProperty((Display*) win->src.display, (Window) win->src.window,
3359 NET_WM_ICON,
3360 6, 32,
3361 PropModeReplace,
3362 (u8*) X11Icon,
3363 longCount);
3364
3365 RGFW_FREE(X11Icon);
3366
3367 XFlush((Display*) win->src.display);
3368 }
3369
3370 void RGFW_window_setMouse(RGFW_window* win, u8* image, RGFW_area a, i32 channels) {
3371 assert(win != NULL);
3372
3373#ifndef RGFW_NO_X11_CURSOR
3374 XcursorImage* native = XcursorImageCreate(a.w, a.h);
3375 native->xhot = 0;
3376 native->yhot = 0;
3377
3378 u8* source = (u8*) image;
3379 XcursorPixel* target = native->pixels;
3380
3381 u32 i;
3382 for (i = 0; i < a.w * a.h; i++, target++, source += 4) {
3383 u8 alpha = 0xFF;
3384 if (channels == 4)
3385 alpha = source[3];
3386
3387 *target = (alpha << 24) | (((source[0] * alpha) / 255) << 16) | (((source[1] * alpha) / 255) << 8) | (((source[2] * alpha) / 255) << 0);
3388 }
3389
3390 Cursor cursor = XcursorImageLoadCursor((Display*) win->src.display, native);
3391 XDefineCursor((Display*) win->src.display, (Window) win->src.window, (Cursor) cursor);
3392
3393 XFreeCursor((Display*) win->src.display, (Cursor) cursor);
3394 XcursorImageDestroy(native);
3395#else
3396 RGFW_UNUSED(image) RGFW_UNUSED(a.w) RGFW_UNUSED(channels)
3397#endif
3398 }
3399
3400 void RGFW_window_moveMouse(RGFW_window* win, RGFW_point v) {
3401 assert(win != NULL);
3402
3403 XEvent event;
3404 XQueryPointer(win->src.display, DefaultRootWindow(win->src.display),
3405 &event.xbutton.root, &event.xbutton.window,
3406 &event.xbutton.x_root, &event.xbutton.y_root,
3407 &event.xbutton.x, &event.xbutton.y,
3408 &event.xbutton.state);
3409
3410 if (event.xbutton.x == v.x && event.xbutton.y == v.y)
3411 return;
3412
3413 XWarpPointer(win->src.display, None, win->src.window, 0, 0, 0, 0, (int) v.x - win->r.x, (int) v.y - win->r.y);
3414 }
3415
3416 RGFWDEF void RGFW_window_disableMouse(RGFW_window* win) {
3417 RGFW_UNUSED(win);
3418 }
3419
3420 void RGFW_window_setMouseDefault(RGFW_window* win) {
3421 RGFW_window_setMouseStandard(win, RGFW_MOUSE_ARROW);
3422 }
3423
3424 void RGFW_window_setMouseStandard(RGFW_window* win, u8 mouse) {
3425 assert(win != NULL);
3426
3427 if (mouse > (sizeof(RGFW_mouseIconSrc) / sizeof(u8)))
3428 return;
3429
3430 mouse = RGFW_mouseIconSrc[mouse];
3431
3432 Cursor cursor = XCreateFontCursor((Display*) win->src.display, mouse);
3433 XDefineCursor((Display*) win->src.display, (Window) win->src.window, (Cursor) cursor);
3434
3435 XFreeCursor((Display*) win->src.display, (Cursor) cursor);
3436 }
3437
3438 void RGFW_window_hide(RGFW_window* win) {
3439 XMapWindow(win->src.display, win->src.window);
3440 }
3441
3442 void RGFW_window_show(RGFW_window* win) {
3443 XUnmapWindow(win->src.display, win->src.window);
3444 }
3445
3446 /*
3447 the majority function is sourced from GLFW
3448 */
3449 char* RGFW_readClipboard(size_t* size) {
3450 static Atom UTF8 = 0;
3451 if (UTF8 == 0)
3452 UTF8 = XInternAtom(RGFW_root->src.display, "UTF8_STRING", True);
3453
3454 XEvent event;
3455 int format;
3456 unsigned long N, sizeN;
3457 char* data, * s = NULL;
3458 Atom target;
3459 Atom CLIPBOARD = 0, XSEL_DATA = 0;
3460
3461 if (CLIPBOARD == 0) {
3462 CLIPBOARD = XInternAtom(RGFW_root->src.display, "CLIPBOARD", 0);
3463 XSEL_DATA = XInternAtom(RGFW_root->src.display, "XSEL_DATA", 0);
3464 }
3465
3466 XConvertSelection(RGFW_root->src.display, CLIPBOARD, UTF8, XSEL_DATA, RGFW_root->src.window, CurrentTime);
3467 XSync(RGFW_root->src.display, 0);
3468 XNextEvent(RGFW_root->src.display, &event);
3469
3470 if (event.type != SelectionNotify || event.xselection.selection != CLIPBOARD || event.xselection.property == 0)
3471 return NULL;
3472
3473 XGetWindowProperty(event.xselection.display, event.xselection.requestor,
3474 event.xselection.property, 0L, (~0L), 0, AnyPropertyType, &target,
3475 &format, &sizeN, &N, (unsigned char**) &data);
3476
3477 if (target == UTF8 || target == XA_STRING) {
3478 s = (char*)RGFW_MALLOC(sizeof(char) * sizeN);
3479 strncpy(s, data, sizeN);
3480 s[sizeN] = '\0';
3481 XFree(data);
3482 }
3483
3484 XDeleteProperty(event.xselection.display, event.xselection.requestor, event.xselection.property);
3485
3486 if (s != NULL && size != NULL)
3487 *size = sizeN;
3488
3489 return s;
3490 }
3491
3492 /*
3493 almost all of this function is sourced from GLFW
3494 */
3495 void RGFW_writeClipboard(const char* text, u32 textLen) {
3496 static Atom CLIPBOARD = 0,
3497 UTF8_STRING = 0,
3498 SAVE_TARGETS = 0,
3499 TARGETS = 0,
3500 MULTIPLE = 0,
3501 ATOM_PAIR = 0,
3502 CLIPBOARD_MANAGER = 0;
3503
3504 if (CLIPBOARD == 0) {
3505 CLIPBOARD = XInternAtom((Display*) RGFW_root->src.display, "CLIPBOARD", False);
3506 UTF8_STRING = XInternAtom((Display*) RGFW_root->src.display, "UTF8_STRING", False);
3507 SAVE_TARGETS = XInternAtom((Display*) RGFW_root->src.display, "SAVE_TARGETS", False);
3508 TARGETS = XInternAtom((Display*) RGFW_root->src.display, "TARGETS", False);
3509 MULTIPLE = XInternAtom((Display*) RGFW_root->src.display, "MULTIPLE", False);
3510 ATOM_PAIR = XInternAtom((Display*) RGFW_root->src.display, "ATOM_PAIR", False);
3511 CLIPBOARD_MANAGER = XInternAtom((Display*) RGFW_root->src.display, "CLIPBOARD_MANAGER", False);
3512 }
3513
3514 XSetSelectionOwner((Display*) RGFW_root->src.display, CLIPBOARD, (Window) RGFW_root->src.window, CurrentTime);
3515
3516 XConvertSelection((Display*) RGFW_root->src.display, CLIPBOARD_MANAGER, SAVE_TARGETS, None, (Window) RGFW_root->src.window, CurrentTime);
3517 for (;;) {
3518 XEvent event;
3519
3520 XNextEvent((Display*) RGFW_root->src.display, &event);
3521 if (event.type != SelectionRequest) {
3522 break;
3523 }
3524
3525 const XSelectionRequestEvent* request = &event.xselectionrequest;
3526
3527 XEvent reply = { SelectionNotify };
3528 reply.xselection.property = 0;
3529
3530 if (request->target == TARGETS) {
3531 const Atom targets[] = { TARGETS,
3532 MULTIPLE,
3533 UTF8_STRING,
3534 XA_STRING };
3535
3536 XChangeProperty((Display*) RGFW_root->src.display,
3537 request->requestor,
3538 request->property,
3539 4,
3540 32,
3541 PropModeReplace,
3542 (u8*) targets,
3543 sizeof(targets) / sizeof(targets[0]));
3544
3545 reply.xselection.property = request->property;
3546 }
3547
3548 if (request->target == MULTIPLE) {
3549 Atom* targets = NULL;
3550
3551 Atom actualType = 0;
3552 int actualFormat = 0;
3553 unsigned long count = 0, bytesAfter = 0;
3554
3555 XGetWindowProperty((Display*) RGFW_root->src.display, request->requestor, request->property, 0, LONG_MAX, False, ATOM_PAIR, &actualType, &actualFormat, &count, &bytesAfter, (u8**) &targets);
3556
3557 unsigned long i;
3558 for (i = 0; i < (u32)count; i += 2) {
3559 if (targets[i] == UTF8_STRING || targets[i] == XA_STRING) {
3560 XChangeProperty((Display*) RGFW_root->src.display,
3561 request->requestor,
3562 targets[i + 1],
3563 targets[i],
3564 8,
3565 PropModeReplace,
3566 (u8*) text,
3567 textLen);
3568 XFlush(RGFW_root->src.display);
3569 } else {
3570 targets[i + 1] = None;
3571 }
3572 }
3573
3574 XChangeProperty((Display*) RGFW_root->src.display,
3575 request->requestor,
3576 request->property,
3577 ATOM_PAIR,
3578 32,
3579 PropModeReplace,
3580 (u8*) targets,
3581 count);
3582
3583 XFlush(RGFW_root->src.display);
3584 XFree(targets);
3585
3586 reply.xselection.property = request->property;
3587 }
3588
3589 reply.xselection.display = request->display;
3590 reply.xselection.requestor = request->requestor;
3591 reply.xselection.selection = request->selection;
3592 reply.xselection.target = request->target;
3593 reply.xselection.time = request->time;
3594
3595 XSendEvent((Display*) RGFW_root->src.display, request->requestor, False, 0, &reply);
3596 XFlush(RGFW_root->src.display);
3597 }
3598 }
3599
3600 u8 RGFW_window_isFullscreen(RGFW_window* win) {
3601 assert(win != NULL);
3602
3603 XWindowAttributes windowAttributes;
3604 XGetWindowAttributes(win->src.display, (Window) win->src.window, &windowAttributes);
3605
3606 /* check if the window is visable */
3607 if (windowAttributes.map_state != IsViewable)
3608 return 0;
3609
3610 /* check if the window covers the full screen */
3611 return (windowAttributes.x == 0 && windowAttributes.y == 0 &&
3612 windowAttributes.width == XDisplayWidth(win->src.display, DefaultScreen(win->src.display)) &&
3613 windowAttributes.height == XDisplayHeight(win->src.display, DefaultScreen(win->src.display)));
3614 }
3615
3616 u8 RGFW_window_isHidden(RGFW_window* win) {
3617 assert(win != NULL);
3618
3619 XWindowAttributes windowAttributes;
3620 XGetWindowAttributes(win->src.display, (Window) win->src.window, &windowAttributes);
3621
3622 return (windowAttributes.map_state == IsUnmapped && !RGFW_window_isMinimized(win));
3623 }
3624
3625 u8 RGFW_window_isMinimized(RGFW_window* win) {
3626 assert(win != NULL);
3627
3628 static Atom prop = 0;
3629 if (prop == 0)
3630 prop = XInternAtom(win->src.display, "WM_STATE", False);
3631
3632 Atom actual_type;
3633 i32 actual_format;
3634 unsigned long nitems, bytes_after;
3635 unsigned char* prop_data;
3636
3637 i16 status = XGetWindowProperty(win->src.display, (Window) win->src.window, prop, 0, 2, False,
3638 AnyPropertyType, &actual_type, &actual_format,
3639 &nitems, &bytes_after, &prop_data);
3640
3641 if (status == Success && nitems >= 1 && *((int*) prop_data) == IconicState) {
3642 XFree(prop_data);
3643 return 1;
3644 }
3645
3646 if (prop_data != NULL)
3647 XFree(prop_data);
3648
3649 return 0;
3650 }
3651
3652 u8 RGFW_window_isMaximized(RGFW_window* win) {
3653 assert(win != NULL);
3654
3655 static Atom net_wm_state = 0;
3656 static Atom net_wm_state_maximized_horz = 0;
3657 static Atom net_wm_state_maximized_vert = 0;
3658
3659 if (net_wm_state == 0) {
3660 net_wm_state = XInternAtom(win->src.display, "_NET_WM_STATE", False);
3661 net_wm_state_maximized_vert = XInternAtom(win->src.display, "_NET_WM_STATE_MAXIMIZED_VERT", False);
3662 net_wm_state_maximized_horz = XInternAtom(win->src.display, "_NET_WM_STATE_MAXIMIZED_HORZ", False);
3663 }
3664
3665 Atom actual_type;
3666 i32 actual_format;
3667 unsigned long nitems, bytes_after;
3668 unsigned char* prop_data;
3669
3670 i16 status = XGetWindowProperty(win->src.display, (Window) win->src.window, net_wm_state, 0, 1024, False,
3671 XA_ATOM, &actual_type, &actual_format,
3672 &nitems, &bytes_after, &prop_data);
3673
3674 if (status != Success) {
3675 if (prop_data != NULL)
3676 XFree(prop_data);
3677
3678 return 0;
3679 }
3680
3681 Atom* atoms = (Atom*) prop_data;
3682 u64 i;
3683 for (i = 0; i < nitems; ++i) {
3684 if (atoms[i] == net_wm_state_maximized_horz ||
3685 atoms[i] == net_wm_state_maximized_vert) {
3686 XFree(prop_data);
3687 return 1;
3688 }
3689 }
3690
3691 return 0;
3692 }
3693
3694 static void XGetSystemContentScale(Display* display, float* xscale, float* yscale) {
3695 float xdpi = 96.f, ydpi = 96.f;
3696
3697#ifndef RGFW_NO_DPI
3698 char* rms = XResourceManagerString(display);
3699 XrmDatabase db = NULL;
3700
3701 if (rms && db)
3702 db = XrmGetStringDatabase(rms);
3703
3704 if (db == 0) {
3705 *xscale = xdpi / 96.f;
3706 *yscale = ydpi / 96.f;
3707 return;
3708 }
3709
3710 XrmValue value;
3711 char* type = NULL;
3712
3713 if (XrmGetResource(db, "Xft.dpi", "Xft.Dpi", &type, &value) && type && strncmp(type, "String", 7) == 0)
3714 xdpi = ydpi = atof(value.addr);
3715 XrmDestroyDatabase(db);
3716#endif
3717
3718 * xscale = xdpi / 96.f;
3719 *yscale = ydpi / 96.f;
3720 }
3721
3722 RGFW_monitor RGFW_XCreateMonitor(i32 screen) {
3723 RGFW_monitor monitor;
3724
3725 Display* display = XOpenDisplay(NULL);
3726
3727 RGFW_area size = RGFW_getScreenSize();
3728
3729 monitor.rect = RGFW_RECT(0, 0, size.w, size.h);
3730 monitor.physW = DisplayWidthMM(display, screen);
3731 monitor.physH = DisplayHeightMM(display, screen);
3732
3733 XGetSystemContentScale(display, &monitor.scaleX, &monitor.scaleY);
3734 XRRScreenResources* sr = XRRGetScreenResourcesCurrent(display, RootWindow(display, screen));
3735
3736 XRRCrtcInfo* ci = NULL;
3737 int crtc = screen;
3738
3739 if (sr->ncrtc > crtc) {
3740 ci = XRRGetCrtcInfo(display, sr, sr->crtcs[crtc]);
3741 }
3742
3743 if (ci == NULL) {
3744 float dpi_width = round((double)monitor.rect.w/(((double)monitor.physW)/25.4));
3745 float dpi_height = round((double)monitor.rect.h/(((double)monitor.physH)/25.4));
3746
3747 monitor.scaleX = (float) (dpi_width) / (float) 96;
3748 monitor.scaleY = (float) (dpi_height) / (float) 96;
3749 XRRFreeScreenResources(sr);
3750 XCloseDisplay(display);
3751 return monitor;
3752 }
3753
3754 XRROutputInfo* info = XRRGetOutputInfo (display, sr, sr->outputs[screen]);
3755 monitor.physW = info->mm_width;
3756 monitor.physH = info->mm_height;
3757
3758 monitor.rect.x = ci->x;
3759 monitor.rect.y = ci->y;
3760 monitor.rect.w = ci->width;
3761 monitor.rect.h = ci->height;
3762
3763 float dpi_width = round((double)monitor.rect.w/(((double)monitor.physW)/25.4));
3764 float dpi_height = round((double)monitor.rect.h/(((double)monitor.physH)/25.4));
3765
3766 monitor.scaleX = (float) (dpi_width) / (float) 96;
3767 monitor.scaleY = (float) (dpi_height) / (float) 96;
3768
3769 if (monitor.scaleX > 1 && monitor.scaleX < 1.1)
3770 monitor.scaleX = 1;
3771
3772 if (monitor.scaleY > 1 && monitor.scaleY < 1.1)
3773 monitor.scaleY = 1;
3774
3775 XRRFreeCrtcInfo(ci);
3776 XRRFreeScreenResources(sr);
3777
3778 XCloseDisplay(display);
3779
3780 return monitor;
3781 }
3782
3783 RGFW_monitor RGFW_monitors[6];
3784 RGFW_monitor* RGFW_getMonitors(void) {
3785 size_t i;
3786 for (i = 0; i < (size_t)ScreenCount(RGFW_root->src.display) && i < 6; i++)
3787 RGFW_monitors[i] = RGFW_XCreateMonitor(i);
3788
3789 return RGFW_monitors;
3790 }
3791
3792 RGFW_monitor RGFW_getPrimaryMonitor(void) {
3793 assert(RGFW_root != NULL);
3794
3795 i32 primary = -1;
3796 Window root = DefaultRootWindow(RGFW_root->src.display);
3797 XRRScreenResources* res = XRRGetScreenResources(RGFW_root->src.display, root);
3798
3799 for (int i = 0; i < res->noutput; i++) {
3800 XRROutputInfo* output_info = XRRGetOutputInfo(RGFW_root->src.display, res, res->outputs[i]);
3801 if (output_info->connection == RR_Connected && output_info->crtc) {
3802 XRRCrtcInfo* crtc_info = XRRGetCrtcInfo(RGFW_root->src.display, res, output_info->crtc);
3803 if (crtc_info->mode != None && crtc_info->x == 0 && crtc_info->y == 0) {
3804 primary = i;
3805 XRRFreeCrtcInfo(crtc_info);
3806 XRRFreeOutputInfo(output_info);
3807 break;
3808 }
3809 XRRFreeCrtcInfo(crtc_info);
3810 }
3811 XRRFreeOutputInfo(output_info);
3812 }
3813
3814 XRRFreeScreenResources(res);
3815
3816 return RGFW_XCreateMonitor(primary);
3817 }
3818
3819 RGFW_monitor RGFW_window_getMonitor(RGFW_window* win) {
3820 return RGFW_XCreateMonitor(DefaultScreen(win->src.display));
3821 }
3822
3823 #ifdef RGFW_OPENGL
3824 void RGFW_window_makeCurrent_OpenGL(RGFW_window* win) {
3825 if (win == NULL)
3826 glXMakeCurrent((Display*) NULL, (Drawable)NULL, (GLXContext) NULL);
3827 else
3828 glXMakeCurrent((Display*) win->src.display, (Drawable) win->src.window, (GLXContext) win->src.ctx);
3829 }
3830 #endif
3831
3832
3833 void RGFW_window_swapBuffers(RGFW_window* win) {
3834 assert(win != NULL);
3835
3836 /* clear the window*/
3837 if (!(win->_winArgs & RGFW_NO_CPU_RENDER)) {
3838#if defined(RGFW_OSMESA) || defined(RGFW_BUFFER)
3839 #ifdef RGFW_OSMESA
3840 RGFW_OSMesa_reorganize();
3841 #endif
3842 RGFW_area area = RGFW_bufferSize;
3843
3844#ifndef RGFW_X11_DONT_CONVERT_BGR
3845 win->src.bitmap->data = (char*) win->buffer;
3846 u32 x, y;
3847 for (y = 0; y < (u32)win->r.h; y++) {
3848 for (x = 0; x < (u32)win->r.w; x++) {
3849 u32 index = (y * 4 * area.w) + x * 4;
3850
3851 u8 red = win->src.bitmap->data[index];
3852 win->src.bitmap->data[index] = win->buffer[index + 2];
3853 win->src.bitmap->data[index + 2] = red;
3854
3855 }
3856 }
3857#endif
3858 XPutImage(win->src.display, (Window) win->src.window, win->src.gc, win->src.bitmap, 0, 0, 0, 0, RGFW_bufferSize.w, RGFW_bufferSize.h);
3859#endif
3860 }
3861
3862 if (!(win->_winArgs & RGFW_NO_GPU_RENDER)) {
3863 #ifdef RGFW_EGL
3864 eglSwapBuffers(win->src.EGL_display, win->src.EGL_surface);
3865 #elif defined(RGFW_OPENGL)
3866 glXSwapBuffers((Display*) win->src.display, (Window) win->src.window);
3867 #endif
3868 }
3869 }
3870
3871 #if !defined(RGFW_EGL)
3872 void RGFW_window_swapInterval(RGFW_window* win, i32 swapInterval) {
3873 assert(win != NULL);
3874
3875 #if defined(RGFW_OPENGL)
3876 ((PFNGLXSWAPINTERVALEXTPROC) glXGetProcAddress((GLubyte*) "glXSwapIntervalEXT"))((Display*) win->src.display, (Window) win->src.window, swapInterval);
3877 #else
3878 RGFW_UNUSED(swapInterval);
3879 #endif
3880 }
3881 #endif
3882
3883
3884 void RGFW_window_close(RGFW_window* win) {
3885 /* ungrab pointer if it was grabbed */
3886 if (win->_winArgs & RGFW_HOLD_MOUSE)
3887 XUngrabPointer(win->src.display, CurrentTime);
3888
3889 assert(win != NULL);
3890#ifdef RGFW_EGL
3891 RGFW_closeEGL(win);
3892#endif
3893
3894#if defined(RGFW_OSMESA) || defined(RGFW_BUFFER)
3895 if (win->buffer != NULL) {
3896 XDestroyImage((XImage*) win->src.bitmap);
3897 XFreeGC(win->src.display, win->src.gc);
3898 }
3899#endif
3900
3901 if ((Display*) win->src.display) {
3902#ifdef RGFW_OPENGL
3903 glXDestroyContext((Display*) win->src.display, win->src.ctx);
3904#endif
3905
3906 if (win == RGFW_root)
3907 RGFW_root = NULL;
3908
3909 if ((Drawable) win->src.window)
3910 XDestroyWindow((Display*) win->src.display, (Drawable) win->src.window); /*!< close the window*/
3911
3912 XCloseDisplay((Display*) win->src.display); /*!< kill the display*/
3913 }
3914
3915#ifdef RGFW_ALLOC_DROPFILES
3916 {
3917 u32 i;
3918 for (i = 0; i < RGFW_MAX_DROPS; i++)
3919 RGFW_FREE(win->event.droppedFiles[i]);
3920
3921
3922 RGFW_FREE(win->event.droppedFiles);
3923 }
3924#endif
3925
3926 RGFW_windowsOpen--;
3927#if !defined(RGFW_NO_X11_CURSOR_PRELOAD) && !defined(RGFW_NO_X11_CURSOR)
3928 if (X11Cursorhandle != NULL && RGFW_windowsOpen <= 0) {
3929 dlclose(X11Cursorhandle);
3930
3931 X11Cursorhandle = NULL;
3932 }
3933#endif
3934#if !defined(RGFW_NO_X11_XI_PRELOAD)
3935 if (X11Xihandle != NULL && RGFW_windowsOpen <= 0) {
3936 dlclose(X11Xihandle);
3937
3938 X11Xihandle = NULL;
3939 }
3940#endif
3941
3942 if (RGFW_libxshape != NULL && RGFW_windowsOpen <= 0) {
3943 dlclose(RGFW_libxshape);
3944 RGFW_libxshape = NULL;
3945 }
3946
3947 if (RGFW_windowsOpen <= 0) {
3948 if (RGFW_eventWait_forceStop[0] || RGFW_eventWait_forceStop[1]){
3949 close(RGFW_eventWait_forceStop[0]);
3950 close(RGFW_eventWait_forceStop[1]);
3951 }
3952
3953 u8 i;
3954 for (i = 0; i < RGFW_joystickCount; i++)
3955 close(RGFW_joysticks[i]);
3956 }
3957
3958 /* set cleared display / window to NULL for error checking */
3959 win->src.display = (Display*) 0;
3960 win->src.window = (Window) 0;
3961
3962 RGFW_FREE(win); /*!< free collected window data */
3963 }
3964
3965
3966/*
3967 End of X11 linux / unix defines
3968*/
3969
3970#endif /* RGFW_X11 */
3971
3972
3973/* wayland or X11 defines*/
3974#if defined(RGFW_WAYLAND) || defined(RGFW_X11)
3975#include <fcntl.h>
3976#include <poll.h>
3977#include <unistd.h>
3978 u16 RGFW_registerJoystickF(RGFW_window* win, char* file) {
3979 assert(win != NULL);
3980
3981#ifdef __linux__
3982
3983 i32 js = open(file, O_RDONLY);
3984
3985 if (js && RGFW_joystickCount < 4) {
3986 RGFW_joystickCount++;
3987
3988 RGFW_joysticks[RGFW_joystickCount - 1] = open(file, O_RDONLY);
3989
3990 u8 i;
3991 for (i = 0; i < 16; i++)
3992 RGFW_jsPressed[RGFW_joystickCount - 1][i] = 0;
3993
3994 }
3995
3996 else {
3997#ifdef RGFW_PRINT_ERRORS
3998 RGFW_error = 1;
3999 fprintf(stderr, "Error RGFW_registerJoystickF : Cannot open file %s\n", file);
4000#endif
4001 }
4002
4003 return RGFW_joystickCount - 1;
4004#endif
4005 }
4006
4007 u16 RGFW_registerJoystick(RGFW_window* win, i32 jsNumber) {
4008 assert(win != NULL);
4009
4010#ifdef __linux__
4011 char file[15];
4012 sprintf(file, "/dev/input/js%i", jsNumber);
4013
4014 return RGFW_registerJoystickF(win, file);
4015#endif
4016 }
4017
4018 void RGFW_stopCheckEvents(void) {
4019 RGFW_eventWait_forceStop[2] = 1;
4020 while (1) {
4021 const char byte = 0;
4022 const ssize_t result = write(RGFW_eventWait_forceStop[1], &byte, 1);
4023 if (result == 1 || result == -1)
4024 break;
4025 }
4026 }
4027
4028 void RGFW_window_eventWait(RGFW_window* win, i32 waitMS) {
4029 if (waitMS == 0)
4030 return;
4031
4032 u8 i;
4033
4034 if (RGFW_eventWait_forceStop[0] == 0 || RGFW_eventWait_forceStop[1] == 0) {
4035 if (pipe(RGFW_eventWait_forceStop) != -1) {
4036 fcntl(RGFW_eventWait_forceStop[0], F_GETFL, 0);
4037 fcntl(RGFW_eventWait_forceStop[0], F_GETFD, 0);
4038 fcntl(RGFW_eventWait_forceStop[1], F_GETFL, 0);
4039 fcntl(RGFW_eventWait_forceStop[1], F_GETFD, 0);
4040 }
4041 }
4042
4043 struct pollfd fds[] = {
4044 #ifdef RGFW_WAYLAND
4045 { wl_display_get_fd(win->src.display), POLLIN, 0 },
4046 #else
4047 { ConnectionNumber(win->src.display), POLLIN, 0 },
4048 #endif
4049 { RGFW_eventWait_forceStop[0], POLLIN, 0 },
4050 #ifdef __linux__ /* blank space for 4 joystick files*/
4051 { -1, POLLIN, 0 }, {-1, POLLIN, 0 }, {-1, POLLIN, 0 }, {-1, POLLIN, 0}
4052 #endif
4053 };
4054
4055 u8 index = 2;
4056
4057 #if defined(__linux__)
4058 for (i = 0; i < RGFW_joystickCount; i++) {
4059 if (RGFW_joysticks[i] == 0)
4060 continue;
4061
4062 fds[index].fd = RGFW_joysticks[i];
4063 index++;
4064 }
4065 #endif
4066
4067
4068 u64 start = RGFW_getTimeNS();
4069
4070 #ifdef RGFW_WAYLAND
4071 while (wl_display_dispatch(win->src.display) <= 0 && waitMS >= -1) {
4072 #else
4073 while (XPending(win->src.display) == 0 && waitMS >= -1) {
4074 #endif
4075 if (poll(fds, index, waitMS) <= 0)
4076 break;
4077
4078 if (waitMS > 0) {
4079 waitMS -= (RGFW_getTimeNS() - start) / 1e+6;
4080 }
4081 }
4082
4083 /* drain any data in the stop request */
4084 if (RGFW_eventWait_forceStop[2]) {
4085 char data[64];
4086 (void)!read(RGFW_eventWait_forceStop[0], data, sizeof(data));
4087
4088 RGFW_eventWait_forceStop[2] = 0;
4089 }
4090 }
4091
4092 u64 RGFW_getTimeNS(void) {
4093 struct timespec ts = { 0 };
4094 clock_gettime(1, &ts);
4095 unsigned long long int nanoSeconds = (unsigned long long int)ts.tv_sec*1000000000LLU + (unsigned long long int)ts.tv_nsec;
4096
4097 return nanoSeconds;
4098 }
4099
4100 u64 RGFW_getTime(void) {
4101 struct timespec ts = { 0 };
4102 clock_gettime(1, &ts);
4103 unsigned long long int nanoSeconds = (unsigned long long int)ts.tv_sec*1000000000LLU + (unsigned long long int)ts.tv_nsec;
4104
4105 return (double)(nanoSeconds) * 1e-9;
4106 }
4107#endif /* end of wayland or X11 time defines*/
4108
4109
4110/*
4111
4112 Start of Wayland defines
4113
4114
4115*/
4116
4117#ifdef RGFW_WAYLAND
4118/*
4119Wayland TODO:
4120- fix RGFW_keyPressed lock state
4121
4122 RGFW_windowMoved, the window was moved (by the user)
4123 RGFW_windowResized the window was resized (by the user), [on webASM this means the browser was resized]
4124 RGFW_windowRefresh The window content needs to be refreshed
4125
4126 RGFW_dnd a file has been dropped into the window
4127 RGFW_dnd_init
4128
4129- window args:
4130 #define RGFW_NO_RESIZE the window cannot be resized by the user
4131 #define RGFW_ALLOW_DND the window supports drag and drop
4132 #define RGFW_SCALE_TO_MONITOR scale the window to the screen
4133
4134- other missing functions functions ("TODO wayland") (~30 functions)
4135- fix buffer rendering weird behavior
4136*/
4137 #include <errno.h>
4138 #include <unistd.h>
4139 #include <sys/mman.h>
4140 #include <xkbcommon/xkbcommon.h>
4141 #include <xkbcommon/xkbcommon-keysyms.h>
4142 #include <dirent.h>
4143 #include <linux/kd.h>
4144 #include <wayland-cursor.h>
4145
4146RGFW_window* RGFW_key_win = NULL;
4147
4148void RGFW_eventPipe_push(RGFW_window* win, RGFW_Event event) {
4149 if (win == NULL) {
4150 win = RGFW_key_win;
4151
4152 if (win == NULL) return;
4153 }
4154
4155 if (win->src.eventLen >= (i32)(sizeof(win->src.events) / sizeof(win->src.events[0])))
4156 return;
4157
4158 win->src.events[win->src.eventLen] = event;
4159 win->src.eventLen += 1;
4160}
4161
4162RGFW_Event RGFW_eventPipe_pop(RGFW_window* win) {
4163 RGFW_Event ev;
4164 ev.type = 0;
4165
4166 if (win->src.eventLen > -1)
4167 win->src.eventLen -= 1;
4168
4169 if (win->src.eventLen >= 0)
4170 ev = win->src.events[win->src.eventLen];
4171
4172 return ev;
4173}
4174
4175/* wayland global garbage (wayland bad, X11 is fine (ish) (not really)) */
4176#include "xdg-shell.h"
4177#include "xdg-decoration-unstable-v1.h"
4178
4179struct xdg_wm_base *xdg_wm_base;
4180struct wl_compositor* RGFW_compositor = NULL;
4181struct wl_shm* shm = NULL;
4182struct wl_shell* RGFW_shell = NULL;
4183static struct wl_seat *seat = NULL;
4184static struct xkb_context *xkb_context;
4185static struct xkb_keymap *keymap = NULL;
4186static struct xkb_state *xkb_state = NULL;
4187enum zxdg_toplevel_decoration_v1_mode client_preferred_mode, RGFW_current_mode;
4188static struct zxdg_decoration_manager_v1 *decoration_manager = NULL;
4189
4190struct wl_cursor_theme* RGFW_wl_cursor_theme = NULL;
4191struct wl_surface* RGFW_cursor_surface = NULL;
4192struct wl_cursor_image* RGFW_cursor_image = NULL;
4193
4194static void xdg_wm_base_ping_handler(void *data,
4195 struct xdg_wm_base *wm_base, uint32_t serial)
4196{
4197 RGFW_UNUSED(data);
4198 xdg_wm_base_pong(wm_base, serial);
4199}
4200
4201static const struct xdg_wm_base_listener xdg_wm_base_listener = {
4202 .ping = xdg_wm_base_ping_handler,
4203};
4204
4205b8 RGFW_wl_configured = 0;
4206
4207static void xdg_surface_configure_handler(void *data,
4208 struct xdg_surface *xdg_surface, uint32_t serial)
4209{
4210 RGFW_UNUSED(data);
4211 xdg_surface_ack_configure(xdg_surface, serial);
4212 #ifdef RGFW_DEBUG
4213 printf("Surface configured\n");
4214 #endif
4215 RGFW_wl_configured = 1;
4216}
4217
4218static const struct xdg_surface_listener xdg_surface_listener = {
4219 .configure = xdg_surface_configure_handler,
4220};
4221
4222static void xdg_toplevel_configure_handler(void *data,
4223 struct xdg_toplevel *toplevel, int32_t width, int32_t height,
4224 struct wl_array *states)
4225{
4226 RGFW_UNUSED(data); RGFW_UNUSED(toplevel); RGFW_UNUSED(states)
4227 fprintf(stderr, "XDG toplevel configure: %dx%d\n", width, height);
4228}
4229
4230static void xdg_toplevel_close_handler(void *data,
4231 struct xdg_toplevel *toplevel)
4232{
4233 RGFW_UNUSED(data);
4234 RGFW_window* win = (RGFW_window*)xdg_toplevel_get_user_data(toplevel);
4235 if (win == NULL)
4236 win = RGFW_key_win;
4237
4238 RGFW_Event ev;
4239 ev.type = RGFW_quit;
4240
4241 RGFW_eventPipe_push(win, ev);
4242
4243 RGFW_windowQuitCallback(win);
4244}
4245
4246static void shm_format_handler(void *data,
4247 struct wl_shm *shm, uint32_t format)
4248{
4249 RGFW_UNUSED(data); RGFW_UNUSED(shm);
4250 fprintf(stderr, "Format %d\n", format);
4251}
4252
4253static const struct wl_shm_listener shm_listener = {
4254 .format = shm_format_handler,
4255};
4256
4257static const struct xdg_toplevel_listener xdg_toplevel_listener = {
4258 .configure = xdg_toplevel_configure_handler,
4259 .close = xdg_toplevel_close_handler,
4260};
4261
4262RGFW_window* RGFW_mouse_win = NULL;
4263
4264static void pointer_enter(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t surface_x, wl_fixed_t surface_y) {
4265 RGFW_UNUSED(data); RGFW_UNUSED(pointer); RGFW_UNUSED(serial); RGFW_UNUSED(surface_x); RGFW_UNUSED(surface_y);
4266 RGFW_window* win = (RGFW_window*)wl_surface_get_user_data(surface);
4267 RGFW_mouse_win = win;
4268
4269 RGFW_Event ev;
4270 ev.type = RGFW_mouseEnter;
4271 ev.point = win->event.point;
4272
4273 RGFW_eventPipe_push(win, ev);
4274
4275 RGFW_mouseNotifyCallBack(win, win->event.point, RGFW_TRUE);
4276}
4277static void pointer_leave(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface) {
4278 RGFW_UNUSED(data); RGFW_UNUSED(pointer); RGFW_UNUSED(serial); RGFW_UNUSED(surface);
4279 RGFW_window* win = (RGFW_window*)wl_surface_get_user_data(surface);
4280 if (RGFW_mouse_win == win)
4281 RGFW_mouse_win = NULL;
4282
4283 RGFW_Event ev;
4284 ev.type = RGFW_mouseLeave;
4285 ev.point = win->event.point;
4286 RGFW_eventPipe_push(win, ev);
4287
4288 RGFW_mouseNotifyCallBack(win, win->event.point, RGFW_FALSE);
4289}
4290static void pointer_motion(void *data, struct wl_pointer *pointer, uint32_t time, wl_fixed_t x, wl_fixed_t y) {
4291 RGFW_UNUSED(data); RGFW_UNUSED(pointer); RGFW_UNUSED(time); RGFW_UNUSED(x); RGFW_UNUSED(y);
4292
4293 assert(RGFW_mouse_win != NULL);
4294
4295 RGFW_Event ev;
4296 ev.type = RGFW_mousePosChanged;
4297 ev.point = RGFW_POINT(wl_fixed_to_double(x), wl_fixed_to_double(y));
4298 RGFW_eventPipe_push(RGFW_mouse_win, ev);
4299
4300 RGFW_mousePosCallback(RGFW_mouse_win, RGFW_POINT(wl_fixed_to_double(x), wl_fixed_to_double(y)));
4301}
4302static void pointer_button(void *data, struct wl_pointer *pointer, uint32_t serial, uint32_t time, uint32_t button, uint32_t state) {
4303 RGFW_UNUSED(data); RGFW_UNUSED(pointer); RGFW_UNUSED(time); RGFW_UNUSED(serial);
4304 assert(RGFW_mouse_win != NULL);
4305
4306 u32 b = (button - 0x110) + 1;
4307
4308 /* flip right and middle button codes */
4309 if (b == 2) b = 3;
4310 else if (b == 3) b = 2;
4311
4312 RGFW_mouseButtons[b].prev = RGFW_mouseButtons[b].current;
4313 RGFW_mouseButtons[b].current = state;
4314
4315 RGFW_Event ev;
4316 ev.type = RGFW_mouseButtonPressed + state;
4317 ev.button = b;
4318 RGFW_eventPipe_push(RGFW_mouse_win, ev);
4319
4320 RGFW_mouseButtonCallback(RGFW_mouse_win, b, 0, state);
4321}
4322static void pointer_axis(void *data, struct wl_pointer *pointer, uint32_t time, uint32_t axis, wl_fixed_t value) {
4323 RGFW_UNUSED(data); RGFW_UNUSED(pointer); RGFW_UNUSED(time); RGFW_UNUSED(axis);
4324 assert(RGFW_mouse_win != NULL);
4325
4326 double scroll = wl_fixed_to_double(value);
4327
4328 RGFW_Event ev;
4329 ev.type = RGFW_mouseButtonPressed;
4330 ev.button = RGFW_mouseScrollUp + (scroll < 0);
4331 RGFW_eventPipe_push(RGFW_mouse_win, ev);
4332
4333 RGFW_mouseButtonCallback(RGFW_mouse_win, RGFW_mouseScrollUp + (scroll < 0), scroll, 1);
4334}
4335
4336void RGFW_doNothing(void) { }
4337static struct wl_pointer_listener pointer_listener = (struct wl_pointer_listener){&pointer_enter, &pointer_leave, &pointer_motion, &pointer_button, &pointer_axis, (void*)&RGFW_doNothing, (void*)&RGFW_doNothing, (void*)&RGFW_doNothing, (void*)&RGFW_doNothing, (void*)&RGFW_doNothing, (void*)&RGFW_doNothing};
4338
4339static void keyboard_keymap (void *data, struct wl_keyboard *keyboard, uint32_t format, int32_t fd, uint32_t size) {
4340 RGFW_UNUSED(data); RGFW_UNUSED(keyboard); RGFW_UNUSED(format);
4341
4342 char *keymap_string = mmap (NULL, size, PROT_READ, MAP_SHARED, fd, 0);
4343 xkb_keymap_unref (keymap);
4344 keymap = xkb_keymap_new_from_string (xkb_context, keymap_string, XKB_KEYMAP_FORMAT_TEXT_V1, XKB_KEYMAP_COMPILE_NO_FLAGS);
4345
4346 munmap (keymap_string, size);
4347 close (fd);
4348 xkb_state_unref (xkb_state);
4349 xkb_state = xkb_state_new (keymap);
4350}
4351static void keyboard_enter (void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface, struct wl_array *keys) {
4352 RGFW_UNUSED(data); RGFW_UNUSED(keyboard); RGFW_UNUSED(serial); RGFW_UNUSED(keys);
4353
4354 RGFW_key_win = (RGFW_window*)wl_surface_get_user_data(surface);
4355
4356 RGFW_Event ev;
4357 ev.type = RGFW_focusIn;
4358 ev.inFocus = RGFW_TRUE;
4359 RGFW_key_win->event.inFocus = RGFW_TRUE;
4360
4361 RGFW_eventPipe_push((RGFW_window*)RGFW_mouse_win, ev);
4362
4363 RGFW_focusCallback(RGFW_key_win, RGFW_TRUE);
4364}
4365static void keyboard_leave (void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface) {
4366 RGFW_UNUSED(data); RGFW_UNUSED(keyboard); RGFW_UNUSED(serial);
4367
4368 RGFW_window* win = (RGFW_window*)wl_surface_get_user_data(surface);
4369 if (RGFW_key_win == win)
4370 RGFW_key_win = NULL;
4371
4372 RGFW_Event ev;
4373 ev.type = RGFW_focusOut;
4374 ev.inFocus = RGFW_FALSE;
4375 win->event.inFocus = RGFW_FALSE;
4376 RGFW_eventPipe_push(win, ev);
4377
4378 RGFW_focusCallback(win, RGFW_FALSE);
4379}
4380static void keyboard_key (void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key, uint32_t state) {
4381 RGFW_UNUSED(data); RGFW_UNUSED(keyboard); RGFW_UNUSED(serial); RGFW_UNUSED(time);
4382
4383 assert(RGFW_key_win != NULL);
4384
4385 xkb_keysym_t keysym = xkb_state_key_get_one_sym (xkb_state, key+8);
4386 char name[16];
4387 xkb_keysym_get_name(keysym, name, 16);
4388
4389 u32 RGFW_key = RGFW_apiKeyCodeToRGFW(key);
4390 RGFW_keyboard[RGFW_key].prev = RGFW_keyboard[RGFW_key].current;
4391 RGFW_keyboard[RGFW_key].current = state;
4392 RGFW_Event ev;
4393 ev.type = RGFW_keyPressed + state;
4394 ev.keyCode = RGFW_key;
4395 strcpy(ev.keyName, name);
4396 ev.repeat = RGFW_isHeld(RGFW_key_win, RGFW_key);
4397 RGFW_eventPipe_push(RGFW_key_win, ev);
4398
4399 RGFW_updateLockState(RGFW_key_win, xkb_keymap_mod_get_index(keymap, "Lock"), xkb_keymap_mod_get_index(keymap, "Mod2"));
4400
4401 RGFW_keyCallback(RGFW_key_win, RGFW_key, name, RGFW_key_win->event.lockState, state);
4402}
4403static void keyboard_modifiers (void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed, uint32_t mods_latched, uint32_t mods_locked, uint32_t group) {
4404 RGFW_UNUSED(data); RGFW_UNUSED(keyboard); RGFW_UNUSED(serial); RGFW_UNUSED(time);
4405 xkb_state_update_mask (xkb_state, mods_depressed, mods_latched, mods_locked, 0, 0, group);
4406}
4407static struct wl_keyboard_listener keyboard_listener = {&keyboard_keymap, &keyboard_enter, &keyboard_leave, &keyboard_key, &keyboard_modifiers, (void*)&RGFW_doNothing};
4408
4409static void seat_capabilities (void *data, struct wl_seat *seat, uint32_t capabilities) {
4410 RGFW_UNUSED(data);
4411
4412 if (capabilities & WL_SEAT_CAPABILITY_POINTER) {
4413 struct wl_pointer *pointer = wl_seat_get_pointer (seat);
4414 wl_pointer_add_listener (pointer, &pointer_listener, NULL);
4415 }
4416 if (capabilities & WL_SEAT_CAPABILITY_KEYBOARD) {
4417 struct wl_keyboard *keyboard = wl_seat_get_keyboard (seat);
4418 wl_keyboard_add_listener (keyboard, &keyboard_listener, NULL);
4419 }
4420}
4421static struct wl_seat_listener seat_listener = {&seat_capabilities, (void*)&RGFW_doNothing};
4422
4423static void wl_global_registry_handler(void *data,
4424 struct wl_registry *registry, uint32_t id, const char *interface,
4425 uint32_t version)
4426{
4427 RGFW_UNUSED(data); RGFW_UNUSED(version);
4428
4429 if (strcmp(interface, "wl_compositor") == 0) {
4430 RGFW_compositor = wl_registry_bind(registry,
4431 id, &wl_compositor_interface, 4);
4432 } else if (strcmp(interface, "xdg_wm_base") == 0) {
4433 xdg_wm_base = wl_registry_bind(registry,
4434 id, &xdg_wm_base_interface, 1);
4435 } else if (strcmp(interface, zxdg_decoration_manager_v1_interface.name) == 0) {
4436 decoration_manager = wl_registry_bind(registry, id, &zxdg_decoration_manager_v1_interface, 1);
4437 } else if (strcmp(interface, "wl_shm") == 0) {
4438 shm = wl_registry_bind(registry,
4439 id, &wl_shm_interface, 1);
4440 wl_shm_add_listener(shm, &shm_listener, NULL);
4441 } else if (strcmp(interface,"wl_seat") == 0) {
4442 seat = wl_registry_bind(registry, id, &wl_seat_interface, 1);
4443 wl_seat_add_listener(seat, &seat_listener, NULL);
4444 }
4445
4446 else {
4447 #ifdef RGFW_DEBUG
4448 printf("did not register %s\n", interface);
4449 return;
4450 #endif
4451 }
4452
4453 #ifdef RGFW_DEBUG
4454 printf("registered %s\n", interface);
4455 #endif
4456}
4457
4458static void wl_global_registry_remove(void *data, struct wl_registry *registry, uint32_t name) { RGFW_UNUSED(data); RGFW_UNUSED(registry); RGFW_UNUSED(name); }
4459static const struct wl_registry_listener registry_listener = {
4460 .global = wl_global_registry_handler,
4461 .global_remove = wl_global_registry_remove,
4462};
4463
4464static const char *get_mode_name(enum zxdg_toplevel_decoration_v1_mode mode) {
4465 switch (mode) {
4466 case ZXDG_TOPLEVEL_DECORATION_V1_MODE_CLIENT_SIDE:
4467 return "client-side decorations";
4468 case ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE:
4469 return "server-side decorations";
4470 }
4471 abort();
4472}
4473
4474
4475static void decoration_handle_configure(void *data,
4476 struct zxdg_toplevel_decoration_v1 *decoration,
4477 enum zxdg_toplevel_decoration_v1_mode mode) {
4478 RGFW_UNUSED(data); RGFW_UNUSED(decoration);
4479 printf("Using %s\n", get_mode_name(mode));
4480 RGFW_current_mode = mode;
4481}
4482
4483static const struct zxdg_toplevel_decoration_v1_listener decoration_listener = {
4484 .configure = decoration_handle_configure,
4485};
4486
4487static void randname(char *buf) {
4488 struct timespec ts;
4489 clock_gettime(CLOCK_REALTIME, &ts);
4490 long r = ts.tv_nsec;
4491 for (int i = 0; i < 6; ++i) {
4492 buf[i] = 'A'+(r&15)+(r&16)*2;
4493 r >>= 5;
4494 }
4495}
4496
4497static int anonymous_shm_open(void) {
4498 char name[] = "/RGFW-wayland-XXXXXX";
4499 int retries = 100;
4500
4501 do {
4502 randname(name + strlen(name) - 6);
4503
4504 --retries;
4505 // shm_open guarantees that O_CLOEXEC is set
4506 int fd = shm_open(name, O_RDWR | O_CREAT | O_EXCL, 0600);
4507 if (fd >= 0) {
4508 shm_unlink(name);
4509 return fd;
4510 }
4511 } while (retries > 0 && errno == EEXIST);
4512
4513 return -1;
4514}
4515
4516int create_shm_file(off_t size) {
4517 int fd = anonymous_shm_open();
4518 if (fd < 0) {
4519 return fd;
4520 }
4521
4522 if (ftruncate(fd, size) < 0) {
4523 close(fd);
4524 return -1;
4525 }
4526
4527 return fd;
4528}
4529
4530static void wl_surface_frame_done(void *data, struct wl_callback *cb, uint32_t time) {
4531 #ifdef RGFW_BUFFER
4532 RGFW_window* win = (RGFW_window*)data;
4533 if ((win->_winArgs & RGFW_NO_CPU_RENDER))
4534 return;
4535
4536 #ifndef RGFW_X11_DONT_CONVERT_BGR
4537 u32 x, y;
4538 for (y = 0; y < (u32)win->r.h; y++) {
4539 for (x = 0; x < (u32)win->r.w; x++) {
4540 u32 index = (y * 4 * win->r.w) + x * 4;
4541
4542 u8 red = win->buffer[index];
4543 win->buffer[index] = win->buffer[index + 2];
4544 win->buffer[index + 2] = red;
4545
4546 }
4547 }
4548 #endif
4549
4550 wl_surface_attach(win->src.surface, win->src.wl_buffer, 0, 0);
4551 wl_surface_damage_buffer(win->src.surface, 0, 0, win->r.w, win->r.h);
4552 wl_surface_commit(win->src.surface);
4553 #endif
4554}
4555
4556static const struct wl_callback_listener wl_surface_frame_listener = {
4557 .done = wl_surface_frame_done,
4558};
4559
4560
4561 /* normal wayland RGFW stuff */
4562
4563 RGFW_area RGFW_getScreenSize(void) {
4564 RGFW_area area = {};
4565
4566 if (RGFW_root != NULL)
4567 /* this isn't right but it's here for buffers */
4568 area = RGFW_AREA(RGFW_root->r.w, RGFW_root->r.h);
4569
4570 /* TODO wayland */
4571 return area;
4572 }
4573
4574 void RGFW_releaseCursor(RGFW_window* win) {
4575 RGFW_UNUSED(win);
4576 }
4577
4578 void RGFW_captureCursor(RGFW_window* win, RGFW_rect r) {
4579 RGFW_UNUSED(win); RGFW_UNUSED(r);
4580
4581 /* TODO wayland */
4582 }
4583
4584
4585 RGFWDEF void RGFW_init_buffer(RGFW_window* win);
4586 void RGFW_init_buffer(RGFW_window* win) {
4587 #if defined(RGFW_OSMESA) || defined(RGFW_BUFFER)
4588 size_t size = win->r.w * win->r.h * 4;
4589 int fd = create_shm_file(size);
4590 if (fd < 0) {
4591 fprintf(stderr, "Failed to create a buffer. size: %ld\n", size);
4592 exit(1);
4593 }
4594
4595 win->buffer = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
4596 if (win->buffer == MAP_FAILED) {
4597 fprintf(stderr, "mmap failed!\n");
4598 close(fd);
4599 exit(1);
4600 }
4601
4602 struct wl_shm_pool* pool = wl_shm_create_pool(shm, fd, size);
4603 win->src.wl_buffer = wl_shm_pool_create_buffer(pool, 0, win->r.w, win->r.h, win->r.w * 4,
4604 WL_SHM_FORMAT_ARGB8888);
4605 wl_shm_pool_destroy(pool);
4606
4607 close(fd);
4608
4609 wl_surface_attach(win->src.surface, win->src.wl_buffer, 0, 0);
4610 wl_surface_commit(win->src.surface);
4611
4612 u8 color[] = {0x00, 0x00, 0x00, 0xFF};
4613
4614 size_t i;
4615 for (i = 0; i < size; i += 4) {
4616 memcpy(&win->buffer[i], color, 4);
4617 }
4618
4619 #if defined(RGFW_OSMESA)
4620 win->src.ctx = OSMesaCreateContext(OSMESA_RGBA, NULL);
4621 OSMesaMakeCurrent(win->src.ctx, win->buffer, GL_UNSIGNED_BYTE, win->r.w, win->r.h);
4622 #endif
4623 #else
4624 RGFW_UNUSED(win);
4625 #endif
4626 }
4627
4628
4629 RGFW_window* RGFW_createWindow(const char* name, RGFW_rect rect, u16 args) {
4630 RGFW_window* win = RGFW_window_basic_init(rect, args);
4631
4632 fprintf(stderr, "Warning: RGFW Wayland support is experimental\n");
4633
4634 win->src.display = wl_display_connect(NULL);
4635 if (win->src.display == NULL) {
4636 #ifdef RGFW_DEBUG
4637 fprintf(stderr, "Failed to load Wayland display\n");
4638 #endif
4639 return NULL;
4640 }
4641
4642 struct wl_registry *registry = wl_display_get_registry(win->src.display);
4643 wl_registry_add_listener(registry, &registry_listener, NULL);
4644
4645 wl_display_dispatch(win->src.display);
4646 wl_display_roundtrip(win->src.display);
4647
4648 if (RGFW_compositor == NULL) {
4649 #ifdef RGFW_DEBUG
4650 fprintf(stderr, "Can't find compositor.\n");
4651 #endif
4652
4653 return NULL;
4654 }
4655
4656 if (RGFW_wl_cursor_theme == NULL) {
4657 RGFW_wl_cursor_theme = wl_cursor_theme_load(NULL, 24, shm);
4658 RGFW_cursor_surface = wl_compositor_create_surface(RGFW_compositor);
4659
4660 struct wl_cursor* cursor = wl_cursor_theme_get_cursor(RGFW_wl_cursor_theme, "left_ptr");
4661 RGFW_cursor_image = cursor->images[0];
4662 struct wl_buffer* cursor_buffer = wl_cursor_image_get_buffer(RGFW_cursor_image);
4663
4664 wl_surface_attach(RGFW_cursor_surface, cursor_buffer, 0, 0);
4665 wl_surface_commit(RGFW_cursor_surface);
4666 }
4667
4668 if (RGFW_root == NULL)
4669 xdg_wm_base_add_listener(xdg_wm_base, &xdg_wm_base_listener, NULL);
4670
4671 xkb_context = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
4672
4673 win->src.surface = wl_compositor_create_surface(RGFW_compositor);
4674 wl_surface_set_user_data(win->src.surface, win);
4675
4676 win->src.xdg_surface = xdg_wm_base_get_xdg_surface(xdg_wm_base, win->src.surface);
4677 xdg_surface_add_listener(win->src.xdg_surface, &xdg_surface_listener, NULL);
4678
4679 xdg_wm_base_set_user_data(xdg_wm_base, win);
4680
4681 win->src.xdg_toplevel = xdg_surface_get_toplevel(win->src.xdg_surface);
4682 xdg_toplevel_set_user_data(win->src.xdg_toplevel, win);
4683 xdg_toplevel_set_title(win->src.xdg_toplevel, name);
4684 xdg_toplevel_add_listener(win->src.xdg_toplevel, &xdg_toplevel_listener, NULL);
4685
4686 xdg_surface_set_window_geometry(win->src.xdg_surface, 0, 0, win->r.w, win->r.h);
4687
4688 if (!(args & RGFW_NO_BORDER)) {
4689 win->src.decoration = zxdg_decoration_manager_v1_get_toplevel_decoration(
4690 decoration_manager, win->src.xdg_toplevel);
4691 }
4692
4693 if (args & RGFW_CENTER) {
4694 RGFW_area screenR = RGFW_getScreenSize();
4695 RGFW_window_move(win, RGFW_POINT((screenR.w - win->r.w) / 2, (screenR.h - win->r.h) / 2));
4696 }
4697
4698 if (args & RGFW_OPENGL_SOFTWARE)
4699 setenv("LIBGL_ALWAYS_SOFTWARE", "1", 1);
4700
4701 wl_display_roundtrip(win->src.display);
4702
4703 wl_surface_commit(win->src.surface);
4704
4705 /* wait for the surface to be configured */
4706 while (wl_display_dispatch(win->src.display) != -1 && !RGFW_wl_configured) { }
4707
4708
4709 #ifdef RGFW_OPENGL
4710 if ((args & RGFW_NO_INIT_API) == 0) {
4711 win->src.window = wl_egl_window_create(win->src.surface, win->r.w, win->r.h);
4712 RGFW_createOpenGLContext(win);
4713 }
4714 #endif
4715
4716 RGFW_init_buffer(win);
4717
4718 struct wl_callback* callback = wl_surface_frame(win->src.surface);
4719 wl_callback_add_listener(callback, &wl_surface_frame_listener, win);
4720 wl_surface_commit(win->src.surface);
4721
4722 if (args & RGFW_HIDE_MOUSE) {
4723 RGFW_window_showMouse(win, 0);
4724 }
4725
4726 if (RGFW_root == NULL) {
4727 RGFW_root = win;
4728 }
4729
4730 win->src.eventIndex = 0;
4731 win->src.eventLen = 0;
4732
4733 return win;
4734 }
4735
4736 RGFW_Event* RGFW_window_checkEvent(RGFW_window* win) {
4737 if (win->_winArgs & RGFW_WINDOW_HIDE)
4738 return NULL;
4739
4740 if (win->src.eventIndex == 0) {
4741 if (wl_display_roundtrip(win->src.display) == -1) {
4742 return NULL;
4743 }
4744 RGFW_resetKey();
4745 }
4746
4747 #ifdef __linux__
4748 RGFW_Event* event = RGFW_linux_updateJoystick(win);
4749 if (event != NULL)
4750 return event;
4751 #endif
4752
4753 if (win->src.eventLen == 0) {
4754 return NULL;
4755 }
4756
4757 RGFW_Event ev = RGFW_eventPipe_pop(win);
4758
4759 if (ev.type == 0 || win->event.type == RGFW_quit) {
4760 return NULL;
4761 }
4762
4763 ev.frameTime = win->event.frameTime;
4764 ev.frameTime2 = win->event.frameTime2;
4765 ev.inFocus = win->event.inFocus;
4766 win->event = ev;
4767
4768 return &win->event;
4769 }
4770
4771
4772 void RGFW_window_resize(RGFW_window* win, RGFW_area a) {
4773 RGFW_UNUSED(win); RGFW_UNUSED(a);
4774
4775 /* TODO wayland */
4776 }
4777
4778 void RGFW_window_move(RGFW_window* win, RGFW_point v) {
4779 RGFW_UNUSED(win); RGFW_UNUSED(v);
4780
4781 /* TODO wayland */
4782 }
4783
4784 void RGFW_window_setIcon(RGFW_window* win, u8* src, RGFW_area a, i32 channels) {
4785 RGFW_UNUSED(win); RGFW_UNUSED(src); RGFW_UNUSED(a); RGFW_UNUSED(channels)
4786 /* TODO wayland */
4787 }
4788
4789 void RGFW_window_moveMouse(RGFW_window* win, RGFW_point v) {
4790 RGFW_UNUSED(win); RGFW_UNUSED(v);
4791
4792 /* TODO wayland */
4793 }
4794
4795 void RGFW_window_showMouse(RGFW_window* win, i8 show) {
4796 RGFW_UNUSED(win);
4797
4798 if (show) {
4799
4800 }
4801 else {
4802
4803 }
4804
4805 /* TODO wayland */
4806 }
4807
4808 b8 RGFW_window_isMaximized(RGFW_window* win) {
4809 RGFW_UNUSED(win);
4810 /* TODO wayland */
4811 return 0;
4812 }
4813
4814 b8 RGFW_window_isMinimized(RGFW_window* win) {
4815 RGFW_UNUSED(win);
4816 /* TODO wayland */
4817 return 0;
4818 }
4819
4820 b8 RGFW_window_isHidden(RGFW_window* win) {
4821 RGFW_UNUSED(win);
4822 /* TODO wayland */
4823 return 0;
4824 }
4825
4826 b8 RGFW_window_isFullscreen(RGFW_window* win) {
4827 RGFW_UNUSED(win);
4828 /* TODO wayland */
4829 return 0;
4830 }
4831
4832 RGFW_point RGFW_window_getMousePoint(RGFW_window* win) {
4833 RGFW_UNUSED(win);
4834 /* TODO wayland */
4835 return RGFW_POINT(0, 0);
4836 }
4837
4838 RGFW_point RGFW_getGlobalMousePoint(void) {
4839 /* TODO wayland */
4840 return RGFW_POINT(0, 0);
4841 }
4842
4843 void RGFW_window_show(RGFW_window* win) {
4844 //wl_surface_attach(win->src.surface, win->rc., 0, 0);
4845 wl_surface_commit(win->src.surface);
4846
4847 if (win->_winArgs & RGFW_WINDOW_HIDE)
4848 win->_winArgs ^= RGFW_WINDOW_HIDE;
4849 }
4850
4851 void RGFW_window_hide(RGFW_window* win) {
4852 wl_surface_attach(win->src.surface, NULL, 0, 0);
4853 wl_surface_commit(win->src.surface);
4854 win->_winArgs |= RGFW_WINDOW_HIDE;
4855 }
4856
4857 void RGFW_window_setMouseDefault(RGFW_window* win) {
4858 RGFW_UNUSED(win);
4859
4860 RGFW_window_setMouseStandard(win, RGFW_MOUSE_NORMAL);
4861 }
4862
4863 void RGFW_window_setMouseStandard(RGFW_window* win, u8 mouse) {
4864 RGFW_UNUSED(win);
4865
4866 static const char* iconStrings[] = { "left_ptr", "left_ptr", "text", "cross", "pointer", "e-resize", "n-resize", "nw-resize", "ne-resize", "all-resize", "not-allowed" };
4867
4868 struct wl_cursor* cursor = wl_cursor_theme_get_cursor(RGFW_wl_cursor_theme, iconStrings[mouse]);
4869 RGFW_cursor_image = cursor->images[0];
4870 struct wl_buffer* cursor_buffer = wl_cursor_image_get_buffer(RGFW_cursor_image);
4871
4872 wl_surface_attach(RGFW_cursor_surface, cursor_buffer, 0, 0);
4873 wl_surface_commit(RGFW_cursor_surface);
4874 }
4875
4876 void RGFW_window_setMouse(RGFW_window* win, u8* image, RGFW_area a, i32 channels) {
4877 RGFW_UNUSED(win); RGFW_UNUSED(image); RGFW_UNUSED(a); RGFW_UNUSED(channels)
4878 //struct wl_cursor* cursor = wl_cursor_theme_get_cursor(RGFW_wl_cursor_theme, iconStrings[mouse]);
4879 //RGFW_cursor_image = image;
4880 struct wl_buffer* cursor_buffer = wl_cursor_image_get_buffer(RGFW_cursor_image);
4881
4882 wl_surface_attach(RGFW_cursor_surface, cursor_buffer, 0, 0);
4883 wl_surface_commit(RGFW_cursor_surface);
4884 }
4885
4886 void RGFW_window_setName(RGFW_window* win, char* name) {
4887 xdg_toplevel_set_title(win->src.xdg_toplevel, name);
4888 }
4889
4890 void RGFW_window_setMousePassthrough(RGFW_window* win, b8 passthrough) {
4891 RGFW_UNUSED(win); RGFW_UNUSED(passthrough);
4892
4893 /* TODO wayland */
4894 }
4895
4896 void RGFW_window_setBorder(RGFW_window* win, b8 border) {
4897 RGFW_UNUSED(win); RGFW_UNUSED(border);
4898
4899 /* TODO wayland */
4900 }
4901
4902 void RGFW_window_restore(RGFW_window* win) {
4903 RGFW_UNUSED(win);
4904
4905 /* TODO wayland */
4906 }
4907
4908 void RGFW_window_minimize(RGFW_window* win) {
4909 RGFW_UNUSED(win);
4910
4911 /* TODO wayland */
4912 }
4913
4914 void RGFW_window_setMaxSize(RGFW_window* win, RGFW_area a) {
4915 RGFW_UNUSED(win); RGFW_UNUSED(a);
4916
4917 /* TODO wayland */
4918 }
4919
4920 void RGFW_window_setMinSize(RGFW_window* win, RGFW_area a) {
4921 RGFW_UNUSED(win); RGFW_UNUSED(a);
4922
4923 /* TODO wayland */
4924 }
4925
4926 RGFW_monitor RGFW_window_getMonitor(RGFW_window* win) {
4927 RGFW_monitor m = {};
4928 RGFW_UNUSED(win);
4929 RGFW_UNUSED(m);
4930 /* TODO wayland */
4931
4932 return m;
4933 }
4934
4935
4936 #ifndef RGFW_EGL
4937 void RGFW_window_swapInterval(RGFW_window* win, i32 swapInterval) { RGFW_UNUSED(win); RGFW_UNUSED(swapInterval); }
4938 #endif
4939
4940 void RGFW_window_swapBuffers(RGFW_window* win) {
4941 assert(win != NULL);
4942
4943 /* clear the window*/
4944 #ifdef RGFW_BUFFER
4945 wl_surface_frame_done(win, NULL, 0);
4946 if (!(win->_winArgs & RGFW_NO_GPU_RENDER))
4947 #endif
4948 {
4949 #ifdef RGFW_OPENGL
4950 eglSwapBuffers(win->src.EGL_display, win->src.EGL_surface);
4951 #endif
4952 }
4953
4954 wl_display_flush(win->src.display);
4955 }
4956
4957 void RGFW_window_close(RGFW_window* win) {
4958 #ifdef RGFW_EGL
4959 RGFW_closeEGL(win);
4960 #endif
4961
4962 if (RGFW_root == win) {
4963 RGFW_root = NULL;
4964 }
4965
4966 xdg_toplevel_destroy(win->src.xdg_toplevel);
4967 xdg_surface_destroy(win->src.xdg_surface);
4968 wl_surface_destroy(win->src.surface);
4969
4970 #ifdef RGFW_BUFFER
4971 wl_buffer_destroy(win->src.wl_buffer);
4972 #endif
4973
4974 wl_display_disconnect(win->src.display);
4975 RGFW_FREE(win);
4976 }
4977
4978 RGFW_monitor RGFW_getPrimaryMonitor(void) {
4979 /* TODO wayland */
4980
4981 return (RGFW_monitor){};
4982 }
4983
4984 RGFW_monitor* RGFW_getMonitors(void) {
4985 /* TODO wayland */
4986
4987 return NULL;
4988 }
4989
4990 void RGFW_writeClipboard(const char* text, u32 textLen) {
4991 RGFW_UNUSED(text); RGFW_UNUSED(textLen);
4992
4993 /* TODO wayland */
4994 }
4995
4996 char* RGFW_readClipboard(size_t* size) {
4997 RGFW_UNUSED(size);
4998
4999 /* TODO wayland */
5000
5001 return NULL;
5002 }
5003#endif /* RGFW_WAYLAND */
5004
5005/*
5006 End of Wayland defines
5007*/
5008
5009
5010/*
5011
5012 Start of Windows defines
5013
5014
5015*/
5016
5017#ifdef RGFW_WINDOWS
5018 #define WIN32_LEAN_AND_MEAN
5019 #define OEMRESOURCE
5020 #include <windows.h>
5021
5022 #include <processthreadsapi.h>
5023 #include <wchar.h>
5024 #include <locale.h>
5025 #include <windowsx.h>
5026 #include <shellapi.h>
5027 #include <shellscalingapi.h>
5028
5029 #include <winuser.h>
5030
5031 __declspec(dllimport) int __stdcall WideCharToMultiByte( UINT CodePage, DWORD dwFlags, const WCHAR* lpWideCharStr, int cchWideChar, LPSTR lpMultiByteStr, int cbMultiByte, LPCCH lpDefaultChar, LPBOOL lpUsedDefaultChar);
5032
5033 #ifndef RGFW_NO_XINPUT
5034 typedef DWORD (WINAPI * PFN_XInputGetState)(DWORD,XINPUT_STATE*);
5035 PFN_XInputGetState XInputGetStateSRC = NULL;
5036 #define XInputGetState XInputGetStateSRC
5037
5038 typedef DWORD (WINAPI * PFN_XInputGetKeystroke)(DWORD, DWORD, PXINPUT_KEYSTROKE);
5039 PFN_XInputGetKeystroke XInputGetKeystrokeSRC = NULL;
5040 #define XInputGetKeystroke XInputGetKeystrokeSRC
5041
5042 static HMODULE RGFW_XInput_dll = NULL;
5043 #endif
5044
5045 u32 RGFW_mouseIconSrc[] = {OCR_NORMAL, OCR_NORMAL, OCR_IBEAM, OCR_CROSS, OCR_HAND, OCR_SIZEWE, OCR_SIZENS, OCR_SIZENWSE, OCR_SIZENESW, OCR_SIZEALL, OCR_NO};
5046
5047 char* createUTF8FromWideStringWin32(const WCHAR* source);
5048
5049#define GL_FRONT 0x0404
5050#define GL_BACK 0x0405
5051#define GL_LEFT 0x0406
5052#define GL_RIGHT 0x0407
5053
5054#if defined(RGFW_OSMESA) && defined(RGFW_LINK_OSMESA)
5055
5056 typedef void (GLAPIENTRY* PFN_OSMesaDestroyContext)(OSMesaContext);
5057 typedef i32(GLAPIENTRY* PFN_OSMesaMakeCurrent)(OSMesaContext, void*, int, int, int);
5058 typedef OSMesaContext(GLAPIENTRY* PFN_OSMesaCreateContext)(GLenum, OSMesaContext);
5059
5060 PFN_OSMesaMakeCurrent OSMesaMakeCurrentSource;
5061 PFN_OSMesaCreateContext OSMesaCreateContextSource;
5062 PFN_OSMesaDestroyContext OSMesaDestroyContextSource;
5063
5064#define OSMesaCreateContext OSMesaCreateContextSource
5065#define OSMesaMakeCurrent OSMesaMakeCurrentSource
5066#define OSMesaDestroyContext OSMesaDestroyContextSource
5067#endif
5068
5069 typedef int (*PFN_wglGetSwapIntervalEXT)(void);
5070 PFN_wglGetSwapIntervalEXT wglGetSwapIntervalEXTSrc = NULL;
5071#define wglGetSwapIntervalEXT wglGetSwapIntervalEXTSrc
5072
5073
5074 void* RGFWjoystickApi = NULL;
5075
5076 /* these two wgl functions need to be preloaded */
5077 typedef HGLRC (WINAPI *PFNWGLCREATECONTEXTATTRIBSARBPROC)(HDC hdc, HGLRC hglrc, const int *attribList);
5078 PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = NULL;
5079
5080 /* defines for creating ARB attributes */
5081#define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
5082#define WGL_CONTEXT_MAJOR_VERSION_ARB 0x2091
5083#define WGL_CONTEXT_MINOR_VERSION_ARB 0x2092
5084#define WGL_DRAW_TO_WINDOW_ARB 0x2001
5085#define WGL_ACCELERATION_ARB 0x2003
5086#define WGL_NO_ACCELERATION_ARB 0x2025
5087#define WGL_DOUBLE_BUFFER_ARB 0x2011
5088#define WGL_COLOR_BITS_ARB 0x2014
5089#define WGL_RED_BITS_ARB 0x2015
5090#define WGL_RED_SHIFT_ARB 0x2016
5091#define WGL_GREEN_BITS_ARB 0x2017
5092#define WGL_GREEN_SHIFT_ARB 0x2018
5093#define WGL_BLUE_BITS_ARB 0x2019
5094#define WGL_BLUE_SHIFT_ARB 0x201a
5095#define WGL_ALPHA_BITS_ARB 0x201b
5096#define WGL_ALPHA_SHIFT_ARB 0x201c
5097#define WGL_ACCUM_BITS_ARB 0x201d
5098#define WGL_ACCUM_RED_BITS_ARB 0x201e
5099#define WGL_ACCUM_GREEN_BITS_ARB 0x201f
5100#define WGL_ACCUM_BLUE_BITS_ARB 0x2020
5101#define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
5102#define WGL_DEPTH_BITS_ARB 0x2022
5103#define WGL_AUX_BUFFERS_ARB 0x2024
5104#define WGL_STEREO_ARB 0x2012
5105#define WGL_DEPTH_BITS_ARB 0x2022
5106#define WGL_STENCIL_BITS_ARB 0x2023
5107#define WGL_FULL_ACCELERATION_ARB 0x2027
5108#define WGL_CONTEXT_FLAGS_ARB 0x2094
5109#define WGL_CONTEXT_PROFILE_MASK_ARB 0x9126
5110#define WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x00000002
5111#define WGL_SAMPLE_BUFFERS_ARB 0x2041
5112#define WGL_SAMPLES_ARB 0x2042
5113#define WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB 0x20a9
5114
5115#ifndef RGFW_EGL
5116static HMODULE wglinstance = NULL;
5117#endif
5118
5119#ifdef RGFW_WGL_LOAD
5120 typedef HGLRC(WINAPI* PFN_wglCreateContext)(HDC);
5121 typedef BOOL(WINAPI* PFN_wglDeleteContext)(HGLRC);
5122 typedef PROC(WINAPI* PFN_wglGetProcAddress)(LPCSTR);
5123 typedef BOOL(WINAPI* PFN_wglMakeCurrent)(HDC, HGLRC);
5124 typedef HDC(WINAPI* PFN_wglGetCurrentDC)();
5125 typedef HGLRC(WINAPI* PFN_wglGetCurrentContext)();
5126
5127 PFN_wglCreateContext wglCreateContextSRC;
5128 PFN_wglDeleteContext wglDeleteContextSRC;
5129 PFN_wglGetProcAddress wglGetProcAddressSRC;
5130 PFN_wglMakeCurrent wglMakeCurrentSRC;
5131 PFN_wglGetCurrentDC wglGetCurrentDCSRC;
5132 PFN_wglGetCurrentContext wglGetCurrentContextSRC;
5133
5134 #define wglCreateContext wglCreateContextSRC
5135 #define wglDeleteContext wglDeleteContextSRC
5136 #define wglGetProcAddress wglGetProcAddressSRC
5137 #define wglMakeCurrent wglMakeCurrentSRC
5138
5139 #define wglGetCurrentDC wglGetCurrentDCSRC
5140 #define wglGetCurrentContext wglGetCurrentContextSRC
5141#endif
5142
5143#ifdef RGFW_OPENGL
5144 void* RGFW_getProcAddress(const char* procname) {
5145 void* proc = (void*) wglGetProcAddress(procname);
5146 if (proc)
5147 return proc;
5148
5149 return (void*) GetProcAddress(wglinstance, procname);
5150 }
5151
5152 typedef HRESULT (APIENTRY* PFNWGLCHOOSEPIXELFORMATARBPROC)(HDC hdc, const int* piAttribIList, const FLOAT* pfAttribFList, UINT nMaxFormats, int* piFormats, UINT* nNumFormats);
5153 static PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = NULL;
5154#endif
5155
5156 RGFW_window RGFW_eventWindow;
5157
5158 LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
5159 switch (message) {
5160 case WM_MOVE:
5161 RGFW_eventWindow.r.x = LOWORD(lParam);
5162 RGFW_eventWindow.r.y = HIWORD(lParam);
5163 RGFW_eventWindow.src.window = hWnd;
5164 return DefWindowProcA(hWnd, message, wParam, lParam);
5165 case WM_SIZE:
5166 RGFW_eventWindow.r.w = LOWORD(lParam);
5167 RGFW_eventWindow.r.h = HIWORD(lParam);
5168 RGFW_eventWindow.src.window = hWnd;
5169 return DefWindowProcA(hWnd, message, wParam, lParam); // Call DefWindowProc after handling
5170 default:
5171 return DefWindowProcA(hWnd, message, wParam, lParam);
5172 }
5173 }
5174
5175 #ifndef RGFW_NO_DPI
5176 static HMODULE RGFW_Shcore_dll = NULL;
5177 typedef HRESULT (WINAPI * PFN_GetDpiForMonitor)(HMONITOR,MONITOR_DPI_TYPE,UINT*,UINT*);
5178 PFN_GetDpiForMonitor GetDpiForMonitorSRC = NULL;
5179 #define GetDpiForMonitor GetDpiForMonitorSRC
5180 #endif
5181
5182 __declspec(dllimport) u32 __stdcall timeBeginPeriod(u32 uPeriod);
5183
5184 #ifndef RGFW_NO_XINPUT
5185 void RGFW_loadXInput(void) {
5186 u32 i;
5187 static const char* names[] = {
5188 "xinput1_4.dll",
5189 "xinput1_3.dll",
5190 "xinput9_1_0.dll",
5191 "xinput1_2.dll",
5192 "xinput1_1.dll"
5193 };
5194
5195 for (i = 0; i < sizeof(names) / sizeof(const char*); i++) {
5196 RGFW_XInput_dll = LoadLibraryA(names[i]);
5197
5198 if (RGFW_XInput_dll) {
5199 XInputGetStateSRC = (PFN_XInputGetState)(void*)GetProcAddress(RGFW_XInput_dll, "XInputGetState");
5200
5201 if (XInputGetStateSRC == NULL)
5202 printf("Failed to load XInputGetState");
5203 }
5204 }
5205 }
5206 #endif
5207
5208 RGFWDEF void RGFW_init_buffer(RGFW_window* win);
5209 void RGFW_init_buffer(RGFW_window* win) {
5210#if defined(RGFW_OSMESA) || defined(RGFW_BUFFER)
5211 if (RGFW_bufferSize.w == 0 && RGFW_bufferSize.h == 0)
5212 RGFW_bufferSize = RGFW_getScreenSize();
5213
5214 BITMAPV5HEADER bi = { 0 };
5215 ZeroMemory(&bi, sizeof(bi));
5216 bi.bV5Size = sizeof(bi);
5217 bi.bV5Width = RGFW_bufferSize.w;
5218 bi.bV5Height = -((LONG) RGFW_bufferSize.h);
5219 bi.bV5Planes = 1;
5220 bi.bV5BitCount = 32;
5221 bi.bV5Compression = BI_BITFIELDS;
5222 bi.bV5BlueMask = 0x00ff0000;
5223 bi.bV5GreenMask = 0x0000ff00;
5224 bi.bV5RedMask = 0x000000ff;
5225 bi.bV5AlphaMask = 0xff000000;
5226
5227 win->src.bitmap = CreateDIBSection(win->src.hdc,
5228 (BITMAPINFO*) &bi,
5229 DIB_RGB_COLORS,
5230 (void**) &win->buffer,
5231 NULL,
5232 (DWORD) 0);
5233
5234 win->src.hdcMem = CreateCompatibleDC(win->src.hdc);
5235
5236 #if defined(RGFW_OSMESA)
5237 win->src.ctx = OSMesaCreateContext(OSMESA_RGBA, NULL);
5238 OSMesaMakeCurrent(win->src.ctx, win->buffer, GL_UNSIGNED_BYTE, win->r.w, win->r.h);
5239 #endif
5240#else
5241RGFW_UNUSED(win); /*!< if buffer rendering is not being used */
5242#endif
5243 }
5244
5245 void RGFW_window_setDND(RGFW_window* win, b8 allow) {
5246 DragAcceptFiles(win->src.window, allow);
5247 }
5248
5249 void RGFW_releaseCursor(RGFW_window* win) {
5250 RGFW_UNUSED(win);
5251 ClipCursor(NULL);
5252 const RAWINPUTDEVICE id = { 0x01, 0x02, RIDEV_REMOVE, NULL };
5253 RegisterRawInputDevices(&id, 1, sizeof(id));
5254 }
5255
5256 void RGFW_captureCursor(RGFW_window* win, RGFW_rect rect) {
5257 RGFW_UNUSED(win); RGFW_UNUSED(rect);
5258
5259 RECT clipRect;
5260 GetClientRect(win->src.window, &clipRect);
5261 ClientToScreen(win->src.window, (POINT*) &clipRect.left);
5262 ClientToScreen(win->src.window, (POINT*) &clipRect.right);
5263 ClipCursor(&clipRect);
5264
5265 const RAWINPUTDEVICE id = { 0x01, 0x02, 0, win->src.window };
5266 RegisterRawInputDevices(&id, 1, sizeof(id));
5267 }
5268
5269 RGFW_window* RGFW_createWindow(const char* name, RGFW_rect rect, u16 args) {
5270 #ifndef RGFW_NO_XINPUT
5271 if (RGFW_XInput_dll == NULL)
5272 RGFW_loadXInput();
5273 #endif
5274
5275 #ifndef RGFW_NO_DPI
5276 if (RGFW_Shcore_dll == NULL) {
5277 RGFW_Shcore_dll = LoadLibraryA("shcore.dll");
5278 GetDpiForMonitorSRC = (PFN_GetDpiForMonitor)(void*)GetProcAddress(RGFW_Shcore_dll, "GetDpiForMonitor");
5279 SetProcessDPIAware();
5280 }
5281 #endif
5282
5283 if (wglinstance == NULL) {
5284 wglinstance = LoadLibraryA("opengl32.dll");
5285#ifdef RGFW_WGL_LOAD
5286 wglCreateContextSRC = (PFN_wglCreateContext) GetProcAddress(wglinstance, "wglCreateContext");
5287 wglDeleteContextSRC = (PFN_wglDeleteContext) GetProcAddress(wglinstance, "wglDeleteContext");
5288 wglGetProcAddressSRC = (PFN_wglGetProcAddress) GetProcAddress(wglinstance, "wglGetProcAddress");
5289 wglMakeCurrentSRC = (PFN_wglMakeCurrent) GetProcAddress(wglinstance, "wglMakeCurrent");
5290 wglGetCurrentDCSRC = (PFN_wglGetCurrentDC) GetProcAddress(wglinstance, "wglGetCurrentDC");
5291 wglGetCurrentContextSRC = (PFN_wglGetCurrentContext) GetProcAddress(wglinstance, "wglGetCurrentContext");
5292#endif
5293 }
5294
5295 if (name[0] == 0) name = (char*) " ";
5296
5297 RGFW_eventWindow.r = RGFW_RECT(-1, -1, -1, -1);
5298 RGFW_eventWindow.src.window = NULL;
5299
5300 RGFW_window* win = RGFW_window_basic_init(rect, args);
5301
5302 win->src.maxSize = RGFW_AREA(0, 0);
5303 win->src.minSize = RGFW_AREA(0, 0);
5304
5305
5306 HINSTANCE inh = GetModuleHandleA(NULL);
5307
5308 #ifndef __cplusplus
5309 WNDCLASSA Class = { 0 }; /*!< Setup the Window class. */
5310 #else
5311 WNDCLASSA Class = { };
5312 #endif
5313
5314 if (RGFW_className == NULL)
5315 RGFW_className = (char*)name;
5316
5317 Class.lpszClassName = RGFW_className;
5318 Class.hInstance = inh;
5319 Class.hCursor = LoadCursor(NULL, IDC_ARROW);
5320 Class.lpfnWndProc = WndProc;
5321
5322 RegisterClassA(&Class);
5323
5324 DWORD window_style = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
5325
5326 RECT windowRect, clientRect;
5327
5328 if (!(args & RGFW_NO_BORDER)) {
5329 window_style |= WS_CAPTION | WS_SYSMENU | WS_BORDER | WS_MINIMIZEBOX;
5330
5331 if (!(args & RGFW_NO_RESIZE))
5332 window_style |= WS_SIZEBOX | WS_MAXIMIZEBOX | WS_THICKFRAME;
5333 } else
5334 window_style |= WS_POPUP | WS_VISIBLE | WS_SYSMENU | WS_MINIMIZEBOX;
5335
5336 HWND dummyWin = CreateWindowA(Class.lpszClassName, name, window_style, win->r.x, win->r.y, win->r.w, win->r.h, 0, 0, inh, 0);
5337
5338 GetWindowRect(dummyWin, &windowRect);
5339 GetClientRect(dummyWin, &clientRect);
5340
5341 win->src.hOffset = (windowRect.bottom - windowRect.top) - (clientRect.bottom - clientRect.top);
5342 win->src.window = CreateWindowA(Class.lpszClassName, name, window_style, win->r.x, win->r.y, win->r.w, win->r.h + win->src.hOffset, 0, 0, inh, 0);
5343
5344 if (args & RGFW_ALLOW_DND) {
5345 win->_winArgs |= RGFW_ALLOW_DND;
5346 RGFW_window_setDND(win, 1);
5347 }
5348 win->src.hdc = GetDC(win->src.window);
5349
5350 if ((args & RGFW_NO_INIT_API) == 0) {
5351#ifdef RGFW_DIRECTX
5352 assert(FAILED(CreateDXGIFactory(&__uuidof(IDXGIFactory), (void**) &RGFW_dxInfo.pFactory)) == 0);
5353
5354 if (FAILED(RGFW_dxInfo.pFactory->lpVtbl->EnumAdapters(RGFW_dxInfo.pFactory, 0, &RGFW_dxInfo.pAdapter))) {
5355 fprintf(stderr, "Failed to enumerate DXGI adapters\n");
5356 RGFW_dxInfo.pFactory->lpVtbl->Release(RGFW_dxInfo.pFactory);
5357 return NULL;
5358 }
5359
5360 D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_0 };
5361
5362 if (FAILED(D3D11CreateDevice(RGFW_dxInfo.pAdapter, D3D_DRIVER_TYPE_UNKNOWN, NULL, 0, featureLevels, 1, D3D11_SDK_VERSION, &RGFW_dxInfo.pDevice, NULL, &RGFW_dxInfo.pDeviceContext))) {
5363 fprintf(stderr, "Failed to create Direct3D device\n");
5364 RGFW_dxInfo.pAdapter->lpVtbl->Release(RGFW_dxInfo.pAdapter);
5365 RGFW_dxInfo.pFactory->lpVtbl->Release(RGFW_dxInfo.pFactory);
5366 return NULL;
5367 }
5368
5369 DXGI_SWAP_CHAIN_DESC swapChainDesc = { 0 };
5370 swapChainDesc.BufferCount = 1;
5371 swapChainDesc.BufferDesc.Width = win->r.w;
5372 swapChainDesc.BufferDesc.Height = win->r.h;
5373 swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
5374 swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
5375 swapChainDesc.OutputWindow = win->src.window;
5376 swapChainDesc.SampleDesc.Count = 1;
5377 swapChainDesc.SampleDesc.Quality = 0;
5378 swapChainDesc.Windowed = TRUE;
5379 RGFW_dxInfo.pFactory->lpVtbl->CreateSwapChain(RGFW_dxInfo.pFactory, (IUnknown*) RGFW_dxInfo.pDevice, &swapChainDesc, &win->src.swapchain);
5380
5381 ID3D11Texture2D* pBackBuffer;
5382 win->src.swapchain->lpVtbl->GetBuffer(win->src.swapchain, 0, &__uuidof(ID3D11Texture2D), (LPVOID*) &pBackBuffer);
5383 RGFW_dxInfo.pDevice->lpVtbl->CreateRenderTargetView(RGFW_dxInfo.pDevice, (ID3D11Resource*) pBackBuffer, NULL, &win->src.renderTargetView);
5384 pBackBuffer->lpVtbl->Release(pBackBuffer);
5385
5386 D3D11_TEXTURE2D_DESC depthStencilDesc = { 0 };
5387 depthStencilDesc.Width = win->r.w;
5388 depthStencilDesc.Height = win->r.h;
5389 depthStencilDesc.MipLevels = 1;
5390 depthStencilDesc.ArraySize = 1;
5391 depthStencilDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
5392 depthStencilDesc.SampleDesc.Count = 1;
5393 depthStencilDesc.SampleDesc.Quality = 0;
5394 depthStencilDesc.Usage = D3D11_USAGE_DEFAULT;
5395 depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
5396
5397 ID3D11Texture2D* pDepthStencilTexture = NULL;
5398 RGFW_dxInfo.pDevice->lpVtbl->CreateTexture2D(RGFW_dxInfo.pDevice, &depthStencilDesc, NULL, &pDepthStencilTexture);
5399
5400 D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc = { 0 };
5401 depthStencilViewDesc.Format = depthStencilDesc.Format;
5402 depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
5403 depthStencilViewDesc.Texture2D.MipSlice = 0;
5404
5405 RGFW_dxInfo.pDevice->lpVtbl->CreateDepthStencilView(RGFW_dxInfo.pDevice, (ID3D11Resource*) pDepthStencilTexture, &depthStencilViewDesc, &win->src.pDepthStencilView);
5406
5407 pDepthStencilTexture->lpVtbl->Release(pDepthStencilTexture);
5408
5409 RGFW_dxInfo.pDeviceContext->lpVtbl->OMSetRenderTargets(RGFW_dxInfo.pDeviceContext, 1, &win->src.renderTargetView, win->src.pDepthStencilView);
5410#endif
5411
5412#ifdef RGFW_OPENGL
5413 HDC dummy_dc = GetDC(dummyWin);
5414
5415 u32 pfd_flags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL;
5416
5417 //if (RGFW_DOUBLE_BUFFER)
5418 pfd_flags |= PFD_DOUBLEBUFFER;
5419
5420 PIXELFORMATDESCRIPTOR pfd = {
5421 sizeof(pfd),
5422 1, /* version */
5423 pfd_flags,
5424 PFD_TYPE_RGBA, /* ipixel type */
5425 24, /* color bits */
5426 0, 0, 0, 0, 0, 0,
5427 8, /* alpha bits */
5428 0, 0, 0, 0, 0, 0,
5429 32, /* depth bits */
5430 8, /* stencil bits */
5431 0,
5432 PFD_MAIN_PLANE, /* Layer type */
5433 0, 0, 0, 0
5434 };
5435
5436 int pixel_format = ChoosePixelFormat(dummy_dc, &pfd);
5437 SetPixelFormat(dummy_dc, pixel_format, &pfd);
5438
5439 HGLRC dummy_context = wglCreateContext(dummy_dc);
5440 wglMakeCurrent(dummy_dc, dummy_context);
5441
5442 if (wglChoosePixelFormatARB == NULL) {
5443 wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC) (void*) wglGetProcAddress("wglCreateContextAttribsARB");
5444 wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC) (void*)wglGetProcAddress("wglChoosePixelFormatARB");
5445 }
5446
5447 wglMakeCurrent(dummy_dc, 0);
5448 wglDeleteContext(dummy_context);
5449 ReleaseDC(dummyWin, dummy_dc);
5450
5451 /* try to create the pixel format we want for opengl and then try to create an opengl context for the specified version */
5452 if (wglCreateContextAttribsARB != NULL) {
5453 PIXELFORMATDESCRIPTOR pfd = {sizeof(pfd), 1, pfd_flags, PFD_TYPE_RGBA, 32, 8, PFD_MAIN_PLANE, 24, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
5454
5455 if (args & RGFW_OPENGL_SOFTWARE)
5456 pfd.dwFlags |= PFD_GENERIC_FORMAT | PFD_GENERIC_ACCELERATED;
5457
5458 if (wglChoosePixelFormatARB != NULL) {
5459 i32* pixel_format_attribs = (i32*)RGFW_initFormatAttribs(args & RGFW_OPENGL_SOFTWARE);
5460
5461 int pixel_format;
5462 UINT num_formats;
5463 wglChoosePixelFormatARB(win->src.hdc, pixel_format_attribs, 0, 1, &pixel_format, &num_formats);
5464 if (!num_formats) {
5465 printf("Failed to create a pixel format for WGL.\n");
5466 }
5467
5468 DescribePixelFormat(win->src.hdc, pixel_format, sizeof(pfd), &pfd);
5469 if (!SetPixelFormat(win->src.hdc, pixel_format, &pfd)) {
5470 printf("Failed to set the WGL pixel format.\n");
5471 }
5472 }
5473
5474 /* create opengl/WGL context for the specified version */
5475 u32 index = 0;
5476 i32 attribs[40];
5477
5478 if (RGFW_profile == RGFW_GL_CORE) {
5479 SET_ATTRIB(WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB);
5480 }
5481 else {
5482 SET_ATTRIB(WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB);
5483 }
5484
5485 if (RGFW_majorVersion || RGFW_minorVersion) {
5486 SET_ATTRIB(WGL_CONTEXT_MAJOR_VERSION_ARB, RGFW_majorVersion);
5487 SET_ATTRIB(WGL_CONTEXT_MINOR_VERSION_ARB, RGFW_minorVersion);
5488 }
5489
5490 SET_ATTRIB(0, 0);
5491
5492 win->src.ctx = (HGLRC)wglCreateContextAttribsARB(win->src.hdc, NULL, attribs);
5493 } else { /* fall back to a default context (probably opengl 2 or something) */
5494 fprintf(stderr, "Failed to create an accelerated OpenGL Context\n");
5495
5496 int pixel_format = ChoosePixelFormat(win->src.hdc, &pfd);
5497 SetPixelFormat(win->src.hdc, pixel_format, &pfd);
5498
5499 win->src.ctx = wglCreateContext(win->src.hdc);
5500 }
5501
5502 wglMakeCurrent(win->src.hdc, win->src.ctx);
5503#endif
5504 }
5505
5506#ifdef RGFW_OSMESA
5507#ifdef RGFW_LINK_OSM ESA
5508 OSMesaMakeCurrentSource = (PFN_OSMesaMakeCurrent) GetProcAddress(win->src.hdc, "OSMesaMakeCurrent");
5509 OSMesaCreateContextSource = (PFN_OSMesaCreateContext) GetProcAddress(win->src.hdc, "OSMesaCreateContext");
5510 OSMesaDestroyContextSource = (PFN_OSMesaDestroyContext) GetProcAddress(win->src.hdc, "OSMesaDestroyContext");
5511#endif
5512#endif
5513
5514#ifdef RGFW_OPENGL
5515 if ((args & RGFW_NO_INIT_API) == 0) {
5516 ReleaseDC(win->src.window, win->src.hdc);
5517 win->src.hdc = GetDC(win->src.window);
5518 wglMakeCurrent(win->src.hdc, win->src.ctx);
5519 }
5520#endif
5521
5522 DestroyWindow(dummyWin);
5523 RGFW_init_buffer(win);
5524
5525
5526 #ifndef RGFW_NO_MONITOR
5527 if (args & RGFW_SCALE_TO_MONITOR)
5528 RGFW_window_scaleToMonitor(win);
5529 #endif
5530
5531 if (args & RGFW_CENTER) {
5532 RGFW_area screenR = RGFW_getScreenSize();
5533 RGFW_window_move(win, RGFW_POINT((screenR.w - win->r.w) / 2, (screenR.h - win->r.h) / 2));
5534 }
5535
5536#ifdef RGFW_EGL
5537 if ((args & RGFW_NO_INIT_API) == 0)
5538 RGFW_createOpenGLContext(win);
5539#endif
5540
5541 if (args & RGFW_HIDE_MOUSE)
5542 RGFW_window_showMouse(win, 0);
5543
5544 if (args & RGFW_TRANSPARENT_WINDOW) {
5545 SetWindowLong(win->src.window, GWL_EXSTYLE, GetWindowLong(win->src.window, GWL_EXSTYLE) | WS_EX_LAYERED);
5546 SetLayeredWindowAttributes(win->src.window, RGB(255, 255, 255), RGFW_ALPHA, LWA_ALPHA);
5547 }
5548
5549 ShowWindow(win->src.window, SW_SHOWNORMAL);
5550
5551 if (RGFW_root == NULL)
5552 RGFW_root = win;
5553
5554 #ifdef RGFW_OPENGL
5555 else
5556 wglShareLists(RGFW_root->src.ctx, win->src.ctx);
5557 #endif
5558
5559 return win;
5560 }
5561
5562 void RGFW_window_setBorder(RGFW_window* win, u8 border) {
5563 DWORD style = GetWindowLong(win->src.window, GWL_STYLE);
5564
5565 if (border == 0) {
5566 SetWindowLong(win->src.window, GWL_STYLE, style & ~WS_OVERLAPPEDWINDOW);
5567 SetWindowPos(
5568 win->src.window, HWND_TOP, 0, 0, 0, 0,
5569 SWP_NOZORDER | SWP_FRAMECHANGED | SWP_SHOWWINDOW | SWP_NOMOVE | SWP_NOSIZE
5570 );
5571 }
5572 else {
5573 SetWindowLong(win->src.window, GWL_STYLE, style | WS_OVERLAPPEDWINDOW);
5574 SetWindowPos(
5575 win->src.window, HWND_TOP, 0, 0, 0, 0,
5576 SWP_NOZORDER | SWP_FRAMECHANGED | SWP_SHOWWINDOW | SWP_NOMOVE | SWP_NOSIZE
5577 );
5578 }
5579 }
5580
5581
5582 RGFW_area RGFW_getScreenSize(void) {
5583 return RGFW_AREA(GetDeviceCaps(GetDC(NULL), HORZRES), GetDeviceCaps(GetDC(NULL), VERTRES));
5584 }
5585
5586 RGFW_point RGFW_getGlobalMousePoint(void) {
5587 POINT p;
5588 GetCursorPos(&p);
5589
5590 return RGFW_POINT(p.x, p.y);
5591 }
5592
5593 RGFW_point RGFW_window_getMousePoint(RGFW_window* win) {
5594 POINT p;
5595 GetCursorPos(&p);
5596 ScreenToClient(win->src.window, &p);
5597
5598 return RGFW_POINT(p.x, p.y);
5599 }
5600
5601 void RGFW_window_setMinSize(RGFW_window* win, RGFW_area a) {
5602 assert(win != NULL);
5603 win->src.minSize = a;
5604 }
5605
5606 void RGFW_window_setMaxSize(RGFW_window* win, RGFW_area a) {
5607 assert(win != NULL);
5608 win->src.maxSize = a;
5609 }
5610
5611
5612 void RGFW_window_minimize(RGFW_window* win) {
5613 assert(win != NULL);
5614
5615 ShowWindow(win->src.window, SW_MINIMIZE);
5616 }
5617
5618 void RGFW_window_restore(RGFW_window* win) {
5619 assert(win != NULL);
5620
5621 ShowWindow(win->src.window, SW_RESTORE);
5622 }
5623
5624
5625 u8 RGFW_xinput2RGFW[] = {
5626 RGFW_JS_A, /* or PS X button */
5627 RGFW_JS_B, /* or PS circle button */
5628 RGFW_JS_X, /* or PS square button */
5629 RGFW_JS_Y, /* or PS triangle button */
5630 RGFW_JS_R1, /* right bumper */
5631 RGFW_JS_L1, /* left bump */
5632 RGFW_JS_L2, /* left trigger*/
5633 RGFW_JS_R2, /* right trigger */
5634 0, 0, 0, 0, 0, 0, 0, 0,
5635 RGFW_JS_UP, /* dpad up */
5636 RGFW_JS_DOWN, /* dpad down*/
5637 RGFW_JS_LEFT, /* dpad left */
5638 RGFW_JS_RIGHT, /* dpad right */
5639 RGFW_JS_START, /* start button */
5640 RGFW_JS_SELECT/* select button */
5641 };
5642
5643 static i32 RGFW_checkXInput(RGFW_window* win, RGFW_Event* e) {
5644 RGFW_UNUSED(win)
5645
5646 size_t i;
5647 for (i = 0; i < 4; i++) {
5648 XINPUT_KEYSTROKE keystroke;
5649
5650 if (XInputGetKeystroke == NULL)
5651 return 0;
5652
5653 DWORD result = XInputGetKeystroke((DWORD)i, 0, &keystroke);
5654
5655 if ((keystroke.Flags & XINPUT_KEYSTROKE_REPEAT) == 0 && result != ERROR_EMPTY) {
5656 if (result != ERROR_SUCCESS)
5657 return 0;
5658
5659 if (keystroke.VirtualKey > VK_PAD_BACK)
5660 continue;
5661
5662 // RGFW_jsButtonPressed + 1 = RGFW_jsButtonReleased
5663 e->type = RGFW_jsButtonPressed + !(keystroke.Flags & XINPUT_KEYSTROKE_KEYDOWN);
5664 e->button = RGFW_xinput2RGFW[keystroke.VirtualKey - 0x5800];
5665 RGFW_jsPressed[i][e->button] = !(keystroke.Flags & XINPUT_KEYSTROKE_KEYDOWN);
5666
5667 return 1;
5668 }
5669
5670 XINPUT_STATE state;
5671 if (XInputGetState == NULL ||
5672 XInputGetState((DWORD) i, &state) == ERROR_DEVICE_NOT_CONNECTED
5673 )
5674 return 0;
5675#define INPUT_DEADZONE ( 0.24f * (float)(0x7FFF) ) // Default to 24% of the +/- 32767 range. This is a reasonable default value but can be altered if needed.
5676
5677 if ((state.Gamepad.sThumbLX < INPUT_DEADZONE &&
5678 state.Gamepad.sThumbLX > -INPUT_DEADZONE) &&
5679 (state.Gamepad.sThumbLY < INPUT_DEADZONE &&
5680 state.Gamepad.sThumbLY > -INPUT_DEADZONE))
5681 {
5682 state.Gamepad.sThumbLX = 0;
5683 state.Gamepad.sThumbLY = 0;
5684 }
5685
5686 if ((state.Gamepad.sThumbRX < INPUT_DEADZONE &&
5687 state.Gamepad.sThumbRX > -INPUT_DEADZONE) &&
5688 (state.Gamepad.sThumbRY < INPUT_DEADZONE &&
5689 state.Gamepad.sThumbRY > -INPUT_DEADZONE))
5690 {
5691 state.Gamepad.sThumbRX = 0;
5692 state.Gamepad.sThumbRY = 0;
5693 }
5694
5695 e->axisesCount = 2;
5696 RGFW_point axis1 = RGFW_POINT(state.Gamepad.sThumbLX, state.Gamepad.sThumbLY);
5697 RGFW_point axis2 = RGFW_POINT(state.Gamepad.sThumbRX, state.Gamepad.sThumbRY);
5698
5699 if (axis1.x != e->axis[0].x || axis1.y != e->axis[0].y || axis2.x != e->axis[1].x || axis2.y != e->axis[1].y) {
5700 e->type = RGFW_jsAxisMove;
5701
5702 e->axis[0] = axis1;
5703 e->axis[1] = axis2;
5704
5705 return 1;
5706 }
5707
5708 e->axis[0] = axis1;
5709 e->axis[1] = axis2;
5710 }
5711
5712 return 0;
5713 }
5714
5715 void RGFW_stopCheckEvents(void) {
5716 PostMessageW(RGFW_root->src.window, WM_NULL, 0, 0);
5717 }
5718
5719 void RGFW_window_eventWait(RGFW_window* win, i32 waitMS) {
5720 RGFW_UNUSED(win);
5721
5722 MsgWaitForMultipleObjects(0, NULL, FALSE, (DWORD) (waitMS * 1e3), QS_ALLINPUT);
5723 }
5724
5725 RGFW_Event* RGFW_window_checkEvent(RGFW_window* win) {
5726 assert(win != NULL);
5727
5728 if (win->event.type == RGFW_quit) {
5729 return NULL;
5730 }
5731
5732 MSG msg;
5733
5734 if (RGFW_eventWindow.src.window == win->src.window) {
5735 if (RGFW_eventWindow.r.x != -1) {
5736 win->r.x = RGFW_eventWindow.r.x;
5737 win->r.y = RGFW_eventWindow.r.y;
5738 win->event.type = RGFW_windowMoved;
5739 RGFW_windowMoveCallback(win, win->r);
5740 }
5741
5742 if (RGFW_eventWindow.r.w != -1) {
5743 win->r.w = RGFW_eventWindow.r.w;
5744 win->r.h = RGFW_eventWindow.r.h;
5745 win->event.type = RGFW_windowResized;
5746 RGFW_windowResizeCallback(win, win->r);
5747 }
5748
5749 RGFW_eventWindow.src.window = NULL;
5750 RGFW_eventWindow.r = RGFW_RECT(-1, -1, -1, -1);
5751
5752 return &win->event;
5753 }
5754
5755
5756 static HDROP drop;
5757
5758 if (win->event.type == RGFW_dnd_init) {
5759 if (win->event.droppedFilesCount) {
5760 u32 i;
5761 for (i = 0; i < win->event.droppedFilesCount; i++)
5762 win->event.droppedFiles[i][0] = '\0';
5763 }
5764
5765 win->event.droppedFilesCount = 0;
5766 win->event.droppedFilesCount = DragQueryFileW(drop, 0xffffffff, NULL, 0);
5767 //win->event.droppedFiles = (char**)RGFW_CALLOC(win->event.droppedFilesCount, sizeof(char*));
5768
5769 u32 i;
5770 for (i = 0; i < win->event.droppedFilesCount; i++) {
5771 const UINT length = DragQueryFileW(drop, i, NULL, 0);
5772 WCHAR* buffer = (WCHAR*) RGFW_CALLOC((size_t) length + 1, sizeof(WCHAR));
5773
5774 DragQueryFileW(drop, i, buffer, length + 1);
5775 strncpy(win->event.droppedFiles[i], createUTF8FromWideStringWin32(buffer), RGFW_MAX_PATH);
5776 win->event.droppedFiles[i][RGFW_MAX_PATH - 1] = '\0';
5777 RGFW_FREE(buffer);
5778 }
5779
5780 DragFinish(drop);
5781 RGFW_dndCallback(win, win->event.droppedFiles, win->event.droppedFilesCount);
5782
5783 win->event.type = RGFW_dnd;
5784 return &win->event;
5785 }
5786
5787 win->event.inFocus = (GetForegroundWindow() == win->src.window);
5788
5789 if (RGFW_checkXInput(win, &win->event))
5790 return &win->event;
5791
5792 static BYTE keyboardState[256];
5793
5794 if (PeekMessageA(&msg, win->src.window, 0u, 0u, PM_REMOVE)) {
5795 switch (msg.message) {
5796 case WM_CLOSE:
5797 case WM_QUIT:
5798 RGFW_windowQuitCallback(win);
5799 win->event.type = RGFW_quit;
5800 break;
5801
5802 case WM_ACTIVATE:
5803 win->event.inFocus = (LOWORD(msg.wParam) == WA_INACTIVE);
5804
5805 if (win->event.inFocus) {
5806 win->event.type = RGFW_focusIn;
5807 RGFW_focusCallback(win, 1);
5808 }
5809 else {
5810 win->event.type = RGFW_focusOut;
5811 RGFW_focusCallback(win, 0);
5812 }
5813
5814 break;
5815
5816 case WM_PAINT:
5817 win->event.type = RGFW_windowRefresh;
5818 RGFW_windowRefreshCallback(win);
5819 break;
5820
5821 case WM_MOUSELEAVE:
5822 win->event.type = RGFW_mouseLeave;
5823 win->_winArgs |= RGFW_MOUSE_LEFT;
5824 RGFW_mouseNotifyCallBack(win, win->event.point, 0);
5825 break;
5826
5827 case WM_KEYUP: {
5828 win->event.keyCode = RGFW_apiKeyCodeToRGFW((u32) msg.wParam);
5829
5830 RGFW_keyboard[win->event.keyCode].prev = RGFW_isPressed(win, win->event.keyCode);
5831
5832 static char keyName[16];
5833
5834 {
5835 GetKeyNameTextA((LONG) msg.lParam, keyName, 16);
5836
5837 if ((!(GetKeyState(VK_CAPITAL) & 0x0001) && !(GetKeyState(VK_SHIFT) & 0x8000)) ||
5838 ((GetKeyState(VK_CAPITAL) & 0x0001) && (GetKeyState(VK_SHIFT) & 0x8000))) {
5839 CharLowerBuffA(keyName, 16);
5840 }
5841 }
5842
5843 RGFW_updateLockState(win, (GetKeyState(VK_CAPITAL) & 0x0001), (GetKeyState(VK_NUMLOCK) & 0x0001));
5844
5845 strncpy(win->event.keyName, keyName, 16);
5846
5847 if (RGFW_isPressed(win, RGFW_ShiftL)) {
5848 ToAscii((UINT) msg.wParam, MapVirtualKey((UINT) msg.wParam, MAPVK_VK_TO_CHAR),
5849 keyboardState, (LPWORD) win->event.keyName, 0);
5850 }
5851
5852 win->event.type = RGFW_keyReleased;
5853 RGFW_keyboard[win->event.keyCode].current = 0;
5854 RGFW_keyCallback(win, win->event.keyCode, win->event.keyName, win->event.lockState, 0);
5855 break;
5856 }
5857 case WM_KEYDOWN: {
5858 win->event.keyCode = RGFW_apiKeyCodeToRGFW((u32) msg.wParam);
5859
5860 RGFW_keyboard[win->event.keyCode].prev = RGFW_isPressed(win, win->event.keyCode);
5861
5862 static char keyName[16];
5863
5864 {
5865 GetKeyNameTextA((LONG) msg.lParam, keyName, 16);
5866
5867 if ((!(GetKeyState(VK_CAPITAL) & 0x0001) && !(GetKeyState(VK_SHIFT) & 0x8000)) ||
5868 ((GetKeyState(VK_CAPITAL) & 0x0001) && (GetKeyState(VK_SHIFT) & 0x8000))) {
5869 CharLowerBuffA(keyName, 16);
5870 }
5871 }
5872
5873 RGFW_updateLockState(win, (GetKeyState(VK_CAPITAL) & 0x0001), (GetKeyState(VK_NUMLOCK) & 0x0001));
5874
5875 strncpy(win->event.keyName, keyName, 16);
5876
5877 if (RGFW_isPressed(win, RGFW_ShiftL) & 0x8000) {
5878 ToAscii((UINT) msg.wParam, MapVirtualKey((UINT) msg.wParam, MAPVK_VK_TO_CHAR),
5879 keyboardState, (LPWORD) win->event.keyName, 0);
5880 }
5881
5882 win->event.type = RGFW_keyPressed;
5883 win->event.repeat = RGFW_isPressed(win, win->event.keyCode);
5884 RGFW_keyboard[win->event.keyCode].current = 1;
5885 RGFW_keyCallback(win, win->event.keyCode, win->event.keyName, win->event.lockState, 1);
5886 break;
5887 }
5888
5889 case WM_MOUSEMOVE:
5890 if ((win->_winArgs & RGFW_HOLD_MOUSE))
5891 break;
5892
5893 win->event.type = RGFW_mousePosChanged;
5894
5895 win->event.point.x = GET_X_LPARAM(msg.lParam);
5896 win->event.point.y = GET_Y_LPARAM(msg.lParam);
5897
5898 RGFW_mousePosCallback(win, win->event.point);
5899
5900 if (win->_winArgs & RGFW_MOUSE_LEFT) {
5901 win->_winArgs ^= RGFW_MOUSE_LEFT;
5902 win->event.type = RGFW_mouseEnter;
5903 RGFW_mouseNotifyCallBack(win, win->event.point, 1);
5904 }
5905
5906 break;
5907
5908 case WM_INPUT: {
5909 if (!(win->_winArgs & RGFW_HOLD_MOUSE))
5910 break;
5911
5912 unsigned size = sizeof(RAWINPUT);
5913 static RAWINPUT raw[sizeof(RAWINPUT)];
5914 GetRawInputData((HRAWINPUT)msg.lParam, RID_INPUT, raw, &size, sizeof(RAWINPUTHEADER));
5915
5916 if (raw->header.dwType != RIM_TYPEMOUSE || (raw->data.mouse.lLastX == 0 && raw->data.mouse.lLastY == 0) )
5917 break;
5918
5919 win->event.type = RGFW_mousePosChanged;
5920 win->event.point.x = raw->data.mouse.lLastX;
5921 win->event.point.y = raw->data.mouse.lLastY;
5922 break;
5923 }
5924
5925 case WM_LBUTTONDOWN:
5926 win->event.button = RGFW_mouseLeft;
5927 RGFW_mouseButtons[win->event.button].prev = RGFW_mouseButtons[win->event.button].current;
5928 RGFW_mouseButtons[win->event.button].current = 1;
5929 win->event.type = RGFW_mouseButtonPressed;
5930 RGFW_mouseButtonCallback(win, win->event.button, win->event.scroll, 1);
5931 break;
5932 case WM_RBUTTONDOWN:
5933 win->event.button = RGFW_mouseRight;
5934 win->event.type = RGFW_mouseButtonPressed;
5935 RGFW_mouseButtons[win->event.button].prev = RGFW_mouseButtons[win->event.button].current;
5936 RGFW_mouseButtons[win->event.button].current = 1;
5937 RGFW_mouseButtonCallback(win, win->event.button, win->event.scroll, 1);
5938 break;
5939 case WM_MBUTTONDOWN:
5940 win->event.button = RGFW_mouseMiddle;
5941 win->event.type = RGFW_mouseButtonPressed;
5942 RGFW_mouseButtons[win->event.button].prev = RGFW_mouseButtons[win->event.button].current;
5943 RGFW_mouseButtons[win->event.button].current = 1;
5944 RGFW_mouseButtonCallback(win, win->event.button, win->event.scroll, 1);
5945 break;
5946
5947 case WM_MOUSEWHEEL:
5948 if (msg.wParam > 0)
5949 win->event.button = RGFW_mouseScrollUp;
5950 else
5951 win->event.button = RGFW_mouseScrollDown;
5952
5953 RGFW_mouseButtons[win->event.button].prev = RGFW_mouseButtons[win->event.button].current;
5954 RGFW_mouseButtons[win->event.button].current = 1;
5955
5956 win->event.scroll = (SHORT) HIWORD(msg.wParam) / (double) WHEEL_DELTA;
5957
5958 win->event.type = RGFW_mouseButtonPressed;
5959 RGFW_mouseButtonCallback(win, win->event.button, win->event.scroll, 1);
5960 break;
5961
5962 case WM_LBUTTONUP:
5963
5964 win->event.button = RGFW_mouseLeft;
5965 win->event.type = RGFW_mouseButtonReleased;
5966
5967 RGFW_mouseButtons[win->event.button].prev = RGFW_mouseButtons[win->event.button].current;
5968 RGFW_mouseButtons[win->event.button].current = 0;
5969 RGFW_mouseButtonCallback(win, win->event.button, win->event.scroll, 0);
5970 break;
5971 case WM_RBUTTONUP:
5972 win->event.button = RGFW_mouseRight;
5973 win->event.type = RGFW_mouseButtonReleased;
5974
5975 RGFW_mouseButtons[win->event.button].prev = RGFW_mouseButtons[win->event.button].current;
5976 RGFW_mouseButtons[win->event.button].current = 0;
5977 RGFW_mouseButtonCallback(win, win->event.button, win->event.scroll, 0);
5978 break;
5979 case WM_MBUTTONUP:
5980 win->event.button = RGFW_mouseMiddle;
5981 win->event.type = RGFW_mouseButtonReleased;
5982
5983 RGFW_mouseButtons[win->event.button].prev = RGFW_mouseButtons[win->event.button].current;
5984 RGFW_mouseButtons[win->event.button].current = 0;
5985 RGFW_mouseButtonCallback(win, win->event.button, win->event.scroll, 0);
5986 break;
5987
5988 /*
5989 much of this event is source from glfw
5990 */
5991 case WM_DROPFILES: {
5992 win->event.type = RGFW_dnd_init;
5993
5994 drop = (HDROP) msg.wParam;
5995 POINT pt;
5996
5997 /* Move the mouse to the position of the drop */
5998 DragQueryPoint(drop, &pt);
5999
6000 win->event.point.x = pt.x;
6001 win->event.point.y = pt.y;
6002
6003 RGFW_dndInitCallback(win, win->event.point);
6004 }
6005 break;
6006 case WM_GETMINMAXINFO:
6007 {
6008 if (win->src.maxSize.w == 0 && win->src.maxSize.h == 0)
6009 break;
6010
6011 MINMAXINFO* mmi = (MINMAXINFO*) msg.lParam;
6012 mmi->ptMinTrackSize.x = win->src.minSize.w;
6013 mmi->ptMinTrackSize.y = win->src.minSize.h;
6014 mmi->ptMaxTrackSize.x = win->src.maxSize.w;
6015 mmi->ptMaxTrackSize.y = win->src.maxSize.h;
6016 return 0;
6017 }
6018 default:
6019 win->event.type = 0;
6020 break;
6021 }
6022
6023 TranslateMessage(&msg);
6024 DispatchMessageA(&msg);
6025 }
6026
6027 else
6028 win->event.type = 0;
6029
6030 if (!IsWindow(win->src.window)) {
6031 win->event.type = RGFW_quit;
6032 RGFW_windowQuitCallback(win);
6033 }
6034
6035 if (win->event.type)
6036 return &win->event;
6037 else
6038 return NULL;
6039 }
6040
6041 u8 RGFW_window_isFullscreen(RGFW_window* win) {
6042 assert(win != NULL);
6043
6044 #ifndef __cplusplus
6045 WINDOWPLACEMENT placement = { 0 };
6046 #else
6047 WINDOWPLACEMENT placement = { };
6048 #endif
6049 GetWindowPlacement(win->src.window, &placement);
6050 return placement.showCmd == SW_SHOWMAXIMIZED;
6051 }
6052
6053 u8 RGFW_window_isHidden(RGFW_window* win) {
6054 assert(win != NULL);
6055
6056 return IsWindowVisible(win->src.window) == 0 && !RGFW_window_isMinimized(win);
6057 }
6058
6059 u8 RGFW_window_isMinimized(RGFW_window* win) {
6060 assert(win != NULL);
6061
6062 #ifndef __cplusplus
6063 WINDOWPLACEMENT placement = { 0 };
6064 #else
6065 WINDOWPLACEMENT placement = { };
6066 #endif
6067 GetWindowPlacement(win->src.window, &placement);
6068 return placement.showCmd == SW_SHOWMINIMIZED;
6069 }
6070
6071 u8 RGFW_window_isMaximized(RGFW_window* win) {
6072 assert(win != NULL);
6073
6074 #ifndef __cplusplus
6075 WINDOWPLACEMENT placement = { 0 };
6076 #else
6077 WINDOWPLACEMENT placement = { };
6078 #endif
6079 GetWindowPlacement(win->src.window, &placement);
6080 return placement.showCmd == SW_SHOWMAXIMIZED;
6081 }
6082
6083 typedef struct { int iIndex; HMONITOR hMonitor; } RGFW_mInfo;
6084 BOOL CALLBACK GetMonitorByHandle(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
6085 RGFW_UNUSED(hdcMonitor)
6086 RGFW_UNUSED(lprcMonitor)
6087
6088 RGFW_mInfo* info = (RGFW_mInfo*) dwData;
6089 if (info->hMonitor == hMonitor)
6090 return FALSE;
6091
6092 info->iIndex++;
6093 return TRUE;
6094 }
6095
6096 #ifndef RGFW_NO_MONITOR
6097 RGFW_monitor win32CreateMonitor(HMONITOR src) {
6098 RGFW_monitor monitor;
6099 MONITORINFO monitorInfo;
6100
6101 monitorInfo.cbSize = sizeof(MONITORINFO);
6102 GetMonitorInfoA(src, &monitorInfo);
6103
6104 RGFW_mInfo info;
6105 info.iIndex = 0;
6106 info.hMonitor = src;
6107
6108 /* get the monitor's index */
6109 if (EnumDisplayMonitors(NULL, NULL, GetMonitorByHandle, (LPARAM) &info)) {
6110 DISPLAY_DEVICEA dd;
6111 dd.cb = sizeof(dd);
6112
6113 /* loop through the devices until you find a device with the monitor's index */
6114 size_t deviceIndex;
6115 for (deviceIndex = 0; EnumDisplayDevicesA(0, (DWORD) deviceIndex, &dd, 0); deviceIndex++) {
6116 char* deviceName = dd.DeviceName;
6117 if (EnumDisplayDevicesA(deviceName, info.iIndex, &dd, 0)) {
6118 strncpy(monitor.name, dd.DeviceString, 128); /*!< copy the monitor's name */
6119 break;
6120 }
6121 }
6122 }
6123
6124 monitor.rect.x = monitorInfo.rcWork.left;
6125 monitor.rect.y = monitorInfo.rcWork.top;
6126 monitor.rect.w = monitorInfo.rcWork.right - monitorInfo.rcWork.left;
6127 monitor.rect.h = monitorInfo.rcWork.bottom - monitorInfo.rcWork.top;
6128
6129#ifndef RGFW_NO_DPI
6130 #ifndef USER_DEFAULT_SCREEN_DPI
6131 #define USER_DEFAULT_SCREEN_DPI 96
6132 #endif
6133
6134 if (GetDpiForMonitor != NULL) {
6135 u32 x, y;
6136 GetDpiForMonitor(src, MDT_EFFECTIVE_DPI, &x, &y);
6137
6138 monitor.scaleX = (float) (x) / (float) USER_DEFAULT_SCREEN_DPI;
6139 monitor.scaleY = (float) (y) / (float) USER_DEFAULT_SCREEN_DPI;
6140 }
6141#endif
6142
6143 HDC hdc = GetDC(NULL);
6144 /* get pixels per inch */
6145 i32 ppiX = GetDeviceCaps(hdc, LOGPIXELSX);
6146 i32 ppiY = GetDeviceCaps(hdc, LOGPIXELSY);
6147 ReleaseDC(NULL, hdc);
6148
6149 /* Calculate physical height in inches */
6150 monitor.physW = GetSystemMetrics(SM_CYSCREEN) / (float) ppiX;
6151 monitor.physH = GetSystemMetrics(SM_CXSCREEN) / (float) ppiY;
6152
6153 return monitor;
6154 }
6155 #endif /* RGFW_NO_MONITOR */
6156
6157
6158 #ifndef RGFW_NO_MONITOR
6159 RGFW_monitor RGFW_monitors[6];
6160 BOOL CALLBACK GetMonitorHandle(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
6161 RGFW_UNUSED(hdcMonitor)
6162 RGFW_UNUSED(lprcMonitor)
6163
6164 RGFW_mInfo* info = (RGFW_mInfo*) dwData;
6165
6166 if (info->iIndex >= 6)
6167 return FALSE;
6168
6169 RGFW_monitors[info->iIndex] = win32CreateMonitor(hMonitor);
6170 info->iIndex++;
6171
6172 return TRUE;
6173 }
6174
6175 RGFW_monitor RGFW_getPrimaryMonitor(void) {
6176 #ifdef __cplusplus
6177 return win32CreateMonitor(MonitorFromPoint({ 0, 0 }, MONITOR_DEFAULTTOPRIMARY));
6178 #else
6179 return win32CreateMonitor(MonitorFromPoint((POINT) { 0, 0 }, MONITOR_DEFAULTTOPRIMARY));
6180 #endif
6181 }
6182
6183 RGFW_monitor* RGFW_getMonitors(void) {
6184 RGFW_mInfo info;
6185 info.iIndex = 0;
6186 while (EnumDisplayMonitors(NULL, NULL, GetMonitorHandle, (LPARAM) &info));
6187
6188 return RGFW_monitors;
6189 }
6190
6191 RGFW_monitor RGFW_window_getMonitor(RGFW_window* win) {
6192 HMONITOR src = MonitorFromWindow(win->src.window, MONITOR_DEFAULTTOPRIMARY);
6193 return win32CreateMonitor(src);
6194 }
6195 #endif
6196
6197 HICON RGFW_loadHandleImage(RGFW_window* win, u8* src, RGFW_area a, BOOL icon) {
6198 assert(win != NULL);
6199
6200 u32 i;
6201 HDC dc;
6202 HICON handle;
6203 HBITMAP color, mask;
6204 BITMAPV5HEADER bi;
6205 ICONINFO ii;
6206 u8* target = NULL;
6207 u8* source = src;
6208
6209 ZeroMemory(&bi, sizeof(bi));
6210 bi.bV5Size = sizeof(bi);
6211 bi.bV5Width = a.w;
6212 bi.bV5Height = -((LONG) a.h);
6213 bi.bV5Planes = 1;
6214 bi.bV5BitCount = 32;
6215 bi.bV5Compression = BI_BITFIELDS;
6216 bi.bV5RedMask = 0x00ff0000;
6217 bi.bV5GreenMask = 0x0000ff00;
6218 bi.bV5BlueMask = 0x000000ff;
6219 bi.bV5AlphaMask = 0xff000000;
6220
6221 dc = GetDC(NULL);
6222 color = CreateDIBSection(dc,
6223 (BITMAPINFO*) &bi,
6224 DIB_RGB_COLORS,
6225 (void**) &target,
6226 NULL,
6227 (DWORD) 0);
6228 ReleaseDC(NULL, dc);
6229
6230 mask = CreateBitmap(a.w, a.h, 1, 1, NULL);
6231
6232 for (i = 0; i < a.w * a.h; i++) {
6233 target[0] = source[2];
6234 target[1] = source[1];
6235 target[2] = source[0];
6236 target[3] = source[3];
6237 target += 4;
6238 source += 4;
6239 }
6240
6241 ZeroMemory(&ii, sizeof(ii));
6242 ii.fIcon = icon;
6243 ii.xHotspot = 0;
6244 ii.yHotspot = 0;
6245 ii.hbmMask = mask;
6246 ii.hbmColor = color;
6247
6248 handle = CreateIconIndirect(&ii);
6249
6250 DeleteObject(color);
6251 DeleteObject(mask);
6252
6253 return handle;
6254 }
6255
6256 void RGFW_window_setMouse(RGFW_window* win, u8* image, RGFW_area a, i32 channels) {
6257 assert(win != NULL);
6258 RGFW_UNUSED(channels)
6259
6260 HCURSOR cursor = (HCURSOR) RGFW_loadHandleImage(win, image, a, FALSE);
6261 SetClassLongPtrA(win->src.window, GCLP_HCURSOR, (LPARAM) cursor);
6262 SetCursor(cursor);
6263 DestroyCursor(cursor);
6264 }
6265
6266 void RGFW_window_setMouseDefault(RGFW_window* win) {
6267 RGFW_window_setMouseStandard(win, RGFW_MOUSE_ARROW);
6268 }
6269
6270 void RGFW_window_setMouseStandard(RGFW_window* win, u8 mouse) {
6271 assert(win != NULL);
6272
6273 if (mouse > (sizeof(RGFW_mouseIconSrc) / sizeof(u32)))
6274 return;
6275
6276 char* icon = MAKEINTRESOURCEA(RGFW_mouseIconSrc[mouse]);
6277
6278 SetClassLongPtrA(win->src.window, GCLP_HCURSOR, (LPARAM) LoadCursorA(NULL, icon));
6279 SetCursor(LoadCursorA(NULL, icon));
6280 }
6281
6282 void RGFW_window_hide(RGFW_window* win) {
6283 ShowWindow(win->src.window, SW_HIDE);
6284 }
6285
6286 void RGFW_window_show(RGFW_window* win) {
6287 ShowWindow(win->src.window, SW_RESTORE);
6288 }
6289
6290 void RGFW_window_close(RGFW_window* win) {
6291 assert(win != NULL);
6292
6293#ifdef RGFW_EGL
6294 RGFW_closeEGL(win);
6295#endif
6296
6297 if (win == RGFW_root) {
6298#ifdef RGFW_DIRECTX
6299 RGFW_dxInfo.pDeviceContext->lpVtbl->Release(RGFW_dxInfo.pDeviceContext);
6300 RGFW_dxInfo.pDevice->lpVtbl->Release(RGFW_dxInfo.pDevice);
6301 RGFW_dxInfo.pAdapter->lpVtbl->Release(RGFW_dxInfo.pAdapter);
6302 RGFW_dxInfo.pFactory->lpVtbl->Release(RGFW_dxInfo.pFactory);
6303#endif
6304
6305 if (RGFW_XInput_dll != NULL) {
6306 FreeLibrary(RGFW_XInput_dll);
6307 RGFW_XInput_dll = NULL;
6308 }
6309
6310 #ifndef RGFW_NO_DPI
6311 if (RGFW_Shcore_dll != NULL) {
6312 FreeLibrary(RGFW_Shcore_dll);
6313 RGFW_Shcore_dll = NULL;
6314 }
6315 #endif
6316
6317 if (wglinstance != NULL) {
6318 FreeLibrary(wglinstance);
6319 wglinstance = NULL;
6320 }
6321
6322 RGFW_root = NULL;
6323 }
6324
6325#ifdef RGFW_DIRECTX
6326 win->src.swapchain->lpVtbl->Release(win->src.swapchain);
6327 win->src.renderTargetView->lpVtbl->Release(win->src.renderTargetView);
6328 win->src.pDepthStencilView->lpVtbl->Release(win->src.pDepthStencilView);
6329#endif
6330
6331#ifdef RGFW_BUFFER
6332 DeleteDC(win->src.hdcMem);
6333 DeleteObject(win->src.bitmap);
6334#endif
6335
6336#ifdef RGFW_OPENGL
6337 wglDeleteContext((HGLRC) win->src.ctx); /*!< delete opengl context */
6338#endif
6339 DeleteDC(win->src.hdc); /*!< delete device context */
6340 DestroyWindow(win->src.window); /*!< delete window */
6341
6342#if defined(RGFW_OSMESA)
6343 if (win->buffer != NULL)
6344 RGFW_FREE(win->buffer);
6345#endif
6346
6347#ifdef RGFW_ALLOC_DROPFILES
6348 {
6349 u32 i;
6350 for (i = 0; i < RGFW_MAX_DROPS; i++)
6351 RGFW_FREE(win->event.droppedFiles[i]);
6352
6353
6354 RGFW_FREE(win->event.droppedFiles);
6355 }
6356#endif
6357
6358 RGFW_FREE(win);
6359 }
6360
6361 void RGFW_window_move(RGFW_window* win, RGFW_point v) {
6362 assert(win != NULL);
6363
6364 win->r.x = v.x;
6365 win->r.y = v.y;
6366 SetWindowPos(win->src.window, HWND_TOP, win->r.x, win->r.y, 0, 0, SWP_NOSIZE);
6367 }
6368
6369 void RGFW_window_resize(RGFW_window* win, RGFW_area a) {
6370 assert(win != NULL);
6371
6372 win->r.w = a.w;
6373 win->r.h = a.h;
6374 SetWindowPos(win->src.window, HWND_TOP, 0, 0, win->r.w, win->r.h + win->src.hOffset, SWP_NOMOVE);
6375 }
6376
6377
6378 void RGFW_window_setName(RGFW_window* win, char* name) {
6379 assert(win != NULL);
6380
6381 SetWindowTextA(win->src.window, name);
6382 }
6383
6384 /* sourced from GLFW */
6385 #ifndef RGFW_NO_PASSTHROUGH
6386 void RGFW_window_setMousePassthrough(RGFW_window* win, b8 passthrough) {
6387 assert(win != NULL);
6388
6389 COLORREF key = 0;
6390 BYTE alpha = 0;
6391 DWORD flags = 0;
6392 DWORD exStyle = GetWindowLongW(win->src.window, GWL_EXSTYLE);
6393
6394 if (exStyle & WS_EX_LAYERED)
6395 GetLayeredWindowAttributes(win->src.window, &key, &alpha, &flags);
6396
6397 if (passthrough)
6398 exStyle |= (WS_EX_TRANSPARENT | WS_EX_LAYERED);
6399 else
6400 {
6401 exStyle &= ~WS_EX_TRANSPARENT;
6402 // NOTE: Window opacity also needs the layered window style so do not
6403 // remove it if the window is alpha blended
6404 if (exStyle & WS_EX_LAYERED)
6405 {
6406 if (!(flags & LWA_ALPHA))
6407 exStyle &= ~WS_EX_LAYERED;
6408 }
6409 }
6410
6411 SetWindowLongW(win->src.window, GWL_EXSTYLE, exStyle);
6412
6413 if (passthrough) {
6414 SetLayeredWindowAttributes(win->src.window, key, alpha, flags);
6415 }
6416 }
6417 #endif
6418
6419 /* much of this function is sourced from GLFW */
6420 void RGFW_window_setIcon(RGFW_window* win, u8* src, RGFW_area a, i32 channels) {
6421 assert(win != NULL);
6422 #ifndef RGFW_WIN95
6423 RGFW_UNUSED(channels)
6424
6425 HICON handle = RGFW_loadHandleImage(win, src, a, TRUE);
6426
6427 SetClassLongPtrA(win->src.window, GCLP_HICON, (LPARAM) handle);
6428
6429 DestroyIcon(handle);
6430 #else
6431 RGFW_UNUSED(src)
6432 RGFW_UNUSED(a)
6433 RGFW_UNUSED(channels)
6434 #endif
6435 }
6436
6437 char* RGFW_readClipboard(size_t* size) {
6438 /* Open the clipboard */
6439 if (OpenClipboard(NULL) == 0)
6440 return (char*) "";
6441
6442 /* Get the clipboard data as a Unicode string */
6443 HANDLE hData = GetClipboardData(CF_UNICODETEXT);
6444 if (hData == NULL) {
6445 CloseClipboard();
6446 return (char*) "";
6447 }
6448
6449 wchar_t* wstr = (wchar_t*) GlobalLock(hData);
6450
6451 char* text;
6452
6453 {
6454 setlocale(LC_ALL, "en_US.UTF-8");
6455
6456 size_t textLen = wcstombs(NULL, wstr, 0);
6457 if (textLen == 0)
6458 return (char*) "";
6459
6460 text = (char*) RGFW_MALLOC((textLen * sizeof(char)) + 1);
6461
6462 wcstombs(text, wstr, (textLen) +1);
6463
6464 if (size != NULL)
6465 *size = textLen + 1;
6466
6467 text[textLen] = '\0';
6468 }
6469
6470 /* Release the clipboard data */
6471 GlobalUnlock(hData);
6472 CloseClipboard();
6473
6474 return text;
6475 }
6476
6477 void RGFW_writeClipboard(const char* text, u32 textLen) {
6478 HANDLE object;
6479 WCHAR* buffer;
6480
6481 object = GlobalAlloc(GMEM_MOVEABLE, (1 + textLen) * sizeof(WCHAR));
6482 if (!object)
6483 return;
6484
6485 buffer = (WCHAR*) GlobalLock(object);
6486 if (!buffer) {
6487 GlobalFree(object);
6488 return;
6489 }
6490
6491 MultiByteToWideChar(CP_UTF8, 0, text, -1, buffer, textLen);
6492 GlobalUnlock(object);
6493
6494 if (!OpenClipboard(RGFW_root->src.window)) {
6495 GlobalFree(object);
6496 return;
6497 }
6498
6499 EmptyClipboard();
6500 SetClipboardData(CF_UNICODETEXT, object);
6501 CloseClipboard();
6502 }
6503
6504 u16 RGFW_registerJoystick(RGFW_window* win, i32 jsNumber) {
6505 assert(win != NULL);
6506
6507 RGFW_UNUSED(jsNumber)
6508
6509 return RGFW_registerJoystickF(win, (char*) "");
6510 }
6511
6512 u16 RGFW_registerJoystickF(RGFW_window* win, char* file) {
6513 assert(win != NULL);
6514 RGFW_UNUSED(file)
6515
6516 return RGFW_joystickCount - 1;
6517 }
6518
6519 void RGFW_window_moveMouse(RGFW_window* win, RGFW_point p) {
6520 assert(win != NULL);
6521
6522 SetCursorPos(p.x, p.y);
6523 }
6524
6525 #ifdef RGFW_OPENGL
6526 void RGFW_window_makeCurrent_OpenGL(RGFW_window* win) {
6527 if (win == NULL)
6528 wglMakeCurrent(NULL, NULL);
6529 else
6530 wglMakeCurrent(win->src.hdc, (HGLRC) win->src.ctx);
6531 }
6532 #endif
6533
6534 #ifndef RGFW_EGL
6535 void RGFW_window_swapInterval(RGFW_window* win, i32 swapInterval) {
6536 assert(win != NULL);
6537
6538 #if defined(RGFW_OPENGL)
6539 typedef BOOL(APIENTRY* PFNWGLSWAPINTERVALEXTPROC)(int interval);
6540 static PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = NULL;
6541 static void* loadSwapFunc = (void*) 1;
6542
6543 if (loadSwapFunc == NULL) {
6544 fprintf(stderr, "wglSwapIntervalEXT not supported\n");
6545 return;
6546 }
6547
6548 if (wglSwapIntervalEXT == NULL) {
6549 loadSwapFunc = (void*) wglGetProcAddress("wglSwapIntervalEXT");
6550 wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC) loadSwapFunc;
6551 }
6552
6553 if (wglSwapIntervalEXT(swapInterval) == FALSE)
6554 fprintf(stderr, "Failed to set swap interval\n");
6555 #else
6556 RGFW_UNUSED(swapInterval);
6557 #endif
6558
6559 }
6560 #endif
6561
6562 void RGFW_window_swapBuffers(RGFW_window* win) {
6563 //assert(win != NULL);
6564 /* clear the window*/
6565
6566 if (!(win->_winArgs & RGFW_NO_CPU_RENDER)) {
6567#if defined(RGFW_OSMESA) || defined(RGFW_BUFFER)
6568 #ifdef RGFW_OSMESA
6569 RGFW_OSMesa_reorganize();
6570 #endif
6571
6572 HGDIOBJ oldbmp = SelectObject(win->src.hdcMem, win->src.bitmap);
6573 BitBlt(win->src.hdc, 0, 0, win->r.w, win->r.h, win->src.hdcMem, 0, 0, SRCCOPY);
6574 SelectObject(win->src.hdcMem, oldbmp);
6575#endif
6576 }
6577
6578 if (!(win->_winArgs & RGFW_NO_GPU_RENDER)) {
6579 #ifdef RGFW_EGL
6580 eglSwapBuffers(win->src.EGL_display, win->src.EGL_surface);
6581 #elif defined(RGFW_OPENGL)
6582 SwapBuffers(win->src.hdc);
6583 #endif
6584
6585 #if defined(RGFW_WINDOWS) && defined(RGFW_DIRECTX)
6586 win->src.swapchain->lpVtbl->Present(win->src.swapchain, 0, 0);
6587 #endif
6588 }
6589 }
6590
6591 char* createUTF8FromWideStringWin32(const WCHAR* source) {
6592 char* target;
6593 i32 size;
6594
6595 size = WideCharToMultiByte(CP_UTF8, 0, source, -1, NULL, 0, NULL, NULL);
6596 if (!size) {
6597 return NULL;
6598 }
6599
6600 target = (char*) RGFW_CALLOC(size, 1);
6601
6602 if (!WideCharToMultiByte(CP_UTF8, 0, source, -1, target, size, NULL, NULL)) {
6603 RGFW_FREE(target);
6604 return NULL;
6605 }
6606
6607 return target;
6608 }
6609
6610 static inline LARGE_INTEGER RGFW_win32_initTimer(void) {
6611 static LARGE_INTEGER frequency = {{0, 0}};
6612 if (frequency.QuadPart == 0) {
6613 timeBeginPeriod(1);
6614 QueryPerformanceFrequency(&frequency);
6615 }
6616
6617 return frequency;
6618 }
6619
6620 u64 RGFW_getTimeNS(void) {
6621 LARGE_INTEGER frequency = RGFW_win32_initTimer();
6622
6623 LARGE_INTEGER counter;
6624 QueryPerformanceCounter(&counter);
6625
6626 return (u64) ((counter.QuadPart * 1e9) / frequency.QuadPart);
6627 }
6628
6629 u64 RGFW_getTime(void) {
6630 LARGE_INTEGER frequency = RGFW_win32_initTimer();
6631
6632 LARGE_INTEGER counter;
6633 QueryPerformanceCounter(&counter);
6634 return (u64) (counter.QuadPart / (double) frequency.QuadPart);
6635 }
6636
6637 void RGFW_sleep(u64 ms) {
6638 Sleep(ms);
6639 }
6640
6641#ifndef RGFW_NO_THREADS
6642 RGFW_thread RGFW_createThread(RGFW_threadFunc_ptr ptr, void* args) { return CreateThread(NULL, 0, ptr, args, 0, NULL); }
6643 void RGFW_cancelThread(RGFW_thread thread) { CloseHandle((HANDLE) thread); }
6644 void RGFW_joinThread(RGFW_thread thread) { WaitForSingleObject((HANDLE) thread, INFINITE); }
6645 void RGFW_setThreadPriority(RGFW_thread thread, u8 priority) { SetThreadPriority((HANDLE) thread, priority); }
6646#endif
6647#endif /* RGFW_WINDOWS */
6648
6649/*
6650 End of Windows defines
6651*/
6652
6653
6654
6655/*
6656
6657 Start of MacOS defines
6658
6659
6660*/
6661
6662#if defined(RGFW_MACOS)
6663 /*
6664 based on silicon.h
6665 start of cocoa wrapper
6666 */
6667
6668#include <CoreVideo/CVDisplayLink.h>
6669#include <ApplicationServices/ApplicationServices.h>
6670#include <objc/runtime.h>
6671#include <objc/message.h>
6672#include <mach/mach_time.h>
6673
6674 typedef CGRect NSRect;
6675 typedef CGPoint NSPoint;
6676 typedef CGSize NSSize;
6677
6678 typedef void NSBitmapImageRep;
6679 typedef void NSCursor;
6680 typedef void NSDraggingInfo;
6681 typedef void NSWindow;
6682 typedef void NSApplication;
6683 typedef void NSScreen;
6684 typedef void NSEvent;
6685 typedef void NSString;
6686 typedef void NSOpenGLContext;
6687 typedef void NSPasteboard;
6688 typedef void NSColor;
6689 typedef void NSArray;
6690 typedef void NSImageRep;
6691 typedef void NSImage;
6692 typedef void NSOpenGLView;
6693
6694
6695 typedef const char* NSPasteboardType;
6696 typedef unsigned long NSUInteger;
6697 typedef long NSInteger;
6698 typedef NSInteger NSModalResponse;
6699
6700#ifdef __arm64__
6701 /* ARM just uses objc_msgSend */
6702#define abi_objc_msgSend_stret objc_msgSend
6703#define abi_objc_msgSend_fpret objc_msgSend
6704#else /* __i386__ */
6705 /* x86 just uses abi_objc_msgSend_fpret and (NSColor *)objc_msgSend_id respectively */
6706#define abi_objc_msgSend_stret objc_msgSend_stret
6707#define abi_objc_msgSend_fpret objc_msgSend_fpret
6708#endif
6709
6710#define NSAlloc(nsclass) objc_msgSend_id((id)nsclass, sel_registerName("alloc"))
6711#define objc_msgSend_bool ((BOOL (*)(id, SEL))objc_msgSend)
6712#define objc_msgSend_void ((void (*)(id, SEL))objc_msgSend)
6713#define objc_msgSend_void_id ((void (*)(id, SEL, id))objc_msgSend)
6714#define objc_msgSend_uint ((NSUInteger (*)(id, SEL))objc_msgSend)
6715#define objc_msgSend_void_bool ((void (*)(id, SEL, BOOL))objc_msgSend)
6716#define objc_msgSend_bool_void ((BOOL (*)(id, SEL))objc_msgSend)
6717#define objc_msgSend_void_SEL ((void (*)(id, SEL, SEL))objc_msgSend)
6718#define objc_msgSend_id ((id (*)(id, SEL))objc_msgSend)
6719#define objc_msgSend_id_id ((id (*)(id, SEL, id))objc_msgSend)
6720#define objc_msgSend_id_bool ((BOOL (*)(id, SEL, id))objc_msgSend)
6721#define objc_msgSend_int ((id (*)(id, SEL, int))objc_msgSend)
6722#define objc_msgSend_arr ((id (*)(id, SEL, int))objc_msgSend)
6723#define objc_msgSend_ptr ((id (*)(id, SEL, void*))objc_msgSend)
6724#define objc_msgSend_class ((id (*)(Class, SEL))objc_msgSend)
6725#define objc_msgSend_class_char ((id (*)(Class, SEL, char*))objc_msgSend)
6726
6727 NSApplication* NSApp = NULL;
6728
6729 void NSRelease(id obj) {
6730 objc_msgSend_void(obj, sel_registerName("release"));
6731 }
6732
6733 #define release NSRelease
6734
6735 NSString* NSString_stringWithUTF8String(const char* str) {
6736 return ((id(*)(id, SEL, const char*))objc_msgSend)
6737 ((id)objc_getClass("NSString"), sel_registerName("stringWithUTF8String:"), str);
6738 }
6739
6740 const char* NSString_to_char(NSString* str) {
6741 return ((const char* (*)(id, SEL)) objc_msgSend) (str, sel_registerName("UTF8String"));
6742 }
6743
6744 void si_impl_func_to_SEL_with_name(const char* class_name, const char* register_name, void* function) {
6745 Class selected_class;
6746
6747 if (strcmp(class_name, "NSView") == 0) {
6748 selected_class = objc_getClass("ViewClass");
6749 } else if (strcmp(class_name, "NSWindow") == 0) {
6750 selected_class = objc_getClass("WindowClass");
6751 } else {
6752 selected_class = objc_getClass(class_name);
6753 }
6754
6755 class_addMethod(selected_class, sel_registerName(register_name), (IMP) function, 0);
6756 }
6757
6758 /* Header for the array. */
6759 typedef struct siArrayHeader {
6760 size_t count;
6761 /* TODO(EimaMei): Add a `type_width` later on. */
6762 } siArrayHeader;
6763
6764 /* Gets the header of the siArray. */
6765#define SI_ARRAY_HEADER(s) ((siArrayHeader*)s - 1)
6766
6767 void* si_array_init_reserve(size_t sizeof_element, size_t count) {
6768 siArrayHeader* ptr = malloc(sizeof(siArrayHeader) + (sizeof_element * count));
6769 void* array = ptr + sizeof(siArrayHeader);
6770
6771 siArrayHeader* header = SI_ARRAY_HEADER(array);
6772 header->count = count;
6773
6774 return array;
6775 }
6776
6777#define si_array_len(array) (SI_ARRAY_HEADER(array)->count)
6778#define si_func_to_SEL(class_name, function) si_impl_func_to_SEL_with_name(class_name, #function":", function)
6779 /* Creates an Objective-C method (SEL) from a regular C function with the option to set the register name.*/
6780#define si_func_to_SEL_with_name(class_name, register_name, function) si_impl_func_to_SEL_with_name(class_name, register_name":", function)
6781
6782 unsigned char* NSBitmapImageRep_bitmapData(NSBitmapImageRep* imageRep) {
6783 return ((unsigned char* (*)(id, SEL))objc_msgSend)
6784 (imageRep, sel_registerName("bitmapData"));
6785 }
6786
6787#define NS_ENUM(type, name) type name; enum
6788
6789 typedef NS_ENUM(NSUInteger, NSBitmapFormat) {
6790 NSBitmapFormatAlphaFirst = 1 << 0, // 0 means is alpha last (RGBA, CMYKA, etc.)
6791 NSBitmapFormatAlphaNonpremultiplied = 1 << 1, // 0 means is premultiplied
6792 NSBitmapFormatFloatingPointSamples = 1 << 2, // 0 is integer
6793
6794 NSBitmapFormatSixteenBitLittleEndian API_AVAILABLE(macos(10.10)) = (1 << 8),
6795 NSBitmapFormatThirtyTwoBitLittleEndian API_AVAILABLE(macos(10.10)) = (1 << 9),
6796 NSBitmapFormatSixteenBitBigEndian API_AVAILABLE(macos(10.10)) = (1 << 10),
6797 NSBitmapFormatThirtyTwoBitBigEndian API_AVAILABLE(macos(10.10)) = (1 << 11)
6798 };
6799
6800 NSBitmapImageRep* NSBitmapImageRep_initWithBitmapData(unsigned char** planes, NSInteger width, NSInteger height, NSInteger bps, NSInteger spp, bool alpha, bool isPlanar, const char* colorSpaceName, NSBitmapFormat bitmapFormat, NSInteger rowBytes, NSInteger pixelBits) {
6801 void* func = sel_registerName("initWithBitmapDataPlanes:pixelsWide:pixelsHigh:bitsPerSample:samplesPerPixel:hasAlpha:isPlanar:colorSpaceName:bitmapFormat:bytesPerRow:bitsPerPixel:");
6802
6803 return (NSBitmapImageRep*) ((id(*)(id, SEL, unsigned char**, NSInteger, NSInteger, NSInteger, NSInteger, bool, bool, const char*, NSBitmapFormat, NSInteger, NSInteger))objc_msgSend)
6804 (NSAlloc((id)objc_getClass("NSBitmapImageRep")), func, planes, width, height, bps, spp, alpha, isPlanar, NSString_stringWithUTF8String(colorSpaceName), bitmapFormat, rowBytes, pixelBits);
6805 }
6806
6807 NSColor* NSColor_colorWithSRGB(CGFloat red, CGFloat green, CGFloat blue, CGFloat alpha) {
6808 void* nsclass = objc_getClass("NSColor");
6809 void* func = sel_registerName("colorWithSRGBRed:green:blue:alpha:");
6810 return ((id(*)(id, SEL, CGFloat, CGFloat, CGFloat, CGFloat))objc_msgSend)
6811 (nsclass, func, red, green, blue, alpha);
6812 }
6813
6814 NSCursor* NSCursor_initWithImage(NSImage* newImage, NSPoint aPoint) {
6815 void* func = sel_registerName("initWithImage:hotSpot:");
6816 void* nsclass = objc_getClass("NSCursor");
6817
6818 return (NSCursor*) ((id(*)(id, SEL, id, NSPoint))objc_msgSend)
6819 (NSAlloc(nsclass), func, newImage, aPoint);
6820 }
6821
6822 void NSImage_addRepresentation(NSImage* image, NSImageRep* imageRep) {
6823 void* func = sel_registerName("addRepresentation:");
6824 objc_msgSend_void_id(image, func, imageRep);
6825 }
6826
6827 NSImage* NSImage_initWithSize(NSSize size) {
6828 void* func = sel_registerName("initWithSize:");
6829 return ((id(*)(id, SEL, NSSize))objc_msgSend)
6830 (NSAlloc((id)objc_getClass("NSImage")), func, size);
6831 }
6832#define NS_OPENGL_ENUM_DEPRECATED(minVers, maxVers) API_AVAILABLE(macos(minVers))
6833 typedef NS_ENUM(NSInteger, NSOpenGLContextParameter) {
6834 NSOpenGLContextParameterSwapInterval NS_OPENGL_ENUM_DEPRECATED(10.0, 10.14) = 222, /* 1 param. 0 -> Don't sync, 1 -> Sync to vertical retrace */
6835 NSOpenGLContextParametectxaceOrder NS_OPENGL_ENUM_DEPRECATED(10.0, 10.14) = 235, /* 1 param. 1 -> Above Window (default), -1 -> Below Window */
6836 NSOpenGLContextParametectxaceOpacity NS_OPENGL_ENUM_DEPRECATED(10.0, 10.14) = 236, /* 1 param. 1-> Surface is opaque (default), 0 -> non-opaque */
6837 NSOpenGLContextParametectxaceBackingSize NS_OPENGL_ENUM_DEPRECATED(10.0, 10.14) = 304, /* 2 params. Width/height of surface backing size */
6838 NSOpenGLContextParameterReclaimResources NS_OPENGL_ENUM_DEPRECATED(10.0, 10.14) = 308, /* 0 params. */
6839 NSOpenGLContextParameterCurrentRendererID NS_OPENGL_ENUM_DEPRECATED(10.0, 10.14) = 309, /* 1 param. Retrieves the current renderer ID */
6840 NSOpenGLContextParameterGPUVertexProcessing NS_OPENGL_ENUM_DEPRECATED(10.0, 10.14) = 310, /* 1 param. Currently processing vertices with GPU (get) */
6841 NSOpenGLContextParameterGPUFragmentProcessing NS_OPENGL_ENUM_DEPRECATED(10.0, 10.14) = 311, /* 1 param. Currently processing fragments with GPU (get) */
6842 NSOpenGLContextParameterHasDrawable NS_OPENGL_ENUM_DEPRECATED(10.0, 10.14) = 314, /* 1 param. Boolean returned if drawable is attached */
6843 NSOpenGLContextParameterMPSwapsInFlight NS_OPENGL_ENUM_DEPRECATED(10.0, 10.14) = 315, /* 1 param. Max number of swaps queued by the MP GL engine */
6844
6845 NSOpenGLContextParameterSwapRectangle API_DEPRECATED("", macos(10.0, 10.14)) = 200, /* 4 params. Set or get the swap rectangle {x, y, w, h} */
6846 NSOpenGLContextParameterSwapRectangleEnable API_DEPRECATED("", macos(10.0, 10.14)) = 201, /* Enable or disable the swap rectangle */
6847 NSOpenGLContextParameterRasterizationEnable API_DEPRECATED("", macos(10.0, 10.14)) = 221, /* Enable or disable all rasterization */
6848 NSOpenGLContextParameterStateValidation API_DEPRECATED("", macos(10.0, 10.14)) = 301, /* Validate state for multi-screen functionality */
6849 NSOpenGLContextParametectxaceSurfaceVolatile API_DEPRECATED("", macos(10.0, 10.14)) = 306, /* 1 param. Surface volatile state */
6850 };
6851
6852
6853 void NSOpenGLContext_setValues(NSOpenGLContext* context, const int* vals, NSOpenGLContextParameter param) {
6854 void* func = sel_registerName("setValues:forParameter:");
6855 ((void (*)(id, SEL, const int*, NSOpenGLContextParameter))objc_msgSend)
6856 (context, func, vals, param);
6857 }
6858
6859 void* NSOpenGLPixelFormat_initWithAttributes(const uint32_t* attribs) {
6860 void* func = sel_registerName("initWithAttributes:");
6861 return (void*) ((id(*)(id, SEL, const uint32_t*))objc_msgSend)
6862 (NSAlloc((id)objc_getClass("NSOpenGLPixelFormat")), func, attribs);
6863 }
6864
6865 NSOpenGLView* NSOpenGLView_initWithFrame(NSRect frameRect, uint32_t* format) {
6866 void* func = sel_registerName("initWithFrame:pixelFormat:");
6867 return (NSOpenGLView*) ((id(*)(id, SEL, NSRect, uint32_t*))objc_msgSend)
6868 (NSAlloc((id)objc_getClass("NSOpenGLView")), func, frameRect, format);
6869 }
6870
6871 void NSCursor_performSelector(NSCursor* cursor, void* selector) {
6872 void* func = sel_registerName("performSelector:");
6873 objc_msgSend_void_SEL(cursor, func, selector);
6874 }
6875
6876 NSPasteboard* NSPasteboard_generalPasteboard(void) {
6877 return (NSPasteboard*) objc_msgSend_id((id)objc_getClass("NSPasteboard"), sel_registerName("generalPasteboard"));
6878 }
6879
6880 NSString** cstrToNSStringArray(char** strs, size_t len) {
6881 static NSString* nstrs[6];
6882 size_t i;
6883 for (i = 0; i < len; i++)
6884 nstrs[i] = NSString_stringWithUTF8String(strs[i]);
6885
6886 return nstrs;
6887 }
6888
6889 const char* NSPasteboard_stringForType(NSPasteboard* pasteboard, NSPasteboardType dataType) {
6890 void* func = sel_registerName("stringForType:");
6891 return (const char*) NSString_to_char(((id(*)(id, SEL, const char*))objc_msgSend)(pasteboard, func, NSString_stringWithUTF8String(dataType)));
6892 }
6893
6894 NSArray* c_array_to_NSArray(void* array, size_t len) {
6895 SEL func = sel_registerName("initWithObjects:count:");
6896 void* nsclass = objc_getClass("NSArray");
6897 return ((id (*)(id, SEL, void*, NSUInteger))objc_msgSend)
6898 (NSAlloc(nsclass), func, array, len);
6899 }
6900
6901 void NSregisterForDraggedTypes(void* view, NSPasteboardType* newTypes, size_t len) {
6902 NSString** ntypes = cstrToNSStringArray((char**)newTypes, len);
6903
6904 NSArray* array = c_array_to_NSArray(ntypes, len);
6905 objc_msgSend_void_id(view, sel_registerName("registerForDraggedTypes:"), array);
6906 NSRelease(array);
6907 }
6908
6909 NSInteger NSPasteBoard_declareTypes(NSPasteboard* pasteboard, NSPasteboardType* newTypes, size_t len, void* owner) {
6910 NSString** ntypes = cstrToNSStringArray((char**)newTypes, len);
6911
6912 void* func = sel_registerName("declareTypes:owner:");
6913
6914 NSArray* array = c_array_to_NSArray(ntypes, len);
6915
6916 NSInteger output = ((NSInteger(*)(id, SEL, id, void*))objc_msgSend)
6917 (pasteboard, func, array, owner);
6918 NSRelease(array);
6919
6920 return output;
6921 }
6922
6923 bool NSPasteBoard_setString(NSPasteboard* pasteboard, const char* stringToWrite, NSPasteboardType dataType) {
6924 void* func = sel_registerName("setString:forType:");
6925 return ((bool (*)(id, SEL, id, NSPasteboardType))objc_msgSend)
6926 (pasteboard, func, NSString_stringWithUTF8String(stringToWrite), NSString_stringWithUTF8String(dataType));
6927 }
6928
6929 void NSRetain(id obj) { objc_msgSend_void(obj, sel_registerName("retain")); }
6930
6931 typedef enum NSApplicationActivationPolicy {
6932 NSApplicationActivationPolicyRegular,
6933 NSApplicationActivationPolicyAccessory,
6934 NSApplicationActivationPolicyProhibited
6935 } NSApplicationActivationPolicy;
6936
6937 typedef NS_ENUM(u32, NSBackingStoreType) {
6938 NSBackingStoreRetained = 0,
6939 NSBackingStoreNonretained = 1,
6940 NSBackingStoreBuffered = 2
6941 };
6942
6943 typedef NS_ENUM(u32, NSWindowStyleMask) {
6944 NSWindowStyleMaskBorderless = 0,
6945 NSWindowStyleMaskTitled = 1 << 0,
6946 NSWindowStyleMaskClosable = 1 << 1,
6947 NSWindowStyleMaskMiniaturizable = 1 << 2,
6948 NSWindowStyleMaskResizable = 1 << 3,
6949 NSWindowStyleMaskTexturedBackground = 1 << 8, /* deprecated */
6950 NSWindowStyleMaskUnifiedTitleAndToolbar = 1 << 12,
6951 NSWindowStyleMaskFullScreen = 1 << 14,
6952 NSWindowStyleMaskFullSizeContentView = 1 << 15,
6953 NSWindowStyleMaskUtilityWindow = 1 << 4,
6954 NSWindowStyleMaskDocModalWindow = 1 << 6,
6955 NSWindowStyleMaskNonactivatingPanel = 1 << 7,
6956 NSWindowStyleMaskHUDWindow = 1 << 13
6957 };
6958
6959 NSPasteboardType const NSPasteboardTypeString = "public.utf8-plain-text"; // Replaces NSStringPboardType
6960
6961
6962 typedef NS_ENUM(i32, NSDragOperation) {
6963 NSDragOperationNone = 0,
6964 NSDragOperationCopy = 1,
6965 NSDragOperationLink = 2,
6966 NSDragOperationGeneric = 4,
6967 NSDragOperationPrivate = 8,
6968 NSDragOperationMove = 16,
6969 NSDragOperationDelete = 32,
6970 NSDragOperationEvery = ULONG_MAX,
6971
6972 //NSDragOperationAll_Obsolete API_DEPRECATED("", macos(10.0,10.10)) = 15, // Use NSDragOperationEvery
6973 //NSDragOperationAll API_DEPRECATED("", macos(10.0,10.10)) = NSDragOperationAll_Obsolete, // Use NSDragOperationEvery
6974 };
6975
6976 void* NSArray_objectAtIndex(NSArray* array, NSUInteger index) {
6977 void* func = sel_registerName("objectAtIndex:");
6978 return ((id(*)(id, SEL, NSUInteger))objc_msgSend)(array, func, index);
6979 }
6980
6981 const char** NSPasteboard_readObjectsForClasses(NSPasteboard* pasteboard, Class* classArray, size_t len, void* options) {
6982 void* func = sel_registerName("readObjectsForClasses:options:");
6983
6984 NSArray* array = c_array_to_NSArray(classArray, len);
6985
6986 NSArray* output = (NSArray*) ((id(*)(id, SEL, id, void*))objc_msgSend)
6987 (pasteboard, func, array, options);
6988
6989 NSRelease(array);
6990 NSUInteger count = ((NSUInteger(*)(id, SEL))objc_msgSend)(output, sel_registerName("count"));
6991
6992 const char** res = si_array_init_reserve(sizeof(const char*), count);
6993
6994 void* path_func = sel_registerName("path");
6995
6996 for (NSUInteger i = 0; i < count; i++) {
6997 void* url = NSArray_objectAtIndex(output, i);
6998 NSString* url_str = ((id(*)(id, SEL))objc_msgSend)(url, path_func);
6999 res[i] = NSString_to_char(url_str);
7000 }
7001
7002 return res;
7003 }
7004
7005 void* NSWindow_contentView(NSWindow* window) {
7006 void* func = sel_registerName("contentView");
7007 return objc_msgSend_id(window, func);
7008 }
7009
7010 /*
7011 End of cocoa wrapper
7012 */
7013
7014 char* RGFW_mouseIconSrc[] = {"arrowCursor", "arrowCursor", "IBeamCursor", "crosshairCursor", "pointingHandCursor", "resizeLeftRightCursor", "resizeUpDownCursor", "_windowResizeNorthWestSouthEastCursor", "_windowResizeNorthEastSouthWestCursor", "closedHandCursor", "operationNotAllowedCursor"};
7015
7016 void* RGFWnsglFramework = NULL;
7017
7018#ifdef RGFW_OPENGL
7019 void* RGFW_getProcAddress(const char* procname) {
7020 if (RGFWnsglFramework == NULL)
7021 RGFWnsglFramework = CFBundleGetBundleWithIdentifier(CFSTR("com.apple.opengl"));
7022
7023 CFStringRef symbolName = CFStringCreateWithCString(kCFAllocatorDefault, procname, kCFStringEncodingASCII);
7024
7025 void* symbol = CFBundleGetFunctionPointerForName(RGFWnsglFramework, symbolName);
7026
7027 CFRelease(symbolName);
7028
7029 return symbol;
7030 }
7031#endif
7032
7033 CVReturn displayCallback(CVDisplayLinkRef displayLink, const CVTimeStamp* inNow, const CVTimeStamp* inOutputTime, CVOptionFlags flagsIn, CVOptionFlags* flagsOut, void* displayLinkContext) {
7034 RGFW_UNUSED(displayLink) RGFW_UNUSED(inNow) RGFW_UNUSED(inOutputTime) RGFW_UNUSED(flagsIn) RGFW_UNUSED(flagsOut) RGFW_UNUSED(displayLinkContext)
7035 return kCVReturnSuccess;
7036 }
7037
7038 id NSWindow_delegate(RGFW_window* win) {
7039 return (id) objc_msgSend_id(win->src.window, sel_registerName("delegate"));
7040 }
7041
7042 u32 RGFW_OnClose(void* self) {
7043 RGFW_window* win = NULL;
7044 object_getInstanceVariable(self, "RGFW_window", (void*)&win);
7045 if (win == NULL)
7046 return true;
7047
7048 win->event.type = RGFW_quit;
7049 RGFW_windowQuitCallback(win);
7050
7051 return true;
7052 }
7053
7054 /* NOTE(EimaMei): Fixes the constant clicking when the app is running under a terminal. */
7055 bool acceptsFirstResponder(void) { return true; }
7056 bool performKeyEquivalent(NSEvent* event) { RGFW_UNUSED(event); return true; }
7057
7058 NSDragOperation draggingEntered(id self, SEL sel, id sender) {
7059 RGFW_UNUSED(sender); RGFW_UNUSED(self); RGFW_UNUSED(sel);
7060
7061 return NSDragOperationCopy;
7062 }
7063 NSDragOperation draggingUpdated(id self, SEL sel, id sender) {
7064 RGFW_UNUSED(sel);
7065
7066 RGFW_window* win = NULL;
7067 object_getInstanceVariable(self, "RGFW_window", (void*)&win);
7068 if (win == NULL)
7069 return 0;
7070
7071 if (!(win->_winArgs & RGFW_ALLOW_DND)) {
7072 return 0;
7073 }
7074
7075 win->event.type = RGFW_dnd_init;
7076 win->src.dndPassed = 0;
7077
7078 NSPoint p = ((NSPoint(*)(id, SEL)) objc_msgSend)(sender, sel_registerName("draggingLocation"));
7079
7080 win->event.point = RGFW_POINT((u32) p.x, (u32) (win->r.h - p.y));
7081 RGFW_dndInitCallback(win, win->event.point);
7082
7083 return NSDragOperationCopy;
7084 }
7085 bool prepareForDragOperation(id self) {
7086 RGFW_window* win = NULL;
7087 object_getInstanceVariable(self, "RGFW_window", (void*)&win);
7088 if (win == NULL)
7089 return true;
7090
7091 if (!(win->_winArgs & RGFW_ALLOW_DND)) {
7092 return false;
7093 }
7094
7095 return true;
7096 }
7097
7098 void RGFW__osxDraggingEnded(id self, SEL sel, id sender) { RGFW_UNUSED(sender); RGFW_UNUSED(self); RGFW_UNUSED(sel); return; }
7099
7100 /* NOTE(EimaMei): Usually, you never need 'id self, SEL cmd' for C -> Obj-C methods. This isn't the case. */
7101 bool performDragOperation(id self, SEL sel, id sender) {
7102 RGFW_UNUSED(sender); RGFW_UNUSED(self); RGFW_UNUSED(sel);
7103
7104 RGFW_window* win = NULL;
7105 object_getInstanceVariable(self, "RGFW_window", (void*)&win);
7106
7107 if (win == NULL)
7108 return false;
7109
7110 // NSPasteboard* pasteBoard = objc_msgSend_id(sender, sel_registerName("draggingPasteboard"));
7111
7112 /////////////////////////////
7113 id pasteBoard = objc_msgSend_id(sender, sel_registerName("draggingPasteboard"));
7114
7115 // Get the types of data available on the pasteboard
7116 id types = objc_msgSend_id(pasteBoard, sel_registerName("types"));
7117
7118 // Get the string type for file URLs
7119 id fileURLsType = objc_msgSend_class_char(objc_getClass("NSString"), sel_registerName("stringWithUTF8String:"), "NSFilenamesPboardType");
7120
7121 // Check if the pasteboard contains file URLs
7122 if (objc_msgSend_id_bool(types, sel_registerName("containsObject:"), fileURLsType) == 0) {
7123 #ifdef RGFW_DEBUG
7124 printf("No files found on the pasteboard.\n");
7125 #endif
7126
7127 return 0;
7128 }
7129
7130 id fileURLs = objc_msgSend_id_id(pasteBoard, sel_registerName("propertyListForType:"), fileURLsType);
7131 int count = ((int (*)(id, SEL))objc_msgSend)(fileURLs, sel_registerName("count"));
7132
7133 if (count == 0)
7134 return 0;
7135
7136 for (int i = 0; i < count; i++) {
7137 id fileURL = objc_msgSend_arr(fileURLs, sel_registerName("objectAtIndex:"), i);
7138 const char *filePath = ((const char* (*)(id, SEL))objc_msgSend)(fileURL, sel_registerName("UTF8String"));
7139 strncpy(win->event.droppedFiles[i], filePath, RGFW_MAX_PATH);
7140 win->event.droppedFiles[i][RGFW_MAX_PATH - 1] = '\0';
7141 }
7142 win->event.droppedFilesCount = count;
7143
7144 win->event.type = RGFW_dnd;
7145 win->src.dndPassed = 0;
7146
7147 NSPoint p = ((NSPoint(*)(id, SEL)) objc_msgSend)(sender, sel_registerName("draggingLocation"));
7148 win->event.point = RGFW_POINT((u32) p.x, (u32) (win->r.h - p.y));
7149
7150 RGFW_dndCallback(win, win->event.droppedFiles, win->event.droppedFilesCount);
7151
7152 return false;
7153 }
7154
7155 static void NSMoveToResourceDir(void) {
7156 /* sourced from glfw */
7157 char resourcesPath[255];
7158
7159 CFBundleRef bundle = CFBundleGetMainBundle();
7160 if (!bundle)
7161 return;
7162
7163 CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(bundle);
7164 CFStringRef last = CFURLCopyLastPathComponent(resourcesURL);
7165
7166 if (
7167 CFStringCompare(CFSTR("Resources"), last, 0) != kCFCompareEqualTo ||
7168 CFURLGetFileSystemRepresentation(resourcesURL, true, (u8*) resourcesPath, 255) == 0
7169 ) {
7170 CFRelease(last);
7171 CFRelease(resourcesURL);
7172 return;
7173 }
7174
7175 CFRelease(last);
7176 CFRelease(resourcesURL);
7177
7178 chdir(resourcesPath);
7179 }
7180
7181
7182 NSSize RGFW__osxWindowResize(void* self, SEL sel, NSSize frameSize) {
7183 RGFW_UNUSED(sel);
7184
7185 RGFW_window* win = NULL;
7186 object_getInstanceVariable(self, "RGFW_window", (void*)&win);
7187 if (win == NULL)
7188 return frameSize;
7189
7190 win->r.w = frameSize.width;
7191 win->r.h = frameSize.height;
7192 win->event.type = RGFW_windowResized;
7193 RGFW_windowResizeCallback(win, win->r);
7194 return frameSize;
7195 }
7196
7197 void RGFW__osxWindowMove(void* self, SEL sel) {
7198 RGFW_UNUSED(sel);
7199
7200 RGFW_window* win = NULL;
7201 object_getInstanceVariable(self, "RGFW_window", (void*)&win);
7202 if (win == NULL)
7203 return;
7204
7205 NSRect frame = ((NSRect(*)(id, SEL))abi_objc_msgSend_stret)(win->src.window, sel_registerName("frame"));
7206 win->r.x = (i32) frame.origin.x;
7207 win->r.y = (i32) frame.origin.y;
7208
7209 win->event.type = RGFW_windowMoved;
7210 RGFW_windowMoveCallback(win, win->r);
7211 }
7212
7213 void RGFW__osxUpdateLayer(void* self, SEL sel) {
7214 RGFW_UNUSED(sel);
7215
7216 RGFW_window* win = NULL;
7217 object_getInstanceVariable(self, "RGFW_window", (void*)&win);
7218 if (win == NULL)
7219 return;
7220
7221 win->event.type = RGFW_windowRefresh;
7222 RGFW_windowRefreshCallback(win);
7223 }
7224
7225 RGFWDEF void RGFW_init_buffer(RGFW_window* win);
7226 void RGFW_init_buffer(RGFW_window* win) {
7227 #if defined(RGFW_OSMESA) || defined(RGFW_BUFFER)
7228 if (RGFW_bufferSize.w == 0 && RGFW_bufferSize.h == 0)
7229 RGFW_bufferSize = RGFW_getScreenSize();
7230
7231 win->buffer = RGFW_MALLOC(RGFW_bufferSize.w * RGFW_bufferSize.h * 4);
7232
7233 #ifdef RGFW_OSMESA
7234 win->src.ctx = OSMesaCreateContext(OSMESA_RGBA, NULL);
7235 OSMesaMakeCurrent(win->src.ctx, win->buffer, GL_UNSIGNED_BYTE, win->r.w, win->r.h);
7236 #endif
7237 #else
7238 RGFW_UNUSED(win); /*!< if buffer rendering is not being used */
7239 #endif
7240 }
7241
7242
7243 void RGFW_window_cocoaSetLayer(RGFW_window* win, void* layer) {
7244 objc_msgSend_void_id(win->src.view, sel_registerName("setLayer"), layer);
7245 }
7246
7247 void* RGFW_cocoaGetLayer(void) {
7248 return objc_msgSend_class(objc_getClass("CAMetalLayer"), sel_registerName("layer"));
7249 }
7250
7251
7252 NSPasteboardType const NSPasteboardTypeURL = "public.url";
7253 NSPasteboardType const NSPasteboardTypeFileURL = "public.file-url";
7254
7255 RGFW_window* RGFW_createWindow(const char* name, RGFW_rect rect, u16 args) {
7256 static u8 RGFW_loaded = 0;
7257
7258 /* NOTE(EimaMei): Why does Apple hate good code? Like wtf, who thought of methods being a great idea???
7259 Imagine a universe, where MacOS had a proper system API (we would probably have like 20% better performance).
7260 */
7261 si_func_to_SEL_with_name("NSObject", "windowShouldClose", RGFW_OnClose);
7262
7263 /* NOTE(EimaMei): Fixes the 'Boop' sfx from constantly playing each time you click a key. Only a problem when running in the terminal. */
7264 si_func_to_SEL("NSWindow", acceptsFirstResponder);
7265 si_func_to_SEL("NSWindow", performKeyEquivalent);
7266
7267 // RR Create an autorelease pool
7268 id pool = objc_msgSend_class(objc_getClass("NSAutoreleasePool"), sel_registerName("alloc"));
7269 pool = objc_msgSend_id(pool, sel_registerName("init"));
7270
7271 if (NSApp == NULL) {
7272 NSApp = objc_msgSend_id((id)objc_getClass("NSApplication"), sel_registerName("sharedApplication"));
7273
7274 ((void (*)(id, SEL, NSUInteger))objc_msgSend)
7275 (NSApp, sel_registerName("setActivationPolicy:"), NSApplicationActivationPolicyRegular);
7276 }
7277
7278 RGFW_window* win = RGFW_window_basic_init(rect, args);
7279
7280 RGFW_window_setMouseDefault(win);
7281
7282 NSRect windowRect;
7283 windowRect.origin.x = win->r.x;
7284 windowRect.origin.y = win->r.y;
7285 windowRect.size.width = win->r.w;
7286 windowRect.size.height = win->r.h;
7287
7288 NSBackingStoreType macArgs = NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | NSBackingStoreBuffered | NSWindowStyleMaskTitled;
7289
7290 if (!(args & RGFW_NO_RESIZE))
7291 macArgs |= NSWindowStyleMaskResizable;
7292 if (!(args & RGFW_NO_BORDER))
7293 macArgs |= NSWindowStyleMaskTitled;
7294 else
7295 macArgs = NSWindowStyleMaskBorderless;
7296 {
7297 void* nsclass = objc_getClass("NSWindow");
7298 void* func = sel_registerName("initWithContentRect:styleMask:backing:defer:");
7299
7300 win->src.window = ((id(*)(id, SEL, NSRect, NSWindowStyleMask, NSBackingStoreType, bool))objc_msgSend)
7301 (NSAlloc(nsclass), func, windowRect, macArgs, macArgs, false);
7302 }
7303
7304 NSString* str = NSString_stringWithUTF8String(name);
7305 objc_msgSend_void_id(win->src.window, sel_registerName("setTitle:"), str);
7306
7307#ifdef RGFW_EGL
7308 if ((args & RGFW_NO_INIT_API) == 0)
7309 RGFW_createOpenGLContext(win);
7310#endif
7311
7312#ifdef RGFW_OPENGL
7313 if ((args & RGFW_NO_INIT_API) == 0) {
7314 void* attrs = RGFW_initFormatAttribs(args & RGFW_OPENGL_SOFTWARE);
7315 void* format = NSOpenGLPixelFormat_initWithAttributes(attrs);
7316
7317 if (format == NULL) {
7318 printf("Failed to load pixel format for OpenGL\n");
7319
7320 void* attrs = RGFW_initFormatAttribs(1);
7321 format = NSOpenGLPixelFormat_initWithAttributes(attrs);
7322 if (format == NULL)
7323 printf("and loading software rendering OpenGL failed\n");
7324 else
7325 printf("Switching to software rendering\n");
7326 }
7327
7328 /* the pixel format can be passed directly to opengl context creation to create a context
7329 this is because the format also includes information about the opengl version (which may be a bad thing) */
7330 win->src.view = NSOpenGLView_initWithFrame((NSRect){{0, 0}, {win->r.w, win->r.h}}, format);
7331 objc_msgSend_void(win->src.view, sel_registerName("prepareOpenGL"));
7332 win->src.ctx = objc_msgSend_id(win->src.view, sel_registerName("openGLContext"));
7333 } else
7334#endif
7335 {
7336 NSRect contentRect = (NSRect){{0, 0}, {win->r.w, win->r.h}};
7337 win->src.view = ((id(*)(id, SEL, NSRect))objc_msgSend)
7338 (NSAlloc((id)objc_getClass("NSView")), sel_registerName("initWithFrame:"),
7339 contentRect);
7340 }
7341
7342 void* contentView = NSWindow_contentView(win->src.window);
7343 objc_msgSend_void_bool(contentView, sel_registerName("setWantsLayer:"), true);
7344
7345 objc_msgSend_void_id(win->src.window, sel_registerName("setContentView:"), win->src.view);
7346
7347#ifdef RGFW_OPENGL
7348 if ((args & RGFW_NO_INIT_API) == 0)
7349 objc_msgSend_void(win->src.ctx, sel_registerName("makeCurrentContext"));
7350#endif
7351 if (args & RGFW_TRANSPARENT_WINDOW) {
7352#ifdef RGFW_OPENGL
7353 if ((args & RGFW_NO_INIT_API) == 0) {
7354 i32 opacity = 0;
7355 #define NSOpenGLCPSurfaceOpacity 236
7356 NSOpenGLContext_setValues(win->src.ctx, &opacity, NSOpenGLCPSurfaceOpacity);
7357 }
7358#endif
7359
7360 objc_msgSend_void_bool(win->src.window, sel_registerName("setOpaque:"), false);
7361
7362 objc_msgSend_void_id(win->src.window, sel_registerName("setBackgroundColor:"),
7363 NSColor_colorWithSRGB(0, 0, 0, 0));
7364 }
7365
7366 win->src.display = CGMainDisplayID();
7367 CVDisplayLinkCreateWithCGDisplay(win->src.display, (CVDisplayLinkRef*)&win->src.displayLink);
7368 CVDisplayLinkSetOutputCallback(win->src.displayLink, displayCallback, win);
7369 CVDisplayLinkStart(win->src.displayLink);
7370
7371 RGFW_init_buffer(win);
7372
7373 #ifndef RGFW_NO_MONITOR
7374 if (args & RGFW_SCALE_TO_MONITOR)
7375 RGFW_window_scaleToMonitor(win);
7376 #endif
7377
7378 if (args & RGFW_CENTER) {
7379 RGFW_area screenR = RGFW_getScreenSize();
7380 RGFW_window_move(win, RGFW_POINT((screenR.w - win->r.w) / 2, (screenR.h - win->r.h) / 2));
7381 }
7382
7383 if (args & RGFW_HIDE_MOUSE)
7384 RGFW_window_showMouse(win, 0);
7385
7386 if (args & RGFW_COCOA_MOVE_TO_RESOURCE_DIR)
7387 NSMoveToResourceDir();
7388
7389 Class delegateClass = objc_allocateClassPair(objc_getClass("NSObject"), "WindowDelegate", 0);
7390
7391 class_addIvar(
7392 delegateClass, "RGFW_window",
7393 sizeof(RGFW_window*), rint(log2(sizeof(RGFW_window*))),
7394 "L"
7395 );
7396
7397 class_addMethod(delegateClass, sel_registerName("windowWillResize:toSize:"), (IMP) RGFW__osxWindowResize, "{NSSize=ff}@:{NSSize=ff}");
7398 class_addMethod(delegateClass, sel_registerName("updateLayer:"), (IMP) RGFW__osxUpdateLayer, "");
7399 class_addMethod(delegateClass, sel_registerName("windowWillMove:"), (IMP) RGFW__osxWindowMove, "");
7400 class_addMethod(delegateClass, sel_registerName("windowDidMove:"), (IMP) RGFW__osxWindowMove, "");
7401 class_addMethod(delegateClass, sel_registerName("draggingEntered:"), (IMP)draggingEntered, "l@:@");
7402 class_addMethod(delegateClass, sel_registerName("draggingUpdated:"), (IMP)draggingUpdated, "l@:@");
7403 class_addMethod(delegateClass, sel_registerName("draggingExited:"), (IMP)RGFW__osxDraggingEnded, "v@:@");
7404 class_addMethod(delegateClass, sel_registerName("draggingEnded:"), (IMP)RGFW__osxDraggingEnded, "v@:@");
7405 class_addMethod(delegateClass, sel_registerName("prepareForDragOperation:"), (IMP)prepareForDragOperation, "B@:@");
7406 class_addMethod(delegateClass, sel_registerName("performDragOperation:"), (IMP)performDragOperation, "B@:@");
7407
7408 id delegate = objc_msgSend_id(NSAlloc(delegateClass), sel_registerName("init"));
7409
7410 object_setInstanceVariable(delegate, "RGFW_window", win);
7411
7412 objc_msgSend_void_id(win->src.window, sel_registerName("setDelegate:"), delegate);
7413
7414 if (args & RGFW_ALLOW_DND) {
7415 win->_winArgs |= RGFW_ALLOW_DND;
7416
7417 NSPasteboardType types[] = {NSPasteboardTypeURL, NSPasteboardTypeFileURL, NSPasteboardTypeString};
7418 NSregisterForDraggedTypes(win->src.window, types, 3);
7419 }
7420
7421 // Show the window
7422 objc_msgSend_void_bool(NSApp, sel_registerName("activateIgnoringOtherApps:"), true);
7423 ((id(*)(id, SEL, SEL))objc_msgSend)(win->src.window, sel_registerName("makeKeyAndOrderFront:"), NULL);
7424 objc_msgSend_void_bool(win->src.window, sel_registerName("setIsVisible:"), true);
7425
7426 if (!RGFW_loaded) {
7427 objc_msgSend_void(win->src.window, sel_registerName("makeMainWindow"));
7428
7429 RGFW_loaded = 1;
7430 }
7431
7432 objc_msgSend_void(win->src.window, sel_registerName("makeKeyWindow"));
7433
7434 objc_msgSend_void(NSApp, sel_registerName("finishLaunching"));
7435
7436 if (RGFW_root == NULL)
7437 RGFW_root = win;
7438
7439 NSRetain(win->src.window);
7440 NSRetain(NSApp);
7441
7442 return win;
7443 }
7444
7445 void RGFW_window_setBorder(RGFW_window* win, u8 border) {
7446 NSBackingStoreType storeType = NSWindowStyleMaskBorderless;
7447 if (!border) {
7448 storeType = NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable;
7449 }
7450 if (!(win->_winArgs & RGFW_NO_RESIZE)) {
7451 storeType |= NSWindowStyleMaskResizable;
7452 }
7453
7454 ((void (*)(id, SEL, NSBackingStoreType))objc_msgSend)(win->src.window, sel_registerName("setStyleMask:"), storeType);
7455
7456 objc_msgSend_void_bool(win->src.window, sel_registerName("setHasShadow:"), border);
7457 }
7458
7459 RGFW_area RGFW_getScreenSize(void) {
7460 static CGDirectDisplayID display = 0;
7461
7462 if (display == 0)
7463 display = CGMainDisplayID();
7464
7465 return RGFW_AREA(CGDisplayPixelsWide(display), CGDisplayPixelsHigh(display));
7466 }
7467
7468 RGFW_point RGFW_getGlobalMousePoint(void) {
7469 assert(RGFW_root != NULL);
7470
7471 CGEventRef e = CGEventCreate(NULL);
7472 CGPoint point = CGEventGetLocation(e);
7473 CFRelease(e);
7474
7475 return RGFW_POINT((u32) point.x, (u32) point.y); /*!< the point is loaded during event checks */
7476 }
7477
7478 RGFW_point RGFW_window_getMousePoint(RGFW_window* win) {
7479 NSPoint p = ((NSPoint(*)(id, SEL)) objc_msgSend)(win->src.window, sel_registerName("mouseLocationOutsideOfEventStream"));
7480
7481 return RGFW_POINT((u32) p.x, (u32) (win->r.h - p.y));
7482 }
7483
7484 u32 RGFW_keysPressed[10]; /*10 keys at a time*/
7485 typedef NS_ENUM(u32, NSEventType) { /* various types of events */
7486 NSEventTypeLeftMouseDown = 1,
7487 NSEventTypeLeftMouseUp = 2,
7488 NSEventTypeRightMouseDown = 3,
7489 NSEventTypeRightMouseUp = 4,
7490 NSEventTypeMouseMoved = 5,
7491 NSEventTypeLeftMouseDragged = 6,
7492 NSEventTypeRightMouseDragged = 7,
7493 NSEventTypeMouseEntered = 8,
7494 NSEventTypeMouseExited = 9,
7495 NSEventTypeKeyDown = 10,
7496 NSEventTypeKeyUp = 11,
7497 NSEventTypeFlagsChanged = 12,
7498 NSEventTypeAppKitDefined = 13,
7499 NSEventTypeSystemDefined = 14,
7500 NSEventTypeApplicationDefined = 15,
7501 NSEventTypePeriodic = 16,
7502 NSEventTypeCursorUpdate = 17,
7503 NSEventTypeScrollWheel = 22,
7504 NSEventTypeTabletPoint = 23,
7505 NSEventTypeTabletProximity = 24,
7506 NSEventTypeOtherMouseDown = 25,
7507 NSEventTypeOtherMouseUp = 26,
7508 NSEventTypeOtherMouseDragged = 27,
7509 /* The following event types are available on some hardware on 10.5.2 and later */
7510 NSEventTypeGesture API_AVAILABLE(macos(10.5)) = 29,
7511 NSEventTypeMagnify API_AVAILABLE(macos(10.5)) = 30,
7512 NSEventTypeSwipe API_AVAILABLE(macos(10.5)) = 31,
7513 NSEventTypeRotate API_AVAILABLE(macos(10.5)) = 18,
7514 NSEventTypeBeginGesture API_AVAILABLE(macos(10.5)) = 19,
7515 NSEventTypeEndGesture API_AVAILABLE(macos(10.5)) = 20,
7516
7517 NSEventTypeSmartMagnify API_AVAILABLE(macos(10.8)) = 32,
7518 NSEventTypeQuickLook API_AVAILABLE(macos(10.8)) = 33,
7519
7520 NSEventTypePressure API_AVAILABLE(macos(10.10.3)) = 34,
7521 NSEventTypeDirectTouch API_AVAILABLE(macos(10.10)) = 37,
7522
7523 NSEventTypeChangeMode API_AVAILABLE(macos(10.15)) = 38,
7524 };
7525
7526 typedef NS_ENUM(unsigned long long, NSEventMask) { /* masks for the types of events */
7527 NSEventMaskLeftMouseDown = 1ULL << NSEventTypeLeftMouseDown,
7528 NSEventMaskLeftMouseUp = 1ULL << NSEventTypeLeftMouseUp,
7529 NSEventMaskRightMouseDown = 1ULL << NSEventTypeRightMouseDown,
7530 NSEventMaskRightMouseUp = 1ULL << NSEventTypeRightMouseUp,
7531 NSEventMaskMouseMoved = 1ULL << NSEventTypeMouseMoved,
7532 NSEventMaskLeftMouseDragged = 1ULL << NSEventTypeLeftMouseDragged,
7533 NSEventMaskRightMouseDragged = 1ULL << NSEventTypeRightMouseDragged,
7534 NSEventMaskMouseEntered = 1ULL << NSEventTypeMouseEntered,
7535 NSEventMaskMouseExited = 1ULL << NSEventTypeMouseExited,
7536 NSEventMaskKeyDown = 1ULL << NSEventTypeKeyDown,
7537 NSEventMaskKeyUp = 1ULL << NSEventTypeKeyUp,
7538 NSEventMaskFlagsChanged = 1ULL << NSEventTypeFlagsChanged,
7539 NSEventMaskAppKitDefined = 1ULL << NSEventTypeAppKitDefined,
7540 NSEventMaskSystemDefined = 1ULL << NSEventTypeSystemDefined,
7541 NSEventMaskApplicationDefined = 1ULL << NSEventTypeApplicationDefined,
7542 NSEventMaskPeriodic = 1ULL << NSEventTypePeriodic,
7543 NSEventMaskCursorUpdate = 1ULL << NSEventTypeCursorUpdate,
7544 NSEventMaskScrollWheel = 1ULL << NSEventTypeScrollWheel,
7545 NSEventMaskTabletPoint = 1ULL << NSEventTypeTabletPoint,
7546 NSEventMaskTabletProximity = 1ULL << NSEventTypeTabletProximity,
7547 NSEventMaskOtherMouseDown = 1ULL << NSEventTypeOtherMouseDown,
7548 NSEventMaskOtherMouseUp = 1ULL << NSEventTypeOtherMouseUp,
7549 NSEventMaskOtherMouseDragged = 1ULL << NSEventTypeOtherMouseDragged,
7550 /* The following event masks are available on some hardware on 10.5.2 and later */
7551 NSEventMaskGesture API_AVAILABLE(macos(10.5)) = 1ULL << NSEventTypeGesture,
7552 NSEventMaskMagnify API_AVAILABLE(macos(10.5)) = 1ULL << NSEventTypeMagnify,
7553 NSEventMaskSwipe API_AVAILABLE(macos(10.5)) = 1ULL << NSEventTypeSwipe,
7554 NSEventMaskRotate API_AVAILABLE(macos(10.5)) = 1ULL << NSEventTypeRotate,
7555 NSEventMaskBeginGesture API_AVAILABLE(macos(10.5)) = 1ULL << NSEventTypeBeginGesture,
7556 NSEventMaskEndGesture API_AVAILABLE(macos(10.5)) = 1ULL << NSEventTypeEndGesture,
7557
7558 /* Note: You can only use these event masks on 64 bit. In other words, you cannot setup a local, nor global, event monitor for these event types on 32 bit. Also, you cannot search the event queue for them (nextEventMatchingMask:...) on 32 bit.
7559 */
7560 NSEventMaskSmartMagnify API_AVAILABLE(macos(10.8)) = 1ULL << NSEventTypeSmartMagnify,
7561 NSEventMaskPressure API_AVAILABLE(macos(10.10.3)) = 1ULL << NSEventTypePressure,
7562 NSEventMaskDirectTouch API_AVAILABLE(macos(10.12.2)) = 1ULL << NSEventTypeDirectTouch,
7563
7564 NSEventMaskChangeMode API_AVAILABLE(macos(10.15)) = 1ULL << NSEventTypeChangeMode,
7565
7566 NSEventMaskAny = ULONG_MAX,
7567
7568 };
7569
7570 typedef enum NSEventModifierFlags {
7571 NSEventModifierFlagCapsLock = 1 << 16,
7572 NSEventModifierFlagShift = 1 << 17,
7573 NSEventModifierFlagControl = 1 << 18,
7574 NSEventModifierFlagOption = 1 << 19,
7575 NSEventModifierFlagCommand = 1 << 20,
7576 NSEventModifierFlagNumericPad = 1 << 21
7577 } NSEventModifierFlags;
7578
7579 void RGFW_stopCheckEvents(void) {
7580 id eventPool = objc_msgSend_class(objc_getClass("NSAutoreleasePool"), sel_registerName("alloc"));
7581 eventPool = objc_msgSend_id(eventPool, sel_registerName("init"));
7582
7583 NSEvent* e = (NSEvent*) ((id(*)(id, SEL, NSEventType, NSPoint, NSEventModifierFlags, void*, NSInteger, void**, short, NSInteger, NSInteger))objc_msgSend)
7584 (NSApp, sel_registerName("otherEventWithType:location:modifierFlags:timestamp:windowNumber:context:subtype:data1:data2:"),
7585 NSEventTypeApplicationDefined, (NSPoint){0, 0}, 0, 0, 0, NULL, 0, 0, 0);
7586
7587 ((void (*)(id, SEL, id, bool))objc_msgSend)
7588 (NSApp, sel_registerName("postEvent:atStart:"), e, 1);
7589
7590 objc_msgSend_bool_void(eventPool, sel_registerName("drain"));
7591 }
7592
7593 void RGFW_window_eventWait(RGFW_window* win, i32 waitMS) {
7594 RGFW_UNUSED(win);
7595
7596 id eventPool = objc_msgSend_class(objc_getClass("NSAutoreleasePool"), sel_registerName("alloc"));
7597 eventPool = objc_msgSend_id(eventPool, sel_registerName("init"));
7598
7599 void* date = (void*) ((id(*)(Class, SEL, double))objc_msgSend)
7600 (objc_getClass("NSDate"), sel_registerName("dateWithTimeIntervalSinceNow:"), waitMS);
7601
7602 NSEvent* e = (NSEvent*) ((id(*)(id, SEL, NSEventMask, void*, NSString*, bool))objc_msgSend)
7603 (NSApp, sel_registerName("nextEventMatchingMask:untilDate:inMode:dequeue:"),
7604 ULONG_MAX, date, NSString_stringWithUTF8String("kCFRunLoopDefaultMode"), true);
7605
7606
7607 if (e) {
7608 objc_msgSend_void_id(NSApp, sel_registerName("sendEvent:"), e);
7609 }
7610
7611 objc_msgSend_bool_void(eventPool, sel_registerName("drain"));
7612 }
7613
7614 RGFW_Event* RGFW_window_checkEvent(RGFW_window* win) {
7615 assert(win != NULL);
7616
7617 if (win->event.type == RGFW_quit)
7618 return NULL;
7619
7620 if ((win->event.type == RGFW_dnd || win->event.type == RGFW_dnd_init) && win->src.dndPassed == 0) {
7621 win->src.dndPassed = 1;
7622 return &win->event;
7623 }
7624
7625 id eventPool = objc_msgSend_class(objc_getClass("NSAutoreleasePool"), sel_registerName("alloc"));
7626 eventPool = objc_msgSend_id(eventPool, sel_registerName("init"));
7627
7628 static void* eventFunc = NULL;
7629 if (eventFunc == NULL)
7630 eventFunc = sel_registerName("nextEventMatchingMask:untilDate:inMode:dequeue:");
7631
7632 if ((win->event.type == RGFW_windowMoved || win->event.type == RGFW_windowResized || win->event.type == RGFW_windowRefresh) && win->event.keyCode != 120) {
7633 win->event.keyCode = 120;
7634 objc_msgSend_bool_void(eventPool, sel_registerName("drain"));
7635 return &win->event;
7636 }
7637
7638 void* date = NULL;
7639
7640 NSEvent* e = (NSEvent*) ((id(*)(id, SEL, NSEventMask, void*, NSString*, bool))objc_msgSend)
7641 (NSApp, eventFunc, ULONG_MAX, date, NSString_stringWithUTF8String("kCFRunLoopDefaultMode"), true);
7642
7643 if (e == NULL) {
7644 objc_msgSend_bool_void(eventPool, sel_registerName("drain"));
7645 return NULL;
7646 }
7647
7648 if (objc_msgSend_id(e, sel_registerName("window")) != win->src.window) {
7649 ((void (*)(id, SEL, id, bool))objc_msgSend)
7650 (NSApp, sel_registerName("postEvent:atStart:"), e, 0);
7651
7652 objc_msgSend_bool_void(eventPool, sel_registerName("drain"));
7653 return NULL;
7654 }
7655
7656 if (win->event.droppedFilesCount) {
7657 u32 i;
7658 for (i = 0; i < win->event.droppedFilesCount; i++)
7659 win->event.droppedFiles[i][0] = '\0';
7660 }
7661
7662 win->event.droppedFilesCount = 0;
7663 win->event.type = 0;
7664
7665 switch (objc_msgSend_uint(e, sel_registerName("type"))) {
7666 case NSEventTypeMouseEntered: {
7667 win->event.type = RGFW_mouseEnter;
7668 NSPoint p = ((NSPoint(*)(id, SEL)) objc_msgSend)(e, sel_registerName("locationInWindow"));
7669
7670 win->event.point = RGFW_POINT((i32) p.x, (i32) (win->r.h - p.y));
7671 RGFW_mouseNotifyCallBack(win, win->event.point, 1);
7672 break;
7673 }
7674
7675 case NSEventTypeMouseExited:
7676 win->event.type = RGFW_mouseLeave;
7677 RGFW_mouseNotifyCallBack(win, win->event.point, 0);
7678 break;
7679
7680 case NSEventTypeKeyDown: {
7681 u32 key = (u16) objc_msgSend_uint(e, sel_registerName("keyCode"));
7682 win->event.keyCode = RGFW_apiKeyCodeToRGFW(key);
7683 RGFW_keyboard[win->event.keyCode].prev = RGFW_keyboard[win->event.keyCode].current;
7684
7685 win->event.type = RGFW_keyPressed;
7686 char* str = (char*)(const char*) NSString_to_char(objc_msgSend_id(e, sel_registerName("characters")));
7687 strncpy(win->event.keyName, str, 16);
7688 win->event.repeat = RGFW_isPressed(win, win->event.keyCode);
7689 RGFW_keyboard[win->event.keyCode].current = 1;
7690
7691 RGFW_keyCallback(win, win->event.keyCode, win->event.keyName, win->event.lockState, 1);
7692 break;
7693 }
7694
7695 case NSEventTypeKeyUp: {
7696 u32 key = (u16) objc_msgSend_uint(e, sel_registerName("keyCode"));
7697 win->event.keyCode = RGFW_apiKeyCodeToRGFW(key);;
7698
7699 RGFW_keyboard[win->event.keyCode].prev = RGFW_keyboard[win->event.keyCode].current;
7700
7701 win->event.type = RGFW_keyReleased;
7702 char* str = (char*)(const char*) NSString_to_char(objc_msgSend_id(e, sel_registerName("characters")));
7703 strncpy(win->event.keyName, str, 16);
7704
7705 RGFW_keyboard[win->event.keyCode].current = 0;
7706 RGFW_keyCallback(win, win->event.keyCode, win->event.keyName, win->event.lockState, 0);
7707 break;
7708 }
7709
7710 case NSEventTypeFlagsChanged: {
7711 u32 flags = objc_msgSend_uint(e, sel_registerName("modifierFlags"));
7712 RGFW_updateLockState(win, ((u32)(flags & NSEventModifierFlagCapsLock) % 255), ((flags & NSEventModifierFlagNumericPad) % 255));
7713
7714 u8 i;
7715 for (i = 0; i < 9; i++)
7716 RGFW_keyboard[i + RGFW_CapsLock].prev = 0;
7717
7718 for (i = 0; i < 5; i++) {
7719 u32 shift = (1 << (i + 16));
7720 u32 key = i + RGFW_CapsLock;
7721
7722 if ((flags & shift) && !RGFW_wasPressed(win, key)) {
7723 RGFW_keyboard[key].current = 1;
7724
7725 if (key != RGFW_CapsLock)
7726 RGFW_keyboard[key+ 4].current = 1;
7727
7728 win->event.type = RGFW_keyPressed;
7729 win->event.keyCode = key;
7730 break;
7731 }
7732
7733 if (!(flags & shift) && RGFW_wasPressed(win, key)) {
7734 RGFW_keyboard[key].current = 0;
7735
7736 if (key != RGFW_CapsLock)
7737 RGFW_keyboard[key + 4].current = 0;
7738
7739 win->event.type = RGFW_keyReleased;
7740 win->event.keyCode = key;
7741 break;
7742 }
7743 }
7744
7745 RGFW_keyCallback(win, win->event.keyCode, win->event.keyName, win->event.lockState, win->event.type == RGFW_keyPressed);
7746
7747 break;
7748 }
7749 case NSEventTypeLeftMouseDragged:
7750 case NSEventTypeOtherMouseDragged:
7751 case NSEventTypeRightMouseDragged:
7752 case NSEventTypeMouseMoved:
7753 win->event.type = RGFW_mousePosChanged;
7754 NSPoint p = ((NSPoint(*)(id, SEL)) objc_msgSend)(e, sel_registerName("locationInWindow"));
7755 win->event.point = RGFW_POINT((u32) p.x, (u32) (win->r.h - p.y));
7756
7757 if ((win->_winArgs & RGFW_HOLD_MOUSE)) {
7758 p.x = ((CGFloat(*)(id, SEL))abi_objc_msgSend_fpret)(e, sel_registerName("deltaX"));
7759 p.y = ((CGFloat(*)(id, SEL))abi_objc_msgSend_fpret)(e, sel_registerName("deltaY"));
7760
7761 win->event.point = RGFW_POINT((i32)p.x, (i32)p.y);
7762 }
7763
7764 RGFW_mousePosCallback(win, win->event.point);
7765 break;
7766
7767 case NSEventTypeLeftMouseDown:
7768 win->event.button = RGFW_mouseLeft;
7769 win->event.type = RGFW_mouseButtonPressed;
7770 RGFW_mouseButtons[win->event.button].prev = RGFW_mouseButtons[win->event.button].current;
7771 RGFW_mouseButtons[win->event.button].current = 1;
7772 RGFW_mouseButtonCallback(win, win->event.button, win->event.scroll, 1);
7773 break;
7774
7775 case NSEventTypeOtherMouseDown:
7776 win->event.button = RGFW_mouseMiddle;
7777 win->event.type = RGFW_mouseButtonPressed;
7778 RGFW_mouseButtons[win->event.button].prev = RGFW_mouseButtons[win->event.button].current;
7779 RGFW_mouseButtons[win->event.button].current = 1;
7780 RGFW_mouseButtonCallback(win, win->event.button, win->event.scroll, 1);
7781 break;
7782
7783 case NSEventTypeRightMouseDown:
7784 win->event.button = RGFW_mouseRight;
7785 win->event.type = RGFW_mouseButtonPressed;
7786 RGFW_mouseButtons[win->event.button].prev = RGFW_mouseButtons[win->event.button].current;
7787 RGFW_mouseButtons[win->event.button].current = 1;
7788 RGFW_mouseButtonCallback(win, win->event.button, win->event.scroll, 1);
7789 break;
7790
7791 case NSEventTypeLeftMouseUp:
7792 win->event.button = RGFW_mouseLeft;
7793 win->event.type = RGFW_mouseButtonReleased;
7794 RGFW_mouseButtons[win->event.button].prev = RGFW_mouseButtons[win->event.button].current;
7795 RGFW_mouseButtons[win->event.button].current = 0;
7796 RGFW_mouseButtonCallback(win, win->event.button, win->event.scroll, 0);
7797 break;
7798
7799 case NSEventTypeOtherMouseUp:
7800 win->event.button = RGFW_mouseMiddle;
7801 RGFW_mouseButtons[win->event.button].prev = RGFW_mouseButtons[win->event.button].current;
7802 RGFW_mouseButtons[win->event.button].current = 0;
7803 win->event.type = RGFW_mouseButtonReleased;
7804 RGFW_mouseButtonCallback(win, win->event.button, win->event.scroll, 0);
7805 break;
7806
7807 case NSEventTypeRightMouseUp:
7808 win->event.button = RGFW_mouseRight;
7809 RGFW_mouseButtons[win->event.button].prev = RGFW_mouseButtons[win->event.button].current;
7810 RGFW_mouseButtons[win->event.button].current = 0;
7811 win->event.type = RGFW_mouseButtonReleased;
7812 RGFW_mouseButtonCallback(win, win->event.button, win->event.scroll, 0);
7813 break;
7814
7815 case NSEventTypeScrollWheel: {
7816 double deltaY = ((CGFloat(*)(id, SEL))abi_objc_msgSend_fpret)(e, sel_registerName("deltaY"));
7817
7818 if (deltaY > 0) {
7819 win->event.button = RGFW_mouseScrollUp;
7820 }
7821 else if (deltaY < 0) {
7822 win->event.button = RGFW_mouseScrollDown;
7823 }
7824
7825 RGFW_mouseButtons[win->event.button].prev = RGFW_mouseButtons[win->event.button].current;
7826 RGFW_mouseButtons[win->event.button].current = 1;
7827
7828 win->event.scroll = deltaY;
7829
7830 win->event.type = RGFW_mouseButtonPressed;
7831 RGFW_mouseButtonCallback(win, win->event.button, win->event.scroll, 1);
7832 break;
7833 }
7834
7835 default:
7836 break;
7837 }
7838
7839 objc_msgSend_void_id(NSApp, sel_registerName("sendEvent:"), e);
7840 ((void(*)(id, SEL))objc_msgSend)(NSApp, sel_registerName("updateWindows"));
7841
7842 objc_msgSend_bool_void(eventPool, sel_registerName("drain"));
7843 return &win->event;
7844 }
7845
7846
7847 void RGFW_window_move(RGFW_window* win, RGFW_point v) {
7848 assert(win != NULL);
7849
7850 win->r.x = v.x;
7851 win->r.y = v.y;
7852 ((void(*)(id, SEL, NSRect, bool, bool))objc_msgSend)
7853 (win->src.window, sel_registerName("setFrame:display:animate:"), (NSRect){{win->r.x, win->r.y}, {win->r.w, win->r.h}}, true, true);
7854 }
7855
7856 void RGFW_window_resize(RGFW_window* win, RGFW_area a) {
7857 assert(win != NULL);
7858
7859 win->r.w = a.w;
7860 win->r.h = a.h;
7861 ((void(*)(id, SEL, NSRect, bool, bool))objc_msgSend)
7862 (win->src.window, sel_registerName("setFrame:display:animate:"), (NSRect){{win->r.x, win->r.y}, {win->r.w, win->r.h}}, true, true);
7863 }
7864
7865 void RGFW_window_minimize(RGFW_window* win) {
7866 assert(win != NULL);
7867
7868 objc_msgSend_void_SEL(win->src.window, sel_registerName("performMiniaturize:"), NULL);
7869 }
7870
7871 void RGFW_window_restore(RGFW_window* win) {
7872 assert(win != NULL);
7873
7874 objc_msgSend_void_SEL(win->src.window, sel_registerName("deminiaturize:"), NULL);
7875 }
7876
7877 void RGFW_window_setName(RGFW_window* win, char* name) {
7878 assert(win != NULL);
7879
7880 NSString* str = NSString_stringWithUTF8String(name);
7881 objc_msgSend_void_id(win->src.window, sel_registerName("setTitle:"), str);
7882 }
7883
7884 #ifndef RGFW_NO_PASSTHROUGH
7885 void RGFW_window_setMousePassthrough(RGFW_window* win, b8 passthrough) {
7886 objc_msgSend_void_bool(win->src.window, sel_registerName("setIgnoresMouseEvents:"), passthrough);
7887 }
7888 #endif
7889
7890 void RGFW_window_setMinSize(RGFW_window* win, RGFW_area a) {
7891 if (a.w == 0 && a.h == 0)
7892 return;
7893
7894 ((void (*)(id, SEL, NSSize))objc_msgSend)
7895 (win->src.window, sel_registerName("setMinSize:"), (NSSize){a.w, a.h});
7896 }
7897
7898 void RGFW_window_setMaxSize(RGFW_window* win, RGFW_area a) {
7899 if (a.w == 0 && a.h == 0)
7900 return;
7901
7902 ((void (*)(id, SEL, NSSize))objc_msgSend)
7903 (win->src.window, sel_registerName("setMaxSize:"), (NSSize){a.w, a.h});
7904 }
7905
7906 void RGFW_window_setIcon(RGFW_window* win, u8* data, RGFW_area area, i32 channels) {
7907 assert(win != NULL);
7908
7909 /* code by EimaMei */
7910 // Make a bitmap representation, then copy the loaded image into it.
7911 void* representation = NSBitmapImageRep_initWithBitmapData(NULL, area.w, area.h, 8, channels, (channels == 4), false, "NSCalibratedRGBColorSpace", 1 << 1, area.w * channels, 8 * channels);
7912 memcpy(NSBitmapImageRep_bitmapData(representation), data, area.w * area.h * channels);
7913
7914 // Add ze representation.
7915 void* dock_image = NSImage_initWithSize((NSSize){area.w, area.h});
7916 NSImage_addRepresentation(dock_image, (void*) representation);
7917
7918 // Finally, set the dock image to it.
7919 objc_msgSend_void_id(NSApp, sel_registerName("setApplicationIconImage:"), dock_image);
7920 // Free the garbage.
7921 release(dock_image);
7922 release(representation);
7923 }
7924
7925 NSCursor* NSCursor_arrowStr(char* str) {
7926 void* nclass = objc_getClass("NSCursor");
7927 void* func = sel_registerName(str);
7928 return (NSCursor*) objc_msgSend_id(nclass, func);
7929 }
7930
7931 void RGFW_window_setMouse(RGFW_window* win, u8* image, RGFW_area a, i32 channels) {
7932 assert(win != NULL);
7933
7934 if (image == NULL) {
7935 objc_msgSend_void(NSCursor_arrowStr("arrowCursor"), sel_registerName("set"));
7936 return;
7937 }
7938
7939 /* NOTE(EimaMei): Code by yours truly. */
7940 // Make a bitmap representation, then copy the loaded image into it.
7941 void* representation = NSBitmapImageRep_initWithBitmapData(NULL, a.w, a.h, 8, channels, (channels == 4), false, "NSCalibratedRGBColorSpace", 1 << 1, a.w * channels, 8 * channels);
7942 memcpy(NSBitmapImageRep_bitmapData(representation), image, a.w * a.h * channels);
7943
7944 // Add ze representation.
7945 void* cursor_image = NSImage_initWithSize((NSSize){a.w, a.h});
7946 NSImage_addRepresentation(cursor_image, representation);
7947
7948 // Finally, set the cursor image.
7949 void* cursor = NSCursor_initWithImage(cursor_image, (NSPoint){0.0, 0.0});
7950
7951 objc_msgSend_void(cursor, sel_registerName("set"));
7952
7953 // Free the garbage.
7954 release(cursor_image);
7955 release(representation);
7956 }
7957
7958 void RGFW_window_setMouseDefault(RGFW_window* win) {
7959 RGFW_window_setMouseStandard(win, RGFW_MOUSE_ARROW);
7960 }
7961
7962 void RGFW_window_showMouse(RGFW_window* win, i8 show) {
7963 RGFW_UNUSED(win);
7964
7965 if (show) {
7966 CGDisplayShowCursor(kCGDirectMainDisplay);
7967 }
7968 else {
7969 CGDisplayHideCursor(kCGDirectMainDisplay);
7970 }
7971 }
7972
7973 void RGFW_window_setMouseStandard(RGFW_window* win, u8 stdMouses) {
7974 if (stdMouses > ((sizeof(RGFW_mouseIconSrc)) / (sizeof(char*))))
7975 return;
7976
7977 char* mouseStr = RGFW_mouseIconSrc[stdMouses];
7978 void* mouse = NSCursor_arrowStr(mouseStr);
7979
7980 if (mouse == NULL)
7981 return;
7982
7983 RGFW_UNUSED(win);
7984 CGDisplayShowCursor(kCGDirectMainDisplay);
7985 objc_msgSend_void(mouse, sel_registerName("set"));
7986 }
7987
7988 void RGFW_releaseCursor(RGFW_window* win) {
7989 RGFW_UNUSED(win);
7990 CGAssociateMouseAndMouseCursorPosition(1);
7991 }
7992
7993 void RGFW_captureCursor(RGFW_window* win, RGFW_rect r) {
7994 RGFW_UNUSED(win)
7995
7996 CGWarpMouseCursorPosition(CGPointMake(r.x + (r.w / 2), r.y + (r.h / 2)));
7997 CGAssociateMouseAndMouseCursorPosition(0);
7998 }
7999
8000 void RGFW_window_moveMouse(RGFW_window* win, RGFW_point v) {
8001 RGFW_UNUSED(win);
8002
8003 CGWarpMouseCursorPosition(CGPointMake(v.x, v.y));
8004 }
8005
8006
8007 void RGFW_window_hide(RGFW_window* win) {
8008 objc_msgSend_void_bool(win->src.window, sel_registerName("setIsVisible:"), false);
8009 }
8010
8011 void RGFW_window_show(RGFW_window* win) {
8012 ((id(*)(id, SEL, SEL))objc_msgSend)(win->src.window, sel_registerName("makeKeyAndOrderFront:"), NULL);
8013 objc_msgSend_void_bool(win->src.window, sel_registerName("setIsVisible:"), true);
8014 }
8015
8016 u8 RGFW_window_isFullscreen(RGFW_window* win) {
8017 assert(win != NULL);
8018
8019 NSWindowStyleMask mask = (NSWindowStyleMask) objc_msgSend_uint(win->src.window, sel_registerName("styleMask"));
8020 return (mask & NSWindowStyleMaskFullScreen) == NSWindowStyleMaskFullScreen;
8021 }
8022
8023 u8 RGFW_window_isHidden(RGFW_window* win) {
8024 assert(win != NULL);
8025
8026 bool visible = objc_msgSend_bool(win->src.window, sel_registerName("isVisible"));
8027 return visible == NO && !RGFW_window_isMinimized(win);
8028 }
8029
8030 u8 RGFW_window_isMinimized(RGFW_window* win) {
8031 assert(win != NULL);
8032
8033 return objc_msgSend_bool(win->src.window, sel_registerName("isMiniaturized")) == YES;
8034 }
8035
8036 u8 RGFW_window_isMaximized(RGFW_window* win) {
8037 assert(win != NULL);
8038
8039 return objc_msgSend_bool(win->src.window, sel_registerName("isZoomed"));
8040 }
8041
8042 static RGFW_monitor RGFW_NSCreateMonitor(CGDirectDisplayID display) {
8043 RGFW_monitor monitor;
8044
8045 CGRect bounds = CGDisplayBounds(display);
8046 monitor.rect = RGFW_RECT((int) bounds.origin.x, (int) bounds.origin.y, (int) bounds.size.width, (int) bounds.size.height);
8047
8048 CGSize screenSizeMM = CGDisplayScreenSize(display);
8049 monitor.physW = screenSizeMM.width;
8050 monitor.physH = screenSizeMM.height;
8051
8052 monitor.scaleX = ((monitor.rect.w / (screenSizeMM.width / 25.4)) / 96) + 0.25;
8053 monitor.scaleY = ((monitor.rect.h / (screenSizeMM.height / 25.4)) / 96) + 0.25;
8054
8055 return monitor;
8056 }
8057
8058
8059 static RGFW_monitor RGFW_monitors[7];
8060
8061 RGFW_monitor* RGFW_getMonitors(void) {
8062 static CGDirectDisplayID displays[7];
8063 u32 count;
8064
8065 if (CGGetActiveDisplayList(6, displays, &count) != kCGErrorSuccess)
8066 return NULL;
8067
8068 for (u32 i = 0; i < count; i++)
8069 RGFW_monitors[i] = RGFW_NSCreateMonitor(displays[i]);
8070
8071 return RGFW_monitors;
8072 }
8073
8074 RGFW_monitor RGFW_getPrimaryMonitor(void) {
8075 CGDirectDisplayID primary = CGMainDisplayID();
8076 return RGFW_NSCreateMonitor(primary);
8077 }
8078
8079 RGFW_monitor RGFW_window_getMonitor(RGFW_window* win) {
8080 return RGFW_NSCreateMonitor(win->src.display);
8081 }
8082
8083 char* RGFW_readClipboard(size_t* size) {
8084 char* clip = (char*)NSPasteboard_stringForType(NSPasteboard_generalPasteboard(), NSPasteboardTypeString);
8085
8086 size_t clip_len = 1;
8087
8088 if (clip != NULL) {
8089 clip_len = strlen(clip) + 1;
8090 }
8091
8092 char* str = (char*)RGFW_MALLOC(sizeof(char) * clip_len);
8093
8094 if (clip != NULL) {
8095 strncpy(str, clip, clip_len);
8096 }
8097
8098 str[clip_len] = '\0';
8099
8100 if (size != NULL)
8101 *size = clip_len;
8102 return str;
8103 }
8104
8105 void RGFW_writeClipboard(const char* text, u32 textLen) {
8106 RGFW_UNUSED(textLen);
8107
8108 NSPasteboardType array[] = { NSPasteboardTypeString, NULL };
8109 NSPasteBoard_declareTypes(NSPasteboard_generalPasteboard(), array, 1, NULL);
8110
8111 NSPasteBoard_setString(NSPasteboard_generalPasteboard(), text, NSPasteboardTypeString);
8112 }
8113
8114 u16 RGFW_registerJoystick(RGFW_window* win, i32 jsNumber) {
8115 RGFW_UNUSED(jsNumber);
8116
8117 assert(win != NULL);
8118
8119 return RGFW_registerJoystickF(win, (char*) "");
8120 }
8121
8122 u16 RGFW_registerJoystickF(RGFW_window* win, char* file) {
8123 RGFW_UNUSED(file);
8124
8125 assert(win != NULL);
8126
8127 return RGFW_joystickCount - 1;
8128 }
8129
8130 #ifdef RGFW_OPENGL
8131 void RGFW_window_makeCurrent_OpenGL(RGFW_window* win) {
8132 assert(win != NULL);
8133 objc_msgSend_void(win->src.ctx, sel_registerName("makeCurrentContext"));
8134 }
8135 #endif
8136
8137 #if !defined(RGFW_EGL)
8138 void RGFW_window_swapInterval(RGFW_window* win, i32 swapInterval) {
8139 assert(win != NULL);
8140 #if defined(RGFW_OPENGL)
8141
8142 NSOpenGLContext_setValues(win->src.ctx, &swapInterval, 222);
8143 #else
8144 RGFW_UNUSED(swapInterval);
8145 #endif
8146 }
8147 #endif
8148
8149 // Function to create a CGImageRef from an array of bytes
8150 CGImageRef createImageFromBytes(unsigned char *buffer, int width, int height)
8151 {
8152 // Define color space
8153 CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
8154 // Create bitmap context
8155 CGContextRef context = CGBitmapContextCreate(
8156 buffer,
8157 width, height,
8158 8,
8159 RGFW_bufferSize.w * 4,
8160 colorSpace,
8161 kCGImageAlphaPremultipliedLast);
8162 // Create image from bitmap context
8163 CGImageRef image = CGBitmapContextCreateImage(context);
8164 // Release the color space and context
8165 CGColorSpaceRelease(colorSpace);
8166 CGContextRelease(context);
8167
8168 return image;
8169 }
8170
8171 void RGFW_window_swapBuffers(RGFW_window* win) {
8172 assert(win != NULL);
8173 /* clear the window*/
8174
8175 if (!(win->_winArgs & RGFW_NO_CPU_RENDER)) {
8176#if defined(RGFW_OSMESA) || defined(RGFW_BUFFER)
8177 #ifdef RGFW_OSMESA
8178 RGFW_OSMesa_reorganize();
8179 #endif
8180
8181 void* view = NSWindow_contentView(win->src.window);
8182 void* layer = objc_msgSend_id(view, sel_registerName("layer"));
8183
8184 ((void(*)(id, SEL, NSRect))objc_msgSend)(layer,
8185 sel_registerName("setFrame:"),
8186 (NSRect){{0, 0}, {win->r.w, win->r.h}});
8187
8188 CGImageRef image = createImageFromBytes(win->buffer, win->r.w, win->r.h);
8189 // Get the current graphics context
8190 id graphicsContext = objc_msgSend_class(objc_getClass("NSGraphicsContext"), sel_registerName("currentContext"));
8191 // Get the CGContext from the current NSGraphicsContext
8192 id cgContext = objc_msgSend_id(graphicsContext, sel_registerName("graphicsPort"));
8193 // Draw the image in the context
8194 NSRect bounds = (NSRect){{0,0}, {win->r.w, win->r.h}};
8195 CGContextDrawImage((void*)cgContext, *(CGRect*)&bounds, image);
8196 // Flush the graphics context to ensure the drawing is displayed
8197 objc_msgSend_id(graphicsContext, sel_registerName("flushGraphics"));
8198
8199 objc_msgSend_void_id(layer, sel_registerName("setContents:"), (id)image);
8200 objc_msgSend_id(layer, sel_registerName("setNeedsDisplay"));
8201
8202 CGImageRelease(image);
8203#endif
8204 }
8205
8206 if (!(win->_winArgs & RGFW_NO_GPU_RENDER)) {
8207 #ifdef RGFW_EGL
8208 eglSwapBuffers(win->src.EGL_display, win->src.EGL_surface);
8209 #elif defined(RGFW_OPENGL)
8210 objc_msgSend_void(win->src.ctx, sel_registerName("flushBuffer"));
8211 #endif
8212 }
8213 }
8214
8215 void RGFW_window_close(RGFW_window* win) {
8216 assert(win != NULL);
8217 release(win->src.view);
8218
8219#ifdef RGFW_ALLOC_DROPFILES
8220 {
8221 u32 i;
8222 for (i = 0; i < RGFW_MAX_DROPS; i++)
8223 RGFW_FREE(win->event.droppedFiles[i]);
8224
8225
8226 RGFW_FREE(win->event.droppedFiles);
8227 }
8228#endif
8229
8230#ifdef RGFW_BUFFER
8231 release(win->src.bitmap);
8232 release(win->src.image);
8233#endif
8234
8235 CVDisplayLinkStop(win->src.displayLink);
8236 CVDisplayLinkRelease(win->src.displayLink);
8237
8238 RGFW_FREE(win);
8239 }
8240
8241 u64 RGFW_getTimeNS(void) {
8242 static mach_timebase_info_data_t timebase_info;
8243 if (timebase_info.denom == 0) {
8244 mach_timebase_info(&timebase_info);
8245 }
8246 return mach_absolute_time() * timebase_info.numer / timebase_info.denom;
8247 }
8248
8249 u64 RGFW_getTime(void) {
8250 static mach_timebase_info_data_t timebase_info;
8251 if (timebase_info.denom == 0) {
8252 mach_timebase_info(&timebase_info);
8253 }
8254 return (double) mach_absolute_time() * (double) timebase_info.numer / ((double) timebase_info.denom * 1e9);
8255 }
8256#endif /* RGFW_MACOS */
8257
8258/*
8259 End of MaOS defines
8260*/
8261
8262/*
8263 WEBASM defines
8264*/
8265
8266#ifdef RGFW_WEBASM
8267RGFW_Event RGFW_events[20];
8268size_t RGFW_eventLen = 0;
8269
8270EM_BOOL Emscripten_on_keydown(int eventType, const EmscriptenKeyboardEvent* e, void* userData) {
8271 RGFW_UNUSED(eventType); RGFW_UNUSED(userData);
8272
8273 RGFW_events[RGFW_eventLen].type = RGFW_keyPressed;
8274 memcpy(RGFW_events[RGFW_eventLen].keyName, e->key, 16);
8275 RGFW_events[RGFW_eventLen].keyCode = RGFW_apiKeyCodeToRGFW(e->keyCode);
8276 RGFW_events[RGFW_eventLen].lockState = 0;
8277 RGFW_eventLen++;
8278
8279 RGFW_keyboard[RGFW_apiKeyCodeToRGFW(e->keyCode)].prev = RGFW_keyboard[RGFW_apiKeyCodeToRGFW(e->keyCode)].current;
8280 RGFW_keyboard[RGFW_apiKeyCodeToRGFW(e->keyCode)].current = 1;
8281 RGFW_keyCallback(RGFW_root, RGFW_apiKeyCodeToRGFW(e->keyCode), RGFW_events[RGFW_eventLen].keyName, 0, 1);
8282
8283 return EM_TRUE;
8284}
8285
8286EM_BOOL Emscripten_on_keyup(int eventType, const EmscriptenKeyboardEvent* e, void* userData) {
8287 RGFW_UNUSED(eventType); RGFW_UNUSED(userData);
8288
8289 RGFW_events[RGFW_eventLen].type = RGFW_keyReleased;
8290 memcpy(RGFW_events[RGFW_eventLen].keyName, e->key, 16);
8291 RGFW_events[RGFW_eventLen].keyCode = RGFW_apiKeyCodeToRGFW(e->keyCode);
8292 RGFW_events[RGFW_eventLen].lockState = 0;
8293 RGFW_eventLen++;
8294
8295 RGFW_keyboard[RGFW_apiKeyCodeToRGFW(e->keyCode)].prev = RGFW_keyboard[RGFW_apiKeyCodeToRGFW(e->keyCode)].current;
8296 RGFW_keyboard[RGFW_apiKeyCodeToRGFW(e->keyCode)].current = 0;
8297
8298 RGFW_keyCallback(RGFW_root, RGFW_apiKeyCodeToRGFW(e->keyCode), RGFW_events[RGFW_eventLen].keyName, 0, 0);
8299
8300 return EM_TRUE;
8301}
8302
8303EM_BOOL Emscripten_on_resize(int eventType, const EmscriptenUiEvent* e, void* userData) {
8304 RGFW_UNUSED(eventType); RGFW_UNUSED(userData);
8305
8306 RGFW_events[RGFW_eventLen].type = RGFW_windowResized;
8307 RGFW_eventLen++;
8308
8309 RGFW_windowResizeCallback(RGFW_root, RGFW_RECT(0, 0, e->windowInnerWidth, e->windowInnerHeight));
8310 return EM_TRUE;
8311}
8312
8313EM_BOOL Emscripten_on_fullscreenchange(int eventType, const EmscriptenFullscreenChangeEvent* e, void* userData) {
8314 RGFW_UNUSED(eventType); RGFW_UNUSED(userData);
8315
8316 RGFW_events[RGFW_eventLen].type = RGFW_windowResized;
8317 RGFW_eventLen++;
8318
8319 RGFW_root->r = RGFW_RECT(0, 0, e->elementWidth, e->elementHeight);
8320 RGFW_windowResizeCallback(RGFW_root, RGFW_root->r);
8321 return EM_TRUE;
8322}
8323
8324EM_BOOL Emscripten_on_focusin(int eventType, const EmscriptenFocusEvent* e, void* userData) {
8325 RGFW_UNUSED(eventType); RGFW_UNUSED(userData); RGFW_UNUSED(e);
8326
8327 RGFW_events[RGFW_eventLen].type = RGFW_focusIn;
8328 RGFW_eventLen++;
8329
8330 RGFW_root->event.inFocus = 1;
8331 RGFW_focusCallback(RGFW_root, 1);
8332 return EM_TRUE;
8333}
8334
8335EM_BOOL Emscripten_on_focusout(int eventType, const EmscriptenFocusEvent* e, void* userData) {
8336 RGFW_UNUSED(eventType); RGFW_UNUSED(userData); RGFW_UNUSED(e);
8337
8338 RGFW_events[RGFW_eventLen].type = RGFW_focusOut;
8339 RGFW_eventLen++;
8340
8341 RGFW_root->event.inFocus = 0;
8342 RGFW_focusCallback(RGFW_root, 0);
8343 return EM_TRUE;
8344}
8345
8346EM_BOOL Emscripten_on_mousemove(int eventType, const EmscriptenMouseEvent* e, void* userData) {
8347 RGFW_UNUSED(eventType); RGFW_UNUSED(userData);
8348
8349 RGFW_events[RGFW_eventLen].type = RGFW_mousePosChanged;
8350
8351 if ((RGFW_root->_winArgs & RGFW_HOLD_MOUSE)) {
8352 RGFW_point p = RGFW_POINT(e->movementX, e->movementY);
8353 RGFW_events[RGFW_eventLen].point = p;
8354 }
8355 else
8356 RGFW_events[RGFW_eventLen].point = RGFW_POINT(e->targetX, e->targetY);
8357 RGFW_eventLen++;
8358
8359 RGFW_mousePosCallback(RGFW_root, RGFW_events[RGFW_eventLen].point);
8360 return EM_TRUE;
8361}
8362
8363EM_BOOL Emscripten_on_mousedown(int eventType, const EmscriptenMouseEvent* e, void* userData) {
8364 RGFW_UNUSED(eventType); RGFW_UNUSED(userData);
8365
8366 RGFW_events[RGFW_eventLen].type = RGFW_mouseButtonPressed;
8367 RGFW_events[RGFW_eventLen].point = RGFW_POINT(e->targetX, e->targetY);
8368 RGFW_events[RGFW_eventLen].button = e->button + 1;
8369 RGFW_events[RGFW_eventLen].scroll = 0;
8370
8371 RGFW_mouseButtons[RGFW_events[RGFW_eventLen].button].prev = RGFW_mouseButtons[RGFW_events[RGFW_eventLen].button].current;
8372 RGFW_mouseButtons[RGFW_events[RGFW_eventLen].button].current = 1;
8373
8374 RGFW_mouseButtonCallback(RGFW_root, RGFW_events[RGFW_eventLen].button, RGFW_events[RGFW_eventLen].scroll, 1);
8375 RGFW_eventLen++;
8376
8377 return EM_TRUE;
8378}
8379
8380EM_BOOL Emscripten_on_mouseup(int eventType, const EmscriptenMouseEvent* e, void* userData) {
8381 RGFW_UNUSED(eventType); RGFW_UNUSED(userData);
8382
8383 RGFW_events[RGFW_eventLen].type = RGFW_mouseButtonReleased;
8384 RGFW_events[RGFW_eventLen].point = RGFW_POINT(e->targetX, e->targetY);
8385 RGFW_events[RGFW_eventLen].button = e->button + 1;
8386 RGFW_events[RGFW_eventLen].scroll = 0;
8387
8388 RGFW_mouseButtons[RGFW_events[RGFW_eventLen].button].prev = RGFW_mouseButtons[RGFW_events[RGFW_eventLen].button].current;
8389 RGFW_mouseButtons[RGFW_events[RGFW_eventLen].button].current = 0;
8390
8391 RGFW_mouseButtonCallback(RGFW_root, RGFW_events[RGFW_eventLen].button, RGFW_events[RGFW_eventLen].scroll, 0);
8392 RGFW_eventLen++;
8393 return EM_TRUE;
8394}
8395
8396EM_BOOL Emscripten_on_wheel(int eventType, const EmscriptenWheelEvent* e, void* userData) {
8397 RGFW_UNUSED(eventType); RGFW_UNUSED(userData);
8398
8399 RGFW_events[RGFW_eventLen].type = RGFW_mouseButtonPressed;
8400 RGFW_events[RGFW_eventLen].point = RGFW_POINT(e->mouse.targetX, e->mouse.targetY);
8401 RGFW_events[RGFW_eventLen].button = RGFW_mouseScrollUp + (e->deltaY < 0);
8402 RGFW_events[RGFW_eventLen].scroll = e->deltaY;
8403
8404 RGFW_mouseButtons[RGFW_events[RGFW_eventLen].button].prev = RGFW_mouseButtons[RGFW_events[RGFW_eventLen].button].current;
8405 RGFW_mouseButtons[RGFW_events[RGFW_eventLen].button].current = 1;
8406
8407 RGFW_mouseButtonCallback(RGFW_root, RGFW_events[RGFW_eventLen].button, RGFW_events[RGFW_eventLen].scroll, 1);
8408 RGFW_eventLen++;
8409
8410 return EM_TRUE;
8411}
8412
8413EM_BOOL Emscripten_on_touchstart(int eventType, const EmscriptenTouchEvent* e, void* userData) {
8414 RGFW_UNUSED(eventType); RGFW_UNUSED(userData);
8415
8416 size_t i;
8417 for (i = 0; i < (size_t)e->numTouches; i++) {
8418 RGFW_events[RGFW_eventLen].type = RGFW_mouseButtonPressed;
8419 RGFW_events[RGFW_eventLen].point = RGFW_POINT(e->touches[i].targetX, e->touches[i].targetY);
8420 RGFW_events[RGFW_eventLen].button = 1;
8421 RGFW_events[RGFW_eventLen].scroll = 0;
8422
8423
8424 RGFW_mouseButtons[RGFW_events[RGFW_eventLen].button].prev = RGFW_mouseButtons[RGFW_events[RGFW_eventLen].button].current;
8425 RGFW_mouseButtons[RGFW_events[RGFW_eventLen].button].current = 1;
8426
8427 RGFW_mousePosCallback(RGFW_root, RGFW_events[RGFW_eventLen].point);
8428
8429 RGFW_mouseButtonCallback(RGFW_root, RGFW_events[RGFW_eventLen].button, RGFW_events[RGFW_eventLen].scroll, 1);
8430 RGFW_eventLen++;
8431 }
8432
8433 return EM_TRUE;
8434}
8435EM_BOOL Emscripten_on_touchmove(int eventType, const EmscriptenTouchEvent* e, void* userData) {
8436 RGFW_UNUSED(eventType); RGFW_UNUSED(userData);
8437
8438 size_t i;
8439 for (i = 0; i < (size_t)e->numTouches; i++) {
8440 RGFW_events[RGFW_eventLen].type = RGFW_mousePosChanged;
8441 RGFW_events[RGFW_eventLen].point = RGFW_POINT(e->touches[i].targetX, e->touches[i].targetY);
8442
8443 RGFW_mousePosCallback(RGFW_root, RGFW_events[RGFW_eventLen].point);
8444 RGFW_eventLen++;
8445 }
8446 return EM_TRUE;
8447}
8448
8449EM_BOOL Emscripten_on_touchend(int eventType, const EmscriptenTouchEvent* e, void* userData) {
8450 RGFW_UNUSED(eventType); RGFW_UNUSED(userData);
8451
8452 size_t i;
8453 for (i = 0; i < (size_t)e->numTouches; i++) {
8454 RGFW_events[RGFW_eventLen].type = RGFW_mouseButtonReleased;
8455 RGFW_events[RGFW_eventLen].point = RGFW_POINT(e->touches[i].targetX, e->touches[i].targetY);
8456 RGFW_events[RGFW_eventLen].button = 1;
8457 RGFW_events[RGFW_eventLen].scroll = 0;
8458
8459 RGFW_mouseButtons[RGFW_events[RGFW_eventLen].button].prev = RGFW_mouseButtons[RGFW_events[RGFW_eventLen].button].current;
8460 RGFW_mouseButtons[RGFW_events[RGFW_eventLen].button].current = 0;
8461
8462 RGFW_mouseButtonCallback(RGFW_root, RGFW_events[RGFW_eventLen].button, RGFW_events[RGFW_eventLen].scroll, 0);
8463 RGFW_eventLen++;
8464 }
8465 return EM_TRUE;
8466}
8467
8468EM_BOOL Emscripten_on_touchcancel(int eventType, const EmscriptenTouchEvent* e, void* userData) { RGFW_UNUSED(eventType); RGFW_UNUSED(userData); RGFW_UNUSED(e); return EM_TRUE; }
8469
8470EM_BOOL Emscripten_on_gamepad(int eventType, const EmscriptenGamepadEvent *gamepadEvent, void *userData) {
8471 RGFW_UNUSED(eventType); RGFW_UNUSED(userData);
8472
8473 if (gamepadEvent->index >= 4)
8474 return 0;
8475
8476 RGFW_joysticks[gamepadEvent->index] = gamepadEvent->connected;
8477
8478 return 1; // The event was consumed by the callback handler
8479}
8480
8481void EMSCRIPTEN_KEEPALIVE Emscripten_onDrop(size_t count) {
8482 if (!(RGFW_root->_winArgs & RGFW_ALLOW_DND))
8483 return;
8484
8485 RGFW_events[RGFW_eventLen].droppedFilesCount = count;
8486 RGFW_dndCallback(RGFW_root, RGFW_events[RGFW_eventLen].droppedFiles, count);
8487 RGFW_eventLen++;
8488}
8489
8490b8 RGFW_stopCheckEvents_bool = RGFW_FALSE;
8491void RGFW_stopCheckEvents(void) {
8492 RGFW_stopCheckEvents_bool = RGFW_TRUE;
8493}
8494
8495void RGFW_window_eventWait(RGFW_window* win, i32 waitMS) {
8496 RGFW_UNUSED(win);
8497
8498 if (waitMS == 0)
8499 return;
8500
8501 u32 start = (u32)(((u64)RGFW_getTimeNS()) / 1e+6);
8502
8503 while ((RGFW_eventLen == 0) && RGFW_stopCheckEvents_bool == RGFW_FALSE &&
8504 (waitMS < 0 || (RGFW_getTimeNS() / 1e+6) - start < waitMS)
8505 ) {
8506 emscripten_sleep(0);
8507 }
8508
8509 RGFW_stopCheckEvents_bool = RGFW_FALSE;
8510}
8511
8512RGFWDEF void RGFW_init_buffer(RGFW_window* win);
8513void RGFW_init_buffer(RGFW_window* win) {
8514 #if defined(RGFW_OSMESA) || defined(RGFW_BUFFER)
8515 if (RGFW_bufferSize.w == 0 && RGFW_bufferSize.h == 0)
8516 RGFW_bufferSize = RGFW_getScreenSize();
8517
8518 win->buffer = RGFW_MALLOC(RGFW_bufferSize.w * RGFW_bufferSize.h * 4);
8519 #ifdef RGFW_OSMESA
8520 win->src.ctx = OSMesaCreateContext(OSMESA_RGBA, NULL);
8521 OSMesaMakeCurrent(win->src.ctx, win->buffer, GL_UNSIGNED_BYTE, win->r.w, win->r.h);
8522 #endif
8523 #else
8524 RGFW_UNUSED(win); /*!< if buffer rendering is not being used */
8525 #endif
8526}
8527
8528void EMSCRIPTEN_KEEPALIVE RGFW_makeSetValue(size_t index, char* file) {
8529 /* This seems like a terrible idea, don't replicate this unless you hate yourself or the OS */
8530 /* TODO: find a better way to do this,
8531 strcpy doesn't seem to work, maybe because of asyncio
8532 */
8533
8534 RGFW_events[RGFW_eventLen].type = RGFW_dnd;
8535 char** arr = (char**)&RGFW_events[RGFW_eventLen].droppedFiles[index];
8536 *arr = file;
8537}
8538
8539#include <sys/stat.h>
8540#include <sys/types.h>
8541#include <errno.h>
8542
8543void EMSCRIPTEN_KEEPALIVE RGFW_mkdir(char* name) { mkdir(name, 0755); }
8544
8545void EMSCRIPTEN_KEEPALIVE RGFW_writeFile(const char *path, const char *data, size_t len) {
8546 FILE* file = fopen(path, "w+");
8547 if (file == NULL)
8548 return;
8549
8550 fwrite(data, sizeof(char), len, file);
8551 fclose(file);
8552}
8553
8554RGFW_window* RGFW_createWindow(const char* name, RGFW_rect rect, u16 args) {
8555 RGFW_UNUSED(name)
8556
8557 RGFW_UNUSED(RGFW_initFormatAttribs);
8558
8559 RGFW_window* win = RGFW_window_basic_init(rect, args);
8560
8561#ifndef RGFW_WEBGPU
8562 EmscriptenWebGLContextAttributes attrs;
8563 attrs.alpha = EM_TRUE;
8564 attrs.depth = EM_TRUE;
8565 attrs.alpha = EM_TRUE;
8566 attrs.stencil = RGFW_STENCIL;
8567 attrs.antialias = RGFW_SAMPLES;
8568 attrs.premultipliedAlpha = EM_TRUE;
8569 attrs.preserveDrawingBuffer = EM_FALSE;
8570
8571 if (RGFW_DOUBLE_BUFFER == 0)
8572 attrs.renderViaOffscreenBackBuffer = 0;
8573 else
8574 attrs.renderViaOffscreenBackBuffer = RGFW_AUX_BUFFERS;
8575
8576 attrs.failIfMajorPerformanceCaveat = EM_FALSE;
8577 attrs.majorVersion = (RGFW_majorVersion == 0) ? 1 : RGFW_majorVersion;
8578 attrs.minorVersion = RGFW_minorVersion;
8579
8580 attrs.enableExtensionsByDefault = EM_TRUE;
8581 attrs.explicitSwapControl = EM_TRUE;
8582
8583 emscripten_webgl_init_context_attributes(&attrs);
8584 win->src.ctx = emscripten_webgl_create_context("#canvas", &attrs);
8585 emscripten_webgl_make_context_current(win->src.ctx);
8586
8587 #ifdef LEGACY_GL_EMULATION
8588 EM_ASM("Module.useWebGL = true; GLImmediate.init();");
8589 #endif
8590#else
8591 win->src.ctx = wgpuCreateInstance(NULL);
8592 win->src.device = emscripten_webgpu_get_device();
8593 win->src.queue = wgpuDeviceGetQueue(win->src.device);
8594#endif
8595
8596 emscripten_set_canvas_element_size("#canvas", rect.w, rect.h);
8597 emscripten_set_window_title(name);
8598
8599 /* load callbacks */
8600 emscripten_set_keydown_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, EM_FALSE, Emscripten_on_keydown);
8601 emscripten_set_keyup_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, EM_FALSE, Emscripten_on_keyup);
8602 emscripten_set_resize_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, EM_FALSE, Emscripten_on_resize);
8603 emscripten_set_fullscreenchange_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, NULL, EM_FALSE, Emscripten_on_fullscreenchange);
8604 emscripten_set_mousemove_callback("#canvas", NULL, EM_FALSE, Emscripten_on_mousemove);
8605 emscripten_set_touchstart_callback("#canvas", NULL, EM_FALSE, Emscripten_on_touchstart);
8606 emscripten_set_touchend_callback("#canvas", NULL, EM_FALSE, Emscripten_on_touchend);
8607 emscripten_set_touchmove_callback("#canvas", NULL, EM_FALSE, Emscripten_on_touchmove);
8608 emscripten_set_touchcancel_callback("#canvas", NULL, EM_FALSE, Emscripten_on_touchcancel);
8609 emscripten_set_mousedown_callback("#canvas", NULL, EM_FALSE, Emscripten_on_mousedown);
8610 emscripten_set_mouseup_callback("#canvas", NULL, EM_FALSE, Emscripten_on_mouseup);
8611 emscripten_set_wheel_callback("#canvas", NULL, EM_FALSE, Emscripten_on_wheel);
8612 emscripten_set_focusin_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, EM_FALSE, Emscripten_on_focusin);
8613 emscripten_set_focusout_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, EM_FALSE, Emscripten_on_focusout);
8614 emscripten_set_gamepadconnected_callback(NULL, 1, Emscripten_on_gamepad);
8615 emscripten_set_gamepaddisconnected_callback(NULL, 1, Emscripten_on_gamepad);
8616
8617 if (args & RGFW_ALLOW_DND) {
8618 win->_winArgs |= RGFW_ALLOW_DND;
8619 }
8620
8621 EM_ASM({
8622 var canvas = document.getElementById('canvas');
8623 canvas.addEventListener('drop', function(e) {
8624 e.preventDefault();
8625 if (e.dataTransfer.file < 0)
8626 return;
8627
8628 var filenamesArray = [];
8629 var count = e.dataTransfer.files.length;
8630
8631 /* Read and save the files to emscripten's files */
8632 var drop_dir = '.rgfw_dropped_files';
8633 Module._RGFW_mkdir(drop_dir);
8634
8635 for (var i = 0; i < count; i++) {
8636 var file = e.dataTransfer.files[i];
8637
8638 var path = '/' + drop_dir + '/' + file.name.replace("//", '_');
8639 var reader = new FileReader();
8640
8641 reader.onloadend = (e) => {
8642 if (reader.readyState != 2) {
8643 out('failed to read dropped file: '+file.name+': '+reader.error);
8644 }
8645 else {
8646 var data = e.target.result;
8647
8648 _RGFW_writeFile(path, new Uint8Array(data), file.size);
8649 }
8650 };
8651
8652 reader.readAsArrayBuffer(file);
8653 // This works weird on modern opengl
8654 var filename = stringToNewUTF8(path);
8655
8656 filenamesArray.push(filename);
8657
8658 Module._RGFW_makeSetValue(i, filename);
8659 }
8660
8661 Module._Emscripten_onDrop(count);
8662
8663 for (var i = 0; i < count; ++i) {
8664 _free(filenamesArray[i]);
8665 }
8666 }, true);
8667
8668 canvas.addEventListener('dragover', function(e) { e.preventDefault(); return false; }, true);
8669 });
8670
8671 RGFW_init_buffer(win);
8672 glViewport(0, 0, rect.w, rect.h);
8673
8674 RGFW_root = win;
8675
8676 if (args & RGFW_HIDE_MOUSE) {
8677 RGFW_window_showMouse(win, 0);
8678 }
8679
8680 if (args & RGFW_FULLSCREEN) {
8681 RGFW_window_resize(win, RGFW_getScreenSize());
8682 }
8683
8684 return win;
8685}
8686
8687RGFW_Event* RGFW_window_checkEvent(RGFW_window* win) {
8688 static u8 index = 0;
8689
8690 if (index == 0)
8691 RGFW_resetKey();
8692
8693 /* check gamepads */
8694 for (int i = 0; (i < emscripten_get_num_gamepads()) && (i < 4); i++) {
8695 if (RGFW_joysticks[i] == 0)
8696 continue;;
8697
8698 EmscriptenGamepadEvent gamepadState;
8699
8700 if (emscripten_get_gamepad_status(i, &gamepadState) != EMSCRIPTEN_RESULT_SUCCESS)
8701 break;
8702
8703 // Register buttons data for every connected gamepad
8704 for (int j = 0; (j < gamepadState.numButtons) && (j < 16); j++) {
8705 u32 map[] = {
8706 RGFW_JS_A, RGFW_JS_X, RGFW_JS_B, RGFW_JS_Y,
8707 RGFW_JS_L1, RGFW_JS_R1, RGFW_JS_L2, RGFW_JS_R2,
8708 RGFW_JS_SELECT, RGFW_JS_START,
8709 0, 0,
8710 RGFW_JS_UP, RGFW_JS_DOWN, RGFW_JS_LEFT, RGFW_JS_RIGHT
8711 };
8712
8713 u32 button = map[j];
8714 if (RGFW_jsPressed[i][button] != gamepadState.digitalButton[j]) {
8715 win->event.type = RGFW_jsButtonPressed;
8716 win->event.joystick = i;
8717 win->event.button = map[j];
8718 return &win->event;
8719 }
8720
8721 RGFW_jsPressed[i][button] = gamepadState.digitalButton[j];
8722 }
8723
8724 for (int j = 0; (j < gamepadState.numAxes) && (j < 4); j += 2) {
8725 win->event.axisesCount = gamepadState.numAxes;
8726 if (win->event.axis[j].x != gamepadState.axis[j] ||
8727 win->event.axis[j].y != gamepadState.axis[j + 1]
8728 ) {
8729 win->event.axis[j].x = gamepadState.axis[j];
8730 win->event.axis[j].y = gamepadState.axis[j + 1];
8731 win->event.type = RGFW_jsAxisMove;
8732 win->event.joystick = i;
8733 return &win->event;
8734 }
8735 }
8736 }
8737
8738 /* check queued events */
8739 if (RGFW_eventLen == 0)
8740 return NULL;
8741
8742 RGFW_events[index].frameTime = win->event.frameTime;
8743 RGFW_events[index].frameTime2 = win->event.frameTime2;
8744 RGFW_events[index].inFocus = win->event.inFocus;
8745
8746 win->event = RGFW_events[index];
8747
8748 RGFW_eventLen--;
8749
8750 if (RGFW_eventLen)
8751 index++;
8752 else
8753 index = 0;
8754
8755 return &win->event;
8756}
8757
8758void RGFW_window_resize(RGFW_window* win, RGFW_area a) {
8759 RGFW_UNUSED(win)
8760 emscripten_set_canvas_element_size("#canvas", a.w, a.h);
8761}
8762
8763/* NOTE: I don't know if this is possible */
8764void RGFW_window_moveMouse(RGFW_window* win, RGFW_point v) { RGFW_UNUSED(win); RGFW_UNUSED(v); }
8765/* this one might be possible but it looks iffy */
8766void RGFW_window_setMouse(RGFW_window* win, u8* image, RGFW_area a, i32 channels) { RGFW_UNUSED(win); RGFW_UNUSED(channels) RGFW_UNUSED(a) RGFW_UNUSED(image) }
8767
8768const char RGFW_CURSORS[11][12] = {
8769 "default",
8770 "default",
8771 "text",
8772 "crosshair",
8773 "pointer",
8774 "ew-resize",
8775 "ns-resize",
8776 "nwse-resize",
8777 "nesw-resize",
8778 "move",
8779 "not-allowed"
8780};
8781
8782void RGFW_window_setMouseStandard(RGFW_window* win, u8 mouse) {
8783 RGFW_UNUSED(win)
8784 EM_ASM( { document.getElementById("canvas").style.cursor = UTF8ToString($0); }, RGFW_CURSORS[mouse]);
8785}
8786
8787void RGFW_window_setMouseDefault(RGFW_window* win) {
8788 RGFW_window_setMouseStandard(win, RGFW_MOUSE_NORMAL);
8789}
8790
8791void RGFW_window_showMouse(RGFW_window* win, i8 show) {
8792 if (show)
8793 RGFW_window_setMouseDefault(win);
8794 else
8795 EM_ASM(document.getElementById('canvas').style.cursor = 'none';);
8796}
8797
8798RGFW_point RGFW_getGlobalMousePoint(void) {
8799 RGFW_point point;
8800 point.x = EM_ASM_INT({
8801 return window.mouseX || 0;
8802 });
8803 point.y = EM_ASM_INT({
8804 return window.mouseY || 0;
8805 });
8806 return point;
8807}
8808
8809RGFW_point RGFW_window_getMousePoint(RGFW_window* win) {
8810 RGFW_UNUSED(win);
8811
8812 EmscriptenMouseEvent mouseEvent;
8813 emscripten_get_mouse_status(&mouseEvent);
8814 return RGFW_POINT( mouseEvent.targetX, mouseEvent.targetY);
8815}
8816
8817void RGFW_window_setMousePassthrough(RGFW_window* win, b8 passthrough) {
8818 RGFW_UNUSED(win);
8819
8820 EM_ASM_({
8821 var canvas = document.getElementById('canvas');
8822 if ($0) {
8823 canvas.style.pointerEvents = 'none';
8824 } else {
8825 canvas.style.pointerEvents = 'auto';
8826 }
8827 }, passthrough);
8828}
8829
8830void RGFW_writeClipboard(const char* text, u32 textLen) {
8831 RGFW_UNUSED(textLen)
8832 EM_ASM({ navigator.clipboard.writeText(UTF8ToString($0)); }, text);
8833}
8834
8835
8836char* RGFW_readClipboard(size_t* size) {
8837 /*
8838 placeholder code for later
8839 I'm not sure if this is possible do the the async stuff
8840 */
8841
8842 if (size != NULL)
8843 *size = 0;
8844
8845 char* str = (char*)malloc(1);
8846 str[0] = '\0';
8847
8848 return str;
8849}
8850
8851void RGFW_window_swapBuffers(RGFW_window* win) {
8852 RGFW_UNUSED(win);
8853
8854 #ifdef RGFW_BUFFER
8855 if (!(win->_winArgs & RGFW_NO_CPU_RENDER)) {
8856 glEnable(GL_TEXTURE_2D);
8857
8858 GLuint texture;
8859 glGenTextures(1,&texture);
8860
8861 glBindTexture(GL_TEXTURE_2D,texture);
8862
8863 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
8864 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
8865 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
8866 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
8867
8868 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, RGFW_bufferSize.w, RGFW_bufferSize.h, 0, GL_RGBA, GL_UNSIGNED_BYTE, win->buffer);
8869
8870 float ratioX = ((float)win->r.w / (float)RGFW_bufferSize.w);
8871 float ratioY = ((float)win->r.h / (float)RGFW_bufferSize.h);
8872
8873 // Set up the viewport
8874 glClear(GL_COLOR_BUFFER_BIT);
8875
8876 glBegin(GL_TRIANGLES);
8877 glTexCoord2f(0, ratioY); glColor3f(1, 1, 1); glVertex2f(-1, -1);
8878 glTexCoord2f(0, 0); glColor3f(1, 1, 1); glVertex2f(-1, 1);
8879 glTexCoord2f(ratioX, ratioY); glColor3f(1, 1, 1); glVertex2f(1, -1);
8880
8881 glTexCoord2f(ratioX, 0); glColor3f(1, 1, 1); glVertex2f(1, 1);
8882 glTexCoord2f(ratioX, ratioY); glColor3f(1, 1, 1); glVertex2f(1, -1);
8883 glTexCoord2f(0, 0); glColor3f(1, 1, 1); glVertex2f(-1, 1);
8884 glEnd();
8885
8886 glDeleteTextures(1, &texture);
8887 }
8888 #endif
8889
8890#ifndef RGFW_WEBGPU
8891 emscripten_webgl_commit_frame();
8892#endif
8893 emscripten_sleep(0);
8894}
8895
8896
8897void RGFW_window_makeCurrent_OpenGL(RGFW_window* win) {
8898#ifndef RGFW_WEBGPU
8899 if (win == NULL)
8900 emscripten_webgl_make_context_current(0);
8901 else
8902 emscripten_webgl_make_context_current(win->src.ctx);
8903#endif
8904}
8905
8906#ifndef RGFW_EGL
8907void RGFW_window_swapInterval(RGFW_window* win, i32 swapInterval) { RGFW_UNUSED(win); RGFW_UNUSED(swapInterval); }
8908#endif
8909
8910void RGFW_window_close(RGFW_window* win) {
8911#ifndef RGFW_WEBGPU
8912 emscripten_webgl_destroy_context(win->src.ctx);
8913#endif
8914
8915 free(win);
8916}
8917
8918int RGFW_innerWidth(void) { return EM_ASM_INT({ return window.innerWidth; }); }
8919int RGFW_innerHeight(void) { return EM_ASM_INT({ return window.innerHeight; }); }
8920
8921RGFW_area RGFW_getScreenSize(void) {
8922 return RGFW_AREA(RGFW_innerWidth(), RGFW_innerHeight());
8923}
8924
8925void* RGFW_getProcAddress(const char* procname) {
8926 return emscripten_webgl_get_proc_address(procname);
8927}
8928
8929void RGFW_sleep(u64 milisecond) {
8930 emscripten_sleep(milisecond);
8931}
8932
8933u64 RGFW_getTimeNS(void) {
8934 return emscripten_get_now() * 1e+6;
8935}
8936
8937u64 RGFW_getTime(void) {
8938 return emscripten_get_now() * 1000;
8939}
8940
8941void RGFW_releaseCursor(RGFW_window* win) {
8942 RGFW_UNUSED(win);
8943 emscripten_exit_pointerlock();
8944}
8945
8946void RGFW_captureCursor(RGFW_window* win, RGFW_rect r) {
8947 RGFW_UNUSED(win); RGFW_UNUSED(r);
8948
8949 emscripten_request_pointerlock("#canvas", 1);
8950}
8951
8952
8953void RGFW_window_setName(RGFW_window* win, char* name) {
8954 RGFW_UNUSED(win);
8955 emscripten_set_window_title(name);
8956}
8957
8958/* unsupported functions */
8959RGFW_monitor* RGFW_getMonitors(void) { return NULL; }
8960RGFW_monitor RGFW_getPrimaryMonitor(void) { return (RGFW_monitor){}; }
8961void RGFW_window_move(RGFW_window* win, RGFW_point v) { RGFW_UNUSED(win) RGFW_UNUSED(v) }
8962void RGFW_window_setMinSize(RGFW_window* win, RGFW_area a) { RGFW_UNUSED(win) RGFW_UNUSED(a) }
8963void RGFW_window_setMaxSize(RGFW_window* win, RGFW_area a) { RGFW_UNUSED(win) RGFW_UNUSED(a) }
8964void RGFW_window_minimize(RGFW_window* win) { RGFW_UNUSED(win)}
8965void RGFW_window_restore(RGFW_window* win) { RGFW_UNUSED(win) }
8966void RGFW_window_setBorder(RGFW_window* win, b8 border) { RGFW_UNUSED(win) RGFW_UNUSED(border) }
8967void RGFW_window_setIcon(RGFW_window* win, u8* icon, RGFW_area a, i32 channels) { RGFW_UNUSED(win) RGFW_UNUSED(icon) RGFW_UNUSED(a) RGFW_UNUSED(channels) }
8968void RGFW_window_hide(RGFW_window* win) { RGFW_UNUSED(win) }
8969void RGFW_window_show(RGFW_window* win) {RGFW_UNUSED(win) }
8970b8 RGFW_window_isHidden(RGFW_window* win) { RGFW_UNUSED(win) return 0; }
8971b8 RGFW_window_isMinimized(RGFW_window* win) { RGFW_UNUSED(win) return 0; }
8972b8 RGFW_window_isMaximized(RGFW_window* win) { RGFW_UNUSED(win) return 0; }
8973RGFW_monitor RGFW_window_getMonitor(RGFW_window* win) { RGFW_UNUSED(win) return (RGFW_monitor){}; }
8974
8975#endif
8976
8977/* end of web asm defines */
8978
8979/* unix (macOS, linux, web asm) only stuff */
8980#if defined(RGFW_X11) || defined(RGFW_MACOS) || defined(RGFW_WEBASM) || defined(RGFW_WAYLAND)
8981/* unix threading */
8982#ifndef RGFW_NO_THREADS
8983#include <pthread.h>
8984
8985 RGFW_thread RGFW_createThread(RGFW_threadFunc_ptr ptr, void* args) {
8986 RGFW_UNUSED(args);
8987
8988 RGFW_thread t;
8989 pthread_create((pthread_t*) &t, NULL, *ptr, NULL);
8990 return t;
8991 }
8992 void RGFW_cancelThread(RGFW_thread thread) { pthread_cancel((pthread_t) thread); }
8993 void RGFW_joinThread(RGFW_thread thread) { pthread_join((pthread_t) thread, NULL); }
8994#ifdef __linux__
8995 void RGFW_setThreadPriority(RGFW_thread thread, u8 priority) { pthread_setschedprio((pthread_t)thread, priority); }
8996#endif
8997#endif
8998
8999#ifndef RGFW_WEBASM
9000/* unix sleep */
9001 void RGFW_sleep(u64 ms) {
9002 struct timespec time;
9003 time.tv_sec = 0;
9004 time.tv_nsec = ms * 1e+6;
9005
9006 nanosleep(&time, NULL);
9007 }
9008#endif
9009
9010#endif /* end of unix / mac stuff*/
9011#endif /*RGFW_IMPLEMENTATION*/
9012
9013#if defined(__cplusplus) && !defined(__EMSCRIPTEN__)
9014}
9015#endif
diff --git a/raylib/src/external/cgltf.h b/raylib/src/external/cgltf.h
new file mode 100644
index 0000000..36fd644
--- /dev/null
+++ b/raylib/src/external/cgltf.h
@@ -0,0 +1,7081 @@
1/**
2 * cgltf - a single-file glTF 2.0 parser written in C99.
3 *
4 * Version: 1.14
5 *
6 * Website: https://github.com/jkuhlmann/cgltf
7 *
8 * Distributed under the MIT License, see notice at the end of this file.
9 *
10 * Building:
11 * Include this file where you need the struct and function
12 * declarations. Have exactly one source file where you define
13 * `CGLTF_IMPLEMENTATION` before including this file to get the
14 * function definitions.
15 *
16 * Reference:
17 * `cgltf_result cgltf_parse(const cgltf_options*, const void*,
18 * cgltf_size, cgltf_data**)` parses both glTF and GLB data. If
19 * this function returns `cgltf_result_success`, you have to call
20 * `cgltf_free()` on the created `cgltf_data*` variable.
21 * Note that contents of external files for buffers and images are not
22 * automatically loaded. You'll need to read these files yourself using
23 * URIs in the `cgltf_data` structure.
24 *
25 * `cgltf_options` is the struct passed to `cgltf_parse()` to control
26 * parts of the parsing process. You can use it to force the file type
27 * and provide memory allocation as well as file operation callbacks.
28 * Should be zero-initialized to trigger default behavior.
29 *
30 * `cgltf_data` is the struct allocated and filled by `cgltf_parse()`.
31 * It generally mirrors the glTF format as described by the spec (see
32 * https://github.com/KhronosGroup/glTF/tree/master/specification/2.0).
33 *
34 * `void cgltf_free(cgltf_data*)` frees the allocated `cgltf_data`
35 * variable.
36 *
37 * `cgltf_result cgltf_load_buffers(const cgltf_options*, cgltf_data*,
38 * const char* gltf_path)` can be optionally called to open and read buffer
39 * files using the `FILE*` APIs. The `gltf_path` argument is the path to
40 * the original glTF file, which allows the parser to resolve the path to
41 * buffer files.
42 *
43 * `cgltf_result cgltf_load_buffer_base64(const cgltf_options* options,
44 * cgltf_size size, const char* base64, void** out_data)` decodes
45 * base64-encoded data content. Used internally by `cgltf_load_buffers()`.
46 * This is useful when decoding data URIs in images.
47 *
48 * `cgltf_result cgltf_parse_file(const cgltf_options* options, const
49 * char* path, cgltf_data** out_data)` can be used to open the given
50 * file using `FILE*` APIs and parse the data using `cgltf_parse()`.
51 *
52 * `cgltf_result cgltf_validate(cgltf_data*)` can be used to do additional
53 * checks to make sure the parsed glTF data is valid.
54 *
55 * `cgltf_node_transform_local` converts the translation / rotation / scale properties of a node
56 * into a mat4.
57 *
58 * `cgltf_node_transform_world` calls `cgltf_node_transform_local` on every ancestor in order
59 * to compute the root-to-node transformation.
60 *
61 * `cgltf_accessor_unpack_floats` reads in the data from an accessor, applies sparse data (if any),
62 * and converts them to floating point. Assumes that `cgltf_load_buffers` has already been called.
63 * By passing null for the output pointer, users can find out how many floats are required in the
64 * output buffer.
65 *
66 * `cgltf_accessor_unpack_indices` reads in the index data from an accessor. Assumes that
67 * `cgltf_load_buffers` has already been called. By passing null for the output pointer, users can
68 * find out how many indices are required in the output buffer. Returns 0 if the accessor is
69 * sparse or if the output component size is less than the accessor's component size.
70 *
71 * `cgltf_num_components` is a tiny utility that tells you the dimensionality of
72 * a certain accessor type. This can be used before `cgltf_accessor_unpack_floats` to help allocate
73 * the necessary amount of memory. `cgltf_component_size` and `cgltf_calc_size` exist for
74 * similar purposes.
75 *
76 * `cgltf_accessor_read_float` reads a certain element from a non-sparse accessor and converts it to
77 * floating point, assuming that `cgltf_load_buffers` has already been called. The passed-in element
78 * size is the number of floats in the output buffer, which should be in the range [1, 16]. Returns
79 * false if the passed-in element_size is too small, or if the accessor is sparse.
80 *
81 * `cgltf_accessor_read_uint` is similar to its floating-point counterpart, but limited to reading
82 * vector types and does not support matrix types. The passed-in element size is the number of uints
83 * in the output buffer, which should be in the range [1, 4]. Returns false if the passed-in
84 * element_size is too small, or if the accessor is sparse.
85 *
86 * `cgltf_accessor_read_index` is similar to its floating-point counterpart, but it returns size_t
87 * and only works with single-component data types.
88 *
89 * `cgltf_copy_extras_json` allows users to retrieve the "extras" data that can be attached to many
90 * glTF objects (which can be arbitrary JSON data). This is a legacy function, consider using
91 * cgltf_extras::data directly instead. You can parse this data using your own JSON parser
92 * or, if you've included the cgltf implementation using the integrated JSMN JSON parser.
93 */
94#ifndef CGLTF_H_INCLUDED__
95#define CGLTF_H_INCLUDED__
96
97#include <stddef.h>
98#include <stdint.h> /* For uint8_t, uint32_t */
99
100#ifdef __cplusplus
101extern "C" {
102#endif
103
104typedef size_t cgltf_size;
105typedef long long int cgltf_ssize;
106typedef float cgltf_float;
107typedef int cgltf_int;
108typedef unsigned int cgltf_uint;
109typedef int cgltf_bool;
110
111typedef enum cgltf_file_type
112{
113 cgltf_file_type_invalid,
114 cgltf_file_type_gltf,
115 cgltf_file_type_glb,
116 cgltf_file_type_max_enum
117} cgltf_file_type;
118
119typedef enum cgltf_result
120{
121 cgltf_result_success,
122 cgltf_result_data_too_short,
123 cgltf_result_unknown_format,
124 cgltf_result_invalid_json,
125 cgltf_result_invalid_gltf,
126 cgltf_result_invalid_options,
127 cgltf_result_file_not_found,
128 cgltf_result_io_error,
129 cgltf_result_out_of_memory,
130 cgltf_result_legacy_gltf,
131 cgltf_result_max_enum
132} cgltf_result;
133
134typedef struct cgltf_memory_options
135{
136 void* (*alloc_func)(void* user, cgltf_size size);
137 void (*free_func) (void* user, void* ptr);
138 void* user_data;
139} cgltf_memory_options;
140
141typedef struct cgltf_file_options
142{
143 cgltf_result(*read)(const struct cgltf_memory_options* memory_options, const struct cgltf_file_options* file_options, const char* path, cgltf_size* size, void** data);
144 void (*release)(const struct cgltf_memory_options* memory_options, const struct cgltf_file_options* file_options, void* data);
145 void* user_data;
146} cgltf_file_options;
147
148typedef struct cgltf_options
149{
150 cgltf_file_type type; /* invalid == auto detect */
151 cgltf_size json_token_count; /* 0 == auto */
152 cgltf_memory_options memory;
153 cgltf_file_options file;
154} cgltf_options;
155
156typedef enum cgltf_buffer_view_type
157{
158 cgltf_buffer_view_type_invalid,
159 cgltf_buffer_view_type_indices,
160 cgltf_buffer_view_type_vertices,
161 cgltf_buffer_view_type_max_enum
162} cgltf_buffer_view_type;
163
164typedef enum cgltf_attribute_type
165{
166 cgltf_attribute_type_invalid,
167 cgltf_attribute_type_position,
168 cgltf_attribute_type_normal,
169 cgltf_attribute_type_tangent,
170 cgltf_attribute_type_texcoord,
171 cgltf_attribute_type_color,
172 cgltf_attribute_type_joints,
173 cgltf_attribute_type_weights,
174 cgltf_attribute_type_custom,
175 cgltf_attribute_type_max_enum
176} cgltf_attribute_type;
177
178typedef enum cgltf_component_type
179{
180 cgltf_component_type_invalid,
181 cgltf_component_type_r_8, /* BYTE */
182 cgltf_component_type_r_8u, /* UNSIGNED_BYTE */
183 cgltf_component_type_r_16, /* SHORT */
184 cgltf_component_type_r_16u, /* UNSIGNED_SHORT */
185 cgltf_component_type_r_32u, /* UNSIGNED_INT */
186 cgltf_component_type_r_32f, /* FLOAT */
187 cgltf_component_type_max_enum
188} cgltf_component_type;
189
190typedef enum cgltf_type
191{
192 cgltf_type_invalid,
193 cgltf_type_scalar,
194 cgltf_type_vec2,
195 cgltf_type_vec3,
196 cgltf_type_vec4,
197 cgltf_type_mat2,
198 cgltf_type_mat3,
199 cgltf_type_mat4,
200 cgltf_type_max_enum
201} cgltf_type;
202
203typedef enum cgltf_primitive_type
204{
205 cgltf_primitive_type_invalid,
206 cgltf_primitive_type_points,
207 cgltf_primitive_type_lines,
208 cgltf_primitive_type_line_loop,
209 cgltf_primitive_type_line_strip,
210 cgltf_primitive_type_triangles,
211 cgltf_primitive_type_triangle_strip,
212 cgltf_primitive_type_triangle_fan,
213 cgltf_primitive_type_max_enum
214} cgltf_primitive_type;
215
216typedef enum cgltf_alpha_mode
217{
218 cgltf_alpha_mode_opaque,
219 cgltf_alpha_mode_mask,
220 cgltf_alpha_mode_blend,
221 cgltf_alpha_mode_max_enum
222} cgltf_alpha_mode;
223
224typedef enum cgltf_animation_path_type {
225 cgltf_animation_path_type_invalid,
226 cgltf_animation_path_type_translation,
227 cgltf_animation_path_type_rotation,
228 cgltf_animation_path_type_scale,
229 cgltf_animation_path_type_weights,
230 cgltf_animation_path_type_max_enum
231} cgltf_animation_path_type;
232
233typedef enum cgltf_interpolation_type {
234 cgltf_interpolation_type_linear,
235 cgltf_interpolation_type_step,
236 cgltf_interpolation_type_cubic_spline,
237 cgltf_interpolation_type_max_enum
238} cgltf_interpolation_type;
239
240typedef enum cgltf_camera_type {
241 cgltf_camera_type_invalid,
242 cgltf_camera_type_perspective,
243 cgltf_camera_type_orthographic,
244 cgltf_camera_type_max_enum
245} cgltf_camera_type;
246
247typedef enum cgltf_light_type {
248 cgltf_light_type_invalid,
249 cgltf_light_type_directional,
250 cgltf_light_type_point,
251 cgltf_light_type_spot,
252 cgltf_light_type_max_enum
253} cgltf_light_type;
254
255typedef enum cgltf_data_free_method {
256 cgltf_data_free_method_none,
257 cgltf_data_free_method_file_release,
258 cgltf_data_free_method_memory_free,
259 cgltf_data_free_method_max_enum
260} cgltf_data_free_method;
261
262typedef struct cgltf_extras {
263 cgltf_size start_offset; /* this field is deprecated and will be removed in the future; use data instead */
264 cgltf_size end_offset; /* this field is deprecated and will be removed in the future; use data instead */
265
266 char* data;
267} cgltf_extras;
268
269typedef struct cgltf_extension {
270 char* name;
271 char* data;
272} cgltf_extension;
273
274typedef struct cgltf_buffer
275{
276 char* name;
277 cgltf_size size;
278 char* uri;
279 void* data; /* loaded by cgltf_load_buffers */
280 cgltf_data_free_method data_free_method;
281 cgltf_extras extras;
282 cgltf_size extensions_count;
283 cgltf_extension* extensions;
284} cgltf_buffer;
285
286typedef enum cgltf_meshopt_compression_mode {
287 cgltf_meshopt_compression_mode_invalid,
288 cgltf_meshopt_compression_mode_attributes,
289 cgltf_meshopt_compression_mode_triangles,
290 cgltf_meshopt_compression_mode_indices,
291 cgltf_meshopt_compression_mode_max_enum
292} cgltf_meshopt_compression_mode;
293
294typedef enum cgltf_meshopt_compression_filter {
295 cgltf_meshopt_compression_filter_none,
296 cgltf_meshopt_compression_filter_octahedral,
297 cgltf_meshopt_compression_filter_quaternion,
298 cgltf_meshopt_compression_filter_exponential,
299 cgltf_meshopt_compression_filter_max_enum
300} cgltf_meshopt_compression_filter;
301
302typedef struct cgltf_meshopt_compression
303{
304 cgltf_buffer* buffer;
305 cgltf_size offset;
306 cgltf_size size;
307 cgltf_size stride;
308 cgltf_size count;
309 cgltf_meshopt_compression_mode mode;
310 cgltf_meshopt_compression_filter filter;
311} cgltf_meshopt_compression;
312
313typedef struct cgltf_buffer_view
314{
315 char *name;
316 cgltf_buffer* buffer;
317 cgltf_size offset;
318 cgltf_size size;
319 cgltf_size stride; /* 0 == automatically determined by accessor */
320 cgltf_buffer_view_type type;
321 void* data; /* overrides buffer->data if present, filled by extensions */
322 cgltf_bool has_meshopt_compression;
323 cgltf_meshopt_compression meshopt_compression;
324 cgltf_extras extras;
325 cgltf_size extensions_count;
326 cgltf_extension* extensions;
327} cgltf_buffer_view;
328
329typedef struct cgltf_accessor_sparse
330{
331 cgltf_size count;
332 cgltf_buffer_view* indices_buffer_view;
333 cgltf_size indices_byte_offset;
334 cgltf_component_type indices_component_type;
335 cgltf_buffer_view* values_buffer_view;
336 cgltf_size values_byte_offset;
337} cgltf_accessor_sparse;
338
339typedef struct cgltf_accessor
340{
341 char* name;
342 cgltf_component_type component_type;
343 cgltf_bool normalized;
344 cgltf_type type;
345 cgltf_size offset;
346 cgltf_size count;
347 cgltf_size stride;
348 cgltf_buffer_view* buffer_view;
349 cgltf_bool has_min;
350 cgltf_float min[16];
351 cgltf_bool has_max;
352 cgltf_float max[16];
353 cgltf_bool is_sparse;
354 cgltf_accessor_sparse sparse;
355 cgltf_extras extras;
356 cgltf_size extensions_count;
357 cgltf_extension* extensions;
358} cgltf_accessor;
359
360typedef struct cgltf_attribute
361{
362 char* name;
363 cgltf_attribute_type type;
364 cgltf_int index;
365 cgltf_accessor* data;
366} cgltf_attribute;
367
368typedef struct cgltf_image
369{
370 char* name;
371 char* uri;
372 cgltf_buffer_view* buffer_view;
373 char* mime_type;
374 cgltf_extras extras;
375 cgltf_size extensions_count;
376 cgltf_extension* extensions;
377} cgltf_image;
378
379typedef struct cgltf_sampler
380{
381 char* name;
382 cgltf_int mag_filter;
383 cgltf_int min_filter;
384 cgltf_int wrap_s;
385 cgltf_int wrap_t;
386 cgltf_extras extras;
387 cgltf_size extensions_count;
388 cgltf_extension* extensions;
389} cgltf_sampler;
390
391typedef struct cgltf_texture
392{
393 char* name;
394 cgltf_image* image;
395 cgltf_sampler* sampler;
396 cgltf_bool has_basisu;
397 cgltf_image* basisu_image;
398 cgltf_bool has_webp;
399 cgltf_image* webp_image;
400 cgltf_extras extras;
401 cgltf_size extensions_count;
402 cgltf_extension* extensions;
403} cgltf_texture;
404
405typedef struct cgltf_texture_transform
406{
407 cgltf_float offset[2];
408 cgltf_float rotation;
409 cgltf_float scale[2];
410 cgltf_bool has_texcoord;
411 cgltf_int texcoord;
412} cgltf_texture_transform;
413
414typedef struct cgltf_texture_view
415{
416 cgltf_texture* texture;
417 cgltf_int texcoord;
418 cgltf_float scale; /* equivalent to strength for occlusion_texture */
419 cgltf_bool has_transform;
420 cgltf_texture_transform transform;
421} cgltf_texture_view;
422
423typedef struct cgltf_pbr_metallic_roughness
424{
425 cgltf_texture_view base_color_texture;
426 cgltf_texture_view metallic_roughness_texture;
427
428 cgltf_float base_color_factor[4];
429 cgltf_float metallic_factor;
430 cgltf_float roughness_factor;
431} cgltf_pbr_metallic_roughness;
432
433typedef struct cgltf_pbr_specular_glossiness
434{
435 cgltf_texture_view diffuse_texture;
436 cgltf_texture_view specular_glossiness_texture;
437
438 cgltf_float diffuse_factor[4];
439 cgltf_float specular_factor[3];
440 cgltf_float glossiness_factor;
441} cgltf_pbr_specular_glossiness;
442
443typedef struct cgltf_clearcoat
444{
445 cgltf_texture_view clearcoat_texture;
446 cgltf_texture_view clearcoat_roughness_texture;
447 cgltf_texture_view clearcoat_normal_texture;
448
449 cgltf_float clearcoat_factor;
450 cgltf_float clearcoat_roughness_factor;
451} cgltf_clearcoat;
452
453typedef struct cgltf_transmission
454{
455 cgltf_texture_view transmission_texture;
456 cgltf_float transmission_factor;
457} cgltf_transmission;
458
459typedef struct cgltf_ior
460{
461 cgltf_float ior;
462} cgltf_ior;
463
464typedef struct cgltf_specular
465{
466 cgltf_texture_view specular_texture;
467 cgltf_texture_view specular_color_texture;
468 cgltf_float specular_color_factor[3];
469 cgltf_float specular_factor;
470} cgltf_specular;
471
472typedef struct cgltf_volume
473{
474 cgltf_texture_view thickness_texture;
475 cgltf_float thickness_factor;
476 cgltf_float attenuation_color[3];
477 cgltf_float attenuation_distance;
478} cgltf_volume;
479
480typedef struct cgltf_sheen
481{
482 cgltf_texture_view sheen_color_texture;
483 cgltf_float sheen_color_factor[3];
484 cgltf_texture_view sheen_roughness_texture;
485 cgltf_float sheen_roughness_factor;
486} cgltf_sheen;
487
488typedef struct cgltf_emissive_strength
489{
490 cgltf_float emissive_strength;
491} cgltf_emissive_strength;
492
493typedef struct cgltf_iridescence
494{
495 cgltf_float iridescence_factor;
496 cgltf_texture_view iridescence_texture;
497 cgltf_float iridescence_ior;
498 cgltf_float iridescence_thickness_min;
499 cgltf_float iridescence_thickness_max;
500 cgltf_texture_view iridescence_thickness_texture;
501} cgltf_iridescence;
502
503typedef struct cgltf_anisotropy
504{
505 cgltf_float anisotropy_strength;
506 cgltf_float anisotropy_rotation;
507 cgltf_texture_view anisotropy_texture;
508} cgltf_anisotropy;
509
510typedef struct cgltf_dispersion
511{
512 cgltf_float dispersion;
513} cgltf_dispersion;
514
515typedef struct cgltf_material
516{
517 char* name;
518 cgltf_bool has_pbr_metallic_roughness;
519 cgltf_bool has_pbr_specular_glossiness;
520 cgltf_bool has_clearcoat;
521 cgltf_bool has_transmission;
522 cgltf_bool has_volume;
523 cgltf_bool has_ior;
524 cgltf_bool has_specular;
525 cgltf_bool has_sheen;
526 cgltf_bool has_emissive_strength;
527 cgltf_bool has_iridescence;
528 cgltf_bool has_anisotropy;
529 cgltf_bool has_dispersion;
530 cgltf_pbr_metallic_roughness pbr_metallic_roughness;
531 cgltf_pbr_specular_glossiness pbr_specular_glossiness;
532 cgltf_clearcoat clearcoat;
533 cgltf_ior ior;
534 cgltf_specular specular;
535 cgltf_sheen sheen;
536 cgltf_transmission transmission;
537 cgltf_volume volume;
538 cgltf_emissive_strength emissive_strength;
539 cgltf_iridescence iridescence;
540 cgltf_anisotropy anisotropy;
541 cgltf_dispersion dispersion;
542 cgltf_texture_view normal_texture;
543 cgltf_texture_view occlusion_texture;
544 cgltf_texture_view emissive_texture;
545 cgltf_float emissive_factor[3];
546 cgltf_alpha_mode alpha_mode;
547 cgltf_float alpha_cutoff;
548 cgltf_bool double_sided;
549 cgltf_bool unlit;
550 cgltf_extras extras;
551 cgltf_size extensions_count;
552 cgltf_extension* extensions;
553} cgltf_material;
554
555typedef struct cgltf_material_mapping
556{
557 cgltf_size variant;
558 cgltf_material* material;
559 cgltf_extras extras;
560} cgltf_material_mapping;
561
562typedef struct cgltf_morph_target {
563 cgltf_attribute* attributes;
564 cgltf_size attributes_count;
565} cgltf_morph_target;
566
567typedef struct cgltf_draco_mesh_compression {
568 cgltf_buffer_view* buffer_view;
569 cgltf_attribute* attributes;
570 cgltf_size attributes_count;
571} cgltf_draco_mesh_compression;
572
573typedef struct cgltf_mesh_gpu_instancing {
574 cgltf_attribute* attributes;
575 cgltf_size attributes_count;
576} cgltf_mesh_gpu_instancing;
577
578typedef struct cgltf_primitive {
579 cgltf_primitive_type type;
580 cgltf_accessor* indices;
581 cgltf_material* material;
582 cgltf_attribute* attributes;
583 cgltf_size attributes_count;
584 cgltf_morph_target* targets;
585 cgltf_size targets_count;
586 cgltf_extras extras;
587 cgltf_bool has_draco_mesh_compression;
588 cgltf_draco_mesh_compression draco_mesh_compression;
589 cgltf_material_mapping* mappings;
590 cgltf_size mappings_count;
591 cgltf_size extensions_count;
592 cgltf_extension* extensions;
593} cgltf_primitive;
594
595typedef struct cgltf_mesh {
596 char* name;
597 cgltf_primitive* primitives;
598 cgltf_size primitives_count;
599 cgltf_float* weights;
600 cgltf_size weights_count;
601 char** target_names;
602 cgltf_size target_names_count;
603 cgltf_extras extras;
604 cgltf_size extensions_count;
605 cgltf_extension* extensions;
606} cgltf_mesh;
607
608typedef struct cgltf_node cgltf_node;
609
610typedef struct cgltf_skin {
611 char* name;
612 cgltf_node** joints;
613 cgltf_size joints_count;
614 cgltf_node* skeleton;
615 cgltf_accessor* inverse_bind_matrices;
616 cgltf_extras extras;
617 cgltf_size extensions_count;
618 cgltf_extension* extensions;
619} cgltf_skin;
620
621typedef struct cgltf_camera_perspective {
622 cgltf_bool has_aspect_ratio;
623 cgltf_float aspect_ratio;
624 cgltf_float yfov;
625 cgltf_bool has_zfar;
626 cgltf_float zfar;
627 cgltf_float znear;
628 cgltf_extras extras;
629} cgltf_camera_perspective;
630
631typedef struct cgltf_camera_orthographic {
632 cgltf_float xmag;
633 cgltf_float ymag;
634 cgltf_float zfar;
635 cgltf_float znear;
636 cgltf_extras extras;
637} cgltf_camera_orthographic;
638
639typedef struct cgltf_camera {
640 char* name;
641 cgltf_camera_type type;
642 union {
643 cgltf_camera_perspective perspective;
644 cgltf_camera_orthographic orthographic;
645 } data;
646 cgltf_extras extras;
647 cgltf_size extensions_count;
648 cgltf_extension* extensions;
649} cgltf_camera;
650
651typedef struct cgltf_light {
652 char* name;
653 cgltf_float color[3];
654 cgltf_float intensity;
655 cgltf_light_type type;
656 cgltf_float range;
657 cgltf_float spot_inner_cone_angle;
658 cgltf_float spot_outer_cone_angle;
659 cgltf_extras extras;
660} cgltf_light;
661
662struct cgltf_node {
663 char* name;
664 cgltf_node* parent;
665 cgltf_node** children;
666 cgltf_size children_count;
667 cgltf_skin* skin;
668 cgltf_mesh* mesh;
669 cgltf_camera* camera;
670 cgltf_light* light;
671 cgltf_float* weights;
672 cgltf_size weights_count;
673 cgltf_bool has_translation;
674 cgltf_bool has_rotation;
675 cgltf_bool has_scale;
676 cgltf_bool has_matrix;
677 cgltf_float translation[3];
678 cgltf_float rotation[4];
679 cgltf_float scale[3];
680 cgltf_float matrix[16];
681 cgltf_extras extras;
682 cgltf_bool has_mesh_gpu_instancing;
683 cgltf_mesh_gpu_instancing mesh_gpu_instancing;
684 cgltf_size extensions_count;
685 cgltf_extension* extensions;
686};
687
688typedef struct cgltf_scene {
689 char* name;
690 cgltf_node** nodes;
691 cgltf_size nodes_count;
692 cgltf_extras extras;
693 cgltf_size extensions_count;
694 cgltf_extension* extensions;
695} cgltf_scene;
696
697typedef struct cgltf_animation_sampler {
698 cgltf_accessor* input;
699 cgltf_accessor* output;
700 cgltf_interpolation_type interpolation;
701 cgltf_extras extras;
702 cgltf_size extensions_count;
703 cgltf_extension* extensions;
704} cgltf_animation_sampler;
705
706typedef struct cgltf_animation_channel {
707 cgltf_animation_sampler* sampler;
708 cgltf_node* target_node;
709 cgltf_animation_path_type target_path;
710 cgltf_extras extras;
711 cgltf_size extensions_count;
712 cgltf_extension* extensions;
713} cgltf_animation_channel;
714
715typedef struct cgltf_animation {
716 char* name;
717 cgltf_animation_sampler* samplers;
718 cgltf_size samplers_count;
719 cgltf_animation_channel* channels;
720 cgltf_size channels_count;
721 cgltf_extras extras;
722 cgltf_size extensions_count;
723 cgltf_extension* extensions;
724} cgltf_animation;
725
726typedef struct cgltf_material_variant
727{
728 char* name;
729 cgltf_extras extras;
730} cgltf_material_variant;
731
732typedef struct cgltf_asset {
733 char* copyright;
734 char* generator;
735 char* version;
736 char* min_version;
737 cgltf_extras extras;
738 cgltf_size extensions_count;
739 cgltf_extension* extensions;
740} cgltf_asset;
741
742typedef struct cgltf_data
743{
744 cgltf_file_type file_type;
745 void* file_data;
746
747 cgltf_asset asset;
748
749 cgltf_mesh* meshes;
750 cgltf_size meshes_count;
751
752 cgltf_material* materials;
753 cgltf_size materials_count;
754
755 cgltf_accessor* accessors;
756 cgltf_size accessors_count;
757
758 cgltf_buffer_view* buffer_views;
759 cgltf_size buffer_views_count;
760
761 cgltf_buffer* buffers;
762 cgltf_size buffers_count;
763
764 cgltf_image* images;
765 cgltf_size images_count;
766
767 cgltf_texture* textures;
768 cgltf_size textures_count;
769
770 cgltf_sampler* samplers;
771 cgltf_size samplers_count;
772
773 cgltf_skin* skins;
774 cgltf_size skins_count;
775
776 cgltf_camera* cameras;
777 cgltf_size cameras_count;
778
779 cgltf_light* lights;
780 cgltf_size lights_count;
781
782 cgltf_node* nodes;
783 cgltf_size nodes_count;
784
785 cgltf_scene* scenes;
786 cgltf_size scenes_count;
787
788 cgltf_scene* scene;
789
790 cgltf_animation* animations;
791 cgltf_size animations_count;
792
793 cgltf_material_variant* variants;
794 cgltf_size variants_count;
795
796 cgltf_extras extras;
797
798 cgltf_size data_extensions_count;
799 cgltf_extension* data_extensions;
800
801 char** extensions_used;
802 cgltf_size extensions_used_count;
803
804 char** extensions_required;
805 cgltf_size extensions_required_count;
806
807 const char* json;
808 cgltf_size json_size;
809
810 const void* bin;
811 cgltf_size bin_size;
812
813 cgltf_memory_options memory;
814 cgltf_file_options file;
815} cgltf_data;
816
817cgltf_result cgltf_parse(
818 const cgltf_options* options,
819 const void* data,
820 cgltf_size size,
821 cgltf_data** out_data);
822
823cgltf_result cgltf_parse_file(
824 const cgltf_options* options,
825 const char* path,
826 cgltf_data** out_data);
827
828cgltf_result cgltf_load_buffers(
829 const cgltf_options* options,
830 cgltf_data* data,
831 const char* gltf_path);
832
833cgltf_result cgltf_load_buffer_base64(const cgltf_options* options, cgltf_size size, const char* base64, void** out_data);
834
835cgltf_size cgltf_decode_string(char* string);
836cgltf_size cgltf_decode_uri(char* uri);
837
838cgltf_result cgltf_validate(cgltf_data* data);
839
840void cgltf_free(cgltf_data* data);
841
842void cgltf_node_transform_local(const cgltf_node* node, cgltf_float* out_matrix);
843void cgltf_node_transform_world(const cgltf_node* node, cgltf_float* out_matrix);
844
845const uint8_t* cgltf_buffer_view_data(const cgltf_buffer_view* view);
846
847cgltf_bool cgltf_accessor_read_float(const cgltf_accessor* accessor, cgltf_size index, cgltf_float* out, cgltf_size element_size);
848cgltf_bool cgltf_accessor_read_uint(const cgltf_accessor* accessor, cgltf_size index, cgltf_uint* out, cgltf_size element_size);
849cgltf_size cgltf_accessor_read_index(const cgltf_accessor* accessor, cgltf_size index);
850
851cgltf_size cgltf_num_components(cgltf_type type);
852cgltf_size cgltf_component_size(cgltf_component_type component_type);
853cgltf_size cgltf_calc_size(cgltf_type type, cgltf_component_type component_type);
854
855cgltf_size cgltf_accessor_unpack_floats(const cgltf_accessor* accessor, cgltf_float* out, cgltf_size float_count);
856cgltf_size cgltf_accessor_unpack_indices(const cgltf_accessor* accessor, void* out, cgltf_size out_component_size, cgltf_size index_count);
857
858/* this function is deprecated and will be removed in the future; use cgltf_extras::data instead */
859cgltf_result cgltf_copy_extras_json(const cgltf_data* data, const cgltf_extras* extras, char* dest, cgltf_size* dest_size);
860
861cgltf_size cgltf_mesh_index(const cgltf_data* data, const cgltf_mesh* object);
862cgltf_size cgltf_material_index(const cgltf_data* data, const cgltf_material* object);
863cgltf_size cgltf_accessor_index(const cgltf_data* data, const cgltf_accessor* object);
864cgltf_size cgltf_buffer_view_index(const cgltf_data* data, const cgltf_buffer_view* object);
865cgltf_size cgltf_buffer_index(const cgltf_data* data, const cgltf_buffer* object);
866cgltf_size cgltf_image_index(const cgltf_data* data, const cgltf_image* object);
867cgltf_size cgltf_texture_index(const cgltf_data* data, const cgltf_texture* object);
868cgltf_size cgltf_sampler_index(const cgltf_data* data, const cgltf_sampler* object);
869cgltf_size cgltf_skin_index(const cgltf_data* data, const cgltf_skin* object);
870cgltf_size cgltf_camera_index(const cgltf_data* data, const cgltf_camera* object);
871cgltf_size cgltf_light_index(const cgltf_data* data, const cgltf_light* object);
872cgltf_size cgltf_node_index(const cgltf_data* data, const cgltf_node* object);
873cgltf_size cgltf_scene_index(const cgltf_data* data, const cgltf_scene* object);
874cgltf_size cgltf_animation_index(const cgltf_data* data, const cgltf_animation* object);
875cgltf_size cgltf_animation_sampler_index(const cgltf_animation* animation, const cgltf_animation_sampler* object);
876cgltf_size cgltf_animation_channel_index(const cgltf_animation* animation, const cgltf_animation_channel* object);
877
878#ifdef __cplusplus
879}
880#endif
881
882#endif /* #ifndef CGLTF_H_INCLUDED__ */
883
884/*
885 *
886 * Stop now, if you are only interested in the API.
887 * Below, you find the implementation.
888 *
889 */
890
891#if defined(__INTELLISENSE__) || defined(__JETBRAINS_IDE__)
892/* This makes MSVC/CLion intellisense work. */
893#define CGLTF_IMPLEMENTATION
894#endif
895
896#ifdef CGLTF_IMPLEMENTATION
897
898#include <assert.h> /* For assert */
899#include <string.h> /* For strncpy */
900#include <stdio.h> /* For fopen */
901#include <limits.h> /* For UINT_MAX etc */
902#include <float.h> /* For FLT_MAX */
903
904#if !defined(CGLTF_MALLOC) || !defined(CGLTF_FREE) || !defined(CGLTF_ATOI) || !defined(CGLTF_ATOF) || !defined(CGLTF_ATOLL)
905#include <stdlib.h> /* For malloc, free, atoi, atof */
906#endif
907
908/* JSMN_PARENT_LINKS is necessary to make parsing large structures linear in input size */
909#define JSMN_PARENT_LINKS
910
911/* JSMN_STRICT is necessary to reject invalid JSON documents */
912#define JSMN_STRICT
913
914/*
915 * -- jsmn.h start --
916 * Source: https://github.com/zserge/jsmn
917 * License: MIT
918 */
919typedef enum {
920 JSMN_UNDEFINED = 0,
921 JSMN_OBJECT = 1,
922 JSMN_ARRAY = 2,
923 JSMN_STRING = 3,
924 JSMN_PRIMITIVE = 4
925} jsmntype_t;
926enum jsmnerr {
927 /* Not enough tokens were provided */
928 JSMN_ERROR_NOMEM = -1,
929 /* Invalid character inside JSON string */
930 JSMN_ERROR_INVAL = -2,
931 /* The string is not a full JSON packet, more bytes expected */
932 JSMN_ERROR_PART = -3
933};
934typedef struct {
935 jsmntype_t type;
936 ptrdiff_t start;
937 ptrdiff_t end;
938 int size;
939#ifdef JSMN_PARENT_LINKS
940 int parent;
941#endif
942} jsmntok_t;
943typedef struct {
944 size_t pos; /* offset in the JSON string */
945 unsigned int toknext; /* next token to allocate */
946 int toksuper; /* superior token node, e.g parent object or array */
947} jsmn_parser;
948static void jsmn_init(jsmn_parser *parser);
949static int jsmn_parse(jsmn_parser *parser, const char *js, size_t len, jsmntok_t *tokens, size_t num_tokens);
950/*
951 * -- jsmn.h end --
952 */
953
954
955#ifndef CGLTF_CONSTS
956#define GlbHeaderSize 12
957#define GlbChunkHeaderSize 8
958static const uint32_t GlbVersion = 2;
959static const uint32_t GlbMagic = 0x46546C67;
960static const uint32_t GlbMagicJsonChunk = 0x4E4F534A;
961static const uint32_t GlbMagicBinChunk = 0x004E4942;
962#define CGLTF_CONSTS
963#endif
964
965#ifndef CGLTF_MALLOC
966#define CGLTF_MALLOC(size) malloc(size)
967#endif
968#ifndef CGLTF_FREE
969#define CGLTF_FREE(ptr) free(ptr)
970#endif
971#ifndef CGLTF_ATOI
972#define CGLTF_ATOI(str) atoi(str)
973#endif
974#ifndef CGLTF_ATOF
975#define CGLTF_ATOF(str) atof(str)
976#endif
977#ifndef CGLTF_ATOLL
978#define CGLTF_ATOLL(str) atoll(str)
979#endif
980#ifndef CGLTF_VALIDATE_ENABLE_ASSERTS
981#define CGLTF_VALIDATE_ENABLE_ASSERTS 0
982#endif
983
984static void* cgltf_default_alloc(void* user, cgltf_size size)
985{
986 (void)user;
987 return CGLTF_MALLOC(size);
988}
989
990static void cgltf_default_free(void* user, void* ptr)
991{
992 (void)user;
993 CGLTF_FREE(ptr);
994}
995
996static void* cgltf_calloc(cgltf_options* options, size_t element_size, cgltf_size count)
997{
998 if (SIZE_MAX / element_size < count)
999 {
1000 return NULL;
1001 }
1002 void* result = options->memory.alloc_func(options->memory.user_data, element_size * count);
1003 if (!result)
1004 {
1005 return NULL;
1006 }
1007 memset(result, 0, element_size * count);
1008 return result;
1009}
1010
1011static cgltf_result cgltf_default_file_read(const struct cgltf_memory_options* memory_options, const struct cgltf_file_options* file_options, const char* path, cgltf_size* size, void** data)
1012{
1013 (void)file_options;
1014 void* (*memory_alloc)(void*, cgltf_size) = memory_options->alloc_func ? memory_options->alloc_func : &cgltf_default_alloc;
1015 void (*memory_free)(void*, void*) = memory_options->free_func ? memory_options->free_func : &cgltf_default_free;
1016
1017 FILE* file = fopen(path, "rb");
1018 if (!file)
1019 {
1020 return cgltf_result_file_not_found;
1021 }
1022
1023 cgltf_size file_size = size ? *size : 0;
1024
1025 if (file_size == 0)
1026 {
1027 fseek(file, 0, SEEK_END);
1028
1029#ifdef _MSC_VER
1030 __int64 length = _ftelli64(file);
1031#else
1032 long length = ftell(file);
1033#endif
1034
1035 if (length < 0)
1036 {
1037 fclose(file);
1038 return cgltf_result_io_error;
1039 }
1040
1041 fseek(file, 0, SEEK_SET);
1042 file_size = (cgltf_size)length;
1043 }
1044
1045 char* file_data = (char*)memory_alloc(memory_options->user_data, file_size);
1046 if (!file_data)
1047 {
1048 fclose(file);
1049 return cgltf_result_out_of_memory;
1050 }
1051
1052 cgltf_size read_size = fread(file_data, 1, file_size, file);
1053
1054 fclose(file);
1055
1056 if (read_size != file_size)
1057 {
1058 memory_free(memory_options->user_data, file_data);
1059 return cgltf_result_io_error;
1060 }
1061
1062 if (size)
1063 {
1064 *size = file_size;
1065 }
1066 if (data)
1067 {
1068 *data = file_data;
1069 }
1070
1071 return cgltf_result_success;
1072}
1073
1074static void cgltf_default_file_release(const struct cgltf_memory_options* memory_options, const struct cgltf_file_options* file_options, void* data)
1075{
1076 (void)file_options;
1077 void (*memfree)(void*, void*) = memory_options->free_func ? memory_options->free_func : &cgltf_default_free;
1078 memfree(memory_options->user_data, data);
1079}
1080
1081static cgltf_result cgltf_parse_json(cgltf_options* options, const uint8_t* json_chunk, cgltf_size size, cgltf_data** out_data);
1082
1083cgltf_result cgltf_parse(const cgltf_options* options, const void* data, cgltf_size size, cgltf_data** out_data)
1084{
1085 if (size < GlbHeaderSize)
1086 {
1087 return cgltf_result_data_too_short;
1088 }
1089
1090 if (options == NULL)
1091 {
1092 return cgltf_result_invalid_options;
1093 }
1094
1095 cgltf_options fixed_options = *options;
1096 if (fixed_options.memory.alloc_func == NULL)
1097 {
1098 fixed_options.memory.alloc_func = &cgltf_default_alloc;
1099 }
1100 if (fixed_options.memory.free_func == NULL)
1101 {
1102 fixed_options.memory.free_func = &cgltf_default_free;
1103 }
1104
1105 uint32_t tmp;
1106 // Magic
1107 memcpy(&tmp, data, 4);
1108 if (tmp != GlbMagic)
1109 {
1110 if (fixed_options.type == cgltf_file_type_invalid)
1111 {
1112 fixed_options.type = cgltf_file_type_gltf;
1113 }
1114 else if (fixed_options.type == cgltf_file_type_glb)
1115 {
1116 return cgltf_result_unknown_format;
1117 }
1118 }
1119
1120 if (fixed_options.type == cgltf_file_type_gltf)
1121 {
1122 cgltf_result json_result = cgltf_parse_json(&fixed_options, (const uint8_t*)data, size, out_data);
1123 if (json_result != cgltf_result_success)
1124 {
1125 return json_result;
1126 }
1127
1128 (*out_data)->file_type = cgltf_file_type_gltf;
1129
1130 return cgltf_result_success;
1131 }
1132
1133 const uint8_t* ptr = (const uint8_t*)data;
1134 // Version
1135 memcpy(&tmp, ptr + 4, 4);
1136 uint32_t version = tmp;
1137 if (version != GlbVersion)
1138 {
1139 return version < GlbVersion ? cgltf_result_legacy_gltf : cgltf_result_unknown_format;
1140 }
1141
1142 // Total length
1143 memcpy(&tmp, ptr + 8, 4);
1144 if (tmp > size)
1145 {
1146 return cgltf_result_data_too_short;
1147 }
1148
1149 const uint8_t* json_chunk = ptr + GlbHeaderSize;
1150
1151 if (GlbHeaderSize + GlbChunkHeaderSize > size)
1152 {
1153 return cgltf_result_data_too_short;
1154 }
1155
1156 // JSON chunk: length
1157 uint32_t json_length;
1158 memcpy(&json_length, json_chunk, 4);
1159 if (json_length > size - GlbHeaderSize - GlbChunkHeaderSize)
1160 {
1161 return cgltf_result_data_too_short;
1162 }
1163
1164 // JSON chunk: magic
1165 memcpy(&tmp, json_chunk + 4, 4);
1166 if (tmp != GlbMagicJsonChunk)
1167 {
1168 return cgltf_result_unknown_format;
1169 }
1170
1171 json_chunk += GlbChunkHeaderSize;
1172
1173 const void* bin = NULL;
1174 cgltf_size bin_size = 0;
1175
1176 if (GlbChunkHeaderSize <= size - GlbHeaderSize - GlbChunkHeaderSize - json_length)
1177 {
1178 // We can read another chunk
1179 const uint8_t* bin_chunk = json_chunk + json_length;
1180
1181 // Bin chunk: length
1182 uint32_t bin_length;
1183 memcpy(&bin_length, bin_chunk, 4);
1184 if (bin_length > size - GlbHeaderSize - GlbChunkHeaderSize - json_length - GlbChunkHeaderSize)
1185 {
1186 return cgltf_result_data_too_short;
1187 }
1188
1189 // Bin chunk: magic
1190 memcpy(&tmp, bin_chunk + 4, 4);
1191 if (tmp != GlbMagicBinChunk)
1192 {
1193 return cgltf_result_unknown_format;
1194 }
1195
1196 bin_chunk += GlbChunkHeaderSize;
1197
1198 bin = bin_chunk;
1199 bin_size = bin_length;
1200 }
1201
1202 cgltf_result json_result = cgltf_parse_json(&fixed_options, json_chunk, json_length, out_data);
1203 if (json_result != cgltf_result_success)
1204 {
1205 return json_result;
1206 }
1207
1208 (*out_data)->file_type = cgltf_file_type_glb;
1209 (*out_data)->bin = bin;
1210 (*out_data)->bin_size = bin_size;
1211
1212 return cgltf_result_success;
1213}
1214
1215cgltf_result cgltf_parse_file(const cgltf_options* options, const char* path, cgltf_data** out_data)
1216{
1217 if (options == NULL)
1218 {
1219 return cgltf_result_invalid_options;
1220 }
1221
1222 cgltf_result (*file_read)(const struct cgltf_memory_options*, const struct cgltf_file_options*, const char*, cgltf_size*, void**) = options->file.read ? options->file.read : &cgltf_default_file_read;
1223 void (*file_release)(const struct cgltf_memory_options*, const struct cgltf_file_options*, void* data) = options->file.release ? options->file.release : cgltf_default_file_release;
1224
1225 void* file_data = NULL;
1226 cgltf_size file_size = 0;
1227 cgltf_result result = file_read(&options->memory, &options->file, path, &file_size, &file_data);
1228 if (result != cgltf_result_success)
1229 {
1230 return result;
1231 }
1232
1233 result = cgltf_parse(options, file_data, file_size, out_data);
1234
1235 if (result != cgltf_result_success)
1236 {
1237 file_release(&options->memory, &options->file, file_data);
1238 return result;
1239 }
1240
1241 (*out_data)->file_data = file_data;
1242
1243 return cgltf_result_success;
1244}
1245
1246static void cgltf_combine_paths(char* path, const char* base, const char* uri)
1247{
1248 const char* s0 = strrchr(base, '/');
1249 const char* s1 = strrchr(base, '\\');
1250 const char* slash = s0 ? (s1 && s1 > s0 ? s1 : s0) : s1;
1251
1252 if (slash)
1253 {
1254 size_t prefix = slash - base + 1;
1255
1256 strncpy(path, base, prefix);
1257 strcpy(path + prefix, uri);
1258 }
1259 else
1260 {
1261 strcpy(path, uri);
1262 }
1263}
1264
1265static cgltf_result cgltf_load_buffer_file(const cgltf_options* options, cgltf_size size, const char* uri, const char* gltf_path, void** out_data)
1266{
1267 void* (*memory_alloc)(void*, cgltf_size) = options->memory.alloc_func ? options->memory.alloc_func : &cgltf_default_alloc;
1268 void (*memory_free)(void*, void*) = options->memory.free_func ? options->memory.free_func : &cgltf_default_free;
1269 cgltf_result (*file_read)(const struct cgltf_memory_options*, const struct cgltf_file_options*, const char*, cgltf_size*, void**) = options->file.read ? options->file.read : &cgltf_default_file_read;
1270
1271 char* path = (char*)memory_alloc(options->memory.user_data, strlen(uri) + strlen(gltf_path) + 1);
1272 if (!path)
1273 {
1274 return cgltf_result_out_of_memory;
1275 }
1276
1277 cgltf_combine_paths(path, gltf_path, uri);
1278
1279 // after combining, the tail of the resulting path is a uri; decode_uri converts it into path
1280 cgltf_decode_uri(path + strlen(path) - strlen(uri));
1281
1282 void* file_data = NULL;
1283 cgltf_result result = file_read(&options->memory, &options->file, path, &size, &file_data);
1284
1285 memory_free(options->memory.user_data, path);
1286
1287 *out_data = (result == cgltf_result_success) ? file_data : NULL;
1288
1289 return result;
1290}
1291
1292cgltf_result cgltf_load_buffer_base64(const cgltf_options* options, cgltf_size size, const char* base64, void** out_data)
1293{
1294 void* (*memory_alloc)(void*, cgltf_size) = options->memory.alloc_func ? options->memory.alloc_func : &cgltf_default_alloc;
1295 void (*memory_free)(void*, void*) = options->memory.free_func ? options->memory.free_func : &cgltf_default_free;
1296
1297 unsigned char* data = (unsigned char*)memory_alloc(options->memory.user_data, size);
1298 if (!data)
1299 {
1300 return cgltf_result_out_of_memory;
1301 }
1302
1303 unsigned int buffer = 0;
1304 unsigned int buffer_bits = 0;
1305
1306 for (cgltf_size i = 0; i < size; ++i)
1307 {
1308 while (buffer_bits < 8)
1309 {
1310 char ch = *base64++;
1311
1312 int index =
1313 (unsigned)(ch - 'A') < 26 ? (ch - 'A') :
1314 (unsigned)(ch - 'a') < 26 ? (ch - 'a') + 26 :
1315 (unsigned)(ch - '0') < 10 ? (ch - '0') + 52 :
1316 ch == '+' ? 62 :
1317 ch == '/' ? 63 :
1318 -1;
1319
1320 if (index < 0)
1321 {
1322 memory_free(options->memory.user_data, data);
1323 return cgltf_result_io_error;
1324 }
1325
1326 buffer = (buffer << 6) | index;
1327 buffer_bits += 6;
1328 }
1329
1330 data[i] = (unsigned char)(buffer >> (buffer_bits - 8));
1331 buffer_bits -= 8;
1332 }
1333
1334 *out_data = data;
1335
1336 return cgltf_result_success;
1337}
1338
1339static int cgltf_unhex(char ch)
1340{
1341 return
1342 (unsigned)(ch - '0') < 10 ? (ch - '0') :
1343 (unsigned)(ch - 'A') < 6 ? (ch - 'A') + 10 :
1344 (unsigned)(ch - 'a') < 6 ? (ch - 'a') + 10 :
1345 -1;
1346}
1347
1348cgltf_size cgltf_decode_string(char* string)
1349{
1350 char* read = string + strcspn(string, "\\");
1351 if (*read == 0)
1352 {
1353 return read - string;
1354 }
1355 char* write = string;
1356 char* last = string;
1357
1358 for (;;)
1359 {
1360 // Copy characters since last escaped sequence
1361 cgltf_size written = read - last;
1362 memmove(write, last, written);
1363 write += written;
1364
1365 if (*read++ == 0)
1366 {
1367 break;
1368 }
1369
1370 // jsmn already checked that all escape sequences are valid
1371 switch (*read++)
1372 {
1373 case '\"': *write++ = '\"'; break;
1374 case '/': *write++ = '/'; break;
1375 case '\\': *write++ = '\\'; break;
1376 case 'b': *write++ = '\b'; break;
1377 case 'f': *write++ = '\f'; break;
1378 case 'r': *write++ = '\r'; break;
1379 case 'n': *write++ = '\n'; break;
1380 case 't': *write++ = '\t'; break;
1381 case 'u':
1382 {
1383 // UCS-2 codepoint \uXXXX to UTF-8
1384 int character = 0;
1385 for (cgltf_size i = 0; i < 4; ++i)
1386 {
1387 character = (character << 4) + cgltf_unhex(*read++);
1388 }
1389
1390 if (character <= 0x7F)
1391 {
1392 *write++ = character & 0xFF;
1393 }
1394 else if (character <= 0x7FF)
1395 {
1396 *write++ = 0xC0 | ((character >> 6) & 0xFF);
1397 *write++ = 0x80 | (character & 0x3F);
1398 }
1399 else
1400 {
1401 *write++ = 0xE0 | ((character >> 12) & 0xFF);
1402 *write++ = 0x80 | ((character >> 6) & 0x3F);
1403 *write++ = 0x80 | (character & 0x3F);
1404 }
1405 break;
1406 }
1407 default:
1408 break;
1409 }
1410
1411 last = read;
1412 read += strcspn(read, "\\");
1413 }
1414
1415 *write = 0;
1416 return write - string;
1417}
1418
1419cgltf_size cgltf_decode_uri(char* uri)
1420{
1421 char* write = uri;
1422 char* i = uri;
1423
1424 while (*i)
1425 {
1426 if (*i == '%')
1427 {
1428 int ch1 = cgltf_unhex(i[1]);
1429
1430 if (ch1 >= 0)
1431 {
1432 int ch2 = cgltf_unhex(i[2]);
1433
1434 if (ch2 >= 0)
1435 {
1436 *write++ = (char)(ch1 * 16 + ch2);
1437 i += 3;
1438 continue;
1439 }
1440 }
1441 }
1442
1443 *write++ = *i++;
1444 }
1445
1446 *write = 0;
1447 return write - uri;
1448}
1449
1450cgltf_result cgltf_load_buffers(const cgltf_options* options, cgltf_data* data, const char* gltf_path)
1451{
1452 if (options == NULL)
1453 {
1454 return cgltf_result_invalid_options;
1455 }
1456
1457 if (data->buffers_count && data->buffers[0].data == NULL && data->buffers[0].uri == NULL && data->bin)
1458 {
1459 if (data->bin_size < data->buffers[0].size)
1460 {
1461 return cgltf_result_data_too_short;
1462 }
1463
1464 data->buffers[0].data = (void*)data->bin;
1465 data->buffers[0].data_free_method = cgltf_data_free_method_none;
1466 }
1467
1468 for (cgltf_size i = 0; i < data->buffers_count; ++i)
1469 {
1470 if (data->buffers[i].data)
1471 {
1472 continue;
1473 }
1474
1475 const char* uri = data->buffers[i].uri;
1476
1477 if (uri == NULL)
1478 {
1479 continue;
1480 }
1481
1482 if (strncmp(uri, "data:", 5) == 0)
1483 {
1484 const char* comma = strchr(uri, ',');
1485
1486 if (comma && comma - uri >= 7 && strncmp(comma - 7, ";base64", 7) == 0)
1487 {
1488 cgltf_result res = cgltf_load_buffer_base64(options, data->buffers[i].size, comma + 1, &data->buffers[i].data);
1489 data->buffers[i].data_free_method = cgltf_data_free_method_memory_free;
1490
1491 if (res != cgltf_result_success)
1492 {
1493 return res;
1494 }
1495 }
1496 else
1497 {
1498 return cgltf_result_unknown_format;
1499 }
1500 }
1501 else if (strstr(uri, "://") == NULL && gltf_path)
1502 {
1503 cgltf_result res = cgltf_load_buffer_file(options, data->buffers[i].size, uri, gltf_path, &data->buffers[i].data);
1504 data->buffers[i].data_free_method = cgltf_data_free_method_file_release;
1505
1506 if (res != cgltf_result_success)
1507 {
1508 return res;
1509 }
1510 }
1511 else
1512 {
1513 return cgltf_result_unknown_format;
1514 }
1515 }
1516
1517 return cgltf_result_success;
1518}
1519
1520static cgltf_size cgltf_calc_index_bound(cgltf_buffer_view* buffer_view, cgltf_size offset, cgltf_component_type component_type, cgltf_size count)
1521{
1522 char* data = (char*)buffer_view->buffer->data + offset + buffer_view->offset;
1523 cgltf_size bound = 0;
1524
1525 switch (component_type)
1526 {
1527 case cgltf_component_type_r_8u:
1528 for (size_t i = 0; i < count; ++i)
1529 {
1530 cgltf_size v = ((unsigned char*)data)[i];
1531 bound = bound > v ? bound : v;
1532 }
1533 break;
1534
1535 case cgltf_component_type_r_16u:
1536 for (size_t i = 0; i < count; ++i)
1537 {
1538 cgltf_size v = ((unsigned short*)data)[i];
1539 bound = bound > v ? bound : v;
1540 }
1541 break;
1542
1543 case cgltf_component_type_r_32u:
1544 for (size_t i = 0; i < count; ++i)
1545 {
1546 cgltf_size v = ((unsigned int*)data)[i];
1547 bound = bound > v ? bound : v;
1548 }
1549 break;
1550
1551 default:
1552 ;
1553 }
1554
1555 return bound;
1556}
1557
1558#if CGLTF_VALIDATE_ENABLE_ASSERTS
1559#define CGLTF_ASSERT_IF(cond, result) assert(!(cond)); if (cond) return result;
1560#else
1561#define CGLTF_ASSERT_IF(cond, result) if (cond) return result;
1562#endif
1563
1564cgltf_result cgltf_validate(cgltf_data* data)
1565{
1566 for (cgltf_size i = 0; i < data->accessors_count; ++i)
1567 {
1568 cgltf_accessor* accessor = &data->accessors[i];
1569
1570 CGLTF_ASSERT_IF(data->accessors[i].component_type == cgltf_component_type_invalid, cgltf_result_invalid_gltf);
1571 CGLTF_ASSERT_IF(data->accessors[i].type == cgltf_type_invalid, cgltf_result_invalid_gltf);
1572
1573 cgltf_size element_size = cgltf_calc_size(accessor->type, accessor->component_type);
1574
1575 if (accessor->buffer_view)
1576 {
1577 cgltf_size req_size = accessor->offset + accessor->stride * (accessor->count - 1) + element_size;
1578
1579 CGLTF_ASSERT_IF(accessor->buffer_view->size < req_size, cgltf_result_data_too_short);
1580 }
1581
1582 if (accessor->is_sparse)
1583 {
1584 cgltf_accessor_sparse* sparse = &accessor->sparse;
1585
1586 cgltf_size indices_component_size = cgltf_component_size(sparse->indices_component_type);
1587 cgltf_size indices_req_size = sparse->indices_byte_offset + indices_component_size * sparse->count;
1588 cgltf_size values_req_size = sparse->values_byte_offset + element_size * sparse->count;
1589
1590 CGLTF_ASSERT_IF(sparse->indices_buffer_view->size < indices_req_size ||
1591 sparse->values_buffer_view->size < values_req_size, cgltf_result_data_too_short);
1592
1593 CGLTF_ASSERT_IF(sparse->indices_component_type != cgltf_component_type_r_8u &&
1594 sparse->indices_component_type != cgltf_component_type_r_16u &&
1595 sparse->indices_component_type != cgltf_component_type_r_32u, cgltf_result_invalid_gltf);
1596
1597 if (sparse->indices_buffer_view->buffer->data)
1598 {
1599 cgltf_size index_bound = cgltf_calc_index_bound(sparse->indices_buffer_view, sparse->indices_byte_offset, sparse->indices_component_type, sparse->count);
1600
1601 CGLTF_ASSERT_IF(index_bound >= accessor->count, cgltf_result_data_too_short);
1602 }
1603 }
1604 }
1605
1606 for (cgltf_size i = 0; i < data->buffer_views_count; ++i)
1607 {
1608 cgltf_size req_size = data->buffer_views[i].offset + data->buffer_views[i].size;
1609
1610 CGLTF_ASSERT_IF(data->buffer_views[i].buffer && data->buffer_views[i].buffer->size < req_size, cgltf_result_data_too_short);
1611
1612 if (data->buffer_views[i].has_meshopt_compression)
1613 {
1614 cgltf_meshopt_compression* mc = &data->buffer_views[i].meshopt_compression;
1615
1616 CGLTF_ASSERT_IF(mc->buffer == NULL || mc->buffer->size < mc->offset + mc->size, cgltf_result_data_too_short);
1617
1618 CGLTF_ASSERT_IF(data->buffer_views[i].stride && mc->stride != data->buffer_views[i].stride, cgltf_result_invalid_gltf);
1619
1620 CGLTF_ASSERT_IF(data->buffer_views[i].size != mc->stride * mc->count, cgltf_result_invalid_gltf);
1621
1622 CGLTF_ASSERT_IF(mc->mode == cgltf_meshopt_compression_mode_invalid, cgltf_result_invalid_gltf);
1623
1624 CGLTF_ASSERT_IF(mc->mode == cgltf_meshopt_compression_mode_attributes && !(mc->stride % 4 == 0 && mc->stride <= 256), cgltf_result_invalid_gltf);
1625
1626 CGLTF_ASSERT_IF(mc->mode == cgltf_meshopt_compression_mode_triangles && mc->count % 3 != 0, cgltf_result_invalid_gltf);
1627
1628 CGLTF_ASSERT_IF((mc->mode == cgltf_meshopt_compression_mode_triangles || mc->mode == cgltf_meshopt_compression_mode_indices) && mc->stride != 2 && mc->stride != 4, cgltf_result_invalid_gltf);
1629
1630 CGLTF_ASSERT_IF((mc->mode == cgltf_meshopt_compression_mode_triangles || mc->mode == cgltf_meshopt_compression_mode_indices) && mc->filter != cgltf_meshopt_compression_filter_none, cgltf_result_invalid_gltf);
1631
1632 CGLTF_ASSERT_IF(mc->filter == cgltf_meshopt_compression_filter_octahedral && mc->stride != 4 && mc->stride != 8, cgltf_result_invalid_gltf);
1633
1634 CGLTF_ASSERT_IF(mc->filter == cgltf_meshopt_compression_filter_quaternion && mc->stride != 8, cgltf_result_invalid_gltf);
1635 }
1636 }
1637
1638 for (cgltf_size i = 0; i < data->meshes_count; ++i)
1639 {
1640 if (data->meshes[i].weights)
1641 {
1642 CGLTF_ASSERT_IF(data->meshes[i].primitives_count && data->meshes[i].primitives[0].targets_count != data->meshes[i].weights_count, cgltf_result_invalid_gltf);
1643 }
1644
1645 if (data->meshes[i].target_names)
1646 {
1647 CGLTF_ASSERT_IF(data->meshes[i].primitives_count && data->meshes[i].primitives[0].targets_count != data->meshes[i].target_names_count, cgltf_result_invalid_gltf);
1648 }
1649
1650 for (cgltf_size j = 0; j < data->meshes[i].primitives_count; ++j)
1651 {
1652 CGLTF_ASSERT_IF(data->meshes[i].primitives[j].type == cgltf_primitive_type_invalid, cgltf_result_invalid_gltf);
1653 CGLTF_ASSERT_IF(data->meshes[i].primitives[j].targets_count != data->meshes[i].primitives[0].targets_count, cgltf_result_invalid_gltf);
1654
1655 CGLTF_ASSERT_IF(data->meshes[i].primitives[j].attributes_count == 0, cgltf_result_invalid_gltf);
1656
1657 cgltf_accessor* first = data->meshes[i].primitives[j].attributes[0].data;
1658
1659 CGLTF_ASSERT_IF(first->count == 0, cgltf_result_invalid_gltf);
1660
1661 for (cgltf_size k = 0; k < data->meshes[i].primitives[j].attributes_count; ++k)
1662 {
1663 CGLTF_ASSERT_IF(data->meshes[i].primitives[j].attributes[k].data->count != first->count, cgltf_result_invalid_gltf);
1664 }
1665
1666 for (cgltf_size k = 0; k < data->meshes[i].primitives[j].targets_count; ++k)
1667 {
1668 for (cgltf_size m = 0; m < data->meshes[i].primitives[j].targets[k].attributes_count; ++m)
1669 {
1670 CGLTF_ASSERT_IF(data->meshes[i].primitives[j].targets[k].attributes[m].data->count != first->count, cgltf_result_invalid_gltf);
1671 }
1672 }
1673
1674 cgltf_accessor* indices = data->meshes[i].primitives[j].indices;
1675
1676 CGLTF_ASSERT_IF(indices &&
1677 indices->component_type != cgltf_component_type_r_8u &&
1678 indices->component_type != cgltf_component_type_r_16u &&
1679 indices->component_type != cgltf_component_type_r_32u, cgltf_result_invalid_gltf);
1680
1681 CGLTF_ASSERT_IF(indices && indices->type != cgltf_type_scalar, cgltf_result_invalid_gltf);
1682 CGLTF_ASSERT_IF(indices && indices->stride != cgltf_component_size(indices->component_type), cgltf_result_invalid_gltf);
1683
1684 if (indices && indices->buffer_view && indices->buffer_view->buffer->data)
1685 {
1686 cgltf_size index_bound = cgltf_calc_index_bound(indices->buffer_view, indices->offset, indices->component_type, indices->count);
1687
1688 CGLTF_ASSERT_IF(index_bound >= first->count, cgltf_result_data_too_short);
1689 }
1690
1691 for (cgltf_size k = 0; k < data->meshes[i].primitives[j].mappings_count; ++k)
1692 {
1693 CGLTF_ASSERT_IF(data->meshes[i].primitives[j].mappings[k].variant >= data->variants_count, cgltf_result_invalid_gltf);
1694 }
1695 }
1696 }
1697
1698 for (cgltf_size i = 0; i < data->nodes_count; ++i)
1699 {
1700 if (data->nodes[i].weights && data->nodes[i].mesh)
1701 {
1702 CGLTF_ASSERT_IF(data->nodes[i].mesh->primitives_count && data->nodes[i].mesh->primitives[0].targets_count != data->nodes[i].weights_count, cgltf_result_invalid_gltf);
1703 }
1704
1705 if (data->nodes[i].has_mesh_gpu_instancing)
1706 {
1707 CGLTF_ASSERT_IF(data->nodes[i].mesh == NULL, cgltf_result_invalid_gltf);
1708 CGLTF_ASSERT_IF(data->nodes[i].mesh_gpu_instancing.attributes_count == 0, cgltf_result_invalid_gltf);
1709
1710 cgltf_accessor* first = data->nodes[i].mesh_gpu_instancing.attributes[0].data;
1711
1712 for (cgltf_size k = 0; k < data->nodes[i].mesh_gpu_instancing.attributes_count; ++k)
1713 {
1714 CGLTF_ASSERT_IF(data->nodes[i].mesh_gpu_instancing.attributes[k].data->count != first->count, cgltf_result_invalid_gltf);
1715 }
1716 }
1717 }
1718
1719 for (cgltf_size i = 0; i < data->nodes_count; ++i)
1720 {
1721 cgltf_node* p1 = data->nodes[i].parent;
1722 cgltf_node* p2 = p1 ? p1->parent : NULL;
1723
1724 while (p1 && p2)
1725 {
1726 CGLTF_ASSERT_IF(p1 == p2, cgltf_result_invalid_gltf);
1727
1728 p1 = p1->parent;
1729 p2 = p2->parent ? p2->parent->parent : NULL;
1730 }
1731 }
1732
1733 for (cgltf_size i = 0; i < data->scenes_count; ++i)
1734 {
1735 for (cgltf_size j = 0; j < data->scenes[i].nodes_count; ++j)
1736 {
1737 CGLTF_ASSERT_IF(data->scenes[i].nodes[j]->parent, cgltf_result_invalid_gltf);
1738 }
1739 }
1740
1741 for (cgltf_size i = 0; i < data->animations_count; ++i)
1742 {
1743 for (cgltf_size j = 0; j < data->animations[i].channels_count; ++j)
1744 {
1745 cgltf_animation_channel* channel = &data->animations[i].channels[j];
1746
1747 if (!channel->target_node)
1748 {
1749 continue;
1750 }
1751
1752 cgltf_size components = 1;
1753
1754 if (channel->target_path == cgltf_animation_path_type_weights)
1755 {
1756 CGLTF_ASSERT_IF(!channel->target_node->mesh || !channel->target_node->mesh->primitives_count, cgltf_result_invalid_gltf);
1757
1758 components = channel->target_node->mesh->primitives[0].targets_count;
1759 }
1760
1761 cgltf_size values = channel->sampler->interpolation == cgltf_interpolation_type_cubic_spline ? 3 : 1;
1762
1763 CGLTF_ASSERT_IF(channel->sampler->input->count * components * values != channel->sampler->output->count, cgltf_result_invalid_gltf);
1764 }
1765 }
1766
1767 for (cgltf_size i = 0; i < data->variants_count; ++i)
1768 {
1769 CGLTF_ASSERT_IF(!data->variants[i].name, cgltf_result_invalid_gltf);
1770 }
1771
1772 return cgltf_result_success;
1773}
1774
1775cgltf_result cgltf_copy_extras_json(const cgltf_data* data, const cgltf_extras* extras, char* dest, cgltf_size* dest_size)
1776{
1777 cgltf_size json_size = extras->end_offset - extras->start_offset;
1778
1779 if (!dest)
1780 {
1781 if (dest_size)
1782 {
1783 *dest_size = json_size + 1;
1784 return cgltf_result_success;
1785 }
1786 return cgltf_result_invalid_options;
1787 }
1788
1789 if (*dest_size + 1 < json_size)
1790 {
1791 strncpy(dest, data->json + extras->start_offset, *dest_size - 1);
1792 dest[*dest_size - 1] = 0;
1793 }
1794 else
1795 {
1796 strncpy(dest, data->json + extras->start_offset, json_size);
1797 dest[json_size] = 0;
1798 }
1799
1800 return cgltf_result_success;
1801}
1802
1803static void cgltf_free_extras(cgltf_data* data, cgltf_extras* extras)
1804{
1805 data->memory.free_func(data->memory.user_data, extras->data);
1806}
1807
1808static void cgltf_free_extensions(cgltf_data* data, cgltf_extension* extensions, cgltf_size extensions_count)
1809{
1810 for (cgltf_size i = 0; i < extensions_count; ++i)
1811 {
1812 data->memory.free_func(data->memory.user_data, extensions[i].name);
1813 data->memory.free_func(data->memory.user_data, extensions[i].data);
1814 }
1815 data->memory.free_func(data->memory.user_data, extensions);
1816}
1817
1818void cgltf_free(cgltf_data* data)
1819{
1820 if (!data)
1821 {
1822 return;
1823 }
1824
1825 void (*file_release)(const struct cgltf_memory_options*, const struct cgltf_file_options*, void* data) = data->file.release ? data->file.release : cgltf_default_file_release;
1826
1827 data->memory.free_func(data->memory.user_data, data->asset.copyright);
1828 data->memory.free_func(data->memory.user_data, data->asset.generator);
1829 data->memory.free_func(data->memory.user_data, data->asset.version);
1830 data->memory.free_func(data->memory.user_data, data->asset.min_version);
1831
1832 cgltf_free_extensions(data, data->asset.extensions, data->asset.extensions_count);
1833 cgltf_free_extras(data, &data->asset.extras);
1834
1835 for (cgltf_size i = 0; i < data->accessors_count; ++i)
1836 {
1837 data->memory.free_func(data->memory.user_data, data->accessors[i].name);
1838
1839 cgltf_free_extensions(data, data->accessors[i].extensions, data->accessors[i].extensions_count);
1840 cgltf_free_extras(data, &data->accessors[i].extras);
1841 }
1842 data->memory.free_func(data->memory.user_data, data->accessors);
1843
1844 for (cgltf_size i = 0; i < data->buffer_views_count; ++i)
1845 {
1846 data->memory.free_func(data->memory.user_data, data->buffer_views[i].name);
1847 data->memory.free_func(data->memory.user_data, data->buffer_views[i].data);
1848
1849 cgltf_free_extensions(data, data->buffer_views[i].extensions, data->buffer_views[i].extensions_count);
1850 cgltf_free_extras(data, &data->buffer_views[i].extras);
1851 }
1852 data->memory.free_func(data->memory.user_data, data->buffer_views);
1853
1854 for (cgltf_size i = 0; i < data->buffers_count; ++i)
1855 {
1856 data->memory.free_func(data->memory.user_data, data->buffers[i].name);
1857
1858 if (data->buffers[i].data_free_method == cgltf_data_free_method_file_release)
1859 {
1860 file_release(&data->memory, &data->file, data->buffers[i].data);
1861 }
1862 else if (data->buffers[i].data_free_method == cgltf_data_free_method_memory_free)
1863 {
1864 data->memory.free_func(data->memory.user_data, data->buffers[i].data);
1865 }
1866
1867 data->memory.free_func(data->memory.user_data, data->buffers[i].uri);
1868
1869 cgltf_free_extensions(data, data->buffers[i].extensions, data->buffers[i].extensions_count);
1870 cgltf_free_extras(data, &data->buffers[i].extras);
1871 }
1872 data->memory.free_func(data->memory.user_data, data->buffers);
1873
1874 for (cgltf_size i = 0; i < data->meshes_count; ++i)
1875 {
1876 data->memory.free_func(data->memory.user_data, data->meshes[i].name);
1877
1878 for (cgltf_size j = 0; j < data->meshes[i].primitives_count; ++j)
1879 {
1880 for (cgltf_size k = 0; k < data->meshes[i].primitives[j].attributes_count; ++k)
1881 {
1882 data->memory.free_func(data->memory.user_data, data->meshes[i].primitives[j].attributes[k].name);
1883 }
1884
1885 data->memory.free_func(data->memory.user_data, data->meshes[i].primitives[j].attributes);
1886
1887 for (cgltf_size k = 0; k < data->meshes[i].primitives[j].targets_count; ++k)
1888 {
1889 for (cgltf_size m = 0; m < data->meshes[i].primitives[j].targets[k].attributes_count; ++m)
1890 {
1891 data->memory.free_func(data->memory.user_data, data->meshes[i].primitives[j].targets[k].attributes[m].name);
1892 }
1893
1894 data->memory.free_func(data->memory.user_data, data->meshes[i].primitives[j].targets[k].attributes);
1895 }
1896
1897 data->memory.free_func(data->memory.user_data, data->meshes[i].primitives[j].targets);
1898
1899 if (data->meshes[i].primitives[j].has_draco_mesh_compression)
1900 {
1901 for (cgltf_size k = 0; k < data->meshes[i].primitives[j].draco_mesh_compression.attributes_count; ++k)
1902 {
1903 data->memory.free_func(data->memory.user_data, data->meshes[i].primitives[j].draco_mesh_compression.attributes[k].name);
1904 }
1905
1906 data->memory.free_func(data->memory.user_data, data->meshes[i].primitives[j].draco_mesh_compression.attributes);
1907 }
1908
1909 for (cgltf_size k = 0; k < data->meshes[i].primitives[j].mappings_count; ++k)
1910 {
1911 cgltf_free_extras(data, &data->meshes[i].primitives[j].mappings[k].extras);
1912 }
1913
1914 data->memory.free_func(data->memory.user_data, data->meshes[i].primitives[j].mappings);
1915
1916 cgltf_free_extensions(data, data->meshes[i].primitives[j].extensions, data->meshes[i].primitives[j].extensions_count);
1917 cgltf_free_extras(data, &data->meshes[i].primitives[j].extras);
1918 }
1919
1920 data->memory.free_func(data->memory.user_data, data->meshes[i].primitives);
1921 data->memory.free_func(data->memory.user_data, data->meshes[i].weights);
1922
1923 for (cgltf_size j = 0; j < data->meshes[i].target_names_count; ++j)
1924 {
1925 data->memory.free_func(data->memory.user_data, data->meshes[i].target_names[j]);
1926 }
1927
1928 cgltf_free_extensions(data, data->meshes[i].extensions, data->meshes[i].extensions_count);
1929 cgltf_free_extras(data, &data->meshes[i].extras);
1930
1931 data->memory.free_func(data->memory.user_data, data->meshes[i].target_names);
1932 }
1933
1934 data->memory.free_func(data->memory.user_data, data->meshes);
1935
1936 for (cgltf_size i = 0; i < data->materials_count; ++i)
1937 {
1938 data->memory.free_func(data->memory.user_data, data->materials[i].name);
1939
1940 cgltf_free_extensions(data, data->materials[i].extensions, data->materials[i].extensions_count);
1941 cgltf_free_extras(data, &data->materials[i].extras);
1942 }
1943
1944 data->memory.free_func(data->memory.user_data, data->materials);
1945
1946 for (cgltf_size i = 0; i < data->images_count; ++i)
1947 {
1948 data->memory.free_func(data->memory.user_data, data->images[i].name);
1949 data->memory.free_func(data->memory.user_data, data->images[i].uri);
1950 data->memory.free_func(data->memory.user_data, data->images[i].mime_type);
1951
1952 cgltf_free_extensions(data, data->images[i].extensions, data->images[i].extensions_count);
1953 cgltf_free_extras(data, &data->images[i].extras);
1954 }
1955
1956 data->memory.free_func(data->memory.user_data, data->images);
1957
1958 for (cgltf_size i = 0; i < data->textures_count; ++i)
1959 {
1960 data->memory.free_func(data->memory.user_data, data->textures[i].name);
1961
1962 cgltf_free_extensions(data, data->textures[i].extensions, data->textures[i].extensions_count);
1963 cgltf_free_extras(data, &data->textures[i].extras);
1964 }
1965
1966 data->memory.free_func(data->memory.user_data, data->textures);
1967
1968 for (cgltf_size i = 0; i < data->samplers_count; ++i)
1969 {
1970 data->memory.free_func(data->memory.user_data, data->samplers[i].name);
1971
1972 cgltf_free_extensions(data, data->samplers[i].extensions, data->samplers[i].extensions_count);
1973 cgltf_free_extras(data, &data->samplers[i].extras);
1974 }
1975
1976 data->memory.free_func(data->memory.user_data, data->samplers);
1977
1978 for (cgltf_size i = 0; i < data->skins_count; ++i)
1979 {
1980 data->memory.free_func(data->memory.user_data, data->skins[i].name);
1981 data->memory.free_func(data->memory.user_data, data->skins[i].joints);
1982
1983 cgltf_free_extensions(data, data->skins[i].extensions, data->skins[i].extensions_count);
1984 cgltf_free_extras(data, &data->skins[i].extras);
1985 }
1986
1987 data->memory.free_func(data->memory.user_data, data->skins);
1988
1989 for (cgltf_size i = 0; i < data->cameras_count; ++i)
1990 {
1991 data->memory.free_func(data->memory.user_data, data->cameras[i].name);
1992
1993 if (data->cameras[i].type == cgltf_camera_type_perspective)
1994 {
1995 cgltf_free_extras(data, &data->cameras[i].data.perspective.extras);
1996 }
1997 else if (data->cameras[i].type == cgltf_camera_type_orthographic)
1998 {
1999 cgltf_free_extras(data, &data->cameras[i].data.orthographic.extras);
2000 }
2001
2002 cgltf_free_extensions(data, data->cameras[i].extensions, data->cameras[i].extensions_count);
2003 cgltf_free_extras(data, &data->cameras[i].extras);
2004 }
2005
2006 data->memory.free_func(data->memory.user_data, data->cameras);
2007
2008 for (cgltf_size i = 0; i < data->lights_count; ++i)
2009 {
2010 data->memory.free_func(data->memory.user_data, data->lights[i].name);
2011
2012 cgltf_free_extras(data, &data->lights[i].extras);
2013 }
2014
2015 data->memory.free_func(data->memory.user_data, data->lights);
2016
2017 for (cgltf_size i = 0; i < data->nodes_count; ++i)
2018 {
2019 data->memory.free_func(data->memory.user_data, data->nodes[i].name);
2020 data->memory.free_func(data->memory.user_data, data->nodes[i].children);
2021 data->memory.free_func(data->memory.user_data, data->nodes[i].weights);
2022
2023 if (data->nodes[i].has_mesh_gpu_instancing)
2024 {
2025 for (cgltf_size j = 0; j < data->nodes[i].mesh_gpu_instancing.attributes_count; ++j)
2026 {
2027 data->memory.free_func(data->memory.user_data, data->nodes[i].mesh_gpu_instancing.attributes[j].name);
2028 }
2029
2030 data->memory.free_func(data->memory.user_data, data->nodes[i].mesh_gpu_instancing.attributes);
2031 }
2032
2033 cgltf_free_extensions(data, data->nodes[i].extensions, data->nodes[i].extensions_count);
2034 cgltf_free_extras(data, &data->nodes[i].extras);
2035 }
2036
2037 data->memory.free_func(data->memory.user_data, data->nodes);
2038
2039 for (cgltf_size i = 0; i < data->scenes_count; ++i)
2040 {
2041 data->memory.free_func(data->memory.user_data, data->scenes[i].name);
2042 data->memory.free_func(data->memory.user_data, data->scenes[i].nodes);
2043
2044 cgltf_free_extensions(data, data->scenes[i].extensions, data->scenes[i].extensions_count);
2045 cgltf_free_extras(data, &data->scenes[i].extras);
2046 }
2047
2048 data->memory.free_func(data->memory.user_data, data->scenes);
2049
2050 for (cgltf_size i = 0; i < data->animations_count; ++i)
2051 {
2052 data->memory.free_func(data->memory.user_data, data->animations[i].name);
2053 for (cgltf_size j = 0; j < data->animations[i].samplers_count; ++j)
2054 {
2055 cgltf_free_extensions(data, data->animations[i].samplers[j].extensions, data->animations[i].samplers[j].extensions_count);
2056 cgltf_free_extras(data, &data->animations[i].samplers[j].extras);
2057 }
2058 data->memory.free_func(data->memory.user_data, data->animations[i].samplers);
2059
2060 for (cgltf_size j = 0; j < data->animations[i].channels_count; ++j)
2061 {
2062 cgltf_free_extensions(data, data->animations[i].channels[j].extensions, data->animations[i].channels[j].extensions_count);
2063 cgltf_free_extras(data, &data->animations[i].channels[j].extras);
2064 }
2065 data->memory.free_func(data->memory.user_data, data->animations[i].channels);
2066
2067 cgltf_free_extensions(data, data->animations[i].extensions, data->animations[i].extensions_count);
2068 cgltf_free_extras(data, &data->animations[i].extras);
2069 }
2070
2071 data->memory.free_func(data->memory.user_data, data->animations);
2072
2073 for (cgltf_size i = 0; i < data->variants_count; ++i)
2074 {
2075 data->memory.free_func(data->memory.user_data, data->variants[i].name);
2076
2077 cgltf_free_extras(data, &data->variants[i].extras);
2078 }
2079
2080 data->memory.free_func(data->memory.user_data, data->variants);
2081
2082 cgltf_free_extensions(data, data->data_extensions, data->data_extensions_count);
2083 cgltf_free_extras(data, &data->extras);
2084
2085 for (cgltf_size i = 0; i < data->extensions_used_count; ++i)
2086 {
2087 data->memory.free_func(data->memory.user_data, data->extensions_used[i]);
2088 }
2089
2090 data->memory.free_func(data->memory.user_data, data->extensions_used);
2091
2092 for (cgltf_size i = 0; i < data->extensions_required_count; ++i)
2093 {
2094 data->memory.free_func(data->memory.user_data, data->extensions_required[i]);
2095 }
2096
2097 data->memory.free_func(data->memory.user_data, data->extensions_required);
2098
2099 file_release(&data->memory, &data->file, data->file_data);
2100
2101 data->memory.free_func(data->memory.user_data, data);
2102}
2103
2104void cgltf_node_transform_local(const cgltf_node* node, cgltf_float* out_matrix)
2105{
2106 cgltf_float* lm = out_matrix;
2107
2108 if (node->has_matrix)
2109 {
2110 memcpy(lm, node->matrix, sizeof(float) * 16);
2111 }
2112 else
2113 {
2114 float tx = node->translation[0];
2115 float ty = node->translation[1];
2116 float tz = node->translation[2];
2117
2118 float qx = node->rotation[0];
2119 float qy = node->rotation[1];
2120 float qz = node->rotation[2];
2121 float qw = node->rotation[3];
2122
2123 float sx = node->scale[0];
2124 float sy = node->scale[1];
2125 float sz = node->scale[2];
2126
2127 lm[0] = (1 - 2 * qy*qy - 2 * qz*qz) * sx;
2128 lm[1] = (2 * qx*qy + 2 * qz*qw) * sx;
2129 lm[2] = (2 * qx*qz - 2 * qy*qw) * sx;
2130 lm[3] = 0.f;
2131
2132 lm[4] = (2 * qx*qy - 2 * qz*qw) * sy;
2133 lm[5] = (1 - 2 * qx*qx - 2 * qz*qz) * sy;
2134 lm[6] = (2 * qy*qz + 2 * qx*qw) * sy;
2135 lm[7] = 0.f;
2136
2137 lm[8] = (2 * qx*qz + 2 * qy*qw) * sz;
2138 lm[9] = (2 * qy*qz - 2 * qx*qw) * sz;
2139 lm[10] = (1 - 2 * qx*qx - 2 * qy*qy) * sz;
2140 lm[11] = 0.f;
2141
2142 lm[12] = tx;
2143 lm[13] = ty;
2144 lm[14] = tz;
2145 lm[15] = 1.f;
2146 }
2147}
2148
2149void cgltf_node_transform_world(const cgltf_node* node, cgltf_float* out_matrix)
2150{
2151 cgltf_float* lm = out_matrix;
2152 cgltf_node_transform_local(node, lm);
2153
2154 const cgltf_node* parent = node->parent;
2155
2156 while (parent)
2157 {
2158 float pm[16];
2159 cgltf_node_transform_local(parent, pm);
2160
2161 for (int i = 0; i < 4; ++i)
2162 {
2163 float l0 = lm[i * 4 + 0];
2164 float l1 = lm[i * 4 + 1];
2165 float l2 = lm[i * 4 + 2];
2166
2167 float r0 = l0 * pm[0] + l1 * pm[4] + l2 * pm[8];
2168 float r1 = l0 * pm[1] + l1 * pm[5] + l2 * pm[9];
2169 float r2 = l0 * pm[2] + l1 * pm[6] + l2 * pm[10];
2170
2171 lm[i * 4 + 0] = r0;
2172 lm[i * 4 + 1] = r1;
2173 lm[i * 4 + 2] = r2;
2174 }
2175
2176 lm[12] += pm[12];
2177 lm[13] += pm[13];
2178 lm[14] += pm[14];
2179
2180 parent = parent->parent;
2181 }
2182}
2183
2184static cgltf_ssize cgltf_component_read_integer(const void* in, cgltf_component_type component_type)
2185{
2186 switch (component_type)
2187 {
2188 case cgltf_component_type_r_16:
2189 return *((const int16_t*) in);
2190 case cgltf_component_type_r_16u:
2191 return *((const uint16_t*) in);
2192 case cgltf_component_type_r_32u:
2193 return *((const uint32_t*) in);
2194 case cgltf_component_type_r_8:
2195 return *((const int8_t*) in);
2196 case cgltf_component_type_r_8u:
2197 return *((const uint8_t*) in);
2198 default:
2199 return 0;
2200 }
2201}
2202
2203static cgltf_size cgltf_component_read_index(const void* in, cgltf_component_type component_type)
2204{
2205 switch (component_type)
2206 {
2207 case cgltf_component_type_r_16u:
2208 return *((const uint16_t*) in);
2209 case cgltf_component_type_r_32u:
2210 return *((const uint32_t*) in);
2211 case cgltf_component_type_r_8u:
2212 return *((const uint8_t*) in);
2213 default:
2214 return 0;
2215 }
2216}
2217
2218static cgltf_float cgltf_component_read_float(const void* in, cgltf_component_type component_type, cgltf_bool normalized)
2219{
2220 if (component_type == cgltf_component_type_r_32f)
2221 {
2222 return *((const float*) in);
2223 }
2224
2225 if (normalized)
2226 {
2227 switch (component_type)
2228 {
2229 // note: glTF spec doesn't currently define normalized conversions for 32-bit integers
2230 case cgltf_component_type_r_16:
2231 return *((const int16_t*) in) / (cgltf_float)32767;
2232 case cgltf_component_type_r_16u:
2233 return *((const uint16_t*) in) / (cgltf_float)65535;
2234 case cgltf_component_type_r_8:
2235 return *((const int8_t*) in) / (cgltf_float)127;
2236 case cgltf_component_type_r_8u:
2237 return *((const uint8_t*) in) / (cgltf_float)255;
2238 default:
2239 return 0;
2240 }
2241 }
2242
2243 return (cgltf_float)cgltf_component_read_integer(in, component_type);
2244}
2245
2246static cgltf_bool cgltf_element_read_float(const uint8_t* element, cgltf_type type, cgltf_component_type component_type, cgltf_bool normalized, cgltf_float* out, cgltf_size element_size)
2247{
2248 cgltf_size num_components = cgltf_num_components(type);
2249
2250 if (element_size < num_components) {
2251 return 0;
2252 }
2253
2254 // There are three special cases for component extraction, see #data-alignment in the 2.0 spec.
2255
2256 cgltf_size component_size = cgltf_component_size(component_type);
2257
2258 if (type == cgltf_type_mat2 && component_size == 1)
2259 {
2260 out[0] = cgltf_component_read_float(element, component_type, normalized);
2261 out[1] = cgltf_component_read_float(element + 1, component_type, normalized);
2262 out[2] = cgltf_component_read_float(element + 4, component_type, normalized);
2263 out[3] = cgltf_component_read_float(element + 5, component_type, normalized);
2264 return 1;
2265 }
2266
2267 if (type == cgltf_type_mat3 && component_size == 1)
2268 {
2269 out[0] = cgltf_component_read_float(element, component_type, normalized);
2270 out[1] = cgltf_component_read_float(element + 1, component_type, normalized);
2271 out[2] = cgltf_component_read_float(element + 2, component_type, normalized);
2272 out[3] = cgltf_component_read_float(element + 4, component_type, normalized);
2273 out[4] = cgltf_component_read_float(element + 5, component_type, normalized);
2274 out[5] = cgltf_component_read_float(element + 6, component_type, normalized);
2275 out[6] = cgltf_component_read_float(element + 8, component_type, normalized);
2276 out[7] = cgltf_component_read_float(element + 9, component_type, normalized);
2277 out[8] = cgltf_component_read_float(element + 10, component_type, normalized);
2278 return 1;
2279 }
2280
2281 if (type == cgltf_type_mat3 && component_size == 2)
2282 {
2283 out[0] = cgltf_component_read_float(element, component_type, normalized);
2284 out[1] = cgltf_component_read_float(element + 2, component_type, normalized);
2285 out[2] = cgltf_component_read_float(element + 4, component_type, normalized);
2286 out[3] = cgltf_component_read_float(element + 8, component_type, normalized);
2287 out[4] = cgltf_component_read_float(element + 10, component_type, normalized);
2288 out[5] = cgltf_component_read_float(element + 12, component_type, normalized);
2289 out[6] = cgltf_component_read_float(element + 16, component_type, normalized);
2290 out[7] = cgltf_component_read_float(element + 18, component_type, normalized);
2291 out[8] = cgltf_component_read_float(element + 20, component_type, normalized);
2292 return 1;
2293 }
2294
2295 for (cgltf_size i = 0; i < num_components; ++i)
2296 {
2297 out[i] = cgltf_component_read_float(element + component_size * i, component_type, normalized);
2298 }
2299 return 1;
2300}
2301
2302const uint8_t* cgltf_buffer_view_data(const cgltf_buffer_view* view)
2303{
2304 if (view->data)
2305 return (const uint8_t*)view->data;
2306
2307 if (!view->buffer->data)
2308 return NULL;
2309
2310 const uint8_t* result = (const uint8_t*)view->buffer->data;
2311 result += view->offset;
2312 return result;
2313}
2314
2315cgltf_bool cgltf_accessor_read_float(const cgltf_accessor* accessor, cgltf_size index, cgltf_float* out, cgltf_size element_size)
2316{
2317 if (accessor->is_sparse)
2318 {
2319 return 0;
2320 }
2321 if (accessor->buffer_view == NULL)
2322 {
2323 memset(out, 0, element_size * sizeof(cgltf_float));
2324 return 1;
2325 }
2326 const uint8_t* element = cgltf_buffer_view_data(accessor->buffer_view);
2327 if (element == NULL)
2328 {
2329 return 0;
2330 }
2331 element += accessor->offset + accessor->stride * index;
2332 return cgltf_element_read_float(element, accessor->type, accessor->component_type, accessor->normalized, out, element_size);
2333}
2334
2335cgltf_size cgltf_accessor_unpack_floats(const cgltf_accessor* accessor, cgltf_float* out, cgltf_size float_count)
2336{
2337 cgltf_size floats_per_element = cgltf_num_components(accessor->type);
2338 cgltf_size available_floats = accessor->count * floats_per_element;
2339 if (out == NULL)
2340 {
2341 return available_floats;
2342 }
2343
2344 float_count = available_floats < float_count ? available_floats : float_count;
2345 cgltf_size element_count = float_count / floats_per_element;
2346
2347 // First pass: convert each element in the base accessor.
2348 if (accessor->buffer_view == NULL)
2349 {
2350 memset(out, 0, element_count * floats_per_element * sizeof(cgltf_float));
2351 }
2352 else
2353 {
2354 const uint8_t* element = cgltf_buffer_view_data(accessor->buffer_view);
2355 if (element == NULL)
2356 {
2357 return 0;
2358 }
2359 element += accessor->offset;
2360
2361 if (accessor->component_type == cgltf_component_type_r_32f && accessor->stride == floats_per_element * sizeof(cgltf_float))
2362 {
2363 memcpy(out, element, element_count * floats_per_element * sizeof(cgltf_float));
2364 }
2365 else
2366 {
2367 cgltf_float* dest = out;
2368
2369 for (cgltf_size index = 0; index < element_count; index++, dest += floats_per_element, element += accessor->stride)
2370 {
2371 if (!cgltf_element_read_float(element, accessor->type, accessor->component_type, accessor->normalized, dest, floats_per_element))
2372 {
2373 return 0;
2374 }
2375 }
2376 }
2377 }
2378
2379 // Second pass: write out each element in the sparse accessor.
2380 if (accessor->is_sparse)
2381 {
2382 const cgltf_accessor_sparse* sparse = &accessor->sparse;
2383
2384 const uint8_t* index_data = cgltf_buffer_view_data(sparse->indices_buffer_view);
2385 const uint8_t* reader_head = cgltf_buffer_view_data(sparse->values_buffer_view);
2386
2387 if (index_data == NULL || reader_head == NULL)
2388 {
2389 return 0;
2390 }
2391
2392 index_data += sparse->indices_byte_offset;
2393 reader_head += sparse->values_byte_offset;
2394
2395 cgltf_size index_stride = cgltf_component_size(sparse->indices_component_type);
2396 for (cgltf_size reader_index = 0; reader_index < sparse->count; reader_index++, index_data += index_stride, reader_head += accessor->stride)
2397 {
2398 size_t writer_index = cgltf_component_read_index(index_data, sparse->indices_component_type);
2399 float* writer_head = out + writer_index * floats_per_element;
2400
2401 if (!cgltf_element_read_float(reader_head, accessor->type, accessor->component_type, accessor->normalized, writer_head, floats_per_element))
2402 {
2403 return 0;
2404 }
2405 }
2406 }
2407
2408 return element_count * floats_per_element;
2409}
2410
2411static cgltf_uint cgltf_component_read_uint(const void* in, cgltf_component_type component_type)
2412{
2413 switch (component_type)
2414 {
2415 case cgltf_component_type_r_8:
2416 return *((const int8_t*) in);
2417
2418 case cgltf_component_type_r_8u:
2419 return *((const uint8_t*) in);
2420
2421 case cgltf_component_type_r_16:
2422 return *((const int16_t*) in);
2423
2424 case cgltf_component_type_r_16u:
2425 return *((const uint16_t*) in);
2426
2427 case cgltf_component_type_r_32u:
2428 return *((const uint32_t*) in);
2429
2430 default:
2431 return 0;
2432 }
2433}
2434
2435static cgltf_bool cgltf_element_read_uint(const uint8_t* element, cgltf_type type, cgltf_component_type component_type, cgltf_uint* out, cgltf_size element_size)
2436{
2437 cgltf_size num_components = cgltf_num_components(type);
2438
2439 if (element_size < num_components)
2440 {
2441 return 0;
2442 }
2443
2444 // Reading integer matrices is not a valid use case
2445 if (type == cgltf_type_mat2 || type == cgltf_type_mat3 || type == cgltf_type_mat4)
2446 {
2447 return 0;
2448 }
2449
2450 cgltf_size component_size = cgltf_component_size(component_type);
2451
2452 for (cgltf_size i = 0; i < num_components; ++i)
2453 {
2454 out[i] = cgltf_component_read_uint(element + component_size * i, component_type);
2455 }
2456 return 1;
2457}
2458
2459cgltf_bool cgltf_accessor_read_uint(const cgltf_accessor* accessor, cgltf_size index, cgltf_uint* out, cgltf_size element_size)
2460{
2461 if (accessor->is_sparse)
2462 {
2463 return 0;
2464 }
2465 if (accessor->buffer_view == NULL)
2466 {
2467 memset(out, 0, element_size * sizeof( cgltf_uint ));
2468 return 1;
2469 }
2470 const uint8_t* element = cgltf_buffer_view_data(accessor->buffer_view);
2471 if (element == NULL)
2472 {
2473 return 0;
2474 }
2475 element += accessor->offset + accessor->stride * index;
2476 return cgltf_element_read_uint(element, accessor->type, accessor->component_type, out, element_size);
2477}
2478
2479cgltf_size cgltf_accessor_read_index(const cgltf_accessor* accessor, cgltf_size index)
2480{
2481 if (accessor->is_sparse)
2482 {
2483 return 0; // This is an error case, but we can't communicate the error with existing interface.
2484 }
2485 if (accessor->buffer_view == NULL)
2486 {
2487 return 0;
2488 }
2489 const uint8_t* element = cgltf_buffer_view_data(accessor->buffer_view);
2490 if (element == NULL)
2491 {
2492 return 0; // This is an error case, but we can't communicate the error with existing interface.
2493 }
2494 element += accessor->offset + accessor->stride * index;
2495 return cgltf_component_read_index(element, accessor->component_type);
2496}
2497
2498cgltf_size cgltf_mesh_index(const cgltf_data* data, const cgltf_mesh* object)
2499{
2500 assert(object && (cgltf_size)(object - data->meshes) < data->meshes_count);
2501 return (cgltf_size)(object - data->meshes);
2502}
2503
2504cgltf_size cgltf_material_index(const cgltf_data* data, const cgltf_material* object)
2505{
2506 assert(object && (cgltf_size)(object - data->materials) < data->materials_count);
2507 return (cgltf_size)(object - data->materials);
2508}
2509
2510cgltf_size cgltf_accessor_index(const cgltf_data* data, const cgltf_accessor* object)
2511{
2512 assert(object && (cgltf_size)(object - data->accessors) < data->accessors_count);
2513 return (cgltf_size)(object - data->accessors);
2514}
2515
2516cgltf_size cgltf_buffer_view_index(const cgltf_data* data, const cgltf_buffer_view* object)
2517{
2518 assert(object && (cgltf_size)(object - data->buffer_views) < data->buffer_views_count);
2519 return (cgltf_size)(object - data->buffer_views);
2520}
2521
2522cgltf_size cgltf_buffer_index(const cgltf_data* data, const cgltf_buffer* object)
2523{
2524 assert(object && (cgltf_size)(object - data->buffers) < data->buffers_count);
2525 return (cgltf_size)(object - data->buffers);
2526}
2527
2528cgltf_size cgltf_image_index(const cgltf_data* data, const cgltf_image* object)
2529{
2530 assert(object && (cgltf_size)(object - data->images) < data->images_count);
2531 return (cgltf_size)(object - data->images);
2532}
2533
2534cgltf_size cgltf_texture_index(const cgltf_data* data, const cgltf_texture* object)
2535{
2536 assert(object && (cgltf_size)(object - data->textures) < data->textures_count);
2537 return (cgltf_size)(object - data->textures);
2538}
2539
2540cgltf_size cgltf_sampler_index(const cgltf_data* data, const cgltf_sampler* object)
2541{
2542 assert(object && (cgltf_size)(object - data->samplers) < data->samplers_count);
2543 return (cgltf_size)(object - data->samplers);
2544}
2545
2546cgltf_size cgltf_skin_index(const cgltf_data* data, const cgltf_skin* object)
2547{
2548 assert(object && (cgltf_size)(object - data->skins) < data->skins_count);
2549 return (cgltf_size)(object - data->skins);
2550}
2551
2552cgltf_size cgltf_camera_index(const cgltf_data* data, const cgltf_camera* object)
2553{
2554 assert(object && (cgltf_size)(object - data->cameras) < data->cameras_count);
2555 return (cgltf_size)(object - data->cameras);
2556}
2557
2558cgltf_size cgltf_light_index(const cgltf_data* data, const cgltf_light* object)
2559{
2560 assert(object && (cgltf_size)(object - data->lights) < data->lights_count);
2561 return (cgltf_size)(object - data->lights);
2562}
2563
2564cgltf_size cgltf_node_index(const cgltf_data* data, const cgltf_node* object)
2565{
2566 assert(object && (cgltf_size)(object - data->nodes) < data->nodes_count);
2567 return (cgltf_size)(object - data->nodes);
2568}
2569
2570cgltf_size cgltf_scene_index(const cgltf_data* data, const cgltf_scene* object)
2571{
2572 assert(object && (cgltf_size)(object - data->scenes) < data->scenes_count);
2573 return (cgltf_size)(object - data->scenes);
2574}
2575
2576cgltf_size cgltf_animation_index(const cgltf_data* data, const cgltf_animation* object)
2577{
2578 assert(object && (cgltf_size)(object - data->animations) < data->animations_count);
2579 return (cgltf_size)(object - data->animations);
2580}
2581
2582cgltf_size cgltf_animation_sampler_index(const cgltf_animation* animation, const cgltf_animation_sampler* object)
2583{
2584 assert(object && (cgltf_size)(object - animation->samplers) < animation->samplers_count);
2585 return (cgltf_size)(object - animation->samplers);
2586}
2587
2588cgltf_size cgltf_animation_channel_index(const cgltf_animation* animation, const cgltf_animation_channel* object)
2589{
2590 assert(object && (cgltf_size)(object - animation->channels) < animation->channels_count);
2591 return (cgltf_size)(object - animation->channels);
2592}
2593
2594cgltf_size cgltf_accessor_unpack_indices(const cgltf_accessor* accessor, void* out, cgltf_size out_component_size, cgltf_size index_count)
2595{
2596 if (out == NULL)
2597 {
2598 return accessor->count;
2599 }
2600
2601 index_count = accessor->count < index_count ? accessor->count : index_count;
2602 cgltf_size index_component_size = cgltf_component_size(accessor->component_type);
2603
2604 if (accessor->is_sparse)
2605 {
2606 return 0;
2607 }
2608 if (accessor->buffer_view == NULL)
2609 {
2610 return 0;
2611 }
2612 if (index_component_size > out_component_size)
2613 {
2614 return 0;
2615 }
2616 const uint8_t* element = cgltf_buffer_view_data(accessor->buffer_view);
2617 if (element == NULL)
2618 {
2619 return 0;
2620 }
2621 element += accessor->offset;
2622
2623 if (index_component_size == out_component_size && accessor->stride == out_component_size)
2624 {
2625 memcpy(out, element, index_count * index_component_size);
2626 return index_count;
2627 }
2628
2629 // The component size of the output array is larger than the component size of the index data, so index data will be padded.
2630 switch (out_component_size)
2631 {
2632 case 2:
2633 for (cgltf_size index = 0; index < index_count; index++, element += accessor->stride)
2634 {
2635 ((uint16_t*)out)[index] = (uint16_t)cgltf_component_read_index(element, accessor->component_type);
2636 }
2637 break;
2638 case 4:
2639 for (cgltf_size index = 0; index < index_count; index++, element += accessor->stride)
2640 {
2641 ((uint32_t*)out)[index] = (uint32_t)cgltf_component_read_index(element, accessor->component_type);
2642 }
2643 break;
2644 default:
2645 break;
2646 }
2647
2648 return index_count;
2649}
2650
2651#define CGLTF_ERROR_JSON -1
2652#define CGLTF_ERROR_NOMEM -2
2653#define CGLTF_ERROR_LEGACY -3
2654
2655#define CGLTF_CHECK_TOKTYPE(tok_, type_) if ((tok_).type != (type_)) { return CGLTF_ERROR_JSON; }
2656#define CGLTF_CHECK_TOKTYPE_RET(tok_, type_, ret_) if ((tok_).type != (type_)) { return ret_; }
2657#define CGLTF_CHECK_KEY(tok_) if ((tok_).type != JSMN_STRING || (tok_).size == 0) { return CGLTF_ERROR_JSON; } /* checking size for 0 verifies that a value follows the key */
2658
2659#define CGLTF_PTRINDEX(type, idx) (type*)((cgltf_size)idx + 1)
2660#define CGLTF_PTRFIXUP(var, data, size) if (var) { if ((cgltf_size)var > size) { return CGLTF_ERROR_JSON; } var = &data[(cgltf_size)var-1]; }
2661#define CGLTF_PTRFIXUP_REQ(var, data, size) if (!var || (cgltf_size)var > size) { return CGLTF_ERROR_JSON; } var = &data[(cgltf_size)var-1];
2662
2663static int cgltf_json_strcmp(jsmntok_t const* tok, const uint8_t* json_chunk, const char* str)
2664{
2665 CGLTF_CHECK_TOKTYPE(*tok, JSMN_STRING);
2666 size_t const str_len = strlen(str);
2667 size_t const name_length = (size_t)(tok->end - tok->start);
2668 return (str_len == name_length) ? strncmp((const char*)json_chunk + tok->start, str, str_len) : 128;
2669}
2670
2671static int cgltf_json_to_int(jsmntok_t const* tok, const uint8_t* json_chunk)
2672{
2673 CGLTF_CHECK_TOKTYPE(*tok, JSMN_PRIMITIVE);
2674 char tmp[128];
2675 int size = (size_t)(tok->end - tok->start) < sizeof(tmp) ? (int)(tok->end - tok->start) : (int)(sizeof(tmp) - 1);
2676 strncpy(tmp, (const char*)json_chunk + tok->start, size);
2677 tmp[size] = 0;
2678 return CGLTF_ATOI(tmp);
2679}
2680
2681static cgltf_size cgltf_json_to_size(jsmntok_t const* tok, const uint8_t* json_chunk)
2682{
2683 CGLTF_CHECK_TOKTYPE_RET(*tok, JSMN_PRIMITIVE, 0);
2684 char tmp[128];
2685 int size = (size_t)(tok->end - tok->start) < sizeof(tmp) ? (int)(tok->end - tok->start) : (int)(sizeof(tmp) - 1);
2686 strncpy(tmp, (const char*)json_chunk + tok->start, size);
2687 tmp[size] = 0;
2688 long long res = CGLTF_ATOLL(tmp);
2689 return res < 0 ? 0 : (cgltf_size)res;
2690}
2691
2692static cgltf_float cgltf_json_to_float(jsmntok_t const* tok, const uint8_t* json_chunk)
2693{
2694 CGLTF_CHECK_TOKTYPE(*tok, JSMN_PRIMITIVE);
2695 char tmp[128];
2696 int size = (size_t)(tok->end - tok->start) < sizeof(tmp) ? (int)(tok->end - tok->start) : (int)(sizeof(tmp) - 1);
2697 strncpy(tmp, (const char*)json_chunk + tok->start, size);
2698 tmp[size] = 0;
2699 return (cgltf_float)CGLTF_ATOF(tmp);
2700}
2701
2702static cgltf_bool cgltf_json_to_bool(jsmntok_t const* tok, const uint8_t* json_chunk)
2703{
2704 int size = (int)(tok->end - tok->start);
2705 return size == 4 && memcmp(json_chunk + tok->start, "true", 4) == 0;
2706}
2707
2708static int cgltf_skip_json(jsmntok_t const* tokens, int i)
2709{
2710 int end = i + 1;
2711
2712 while (i < end)
2713 {
2714 switch (tokens[i].type)
2715 {
2716 case JSMN_OBJECT:
2717 end += tokens[i].size * 2;
2718 break;
2719
2720 case JSMN_ARRAY:
2721 end += tokens[i].size;
2722 break;
2723
2724 case JSMN_PRIMITIVE:
2725 case JSMN_STRING:
2726 break;
2727
2728 default:
2729 return -1;
2730 }
2731
2732 i++;
2733 }
2734
2735 return i;
2736}
2737
2738static void cgltf_fill_float_array(float* out_array, int size, float value)
2739{
2740 for (int j = 0; j < size; ++j)
2741 {
2742 out_array[j] = value;
2743 }
2744}
2745
2746static int cgltf_parse_json_float_array(jsmntok_t const* tokens, int i, const uint8_t* json_chunk, float* out_array, int size)
2747{
2748 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_ARRAY);
2749 if (tokens[i].size != size)
2750 {
2751 return CGLTF_ERROR_JSON;
2752 }
2753 ++i;
2754 for (int j = 0; j < size; ++j)
2755 {
2756 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_PRIMITIVE);
2757 out_array[j] = cgltf_json_to_float(tokens + i, json_chunk);
2758 ++i;
2759 }
2760 return i;
2761}
2762
2763static int cgltf_parse_json_string(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, char** out_string)
2764{
2765 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_STRING);
2766 if (*out_string)
2767 {
2768 return CGLTF_ERROR_JSON;
2769 }
2770 int size = (int)(tokens[i].end - tokens[i].start);
2771 char* result = (char*)options->memory.alloc_func(options->memory.user_data, size + 1);
2772 if (!result)
2773 {
2774 return CGLTF_ERROR_NOMEM;
2775 }
2776 strncpy(result, (const char*)json_chunk + tokens[i].start, size);
2777 result[size] = 0;
2778 *out_string = result;
2779 return i + 1;
2780}
2781
2782static int cgltf_parse_json_array(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, size_t element_size, void** out_array, cgltf_size* out_size)
2783{
2784 (void)json_chunk;
2785 if (tokens[i].type != JSMN_ARRAY)
2786 {
2787 return tokens[i].type == JSMN_OBJECT ? CGLTF_ERROR_LEGACY : CGLTF_ERROR_JSON;
2788 }
2789 if (*out_array)
2790 {
2791 return CGLTF_ERROR_JSON;
2792 }
2793 int size = tokens[i].size;
2794 void* result = cgltf_calloc(options, element_size, size);
2795 if (!result)
2796 {
2797 return CGLTF_ERROR_NOMEM;
2798 }
2799 *out_array = result;
2800 *out_size = size;
2801 return i + 1;
2802}
2803
2804static int cgltf_parse_json_string_array(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, char*** out_array, cgltf_size* out_size)
2805{
2806 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_ARRAY);
2807 i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(char*), (void**)out_array, out_size);
2808 if (i < 0)
2809 {
2810 return i;
2811 }
2812
2813 for (cgltf_size j = 0; j < *out_size; ++j)
2814 {
2815 i = cgltf_parse_json_string(options, tokens, i, json_chunk, j + (*out_array));
2816 if (i < 0)
2817 {
2818 return i;
2819 }
2820 }
2821 return i;
2822}
2823
2824static void cgltf_parse_attribute_type(const char* name, cgltf_attribute_type* out_type, int* out_index)
2825{
2826 if (*name == '_')
2827 {
2828 *out_type = cgltf_attribute_type_custom;
2829 return;
2830 }
2831
2832 const char* us = strchr(name, '_');
2833 size_t len = us ? (size_t)(us - name) : strlen(name);
2834
2835 if (len == 8 && strncmp(name, "POSITION", 8) == 0)
2836 {
2837 *out_type = cgltf_attribute_type_position;
2838 }
2839 else if (len == 6 && strncmp(name, "NORMAL", 6) == 0)
2840 {
2841 *out_type = cgltf_attribute_type_normal;
2842 }
2843 else if (len == 7 && strncmp(name, "TANGENT", 7) == 0)
2844 {
2845 *out_type = cgltf_attribute_type_tangent;
2846 }
2847 else if (len == 8 && strncmp(name, "TEXCOORD", 8) == 0)
2848 {
2849 *out_type = cgltf_attribute_type_texcoord;
2850 }
2851 else if (len == 5 && strncmp(name, "COLOR", 5) == 0)
2852 {
2853 *out_type = cgltf_attribute_type_color;
2854 }
2855 else if (len == 6 && strncmp(name, "JOINTS", 6) == 0)
2856 {
2857 *out_type = cgltf_attribute_type_joints;
2858 }
2859 else if (len == 7 && strncmp(name, "WEIGHTS", 7) == 0)
2860 {
2861 *out_type = cgltf_attribute_type_weights;
2862 }
2863 else
2864 {
2865 *out_type = cgltf_attribute_type_invalid;
2866 }
2867
2868 if (us && *out_type != cgltf_attribute_type_invalid)
2869 {
2870 *out_index = CGLTF_ATOI(us + 1);
2871 if (*out_index < 0)
2872 {
2873 *out_type = cgltf_attribute_type_invalid;
2874 *out_index = 0;
2875 }
2876 }
2877}
2878
2879static int cgltf_parse_json_attribute_list(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_attribute** out_attributes, cgltf_size* out_attributes_count)
2880{
2881 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
2882
2883 if (*out_attributes)
2884 {
2885 return CGLTF_ERROR_JSON;
2886 }
2887
2888 *out_attributes_count = tokens[i].size;
2889 *out_attributes = (cgltf_attribute*)cgltf_calloc(options, sizeof(cgltf_attribute), *out_attributes_count);
2890 ++i;
2891
2892 if (!*out_attributes)
2893 {
2894 return CGLTF_ERROR_NOMEM;
2895 }
2896
2897 for (cgltf_size j = 0; j < *out_attributes_count; ++j)
2898 {
2899 CGLTF_CHECK_KEY(tokens[i]);
2900
2901 i = cgltf_parse_json_string(options, tokens, i, json_chunk, &(*out_attributes)[j].name);
2902 if (i < 0)
2903 {
2904 return CGLTF_ERROR_JSON;
2905 }
2906
2907 cgltf_parse_attribute_type((*out_attributes)[j].name, &(*out_attributes)[j].type, &(*out_attributes)[j].index);
2908
2909 (*out_attributes)[j].data = CGLTF_PTRINDEX(cgltf_accessor, cgltf_json_to_int(tokens + i, json_chunk));
2910 ++i;
2911 }
2912
2913 return i;
2914}
2915
2916static int cgltf_parse_json_extras(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_extras* out_extras)
2917{
2918 if (out_extras->data)
2919 {
2920 return CGLTF_ERROR_JSON;
2921 }
2922
2923 /* fill deprecated fields for now, this will be removed in the future */
2924 out_extras->start_offset = tokens[i].start;
2925 out_extras->end_offset = tokens[i].end;
2926
2927 size_t start = tokens[i].start;
2928 size_t size = tokens[i].end - start;
2929 out_extras->data = (char*)options->memory.alloc_func(options->memory.user_data, size + 1);
2930 if (!out_extras->data)
2931 {
2932 return CGLTF_ERROR_NOMEM;
2933 }
2934 strncpy(out_extras->data, (const char*)json_chunk + start, size);
2935 out_extras->data[size] = '\0';
2936
2937 i = cgltf_skip_json(tokens, i);
2938 return i;
2939}
2940
2941static int cgltf_parse_json_unprocessed_extension(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_extension* out_extension)
2942{
2943 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_STRING);
2944 CGLTF_CHECK_TOKTYPE(tokens[i+1], JSMN_OBJECT);
2945 if (out_extension->name)
2946 {
2947 return CGLTF_ERROR_JSON;
2948 }
2949
2950 cgltf_size name_length = tokens[i].end - tokens[i].start;
2951 out_extension->name = (char*)options->memory.alloc_func(options->memory.user_data, name_length + 1);
2952 if (!out_extension->name)
2953 {
2954 return CGLTF_ERROR_NOMEM;
2955 }
2956 strncpy(out_extension->name, (const char*)json_chunk + tokens[i].start, name_length);
2957 out_extension->name[name_length] = 0;
2958 i++;
2959
2960 size_t start = tokens[i].start;
2961 size_t size = tokens[i].end - start;
2962 out_extension->data = (char*)options->memory.alloc_func(options->memory.user_data, size + 1);
2963 if (!out_extension->data)
2964 {
2965 return CGLTF_ERROR_NOMEM;
2966 }
2967 strncpy(out_extension->data, (const char*)json_chunk + start, size);
2968 out_extension->data[size] = '\0';
2969
2970 i = cgltf_skip_json(tokens, i);
2971
2972 return i;
2973}
2974
2975static int cgltf_parse_json_unprocessed_extensions(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_size* out_extensions_count, cgltf_extension** out_extensions)
2976{
2977 ++i;
2978
2979 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
2980 if(*out_extensions)
2981 {
2982 return CGLTF_ERROR_JSON;
2983 }
2984
2985 int extensions_size = tokens[i].size;
2986 *out_extensions_count = 0;
2987 *out_extensions = (cgltf_extension*)cgltf_calloc(options, sizeof(cgltf_extension), extensions_size);
2988
2989 if (!*out_extensions)
2990 {
2991 return CGLTF_ERROR_NOMEM;
2992 }
2993
2994 ++i;
2995
2996 for (int j = 0; j < extensions_size; ++j)
2997 {
2998 CGLTF_CHECK_KEY(tokens[i]);
2999
3000 cgltf_size extension_index = (*out_extensions_count)++;
3001 cgltf_extension* extension = &((*out_extensions)[extension_index]);
3002 i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, extension);
3003
3004 if (i < 0)
3005 {
3006 return i;
3007 }
3008 }
3009 return i;
3010}
3011
3012static int cgltf_parse_json_draco_mesh_compression(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_draco_mesh_compression* out_draco_mesh_compression)
3013{
3014 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
3015
3016 int size = tokens[i].size;
3017 ++i;
3018
3019 for (int j = 0; j < size; ++j)
3020 {
3021 CGLTF_CHECK_KEY(tokens[i]);
3022
3023 if (cgltf_json_strcmp(tokens + i, json_chunk, "attributes") == 0)
3024 {
3025 i = cgltf_parse_json_attribute_list(options, tokens, i + 1, json_chunk, &out_draco_mesh_compression->attributes, &out_draco_mesh_compression->attributes_count);
3026 }
3027 else if (cgltf_json_strcmp(tokens + i, json_chunk, "bufferView") == 0)
3028 {
3029 ++i;
3030 out_draco_mesh_compression->buffer_view = CGLTF_PTRINDEX(cgltf_buffer_view, cgltf_json_to_int(tokens + i, json_chunk));
3031 ++i;
3032 }
3033 else
3034 {
3035 i = cgltf_skip_json(tokens, i+1);
3036 }
3037
3038 if (i < 0)
3039 {
3040 return i;
3041 }
3042 }
3043
3044 return i;
3045}
3046
3047static int cgltf_parse_json_mesh_gpu_instancing(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_mesh_gpu_instancing* out_mesh_gpu_instancing)
3048{
3049 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
3050
3051 int size = tokens[i].size;
3052 ++i;
3053
3054 for (int j = 0; j < size; ++j)
3055 {
3056 CGLTF_CHECK_KEY(tokens[i]);
3057
3058 if (cgltf_json_strcmp(tokens + i, json_chunk, "attributes") == 0)
3059 {
3060 i = cgltf_parse_json_attribute_list(options, tokens, i + 1, json_chunk, &out_mesh_gpu_instancing->attributes, &out_mesh_gpu_instancing->attributes_count);
3061 }
3062 else
3063 {
3064 i = cgltf_skip_json(tokens, i+1);
3065 }
3066
3067 if (i < 0)
3068 {
3069 return i;
3070 }
3071 }
3072
3073 return i;
3074}
3075
3076static int cgltf_parse_json_material_mapping_data(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_material_mapping* out_mappings, cgltf_size* offset)
3077{
3078 (void)options;
3079 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_ARRAY);
3080
3081 int size = tokens[i].size;
3082 ++i;
3083
3084 for (int j = 0; j < size; ++j)
3085 {
3086 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
3087
3088 int obj_size = tokens[i].size;
3089 ++i;
3090
3091 int material = -1;
3092 int variants_tok = -1;
3093 int extras_tok = -1;
3094
3095 for (int k = 0; k < obj_size; ++k)
3096 {
3097 CGLTF_CHECK_KEY(tokens[i]);
3098
3099 if (cgltf_json_strcmp(tokens + i, json_chunk, "material") == 0)
3100 {
3101 ++i;
3102 material = cgltf_json_to_int(tokens + i, json_chunk);
3103 ++i;
3104 }
3105 else if (cgltf_json_strcmp(tokens + i, json_chunk, "variants") == 0)
3106 {
3107 variants_tok = i+1;
3108 CGLTF_CHECK_TOKTYPE(tokens[variants_tok], JSMN_ARRAY);
3109
3110 i = cgltf_skip_json(tokens, i+1);
3111 }
3112 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
3113 {
3114 extras_tok = i + 1;
3115 i = cgltf_skip_json(tokens, extras_tok);
3116 }
3117 else
3118 {
3119 i = cgltf_skip_json(tokens, i+1);
3120 }
3121
3122 if (i < 0)
3123 {
3124 return i;
3125 }
3126 }
3127
3128 if (material < 0 || variants_tok < 0)
3129 {
3130 return CGLTF_ERROR_JSON;
3131 }
3132
3133 if (out_mappings)
3134 {
3135 for (int k = 0; k < tokens[variants_tok].size; ++k)
3136 {
3137 int variant = cgltf_json_to_int(&tokens[variants_tok + 1 + k], json_chunk);
3138 if (variant < 0)
3139 return variant;
3140
3141 out_mappings[*offset].material = CGLTF_PTRINDEX(cgltf_material, material);
3142 out_mappings[*offset].variant = variant;
3143
3144 if (extras_tok >= 0)
3145 {
3146 int e = cgltf_parse_json_extras(options, tokens, extras_tok, json_chunk, &out_mappings[*offset].extras);
3147 if (e < 0)
3148 return e;
3149 }
3150
3151 (*offset)++;
3152 }
3153 }
3154 else
3155 {
3156 (*offset) += tokens[variants_tok].size;
3157 }
3158 }
3159
3160 return i;
3161}
3162
3163static int cgltf_parse_json_material_mappings(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_primitive* out_prim)
3164{
3165 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
3166
3167 int size = tokens[i].size;
3168 ++i;
3169
3170 for (int j = 0; j < size; ++j)
3171 {
3172 CGLTF_CHECK_KEY(tokens[i]);
3173
3174 if (cgltf_json_strcmp(tokens + i, json_chunk, "mappings") == 0)
3175 {
3176 if (out_prim->mappings)
3177 {
3178 return CGLTF_ERROR_JSON;
3179 }
3180
3181 cgltf_size mappings_offset = 0;
3182 int k = cgltf_parse_json_material_mapping_data(options, tokens, i + 1, json_chunk, NULL, &mappings_offset);
3183 if (k < 0)
3184 {
3185 return k;
3186 }
3187
3188 out_prim->mappings_count = mappings_offset;
3189 out_prim->mappings = (cgltf_material_mapping*)cgltf_calloc(options, sizeof(cgltf_material_mapping), out_prim->mappings_count);
3190
3191 mappings_offset = 0;
3192 i = cgltf_parse_json_material_mapping_data(options, tokens, i + 1, json_chunk, out_prim->mappings, &mappings_offset);
3193 }
3194 else
3195 {
3196 i = cgltf_skip_json(tokens, i+1);
3197 }
3198
3199 if (i < 0)
3200 {
3201 return i;
3202 }
3203 }
3204
3205 return i;
3206}
3207
3208static cgltf_primitive_type cgltf_json_to_primitive_type(jsmntok_t const* tok, const uint8_t* json_chunk)
3209{
3210 int type = cgltf_json_to_int(tok, json_chunk);
3211
3212 switch (type)
3213 {
3214 case 0:
3215 return cgltf_primitive_type_points;
3216 case 1:
3217 return cgltf_primitive_type_lines;
3218 case 2:
3219 return cgltf_primitive_type_line_loop;
3220 case 3:
3221 return cgltf_primitive_type_line_strip;
3222 case 4:
3223 return cgltf_primitive_type_triangles;
3224 case 5:
3225 return cgltf_primitive_type_triangle_strip;
3226 case 6:
3227 return cgltf_primitive_type_triangle_fan;
3228 default:
3229 return cgltf_primitive_type_invalid;
3230 }
3231}
3232
3233static int cgltf_parse_json_primitive(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_primitive* out_prim)
3234{
3235 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
3236
3237 out_prim->type = cgltf_primitive_type_triangles;
3238
3239 int size = tokens[i].size;
3240 ++i;
3241
3242 for (int j = 0; j < size; ++j)
3243 {
3244 CGLTF_CHECK_KEY(tokens[i]);
3245
3246 if (cgltf_json_strcmp(tokens+i, json_chunk, "mode") == 0)
3247 {
3248 ++i;
3249 out_prim->type = cgltf_json_to_primitive_type(tokens+i, json_chunk);
3250 ++i;
3251 }
3252 else if (cgltf_json_strcmp(tokens+i, json_chunk, "indices") == 0)
3253 {
3254 ++i;
3255 out_prim->indices = CGLTF_PTRINDEX(cgltf_accessor, cgltf_json_to_int(tokens + i, json_chunk));
3256 ++i;
3257 }
3258 else if (cgltf_json_strcmp(tokens+i, json_chunk, "material") == 0)
3259 {
3260 ++i;
3261 out_prim->material = CGLTF_PTRINDEX(cgltf_material, cgltf_json_to_int(tokens + i, json_chunk));
3262 ++i;
3263 }
3264 else if (cgltf_json_strcmp(tokens+i, json_chunk, "attributes") == 0)
3265 {
3266 i = cgltf_parse_json_attribute_list(options, tokens, i + 1, json_chunk, &out_prim->attributes, &out_prim->attributes_count);
3267 }
3268 else if (cgltf_json_strcmp(tokens+i, json_chunk, "targets") == 0)
3269 {
3270 i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_morph_target), (void**)&out_prim->targets, &out_prim->targets_count);
3271 if (i < 0)
3272 {
3273 return i;
3274 }
3275
3276 for (cgltf_size k = 0; k < out_prim->targets_count; ++k)
3277 {
3278 i = cgltf_parse_json_attribute_list(options, tokens, i, json_chunk, &out_prim->targets[k].attributes, &out_prim->targets[k].attributes_count);
3279 if (i < 0)
3280 {
3281 return i;
3282 }
3283 }
3284 }
3285 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
3286 {
3287 i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_prim->extras);
3288 }
3289 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
3290 {
3291 ++i;
3292
3293 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
3294 if(out_prim->extensions)
3295 {
3296 return CGLTF_ERROR_JSON;
3297 }
3298
3299 int extensions_size = tokens[i].size;
3300 out_prim->extensions_count = 0;
3301 out_prim->extensions = (cgltf_extension*)cgltf_calloc(options, sizeof(cgltf_extension), extensions_size);
3302
3303 if (!out_prim->extensions)
3304 {
3305 return CGLTF_ERROR_NOMEM;
3306 }
3307
3308 ++i;
3309 for (int k = 0; k < extensions_size; ++k)
3310 {
3311 CGLTF_CHECK_KEY(tokens[i]);
3312
3313 if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_draco_mesh_compression") == 0)
3314 {
3315 out_prim->has_draco_mesh_compression = 1;
3316 i = cgltf_parse_json_draco_mesh_compression(options, tokens, i + 1, json_chunk, &out_prim->draco_mesh_compression);
3317 }
3318 else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_variants") == 0)
3319 {
3320 i = cgltf_parse_json_material_mappings(options, tokens, i + 1, json_chunk, out_prim);
3321 }
3322 else
3323 {
3324 i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, &(out_prim->extensions[out_prim->extensions_count++]));
3325 }
3326
3327 if (i < 0)
3328 {
3329 return i;
3330 }
3331 }
3332 }
3333 else
3334 {
3335 i = cgltf_skip_json(tokens, i+1);
3336 }
3337
3338 if (i < 0)
3339 {
3340 return i;
3341 }
3342 }
3343
3344 return i;
3345}
3346
3347static int cgltf_parse_json_mesh(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_mesh* out_mesh)
3348{
3349 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
3350
3351 int size = tokens[i].size;
3352 ++i;
3353
3354 for (int j = 0; j < size; ++j)
3355 {
3356 CGLTF_CHECK_KEY(tokens[i]);
3357
3358 if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0)
3359 {
3360 i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_mesh->name);
3361 }
3362 else if (cgltf_json_strcmp(tokens+i, json_chunk, "primitives") == 0)
3363 {
3364 i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_primitive), (void**)&out_mesh->primitives, &out_mesh->primitives_count);
3365 if (i < 0)
3366 {
3367 return i;
3368 }
3369
3370 for (cgltf_size prim_index = 0; prim_index < out_mesh->primitives_count; ++prim_index)
3371 {
3372 i = cgltf_parse_json_primitive(options, tokens, i, json_chunk, &out_mesh->primitives[prim_index]);
3373 if (i < 0)
3374 {
3375 return i;
3376 }
3377 }
3378 }
3379 else if (cgltf_json_strcmp(tokens + i, json_chunk, "weights") == 0)
3380 {
3381 i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_float), (void**)&out_mesh->weights, &out_mesh->weights_count);
3382 if (i < 0)
3383 {
3384 return i;
3385 }
3386
3387 i = cgltf_parse_json_float_array(tokens, i - 1, json_chunk, out_mesh->weights, (int)out_mesh->weights_count);
3388 }
3389 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
3390 {
3391 ++i;
3392
3393 out_mesh->extras.start_offset = tokens[i].start;
3394 out_mesh->extras.end_offset = tokens[i].end;
3395
3396 if (tokens[i].type == JSMN_OBJECT)
3397 {
3398 int extras_size = tokens[i].size;
3399 ++i;
3400
3401 for (int k = 0; k < extras_size; ++k)
3402 {
3403 CGLTF_CHECK_KEY(tokens[i]);
3404
3405 if (cgltf_json_strcmp(tokens+i, json_chunk, "targetNames") == 0 && tokens[i+1].type == JSMN_ARRAY)
3406 {
3407 i = cgltf_parse_json_string_array(options, tokens, i + 1, json_chunk, &out_mesh->target_names, &out_mesh->target_names_count);
3408 }
3409 else
3410 {
3411 i = cgltf_skip_json(tokens, i+1);
3412 }
3413
3414 if (i < 0)
3415 {
3416 return i;
3417 }
3418 }
3419 }
3420 else
3421 {
3422 i = cgltf_skip_json(tokens, i);
3423 }
3424 }
3425 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
3426 {
3427 i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_mesh->extensions_count, &out_mesh->extensions);
3428 }
3429 else
3430 {
3431 i = cgltf_skip_json(tokens, i+1);
3432 }
3433
3434 if (i < 0)
3435 {
3436 return i;
3437 }
3438 }
3439
3440 return i;
3441}
3442
3443static int cgltf_parse_json_meshes(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data)
3444{
3445 i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_mesh), (void**)&out_data->meshes, &out_data->meshes_count);
3446 if (i < 0)
3447 {
3448 return i;
3449 }
3450
3451 for (cgltf_size j = 0; j < out_data->meshes_count; ++j)
3452 {
3453 i = cgltf_parse_json_mesh(options, tokens, i, json_chunk, &out_data->meshes[j]);
3454 if (i < 0)
3455 {
3456 return i;
3457 }
3458 }
3459 return i;
3460}
3461
3462static cgltf_component_type cgltf_json_to_component_type(jsmntok_t const* tok, const uint8_t* json_chunk)
3463{
3464 int type = cgltf_json_to_int(tok, json_chunk);
3465
3466 switch (type)
3467 {
3468 case 5120:
3469 return cgltf_component_type_r_8;
3470 case 5121:
3471 return cgltf_component_type_r_8u;
3472 case 5122:
3473 return cgltf_component_type_r_16;
3474 case 5123:
3475 return cgltf_component_type_r_16u;
3476 case 5125:
3477 return cgltf_component_type_r_32u;
3478 case 5126:
3479 return cgltf_component_type_r_32f;
3480 default:
3481 return cgltf_component_type_invalid;
3482 }
3483}
3484
3485static int cgltf_parse_json_accessor_sparse(jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_accessor_sparse* out_sparse)
3486{
3487 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
3488
3489 int size = tokens[i].size;
3490 ++i;
3491
3492 for (int j = 0; j < size; ++j)
3493 {
3494 CGLTF_CHECK_KEY(tokens[i]);
3495
3496 if (cgltf_json_strcmp(tokens+i, json_chunk, "count") == 0)
3497 {
3498 ++i;
3499 out_sparse->count = cgltf_json_to_size(tokens + i, json_chunk);
3500 ++i;
3501 }
3502 else if (cgltf_json_strcmp(tokens+i, json_chunk, "indices") == 0)
3503 {
3504 ++i;
3505 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
3506
3507 int indices_size = tokens[i].size;
3508 ++i;
3509
3510 for (int k = 0; k < indices_size; ++k)
3511 {
3512 CGLTF_CHECK_KEY(tokens[i]);
3513
3514 if (cgltf_json_strcmp(tokens+i, json_chunk, "bufferView") == 0)
3515 {
3516 ++i;
3517 out_sparse->indices_buffer_view = CGLTF_PTRINDEX(cgltf_buffer_view, cgltf_json_to_int(tokens + i, json_chunk));
3518 ++i;
3519 }
3520 else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteOffset") == 0)
3521 {
3522 ++i;
3523 out_sparse->indices_byte_offset = cgltf_json_to_size(tokens + i, json_chunk);
3524 ++i;
3525 }
3526 else if (cgltf_json_strcmp(tokens+i, json_chunk, "componentType") == 0)
3527 {
3528 ++i;
3529 out_sparse->indices_component_type = cgltf_json_to_component_type(tokens + i, json_chunk);
3530 ++i;
3531 }
3532 else
3533 {
3534 i = cgltf_skip_json(tokens, i+1);
3535 }
3536
3537 if (i < 0)
3538 {
3539 return i;
3540 }
3541 }
3542 }
3543 else if (cgltf_json_strcmp(tokens+i, json_chunk, "values") == 0)
3544 {
3545 ++i;
3546 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
3547
3548 int values_size = tokens[i].size;
3549 ++i;
3550
3551 for (int k = 0; k < values_size; ++k)
3552 {
3553 CGLTF_CHECK_KEY(tokens[i]);
3554
3555 if (cgltf_json_strcmp(tokens+i, json_chunk, "bufferView") == 0)
3556 {
3557 ++i;
3558 out_sparse->values_buffer_view = CGLTF_PTRINDEX(cgltf_buffer_view, cgltf_json_to_int(tokens + i, json_chunk));
3559 ++i;
3560 }
3561 else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteOffset") == 0)
3562 {
3563 ++i;
3564 out_sparse->values_byte_offset = cgltf_json_to_size(tokens + i, json_chunk);
3565 ++i;
3566 }
3567 else
3568 {
3569 i = cgltf_skip_json(tokens, i+1);
3570 }
3571
3572 if (i < 0)
3573 {
3574 return i;
3575 }
3576 }
3577 }
3578 else
3579 {
3580 i = cgltf_skip_json(tokens, i+1);
3581 }
3582
3583 if (i < 0)
3584 {
3585 return i;
3586 }
3587 }
3588
3589 return i;
3590}
3591
3592static int cgltf_parse_json_accessor(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_accessor* out_accessor)
3593{
3594 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
3595
3596 int size = tokens[i].size;
3597 ++i;
3598
3599 for (int j = 0; j < size; ++j)
3600 {
3601 CGLTF_CHECK_KEY(tokens[i]);
3602
3603 if (cgltf_json_strcmp(tokens + i, json_chunk, "name") == 0)
3604 {
3605 i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_accessor->name);
3606 }
3607 else if (cgltf_json_strcmp(tokens+i, json_chunk, "bufferView") == 0)
3608 {
3609 ++i;
3610 out_accessor->buffer_view = CGLTF_PTRINDEX(cgltf_buffer_view, cgltf_json_to_int(tokens + i, json_chunk));
3611 ++i;
3612 }
3613 else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteOffset") == 0)
3614 {
3615 ++i;
3616 out_accessor->offset =
3617 cgltf_json_to_size(tokens+i, json_chunk);
3618 ++i;
3619 }
3620 else if (cgltf_json_strcmp(tokens+i, json_chunk, "componentType") == 0)
3621 {
3622 ++i;
3623 out_accessor->component_type = cgltf_json_to_component_type(tokens + i, json_chunk);
3624 ++i;
3625 }
3626 else if (cgltf_json_strcmp(tokens+i, json_chunk, "normalized") == 0)
3627 {
3628 ++i;
3629 out_accessor->normalized = cgltf_json_to_bool(tokens+i, json_chunk);
3630 ++i;
3631 }
3632 else if (cgltf_json_strcmp(tokens+i, json_chunk, "count") == 0)
3633 {
3634 ++i;
3635 out_accessor->count = cgltf_json_to_size(tokens+i, json_chunk);
3636 ++i;
3637 }
3638 else if (cgltf_json_strcmp(tokens+i, json_chunk, "type") == 0)
3639 {
3640 ++i;
3641 if (cgltf_json_strcmp(tokens+i, json_chunk, "SCALAR") == 0)
3642 {
3643 out_accessor->type = cgltf_type_scalar;
3644 }
3645 else if (cgltf_json_strcmp(tokens+i, json_chunk, "VEC2") == 0)
3646 {
3647 out_accessor->type = cgltf_type_vec2;
3648 }
3649 else if (cgltf_json_strcmp(tokens+i, json_chunk, "VEC3") == 0)
3650 {
3651 out_accessor->type = cgltf_type_vec3;
3652 }
3653 else if (cgltf_json_strcmp(tokens+i, json_chunk, "VEC4") == 0)
3654 {
3655 out_accessor->type = cgltf_type_vec4;
3656 }
3657 else if (cgltf_json_strcmp(tokens+i, json_chunk, "MAT2") == 0)
3658 {
3659 out_accessor->type = cgltf_type_mat2;
3660 }
3661 else if (cgltf_json_strcmp(tokens+i, json_chunk, "MAT3") == 0)
3662 {
3663 out_accessor->type = cgltf_type_mat3;
3664 }
3665 else if (cgltf_json_strcmp(tokens+i, json_chunk, "MAT4") == 0)
3666 {
3667 out_accessor->type = cgltf_type_mat4;
3668 }
3669 ++i;
3670 }
3671 else if (cgltf_json_strcmp(tokens + i, json_chunk, "min") == 0)
3672 {
3673 ++i;
3674 out_accessor->has_min = 1;
3675 // note: we can't parse the precise number of elements since type may not have been computed yet
3676 int min_size = tokens[i].size > 16 ? 16 : tokens[i].size;
3677 i = cgltf_parse_json_float_array(tokens, i, json_chunk, out_accessor->min, min_size);
3678 }
3679 else if (cgltf_json_strcmp(tokens + i, json_chunk, "max") == 0)
3680 {
3681 ++i;
3682 out_accessor->has_max = 1;
3683 // note: we can't parse the precise number of elements since type may not have been computed yet
3684 int max_size = tokens[i].size > 16 ? 16 : tokens[i].size;
3685 i = cgltf_parse_json_float_array(tokens, i, json_chunk, out_accessor->max, max_size);
3686 }
3687 else if (cgltf_json_strcmp(tokens + i, json_chunk, "sparse") == 0)
3688 {
3689 out_accessor->is_sparse = 1;
3690 i = cgltf_parse_json_accessor_sparse(tokens, i + 1, json_chunk, &out_accessor->sparse);
3691 }
3692 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
3693 {
3694 i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_accessor->extras);
3695 }
3696 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
3697 {
3698 i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_accessor->extensions_count, &out_accessor->extensions);
3699 }
3700 else
3701 {
3702 i = cgltf_skip_json(tokens, i+1);
3703 }
3704
3705 if (i < 0)
3706 {
3707 return i;
3708 }
3709 }
3710
3711 return i;
3712}
3713
3714static int cgltf_parse_json_texture_transform(jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_texture_transform* out_texture_transform)
3715{
3716 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
3717
3718 int size = tokens[i].size;
3719 ++i;
3720
3721 for (int j = 0; j < size; ++j)
3722 {
3723 CGLTF_CHECK_KEY(tokens[i]);
3724
3725 if (cgltf_json_strcmp(tokens + i, json_chunk, "offset") == 0)
3726 {
3727 i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_texture_transform->offset, 2);
3728 }
3729 else if (cgltf_json_strcmp(tokens + i, json_chunk, "rotation") == 0)
3730 {
3731 ++i;
3732 out_texture_transform->rotation = cgltf_json_to_float(tokens + i, json_chunk);
3733 ++i;
3734 }
3735 else if (cgltf_json_strcmp(tokens + i, json_chunk, "scale") == 0)
3736 {
3737 i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_texture_transform->scale, 2);
3738 }
3739 else if (cgltf_json_strcmp(tokens + i, json_chunk, "texCoord") == 0)
3740 {
3741 ++i;
3742 out_texture_transform->has_texcoord = 1;
3743 out_texture_transform->texcoord = cgltf_json_to_int(tokens + i, json_chunk);
3744 ++i;
3745 }
3746 else
3747 {
3748 i = cgltf_skip_json(tokens, i + 1);
3749 }
3750
3751 if (i < 0)
3752 {
3753 return i;
3754 }
3755 }
3756
3757 return i;
3758}
3759
3760static int cgltf_parse_json_texture_view(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_texture_view* out_texture_view)
3761{
3762 (void)options;
3763
3764 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
3765
3766 out_texture_view->scale = 1.0f;
3767 cgltf_fill_float_array(out_texture_view->transform.scale, 2, 1.0f);
3768
3769 int size = tokens[i].size;
3770 ++i;
3771
3772 for (int j = 0; j < size; ++j)
3773 {
3774 CGLTF_CHECK_KEY(tokens[i]);
3775
3776 if (cgltf_json_strcmp(tokens + i, json_chunk, "index") == 0)
3777 {
3778 ++i;
3779 out_texture_view->texture = CGLTF_PTRINDEX(cgltf_texture, cgltf_json_to_int(tokens + i, json_chunk));
3780 ++i;
3781 }
3782 else if (cgltf_json_strcmp(tokens + i, json_chunk, "texCoord") == 0)
3783 {
3784 ++i;
3785 out_texture_view->texcoord = cgltf_json_to_int(tokens + i, json_chunk);
3786 ++i;
3787 }
3788 else if (cgltf_json_strcmp(tokens + i, json_chunk, "scale") == 0)
3789 {
3790 ++i;
3791 out_texture_view->scale = cgltf_json_to_float(tokens + i, json_chunk);
3792 ++i;
3793 }
3794 else if (cgltf_json_strcmp(tokens + i, json_chunk, "strength") == 0)
3795 {
3796 ++i;
3797 out_texture_view->scale = cgltf_json_to_float(tokens + i, json_chunk);
3798 ++i;
3799 }
3800 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
3801 {
3802 ++i;
3803
3804 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
3805 int extensions_size = tokens[i].size;
3806
3807 ++i;
3808
3809 for (int k = 0; k < extensions_size; ++k)
3810 {
3811 CGLTF_CHECK_KEY(tokens[i]);
3812
3813 if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_texture_transform") == 0)
3814 {
3815 out_texture_view->has_transform = 1;
3816 i = cgltf_parse_json_texture_transform(tokens, i + 1, json_chunk, &out_texture_view->transform);
3817 }
3818 else
3819 {
3820 i = cgltf_skip_json(tokens, i + 1);
3821 }
3822
3823 if (i < 0)
3824 {
3825 return i;
3826 }
3827 }
3828 }
3829 else
3830 {
3831 i = cgltf_skip_json(tokens, i + 1);
3832 }
3833
3834 if (i < 0)
3835 {
3836 return i;
3837 }
3838 }
3839
3840 return i;
3841}
3842
3843static int cgltf_parse_json_pbr_metallic_roughness(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_pbr_metallic_roughness* out_pbr)
3844{
3845 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
3846
3847 int size = tokens[i].size;
3848 ++i;
3849
3850 for (int j = 0; j < size; ++j)
3851 {
3852 CGLTF_CHECK_KEY(tokens[i]);
3853
3854 if (cgltf_json_strcmp(tokens+i, json_chunk, "metallicFactor") == 0)
3855 {
3856 ++i;
3857 out_pbr->metallic_factor =
3858 cgltf_json_to_float(tokens + i, json_chunk);
3859 ++i;
3860 }
3861 else if (cgltf_json_strcmp(tokens+i, json_chunk, "roughnessFactor") == 0)
3862 {
3863 ++i;
3864 out_pbr->roughness_factor =
3865 cgltf_json_to_float(tokens+i, json_chunk);
3866 ++i;
3867 }
3868 else if (cgltf_json_strcmp(tokens+i, json_chunk, "baseColorFactor") == 0)
3869 {
3870 i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_pbr->base_color_factor, 4);
3871 }
3872 else if (cgltf_json_strcmp(tokens+i, json_chunk, "baseColorTexture") == 0)
3873 {
3874 i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_pbr->base_color_texture);
3875 }
3876 else if (cgltf_json_strcmp(tokens + i, json_chunk, "metallicRoughnessTexture") == 0)
3877 {
3878 i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_pbr->metallic_roughness_texture);
3879 }
3880 else
3881 {
3882 i = cgltf_skip_json(tokens, i+1);
3883 }
3884
3885 if (i < 0)
3886 {
3887 return i;
3888 }
3889 }
3890
3891 return i;
3892}
3893
3894static int cgltf_parse_json_pbr_specular_glossiness(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_pbr_specular_glossiness* out_pbr)
3895{
3896 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
3897 int size = tokens[i].size;
3898 ++i;
3899
3900 for (int j = 0; j < size; ++j)
3901 {
3902 CGLTF_CHECK_KEY(tokens[i]);
3903
3904 if (cgltf_json_strcmp(tokens+i, json_chunk, "diffuseFactor") == 0)
3905 {
3906 i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_pbr->diffuse_factor, 4);
3907 }
3908 else if (cgltf_json_strcmp(tokens+i, json_chunk, "specularFactor") == 0)
3909 {
3910 i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_pbr->specular_factor, 3);
3911 }
3912 else if (cgltf_json_strcmp(tokens+i, json_chunk, "glossinessFactor") == 0)
3913 {
3914 ++i;
3915 out_pbr->glossiness_factor = cgltf_json_to_float(tokens + i, json_chunk);
3916 ++i;
3917 }
3918 else if (cgltf_json_strcmp(tokens+i, json_chunk, "diffuseTexture") == 0)
3919 {
3920 i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_pbr->diffuse_texture);
3921 }
3922 else if (cgltf_json_strcmp(tokens+i, json_chunk, "specularGlossinessTexture") == 0)
3923 {
3924 i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_pbr->specular_glossiness_texture);
3925 }
3926 else
3927 {
3928 i = cgltf_skip_json(tokens, i+1);
3929 }
3930
3931 if (i < 0)
3932 {
3933 return i;
3934 }
3935 }
3936
3937 return i;
3938}
3939
3940static int cgltf_parse_json_clearcoat(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_clearcoat* out_clearcoat)
3941{
3942 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
3943 int size = tokens[i].size;
3944 ++i;
3945
3946 for (int j = 0; j < size; ++j)
3947 {
3948 CGLTF_CHECK_KEY(tokens[i]);
3949
3950 if (cgltf_json_strcmp(tokens+i, json_chunk, "clearcoatFactor") == 0)
3951 {
3952 ++i;
3953 out_clearcoat->clearcoat_factor = cgltf_json_to_float(tokens + i, json_chunk);
3954 ++i;
3955 }
3956 else if (cgltf_json_strcmp(tokens+i, json_chunk, "clearcoatRoughnessFactor") == 0)
3957 {
3958 ++i;
3959 out_clearcoat->clearcoat_roughness_factor = cgltf_json_to_float(tokens + i, json_chunk);
3960 ++i;
3961 }
3962 else if (cgltf_json_strcmp(tokens+i, json_chunk, "clearcoatTexture") == 0)
3963 {
3964 i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_clearcoat->clearcoat_texture);
3965 }
3966 else if (cgltf_json_strcmp(tokens+i, json_chunk, "clearcoatRoughnessTexture") == 0)
3967 {
3968 i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_clearcoat->clearcoat_roughness_texture);
3969 }
3970 else if (cgltf_json_strcmp(tokens+i, json_chunk, "clearcoatNormalTexture") == 0)
3971 {
3972 i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_clearcoat->clearcoat_normal_texture);
3973 }
3974 else
3975 {
3976 i = cgltf_skip_json(tokens, i+1);
3977 }
3978
3979 if (i < 0)
3980 {
3981 return i;
3982 }
3983 }
3984
3985 return i;
3986}
3987
3988static int cgltf_parse_json_ior(jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_ior* out_ior)
3989{
3990 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
3991 int size = tokens[i].size;
3992 ++i;
3993
3994 // Default values
3995 out_ior->ior = 1.5f;
3996
3997 for (int j = 0; j < size; ++j)
3998 {
3999 CGLTF_CHECK_KEY(tokens[i]);
4000
4001 if (cgltf_json_strcmp(tokens+i, json_chunk, "ior") == 0)
4002 {
4003 ++i;
4004 out_ior->ior = cgltf_json_to_float(tokens + i, json_chunk);
4005 ++i;
4006 }
4007 else
4008 {
4009 i = cgltf_skip_json(tokens, i+1);
4010 }
4011
4012 if (i < 0)
4013 {
4014 return i;
4015 }
4016 }
4017
4018 return i;
4019}
4020
4021static int cgltf_parse_json_specular(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_specular* out_specular)
4022{
4023 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
4024 int size = tokens[i].size;
4025 ++i;
4026
4027 // Default values
4028 out_specular->specular_factor = 1.0f;
4029 cgltf_fill_float_array(out_specular->specular_color_factor, 3, 1.0f);
4030
4031 for (int j = 0; j < size; ++j)
4032 {
4033 CGLTF_CHECK_KEY(tokens[i]);
4034
4035 if (cgltf_json_strcmp(tokens+i, json_chunk, "specularFactor") == 0)
4036 {
4037 ++i;
4038 out_specular->specular_factor = cgltf_json_to_float(tokens + i, json_chunk);
4039 ++i;
4040 }
4041 else if (cgltf_json_strcmp(tokens+i, json_chunk, "specularColorFactor") == 0)
4042 {
4043 i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_specular->specular_color_factor, 3);
4044 }
4045 else if (cgltf_json_strcmp(tokens+i, json_chunk, "specularTexture") == 0)
4046 {
4047 i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_specular->specular_texture);
4048 }
4049 else if (cgltf_json_strcmp(tokens + i, json_chunk, "specularColorTexture") == 0)
4050 {
4051 i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_specular->specular_color_texture);
4052 }
4053 else
4054 {
4055 i = cgltf_skip_json(tokens, i+1);
4056 }
4057
4058 if (i < 0)
4059 {
4060 return i;
4061 }
4062 }
4063
4064 return i;
4065}
4066
4067static int cgltf_parse_json_transmission(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_transmission* out_transmission)
4068{
4069 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
4070 int size = tokens[i].size;
4071 ++i;
4072
4073 for (int j = 0; j < size; ++j)
4074 {
4075 CGLTF_CHECK_KEY(tokens[i]);
4076
4077 if (cgltf_json_strcmp(tokens+i, json_chunk, "transmissionFactor") == 0)
4078 {
4079 ++i;
4080 out_transmission->transmission_factor = cgltf_json_to_float(tokens + i, json_chunk);
4081 ++i;
4082 }
4083 else if (cgltf_json_strcmp(tokens+i, json_chunk, "transmissionTexture") == 0)
4084 {
4085 i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_transmission->transmission_texture);
4086 }
4087 else
4088 {
4089 i = cgltf_skip_json(tokens, i+1);
4090 }
4091
4092 if (i < 0)
4093 {
4094 return i;
4095 }
4096 }
4097
4098 return i;
4099}
4100
4101static int cgltf_parse_json_volume(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_volume* out_volume)
4102{
4103 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
4104 int size = tokens[i].size;
4105 ++i;
4106
4107 for (int j = 0; j < size; ++j)
4108 {
4109 CGLTF_CHECK_KEY(tokens[i]);
4110
4111 if (cgltf_json_strcmp(tokens + i, json_chunk, "thicknessFactor") == 0)
4112 {
4113 ++i;
4114 out_volume->thickness_factor = cgltf_json_to_float(tokens + i, json_chunk);
4115 ++i;
4116 }
4117 else if (cgltf_json_strcmp(tokens + i, json_chunk, "thicknessTexture") == 0)
4118 {
4119 i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_volume->thickness_texture);
4120 }
4121 else if (cgltf_json_strcmp(tokens + i, json_chunk, "attenuationColor") == 0)
4122 {
4123 i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_volume->attenuation_color, 3);
4124 }
4125 else if (cgltf_json_strcmp(tokens + i, json_chunk, "attenuationDistance") == 0)
4126 {
4127 ++i;
4128 out_volume->attenuation_distance = cgltf_json_to_float(tokens + i, json_chunk);
4129 ++i;
4130 }
4131 else
4132 {
4133 i = cgltf_skip_json(tokens, i + 1);
4134 }
4135
4136 if (i < 0)
4137 {
4138 return i;
4139 }
4140 }
4141
4142 return i;
4143}
4144
4145static int cgltf_parse_json_sheen(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_sheen* out_sheen)
4146{
4147 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
4148 int size = tokens[i].size;
4149 ++i;
4150
4151 for (int j = 0; j < size; ++j)
4152 {
4153 CGLTF_CHECK_KEY(tokens[i]);
4154
4155 if (cgltf_json_strcmp(tokens+i, json_chunk, "sheenColorFactor") == 0)
4156 {
4157 i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_sheen->sheen_color_factor, 3);
4158 }
4159 else if (cgltf_json_strcmp(tokens+i, json_chunk, "sheenColorTexture") == 0)
4160 {
4161 i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_sheen->sheen_color_texture);
4162 }
4163 else if (cgltf_json_strcmp(tokens+i, json_chunk, "sheenRoughnessFactor") == 0)
4164 {
4165 ++i;
4166 out_sheen->sheen_roughness_factor = cgltf_json_to_float(tokens + i, json_chunk);
4167 ++i;
4168 }
4169 else if (cgltf_json_strcmp(tokens+i, json_chunk, "sheenRoughnessTexture") == 0)
4170 {
4171 i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_sheen->sheen_roughness_texture);
4172 }
4173 else
4174 {
4175 i = cgltf_skip_json(tokens, i+1);
4176 }
4177
4178 if (i < 0)
4179 {
4180 return i;
4181 }
4182 }
4183
4184 return i;
4185}
4186
4187static int cgltf_parse_json_emissive_strength(jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_emissive_strength* out_emissive_strength)
4188{
4189 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
4190 int size = tokens[i].size;
4191 ++i;
4192
4193 // Default
4194 out_emissive_strength->emissive_strength = 1.f;
4195
4196 for (int j = 0; j < size; ++j)
4197 {
4198 CGLTF_CHECK_KEY(tokens[i]);
4199
4200 if (cgltf_json_strcmp(tokens + i, json_chunk, "emissiveStrength") == 0)
4201 {
4202 ++i;
4203 out_emissive_strength->emissive_strength = cgltf_json_to_float(tokens + i, json_chunk);
4204 ++i;
4205 }
4206 else
4207 {
4208 i = cgltf_skip_json(tokens, i + 1);
4209 }
4210
4211 if (i < 0)
4212 {
4213 return i;
4214 }
4215 }
4216
4217 return i;
4218}
4219
4220static int cgltf_parse_json_iridescence(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_iridescence* out_iridescence)
4221{
4222 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
4223 int size = tokens[i].size;
4224 ++i;
4225
4226 // Default
4227 out_iridescence->iridescence_ior = 1.3f;
4228 out_iridescence->iridescence_thickness_min = 100.f;
4229 out_iridescence->iridescence_thickness_max = 400.f;
4230
4231 for (int j = 0; j < size; ++j)
4232 {
4233 CGLTF_CHECK_KEY(tokens[i]);
4234
4235 if (cgltf_json_strcmp(tokens + i, json_chunk, "iridescenceFactor") == 0)
4236 {
4237 ++i;
4238 out_iridescence->iridescence_factor = cgltf_json_to_float(tokens + i, json_chunk);
4239 ++i;
4240 }
4241 else if (cgltf_json_strcmp(tokens + i, json_chunk, "iridescenceTexture") == 0)
4242 {
4243 i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_iridescence->iridescence_texture);
4244 }
4245 else if (cgltf_json_strcmp(tokens + i, json_chunk, "iridescenceIor") == 0)
4246 {
4247 ++i;
4248 out_iridescence->iridescence_ior = cgltf_json_to_float(tokens + i, json_chunk);
4249 ++i;
4250 }
4251 else if (cgltf_json_strcmp(tokens + i, json_chunk, "iridescenceThicknessMinimum") == 0)
4252 {
4253 ++i;
4254 out_iridescence->iridescence_thickness_min = cgltf_json_to_float(tokens + i, json_chunk);
4255 ++i;
4256 }
4257 else if (cgltf_json_strcmp(tokens + i, json_chunk, "iridescenceThicknessMaximum") == 0)
4258 {
4259 ++i;
4260 out_iridescence->iridescence_thickness_max = cgltf_json_to_float(tokens + i, json_chunk);
4261 ++i;
4262 }
4263 else if (cgltf_json_strcmp(tokens + i, json_chunk, "iridescenceThicknessTexture") == 0)
4264 {
4265 i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_iridescence->iridescence_thickness_texture);
4266 }
4267 else
4268 {
4269 i = cgltf_skip_json(tokens, i + 1);
4270 }
4271
4272 if (i < 0)
4273 {
4274 return i;
4275 }
4276 }
4277
4278 return i;
4279}
4280
4281static int cgltf_parse_json_anisotropy(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_anisotropy* out_anisotropy)
4282{
4283 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
4284 int size = tokens[i].size;
4285 ++i;
4286
4287
4288 for (int j = 0; j < size; ++j)
4289 {
4290 CGLTF_CHECK_KEY(tokens[i]);
4291
4292 if (cgltf_json_strcmp(tokens + i, json_chunk, "anisotropyStrength") == 0)
4293 {
4294 ++i;
4295 out_anisotropy->anisotropy_strength = cgltf_json_to_float(tokens + i, json_chunk);
4296 ++i;
4297 }
4298 else if (cgltf_json_strcmp(tokens + i, json_chunk, "anisotropyRotation") == 0)
4299 {
4300 ++i;
4301 out_anisotropy->anisotropy_rotation = cgltf_json_to_float(tokens + i, json_chunk);
4302 ++i;
4303 }
4304 else if (cgltf_json_strcmp(tokens + i, json_chunk, "anisotropyTexture") == 0)
4305 {
4306 i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_anisotropy->anisotropy_texture);
4307 }
4308 else
4309 {
4310 i = cgltf_skip_json(tokens, i + 1);
4311 }
4312
4313 if (i < 0)
4314 {
4315 return i;
4316 }
4317 }
4318
4319 return i;
4320}
4321
4322static int cgltf_parse_json_dispersion(jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_dispersion* out_dispersion)
4323{
4324 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
4325 int size = tokens[i].size;
4326 ++i;
4327
4328
4329 for (int j = 0; j < size; ++j)
4330 {
4331 CGLTF_CHECK_KEY(tokens[i]);
4332
4333 if (cgltf_json_strcmp(tokens + i, json_chunk, "dispersion") == 0)
4334 {
4335 ++i;
4336 out_dispersion->dispersion = cgltf_json_to_float(tokens + i, json_chunk);
4337 ++i;
4338 }
4339 else
4340 {
4341 i = cgltf_skip_json(tokens, i + 1);
4342 }
4343
4344 if (i < 0)
4345 {
4346 return i;
4347 }
4348 }
4349
4350 return i;
4351}
4352
4353static int cgltf_parse_json_image(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_image* out_image)
4354{
4355 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
4356
4357 int size = tokens[i].size;
4358 ++i;
4359
4360 for (int j = 0; j < size; ++j)
4361 {
4362 CGLTF_CHECK_KEY(tokens[i]);
4363
4364 if (cgltf_json_strcmp(tokens + i, json_chunk, "uri") == 0)
4365 {
4366 i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_image->uri);
4367 }
4368 else if (cgltf_json_strcmp(tokens+i, json_chunk, "bufferView") == 0)
4369 {
4370 ++i;
4371 out_image->buffer_view = CGLTF_PTRINDEX(cgltf_buffer_view, cgltf_json_to_int(tokens + i, json_chunk));
4372 ++i;
4373 }
4374 else if (cgltf_json_strcmp(tokens + i, json_chunk, "mimeType") == 0)
4375 {
4376 i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_image->mime_type);
4377 }
4378 else if (cgltf_json_strcmp(tokens + i, json_chunk, "name") == 0)
4379 {
4380 i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_image->name);
4381 }
4382 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
4383 {
4384 i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_image->extras);
4385 }
4386 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
4387 {
4388 i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_image->extensions_count, &out_image->extensions);
4389 }
4390 else
4391 {
4392 i = cgltf_skip_json(tokens, i + 1);
4393 }
4394
4395 if (i < 0)
4396 {
4397 return i;
4398 }
4399 }
4400
4401 return i;
4402}
4403
4404static int cgltf_parse_json_sampler(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_sampler* out_sampler)
4405{
4406 (void)options;
4407 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
4408
4409 out_sampler->wrap_s = 10497;
4410 out_sampler->wrap_t = 10497;
4411
4412 int size = tokens[i].size;
4413 ++i;
4414
4415 for (int j = 0; j < size; ++j)
4416 {
4417 CGLTF_CHECK_KEY(tokens[i]);
4418
4419 if (cgltf_json_strcmp(tokens + i, json_chunk, "name") == 0)
4420 {
4421 i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_sampler->name);
4422 }
4423 else if (cgltf_json_strcmp(tokens + i, json_chunk, "magFilter") == 0)
4424 {
4425 ++i;
4426 out_sampler->mag_filter
4427 = cgltf_json_to_int(tokens + i, json_chunk);
4428 ++i;
4429 }
4430 else if (cgltf_json_strcmp(tokens + i, json_chunk, "minFilter") == 0)
4431 {
4432 ++i;
4433 out_sampler->min_filter
4434 = cgltf_json_to_int(tokens + i, json_chunk);
4435 ++i;
4436 }
4437 else if (cgltf_json_strcmp(tokens + i, json_chunk, "wrapS") == 0)
4438 {
4439 ++i;
4440 out_sampler->wrap_s
4441 = cgltf_json_to_int(tokens + i, json_chunk);
4442 ++i;
4443 }
4444 else if (cgltf_json_strcmp(tokens + i, json_chunk, "wrapT") == 0)
4445 {
4446 ++i;
4447 out_sampler->wrap_t
4448 = cgltf_json_to_int(tokens + i, json_chunk);
4449 ++i;
4450 }
4451 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
4452 {
4453 i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_sampler->extras);
4454 }
4455 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
4456 {
4457 i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_sampler->extensions_count, &out_sampler->extensions);
4458 }
4459 else
4460 {
4461 i = cgltf_skip_json(tokens, i + 1);
4462 }
4463
4464 if (i < 0)
4465 {
4466 return i;
4467 }
4468 }
4469
4470 return i;
4471}
4472
4473static int cgltf_parse_json_texture(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_texture* out_texture)
4474{
4475 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
4476
4477 int size = tokens[i].size;
4478 ++i;
4479
4480 for (int j = 0; j < size; ++j)
4481 {
4482 CGLTF_CHECK_KEY(tokens[i]);
4483
4484 if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0)
4485 {
4486 i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_texture->name);
4487 }
4488 else if (cgltf_json_strcmp(tokens + i, json_chunk, "sampler") == 0)
4489 {
4490 ++i;
4491 out_texture->sampler = CGLTF_PTRINDEX(cgltf_sampler, cgltf_json_to_int(tokens + i, json_chunk));
4492 ++i;
4493 }
4494 else if (cgltf_json_strcmp(tokens + i, json_chunk, "source") == 0)
4495 {
4496 ++i;
4497 out_texture->image = CGLTF_PTRINDEX(cgltf_image, cgltf_json_to_int(tokens + i, json_chunk));
4498 ++i;
4499 }
4500 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
4501 {
4502 i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_texture->extras);
4503 }
4504 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
4505 {
4506 ++i;
4507
4508 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
4509 if (out_texture->extensions)
4510 {
4511 return CGLTF_ERROR_JSON;
4512 }
4513
4514 int extensions_size = tokens[i].size;
4515 ++i;
4516 out_texture->extensions = (cgltf_extension*)cgltf_calloc(options, sizeof(cgltf_extension), extensions_size);
4517 out_texture->extensions_count = 0;
4518
4519 if (!out_texture->extensions)
4520 {
4521 return CGLTF_ERROR_NOMEM;
4522 }
4523
4524 for (int k = 0; k < extensions_size; ++k)
4525 {
4526 CGLTF_CHECK_KEY(tokens[i]);
4527
4528 if (cgltf_json_strcmp(tokens + i, json_chunk, "KHR_texture_basisu") == 0)
4529 {
4530 out_texture->has_basisu = 1;
4531 ++i;
4532 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
4533 int num_properties = tokens[i].size;
4534 ++i;
4535
4536 for (int t = 0; t < num_properties; ++t)
4537 {
4538 CGLTF_CHECK_KEY(tokens[i]);
4539
4540 if (cgltf_json_strcmp(tokens + i, json_chunk, "source") == 0)
4541 {
4542 ++i;
4543 out_texture->basisu_image = CGLTF_PTRINDEX(cgltf_image, cgltf_json_to_int(tokens + i, json_chunk));
4544 ++i;
4545 }
4546 else
4547 {
4548 i = cgltf_skip_json(tokens, i + 1);
4549 }
4550 if (i < 0)
4551 {
4552 return i;
4553 }
4554 }
4555 }
4556 else if (cgltf_json_strcmp(tokens + i, json_chunk, "EXT_texture_webp") == 0)
4557 {
4558 out_texture->has_webp = 1;
4559 ++i;
4560 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
4561 int num_properties = tokens[i].size;
4562 ++i;
4563
4564 for (int t = 0; t < num_properties; ++t)
4565 {
4566 CGLTF_CHECK_KEY(tokens[i]);
4567
4568 if (cgltf_json_strcmp(tokens + i, json_chunk, "source") == 0)
4569 {
4570 ++i;
4571 out_texture->webp_image = CGLTF_PTRINDEX(cgltf_image, cgltf_json_to_int(tokens + i, json_chunk));
4572 ++i;
4573 }
4574 else
4575 {
4576 i = cgltf_skip_json(tokens, i + 1);
4577 }
4578 if (i < 0)
4579 {
4580 return i;
4581 }
4582 }
4583 }
4584 else
4585 {
4586 i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, &(out_texture->extensions[out_texture->extensions_count++]));
4587 }
4588
4589 if (i < 0)
4590 {
4591 return i;
4592 }
4593 }
4594 }
4595 else
4596 {
4597 i = cgltf_skip_json(tokens, i + 1);
4598 }
4599
4600 if (i < 0)
4601 {
4602 return i;
4603 }
4604 }
4605
4606 return i;
4607}
4608
4609static int cgltf_parse_json_material(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_material* out_material)
4610{
4611 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
4612
4613 cgltf_fill_float_array(out_material->pbr_metallic_roughness.base_color_factor, 4, 1.0f);
4614 out_material->pbr_metallic_roughness.metallic_factor = 1.0f;
4615 out_material->pbr_metallic_roughness.roughness_factor = 1.0f;
4616
4617 cgltf_fill_float_array(out_material->pbr_specular_glossiness.diffuse_factor, 4, 1.0f);
4618 cgltf_fill_float_array(out_material->pbr_specular_glossiness.specular_factor, 3, 1.0f);
4619 out_material->pbr_specular_glossiness.glossiness_factor = 1.0f;
4620
4621 cgltf_fill_float_array(out_material->volume.attenuation_color, 3, 1.0f);
4622 out_material->volume.attenuation_distance = FLT_MAX;
4623
4624 out_material->alpha_cutoff = 0.5f;
4625
4626 int size = tokens[i].size;
4627 ++i;
4628
4629 for (int j = 0; j < size; ++j)
4630 {
4631 CGLTF_CHECK_KEY(tokens[i]);
4632
4633 if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0)
4634 {
4635 i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_material->name);
4636 }
4637 else if (cgltf_json_strcmp(tokens+i, json_chunk, "pbrMetallicRoughness") == 0)
4638 {
4639 out_material->has_pbr_metallic_roughness = 1;
4640 i = cgltf_parse_json_pbr_metallic_roughness(options, tokens, i + 1, json_chunk, &out_material->pbr_metallic_roughness);
4641 }
4642 else if (cgltf_json_strcmp(tokens+i, json_chunk, "emissiveFactor") == 0)
4643 {
4644 i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_material->emissive_factor, 3);
4645 }
4646 else if (cgltf_json_strcmp(tokens + i, json_chunk, "normalTexture") == 0)
4647 {
4648 i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk,
4649 &out_material->normal_texture);
4650 }
4651 else if (cgltf_json_strcmp(tokens + i, json_chunk, "occlusionTexture") == 0)
4652 {
4653 i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk,
4654 &out_material->occlusion_texture);
4655 }
4656 else if (cgltf_json_strcmp(tokens + i, json_chunk, "emissiveTexture") == 0)
4657 {
4658 i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk,
4659 &out_material->emissive_texture);
4660 }
4661 else if (cgltf_json_strcmp(tokens + i, json_chunk, "alphaMode") == 0)
4662 {
4663 ++i;
4664 if (cgltf_json_strcmp(tokens + i, json_chunk, "OPAQUE") == 0)
4665 {
4666 out_material->alpha_mode = cgltf_alpha_mode_opaque;
4667 }
4668 else if (cgltf_json_strcmp(tokens + i, json_chunk, "MASK") == 0)
4669 {
4670 out_material->alpha_mode = cgltf_alpha_mode_mask;
4671 }
4672 else if (cgltf_json_strcmp(tokens + i, json_chunk, "BLEND") == 0)
4673 {
4674 out_material->alpha_mode = cgltf_alpha_mode_blend;
4675 }
4676 ++i;
4677 }
4678 else if (cgltf_json_strcmp(tokens + i, json_chunk, "alphaCutoff") == 0)
4679 {
4680 ++i;
4681 out_material->alpha_cutoff = cgltf_json_to_float(tokens + i, json_chunk);
4682 ++i;
4683 }
4684 else if (cgltf_json_strcmp(tokens + i, json_chunk, "doubleSided") == 0)
4685 {
4686 ++i;
4687 out_material->double_sided =
4688 cgltf_json_to_bool(tokens + i, json_chunk);
4689 ++i;
4690 }
4691 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
4692 {
4693 i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_material->extras);
4694 }
4695 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
4696 {
4697 ++i;
4698
4699 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
4700 if(out_material->extensions)
4701 {
4702 return CGLTF_ERROR_JSON;
4703 }
4704
4705 int extensions_size = tokens[i].size;
4706 ++i;
4707 out_material->extensions = (cgltf_extension*)cgltf_calloc(options, sizeof(cgltf_extension), extensions_size);
4708 out_material->extensions_count= 0;
4709
4710 if (!out_material->extensions)
4711 {
4712 return CGLTF_ERROR_NOMEM;
4713 }
4714
4715 for (int k = 0; k < extensions_size; ++k)
4716 {
4717 CGLTF_CHECK_KEY(tokens[i]);
4718
4719 if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_pbrSpecularGlossiness") == 0)
4720 {
4721 out_material->has_pbr_specular_glossiness = 1;
4722 i = cgltf_parse_json_pbr_specular_glossiness(options, tokens, i + 1, json_chunk, &out_material->pbr_specular_glossiness);
4723 }
4724 else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_unlit") == 0)
4725 {
4726 out_material->unlit = 1;
4727 i = cgltf_skip_json(tokens, i+1);
4728 }
4729 else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_clearcoat") == 0)
4730 {
4731 out_material->has_clearcoat = 1;
4732 i = cgltf_parse_json_clearcoat(options, tokens, i + 1, json_chunk, &out_material->clearcoat);
4733 }
4734 else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_ior") == 0)
4735 {
4736 out_material->has_ior = 1;
4737 i = cgltf_parse_json_ior(tokens, i + 1, json_chunk, &out_material->ior);
4738 }
4739 else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_specular") == 0)
4740 {
4741 out_material->has_specular = 1;
4742 i = cgltf_parse_json_specular(options, tokens, i + 1, json_chunk, &out_material->specular);
4743 }
4744 else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_transmission") == 0)
4745 {
4746 out_material->has_transmission = 1;
4747 i = cgltf_parse_json_transmission(options, tokens, i + 1, json_chunk, &out_material->transmission);
4748 }
4749 else if (cgltf_json_strcmp(tokens + i, json_chunk, "KHR_materials_volume") == 0)
4750 {
4751 out_material->has_volume = 1;
4752 i = cgltf_parse_json_volume(options, tokens, i + 1, json_chunk, &out_material->volume);
4753 }
4754 else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_sheen") == 0)
4755 {
4756 out_material->has_sheen = 1;
4757 i = cgltf_parse_json_sheen(options, tokens, i + 1, json_chunk, &out_material->sheen);
4758 }
4759 else if (cgltf_json_strcmp(tokens + i, json_chunk, "KHR_materials_emissive_strength") == 0)
4760 {
4761 out_material->has_emissive_strength = 1;
4762 i = cgltf_parse_json_emissive_strength(tokens, i + 1, json_chunk, &out_material->emissive_strength);
4763 }
4764 else if (cgltf_json_strcmp(tokens + i, json_chunk, "KHR_materials_iridescence") == 0)
4765 {
4766 out_material->has_iridescence = 1;
4767 i = cgltf_parse_json_iridescence(options, tokens, i + 1, json_chunk, &out_material->iridescence);
4768 }
4769 else if (cgltf_json_strcmp(tokens + i, json_chunk, "KHR_materials_anisotropy") == 0)
4770 {
4771 out_material->has_anisotropy = 1;
4772 i = cgltf_parse_json_anisotropy(options, tokens, i + 1, json_chunk, &out_material->anisotropy);
4773 }
4774 else if (cgltf_json_strcmp(tokens + i, json_chunk, "KHR_materials_dispersion") == 0)
4775 {
4776 out_material->has_dispersion = 1;
4777 i = cgltf_parse_json_dispersion(tokens, i + 1, json_chunk, &out_material->dispersion);
4778 }
4779 else
4780 {
4781 i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, &(out_material->extensions[out_material->extensions_count++]));
4782 }
4783
4784 if (i < 0)
4785 {
4786 return i;
4787 }
4788 }
4789 }
4790 else
4791 {
4792 i = cgltf_skip_json(tokens, i+1);
4793 }
4794
4795 if (i < 0)
4796 {
4797 return i;
4798 }
4799 }
4800
4801 return i;
4802}
4803
4804static int cgltf_parse_json_accessors(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data)
4805{
4806 i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_accessor), (void**)&out_data->accessors, &out_data->accessors_count);
4807 if (i < 0)
4808 {
4809 return i;
4810 }
4811
4812 for (cgltf_size j = 0; j < out_data->accessors_count; ++j)
4813 {
4814 i = cgltf_parse_json_accessor(options, tokens, i, json_chunk, &out_data->accessors[j]);
4815 if (i < 0)
4816 {
4817 return i;
4818 }
4819 }
4820 return i;
4821}
4822
4823static int cgltf_parse_json_materials(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data)
4824{
4825 i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_material), (void**)&out_data->materials, &out_data->materials_count);
4826 if (i < 0)
4827 {
4828 return i;
4829 }
4830
4831 for (cgltf_size j = 0; j < out_data->materials_count; ++j)
4832 {
4833 i = cgltf_parse_json_material(options, tokens, i, json_chunk, &out_data->materials[j]);
4834 if (i < 0)
4835 {
4836 return i;
4837 }
4838 }
4839 return i;
4840}
4841
4842static int cgltf_parse_json_images(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data)
4843{
4844 i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_image), (void**)&out_data->images, &out_data->images_count);
4845 if (i < 0)
4846 {
4847 return i;
4848 }
4849
4850 for (cgltf_size j = 0; j < out_data->images_count; ++j)
4851 {
4852 i = cgltf_parse_json_image(options, tokens, i, json_chunk, &out_data->images[j]);
4853 if (i < 0)
4854 {
4855 return i;
4856 }
4857 }
4858 return i;
4859}
4860
4861static int cgltf_parse_json_textures(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data)
4862{
4863 i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_texture), (void**)&out_data->textures, &out_data->textures_count);
4864 if (i < 0)
4865 {
4866 return i;
4867 }
4868
4869 for (cgltf_size j = 0; j < out_data->textures_count; ++j)
4870 {
4871 i = cgltf_parse_json_texture(options, tokens, i, json_chunk, &out_data->textures[j]);
4872 if (i < 0)
4873 {
4874 return i;
4875 }
4876 }
4877 return i;
4878}
4879
4880static int cgltf_parse_json_samplers(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data)
4881{
4882 i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_sampler), (void**)&out_data->samplers, &out_data->samplers_count);
4883 if (i < 0)
4884 {
4885 return i;
4886 }
4887
4888 for (cgltf_size j = 0; j < out_data->samplers_count; ++j)
4889 {
4890 i = cgltf_parse_json_sampler(options, tokens, i, json_chunk, &out_data->samplers[j]);
4891 if (i < 0)
4892 {
4893 return i;
4894 }
4895 }
4896 return i;
4897}
4898
4899static int cgltf_parse_json_meshopt_compression(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_meshopt_compression* out_meshopt_compression)
4900{
4901 (void)options;
4902 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
4903
4904 int size = tokens[i].size;
4905 ++i;
4906
4907 for (int j = 0; j < size; ++j)
4908 {
4909 CGLTF_CHECK_KEY(tokens[i]);
4910
4911 if (cgltf_json_strcmp(tokens+i, json_chunk, "buffer") == 0)
4912 {
4913 ++i;
4914 out_meshopt_compression->buffer = CGLTF_PTRINDEX(cgltf_buffer, cgltf_json_to_int(tokens + i, json_chunk));
4915 ++i;
4916 }
4917 else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteOffset") == 0)
4918 {
4919 ++i;
4920 out_meshopt_compression->offset = cgltf_json_to_size(tokens+i, json_chunk);
4921 ++i;
4922 }
4923 else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteLength") == 0)
4924 {
4925 ++i;
4926 out_meshopt_compression->size = cgltf_json_to_size(tokens+i, json_chunk);
4927 ++i;
4928 }
4929 else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteStride") == 0)
4930 {
4931 ++i;
4932 out_meshopt_compression->stride = cgltf_json_to_size(tokens+i, json_chunk);
4933 ++i;
4934 }
4935 else if (cgltf_json_strcmp(tokens+i, json_chunk, "count") == 0)
4936 {
4937 ++i;
4938 out_meshopt_compression->count = cgltf_json_to_size(tokens+i, json_chunk);
4939 ++i;
4940 }
4941 else if (cgltf_json_strcmp(tokens+i, json_chunk, "mode") == 0)
4942 {
4943 ++i;
4944 if (cgltf_json_strcmp(tokens+i, json_chunk, "ATTRIBUTES") == 0)
4945 {
4946 out_meshopt_compression->mode = cgltf_meshopt_compression_mode_attributes;
4947 }
4948 else if (cgltf_json_strcmp(tokens+i, json_chunk, "TRIANGLES") == 0)
4949 {
4950 out_meshopt_compression->mode = cgltf_meshopt_compression_mode_triangles;
4951 }
4952 else if (cgltf_json_strcmp(tokens+i, json_chunk, "INDICES") == 0)
4953 {
4954 out_meshopt_compression->mode = cgltf_meshopt_compression_mode_indices;
4955 }
4956 ++i;
4957 }
4958 else if (cgltf_json_strcmp(tokens+i, json_chunk, "filter") == 0)
4959 {
4960 ++i;
4961 if (cgltf_json_strcmp(tokens+i, json_chunk, "NONE") == 0)
4962 {
4963 out_meshopt_compression->filter = cgltf_meshopt_compression_filter_none;
4964 }
4965 else if (cgltf_json_strcmp(tokens+i, json_chunk, "OCTAHEDRAL") == 0)
4966 {
4967 out_meshopt_compression->filter = cgltf_meshopt_compression_filter_octahedral;
4968 }
4969 else if (cgltf_json_strcmp(tokens+i, json_chunk, "QUATERNION") == 0)
4970 {
4971 out_meshopt_compression->filter = cgltf_meshopt_compression_filter_quaternion;
4972 }
4973 else if (cgltf_json_strcmp(tokens+i, json_chunk, "EXPONENTIAL") == 0)
4974 {
4975 out_meshopt_compression->filter = cgltf_meshopt_compression_filter_exponential;
4976 }
4977 ++i;
4978 }
4979 else
4980 {
4981 i = cgltf_skip_json(tokens, i+1);
4982 }
4983
4984 if (i < 0)
4985 {
4986 return i;
4987 }
4988 }
4989
4990 return i;
4991}
4992
4993static int cgltf_parse_json_buffer_view(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_buffer_view* out_buffer_view)
4994{
4995 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
4996
4997 int size = tokens[i].size;
4998 ++i;
4999
5000 for (int j = 0; j < size; ++j)
5001 {
5002 CGLTF_CHECK_KEY(tokens[i]);
5003
5004 if (cgltf_json_strcmp(tokens + i, json_chunk, "name") == 0)
5005 {
5006 i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_buffer_view->name);
5007 }
5008 else if (cgltf_json_strcmp(tokens+i, json_chunk, "buffer") == 0)
5009 {
5010 ++i;
5011 out_buffer_view->buffer = CGLTF_PTRINDEX(cgltf_buffer, cgltf_json_to_int(tokens + i, json_chunk));
5012 ++i;
5013 }
5014 else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteOffset") == 0)
5015 {
5016 ++i;
5017 out_buffer_view->offset =
5018 cgltf_json_to_size(tokens+i, json_chunk);
5019 ++i;
5020 }
5021 else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteLength") == 0)
5022 {
5023 ++i;
5024 out_buffer_view->size =
5025 cgltf_json_to_size(tokens+i, json_chunk);
5026 ++i;
5027 }
5028 else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteStride") == 0)
5029 {
5030 ++i;
5031 out_buffer_view->stride =
5032 cgltf_json_to_size(tokens+i, json_chunk);
5033 ++i;
5034 }
5035 else if (cgltf_json_strcmp(tokens+i, json_chunk, "target") == 0)
5036 {
5037 ++i;
5038 int type = cgltf_json_to_int(tokens+i, json_chunk);
5039 switch (type)
5040 {
5041 case 34962:
5042 type = cgltf_buffer_view_type_vertices;
5043 break;
5044 case 34963:
5045 type = cgltf_buffer_view_type_indices;
5046 break;
5047 default:
5048 type = cgltf_buffer_view_type_invalid;
5049 break;
5050 }
5051 out_buffer_view->type = (cgltf_buffer_view_type)type;
5052 ++i;
5053 }
5054 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
5055 {
5056 i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_buffer_view->extras);
5057 }
5058 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
5059 {
5060 ++i;
5061
5062 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
5063 if(out_buffer_view->extensions)
5064 {
5065 return CGLTF_ERROR_JSON;
5066 }
5067
5068 int extensions_size = tokens[i].size;
5069 out_buffer_view->extensions_count = 0;
5070 out_buffer_view->extensions = (cgltf_extension*)cgltf_calloc(options, sizeof(cgltf_extension), extensions_size);
5071
5072 if (!out_buffer_view->extensions)
5073 {
5074 return CGLTF_ERROR_NOMEM;
5075 }
5076
5077 ++i;
5078 for (int k = 0; k < extensions_size; ++k)
5079 {
5080 CGLTF_CHECK_KEY(tokens[i]);
5081
5082 if (cgltf_json_strcmp(tokens+i, json_chunk, "EXT_meshopt_compression") == 0)
5083 {
5084 out_buffer_view->has_meshopt_compression = 1;
5085 i = cgltf_parse_json_meshopt_compression(options, tokens, i + 1, json_chunk, &out_buffer_view->meshopt_compression);
5086 }
5087 else
5088 {
5089 i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, &(out_buffer_view->extensions[out_buffer_view->extensions_count++]));
5090 }
5091
5092 if (i < 0)
5093 {
5094 return i;
5095 }
5096 }
5097 }
5098 else
5099 {
5100 i = cgltf_skip_json(tokens, i+1);
5101 }
5102
5103 if (i < 0)
5104 {
5105 return i;
5106 }
5107 }
5108
5109 return i;
5110}
5111
5112static int cgltf_parse_json_buffer_views(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data)
5113{
5114 i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_buffer_view), (void**)&out_data->buffer_views, &out_data->buffer_views_count);
5115 if (i < 0)
5116 {
5117 return i;
5118 }
5119
5120 for (cgltf_size j = 0; j < out_data->buffer_views_count; ++j)
5121 {
5122 i = cgltf_parse_json_buffer_view(options, tokens, i, json_chunk, &out_data->buffer_views[j]);
5123 if (i < 0)
5124 {
5125 return i;
5126 }
5127 }
5128 return i;
5129}
5130
5131static int cgltf_parse_json_buffer(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_buffer* out_buffer)
5132{
5133 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
5134
5135 int size = tokens[i].size;
5136 ++i;
5137
5138 for (int j = 0; j < size; ++j)
5139 {
5140 CGLTF_CHECK_KEY(tokens[i]);
5141
5142 if (cgltf_json_strcmp(tokens + i, json_chunk, "name") == 0)
5143 {
5144 i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_buffer->name);
5145 }
5146 else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteLength") == 0)
5147 {
5148 ++i;
5149 out_buffer->size =
5150 cgltf_json_to_size(tokens+i, json_chunk);
5151 ++i;
5152 }
5153 else if (cgltf_json_strcmp(tokens+i, json_chunk, "uri") == 0)
5154 {
5155 i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_buffer->uri);
5156 }
5157 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
5158 {
5159 i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_buffer->extras);
5160 }
5161 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
5162 {
5163 i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_buffer->extensions_count, &out_buffer->extensions);
5164 }
5165 else
5166 {
5167 i = cgltf_skip_json(tokens, i+1);
5168 }
5169
5170 if (i < 0)
5171 {
5172 return i;
5173 }
5174 }
5175
5176 return i;
5177}
5178
5179static int cgltf_parse_json_buffers(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data)
5180{
5181 i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_buffer), (void**)&out_data->buffers, &out_data->buffers_count);
5182 if (i < 0)
5183 {
5184 return i;
5185 }
5186
5187 for (cgltf_size j = 0; j < out_data->buffers_count; ++j)
5188 {
5189 i = cgltf_parse_json_buffer(options, tokens, i, json_chunk, &out_data->buffers[j]);
5190 if (i < 0)
5191 {
5192 return i;
5193 }
5194 }
5195 return i;
5196}
5197
5198static int cgltf_parse_json_skin(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_skin* out_skin)
5199{
5200 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
5201
5202 int size = tokens[i].size;
5203 ++i;
5204
5205 for (int j = 0; j < size; ++j)
5206 {
5207 CGLTF_CHECK_KEY(tokens[i]);
5208
5209 if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0)
5210 {
5211 i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_skin->name);
5212 }
5213 else if (cgltf_json_strcmp(tokens+i, json_chunk, "joints") == 0)
5214 {
5215 i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_node*), (void**)&out_skin->joints, &out_skin->joints_count);
5216 if (i < 0)
5217 {
5218 return i;
5219 }
5220
5221 for (cgltf_size k = 0; k < out_skin->joints_count; ++k)
5222 {
5223 out_skin->joints[k] = CGLTF_PTRINDEX(cgltf_node, cgltf_json_to_int(tokens + i, json_chunk));
5224 ++i;
5225 }
5226 }
5227 else if (cgltf_json_strcmp(tokens+i, json_chunk, "skeleton") == 0)
5228 {
5229 ++i;
5230 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_PRIMITIVE);
5231 out_skin->skeleton = CGLTF_PTRINDEX(cgltf_node, cgltf_json_to_int(tokens + i, json_chunk));
5232 ++i;
5233 }
5234 else if (cgltf_json_strcmp(tokens+i, json_chunk, "inverseBindMatrices") == 0)
5235 {
5236 ++i;
5237 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_PRIMITIVE);
5238 out_skin->inverse_bind_matrices = CGLTF_PTRINDEX(cgltf_accessor, cgltf_json_to_int(tokens + i, json_chunk));
5239 ++i;
5240 }
5241 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
5242 {
5243 i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_skin->extras);
5244 }
5245 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
5246 {
5247 i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_skin->extensions_count, &out_skin->extensions);
5248 }
5249 else
5250 {
5251 i = cgltf_skip_json(tokens, i+1);
5252 }
5253
5254 if (i < 0)
5255 {
5256 return i;
5257 }
5258 }
5259
5260 return i;
5261}
5262
5263static int cgltf_parse_json_skins(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data)
5264{
5265 i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_skin), (void**)&out_data->skins, &out_data->skins_count);
5266 if (i < 0)
5267 {
5268 return i;
5269 }
5270
5271 for (cgltf_size j = 0; j < out_data->skins_count; ++j)
5272 {
5273 i = cgltf_parse_json_skin(options, tokens, i, json_chunk, &out_data->skins[j]);
5274 if (i < 0)
5275 {
5276 return i;
5277 }
5278 }
5279 return i;
5280}
5281
5282static int cgltf_parse_json_camera(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_camera* out_camera)
5283{
5284 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
5285
5286 int size = tokens[i].size;
5287 ++i;
5288
5289 for (int j = 0; j < size; ++j)
5290 {
5291 CGLTF_CHECK_KEY(tokens[i]);
5292
5293 if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0)
5294 {
5295 i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_camera->name);
5296 }
5297 else if (cgltf_json_strcmp(tokens+i, json_chunk, "perspective") == 0)
5298 {
5299 ++i;
5300
5301 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
5302
5303 int data_size = tokens[i].size;
5304 ++i;
5305
5306 if (out_camera->type != cgltf_camera_type_invalid)
5307 {
5308 return CGLTF_ERROR_JSON;
5309 }
5310
5311 out_camera->type = cgltf_camera_type_perspective;
5312
5313 for (int k = 0; k < data_size; ++k)
5314 {
5315 CGLTF_CHECK_KEY(tokens[i]);
5316
5317 if (cgltf_json_strcmp(tokens+i, json_chunk, "aspectRatio") == 0)
5318 {
5319 ++i;
5320 out_camera->data.perspective.has_aspect_ratio = 1;
5321 out_camera->data.perspective.aspect_ratio = cgltf_json_to_float(tokens + i, json_chunk);
5322 ++i;
5323 }
5324 else if (cgltf_json_strcmp(tokens+i, json_chunk, "yfov") == 0)
5325 {
5326 ++i;
5327 out_camera->data.perspective.yfov = cgltf_json_to_float(tokens + i, json_chunk);
5328 ++i;
5329 }
5330 else if (cgltf_json_strcmp(tokens+i, json_chunk, "zfar") == 0)
5331 {
5332 ++i;
5333 out_camera->data.perspective.has_zfar = 1;
5334 out_camera->data.perspective.zfar = cgltf_json_to_float(tokens + i, json_chunk);
5335 ++i;
5336 }
5337 else if (cgltf_json_strcmp(tokens+i, json_chunk, "znear") == 0)
5338 {
5339 ++i;
5340 out_camera->data.perspective.znear = cgltf_json_to_float(tokens + i, json_chunk);
5341 ++i;
5342 }
5343 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
5344 {
5345 i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_camera->data.perspective.extras);
5346 }
5347 else
5348 {
5349 i = cgltf_skip_json(tokens, i+1);
5350 }
5351
5352 if (i < 0)
5353 {
5354 return i;
5355 }
5356 }
5357 }
5358 else if (cgltf_json_strcmp(tokens+i, json_chunk, "orthographic") == 0)
5359 {
5360 ++i;
5361
5362 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
5363
5364 int data_size = tokens[i].size;
5365 ++i;
5366
5367 if (out_camera->type != cgltf_camera_type_invalid)
5368 {
5369 return CGLTF_ERROR_JSON;
5370 }
5371
5372 out_camera->type = cgltf_camera_type_orthographic;
5373
5374 for (int k = 0; k < data_size; ++k)
5375 {
5376 CGLTF_CHECK_KEY(tokens[i]);
5377
5378 if (cgltf_json_strcmp(tokens+i, json_chunk, "xmag") == 0)
5379 {
5380 ++i;
5381 out_camera->data.orthographic.xmag = cgltf_json_to_float(tokens + i, json_chunk);
5382 ++i;
5383 }
5384 else if (cgltf_json_strcmp(tokens+i, json_chunk, "ymag") == 0)
5385 {
5386 ++i;
5387 out_camera->data.orthographic.ymag = cgltf_json_to_float(tokens + i, json_chunk);
5388 ++i;
5389 }
5390 else if (cgltf_json_strcmp(tokens+i, json_chunk, "zfar") == 0)
5391 {
5392 ++i;
5393 out_camera->data.orthographic.zfar = cgltf_json_to_float(tokens + i, json_chunk);
5394 ++i;
5395 }
5396 else if (cgltf_json_strcmp(tokens+i, json_chunk, "znear") == 0)
5397 {
5398 ++i;
5399 out_camera->data.orthographic.znear = cgltf_json_to_float(tokens + i, json_chunk);
5400 ++i;
5401 }
5402 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
5403 {
5404 i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_camera->data.orthographic.extras);
5405 }
5406 else
5407 {
5408 i = cgltf_skip_json(tokens, i+1);
5409 }
5410
5411 if (i < 0)
5412 {
5413 return i;
5414 }
5415 }
5416 }
5417 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
5418 {
5419 i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_camera->extras);
5420 }
5421 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
5422 {
5423 i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_camera->extensions_count, &out_camera->extensions);
5424 }
5425 else
5426 {
5427 i = cgltf_skip_json(tokens, i+1);
5428 }
5429
5430 if (i < 0)
5431 {
5432 return i;
5433 }
5434 }
5435
5436 return i;
5437}
5438
5439static int cgltf_parse_json_cameras(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data)
5440{
5441 i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_camera), (void**)&out_data->cameras, &out_data->cameras_count);
5442 if (i < 0)
5443 {
5444 return i;
5445 }
5446
5447 for (cgltf_size j = 0; j < out_data->cameras_count; ++j)
5448 {
5449 i = cgltf_parse_json_camera(options, tokens, i, json_chunk, &out_data->cameras[j]);
5450 if (i < 0)
5451 {
5452 return i;
5453 }
5454 }
5455 return i;
5456}
5457
5458static int cgltf_parse_json_light(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_light* out_light)
5459{
5460 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
5461
5462 out_light->color[0] = 1.f;
5463 out_light->color[1] = 1.f;
5464 out_light->color[2] = 1.f;
5465 out_light->intensity = 1.f;
5466
5467 out_light->spot_inner_cone_angle = 0.f;
5468 out_light->spot_outer_cone_angle = 3.1415926535f / 4.0f;
5469
5470 int size = tokens[i].size;
5471 ++i;
5472
5473 for (int j = 0; j < size; ++j)
5474 {
5475 CGLTF_CHECK_KEY(tokens[i]);
5476
5477 if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0)
5478 {
5479 i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_light->name);
5480 }
5481 else if (cgltf_json_strcmp(tokens + i, json_chunk, "color") == 0)
5482 {
5483 i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_light->color, 3);
5484 }
5485 else if (cgltf_json_strcmp(tokens + i, json_chunk, "intensity") == 0)
5486 {
5487 ++i;
5488 out_light->intensity = cgltf_json_to_float(tokens + i, json_chunk);
5489 ++i;
5490 }
5491 else if (cgltf_json_strcmp(tokens+i, json_chunk, "type") == 0)
5492 {
5493 ++i;
5494 if (cgltf_json_strcmp(tokens + i, json_chunk, "directional") == 0)
5495 {
5496 out_light->type = cgltf_light_type_directional;
5497 }
5498 else if (cgltf_json_strcmp(tokens + i, json_chunk, "point") == 0)
5499 {
5500 out_light->type = cgltf_light_type_point;
5501 }
5502 else if (cgltf_json_strcmp(tokens + i, json_chunk, "spot") == 0)
5503 {
5504 out_light->type = cgltf_light_type_spot;
5505 }
5506 ++i;
5507 }
5508 else if (cgltf_json_strcmp(tokens + i, json_chunk, "range") == 0)
5509 {
5510 ++i;
5511 out_light->range = cgltf_json_to_float(tokens + i, json_chunk);
5512 ++i;
5513 }
5514 else if (cgltf_json_strcmp(tokens+i, json_chunk, "spot") == 0)
5515 {
5516 ++i;
5517
5518 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
5519
5520 int data_size = tokens[i].size;
5521 ++i;
5522
5523 for (int k = 0; k < data_size; ++k)
5524 {
5525 CGLTF_CHECK_KEY(tokens[i]);
5526
5527 if (cgltf_json_strcmp(tokens+i, json_chunk, "innerConeAngle") == 0)
5528 {
5529 ++i;
5530 out_light->spot_inner_cone_angle = cgltf_json_to_float(tokens + i, json_chunk);
5531 ++i;
5532 }
5533 else if (cgltf_json_strcmp(tokens+i, json_chunk, "outerConeAngle") == 0)
5534 {
5535 ++i;
5536 out_light->spot_outer_cone_angle = cgltf_json_to_float(tokens + i, json_chunk);
5537 ++i;
5538 }
5539 else
5540 {
5541 i = cgltf_skip_json(tokens, i+1);
5542 }
5543
5544 if (i < 0)
5545 {
5546 return i;
5547 }
5548 }
5549 }
5550 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
5551 {
5552 i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_light->extras);
5553 }
5554 else
5555 {
5556 i = cgltf_skip_json(tokens, i+1);
5557 }
5558
5559 if (i < 0)
5560 {
5561 return i;
5562 }
5563 }
5564
5565 return i;
5566}
5567
5568static int cgltf_parse_json_lights(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data)
5569{
5570 i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_light), (void**)&out_data->lights, &out_data->lights_count);
5571 if (i < 0)
5572 {
5573 return i;
5574 }
5575
5576 for (cgltf_size j = 0; j < out_data->lights_count; ++j)
5577 {
5578 i = cgltf_parse_json_light(options, tokens, i, json_chunk, &out_data->lights[j]);
5579 if (i < 0)
5580 {
5581 return i;
5582 }
5583 }
5584 return i;
5585}
5586
5587static int cgltf_parse_json_node(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_node* out_node)
5588{
5589 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
5590
5591 out_node->rotation[3] = 1.0f;
5592 out_node->scale[0] = 1.0f;
5593 out_node->scale[1] = 1.0f;
5594 out_node->scale[2] = 1.0f;
5595 out_node->matrix[0] = 1.0f;
5596 out_node->matrix[5] = 1.0f;
5597 out_node->matrix[10] = 1.0f;
5598 out_node->matrix[15] = 1.0f;
5599
5600 int size = tokens[i].size;
5601 ++i;
5602
5603 for (int j = 0; j < size; ++j)
5604 {
5605 CGLTF_CHECK_KEY(tokens[i]);
5606
5607 if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0)
5608 {
5609 i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_node->name);
5610 }
5611 else if (cgltf_json_strcmp(tokens+i, json_chunk, "children") == 0)
5612 {
5613 i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_node*), (void**)&out_node->children, &out_node->children_count);
5614 if (i < 0)
5615 {
5616 return i;
5617 }
5618
5619 for (cgltf_size k = 0; k < out_node->children_count; ++k)
5620 {
5621 out_node->children[k] = CGLTF_PTRINDEX(cgltf_node, cgltf_json_to_int(tokens + i, json_chunk));
5622 ++i;
5623 }
5624 }
5625 else if (cgltf_json_strcmp(tokens+i, json_chunk, "mesh") == 0)
5626 {
5627 ++i;
5628 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_PRIMITIVE);
5629 out_node->mesh = CGLTF_PTRINDEX(cgltf_mesh, cgltf_json_to_int(tokens + i, json_chunk));
5630 ++i;
5631 }
5632 else if (cgltf_json_strcmp(tokens+i, json_chunk, "skin") == 0)
5633 {
5634 ++i;
5635 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_PRIMITIVE);
5636 out_node->skin = CGLTF_PTRINDEX(cgltf_skin, cgltf_json_to_int(tokens + i, json_chunk));
5637 ++i;
5638 }
5639 else if (cgltf_json_strcmp(tokens+i, json_chunk, "camera") == 0)
5640 {
5641 ++i;
5642 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_PRIMITIVE);
5643 out_node->camera = CGLTF_PTRINDEX(cgltf_camera, cgltf_json_to_int(tokens + i, json_chunk));
5644 ++i;
5645 }
5646 else if (cgltf_json_strcmp(tokens+i, json_chunk, "translation") == 0)
5647 {
5648 out_node->has_translation = 1;
5649 i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_node->translation, 3);
5650 }
5651 else if (cgltf_json_strcmp(tokens+i, json_chunk, "rotation") == 0)
5652 {
5653 out_node->has_rotation = 1;
5654 i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_node->rotation, 4);
5655 }
5656 else if (cgltf_json_strcmp(tokens+i, json_chunk, "scale") == 0)
5657 {
5658 out_node->has_scale = 1;
5659 i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_node->scale, 3);
5660 }
5661 else if (cgltf_json_strcmp(tokens+i, json_chunk, "matrix") == 0)
5662 {
5663 out_node->has_matrix = 1;
5664 i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_node->matrix, 16);
5665 }
5666 else if (cgltf_json_strcmp(tokens + i, json_chunk, "weights") == 0)
5667 {
5668 i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_float), (void**)&out_node->weights, &out_node->weights_count);
5669 if (i < 0)
5670 {
5671 return i;
5672 }
5673
5674 i = cgltf_parse_json_float_array(tokens, i - 1, json_chunk, out_node->weights, (int)out_node->weights_count);
5675 }
5676 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
5677 {
5678 i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_node->extras);
5679 }
5680 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
5681 {
5682 ++i;
5683
5684 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
5685 if(out_node->extensions)
5686 {
5687 return CGLTF_ERROR_JSON;
5688 }
5689
5690 int extensions_size = tokens[i].size;
5691 out_node->extensions_count= 0;
5692 out_node->extensions = (cgltf_extension*)cgltf_calloc(options, sizeof(cgltf_extension), extensions_size);
5693
5694 if (!out_node->extensions)
5695 {
5696 return CGLTF_ERROR_NOMEM;
5697 }
5698
5699 ++i;
5700
5701 for (int k = 0; k < extensions_size; ++k)
5702 {
5703 CGLTF_CHECK_KEY(tokens[i]);
5704
5705 if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_lights_punctual") == 0)
5706 {
5707 ++i;
5708
5709 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
5710
5711 int data_size = tokens[i].size;
5712 ++i;
5713
5714 for (int m = 0; m < data_size; ++m)
5715 {
5716 CGLTF_CHECK_KEY(tokens[i]);
5717
5718 if (cgltf_json_strcmp(tokens + i, json_chunk, "light") == 0)
5719 {
5720 ++i;
5721 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_PRIMITIVE);
5722 out_node->light = CGLTF_PTRINDEX(cgltf_light, cgltf_json_to_int(tokens + i, json_chunk));
5723 ++i;
5724 }
5725 else
5726 {
5727 i = cgltf_skip_json(tokens, i + 1);
5728 }
5729
5730 if (i < 0)
5731 {
5732 return i;
5733 }
5734 }
5735 }
5736 else if (cgltf_json_strcmp(tokens + i, json_chunk, "EXT_mesh_gpu_instancing") == 0)
5737 {
5738 out_node->has_mesh_gpu_instancing = 1;
5739 i = cgltf_parse_json_mesh_gpu_instancing(options, tokens, i + 1, json_chunk, &out_node->mesh_gpu_instancing);
5740 }
5741 else
5742 {
5743 i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, &(out_node->extensions[out_node->extensions_count++]));
5744 }
5745
5746 if (i < 0)
5747 {
5748 return i;
5749 }
5750 }
5751 }
5752 else
5753 {
5754 i = cgltf_skip_json(tokens, i+1);
5755 }
5756
5757 if (i < 0)
5758 {
5759 return i;
5760 }
5761 }
5762
5763 return i;
5764}
5765
5766static int cgltf_parse_json_nodes(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data)
5767{
5768 i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_node), (void**)&out_data->nodes, &out_data->nodes_count);
5769 if (i < 0)
5770 {
5771 return i;
5772 }
5773
5774 for (cgltf_size j = 0; j < out_data->nodes_count; ++j)
5775 {
5776 i = cgltf_parse_json_node(options, tokens, i, json_chunk, &out_data->nodes[j]);
5777 if (i < 0)
5778 {
5779 return i;
5780 }
5781 }
5782 return i;
5783}
5784
5785static int cgltf_parse_json_scene(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_scene* out_scene)
5786{
5787 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
5788
5789 int size = tokens[i].size;
5790 ++i;
5791
5792 for (int j = 0; j < size; ++j)
5793 {
5794 CGLTF_CHECK_KEY(tokens[i]);
5795
5796 if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0)
5797 {
5798 i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_scene->name);
5799 }
5800 else if (cgltf_json_strcmp(tokens+i, json_chunk, "nodes") == 0)
5801 {
5802 i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_node*), (void**)&out_scene->nodes, &out_scene->nodes_count);
5803 if (i < 0)
5804 {
5805 return i;
5806 }
5807
5808 for (cgltf_size k = 0; k < out_scene->nodes_count; ++k)
5809 {
5810 out_scene->nodes[k] = CGLTF_PTRINDEX(cgltf_node, cgltf_json_to_int(tokens + i, json_chunk));
5811 ++i;
5812 }
5813 }
5814 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
5815 {
5816 i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_scene->extras);
5817 }
5818 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
5819 {
5820 i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_scene->extensions_count, &out_scene->extensions);
5821 }
5822 else
5823 {
5824 i = cgltf_skip_json(tokens, i+1);
5825 }
5826
5827 if (i < 0)
5828 {
5829 return i;
5830 }
5831 }
5832
5833 return i;
5834}
5835
5836static int cgltf_parse_json_scenes(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data)
5837{
5838 i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_scene), (void**)&out_data->scenes, &out_data->scenes_count);
5839 if (i < 0)
5840 {
5841 return i;
5842 }
5843
5844 for (cgltf_size j = 0; j < out_data->scenes_count; ++j)
5845 {
5846 i = cgltf_parse_json_scene(options, tokens, i, json_chunk, &out_data->scenes[j]);
5847 if (i < 0)
5848 {
5849 return i;
5850 }
5851 }
5852 return i;
5853}
5854
5855static int cgltf_parse_json_animation_sampler(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_animation_sampler* out_sampler)
5856{
5857 (void)options;
5858 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
5859
5860 int size = tokens[i].size;
5861 ++i;
5862
5863 for (int j = 0; j < size; ++j)
5864 {
5865 CGLTF_CHECK_KEY(tokens[i]);
5866
5867 if (cgltf_json_strcmp(tokens+i, json_chunk, "input") == 0)
5868 {
5869 ++i;
5870 out_sampler->input = CGLTF_PTRINDEX(cgltf_accessor, cgltf_json_to_int(tokens + i, json_chunk));
5871 ++i;
5872 }
5873 else if (cgltf_json_strcmp(tokens+i, json_chunk, "output") == 0)
5874 {
5875 ++i;
5876 out_sampler->output = CGLTF_PTRINDEX(cgltf_accessor, cgltf_json_to_int(tokens + i, json_chunk));
5877 ++i;
5878 }
5879 else if (cgltf_json_strcmp(tokens+i, json_chunk, "interpolation") == 0)
5880 {
5881 ++i;
5882 if (cgltf_json_strcmp(tokens + i, json_chunk, "LINEAR") == 0)
5883 {
5884 out_sampler->interpolation = cgltf_interpolation_type_linear;
5885 }
5886 else if (cgltf_json_strcmp(tokens + i, json_chunk, "STEP") == 0)
5887 {
5888 out_sampler->interpolation = cgltf_interpolation_type_step;
5889 }
5890 else if (cgltf_json_strcmp(tokens + i, json_chunk, "CUBICSPLINE") == 0)
5891 {
5892 out_sampler->interpolation = cgltf_interpolation_type_cubic_spline;
5893 }
5894 ++i;
5895 }
5896 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
5897 {
5898 i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_sampler->extras);
5899 }
5900 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
5901 {
5902 i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_sampler->extensions_count, &out_sampler->extensions);
5903 }
5904 else
5905 {
5906 i = cgltf_skip_json(tokens, i+1);
5907 }
5908
5909 if (i < 0)
5910 {
5911 return i;
5912 }
5913 }
5914
5915 return i;
5916}
5917
5918static int cgltf_parse_json_animation_channel(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_animation_channel* out_channel)
5919{
5920 (void)options;
5921 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
5922
5923 int size = tokens[i].size;
5924 ++i;
5925
5926 for (int j = 0; j < size; ++j)
5927 {
5928 CGLTF_CHECK_KEY(tokens[i]);
5929
5930 if (cgltf_json_strcmp(tokens+i, json_chunk, "sampler") == 0)
5931 {
5932 ++i;
5933 out_channel->sampler = CGLTF_PTRINDEX(cgltf_animation_sampler, cgltf_json_to_int(tokens + i, json_chunk));
5934 ++i;
5935 }
5936 else if (cgltf_json_strcmp(tokens+i, json_chunk, "target") == 0)
5937 {
5938 ++i;
5939
5940 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
5941
5942 int target_size = tokens[i].size;
5943 ++i;
5944
5945 for (int k = 0; k < target_size; ++k)
5946 {
5947 CGLTF_CHECK_KEY(tokens[i]);
5948
5949 if (cgltf_json_strcmp(tokens+i, json_chunk, "node") == 0)
5950 {
5951 ++i;
5952 out_channel->target_node = CGLTF_PTRINDEX(cgltf_node, cgltf_json_to_int(tokens + i, json_chunk));
5953 ++i;
5954 }
5955 else if (cgltf_json_strcmp(tokens+i, json_chunk, "path") == 0)
5956 {
5957 ++i;
5958 if (cgltf_json_strcmp(tokens+i, json_chunk, "translation") == 0)
5959 {
5960 out_channel->target_path = cgltf_animation_path_type_translation;
5961 }
5962 else if (cgltf_json_strcmp(tokens+i, json_chunk, "rotation") == 0)
5963 {
5964 out_channel->target_path = cgltf_animation_path_type_rotation;
5965 }
5966 else if (cgltf_json_strcmp(tokens+i, json_chunk, "scale") == 0)
5967 {
5968 out_channel->target_path = cgltf_animation_path_type_scale;
5969 }
5970 else if (cgltf_json_strcmp(tokens+i, json_chunk, "weights") == 0)
5971 {
5972 out_channel->target_path = cgltf_animation_path_type_weights;
5973 }
5974 ++i;
5975 }
5976 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
5977 {
5978 i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_channel->extras);
5979 }
5980 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
5981 {
5982 i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_channel->extensions_count, &out_channel->extensions);
5983 }
5984 else
5985 {
5986 i = cgltf_skip_json(tokens, i+1);
5987 }
5988
5989 if (i < 0)
5990 {
5991 return i;
5992 }
5993 }
5994 }
5995 else
5996 {
5997 i = cgltf_skip_json(tokens, i+1);
5998 }
5999
6000 if (i < 0)
6001 {
6002 return i;
6003 }
6004 }
6005
6006 return i;
6007}
6008
6009static int cgltf_parse_json_animation(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_animation* out_animation)
6010{
6011 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
6012
6013 int size = tokens[i].size;
6014 ++i;
6015
6016 for (int j = 0; j < size; ++j)
6017 {
6018 CGLTF_CHECK_KEY(tokens[i]);
6019
6020 if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0)
6021 {
6022 i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_animation->name);
6023 }
6024 else if (cgltf_json_strcmp(tokens+i, json_chunk, "samplers") == 0)
6025 {
6026 i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_animation_sampler), (void**)&out_animation->samplers, &out_animation->samplers_count);
6027 if (i < 0)
6028 {
6029 return i;
6030 }
6031
6032 for (cgltf_size k = 0; k < out_animation->samplers_count; ++k)
6033 {
6034 i = cgltf_parse_json_animation_sampler(options, tokens, i, json_chunk, &out_animation->samplers[k]);
6035 if (i < 0)
6036 {
6037 return i;
6038 }
6039 }
6040 }
6041 else if (cgltf_json_strcmp(tokens+i, json_chunk, "channels") == 0)
6042 {
6043 i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_animation_channel), (void**)&out_animation->channels, &out_animation->channels_count);
6044 if (i < 0)
6045 {
6046 return i;
6047 }
6048
6049 for (cgltf_size k = 0; k < out_animation->channels_count; ++k)
6050 {
6051 i = cgltf_parse_json_animation_channel(options, tokens, i, json_chunk, &out_animation->channels[k]);
6052 if (i < 0)
6053 {
6054 return i;
6055 }
6056 }
6057 }
6058 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
6059 {
6060 i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_animation->extras);
6061 }
6062 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
6063 {
6064 i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_animation->extensions_count, &out_animation->extensions);
6065 }
6066 else
6067 {
6068 i = cgltf_skip_json(tokens, i+1);
6069 }
6070
6071 if (i < 0)
6072 {
6073 return i;
6074 }
6075 }
6076
6077 return i;
6078}
6079
6080static int cgltf_parse_json_animations(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data)
6081{
6082 i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_animation), (void**)&out_data->animations, &out_data->animations_count);
6083 if (i < 0)
6084 {
6085 return i;
6086 }
6087
6088 for (cgltf_size j = 0; j < out_data->animations_count; ++j)
6089 {
6090 i = cgltf_parse_json_animation(options, tokens, i, json_chunk, &out_data->animations[j]);
6091 if (i < 0)
6092 {
6093 return i;
6094 }
6095 }
6096 return i;
6097}
6098
6099static int cgltf_parse_json_variant(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_material_variant* out_variant)
6100{
6101 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
6102
6103 int size = tokens[i].size;
6104 ++i;
6105
6106 for (int j = 0; j < size; ++j)
6107 {
6108 CGLTF_CHECK_KEY(tokens[i]);
6109
6110 if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0)
6111 {
6112 i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_variant->name);
6113 }
6114 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
6115 {
6116 i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_variant->extras);
6117 }
6118 else
6119 {
6120 i = cgltf_skip_json(tokens, i+1);
6121 }
6122
6123 if (i < 0)
6124 {
6125 return i;
6126 }
6127 }
6128
6129 return i;
6130}
6131
6132static int cgltf_parse_json_variants(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data)
6133{
6134 i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_material_variant), (void**)&out_data->variants, &out_data->variants_count);
6135 if (i < 0)
6136 {
6137 return i;
6138 }
6139
6140 for (cgltf_size j = 0; j < out_data->variants_count; ++j)
6141 {
6142 i = cgltf_parse_json_variant(options, tokens, i, json_chunk, &out_data->variants[j]);
6143 if (i < 0)
6144 {
6145 return i;
6146 }
6147 }
6148 return i;
6149}
6150
6151static int cgltf_parse_json_asset(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_asset* out_asset)
6152{
6153 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
6154
6155 int size = tokens[i].size;
6156 ++i;
6157
6158 for (int j = 0; j < size; ++j)
6159 {
6160 CGLTF_CHECK_KEY(tokens[i]);
6161
6162 if (cgltf_json_strcmp(tokens+i, json_chunk, "copyright") == 0)
6163 {
6164 i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_asset->copyright);
6165 }
6166 else if (cgltf_json_strcmp(tokens+i, json_chunk, "generator") == 0)
6167 {
6168 i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_asset->generator);
6169 }
6170 else if (cgltf_json_strcmp(tokens+i, json_chunk, "version") == 0)
6171 {
6172 i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_asset->version);
6173 }
6174 else if (cgltf_json_strcmp(tokens+i, json_chunk, "minVersion") == 0)
6175 {
6176 i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_asset->min_version);
6177 }
6178 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
6179 {
6180 i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_asset->extras);
6181 }
6182 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
6183 {
6184 i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_asset->extensions_count, &out_asset->extensions);
6185 }
6186 else
6187 {
6188 i = cgltf_skip_json(tokens, i+1);
6189 }
6190
6191 if (i < 0)
6192 {
6193 return i;
6194 }
6195 }
6196
6197 if (out_asset->version && CGLTF_ATOF(out_asset->version) < 2)
6198 {
6199 return CGLTF_ERROR_LEGACY;
6200 }
6201
6202 return i;
6203}
6204
6205cgltf_size cgltf_num_components(cgltf_type type) {
6206 switch (type)
6207 {
6208 case cgltf_type_vec2:
6209 return 2;
6210 case cgltf_type_vec3:
6211 return 3;
6212 case cgltf_type_vec4:
6213 return 4;
6214 case cgltf_type_mat2:
6215 return 4;
6216 case cgltf_type_mat3:
6217 return 9;
6218 case cgltf_type_mat4:
6219 return 16;
6220 case cgltf_type_invalid:
6221 case cgltf_type_scalar:
6222 default:
6223 return 1;
6224 }
6225}
6226
6227cgltf_size cgltf_component_size(cgltf_component_type component_type) {
6228 switch (component_type)
6229 {
6230 case cgltf_component_type_r_8:
6231 case cgltf_component_type_r_8u:
6232 return 1;
6233 case cgltf_component_type_r_16:
6234 case cgltf_component_type_r_16u:
6235 return 2;
6236 case cgltf_component_type_r_32u:
6237 case cgltf_component_type_r_32f:
6238 return 4;
6239 case cgltf_component_type_invalid:
6240 default:
6241 return 0;
6242 }
6243}
6244
6245cgltf_size cgltf_calc_size(cgltf_type type, cgltf_component_type component_type)
6246{
6247 cgltf_size component_size = cgltf_component_size(component_type);
6248 if (type == cgltf_type_mat2 && component_size == 1)
6249 {
6250 return 8 * component_size;
6251 }
6252 else if (type == cgltf_type_mat3 && (component_size == 1 || component_size == 2))
6253 {
6254 return 12 * component_size;
6255 }
6256 return component_size * cgltf_num_components(type);
6257}
6258
6259static int cgltf_fixup_pointers(cgltf_data* out_data);
6260
6261static int cgltf_parse_json_root(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data)
6262{
6263 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
6264
6265 int size = tokens[i].size;
6266 ++i;
6267
6268 for (int j = 0; j < size; ++j)
6269 {
6270 CGLTF_CHECK_KEY(tokens[i]);
6271
6272 if (cgltf_json_strcmp(tokens + i, json_chunk, "asset") == 0)
6273 {
6274 i = cgltf_parse_json_asset(options, tokens, i + 1, json_chunk, &out_data->asset);
6275 }
6276 else if (cgltf_json_strcmp(tokens + i, json_chunk, "meshes") == 0)
6277 {
6278 i = cgltf_parse_json_meshes(options, tokens, i + 1, json_chunk, out_data);
6279 }
6280 else if (cgltf_json_strcmp(tokens + i, json_chunk, "accessors") == 0)
6281 {
6282 i = cgltf_parse_json_accessors(options, tokens, i + 1, json_chunk, out_data);
6283 }
6284 else if (cgltf_json_strcmp(tokens + i, json_chunk, "bufferViews") == 0)
6285 {
6286 i = cgltf_parse_json_buffer_views(options, tokens, i + 1, json_chunk, out_data);
6287 }
6288 else if (cgltf_json_strcmp(tokens + i, json_chunk, "buffers") == 0)
6289 {
6290 i = cgltf_parse_json_buffers(options, tokens, i + 1, json_chunk, out_data);
6291 }
6292 else if (cgltf_json_strcmp(tokens + i, json_chunk, "materials") == 0)
6293 {
6294 i = cgltf_parse_json_materials(options, tokens, i + 1, json_chunk, out_data);
6295 }
6296 else if (cgltf_json_strcmp(tokens + i, json_chunk, "images") == 0)
6297 {
6298 i = cgltf_parse_json_images(options, tokens, i + 1, json_chunk, out_data);
6299 }
6300 else if (cgltf_json_strcmp(tokens + i, json_chunk, "textures") == 0)
6301 {
6302 i = cgltf_parse_json_textures(options, tokens, i + 1, json_chunk, out_data);
6303 }
6304 else if (cgltf_json_strcmp(tokens + i, json_chunk, "samplers") == 0)
6305 {
6306 i = cgltf_parse_json_samplers(options, tokens, i + 1, json_chunk, out_data);
6307 }
6308 else if (cgltf_json_strcmp(tokens + i, json_chunk, "skins") == 0)
6309 {
6310 i = cgltf_parse_json_skins(options, tokens, i + 1, json_chunk, out_data);
6311 }
6312 else if (cgltf_json_strcmp(tokens + i, json_chunk, "cameras") == 0)
6313 {
6314 i = cgltf_parse_json_cameras(options, tokens, i + 1, json_chunk, out_data);
6315 }
6316 else if (cgltf_json_strcmp(tokens + i, json_chunk, "nodes") == 0)
6317 {
6318 i = cgltf_parse_json_nodes(options, tokens, i + 1, json_chunk, out_data);
6319 }
6320 else if (cgltf_json_strcmp(tokens + i, json_chunk, "scenes") == 0)
6321 {
6322 i = cgltf_parse_json_scenes(options, tokens, i + 1, json_chunk, out_data);
6323 }
6324 else if (cgltf_json_strcmp(tokens + i, json_chunk, "scene") == 0)
6325 {
6326 ++i;
6327 out_data->scene = CGLTF_PTRINDEX(cgltf_scene, cgltf_json_to_int(tokens + i, json_chunk));
6328 ++i;
6329 }
6330 else if (cgltf_json_strcmp(tokens + i, json_chunk, "animations") == 0)
6331 {
6332 i = cgltf_parse_json_animations(options, tokens, i + 1, json_chunk, out_data);
6333 }
6334 else if (cgltf_json_strcmp(tokens+i, json_chunk, "extras") == 0)
6335 {
6336 i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_data->extras);
6337 }
6338 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
6339 {
6340 ++i;
6341
6342 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
6343 if(out_data->data_extensions)
6344 {
6345 return CGLTF_ERROR_JSON;
6346 }
6347
6348 int extensions_size = tokens[i].size;
6349 out_data->data_extensions_count = 0;
6350 out_data->data_extensions = (cgltf_extension*)cgltf_calloc(options, sizeof(cgltf_extension), extensions_size);
6351
6352 if (!out_data->data_extensions)
6353 {
6354 return CGLTF_ERROR_NOMEM;
6355 }
6356
6357 ++i;
6358
6359 for (int k = 0; k < extensions_size; ++k)
6360 {
6361 CGLTF_CHECK_KEY(tokens[i]);
6362
6363 if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_lights_punctual") == 0)
6364 {
6365 ++i;
6366
6367 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
6368
6369 int data_size = tokens[i].size;
6370 ++i;
6371
6372 for (int m = 0; m < data_size; ++m)
6373 {
6374 CGLTF_CHECK_KEY(tokens[i]);
6375
6376 if (cgltf_json_strcmp(tokens + i, json_chunk, "lights") == 0)
6377 {
6378 i = cgltf_parse_json_lights(options, tokens, i + 1, json_chunk, out_data);
6379 }
6380 else
6381 {
6382 i = cgltf_skip_json(tokens, i + 1);
6383 }
6384
6385 if (i < 0)
6386 {
6387 return i;
6388 }
6389 }
6390 }
6391 else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_variants") == 0)
6392 {
6393 ++i;
6394
6395 CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
6396
6397 int data_size = tokens[i].size;
6398 ++i;
6399
6400 for (int m = 0; m < data_size; ++m)
6401 {
6402 CGLTF_CHECK_KEY(tokens[i]);
6403
6404 if (cgltf_json_strcmp(tokens + i, json_chunk, "variants") == 0)
6405 {
6406 i = cgltf_parse_json_variants(options, tokens, i + 1, json_chunk, out_data);
6407 }
6408 else
6409 {
6410 i = cgltf_skip_json(tokens, i + 1);
6411 }
6412
6413 if (i < 0)
6414 {
6415 return i;
6416 }
6417 }
6418 }
6419 else
6420 {
6421 i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, &(out_data->data_extensions[out_data->data_extensions_count++]));
6422 }
6423
6424 if (i < 0)
6425 {
6426 return i;
6427 }
6428 }
6429 }
6430 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensionsUsed") == 0)
6431 {
6432 i = cgltf_parse_json_string_array(options, tokens, i + 1, json_chunk, &out_data->extensions_used, &out_data->extensions_used_count);
6433 }
6434 else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensionsRequired") == 0)
6435 {
6436 i = cgltf_parse_json_string_array(options, tokens, i + 1, json_chunk, &out_data->extensions_required, &out_data->extensions_required_count);
6437 }
6438 else
6439 {
6440 i = cgltf_skip_json(tokens, i + 1);
6441 }
6442
6443 if (i < 0)
6444 {
6445 return i;
6446 }
6447 }
6448
6449 return i;
6450}
6451
6452cgltf_result cgltf_parse_json(cgltf_options* options, const uint8_t* json_chunk, cgltf_size size, cgltf_data** out_data)
6453{
6454 jsmn_parser parser = { 0, 0, 0 };
6455
6456 if (options->json_token_count == 0)
6457 {
6458 int token_count = jsmn_parse(&parser, (const char*)json_chunk, size, NULL, 0);
6459
6460 if (token_count <= 0)
6461 {
6462 return cgltf_result_invalid_json;
6463 }
6464
6465 options->json_token_count = token_count;
6466 }
6467
6468 jsmntok_t* tokens = (jsmntok_t*)options->memory.alloc_func(options->memory.user_data, sizeof(jsmntok_t) * (options->json_token_count + 1));
6469
6470 if (!tokens)
6471 {
6472 return cgltf_result_out_of_memory;
6473 }
6474
6475 jsmn_init(&parser);
6476
6477 int token_count = jsmn_parse(&parser, (const char*)json_chunk, size, tokens, options->json_token_count);
6478
6479 if (token_count <= 0)
6480 {
6481 options->memory.free_func(options->memory.user_data, tokens);
6482 return cgltf_result_invalid_json;
6483 }
6484
6485 // this makes sure that we always have an UNDEFINED token at the end of the stream
6486 // for invalid JSON inputs this makes sure we don't perform out of bound reads of token data
6487 tokens[token_count].type = JSMN_UNDEFINED;
6488
6489 cgltf_data* data = (cgltf_data*)options->memory.alloc_func(options->memory.user_data, sizeof(cgltf_data));
6490
6491 if (!data)
6492 {
6493 options->memory.free_func(options->memory.user_data, tokens);
6494 return cgltf_result_out_of_memory;
6495 }
6496
6497 memset(data, 0, sizeof(cgltf_data));
6498 data->memory = options->memory;
6499 data->file = options->file;
6500
6501 int i = cgltf_parse_json_root(options, tokens, 0, json_chunk, data);
6502
6503 options->memory.free_func(options->memory.user_data, tokens);
6504
6505 if (i < 0)
6506 {
6507 cgltf_free(data);
6508
6509 switch (i)
6510 {
6511 case CGLTF_ERROR_NOMEM: return cgltf_result_out_of_memory;
6512 case CGLTF_ERROR_LEGACY: return cgltf_result_legacy_gltf;
6513 default: return cgltf_result_invalid_gltf;
6514 }
6515 }
6516
6517 if (cgltf_fixup_pointers(data) < 0)
6518 {
6519 cgltf_free(data);
6520 return cgltf_result_invalid_gltf;
6521 }
6522
6523 data->json = (const char*)json_chunk;
6524 data->json_size = size;
6525
6526 *out_data = data;
6527
6528 return cgltf_result_success;
6529}
6530
6531static int cgltf_fixup_pointers(cgltf_data* data)
6532{
6533 for (cgltf_size i = 0; i < data->meshes_count; ++i)
6534 {
6535 for (cgltf_size j = 0; j < data->meshes[i].primitives_count; ++j)
6536 {
6537 CGLTF_PTRFIXUP(data->meshes[i].primitives[j].indices, data->accessors, data->accessors_count);
6538 CGLTF_PTRFIXUP(data->meshes[i].primitives[j].material, data->materials, data->materials_count);
6539
6540 for (cgltf_size k = 0; k < data->meshes[i].primitives[j].attributes_count; ++k)
6541 {
6542 CGLTF_PTRFIXUP_REQ(data->meshes[i].primitives[j].attributes[k].data, data->accessors, data->accessors_count);
6543 }
6544
6545 for (cgltf_size k = 0; k < data->meshes[i].primitives[j].targets_count; ++k)
6546 {
6547 for (cgltf_size m = 0; m < data->meshes[i].primitives[j].targets[k].attributes_count; ++m)
6548 {
6549 CGLTF_PTRFIXUP_REQ(data->meshes[i].primitives[j].targets[k].attributes[m].data, data->accessors, data->accessors_count);
6550 }
6551 }
6552
6553 if (data->meshes[i].primitives[j].has_draco_mesh_compression)
6554 {
6555 CGLTF_PTRFIXUP_REQ(data->meshes[i].primitives[j].draco_mesh_compression.buffer_view, data->buffer_views, data->buffer_views_count);
6556 for (cgltf_size m = 0; m < data->meshes[i].primitives[j].draco_mesh_compression.attributes_count; ++m)
6557 {
6558 CGLTF_PTRFIXUP_REQ(data->meshes[i].primitives[j].draco_mesh_compression.attributes[m].data, data->accessors, data->accessors_count);
6559 }
6560 }
6561
6562 for (cgltf_size k = 0; k < data->meshes[i].primitives[j].mappings_count; ++k)
6563 {
6564 CGLTF_PTRFIXUP_REQ(data->meshes[i].primitives[j].mappings[k].material, data->materials, data->materials_count);
6565 }
6566 }
6567 }
6568
6569 for (cgltf_size i = 0; i < data->accessors_count; ++i)
6570 {
6571 CGLTF_PTRFIXUP(data->accessors[i].buffer_view, data->buffer_views, data->buffer_views_count);
6572
6573 if (data->accessors[i].is_sparse)
6574 {
6575 CGLTF_PTRFIXUP_REQ(data->accessors[i].sparse.indices_buffer_view, data->buffer_views, data->buffer_views_count);
6576 CGLTF_PTRFIXUP_REQ(data->accessors[i].sparse.values_buffer_view, data->buffer_views, data->buffer_views_count);
6577 }
6578
6579 if (data->accessors[i].buffer_view)
6580 {
6581 data->accessors[i].stride = data->accessors[i].buffer_view->stride;
6582 }
6583
6584 if (data->accessors[i].stride == 0)
6585 {
6586 data->accessors[i].stride = cgltf_calc_size(data->accessors[i].type, data->accessors[i].component_type);
6587 }
6588 }
6589
6590 for (cgltf_size i = 0; i < data->textures_count; ++i)
6591 {
6592 CGLTF_PTRFIXUP(data->textures[i].image, data->images, data->images_count);
6593 CGLTF_PTRFIXUP(data->textures[i].basisu_image, data->images, data->images_count);
6594 CGLTF_PTRFIXUP(data->textures[i].webp_image, data->images, data->images_count);
6595 CGLTF_PTRFIXUP(data->textures[i].sampler, data->samplers, data->samplers_count);
6596 }
6597
6598 for (cgltf_size i = 0; i < data->images_count; ++i)
6599 {
6600 CGLTF_PTRFIXUP(data->images[i].buffer_view, data->buffer_views, data->buffer_views_count);
6601 }
6602
6603 for (cgltf_size i = 0; i < data->materials_count; ++i)
6604 {
6605 CGLTF_PTRFIXUP(data->materials[i].normal_texture.texture, data->textures, data->textures_count);
6606 CGLTF_PTRFIXUP(data->materials[i].emissive_texture.texture, data->textures, data->textures_count);
6607 CGLTF_PTRFIXUP(data->materials[i].occlusion_texture.texture, data->textures, data->textures_count);
6608
6609 CGLTF_PTRFIXUP(data->materials[i].pbr_metallic_roughness.base_color_texture.texture, data->textures, data->textures_count);
6610 CGLTF_PTRFIXUP(data->materials[i].pbr_metallic_roughness.metallic_roughness_texture.texture, data->textures, data->textures_count);
6611
6612 CGLTF_PTRFIXUP(data->materials[i].pbr_specular_glossiness.diffuse_texture.texture, data->textures, data->textures_count);
6613 CGLTF_PTRFIXUP(data->materials[i].pbr_specular_glossiness.specular_glossiness_texture.texture, data->textures, data->textures_count);
6614
6615 CGLTF_PTRFIXUP(data->materials[i].clearcoat.clearcoat_texture.texture, data->textures, data->textures_count);
6616 CGLTF_PTRFIXUP(data->materials[i].clearcoat.clearcoat_roughness_texture.texture, data->textures, data->textures_count);
6617 CGLTF_PTRFIXUP(data->materials[i].clearcoat.clearcoat_normal_texture.texture, data->textures, data->textures_count);
6618
6619 CGLTF_PTRFIXUP(data->materials[i].specular.specular_texture.texture, data->textures, data->textures_count);
6620 CGLTF_PTRFIXUP(data->materials[i].specular.specular_color_texture.texture, data->textures, data->textures_count);
6621
6622 CGLTF_PTRFIXUP(data->materials[i].transmission.transmission_texture.texture, data->textures, data->textures_count);
6623
6624 CGLTF_PTRFIXUP(data->materials[i].volume.thickness_texture.texture, data->textures, data->textures_count);
6625
6626 CGLTF_PTRFIXUP(data->materials[i].sheen.sheen_color_texture.texture, data->textures, data->textures_count);
6627 CGLTF_PTRFIXUP(data->materials[i].sheen.sheen_roughness_texture.texture, data->textures, data->textures_count);
6628
6629 CGLTF_PTRFIXUP(data->materials[i].iridescence.iridescence_texture.texture, data->textures, data->textures_count);
6630 CGLTF_PTRFIXUP(data->materials[i].iridescence.iridescence_thickness_texture.texture, data->textures, data->textures_count);
6631
6632 CGLTF_PTRFIXUP(data->materials[i].anisotropy.anisotropy_texture.texture, data->textures, data->textures_count);
6633 }
6634
6635 for (cgltf_size i = 0; i < data->buffer_views_count; ++i)
6636 {
6637 CGLTF_PTRFIXUP_REQ(data->buffer_views[i].buffer, data->buffers, data->buffers_count);
6638
6639 if (data->buffer_views[i].has_meshopt_compression)
6640 {
6641 CGLTF_PTRFIXUP_REQ(data->buffer_views[i].meshopt_compression.buffer, data->buffers, data->buffers_count);
6642 }
6643 }
6644
6645 for (cgltf_size i = 0; i < data->skins_count; ++i)
6646 {
6647 for (cgltf_size j = 0; j < data->skins[i].joints_count; ++j)
6648 {
6649 CGLTF_PTRFIXUP_REQ(data->skins[i].joints[j], data->nodes, data->nodes_count);
6650 }
6651
6652 CGLTF_PTRFIXUP(data->skins[i].skeleton, data->nodes, data->nodes_count);
6653 CGLTF_PTRFIXUP(data->skins[i].inverse_bind_matrices, data->accessors, data->accessors_count);
6654 }
6655
6656 for (cgltf_size i = 0; i < data->nodes_count; ++i)
6657 {
6658 for (cgltf_size j = 0; j < data->nodes[i].children_count; ++j)
6659 {
6660 CGLTF_PTRFIXUP_REQ(data->nodes[i].children[j], data->nodes, data->nodes_count);
6661
6662 if (data->nodes[i].children[j]->parent)
6663 {
6664 return CGLTF_ERROR_JSON;
6665 }
6666
6667 data->nodes[i].children[j]->parent = &data->nodes[i];
6668 }
6669
6670 CGLTF_PTRFIXUP(data->nodes[i].mesh, data->meshes, data->meshes_count);
6671 CGLTF_PTRFIXUP(data->nodes[i].skin, data->skins, data->skins_count);
6672 CGLTF_PTRFIXUP(data->nodes[i].camera, data->cameras, data->cameras_count);
6673 CGLTF_PTRFIXUP(data->nodes[i].light, data->lights, data->lights_count);
6674
6675 if (data->nodes[i].has_mesh_gpu_instancing)
6676 {
6677 for (cgltf_size m = 0; m < data->nodes[i].mesh_gpu_instancing.attributes_count; ++m)
6678 {
6679 CGLTF_PTRFIXUP_REQ(data->nodes[i].mesh_gpu_instancing.attributes[m].data, data->accessors, data->accessors_count);
6680 }
6681 }
6682 }
6683
6684 for (cgltf_size i = 0; i < data->scenes_count; ++i)
6685 {
6686 for (cgltf_size j = 0; j < data->scenes[i].nodes_count; ++j)
6687 {
6688 CGLTF_PTRFIXUP_REQ(data->scenes[i].nodes[j], data->nodes, data->nodes_count);
6689
6690 if (data->scenes[i].nodes[j]->parent)
6691 {
6692 return CGLTF_ERROR_JSON;
6693 }
6694 }
6695 }
6696
6697 CGLTF_PTRFIXUP(data->scene, data->scenes, data->scenes_count);
6698
6699 for (cgltf_size i = 0; i < data->animations_count; ++i)
6700 {
6701 for (cgltf_size j = 0; j < data->animations[i].samplers_count; ++j)
6702 {
6703 CGLTF_PTRFIXUP_REQ(data->animations[i].samplers[j].input, data->accessors, data->accessors_count);
6704 CGLTF_PTRFIXUP_REQ(data->animations[i].samplers[j].output, data->accessors, data->accessors_count);
6705 }
6706
6707 for (cgltf_size j = 0; j < data->animations[i].channels_count; ++j)
6708 {
6709 CGLTF_PTRFIXUP_REQ(data->animations[i].channels[j].sampler, data->animations[i].samplers, data->animations[i].samplers_count);
6710 CGLTF_PTRFIXUP(data->animations[i].channels[j].target_node, data->nodes, data->nodes_count);
6711 }
6712 }
6713
6714 return 0;
6715}
6716
6717/*
6718 * -- jsmn.c start --
6719 * Source: https://github.com/zserge/jsmn
6720 * License: MIT
6721 *
6722 * Copyright (c) 2010 Serge A. Zaitsev
6723
6724 * Permission is hereby granted, free of charge, to any person obtaining a copy
6725 * of this software and associated documentation files (the "Software"), to deal
6726 * in the Software without restriction, including without limitation the rights
6727 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
6728 * copies of the Software, and to permit persons to whom the Software is
6729 * furnished to do so, subject to the following conditions:
6730
6731 * The above copyright notice and this permission notice shall be included in
6732 * all copies or substantial portions of the Software.
6733
6734 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
6735 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
6736 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
6737 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
6738 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
6739 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
6740 * THE SOFTWARE.
6741 */
6742
6743/**
6744 * Allocates a fresh unused token from the token pull.
6745 */
6746static jsmntok_t *jsmn_alloc_token(jsmn_parser *parser,
6747 jsmntok_t *tokens, size_t num_tokens) {
6748 jsmntok_t *tok;
6749 if (parser->toknext >= num_tokens) {
6750 return NULL;
6751 }
6752 tok = &tokens[parser->toknext++];
6753 tok->start = tok->end = -1;
6754 tok->size = 0;
6755#ifdef JSMN_PARENT_LINKS
6756 tok->parent = -1;
6757#endif
6758 return tok;
6759}
6760
6761/**
6762 * Fills token type and boundaries.
6763 */
6764static void jsmn_fill_token(jsmntok_t *token, jsmntype_t type,
6765 ptrdiff_t start, ptrdiff_t end) {
6766 token->type = type;
6767 token->start = start;
6768 token->end = end;
6769 token->size = 0;
6770}
6771
6772/**
6773 * Fills next available token with JSON primitive.
6774 */
6775static int jsmn_parse_primitive(jsmn_parser *parser, const char *js,
6776 size_t len, jsmntok_t *tokens, size_t num_tokens) {
6777 jsmntok_t *token;
6778 ptrdiff_t start;
6779
6780 start = parser->pos;
6781
6782 for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) {
6783 switch (js[parser->pos]) {
6784#ifndef JSMN_STRICT
6785 /* In strict mode primitive must be followed by "," or "}" or "]" */
6786 case ':':
6787#endif
6788 case '\t' : case '\r' : case '\n' : case ' ' :
6789 case ',' : case ']' : case '}' :
6790 goto found;
6791 }
6792 if (js[parser->pos] < 32 || js[parser->pos] >= 127) {
6793 parser->pos = start;
6794 return JSMN_ERROR_INVAL;
6795 }
6796 }
6797#ifdef JSMN_STRICT
6798 /* In strict mode primitive must be followed by a comma/object/array */
6799 parser->pos = start;
6800 return JSMN_ERROR_PART;
6801#endif
6802
6803found:
6804 if (tokens == NULL) {
6805 parser->pos--;
6806 return 0;
6807 }
6808 token = jsmn_alloc_token(parser, tokens, num_tokens);
6809 if (token == NULL) {
6810 parser->pos = start;
6811 return JSMN_ERROR_NOMEM;
6812 }
6813 jsmn_fill_token(token, JSMN_PRIMITIVE, start, parser->pos);
6814#ifdef JSMN_PARENT_LINKS
6815 token->parent = parser->toksuper;
6816#endif
6817 parser->pos--;
6818 return 0;
6819}
6820
6821/**
6822 * Fills next token with JSON string.
6823 */
6824static int jsmn_parse_string(jsmn_parser *parser, const char *js,
6825 size_t len, jsmntok_t *tokens, size_t num_tokens) {
6826 jsmntok_t *token;
6827
6828 ptrdiff_t start = parser->pos;
6829
6830 parser->pos++;
6831
6832 /* Skip starting quote */
6833 for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) {
6834 char c = js[parser->pos];
6835
6836 /* Quote: end of string */
6837 if (c == '\"') {
6838 if (tokens == NULL) {
6839 return 0;
6840 }
6841 token = jsmn_alloc_token(parser, tokens, num_tokens);
6842 if (token == NULL) {
6843 parser->pos = start;
6844 return JSMN_ERROR_NOMEM;
6845 }
6846 jsmn_fill_token(token, JSMN_STRING, start+1, parser->pos);
6847#ifdef JSMN_PARENT_LINKS
6848 token->parent = parser->toksuper;
6849#endif
6850 return 0;
6851 }
6852
6853 /* Backslash: Quoted symbol expected */
6854 if (c == '\\' && parser->pos + 1 < len) {
6855 int i;
6856 parser->pos++;
6857 switch (js[parser->pos]) {
6858 /* Allowed escaped symbols */
6859 case '\"': case '/' : case '\\' : case 'b' :
6860 case 'f' : case 'r' : case 'n' : case 't' :
6861 break;
6862 /* Allows escaped symbol \uXXXX */
6863 case 'u':
6864 parser->pos++;
6865 for(i = 0; i < 4 && parser->pos < len && js[parser->pos] != '\0'; i++) {
6866 /* If it isn't a hex character we have an error */
6867 if(!((js[parser->pos] >= 48 && js[parser->pos] <= 57) || /* 0-9 */
6868 (js[parser->pos] >= 65 && js[parser->pos] <= 70) || /* A-F */
6869 (js[parser->pos] >= 97 && js[parser->pos] <= 102))) { /* a-f */
6870 parser->pos = start;
6871 return JSMN_ERROR_INVAL;
6872 }
6873 parser->pos++;
6874 }
6875 parser->pos--;
6876 break;
6877 /* Unexpected symbol */
6878 default:
6879 parser->pos = start;
6880 return JSMN_ERROR_INVAL;
6881 }
6882 }
6883 }
6884 parser->pos = start;
6885 return JSMN_ERROR_PART;
6886}
6887
6888/**
6889 * Parse JSON string and fill tokens.
6890 */
6891static int jsmn_parse(jsmn_parser *parser, const char *js, size_t len,
6892 jsmntok_t *tokens, size_t num_tokens) {
6893 int r;
6894 int i;
6895 jsmntok_t *token;
6896 int count = parser->toknext;
6897
6898 for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) {
6899 char c;
6900 jsmntype_t type;
6901
6902 c = js[parser->pos];
6903 switch (c) {
6904 case '{': case '[':
6905 count++;
6906 if (tokens == NULL) {
6907 break;
6908 }
6909 token = jsmn_alloc_token(parser, tokens, num_tokens);
6910 if (token == NULL)
6911 return JSMN_ERROR_NOMEM;
6912 if (parser->toksuper != -1) {
6913 tokens[parser->toksuper].size++;
6914#ifdef JSMN_PARENT_LINKS
6915 token->parent = parser->toksuper;
6916#endif
6917 }
6918 token->type = (c == '{' ? JSMN_OBJECT : JSMN_ARRAY);
6919 token->start = parser->pos;
6920 parser->toksuper = parser->toknext - 1;
6921 break;
6922 case '}': case ']':
6923 if (tokens == NULL)
6924 break;
6925 type = (c == '}' ? JSMN_OBJECT : JSMN_ARRAY);
6926#ifdef JSMN_PARENT_LINKS
6927 if (parser->toknext < 1) {
6928 return JSMN_ERROR_INVAL;
6929 }
6930 token = &tokens[parser->toknext - 1];
6931 for (;;) {
6932 if (token->start != -1 && token->end == -1) {
6933 if (token->type != type) {
6934 return JSMN_ERROR_INVAL;
6935 }
6936 token->end = parser->pos + 1;
6937 parser->toksuper = token->parent;
6938 break;
6939 }
6940 if (token->parent == -1) {
6941 if(token->type != type || parser->toksuper == -1) {
6942 return JSMN_ERROR_INVAL;
6943 }
6944 break;
6945 }
6946 token = &tokens[token->parent];
6947 }
6948#else
6949 for (i = parser->toknext - 1; i >= 0; i--) {
6950 token = &tokens[i];
6951 if (token->start != -1 && token->end == -1) {
6952 if (token->type != type) {
6953 return JSMN_ERROR_INVAL;
6954 }
6955 parser->toksuper = -1;
6956 token->end = parser->pos + 1;
6957 break;
6958 }
6959 }
6960 /* Error if unmatched closing bracket */
6961 if (i == -1) return JSMN_ERROR_INVAL;
6962 for (; i >= 0; i--) {
6963 token = &tokens[i];
6964 if (token->start != -1 && token->end == -1) {
6965 parser->toksuper = i;
6966 break;
6967 }
6968 }
6969#endif
6970 break;
6971 case '\"':
6972 r = jsmn_parse_string(parser, js, len, tokens, num_tokens);
6973 if (r < 0) return r;
6974 count++;
6975 if (parser->toksuper != -1 && tokens != NULL)
6976 tokens[parser->toksuper].size++;
6977 break;
6978 case '\t' : case '\r' : case '\n' : case ' ':
6979 break;
6980 case ':':
6981 parser->toksuper = parser->toknext - 1;
6982 break;
6983 case ',':
6984 if (tokens != NULL && parser->toksuper != -1 &&
6985 tokens[parser->toksuper].type != JSMN_ARRAY &&
6986 tokens[parser->toksuper].type != JSMN_OBJECT) {
6987#ifdef JSMN_PARENT_LINKS
6988 parser->toksuper = tokens[parser->toksuper].parent;
6989#else
6990 for (i = parser->toknext - 1; i >= 0; i--) {
6991 if (tokens[i].type == JSMN_ARRAY || tokens[i].type == JSMN_OBJECT) {
6992 if (tokens[i].start != -1 && tokens[i].end == -1) {
6993 parser->toksuper = i;
6994 break;
6995 }
6996 }
6997 }
6998#endif
6999 }
7000 break;
7001#ifdef JSMN_STRICT
7002 /* In strict mode primitives are: numbers and booleans */
7003 case '-': case '0': case '1' : case '2': case '3' : case '4':
7004 case '5': case '6': case '7' : case '8': case '9':
7005 case 't': case 'f': case 'n' :
7006 /* And they must not be keys of the object */
7007 if (tokens != NULL && parser->toksuper != -1) {
7008 jsmntok_t *t = &tokens[parser->toksuper];
7009 if (t->type == JSMN_OBJECT ||
7010 (t->type == JSMN_STRING && t->size != 0)) {
7011 return JSMN_ERROR_INVAL;
7012 }
7013 }
7014#else
7015 /* In non-strict mode every unquoted value is a primitive */
7016 default:
7017#endif
7018 r = jsmn_parse_primitive(parser, js, len, tokens, num_tokens);
7019 if (r < 0) return r;
7020 count++;
7021 if (parser->toksuper != -1 && tokens != NULL)
7022 tokens[parser->toksuper].size++;
7023 break;
7024
7025#ifdef JSMN_STRICT
7026 /* Unexpected char in strict mode */
7027 default:
7028 return JSMN_ERROR_INVAL;
7029#endif
7030 }
7031 }
7032
7033 if (tokens != NULL) {
7034 for (i = parser->toknext - 1; i >= 0; i--) {
7035 /* Unmatched opened object or array */
7036 if (tokens[i].start != -1 && tokens[i].end == -1) {
7037 return JSMN_ERROR_PART;
7038 }
7039 }
7040 }
7041
7042 return count;
7043}
7044
7045/**
7046 * Creates a new parser based over a given buffer with an array of tokens
7047 * available.
7048 */
7049static void jsmn_init(jsmn_parser *parser) {
7050 parser->pos = 0;
7051 parser->toknext = 0;
7052 parser->toksuper = -1;
7053}
7054/*
7055 * -- jsmn.c end --
7056 */
7057
7058#endif /* #ifdef CGLTF_IMPLEMENTATION */
7059
7060/* cgltf is distributed under MIT license:
7061 *
7062 * Copyright (c) 2018-2021 Johannes Kuhlmann
7063
7064 * Permission is hereby granted, free of charge, to any person obtaining a copy
7065 * of this software and associated documentation files (the "Software"), to deal
7066 * in the Software without restriction, including without limitation the rights
7067 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7068 * copies of the Software, and to permit persons to whom the Software is
7069 * furnished to do so, subject to the following conditions:
7070
7071 * The above copyright notice and this permission notice shall be included in all
7072 * copies or substantial portions of the Software.
7073
7074 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
7075 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
7076 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
7077 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
7078 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
7079 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
7080 * SOFTWARE.
7081 */
diff --git a/raylib/src/external/dirent.h b/raylib/src/external/dirent.h
new file mode 100644
index 0000000..c611376
--- /dev/null
+++ b/raylib/src/external/dirent.h
@@ -0,0 +1,183 @@
1/****************************************************************************
2
3 Declaration of POSIX directory browsing functions and types for Win32.
4
5 Author: Kevlin Henney (kevlin@acm.org, kevlin@curbralan.com)
6 History: Created March 1997. Updated June 2003.
7 Reviewed by Ramon Santamaria for raylib on January 2020.
8
9 Copyright Kevlin Henney, 1997, 2003. All rights reserved.
10
11 Permission to use, copy, modify, and distribute this software and its
12 documentation for any purpose is hereby granted without fee, provided
13 that this copyright and permissions notice appear in all copies and
14 derivatives.
15
16 This software is supplied "as is" without express or implied warranty.
17
18 But that said, if there are any problems please get in touch.
19
20****************************************************************************/
21
22#ifndef DIRENT_H
23#define DIRENT_H
24
25// Allow custom memory allocators
26#ifndef DIRENT_MALLOC
27 #define DIRENT_MALLOC(sz) malloc(sz)
28#endif
29#ifndef DIRENT_FREE
30 #define DIRENT_FREE(p) free(p)
31#endif
32
33//----------------------------------------------------------------------------------
34// Types and Structures Definition
35//----------------------------------------------------------------------------------
36
37// Fordward declaration of DIR, implementation below
38typedef struct DIR DIR;
39
40struct dirent {
41 char *d_name;
42};
43
44#ifdef __cplusplus
45extern "C" {
46#endif
47
48//------------------------------------------------------------------------------------
49// Functions Declaration
50//------------------------------------------------------------------------------------
51DIR *opendir(const char *name);
52int closedir(DIR *dir);
53struct dirent *readdir(DIR *dir);
54void rewinddir(DIR *dir);
55
56#ifdef __cplusplus
57}
58#endif
59
60#endif // DIRENT_H
61
62/****************************************************************************
63
64 Implementation of POSIX directory browsing functions and types for Win32.
65
66 Author: Kevlin Henney (kevlin@acm.org, kevlin@curbralan.com)
67 History: Created March 1997. Updated June 2003.
68 Reviewed by Ramon Santamaria for raylib on January 2020.
69
70 Copyright Kevlin Henney, 1997, 2003. All rights reserved.
71
72 Permission to use, copy, modify, and distribute this software and its
73 documentation for any purpose is hereby granted without fee, provided
74 that this copyright and permissions notice appear in all copies and
75 derivatives.
76
77 This software is supplied "as is" without express or implied warranty.
78
79 But that said, if there are any problems please get in touch.
80
81****************************************************************************/
82
83#include <io.h> // _findfirst and _findnext set errno iff they return -1
84#include <stdlib.h>
85#include <string.h>
86#include <errno.h>
87
88//----------------------------------------------------------------------------------
89// Types and Structures Definition
90//----------------------------------------------------------------------------------
91typedef ptrdiff_t handle_type; // C99's intptr_t not sufficiently portable
92
93struct DIR {
94 handle_type handle; // -1 for failed rewind
95 struct _finddata_t info;
96 struct dirent result; // d_name null iff first time
97 char *name; // null-terminated char string
98};
99
100DIR *opendir(const char *name)
101{
102 DIR *dir = 0;
103
104 if (name && name[0])
105 {
106 size_t base_length = strlen(name);
107
108 // Search pattern must end with suitable wildcard
109 const char *all = strchr("/\\", name[base_length - 1]) ? "*" : "/*";
110
111 if ((dir = (DIR *)DIRENT_MALLOC(sizeof *dir)) != 0 &&
112 (dir->name = (char *)DIRENT_MALLOC(base_length + strlen(all) + 1)) != 0)
113 {
114 strcat(strcpy(dir->name, name), all);
115
116 if ((dir->handle = (handle_type) _findfirst(dir->name, &dir->info)) != -1)
117 {
118 dir->result.d_name = 0;
119 }
120 else // rollback
121 {
122 DIRENT_FREE(dir->name);
123 DIRENT_FREE(dir);
124 dir = 0;
125 }
126 }
127 else // rollback
128 {
129 DIRENT_FREE(dir);
130 dir = 0;
131 errno = ENOMEM;
132 }
133 }
134 else errno = EINVAL;
135
136 return dir;
137}
138
139int closedir(DIR *dir)
140{
141 int result = -1;
142
143 if (dir)
144 {
145 if (dir->handle != -1) result = _findclose(dir->handle);
146
147 DIRENT_FREE(dir->name);
148 DIRENT_FREE(dir);
149 }
150
151 // NOTE: All errors ampped to EBADF
152 if (result == -1) errno = EBADF;
153
154 return result;
155}
156
157struct dirent *readdir(DIR *dir)
158{
159 struct dirent *result = 0;
160
161 if (dir && dir->handle != -1)
162 {
163 if (!dir->result.d_name || _findnext(dir->handle, &dir->info) != -1)
164 {
165 result = &dir->result;
166 result->d_name = dir->info.name;
167 }
168 }
169 else errno = EBADF;
170
171 return result;
172}
173
174void rewinddir(DIR *dir)
175{
176 if (dir && dir->handle != -1)
177 {
178 _findclose(dir->handle);
179 dir->handle = (handle_type) _findfirst(dir->name, &dir->info);
180 dir->result.d_name = 0;
181 }
182 else errno = EBADF;
183}
diff --git a/raylib/src/external/dr_flac.h b/raylib/src/external/dr_flac.h
new file mode 100644
index 0000000..14324cf
--- /dev/null
+++ b/raylib/src/external/dr_flac.h
@@ -0,0 +1,12536 @@
1/*
2FLAC audio decoder. Choice of public domain or MIT-0. See license statements at the end of this file.
3dr_flac - v0.12.42 - 2023-11-02
4
5David Reid - mackron@gmail.com
6
7GitHub: https://github.com/mackron/dr_libs
8*/
9
10/*
11RELEASE NOTES - v0.12.0
12=======================
13Version 0.12.0 has breaking API changes including changes to the existing API and the removal of deprecated APIs.
14
15
16Improved Client-Defined Memory Allocation
17-----------------------------------------
18The main change with this release is the addition of a more flexible way of implementing custom memory allocation routines. The
19existing system of DRFLAC_MALLOC, DRFLAC_REALLOC and DRFLAC_FREE are still in place and will be used by default when no custom
20allocation callbacks are specified.
21
22To use the new system, you pass in a pointer to a drflac_allocation_callbacks object to drflac_open() and family, like this:
23
24 void* my_malloc(size_t sz, void* pUserData)
25 {
26 return malloc(sz);
27 }
28 void* my_realloc(void* p, size_t sz, void* pUserData)
29 {
30 return realloc(p, sz);
31 }
32 void my_free(void* p, void* pUserData)
33 {
34 free(p);
35 }
36
37 ...
38
39 drflac_allocation_callbacks allocationCallbacks;
40 allocationCallbacks.pUserData = &myData;
41 allocationCallbacks.onMalloc = my_malloc;
42 allocationCallbacks.onRealloc = my_realloc;
43 allocationCallbacks.onFree = my_free;
44 drflac* pFlac = drflac_open_file("my_file.flac", &allocationCallbacks);
45
46The advantage of this new system is that it allows you to specify user data which will be passed in to the allocation routines.
47
48Passing in null for the allocation callbacks object will cause dr_flac to use defaults which is the same as DRFLAC_MALLOC,
49DRFLAC_REALLOC and DRFLAC_FREE and the equivalent of how it worked in previous versions.
50
51Every API that opens a drflac object now takes this extra parameter. These include the following:
52
53 drflac_open()
54 drflac_open_relaxed()
55 drflac_open_with_metadata()
56 drflac_open_with_metadata_relaxed()
57 drflac_open_file()
58 drflac_open_file_with_metadata()
59 drflac_open_memory()
60 drflac_open_memory_with_metadata()
61 drflac_open_and_read_pcm_frames_s32()
62 drflac_open_and_read_pcm_frames_s16()
63 drflac_open_and_read_pcm_frames_f32()
64 drflac_open_file_and_read_pcm_frames_s32()
65 drflac_open_file_and_read_pcm_frames_s16()
66 drflac_open_file_and_read_pcm_frames_f32()
67 drflac_open_memory_and_read_pcm_frames_s32()
68 drflac_open_memory_and_read_pcm_frames_s16()
69 drflac_open_memory_and_read_pcm_frames_f32()
70
71
72
73Optimizations
74-------------
75Seeking performance has been greatly improved. A new binary search based seeking algorithm has been introduced which significantly
76improves performance over the brute force method which was used when no seek table was present. Seek table based seeking also takes
77advantage of the new binary search seeking system to further improve performance there as well. Note that this depends on CRC which
78means it will be disabled when DR_FLAC_NO_CRC is used.
79
80The SSE4.1 pipeline has been cleaned up and optimized. You should see some improvements with decoding speed of 24-bit files in
81particular. 16-bit streams should also see some improvement.
82
83drflac_read_pcm_frames_s16() has been optimized. Previously this sat on top of drflac_read_pcm_frames_s32() and performed it's s32
84to s16 conversion in a second pass. This is now all done in a single pass. This includes SSE2 and ARM NEON optimized paths.
85
86A minor optimization has been implemented for drflac_read_pcm_frames_s32(). This will now use an SSE2 optimized pipeline for stereo
87channel reconstruction which is the last part of the decoding process.
88
89The ARM build has seen a few improvements. The CLZ (count leading zeroes) and REV (byte swap) instructions are now used when
90compiling with GCC and Clang which is achieved using inline assembly. The CLZ instruction requires ARM architecture version 5 at
91compile time and the REV instruction requires ARM architecture version 6.
92
93An ARM NEON optimized pipeline has been implemented. To enable this you'll need to add -mfpu=neon to the command line when compiling.
94
95
96Removed APIs
97------------
98The following APIs were deprecated in version 0.11.0 and have been completely removed in version 0.12.0:
99
100 drflac_read_s32() -> drflac_read_pcm_frames_s32()
101 drflac_read_s16() -> drflac_read_pcm_frames_s16()
102 drflac_read_f32() -> drflac_read_pcm_frames_f32()
103 drflac_seek_to_sample() -> drflac_seek_to_pcm_frame()
104 drflac_open_and_decode_s32() -> drflac_open_and_read_pcm_frames_s32()
105 drflac_open_and_decode_s16() -> drflac_open_and_read_pcm_frames_s16()
106 drflac_open_and_decode_f32() -> drflac_open_and_read_pcm_frames_f32()
107 drflac_open_and_decode_file_s32() -> drflac_open_file_and_read_pcm_frames_s32()
108 drflac_open_and_decode_file_s16() -> drflac_open_file_and_read_pcm_frames_s16()
109 drflac_open_and_decode_file_f32() -> drflac_open_file_and_read_pcm_frames_f32()
110 drflac_open_and_decode_memory_s32() -> drflac_open_memory_and_read_pcm_frames_s32()
111 drflac_open_and_decode_memory_s16() -> drflac_open_memory_and_read_pcm_frames_s16()
112 drflac_open_and_decode_memory_f32() -> drflac_open_memroy_and_read_pcm_frames_f32()
113
114Prior versions of dr_flac operated on a per-sample basis whereas now it operates on PCM frames. The removed APIs all relate
115to the old per-sample APIs. You now need to use the "pcm_frame" versions.
116*/
117
118
119/*
120Introduction
121============
122dr_flac is a single file library. To use it, do something like the following in one .c file.
123
124 ```c
125 #define DR_FLAC_IMPLEMENTATION
126 #include "dr_flac.h"
127 ```
128
129You can then #include this file in other parts of the program as you would with any other header file. To decode audio data, do something like the following:
130
131 ```c
132 drflac* pFlac = drflac_open_file("MySong.flac", NULL);
133 if (pFlac == NULL) {
134 // Failed to open FLAC file
135 }
136
137 drflac_int32* pSamples = malloc(pFlac->totalPCMFrameCount * pFlac->channels * sizeof(drflac_int32));
138 drflac_uint64 numberOfInterleavedSamplesActuallyRead = drflac_read_pcm_frames_s32(pFlac, pFlac->totalPCMFrameCount, pSamples);
139 ```
140
141The drflac object represents the decoder. It is a transparent type so all the information you need, such as the number of channels and the bits per sample,
142should be directly accessible - just make sure you don't change their values. Samples are always output as interleaved signed 32-bit PCM. In the example above
143a native FLAC stream was opened, however dr_flac has seamless support for Ogg encapsulated FLAC streams as well.
144
145You do not need to decode the entire stream in one go - you just specify how many samples you'd like at any given time and the decoder will give you as many
146samples as it can, up to the amount requested. Later on when you need the next batch of samples, just call it again. Example:
147
148 ```c
149 while (drflac_read_pcm_frames_s32(pFlac, chunkSizeInPCMFrames, pChunkSamples) > 0) {
150 do_something();
151 }
152 ```
153
154You can seek to a specific PCM frame with `drflac_seek_to_pcm_frame()`.
155
156If you just want to quickly decode an entire FLAC file in one go you can do something like this:
157
158 ```c
159 unsigned int channels;
160 unsigned int sampleRate;
161 drflac_uint64 totalPCMFrameCount;
162 drflac_int32* pSampleData = drflac_open_file_and_read_pcm_frames_s32("MySong.flac", &channels, &sampleRate, &totalPCMFrameCount, NULL);
163 if (pSampleData == NULL) {
164 // Failed to open and decode FLAC file.
165 }
166
167 ...
168
169 drflac_free(pSampleData, NULL);
170 ```
171
172You can read samples as signed 16-bit integer and 32-bit floating-point PCM with the *_s16() and *_f32() family of APIs respectively, but note that these
173should be considered lossy.
174
175
176If you need access to metadata (album art, etc.), use `drflac_open_with_metadata()`, `drflac_open_file_with_metdata()` or `drflac_open_memory_with_metadata()`.
177The rationale for keeping these APIs separate is that they're slightly slower than the normal versions and also just a little bit harder to use. dr_flac
178reports metadata to the application through the use of a callback, and every metadata block is reported before `drflac_open_with_metdata()` returns.
179
180The main opening APIs (`drflac_open()`, etc.) will fail if the header is not present. The presents a problem in certain scenarios such as broadcast style
181streams or internet radio where the header may not be present because the user has started playback mid-stream. To handle this, use the relaxed APIs:
182
183 `drflac_open_relaxed()`
184 `drflac_open_with_metadata_relaxed()`
185
186It is not recommended to use these APIs for file based streams because a missing header would usually indicate a corrupt or perverse file. In addition, these
187APIs can take a long time to initialize because they may need to spend a lot of time finding the first frame.
188
189
190
191Build Options
192=============
193#define these options before including this file.
194
195#define DR_FLAC_NO_STDIO
196 Disable `drflac_open_file()` and family.
197
198#define DR_FLAC_NO_OGG
199 Disables support for Ogg/FLAC streams.
200
201#define DR_FLAC_BUFFER_SIZE <number>
202 Defines the size of the internal buffer to store data from onRead(). This buffer is used to reduce the number of calls back to the client for more data.
203 Larger values means more memory, but better performance. My tests show diminishing returns after about 4KB (which is the default). Consider reducing this if
204 you have a very efficient implementation of onRead(), or increase it if it's very inefficient. Must be a multiple of 8.
205
206#define DR_FLAC_NO_CRC
207 Disables CRC checks. This will offer a performance boost when CRC is unnecessary. This will disable binary search seeking. When seeking, the seek table will
208 be used if available. Otherwise the seek will be performed using brute force.
209
210#define DR_FLAC_NO_SIMD
211 Disables SIMD optimizations (SSE on x86/x64 architectures, NEON on ARM architectures). Use this if you are having compatibility issues with your compiler.
212
213#define DR_FLAC_NO_WCHAR
214 Disables all functions ending with `_w`. Use this if your compiler does not provide wchar.h. Not required if DR_FLAC_NO_STDIO is also defined.
215
216
217
218Notes
219=====
220- dr_flac does not support changing the sample rate nor channel count mid stream.
221- dr_flac is not thread-safe, but its APIs can be called from any thread so long as you do your own synchronization.
222- When using Ogg encapsulation, a corrupted metadata block will result in `drflac_open_with_metadata()` and `drflac_open()` returning inconsistent samples due
223 to differences in corrupted stream recorvery logic between the two APIs.
224*/
225
226#ifndef dr_flac_h
227#define dr_flac_h
228
229#ifdef __cplusplus
230extern "C" {
231#endif
232
233#define DRFLAC_STRINGIFY(x) #x
234#define DRFLAC_XSTRINGIFY(x) DRFLAC_STRINGIFY(x)
235
236#define DRFLAC_VERSION_MAJOR 0
237#define DRFLAC_VERSION_MINOR 12
238#define DRFLAC_VERSION_REVISION 42
239#define DRFLAC_VERSION_STRING DRFLAC_XSTRINGIFY(DRFLAC_VERSION_MAJOR) "." DRFLAC_XSTRINGIFY(DRFLAC_VERSION_MINOR) "." DRFLAC_XSTRINGIFY(DRFLAC_VERSION_REVISION)
240
241#include <stddef.h> /* For size_t. */
242
243/* Sized Types */
244typedef signed char drflac_int8;
245typedef unsigned char drflac_uint8;
246typedef signed short drflac_int16;
247typedef unsigned short drflac_uint16;
248typedef signed int drflac_int32;
249typedef unsigned int drflac_uint32;
250#if defined(_MSC_VER) && !defined(__clang__)
251 typedef signed __int64 drflac_int64;
252 typedef unsigned __int64 drflac_uint64;
253#else
254 #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
255 #pragma GCC diagnostic push
256 #pragma GCC diagnostic ignored "-Wlong-long"
257 #if defined(__clang__)
258 #pragma GCC diagnostic ignored "-Wc++11-long-long"
259 #endif
260 #endif
261 typedef signed long long drflac_int64;
262 typedef unsigned long long drflac_uint64;
263 #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
264 #pragma GCC diagnostic pop
265 #endif
266#endif
267#if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__)) || defined(_M_X64) || defined(__ia64) || defined(_M_IA64) || defined(__aarch64__) || defined(_M_ARM64) || defined(__powerpc64__)
268 typedef drflac_uint64 drflac_uintptr;
269#else
270 typedef drflac_uint32 drflac_uintptr;
271#endif
272typedef drflac_uint8 drflac_bool8;
273typedef drflac_uint32 drflac_bool32;
274#define DRFLAC_TRUE 1
275#define DRFLAC_FALSE 0
276/* End Sized Types */
277
278/* Decorations */
279#if !defined(DRFLAC_API)
280 #if defined(DRFLAC_DLL)
281 #if defined(_WIN32)
282 #define DRFLAC_DLL_IMPORT __declspec(dllimport)
283 #define DRFLAC_DLL_EXPORT __declspec(dllexport)
284 #define DRFLAC_DLL_PRIVATE static
285 #else
286 #if defined(__GNUC__) && __GNUC__ >= 4
287 #define DRFLAC_DLL_IMPORT __attribute__((visibility("default")))
288 #define DRFLAC_DLL_EXPORT __attribute__((visibility("default")))
289 #define DRFLAC_DLL_PRIVATE __attribute__((visibility("hidden")))
290 #else
291 #define DRFLAC_DLL_IMPORT
292 #define DRFLAC_DLL_EXPORT
293 #define DRFLAC_DLL_PRIVATE static
294 #endif
295 #endif
296
297 #if defined(DR_FLAC_IMPLEMENTATION) || defined(DRFLAC_IMPLEMENTATION)
298 #define DRFLAC_API DRFLAC_DLL_EXPORT
299 #else
300 #define DRFLAC_API DRFLAC_DLL_IMPORT
301 #endif
302 #define DRFLAC_PRIVATE DRFLAC_DLL_PRIVATE
303 #else
304 #define DRFLAC_API extern
305 #define DRFLAC_PRIVATE static
306 #endif
307#endif
308/* End Decorations */
309
310#if defined(_MSC_VER) && _MSC_VER >= 1700 /* Visual Studio 2012 */
311 #define DRFLAC_DEPRECATED __declspec(deprecated)
312#elif (defined(__GNUC__) && __GNUC__ >= 4) /* GCC 4 */
313 #define DRFLAC_DEPRECATED __attribute__((deprecated))
314#elif defined(__has_feature) /* Clang */
315 #if __has_feature(attribute_deprecated)
316 #define DRFLAC_DEPRECATED __attribute__((deprecated))
317 #else
318 #define DRFLAC_DEPRECATED
319 #endif
320#else
321 #define DRFLAC_DEPRECATED
322#endif
323
324DRFLAC_API void drflac_version(drflac_uint32* pMajor, drflac_uint32* pMinor, drflac_uint32* pRevision);
325DRFLAC_API const char* drflac_version_string(void);
326
327/* Allocation Callbacks */
328typedef struct
329{
330 void* pUserData;
331 void* (* onMalloc)(size_t sz, void* pUserData);
332 void* (* onRealloc)(void* p, size_t sz, void* pUserData);
333 void (* onFree)(void* p, void* pUserData);
334} drflac_allocation_callbacks;
335/* End Allocation Callbacks */
336
337/*
338As data is read from the client it is placed into an internal buffer for fast access. This controls the size of that buffer. Larger values means more speed,
339but also more memory. In my testing there is diminishing returns after about 4KB, but you can fiddle with this to suit your own needs. Must be a multiple of 8.
340*/
341#ifndef DR_FLAC_BUFFER_SIZE
342#define DR_FLAC_BUFFER_SIZE 4096
343#endif
344
345
346/* Architecture Detection */
347#if defined(_WIN64) || defined(_LP64) || defined(__LP64__)
348#define DRFLAC_64BIT
349#endif
350
351#if defined(__x86_64__) || defined(_M_X64)
352 #define DRFLAC_X64
353#elif defined(__i386) || defined(_M_IX86)
354 #define DRFLAC_X86
355#elif defined(__arm__) || defined(_M_ARM) || defined(__arm64) || defined(__arm64__) || defined(__aarch64__) || defined(_M_ARM64)
356 #define DRFLAC_ARM
357#endif
358/* End Architecture Detection */
359
360
361#ifdef DRFLAC_64BIT
362typedef drflac_uint64 drflac_cache_t;
363#else
364typedef drflac_uint32 drflac_cache_t;
365#endif
366
367/* The various metadata block types. */
368#define DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO 0
369#define DRFLAC_METADATA_BLOCK_TYPE_PADDING 1
370#define DRFLAC_METADATA_BLOCK_TYPE_APPLICATION 2
371#define DRFLAC_METADATA_BLOCK_TYPE_SEEKTABLE 3
372#define DRFLAC_METADATA_BLOCK_TYPE_VORBIS_COMMENT 4
373#define DRFLAC_METADATA_BLOCK_TYPE_CUESHEET 5
374#define DRFLAC_METADATA_BLOCK_TYPE_PICTURE 6
375#define DRFLAC_METADATA_BLOCK_TYPE_INVALID 127
376
377/* The various picture types specified in the PICTURE block. */
378#define DRFLAC_PICTURE_TYPE_OTHER 0
379#define DRFLAC_PICTURE_TYPE_FILE_ICON 1
380#define DRFLAC_PICTURE_TYPE_OTHER_FILE_ICON 2
381#define DRFLAC_PICTURE_TYPE_COVER_FRONT 3
382#define DRFLAC_PICTURE_TYPE_COVER_BACK 4
383#define DRFLAC_PICTURE_TYPE_LEAFLET_PAGE 5
384#define DRFLAC_PICTURE_TYPE_MEDIA 6
385#define DRFLAC_PICTURE_TYPE_LEAD_ARTIST 7
386#define DRFLAC_PICTURE_TYPE_ARTIST 8
387#define DRFLAC_PICTURE_TYPE_CONDUCTOR 9
388#define DRFLAC_PICTURE_TYPE_BAND 10
389#define DRFLAC_PICTURE_TYPE_COMPOSER 11
390#define DRFLAC_PICTURE_TYPE_LYRICIST 12
391#define DRFLAC_PICTURE_TYPE_RECORDING_LOCATION 13
392#define DRFLAC_PICTURE_TYPE_DURING_RECORDING 14
393#define DRFLAC_PICTURE_TYPE_DURING_PERFORMANCE 15
394#define DRFLAC_PICTURE_TYPE_SCREEN_CAPTURE 16
395#define DRFLAC_PICTURE_TYPE_BRIGHT_COLORED_FISH 17
396#define DRFLAC_PICTURE_TYPE_ILLUSTRATION 18
397#define DRFLAC_PICTURE_TYPE_BAND_LOGOTYPE 19
398#define DRFLAC_PICTURE_TYPE_PUBLISHER_LOGOTYPE 20
399
400typedef enum
401{
402 drflac_container_native,
403 drflac_container_ogg,
404 drflac_container_unknown
405} drflac_container;
406
407typedef enum
408{
409 drflac_seek_origin_start,
410 drflac_seek_origin_current
411} drflac_seek_origin;
412
413/* The order of members in this structure is important because we map this directly to the raw data within the SEEKTABLE metadata block. */
414typedef struct
415{
416 drflac_uint64 firstPCMFrame;
417 drflac_uint64 flacFrameOffset; /* The offset from the first byte of the header of the first frame. */
418 drflac_uint16 pcmFrameCount;
419} drflac_seekpoint;
420
421typedef struct
422{
423 drflac_uint16 minBlockSizeInPCMFrames;
424 drflac_uint16 maxBlockSizeInPCMFrames;
425 drflac_uint32 minFrameSizeInPCMFrames;
426 drflac_uint32 maxFrameSizeInPCMFrames;
427 drflac_uint32 sampleRate;
428 drflac_uint8 channels;
429 drflac_uint8 bitsPerSample;
430 drflac_uint64 totalPCMFrameCount;
431 drflac_uint8 md5[16];
432} drflac_streaminfo;
433
434typedef struct
435{
436 /*
437 The metadata type. Use this to know how to interpret the data below. Will be set to one of the
438 DRFLAC_METADATA_BLOCK_TYPE_* tokens.
439 */
440 drflac_uint32 type;
441
442 /*
443 A pointer to the raw data. This points to a temporary buffer so don't hold on to it. It's best to
444 not modify the contents of this buffer. Use the structures below for more meaningful and structured
445 information about the metadata. It's possible for this to be null.
446 */
447 const void* pRawData;
448
449 /* The size in bytes of the block and the buffer pointed to by pRawData if it's non-NULL. */
450 drflac_uint32 rawDataSize;
451
452 union
453 {
454 drflac_streaminfo streaminfo;
455
456 struct
457 {
458 int unused;
459 } padding;
460
461 struct
462 {
463 drflac_uint32 id;
464 const void* pData;
465 drflac_uint32 dataSize;
466 } application;
467
468 struct
469 {
470 drflac_uint32 seekpointCount;
471 const drflac_seekpoint* pSeekpoints;
472 } seektable;
473
474 struct
475 {
476 drflac_uint32 vendorLength;
477 const char* vendor;
478 drflac_uint32 commentCount;
479 const void* pComments;
480 } vorbis_comment;
481
482 struct
483 {
484 char catalog[128];
485 drflac_uint64 leadInSampleCount;
486 drflac_bool32 isCD;
487 drflac_uint8 trackCount;
488 const void* pTrackData;
489 } cuesheet;
490
491 struct
492 {
493 drflac_uint32 type;
494 drflac_uint32 mimeLength;
495 const char* mime;
496 drflac_uint32 descriptionLength;
497 const char* description;
498 drflac_uint32 width;
499 drflac_uint32 height;
500 drflac_uint32 colorDepth;
501 drflac_uint32 indexColorCount;
502 drflac_uint32 pictureDataSize;
503 const drflac_uint8* pPictureData;
504 } picture;
505 } data;
506} drflac_metadata;
507
508
509/*
510Callback for when data needs to be read from the client.
511
512
513Parameters
514----------
515pUserData (in)
516 The user data that was passed to drflac_open() and family.
517
518pBufferOut (out)
519 The output buffer.
520
521bytesToRead (in)
522 The number of bytes to read.
523
524
525Return Value
526------------
527The number of bytes actually read.
528
529
530Remarks
531-------
532A return value of less than bytesToRead indicates the end of the stream. Do _not_ return from this callback until either the entire bytesToRead is filled or
533you have reached the end of the stream.
534*/
535typedef size_t (* drflac_read_proc)(void* pUserData, void* pBufferOut, size_t bytesToRead);
536
537/*
538Callback for when data needs to be seeked.
539
540
541Parameters
542----------
543pUserData (in)
544 The user data that was passed to drflac_open() and family.
545
546offset (in)
547 The number of bytes to move, relative to the origin. Will never be negative.
548
549origin (in)
550 The origin of the seek - the current position or the start of the stream.
551
552
553Return Value
554------------
555Whether or not the seek was successful.
556
557
558Remarks
559-------
560The offset will never be negative. Whether or not it is relative to the beginning or current position is determined by the "origin" parameter which will be
561either drflac_seek_origin_start or drflac_seek_origin_current.
562
563When seeking to a PCM frame using drflac_seek_to_pcm_frame(), dr_flac may call this with an offset beyond the end of the FLAC stream. This needs to be detected
564and handled by returning DRFLAC_FALSE.
565*/
566typedef drflac_bool32 (* drflac_seek_proc)(void* pUserData, int offset, drflac_seek_origin origin);
567
568/*
569Callback for when a metadata block is read.
570
571
572Parameters
573----------
574pUserData (in)
575 The user data that was passed to drflac_open() and family.
576
577pMetadata (in)
578 A pointer to a structure containing the data of the metadata block.
579
580
581Remarks
582-------
583Use pMetadata->type to determine which metadata block is being handled and how to read the data. This
584will be set to one of the DRFLAC_METADATA_BLOCK_TYPE_* tokens.
585*/
586typedef void (* drflac_meta_proc)(void* pUserData, drflac_metadata* pMetadata);
587
588
589/* Structure for internal use. Only used for decoders opened with drflac_open_memory. */
590typedef struct
591{
592 const drflac_uint8* data;
593 size_t dataSize;
594 size_t currentReadPos;
595} drflac__memory_stream;
596
597/* Structure for internal use. Used for bit streaming. */
598typedef struct
599{
600 /* The function to call when more data needs to be read. */
601 drflac_read_proc onRead;
602
603 /* The function to call when the current read position needs to be moved. */
604 drflac_seek_proc onSeek;
605
606 /* The user data to pass around to onRead and onSeek. */
607 void* pUserData;
608
609
610 /*
611 The number of unaligned bytes in the L2 cache. This will always be 0 until the end of the stream is hit. At the end of the
612 stream there will be a number of bytes that don't cleanly fit in an L1 cache line, so we use this variable to know whether
613 or not the bistreamer needs to run on a slower path to read those last bytes. This will never be more than sizeof(drflac_cache_t).
614 */
615 size_t unalignedByteCount;
616
617 /* The content of the unaligned bytes. */
618 drflac_cache_t unalignedCache;
619
620 /* The index of the next valid cache line in the "L2" cache. */
621 drflac_uint32 nextL2Line;
622
623 /* The number of bits that have been consumed by the cache. This is used to determine how many valid bits are remaining. */
624 drflac_uint32 consumedBits;
625
626 /*
627 The cached data which was most recently read from the client. There are two levels of cache. Data flows as such:
628 Client -> L2 -> L1. The L2 -> L1 movement is aligned and runs on a fast path in just a few instructions.
629 */
630 drflac_cache_t cacheL2[DR_FLAC_BUFFER_SIZE/sizeof(drflac_cache_t)];
631 drflac_cache_t cache;
632
633 /*
634 CRC-16. This is updated whenever bits are read from the bit stream. Manually set this to 0 to reset the CRC. For FLAC, this
635 is reset to 0 at the beginning of each frame.
636 */
637 drflac_uint16 crc16;
638 drflac_cache_t crc16Cache; /* A cache for optimizing CRC calculations. This is filled when when the L1 cache is reloaded. */
639 drflac_uint32 crc16CacheIgnoredBytes; /* The number of bytes to ignore when updating the CRC-16 from the CRC-16 cache. */
640} drflac_bs;
641
642typedef struct
643{
644 /* The type of the subframe: SUBFRAME_CONSTANT, SUBFRAME_VERBATIM, SUBFRAME_FIXED or SUBFRAME_LPC. */
645 drflac_uint8 subframeType;
646
647 /* The number of wasted bits per sample as specified by the sub-frame header. */
648 drflac_uint8 wastedBitsPerSample;
649
650 /* The order to use for the prediction stage for SUBFRAME_FIXED and SUBFRAME_LPC. */
651 drflac_uint8 lpcOrder;
652
653 /* A pointer to the buffer containing the decoded samples in the subframe. This pointer is an offset from drflac::pExtraData. */
654 drflac_int32* pSamplesS32;
655} drflac_subframe;
656
657typedef struct
658{
659 /*
660 If the stream uses variable block sizes, this will be set to the index of the first PCM frame. If fixed block sizes are used, this will
661 always be set to 0. This is 64-bit because the decoded PCM frame number will be 36 bits.
662 */
663 drflac_uint64 pcmFrameNumber;
664
665 /*
666 If the stream uses fixed block sizes, this will be set to the frame number. If variable block sizes are used, this will always be 0. This
667 is 32-bit because in fixed block sizes, the maximum frame number will be 31 bits.
668 */
669 drflac_uint32 flacFrameNumber;
670
671 /* The sample rate of this frame. */
672 drflac_uint32 sampleRate;
673
674 /* The number of PCM frames in each sub-frame within this frame. */
675 drflac_uint16 blockSizeInPCMFrames;
676
677 /*
678 The channel assignment of this frame. This is not always set to the channel count. If interchannel decorrelation is being used this
679 will be set to DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE, DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE or DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE.
680 */
681 drflac_uint8 channelAssignment;
682
683 /* The number of bits per sample within this frame. */
684 drflac_uint8 bitsPerSample;
685
686 /* The frame's CRC. */
687 drflac_uint8 crc8;
688} drflac_frame_header;
689
690typedef struct
691{
692 /* The header. */
693 drflac_frame_header header;
694
695 /*
696 The number of PCM frames left to be read in this FLAC frame. This is initially set to the block size. As PCM frames are read,
697 this will be decremented. When it reaches 0, the decoder will see this frame as fully consumed and load the next frame.
698 */
699 drflac_uint32 pcmFramesRemaining;
700
701 /* The list of sub-frames within the frame. There is one sub-frame for each channel, and there's a maximum of 8 channels. */
702 drflac_subframe subframes[8];
703} drflac_frame;
704
705typedef struct
706{
707 /* The function to call when a metadata block is read. */
708 drflac_meta_proc onMeta;
709
710 /* The user data posted to the metadata callback function. */
711 void* pUserDataMD;
712
713 /* Memory allocation callbacks. */
714 drflac_allocation_callbacks allocationCallbacks;
715
716
717 /* The sample rate. Will be set to something like 44100. */
718 drflac_uint32 sampleRate;
719
720 /*
721 The number of channels. This will be set to 1 for monaural streams, 2 for stereo, etc. Maximum 8. This is set based on the
722 value specified in the STREAMINFO block.
723 */
724 drflac_uint8 channels;
725
726 /* The bits per sample. Will be set to something like 16, 24, etc. */
727 drflac_uint8 bitsPerSample;
728
729 /* The maximum block size, in samples. This number represents the number of samples in each channel (not combined). */
730 drflac_uint16 maxBlockSizeInPCMFrames;
731
732 /*
733 The total number of PCM Frames making up the stream. Can be 0 in which case it's still a valid stream, but just means
734 the total PCM frame count is unknown. Likely the case with streams like internet radio.
735 */
736 drflac_uint64 totalPCMFrameCount;
737
738
739 /* The container type. This is set based on whether or not the decoder was opened from a native or Ogg stream. */
740 drflac_container container;
741
742 /* The number of seekpoints in the seektable. */
743 drflac_uint32 seekpointCount;
744
745
746 /* Information about the frame the decoder is currently sitting on. */
747 drflac_frame currentFLACFrame;
748
749
750 /* The index of the PCM frame the decoder is currently sitting on. This is only used for seeking. */
751 drflac_uint64 currentPCMFrame;
752
753 /* The position of the first FLAC frame in the stream. This is only ever used for seeking. */
754 drflac_uint64 firstFLACFramePosInBytes;
755
756
757 /* A hack to avoid a malloc() when opening a decoder with drflac_open_memory(). */
758 drflac__memory_stream memoryStream;
759
760
761 /* A pointer to the decoded sample data. This is an offset of pExtraData. */
762 drflac_int32* pDecodedSamples;
763
764 /* A pointer to the seek table. This is an offset of pExtraData, or NULL if there is no seek table. */
765 drflac_seekpoint* pSeekpoints;
766
767 /* Internal use only. Only used with Ogg containers. Points to a drflac_oggbs object. This is an offset of pExtraData. */
768 void* _oggbs;
769
770 /* Internal use only. Used for profiling and testing different seeking modes. */
771 drflac_bool32 _noSeekTableSeek : 1;
772 drflac_bool32 _noBinarySearchSeek : 1;
773 drflac_bool32 _noBruteForceSeek : 1;
774
775 /* The bit streamer. The raw FLAC data is fed through this object. */
776 drflac_bs bs;
777
778 /* Variable length extra data. We attach this to the end of the object so we can avoid unnecessary mallocs. */
779 drflac_uint8 pExtraData[1];
780} drflac;
781
782
783/*
784Opens a FLAC decoder.
785
786
787Parameters
788----------
789onRead (in)
790 The function to call when data needs to be read from the client.
791
792onSeek (in)
793 The function to call when the read position of the client data needs to move.
794
795pUserData (in, optional)
796 A pointer to application defined data that will be passed to onRead and onSeek.
797
798pAllocationCallbacks (in, optional)
799 A pointer to application defined callbacks for managing memory allocations.
800
801
802Return Value
803------------
804Returns a pointer to an object representing the decoder.
805
806
807Remarks
808-------
809Close the decoder with `drflac_close()`.
810
811`pAllocationCallbacks` can be NULL in which case it will use `DRFLAC_MALLOC`, `DRFLAC_REALLOC` and `DRFLAC_FREE`.
812
813This function will automatically detect whether or not you are attempting to open a native or Ogg encapsulated FLAC, both of which should work seamlessly
814without any manual intervention. Ogg encapsulation also works with multiplexed streams which basically means it can play FLAC encoded audio tracks in videos.
815
816This is the lowest level function for opening a FLAC stream. You can also use `drflac_open_file()` and `drflac_open_memory()` to open the stream from a file or
817from a block of memory respectively.
818
819The STREAMINFO block must be present for this to succeed. Use `drflac_open_relaxed()` to open a FLAC stream where the header may not be present.
820
821Use `drflac_open_with_metadata()` if you need access to metadata.
822
823
824Seek Also
825---------
826drflac_open_file()
827drflac_open_memory()
828drflac_open_with_metadata()
829drflac_close()
830*/
831DRFLAC_API drflac* drflac_open(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
832
833/*
834Opens a FLAC stream with relaxed validation of the header block.
835
836
837Parameters
838----------
839onRead (in)
840 The function to call when data needs to be read from the client.
841
842onSeek (in)
843 The function to call when the read position of the client data needs to move.
844
845container (in)
846 Whether or not the FLAC stream is encapsulated using standard FLAC encapsulation or Ogg encapsulation.
847
848pUserData (in, optional)
849 A pointer to application defined data that will be passed to onRead and onSeek.
850
851pAllocationCallbacks (in, optional)
852 A pointer to application defined callbacks for managing memory allocations.
853
854
855Return Value
856------------
857A pointer to an object representing the decoder.
858
859
860Remarks
861-------
862The same as drflac_open(), except attempts to open the stream even when a header block is not present.
863
864Because the header is not necessarily available, the caller must explicitly define the container (Native or Ogg). Do not set this to `drflac_container_unknown`
865as that is for internal use only.
866
867Opening in relaxed mode will continue reading data from onRead until it finds a valid frame. If a frame is never found it will continue forever. To abort,
868force your `onRead` callback to return 0, which dr_flac will use as an indicator that the end of the stream was found.
869
870Use `drflac_open_with_metadata_relaxed()` if you need access to metadata.
871*/
872DRFLAC_API drflac* drflac_open_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_container container, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
873
874/*
875Opens a FLAC decoder and notifies the caller of the metadata chunks (album art, etc.).
876
877
878Parameters
879----------
880onRead (in)
881 The function to call when data needs to be read from the client.
882
883onSeek (in)
884 The function to call when the read position of the client data needs to move.
885
886onMeta (in)
887 The function to call for every metadata block.
888
889pUserData (in, optional)
890 A pointer to application defined data that will be passed to onRead, onSeek and onMeta.
891
892pAllocationCallbacks (in, optional)
893 A pointer to application defined callbacks for managing memory allocations.
894
895
896Return Value
897------------
898A pointer to an object representing the decoder.
899
900
901Remarks
902-------
903Close the decoder with `drflac_close()`.
904
905`pAllocationCallbacks` can be NULL in which case it will use `DRFLAC_MALLOC`, `DRFLAC_REALLOC` and `DRFLAC_FREE`.
906
907This is slower than `drflac_open()`, so avoid this one if you don't need metadata. Internally, this will allocate and free memory on the heap for every
908metadata block except for STREAMINFO and PADDING blocks.
909
910The caller is notified of the metadata via the `onMeta` callback. All metadata blocks will be handled before the function returns. This callback takes a
911pointer to a `drflac_metadata` object which is a union containing the data of all relevant metadata blocks. Use the `type` member to discriminate against
912the different metadata types.
913
914The STREAMINFO block must be present for this to succeed. Use `drflac_open_with_metadata_relaxed()` to open a FLAC stream where the header may not be present.
915
916Note that this will behave inconsistently with `drflac_open()` if the stream is an Ogg encapsulated stream and a metadata block is corrupted. This is due to
917the way the Ogg stream recovers from corrupted pages. When `drflac_open_with_metadata()` is being used, the open routine will try to read the contents of the
918metadata block, whereas `drflac_open()` will simply seek past it (for the sake of efficiency). This inconsistency can result in different samples being
919returned depending on whether or not the stream is being opened with metadata.
920
921
922Seek Also
923---------
924drflac_open_file_with_metadata()
925drflac_open_memory_with_metadata()
926drflac_open()
927drflac_close()
928*/
929DRFLAC_API drflac* drflac_open_with_metadata(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
930
931/*
932The same as drflac_open_with_metadata(), except attempts to open the stream even when a header block is not present.
933
934See Also
935--------
936drflac_open_with_metadata()
937drflac_open_relaxed()
938*/
939DRFLAC_API drflac* drflac_open_with_metadata_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, drflac_container container, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
940
941/*
942Closes the given FLAC decoder.
943
944
945Parameters
946----------
947pFlac (in)
948 The decoder to close.
949
950
951Remarks
952-------
953This will destroy the decoder object.
954
955
956See Also
957--------
958drflac_open()
959drflac_open_with_metadata()
960drflac_open_file()
961drflac_open_file_w()
962drflac_open_file_with_metadata()
963drflac_open_file_with_metadata_w()
964drflac_open_memory()
965drflac_open_memory_with_metadata()
966*/
967DRFLAC_API void drflac_close(drflac* pFlac);
968
969
970/*
971Reads sample data from the given FLAC decoder, output as interleaved signed 32-bit PCM.
972
973
974Parameters
975----------
976pFlac (in)
977 The decoder.
978
979framesToRead (in)
980 The number of PCM frames to read.
981
982pBufferOut (out, optional)
983 A pointer to the buffer that will receive the decoded samples.
984
985
986Return Value
987------------
988Returns the number of PCM frames actually read. If the return value is less than `framesToRead` it has reached the end.
989
990
991Remarks
992-------
993pBufferOut can be null, in which case the call will act as a seek, and the return value will be the number of frames seeked.
994*/
995DRFLAC_API drflac_uint64 drflac_read_pcm_frames_s32(drflac* pFlac, drflac_uint64 framesToRead, drflac_int32* pBufferOut);
996
997
998/*
999Reads sample data from the given FLAC decoder, output as interleaved signed 16-bit PCM.
1000
1001
1002Parameters
1003----------
1004pFlac (in)
1005 The decoder.
1006
1007framesToRead (in)
1008 The number of PCM frames to read.
1009
1010pBufferOut (out, optional)
1011 A pointer to the buffer that will receive the decoded samples.
1012
1013
1014Return Value
1015------------
1016Returns the number of PCM frames actually read. If the return value is less than `framesToRead` it has reached the end.
1017
1018
1019Remarks
1020-------
1021pBufferOut can be null, in which case the call will act as a seek, and the return value will be the number of frames seeked.
1022
1023Note that this is lossy for streams where the bits per sample is larger than 16.
1024*/
1025DRFLAC_API drflac_uint64 drflac_read_pcm_frames_s16(drflac* pFlac, drflac_uint64 framesToRead, drflac_int16* pBufferOut);
1026
1027/*
1028Reads sample data from the given FLAC decoder, output as interleaved 32-bit floating point PCM.
1029
1030
1031Parameters
1032----------
1033pFlac (in)
1034 The decoder.
1035
1036framesToRead (in)
1037 The number of PCM frames to read.
1038
1039pBufferOut (out, optional)
1040 A pointer to the buffer that will receive the decoded samples.
1041
1042
1043Return Value
1044------------
1045Returns the number of PCM frames actually read. If the return value is less than `framesToRead` it has reached the end.
1046
1047
1048Remarks
1049-------
1050pBufferOut can be null, in which case the call will act as a seek, and the return value will be the number of frames seeked.
1051
1052Note that this should be considered lossy due to the nature of floating point numbers not being able to exactly represent every possible number.
1053*/
1054DRFLAC_API drflac_uint64 drflac_read_pcm_frames_f32(drflac* pFlac, drflac_uint64 framesToRead, float* pBufferOut);
1055
1056/*
1057Seeks to the PCM frame at the given index.
1058
1059
1060Parameters
1061----------
1062pFlac (in)
1063 The decoder.
1064
1065pcmFrameIndex (in)
1066 The index of the PCM frame to seek to. See notes below.
1067
1068
1069Return Value
1070-------------
1071`DRFLAC_TRUE` if successful; `DRFLAC_FALSE` otherwise.
1072*/
1073DRFLAC_API drflac_bool32 drflac_seek_to_pcm_frame(drflac* pFlac, drflac_uint64 pcmFrameIndex);
1074
1075
1076
1077#ifndef DR_FLAC_NO_STDIO
1078/*
1079Opens a FLAC decoder from the file at the given path.
1080
1081
1082Parameters
1083----------
1084pFileName (in)
1085 The path of the file to open, either absolute or relative to the current directory.
1086
1087pAllocationCallbacks (in, optional)
1088 A pointer to application defined callbacks for managing memory allocations.
1089
1090
1091Return Value
1092------------
1093A pointer to an object representing the decoder.
1094
1095
1096Remarks
1097-------
1098Close the decoder with drflac_close().
1099
1100
1101Remarks
1102-------
1103This will hold a handle to the file until the decoder is closed with drflac_close(). Some platforms will restrict the number of files a process can have open
1104at any given time, so keep this mind if you have many decoders open at the same time.
1105
1106
1107See Also
1108--------
1109drflac_open_file_with_metadata()
1110drflac_open()
1111drflac_close()
1112*/
1113DRFLAC_API drflac* drflac_open_file(const char* pFileName, const drflac_allocation_callbacks* pAllocationCallbacks);
1114DRFLAC_API drflac* drflac_open_file_w(const wchar_t* pFileName, const drflac_allocation_callbacks* pAllocationCallbacks);
1115
1116/*
1117Opens a FLAC decoder from the file at the given path and notifies the caller of the metadata chunks (album art, etc.)
1118
1119
1120Parameters
1121----------
1122pFileName (in)
1123 The path of the file to open, either absolute or relative to the current directory.
1124
1125pAllocationCallbacks (in, optional)
1126 A pointer to application defined callbacks for managing memory allocations.
1127
1128onMeta (in)
1129 The callback to fire for each metadata block.
1130
1131pUserData (in)
1132 A pointer to the user data to pass to the metadata callback.
1133
1134pAllocationCallbacks (in)
1135 A pointer to application defined callbacks for managing memory allocations.
1136
1137
1138Remarks
1139-------
1140Look at the documentation for drflac_open_with_metadata() for more information on how metadata is handled.
1141
1142
1143See Also
1144--------
1145drflac_open_with_metadata()
1146drflac_open()
1147drflac_close()
1148*/
1149DRFLAC_API drflac* drflac_open_file_with_metadata(const char* pFileName, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
1150DRFLAC_API drflac* drflac_open_file_with_metadata_w(const wchar_t* pFileName, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
1151#endif
1152
1153/*
1154Opens a FLAC decoder from a pre-allocated block of memory
1155
1156
1157Parameters
1158----------
1159pData (in)
1160 A pointer to the raw encoded FLAC data.
1161
1162dataSize (in)
1163 The size in bytes of `data`.
1164
1165pAllocationCallbacks (in)
1166 A pointer to application defined callbacks for managing memory allocations.
1167
1168
1169Return Value
1170------------
1171A pointer to an object representing the decoder.
1172
1173
1174Remarks
1175-------
1176This does not create a copy of the data. It is up to the application to ensure the buffer remains valid for the lifetime of the decoder.
1177
1178
1179See Also
1180--------
1181drflac_open()
1182drflac_close()
1183*/
1184DRFLAC_API drflac* drflac_open_memory(const void* pData, size_t dataSize, const drflac_allocation_callbacks* pAllocationCallbacks);
1185
1186/*
1187Opens a FLAC decoder from a pre-allocated block of memory and notifies the caller of the metadata chunks (album art, etc.)
1188
1189
1190Parameters
1191----------
1192pData (in)
1193 A pointer to the raw encoded FLAC data.
1194
1195dataSize (in)
1196 The size in bytes of `data`.
1197
1198onMeta (in)
1199 The callback to fire for each metadata block.
1200
1201pUserData (in)
1202 A pointer to the user data to pass to the metadata callback.
1203
1204pAllocationCallbacks (in)
1205 A pointer to application defined callbacks for managing memory allocations.
1206
1207
1208Remarks
1209-------
1210Look at the documentation for drflac_open_with_metadata() for more information on how metadata is handled.
1211
1212
1213See Also
1214-------
1215drflac_open_with_metadata()
1216drflac_open()
1217drflac_close()
1218*/
1219DRFLAC_API drflac* drflac_open_memory_with_metadata(const void* pData, size_t dataSize, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
1220
1221
1222
1223/* High Level APIs */
1224
1225/*
1226Opens a FLAC stream from the given callbacks and fully decodes it in a single operation. The return value is a
1227pointer to the sample data as interleaved signed 32-bit PCM. The returned data must be freed with drflac_free().
1228
1229You can pass in custom memory allocation callbacks via the pAllocationCallbacks parameter. This can be NULL in which
1230case it will use DRFLAC_MALLOC, DRFLAC_REALLOC and DRFLAC_FREE.
1231
1232Sometimes a FLAC file won't keep track of the total sample count. In this situation the function will continuously
1233read samples into a dynamically sized buffer on the heap until no samples are left.
1234
1235Do not call this function on a broadcast type of stream (like internet radio streams and whatnot).
1236*/
1237DRFLAC_API drflac_int32* drflac_open_and_read_pcm_frames_s32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
1238
1239/* Same as drflac_open_and_read_pcm_frames_s32(), except returns signed 16-bit integer samples. */
1240DRFLAC_API drflac_int16* drflac_open_and_read_pcm_frames_s16(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
1241
1242/* Same as drflac_open_and_read_pcm_frames_s32(), except returns 32-bit floating-point samples. */
1243DRFLAC_API float* drflac_open_and_read_pcm_frames_f32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
1244
1245#ifndef DR_FLAC_NO_STDIO
1246/* Same as drflac_open_and_read_pcm_frames_s32() except opens the decoder from a file. */
1247DRFLAC_API drflac_int32* drflac_open_file_and_read_pcm_frames_s32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
1248
1249/* Same as drflac_open_file_and_read_pcm_frames_s32(), except returns signed 16-bit integer samples. */
1250DRFLAC_API drflac_int16* drflac_open_file_and_read_pcm_frames_s16(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
1251
1252/* Same as drflac_open_file_and_read_pcm_frames_s32(), except returns 32-bit floating-point samples. */
1253DRFLAC_API float* drflac_open_file_and_read_pcm_frames_f32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
1254#endif
1255
1256/* Same as drflac_open_and_read_pcm_frames_s32() except opens the decoder from a block of memory. */
1257DRFLAC_API drflac_int32* drflac_open_memory_and_read_pcm_frames_s32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
1258
1259/* Same as drflac_open_memory_and_read_pcm_frames_s32(), except returns signed 16-bit integer samples. */
1260DRFLAC_API drflac_int16* drflac_open_memory_and_read_pcm_frames_s16(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
1261
1262/* Same as drflac_open_memory_and_read_pcm_frames_s32(), except returns 32-bit floating-point samples. */
1263DRFLAC_API float* drflac_open_memory_and_read_pcm_frames_f32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
1264
1265/*
1266Frees memory that was allocated internally by dr_flac.
1267
1268Set pAllocationCallbacks to the same object that was passed to drflac_open_*_and_read_pcm_frames_*(). If you originally passed in NULL, pass in NULL for this.
1269*/
1270DRFLAC_API void drflac_free(void* p, const drflac_allocation_callbacks* pAllocationCallbacks);
1271
1272
1273/* Structure representing an iterator for vorbis comments in a VORBIS_COMMENT metadata block. */
1274typedef struct
1275{
1276 drflac_uint32 countRemaining;
1277 const char* pRunningData;
1278} drflac_vorbis_comment_iterator;
1279
1280/*
1281Initializes a vorbis comment iterator. This can be used for iterating over the vorbis comments in a VORBIS_COMMENT
1282metadata block.
1283*/
1284DRFLAC_API void drflac_init_vorbis_comment_iterator(drflac_vorbis_comment_iterator* pIter, drflac_uint32 commentCount, const void* pComments);
1285
1286/*
1287Goes to the next vorbis comment in the given iterator. If null is returned it means there are no more comments. The
1288returned string is NOT null terminated.
1289*/
1290DRFLAC_API const char* drflac_next_vorbis_comment(drflac_vorbis_comment_iterator* pIter, drflac_uint32* pCommentLengthOut);
1291
1292
1293/* Structure representing an iterator for cuesheet tracks in a CUESHEET metadata block. */
1294typedef struct
1295{
1296 drflac_uint32 countRemaining;
1297 const char* pRunningData;
1298} drflac_cuesheet_track_iterator;
1299
1300/* The order of members here is important because we map this directly to the raw data within the CUESHEET metadata block. */
1301typedef struct
1302{
1303 drflac_uint64 offset;
1304 drflac_uint8 index;
1305 drflac_uint8 reserved[3];
1306} drflac_cuesheet_track_index;
1307
1308typedef struct
1309{
1310 drflac_uint64 offset;
1311 drflac_uint8 trackNumber;
1312 char ISRC[12];
1313 drflac_bool8 isAudio;
1314 drflac_bool8 preEmphasis;
1315 drflac_uint8 indexCount;
1316 const drflac_cuesheet_track_index* pIndexPoints;
1317} drflac_cuesheet_track;
1318
1319/*
1320Initializes a cuesheet track iterator. This can be used for iterating over the cuesheet tracks in a CUESHEET metadata
1321block.
1322*/
1323DRFLAC_API void drflac_init_cuesheet_track_iterator(drflac_cuesheet_track_iterator* pIter, drflac_uint32 trackCount, const void* pTrackData);
1324
1325/* Goes to the next cuesheet track in the given iterator. If DRFLAC_FALSE is returned it means there are no more comments. */
1326DRFLAC_API drflac_bool32 drflac_next_cuesheet_track(drflac_cuesheet_track_iterator* pIter, drflac_cuesheet_track* pCuesheetTrack);
1327
1328
1329#ifdef __cplusplus
1330}
1331#endif
1332#endif /* dr_flac_h */
1333
1334
1335/************************************************************************************************************************************************************
1336 ************************************************************************************************************************************************************
1337
1338 IMPLEMENTATION
1339
1340 ************************************************************************************************************************************************************
1341 ************************************************************************************************************************************************************/
1342#if defined(DR_FLAC_IMPLEMENTATION) || defined(DRFLAC_IMPLEMENTATION)
1343#ifndef dr_flac_c
1344#define dr_flac_c
1345
1346/* Disable some annoying warnings. */
1347#if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
1348 #pragma GCC diagnostic push
1349 #if __GNUC__ >= 7
1350 #pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
1351 #endif
1352#endif
1353
1354#ifdef __linux__
1355 #ifndef _BSD_SOURCE
1356 #define _BSD_SOURCE
1357 #endif
1358 #ifndef _DEFAULT_SOURCE
1359 #define _DEFAULT_SOURCE
1360 #endif
1361 #ifndef __USE_BSD
1362 #define __USE_BSD
1363 #endif
1364 #include <endian.h>
1365#endif
1366
1367#include <stdlib.h>
1368#include <string.h>
1369
1370/* Inline */
1371#ifdef _MSC_VER
1372 #define DRFLAC_INLINE __forceinline
1373#elif defined(__GNUC__)
1374 /*
1375 I've had a bug report where GCC is emitting warnings about functions possibly not being inlineable. This warning happens when
1376 the __attribute__((always_inline)) attribute is defined without an "inline" statement. I think therefore there must be some
1377 case where "__inline__" is not always defined, thus the compiler emitting these warnings. When using -std=c89 or -ansi on the
1378 command line, we cannot use the "inline" keyword and instead need to use "__inline__". In an attempt to work around this issue
1379 I am using "__inline__" only when we're compiling in strict ANSI mode.
1380 */
1381 #if defined(__STRICT_ANSI__)
1382 #define DRFLAC_GNUC_INLINE_HINT __inline__
1383 #else
1384 #define DRFLAC_GNUC_INLINE_HINT inline
1385 #endif
1386
1387 #if (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 2)) || defined(__clang__)
1388 #define DRFLAC_INLINE DRFLAC_GNUC_INLINE_HINT __attribute__((always_inline))
1389 #else
1390 #define DRFLAC_INLINE DRFLAC_GNUC_INLINE_HINT
1391 #endif
1392#elif defined(__WATCOMC__)
1393 #define DRFLAC_INLINE __inline
1394#else
1395 #define DRFLAC_INLINE
1396#endif
1397/* End Inline */
1398
1399/*
1400Intrinsics Support
1401
1402There's a bug in GCC 4.2.x which results in an incorrect compilation error when using _mm_slli_epi32() where it complains with
1403
1404 "error: shift must be an immediate"
1405
1406Unfortuantely dr_flac depends on this for a few things so we're just going to disable SSE on GCC 4.2 and below.
1407*/
1408#if !defined(DR_FLAC_NO_SIMD)
1409 #if defined(DRFLAC_X64) || defined(DRFLAC_X86)
1410 #if defined(_MSC_VER) && !defined(__clang__)
1411 /* MSVC. */
1412 #if _MSC_VER >= 1400 && !defined(DRFLAC_NO_SSE2) /* 2005 */
1413 #define DRFLAC_SUPPORT_SSE2
1414 #endif
1415 #if _MSC_VER >= 1600 && !defined(DRFLAC_NO_SSE41) /* 2010 */
1416 #define DRFLAC_SUPPORT_SSE41
1417 #endif
1418 #elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)))
1419 /* Assume GNUC-style. */
1420 #if defined(__SSE2__) && !defined(DRFLAC_NO_SSE2)
1421 #define DRFLAC_SUPPORT_SSE2
1422 #endif
1423 #if defined(__SSE4_1__) && !defined(DRFLAC_NO_SSE41)
1424 #define DRFLAC_SUPPORT_SSE41
1425 #endif
1426 #endif
1427
1428 /* If at this point we still haven't determined compiler support for the intrinsics just fall back to __has_include. */
1429 #if !defined(__GNUC__) && !defined(__clang__) && defined(__has_include)
1430 #if !defined(DRFLAC_SUPPORT_SSE2) && !defined(DRFLAC_NO_SSE2) && __has_include(<emmintrin.h>)
1431 #define DRFLAC_SUPPORT_SSE2
1432 #endif
1433 #if !defined(DRFLAC_SUPPORT_SSE41) && !defined(DRFLAC_NO_SSE41) && __has_include(<smmintrin.h>)
1434 #define DRFLAC_SUPPORT_SSE41
1435 #endif
1436 #endif
1437
1438 #if defined(DRFLAC_SUPPORT_SSE41)
1439 #include <smmintrin.h>
1440 #elif defined(DRFLAC_SUPPORT_SSE2)
1441 #include <emmintrin.h>
1442 #endif
1443 #endif
1444
1445 #if defined(DRFLAC_ARM)
1446 #if !defined(DRFLAC_NO_NEON) && (defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64))
1447 #define DRFLAC_SUPPORT_NEON
1448 #include <arm_neon.h>
1449 #endif
1450 #endif
1451#endif
1452
1453/* Compile-time CPU feature support. */
1454#if !defined(DR_FLAC_NO_SIMD) && (defined(DRFLAC_X86) || defined(DRFLAC_X64))
1455 #if defined(_MSC_VER) && !defined(__clang__)
1456 #if _MSC_VER >= 1400
1457 #include <intrin.h>
1458 static void drflac__cpuid(int info[4], int fid)
1459 {
1460 __cpuid(info, fid);
1461 }
1462 #else
1463 #define DRFLAC_NO_CPUID
1464 #endif
1465 #else
1466 #if defined(__GNUC__) || defined(__clang__)
1467 static void drflac__cpuid(int info[4], int fid)
1468 {
1469 /*
1470 It looks like the -fPIC option uses the ebx register which GCC complains about. We can work around this by just using a different register, the
1471 specific register of which I'm letting the compiler decide on. The "k" prefix is used to specify a 32-bit register. The {...} syntax is for
1472 supporting different assembly dialects.
1473
1474 What's basically happening is that we're saving and restoring the ebx register manually.
1475 */
1476 #if defined(DRFLAC_X86) && defined(__PIC__)
1477 __asm__ __volatile__ (
1478 "xchg{l} {%%}ebx, %k1;"
1479 "cpuid;"
1480 "xchg{l} {%%}ebx, %k1;"
1481 : "=a"(info[0]), "=&r"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(fid), "c"(0)
1482 );
1483 #else
1484 __asm__ __volatile__ (
1485 "cpuid" : "=a"(info[0]), "=b"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(fid), "c"(0)
1486 );
1487 #endif
1488 }
1489 #else
1490 #define DRFLAC_NO_CPUID
1491 #endif
1492 #endif
1493#else
1494 #define DRFLAC_NO_CPUID
1495#endif
1496
1497static DRFLAC_INLINE drflac_bool32 drflac_has_sse2(void)
1498{
1499#if defined(DRFLAC_SUPPORT_SSE2)
1500 #if (defined(DRFLAC_X64) || defined(DRFLAC_X86)) && !defined(DRFLAC_NO_SSE2)
1501 #if defined(DRFLAC_X64)
1502 return DRFLAC_TRUE; /* 64-bit targets always support SSE2. */
1503 #elif (defined(_M_IX86_FP) && _M_IX86_FP == 2) || defined(__SSE2__)
1504 return DRFLAC_TRUE; /* If the compiler is allowed to freely generate SSE2 code we can assume support. */
1505 #else
1506 #if defined(DRFLAC_NO_CPUID)
1507 return DRFLAC_FALSE;
1508 #else
1509 int info[4];
1510 drflac__cpuid(info, 1);
1511 return (info[3] & (1 << 26)) != 0;
1512 #endif
1513 #endif
1514 #else
1515 return DRFLAC_FALSE; /* SSE2 is only supported on x86 and x64 architectures. */
1516 #endif
1517#else
1518 return DRFLAC_FALSE; /* No compiler support. */
1519#endif
1520}
1521
1522static DRFLAC_INLINE drflac_bool32 drflac_has_sse41(void)
1523{
1524#if defined(DRFLAC_SUPPORT_SSE41)
1525 #if (defined(DRFLAC_X64) || defined(DRFLAC_X86)) && !defined(DRFLAC_NO_SSE41)
1526 #if defined(__SSE4_1__) || defined(__AVX__)
1527 return DRFLAC_TRUE; /* If the compiler is allowed to freely generate SSE41 code we can assume support. */
1528 #else
1529 #if defined(DRFLAC_NO_CPUID)
1530 return DRFLAC_FALSE;
1531 #else
1532 int info[4];
1533 drflac__cpuid(info, 1);
1534 return (info[2] & (1 << 19)) != 0;
1535 #endif
1536 #endif
1537 #else
1538 return DRFLAC_FALSE; /* SSE41 is only supported on x86 and x64 architectures. */
1539 #endif
1540#else
1541 return DRFLAC_FALSE; /* No compiler support. */
1542#endif
1543}
1544
1545
1546#if defined(_MSC_VER) && _MSC_VER >= 1500 && (defined(DRFLAC_X86) || defined(DRFLAC_X64)) && !defined(__clang__)
1547 #define DRFLAC_HAS_LZCNT_INTRINSIC
1548#elif (defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7)))
1549 #define DRFLAC_HAS_LZCNT_INTRINSIC
1550#elif defined(__clang__)
1551 #if defined(__has_builtin)
1552 #if __has_builtin(__builtin_clzll) || __has_builtin(__builtin_clzl)
1553 #define DRFLAC_HAS_LZCNT_INTRINSIC
1554 #endif
1555 #endif
1556#endif
1557
1558#if defined(_MSC_VER) && _MSC_VER >= 1400 && !defined(__clang__)
1559 #define DRFLAC_HAS_BYTESWAP16_INTRINSIC
1560 #define DRFLAC_HAS_BYTESWAP32_INTRINSIC
1561 #define DRFLAC_HAS_BYTESWAP64_INTRINSIC
1562#elif defined(__clang__)
1563 #if defined(__has_builtin)
1564 #if __has_builtin(__builtin_bswap16)
1565 #define DRFLAC_HAS_BYTESWAP16_INTRINSIC
1566 #endif
1567 #if __has_builtin(__builtin_bswap32)
1568 #define DRFLAC_HAS_BYTESWAP32_INTRINSIC
1569 #endif
1570 #if __has_builtin(__builtin_bswap64)
1571 #define DRFLAC_HAS_BYTESWAP64_INTRINSIC
1572 #endif
1573 #endif
1574#elif defined(__GNUC__)
1575 #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
1576 #define DRFLAC_HAS_BYTESWAP32_INTRINSIC
1577 #define DRFLAC_HAS_BYTESWAP64_INTRINSIC
1578 #endif
1579 #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))
1580 #define DRFLAC_HAS_BYTESWAP16_INTRINSIC
1581 #endif
1582#elif defined(__WATCOMC__) && defined(__386__)
1583 #define DRFLAC_HAS_BYTESWAP16_INTRINSIC
1584 #define DRFLAC_HAS_BYTESWAP32_INTRINSIC
1585 #define DRFLAC_HAS_BYTESWAP64_INTRINSIC
1586 extern __inline drflac_uint16 _watcom_bswap16(drflac_uint16);
1587 extern __inline drflac_uint32 _watcom_bswap32(drflac_uint32);
1588 extern __inline drflac_uint64 _watcom_bswap64(drflac_uint64);
1589#pragma aux _watcom_bswap16 = \
1590 "xchg al, ah" \
1591 parm [ax] \
1592 value [ax] \
1593 modify nomemory;
1594#pragma aux _watcom_bswap32 = \
1595 "bswap eax" \
1596 parm [eax] \
1597 value [eax] \
1598 modify nomemory;
1599#pragma aux _watcom_bswap64 = \
1600 "bswap eax" \
1601 "bswap edx" \
1602 "xchg eax,edx" \
1603 parm [eax edx] \
1604 value [eax edx] \
1605 modify nomemory;
1606#endif
1607
1608
1609/* Standard library stuff. */
1610#ifndef DRFLAC_ASSERT
1611#include <assert.h>
1612#define DRFLAC_ASSERT(expression) assert(expression)
1613#endif
1614#ifndef DRFLAC_MALLOC
1615#define DRFLAC_MALLOC(sz) malloc((sz))
1616#endif
1617#ifndef DRFLAC_REALLOC
1618#define DRFLAC_REALLOC(p, sz) realloc((p), (sz))
1619#endif
1620#ifndef DRFLAC_FREE
1621#define DRFLAC_FREE(p) free((p))
1622#endif
1623#ifndef DRFLAC_COPY_MEMORY
1624#define DRFLAC_COPY_MEMORY(dst, src, sz) memcpy((dst), (src), (sz))
1625#endif
1626#ifndef DRFLAC_ZERO_MEMORY
1627#define DRFLAC_ZERO_MEMORY(p, sz) memset((p), 0, (sz))
1628#endif
1629#ifndef DRFLAC_ZERO_OBJECT
1630#define DRFLAC_ZERO_OBJECT(p) DRFLAC_ZERO_MEMORY((p), sizeof(*(p)))
1631#endif
1632
1633#define DRFLAC_MAX_SIMD_VECTOR_SIZE 64 /* 64 for AVX-512 in the future. */
1634
1635/* Result Codes */
1636typedef drflac_int32 drflac_result;
1637#define DRFLAC_SUCCESS 0
1638#define DRFLAC_ERROR -1 /* A generic error. */
1639#define DRFLAC_INVALID_ARGS -2
1640#define DRFLAC_INVALID_OPERATION -3
1641#define DRFLAC_OUT_OF_MEMORY -4
1642#define DRFLAC_OUT_OF_RANGE -5
1643#define DRFLAC_ACCESS_DENIED -6
1644#define DRFLAC_DOES_NOT_EXIST -7
1645#define DRFLAC_ALREADY_EXISTS -8
1646#define DRFLAC_TOO_MANY_OPEN_FILES -9
1647#define DRFLAC_INVALID_FILE -10
1648#define DRFLAC_TOO_BIG -11
1649#define DRFLAC_PATH_TOO_LONG -12
1650#define DRFLAC_NAME_TOO_LONG -13
1651#define DRFLAC_NOT_DIRECTORY -14
1652#define DRFLAC_IS_DIRECTORY -15
1653#define DRFLAC_DIRECTORY_NOT_EMPTY -16
1654#define DRFLAC_END_OF_FILE -17
1655#define DRFLAC_NO_SPACE -18
1656#define DRFLAC_BUSY -19
1657#define DRFLAC_IO_ERROR -20
1658#define DRFLAC_INTERRUPT -21
1659#define DRFLAC_UNAVAILABLE -22
1660#define DRFLAC_ALREADY_IN_USE -23
1661#define DRFLAC_BAD_ADDRESS -24
1662#define DRFLAC_BAD_SEEK -25
1663#define DRFLAC_BAD_PIPE -26
1664#define DRFLAC_DEADLOCK -27
1665#define DRFLAC_TOO_MANY_LINKS -28
1666#define DRFLAC_NOT_IMPLEMENTED -29
1667#define DRFLAC_NO_MESSAGE -30
1668#define DRFLAC_BAD_MESSAGE -31
1669#define DRFLAC_NO_DATA_AVAILABLE -32
1670#define DRFLAC_INVALID_DATA -33
1671#define DRFLAC_TIMEOUT -34
1672#define DRFLAC_NO_NETWORK -35
1673#define DRFLAC_NOT_UNIQUE -36
1674#define DRFLAC_NOT_SOCKET -37
1675#define DRFLAC_NO_ADDRESS -38
1676#define DRFLAC_BAD_PROTOCOL -39
1677#define DRFLAC_PROTOCOL_UNAVAILABLE -40
1678#define DRFLAC_PROTOCOL_NOT_SUPPORTED -41
1679#define DRFLAC_PROTOCOL_FAMILY_NOT_SUPPORTED -42
1680#define DRFLAC_ADDRESS_FAMILY_NOT_SUPPORTED -43
1681#define DRFLAC_SOCKET_NOT_SUPPORTED -44
1682#define DRFLAC_CONNECTION_RESET -45
1683#define DRFLAC_ALREADY_CONNECTED -46
1684#define DRFLAC_NOT_CONNECTED -47
1685#define DRFLAC_CONNECTION_REFUSED -48
1686#define DRFLAC_NO_HOST -49
1687#define DRFLAC_IN_PROGRESS -50
1688#define DRFLAC_CANCELLED -51
1689#define DRFLAC_MEMORY_ALREADY_MAPPED -52
1690#define DRFLAC_AT_END -53
1691
1692#define DRFLAC_CRC_MISMATCH -100
1693/* End Result Codes */
1694
1695
1696#define DRFLAC_SUBFRAME_CONSTANT 0
1697#define DRFLAC_SUBFRAME_VERBATIM 1
1698#define DRFLAC_SUBFRAME_FIXED 8
1699#define DRFLAC_SUBFRAME_LPC 32
1700#define DRFLAC_SUBFRAME_RESERVED 255
1701
1702#define DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE 0
1703#define DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2 1
1704
1705#define DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT 0
1706#define DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE 8
1707#define DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE 9
1708#define DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE 10
1709
1710#define DRFLAC_SEEKPOINT_SIZE_IN_BYTES 18
1711#define DRFLAC_CUESHEET_TRACK_SIZE_IN_BYTES 36
1712#define DRFLAC_CUESHEET_TRACK_INDEX_SIZE_IN_BYTES 12
1713
1714#define drflac_align(x, a) ((((x) + (a) - 1) / (a)) * (a))
1715
1716
1717DRFLAC_API void drflac_version(drflac_uint32* pMajor, drflac_uint32* pMinor, drflac_uint32* pRevision)
1718{
1719 if (pMajor) {
1720 *pMajor = DRFLAC_VERSION_MAJOR;
1721 }
1722
1723 if (pMinor) {
1724 *pMinor = DRFLAC_VERSION_MINOR;
1725 }
1726
1727 if (pRevision) {
1728 *pRevision = DRFLAC_VERSION_REVISION;
1729 }
1730}
1731
1732DRFLAC_API const char* drflac_version_string(void)
1733{
1734 return DRFLAC_VERSION_STRING;
1735}
1736
1737
1738/* CPU caps. */
1739#if defined(__has_feature)
1740 #if __has_feature(thread_sanitizer)
1741 #define DRFLAC_NO_THREAD_SANITIZE __attribute__((no_sanitize("thread")))
1742 #else
1743 #define DRFLAC_NO_THREAD_SANITIZE
1744 #endif
1745#else
1746 #define DRFLAC_NO_THREAD_SANITIZE
1747#endif
1748
1749#if defined(DRFLAC_HAS_LZCNT_INTRINSIC)
1750static drflac_bool32 drflac__gIsLZCNTSupported = DRFLAC_FALSE;
1751#endif
1752
1753#ifndef DRFLAC_NO_CPUID
1754static drflac_bool32 drflac__gIsSSE2Supported = DRFLAC_FALSE;
1755static drflac_bool32 drflac__gIsSSE41Supported = DRFLAC_FALSE;
1756
1757/*
1758I've had a bug report that Clang's ThreadSanitizer presents a warning in this function. Having reviewed this, this does
1759actually make sense. However, since CPU caps should never differ for a running process, I don't think the trade off of
1760complicating internal API's by passing around CPU caps versus just disabling the warnings is worthwhile. I'm therefore
1761just going to disable these warnings. This is disabled via the DRFLAC_NO_THREAD_SANITIZE attribute.
1762*/
1763DRFLAC_NO_THREAD_SANITIZE static void drflac__init_cpu_caps(void)
1764{
1765 static drflac_bool32 isCPUCapsInitialized = DRFLAC_FALSE;
1766
1767 if (!isCPUCapsInitialized) {
1768 /* LZCNT */
1769#if defined(DRFLAC_HAS_LZCNT_INTRINSIC)
1770 int info[4] = {0};
1771 drflac__cpuid(info, 0x80000001);
1772 drflac__gIsLZCNTSupported = (info[2] & (1 << 5)) != 0;
1773#endif
1774
1775 /* SSE2 */
1776 drflac__gIsSSE2Supported = drflac_has_sse2();
1777
1778 /* SSE4.1 */
1779 drflac__gIsSSE41Supported = drflac_has_sse41();
1780
1781 /* Initialized. */
1782 isCPUCapsInitialized = DRFLAC_TRUE;
1783 }
1784}
1785#else
1786static drflac_bool32 drflac__gIsNEONSupported = DRFLAC_FALSE;
1787
1788static DRFLAC_INLINE drflac_bool32 drflac__has_neon(void)
1789{
1790#if defined(DRFLAC_SUPPORT_NEON)
1791 #if defined(DRFLAC_ARM) && !defined(DRFLAC_NO_NEON)
1792 #if (defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64))
1793 return DRFLAC_TRUE; /* If the compiler is allowed to freely generate NEON code we can assume support. */
1794 #else
1795 /* TODO: Runtime check. */
1796 return DRFLAC_FALSE;
1797 #endif
1798 #else
1799 return DRFLAC_FALSE; /* NEON is only supported on ARM architectures. */
1800 #endif
1801#else
1802 return DRFLAC_FALSE; /* No compiler support. */
1803#endif
1804}
1805
1806DRFLAC_NO_THREAD_SANITIZE static void drflac__init_cpu_caps(void)
1807{
1808 drflac__gIsNEONSupported = drflac__has_neon();
1809
1810#if defined(DRFLAC_HAS_LZCNT_INTRINSIC) && defined(DRFLAC_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 5)
1811 drflac__gIsLZCNTSupported = DRFLAC_TRUE;
1812#endif
1813}
1814#endif
1815
1816
1817/* Endian Management */
1818static DRFLAC_INLINE drflac_bool32 drflac__is_little_endian(void)
1819{
1820#if defined(DRFLAC_X86) || defined(DRFLAC_X64)
1821 return DRFLAC_TRUE;
1822#elif defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && __BYTE_ORDER == __LITTLE_ENDIAN
1823 return DRFLAC_TRUE;
1824#else
1825 int n = 1;
1826 return (*(char*)&n) == 1;
1827#endif
1828}
1829
1830static DRFLAC_INLINE drflac_uint16 drflac__swap_endian_uint16(drflac_uint16 n)
1831{
1832#ifdef DRFLAC_HAS_BYTESWAP16_INTRINSIC
1833 #if defined(_MSC_VER) && !defined(__clang__)
1834 return _byteswap_ushort(n);
1835 #elif defined(__GNUC__) || defined(__clang__)
1836 return __builtin_bswap16(n);
1837 #elif defined(__WATCOMC__) && defined(__386__)
1838 return _watcom_bswap16(n);
1839 #else
1840 #error "This compiler does not support the byte swap intrinsic."
1841 #endif
1842#else
1843 return ((n & 0xFF00) >> 8) |
1844 ((n & 0x00FF) << 8);
1845#endif
1846}
1847
1848static DRFLAC_INLINE drflac_uint32 drflac__swap_endian_uint32(drflac_uint32 n)
1849{
1850#ifdef DRFLAC_HAS_BYTESWAP32_INTRINSIC
1851 #if defined(_MSC_VER) && !defined(__clang__)
1852 return _byteswap_ulong(n);
1853 #elif defined(__GNUC__) || defined(__clang__)
1854 #if defined(DRFLAC_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 6) && !defined(__ARM_ARCH_6M__) && !defined(DRFLAC_64BIT) /* <-- 64-bit inline assembly has not been tested, so disabling for now. */
1855 /* Inline assembly optimized implementation for ARM. In my testing, GCC does not generate optimized code with __builtin_bswap32(). */
1856 drflac_uint32 r;
1857 __asm__ __volatile__ (
1858 #if defined(DRFLAC_64BIT)
1859 "rev %w[out], %w[in]" : [out]"=r"(r) : [in]"r"(n) /* <-- This is untested. If someone in the community could test this, that would be appreciated! */
1860 #else
1861 "rev %[out], %[in]" : [out]"=r"(r) : [in]"r"(n)
1862 #endif
1863 );
1864 return r;
1865 #else
1866 return __builtin_bswap32(n);
1867 #endif
1868 #elif defined(__WATCOMC__) && defined(__386__)
1869 return _watcom_bswap32(n);
1870 #else
1871 #error "This compiler does not support the byte swap intrinsic."
1872 #endif
1873#else
1874 return ((n & 0xFF000000) >> 24) |
1875 ((n & 0x00FF0000) >> 8) |
1876 ((n & 0x0000FF00) << 8) |
1877 ((n & 0x000000FF) << 24);
1878#endif
1879}
1880
1881static DRFLAC_INLINE drflac_uint64 drflac__swap_endian_uint64(drflac_uint64 n)
1882{
1883#ifdef DRFLAC_HAS_BYTESWAP64_INTRINSIC
1884 #if defined(_MSC_VER) && !defined(__clang__)
1885 return _byteswap_uint64(n);
1886 #elif defined(__GNUC__) || defined(__clang__)
1887 return __builtin_bswap64(n);
1888 #elif defined(__WATCOMC__) && defined(__386__)
1889 return _watcom_bswap64(n);
1890 #else
1891 #error "This compiler does not support the byte swap intrinsic."
1892 #endif
1893#else
1894 /* Weird "<< 32" bitshift is required for C89 because it doesn't support 64-bit constants. Should be optimized out by a good compiler. */
1895 return ((n & ((drflac_uint64)0xFF000000 << 32)) >> 56) |
1896 ((n & ((drflac_uint64)0x00FF0000 << 32)) >> 40) |
1897 ((n & ((drflac_uint64)0x0000FF00 << 32)) >> 24) |
1898 ((n & ((drflac_uint64)0x000000FF << 32)) >> 8) |
1899 ((n & ((drflac_uint64)0xFF000000 )) << 8) |
1900 ((n & ((drflac_uint64)0x00FF0000 )) << 24) |
1901 ((n & ((drflac_uint64)0x0000FF00 )) << 40) |
1902 ((n & ((drflac_uint64)0x000000FF )) << 56);
1903#endif
1904}
1905
1906
1907static DRFLAC_INLINE drflac_uint16 drflac__be2host_16(drflac_uint16 n)
1908{
1909 if (drflac__is_little_endian()) {
1910 return drflac__swap_endian_uint16(n);
1911 }
1912
1913 return n;
1914}
1915
1916static DRFLAC_INLINE drflac_uint32 drflac__be2host_32(drflac_uint32 n)
1917{
1918 if (drflac__is_little_endian()) {
1919 return drflac__swap_endian_uint32(n);
1920 }
1921
1922 return n;
1923}
1924
1925static DRFLAC_INLINE drflac_uint32 drflac__be2host_32_ptr_unaligned(const void* pData)
1926{
1927 const drflac_uint8* pNum = (drflac_uint8*)pData;
1928 return *(pNum) << 24 | *(pNum+1) << 16 | *(pNum+2) << 8 | *(pNum+3);
1929}
1930
1931static DRFLAC_INLINE drflac_uint64 drflac__be2host_64(drflac_uint64 n)
1932{
1933 if (drflac__is_little_endian()) {
1934 return drflac__swap_endian_uint64(n);
1935 }
1936
1937 return n;
1938}
1939
1940
1941static DRFLAC_INLINE drflac_uint32 drflac__le2host_32(drflac_uint32 n)
1942{
1943 if (!drflac__is_little_endian()) {
1944 return drflac__swap_endian_uint32(n);
1945 }
1946
1947 return n;
1948}
1949
1950static DRFLAC_INLINE drflac_uint32 drflac__le2host_32_ptr_unaligned(const void* pData)
1951{
1952 const drflac_uint8* pNum = (drflac_uint8*)pData;
1953 return *pNum | *(pNum+1) << 8 | *(pNum+2) << 16 | *(pNum+3) << 24;
1954}
1955
1956
1957static DRFLAC_INLINE drflac_uint32 drflac__unsynchsafe_32(drflac_uint32 n)
1958{
1959 drflac_uint32 result = 0;
1960 result |= (n & 0x7F000000) >> 3;
1961 result |= (n & 0x007F0000) >> 2;
1962 result |= (n & 0x00007F00) >> 1;
1963 result |= (n & 0x0000007F) >> 0;
1964
1965 return result;
1966}
1967
1968
1969
1970/* The CRC code below is based on this document: http://zlib.net/crc_v3.txt */
1971static drflac_uint8 drflac__crc8_table[] = {
1972 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15, 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
1973 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65, 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
1974 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5, 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
1975 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85, 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
1976 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2, 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
1977 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2, 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
1978 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32, 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
1979 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42, 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
1980 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C, 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
1981 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC, 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
1982 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C, 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
1983 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C, 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
1984 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B, 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
1985 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B, 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
1986 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB, 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
1987 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB, 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
1988};
1989
1990static drflac_uint16 drflac__crc16_table[] = {
1991 0x0000, 0x8005, 0x800F, 0x000A, 0x801B, 0x001E, 0x0014, 0x8011,
1992 0x8033, 0x0036, 0x003C, 0x8039, 0x0028, 0x802D, 0x8027, 0x0022,
1993 0x8063, 0x0066, 0x006C, 0x8069, 0x0078, 0x807D, 0x8077, 0x0072,
1994 0x0050, 0x8055, 0x805F, 0x005A, 0x804B, 0x004E, 0x0044, 0x8041,
1995 0x80C3, 0x00C6, 0x00CC, 0x80C9, 0x00D8, 0x80DD, 0x80D7, 0x00D2,
1996 0x00F0, 0x80F5, 0x80FF, 0x00FA, 0x80EB, 0x00EE, 0x00E4, 0x80E1,
1997 0x00A0, 0x80A5, 0x80AF, 0x00AA, 0x80BB, 0x00BE, 0x00B4, 0x80B1,
1998 0x8093, 0x0096, 0x009C, 0x8099, 0x0088, 0x808D, 0x8087, 0x0082,
1999 0x8183, 0x0186, 0x018C, 0x8189, 0x0198, 0x819D, 0x8197, 0x0192,
2000 0x01B0, 0x81B5, 0x81BF, 0x01BA, 0x81AB, 0x01AE, 0x01A4, 0x81A1,
2001 0x01E0, 0x81E5, 0x81EF, 0x01EA, 0x81FB, 0x01FE, 0x01F4, 0x81F1,
2002 0x81D3, 0x01D6, 0x01DC, 0x81D9, 0x01C8, 0x81CD, 0x81C7, 0x01C2,
2003 0x0140, 0x8145, 0x814F, 0x014A, 0x815B, 0x015E, 0x0154, 0x8151,
2004 0x8173, 0x0176, 0x017C, 0x8179, 0x0168, 0x816D, 0x8167, 0x0162,
2005 0x8123, 0x0126, 0x012C, 0x8129, 0x0138, 0x813D, 0x8137, 0x0132,
2006 0x0110, 0x8115, 0x811F, 0x011A, 0x810B, 0x010E, 0x0104, 0x8101,
2007 0x8303, 0x0306, 0x030C, 0x8309, 0x0318, 0x831D, 0x8317, 0x0312,
2008 0x0330, 0x8335, 0x833F, 0x033A, 0x832B, 0x032E, 0x0324, 0x8321,
2009 0x0360, 0x8365, 0x836F, 0x036A, 0x837B, 0x037E, 0x0374, 0x8371,
2010 0x8353, 0x0356, 0x035C, 0x8359, 0x0348, 0x834D, 0x8347, 0x0342,
2011 0x03C0, 0x83C5, 0x83CF, 0x03CA, 0x83DB, 0x03DE, 0x03D4, 0x83D1,
2012 0x83F3, 0x03F6, 0x03FC, 0x83F9, 0x03E8, 0x83ED, 0x83E7, 0x03E2,
2013 0x83A3, 0x03A6, 0x03AC, 0x83A9, 0x03B8, 0x83BD, 0x83B7, 0x03B2,
2014 0x0390, 0x8395, 0x839F, 0x039A, 0x838B, 0x038E, 0x0384, 0x8381,
2015 0x0280, 0x8285, 0x828F, 0x028A, 0x829B, 0x029E, 0x0294, 0x8291,
2016 0x82B3, 0x02B6, 0x02BC, 0x82B9, 0x02A8, 0x82AD, 0x82A7, 0x02A2,
2017 0x82E3, 0x02E6, 0x02EC, 0x82E9, 0x02F8, 0x82FD, 0x82F7, 0x02F2,
2018 0x02D0, 0x82D5, 0x82DF, 0x02DA, 0x82CB, 0x02CE, 0x02C4, 0x82C1,
2019 0x8243, 0x0246, 0x024C, 0x8249, 0x0258, 0x825D, 0x8257, 0x0252,
2020 0x0270, 0x8275, 0x827F, 0x027A, 0x826B, 0x026E, 0x0264, 0x8261,
2021 0x0220, 0x8225, 0x822F, 0x022A, 0x823B, 0x023E, 0x0234, 0x8231,
2022 0x8213, 0x0216, 0x021C, 0x8219, 0x0208, 0x820D, 0x8207, 0x0202
2023};
2024
2025static DRFLAC_INLINE drflac_uint8 drflac_crc8_byte(drflac_uint8 crc, drflac_uint8 data)
2026{
2027 return drflac__crc8_table[crc ^ data];
2028}
2029
2030static DRFLAC_INLINE drflac_uint8 drflac_crc8(drflac_uint8 crc, drflac_uint32 data, drflac_uint32 count)
2031{
2032#ifdef DR_FLAC_NO_CRC
2033 (void)crc;
2034 (void)data;
2035 (void)count;
2036 return 0;
2037#else
2038#if 0
2039 /* REFERENCE (use of this implementation requires an explicit flush by doing "drflac_crc8(crc, 0, 8);") */
2040 drflac_uint8 p = 0x07;
2041 for (int i = count-1; i >= 0; --i) {
2042 drflac_uint8 bit = (data & (1 << i)) >> i;
2043 if (crc & 0x80) {
2044 crc = ((crc << 1) | bit) ^ p;
2045 } else {
2046 crc = ((crc << 1) | bit);
2047 }
2048 }
2049 return crc;
2050#else
2051 drflac_uint32 wholeBytes;
2052 drflac_uint32 leftoverBits;
2053 drflac_uint64 leftoverDataMask;
2054
2055 static drflac_uint64 leftoverDataMaskTable[8] = {
2056 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F
2057 };
2058
2059 DRFLAC_ASSERT(count <= 32);
2060
2061 wholeBytes = count >> 3;
2062 leftoverBits = count - (wholeBytes*8);
2063 leftoverDataMask = leftoverDataMaskTable[leftoverBits];
2064
2065 switch (wholeBytes) {
2066 case 4: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0xFF000000UL << leftoverBits)) >> (24 + leftoverBits)));
2067 case 3: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0x00FF0000UL << leftoverBits)) >> (16 + leftoverBits)));
2068 case 2: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0x0000FF00UL << leftoverBits)) >> ( 8 + leftoverBits)));
2069 case 1: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0x000000FFUL << leftoverBits)) >> ( 0 + leftoverBits)));
2070 case 0: if (leftoverBits > 0) crc = (drflac_uint8)((crc << leftoverBits) ^ drflac__crc8_table[(crc >> (8 - leftoverBits)) ^ (data & leftoverDataMask)]);
2071 }
2072 return crc;
2073#endif
2074#endif
2075}
2076
2077static DRFLAC_INLINE drflac_uint16 drflac_crc16_byte(drflac_uint16 crc, drflac_uint8 data)
2078{
2079 return (crc << 8) ^ drflac__crc16_table[(drflac_uint8)(crc >> 8) ^ data];
2080}
2081
2082static DRFLAC_INLINE drflac_uint16 drflac_crc16_cache(drflac_uint16 crc, drflac_cache_t data)
2083{
2084#ifdef DRFLAC_64BIT
2085 crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 56) & 0xFF));
2086 crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 48) & 0xFF));
2087 crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 40) & 0xFF));
2088 crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 32) & 0xFF));
2089#endif
2090 crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 24) & 0xFF));
2091 crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 16) & 0xFF));
2092 crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 8) & 0xFF));
2093 crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 0) & 0xFF));
2094
2095 return crc;
2096}
2097
2098static DRFLAC_INLINE drflac_uint16 drflac_crc16_bytes(drflac_uint16 crc, drflac_cache_t data, drflac_uint32 byteCount)
2099{
2100 switch (byteCount)
2101 {
2102#ifdef DRFLAC_64BIT
2103 case 8: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 56) & 0xFF));
2104 case 7: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 48) & 0xFF));
2105 case 6: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 40) & 0xFF));
2106 case 5: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 32) & 0xFF));
2107#endif
2108 case 4: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 24) & 0xFF));
2109 case 3: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 16) & 0xFF));
2110 case 2: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 8) & 0xFF));
2111 case 1: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 0) & 0xFF));
2112 }
2113
2114 return crc;
2115}
2116
2117#if 0
2118static DRFLAC_INLINE drflac_uint16 drflac_crc16__32bit(drflac_uint16 crc, drflac_uint32 data, drflac_uint32 count)
2119{
2120#ifdef DR_FLAC_NO_CRC
2121 (void)crc;
2122 (void)data;
2123 (void)count;
2124 return 0;
2125#else
2126#if 0
2127 /* REFERENCE (use of this implementation requires an explicit flush by doing "drflac_crc16(crc, 0, 16);") */
2128 drflac_uint16 p = 0x8005;
2129 for (int i = count-1; i >= 0; --i) {
2130 drflac_uint16 bit = (data & (1ULL << i)) >> i;
2131 if (r & 0x8000) {
2132 r = ((r << 1) | bit) ^ p;
2133 } else {
2134 r = ((r << 1) | bit);
2135 }
2136 }
2137
2138 return crc;
2139#else
2140 drflac_uint32 wholeBytes;
2141 drflac_uint32 leftoverBits;
2142 drflac_uint64 leftoverDataMask;
2143
2144 static drflac_uint64 leftoverDataMaskTable[8] = {
2145 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F
2146 };
2147
2148 DRFLAC_ASSERT(count <= 64);
2149
2150 wholeBytes = count >> 3;
2151 leftoverBits = count & 7;
2152 leftoverDataMask = leftoverDataMaskTable[leftoverBits];
2153
2154 switch (wholeBytes) {
2155 default:
2156 case 4: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0xFF000000UL << leftoverBits)) >> (24 + leftoverBits)));
2157 case 3: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0x00FF0000UL << leftoverBits)) >> (16 + leftoverBits)));
2158 case 2: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0x0000FF00UL << leftoverBits)) >> ( 8 + leftoverBits)));
2159 case 1: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0x000000FFUL << leftoverBits)) >> ( 0 + leftoverBits)));
2160 case 0: if (leftoverBits > 0) crc = (crc << leftoverBits) ^ drflac__crc16_table[(crc >> (16 - leftoverBits)) ^ (data & leftoverDataMask)];
2161 }
2162 return crc;
2163#endif
2164#endif
2165}
2166
2167static DRFLAC_INLINE drflac_uint16 drflac_crc16__64bit(drflac_uint16 crc, drflac_uint64 data, drflac_uint32 count)
2168{
2169#ifdef DR_FLAC_NO_CRC
2170 (void)crc;
2171 (void)data;
2172 (void)count;
2173 return 0;
2174#else
2175 drflac_uint32 wholeBytes;
2176 drflac_uint32 leftoverBits;
2177 drflac_uint64 leftoverDataMask;
2178
2179 static drflac_uint64 leftoverDataMaskTable[8] = {
2180 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F
2181 };
2182
2183 DRFLAC_ASSERT(count <= 64);
2184
2185 wholeBytes = count >> 3;
2186 leftoverBits = count & 7;
2187 leftoverDataMask = leftoverDataMaskTable[leftoverBits];
2188
2189 switch (wholeBytes) {
2190 default:
2191 case 8: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0xFF000000 << 32) << leftoverBits)) >> (56 + leftoverBits))); /* Weird "<< 32" bitshift is required for C89 because it doesn't support 64-bit constants. Should be optimized out by a good compiler. */
2192 case 7: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x00FF0000 << 32) << leftoverBits)) >> (48 + leftoverBits)));
2193 case 6: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x0000FF00 << 32) << leftoverBits)) >> (40 + leftoverBits)));
2194 case 5: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x000000FF << 32) << leftoverBits)) >> (32 + leftoverBits)));
2195 case 4: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0xFF000000 ) << leftoverBits)) >> (24 + leftoverBits)));
2196 case 3: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x00FF0000 ) << leftoverBits)) >> (16 + leftoverBits)));
2197 case 2: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x0000FF00 ) << leftoverBits)) >> ( 8 + leftoverBits)));
2198 case 1: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x000000FF ) << leftoverBits)) >> ( 0 + leftoverBits)));
2199 case 0: if (leftoverBits > 0) crc = (crc << leftoverBits) ^ drflac__crc16_table[(crc >> (16 - leftoverBits)) ^ (data & leftoverDataMask)];
2200 }
2201 return crc;
2202#endif
2203}
2204
2205
2206static DRFLAC_INLINE drflac_uint16 drflac_crc16(drflac_uint16 crc, drflac_cache_t data, drflac_uint32 count)
2207{
2208#ifdef DRFLAC_64BIT
2209 return drflac_crc16__64bit(crc, data, count);
2210#else
2211 return drflac_crc16__32bit(crc, data, count);
2212#endif
2213}
2214#endif
2215
2216
2217#ifdef DRFLAC_64BIT
2218#define drflac__be2host__cache_line drflac__be2host_64
2219#else
2220#define drflac__be2host__cache_line drflac__be2host_32
2221#endif
2222
2223/*
2224BIT READING ATTEMPT #2
2225
2226This uses a 32- or 64-bit bit-shifted cache - as bits are read, the cache is shifted such that the first valid bit is sitting
2227on the most significant bit. It uses the notion of an L1 and L2 cache (borrowed from CPU architecture), where the L1 cache
2228is a 32- or 64-bit unsigned integer (depending on whether or not a 32- or 64-bit build is being compiled) and the L2 is an
2229array of "cache lines", with each cache line being the same size as the L1. The L2 is a buffer of about 4KB and is where data
2230from onRead() is read into.
2231*/
2232#define DRFLAC_CACHE_L1_SIZE_BYTES(bs) (sizeof((bs)->cache))
2233#define DRFLAC_CACHE_L1_SIZE_BITS(bs) (sizeof((bs)->cache)*8)
2234#define DRFLAC_CACHE_L1_BITS_REMAINING(bs) (DRFLAC_CACHE_L1_SIZE_BITS(bs) - (bs)->consumedBits)
2235#define DRFLAC_CACHE_L1_SELECTION_MASK(_bitCount) (~((~(drflac_cache_t)0) >> (_bitCount)))
2236#define DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, _bitCount) (DRFLAC_CACHE_L1_SIZE_BITS(bs) - (_bitCount))
2237#define DRFLAC_CACHE_L1_SELECT(bs, _bitCount) (((bs)->cache) & DRFLAC_CACHE_L1_SELECTION_MASK(_bitCount))
2238#define DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, _bitCount) (DRFLAC_CACHE_L1_SELECT((bs), (_bitCount)) >> DRFLAC_CACHE_L1_SELECTION_SHIFT((bs), (_bitCount)))
2239#define DRFLAC_CACHE_L1_SELECT_AND_SHIFT_SAFE(bs, _bitCount)(DRFLAC_CACHE_L1_SELECT((bs), (_bitCount)) >> (DRFLAC_CACHE_L1_SELECTION_SHIFT((bs), (_bitCount)) & (DRFLAC_CACHE_L1_SIZE_BITS(bs)-1)))
2240#define DRFLAC_CACHE_L2_SIZE_BYTES(bs) (sizeof((bs)->cacheL2))
2241#define DRFLAC_CACHE_L2_LINE_COUNT(bs) (DRFLAC_CACHE_L2_SIZE_BYTES(bs) / sizeof((bs)->cacheL2[0]))
2242#define DRFLAC_CACHE_L2_LINES_REMAINING(bs) (DRFLAC_CACHE_L2_LINE_COUNT(bs) - (bs)->nextL2Line)
2243
2244
2245#ifndef DR_FLAC_NO_CRC
2246static DRFLAC_INLINE void drflac__reset_crc16(drflac_bs* bs)
2247{
2248 bs->crc16 = 0;
2249 bs->crc16CacheIgnoredBytes = bs->consumedBits >> 3;
2250}
2251
2252static DRFLAC_INLINE void drflac__update_crc16(drflac_bs* bs)
2253{
2254 if (bs->crc16CacheIgnoredBytes == 0) {
2255 bs->crc16 = drflac_crc16_cache(bs->crc16, bs->crc16Cache);
2256 } else {
2257 bs->crc16 = drflac_crc16_bytes(bs->crc16, bs->crc16Cache, DRFLAC_CACHE_L1_SIZE_BYTES(bs) - bs->crc16CacheIgnoredBytes);
2258 bs->crc16CacheIgnoredBytes = 0;
2259 }
2260}
2261
2262static DRFLAC_INLINE drflac_uint16 drflac__flush_crc16(drflac_bs* bs)
2263{
2264 /* We should never be flushing in a situation where we are not aligned on a byte boundary. */
2265 DRFLAC_ASSERT((DRFLAC_CACHE_L1_BITS_REMAINING(bs) & 7) == 0);
2266
2267 /*
2268 The bits that were read from the L1 cache need to be accumulated. The number of bytes needing to be accumulated is determined
2269 by the number of bits that have been consumed.
2270 */
2271 if (DRFLAC_CACHE_L1_BITS_REMAINING(bs) == 0) {
2272 drflac__update_crc16(bs);
2273 } else {
2274 /* We only accumulate the consumed bits. */
2275 bs->crc16 = drflac_crc16_bytes(bs->crc16, bs->crc16Cache >> DRFLAC_CACHE_L1_BITS_REMAINING(bs), (bs->consumedBits >> 3) - bs->crc16CacheIgnoredBytes);
2276
2277 /*
2278 The bits that we just accumulated should never be accumulated again. We need to keep track of how many bytes were accumulated
2279 so we can handle that later.
2280 */
2281 bs->crc16CacheIgnoredBytes = bs->consumedBits >> 3;
2282 }
2283
2284 return bs->crc16;
2285}
2286#endif
2287
2288static DRFLAC_INLINE drflac_bool32 drflac__reload_l1_cache_from_l2(drflac_bs* bs)
2289{
2290 size_t bytesRead;
2291 size_t alignedL1LineCount;
2292
2293 /* Fast path. Try loading straight from L2. */
2294 if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
2295 bs->cache = bs->cacheL2[bs->nextL2Line++];
2296 return DRFLAC_TRUE;
2297 }
2298
2299 /*
2300 If we get here it means we've run out of data in the L2 cache. We'll need to fetch more from the client, if there's
2301 any left.
2302 */
2303 if (bs->unalignedByteCount > 0) {
2304 return DRFLAC_FALSE; /* If we have any unaligned bytes it means there's no more aligned bytes left in the client. */
2305 }
2306
2307 bytesRead = bs->onRead(bs->pUserData, bs->cacheL2, DRFLAC_CACHE_L2_SIZE_BYTES(bs));
2308
2309 bs->nextL2Line = 0;
2310 if (bytesRead == DRFLAC_CACHE_L2_SIZE_BYTES(bs)) {
2311 bs->cache = bs->cacheL2[bs->nextL2Line++];
2312 return DRFLAC_TRUE;
2313 }
2314
2315
2316 /*
2317 If we get here it means we were unable to retrieve enough data to fill the entire L2 cache. It probably
2318 means we've just reached the end of the file. We need to move the valid data down to the end of the buffer
2319 and adjust the index of the next line accordingly. Also keep in mind that the L2 cache must be aligned to
2320 the size of the L1 so we'll need to seek backwards by any misaligned bytes.
2321 */
2322 alignedL1LineCount = bytesRead / DRFLAC_CACHE_L1_SIZE_BYTES(bs);
2323
2324 /* We need to keep track of any unaligned bytes for later use. */
2325 bs->unalignedByteCount = bytesRead - (alignedL1LineCount * DRFLAC_CACHE_L1_SIZE_BYTES(bs));
2326 if (bs->unalignedByteCount > 0) {
2327 bs->unalignedCache = bs->cacheL2[alignedL1LineCount];
2328 }
2329
2330 if (alignedL1LineCount > 0) {
2331 size_t offset = DRFLAC_CACHE_L2_LINE_COUNT(bs) - alignedL1LineCount;
2332 size_t i;
2333 for (i = alignedL1LineCount; i > 0; --i) {
2334 bs->cacheL2[i-1 + offset] = bs->cacheL2[i-1];
2335 }
2336
2337 bs->nextL2Line = (drflac_uint32)offset;
2338 bs->cache = bs->cacheL2[bs->nextL2Line++];
2339 return DRFLAC_TRUE;
2340 } else {
2341 /* If we get into this branch it means we weren't able to load any L1-aligned data. */
2342 bs->nextL2Line = DRFLAC_CACHE_L2_LINE_COUNT(bs);
2343 return DRFLAC_FALSE;
2344 }
2345}
2346
2347static drflac_bool32 drflac__reload_cache(drflac_bs* bs)
2348{
2349 size_t bytesRead;
2350
2351#ifndef DR_FLAC_NO_CRC
2352 drflac__update_crc16(bs);
2353#endif
2354
2355 /* Fast path. Try just moving the next value in the L2 cache to the L1 cache. */
2356 if (drflac__reload_l1_cache_from_l2(bs)) {
2357 bs->cache = drflac__be2host__cache_line(bs->cache);
2358 bs->consumedBits = 0;
2359#ifndef DR_FLAC_NO_CRC
2360 bs->crc16Cache = bs->cache;
2361#endif
2362 return DRFLAC_TRUE;
2363 }
2364
2365 /* Slow path. */
2366
2367 /*
2368 If we get here it means we have failed to load the L1 cache from the L2. Likely we've just reached the end of the stream and the last
2369 few bytes did not meet the alignment requirements for the L2 cache. In this case we need to fall back to a slower path and read the
2370 data from the unaligned cache.
2371 */
2372 bytesRead = bs->unalignedByteCount;
2373 if (bytesRead == 0) {
2374 bs->consumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs); /* <-- The stream has been exhausted, so marked the bits as consumed. */
2375 return DRFLAC_FALSE;
2376 }
2377
2378 DRFLAC_ASSERT(bytesRead < DRFLAC_CACHE_L1_SIZE_BYTES(bs));
2379 bs->consumedBits = (drflac_uint32)(DRFLAC_CACHE_L1_SIZE_BYTES(bs) - bytesRead) * 8;
2380
2381 bs->cache = drflac__be2host__cache_line(bs->unalignedCache);
2382 bs->cache &= DRFLAC_CACHE_L1_SELECTION_MASK(DRFLAC_CACHE_L1_BITS_REMAINING(bs)); /* <-- Make sure the consumed bits are always set to zero. Other parts of the library depend on this property. */
2383 bs->unalignedByteCount = 0; /* <-- At this point the unaligned bytes have been moved into the cache and we thus have no more unaligned bytes. */
2384
2385#ifndef DR_FLAC_NO_CRC
2386 bs->crc16Cache = bs->cache >> bs->consumedBits;
2387 bs->crc16CacheIgnoredBytes = bs->consumedBits >> 3;
2388#endif
2389 return DRFLAC_TRUE;
2390}
2391
2392static void drflac__reset_cache(drflac_bs* bs)
2393{
2394 bs->nextL2Line = DRFLAC_CACHE_L2_LINE_COUNT(bs); /* <-- This clears the L2 cache. */
2395 bs->consumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs); /* <-- This clears the L1 cache. */
2396 bs->cache = 0;
2397 bs->unalignedByteCount = 0; /* <-- This clears the trailing unaligned bytes. */
2398 bs->unalignedCache = 0;
2399
2400#ifndef DR_FLAC_NO_CRC
2401 bs->crc16Cache = 0;
2402 bs->crc16CacheIgnoredBytes = 0;
2403#endif
2404}
2405
2406
2407static DRFLAC_INLINE drflac_bool32 drflac__read_uint32(drflac_bs* bs, unsigned int bitCount, drflac_uint32* pResultOut)
2408{
2409 DRFLAC_ASSERT(bs != NULL);
2410 DRFLAC_ASSERT(pResultOut != NULL);
2411 DRFLAC_ASSERT(bitCount > 0);
2412 DRFLAC_ASSERT(bitCount <= 32);
2413
2414 if (bs->consumedBits == DRFLAC_CACHE_L1_SIZE_BITS(bs)) {
2415 if (!drflac__reload_cache(bs)) {
2416 return DRFLAC_FALSE;
2417 }
2418 }
2419
2420 if (bitCount <= DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
2421 /*
2422 If we want to load all 32-bits from a 32-bit cache we need to do it slightly differently because we can't do
2423 a 32-bit shift on a 32-bit integer. This will never be the case on 64-bit caches, so we can have a slightly
2424 more optimal solution for this.
2425 */
2426#ifdef DRFLAC_64BIT
2427 *pResultOut = (drflac_uint32)DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCount);
2428 bs->consumedBits += bitCount;
2429 bs->cache <<= bitCount;
2430#else
2431 if (bitCount < DRFLAC_CACHE_L1_SIZE_BITS(bs)) {
2432 *pResultOut = (drflac_uint32)DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCount);
2433 bs->consumedBits += bitCount;
2434 bs->cache <<= bitCount;
2435 } else {
2436 /* Cannot shift by 32-bits, so need to do it differently. */
2437 *pResultOut = (drflac_uint32)bs->cache;
2438 bs->consumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs);
2439 bs->cache = 0;
2440 }
2441#endif
2442
2443 return DRFLAC_TRUE;
2444 } else {
2445 /* It straddles the cached data. It will never cover more than the next chunk. We just read the number in two parts and combine them. */
2446 drflac_uint32 bitCountHi = DRFLAC_CACHE_L1_BITS_REMAINING(bs);
2447 drflac_uint32 bitCountLo = bitCount - bitCountHi;
2448 drflac_uint32 resultHi;
2449
2450 DRFLAC_ASSERT(bitCountHi > 0);
2451 DRFLAC_ASSERT(bitCountHi < 32);
2452 resultHi = (drflac_uint32)DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCountHi);
2453
2454 if (!drflac__reload_cache(bs)) {
2455 return DRFLAC_FALSE;
2456 }
2457 if (bitCountLo > DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
2458 /* This happens when we get to end of stream */
2459 return DRFLAC_FALSE;
2460 }
2461
2462 *pResultOut = (resultHi << bitCountLo) | (drflac_uint32)DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCountLo);
2463 bs->consumedBits += bitCountLo;
2464 bs->cache <<= bitCountLo;
2465 return DRFLAC_TRUE;
2466 }
2467}
2468
2469static drflac_bool32 drflac__read_int32(drflac_bs* bs, unsigned int bitCount, drflac_int32* pResult)
2470{
2471 drflac_uint32 result;
2472
2473 DRFLAC_ASSERT(bs != NULL);
2474 DRFLAC_ASSERT(pResult != NULL);
2475 DRFLAC_ASSERT(bitCount > 0);
2476 DRFLAC_ASSERT(bitCount <= 32);
2477
2478 if (!drflac__read_uint32(bs, bitCount, &result)) {
2479 return DRFLAC_FALSE;
2480 }
2481
2482 /* Do not attempt to shift by 32 as it's undefined. */
2483 if (bitCount < 32) {
2484 drflac_uint32 signbit;
2485 signbit = ((result >> (bitCount-1)) & 0x01);
2486 result |= (~signbit + 1) << bitCount;
2487 }
2488
2489 *pResult = (drflac_int32)result;
2490 return DRFLAC_TRUE;
2491}
2492
2493#ifdef DRFLAC_64BIT
2494static drflac_bool32 drflac__read_uint64(drflac_bs* bs, unsigned int bitCount, drflac_uint64* pResultOut)
2495{
2496 drflac_uint32 resultHi;
2497 drflac_uint32 resultLo;
2498
2499 DRFLAC_ASSERT(bitCount <= 64);
2500 DRFLAC_ASSERT(bitCount > 32);
2501
2502 if (!drflac__read_uint32(bs, bitCount - 32, &resultHi)) {
2503 return DRFLAC_FALSE;
2504 }
2505
2506 if (!drflac__read_uint32(bs, 32, &resultLo)) {
2507 return DRFLAC_FALSE;
2508 }
2509
2510 *pResultOut = (((drflac_uint64)resultHi) << 32) | ((drflac_uint64)resultLo);
2511 return DRFLAC_TRUE;
2512}
2513#endif
2514
2515/* Function below is unused, but leaving it here in case I need to quickly add it again. */
2516#if 0
2517static drflac_bool32 drflac__read_int64(drflac_bs* bs, unsigned int bitCount, drflac_int64* pResultOut)
2518{
2519 drflac_uint64 result;
2520 drflac_uint64 signbit;
2521
2522 DRFLAC_ASSERT(bitCount <= 64);
2523
2524 if (!drflac__read_uint64(bs, bitCount, &result)) {
2525 return DRFLAC_FALSE;
2526 }
2527
2528 signbit = ((result >> (bitCount-1)) & 0x01);
2529 result |= (~signbit + 1) << bitCount;
2530
2531 *pResultOut = (drflac_int64)result;
2532 return DRFLAC_TRUE;
2533}
2534#endif
2535
2536static drflac_bool32 drflac__read_uint16(drflac_bs* bs, unsigned int bitCount, drflac_uint16* pResult)
2537{
2538 drflac_uint32 result;
2539
2540 DRFLAC_ASSERT(bs != NULL);
2541 DRFLAC_ASSERT(pResult != NULL);
2542 DRFLAC_ASSERT(bitCount > 0);
2543 DRFLAC_ASSERT(bitCount <= 16);
2544
2545 if (!drflac__read_uint32(bs, bitCount, &result)) {
2546 return DRFLAC_FALSE;
2547 }
2548
2549 *pResult = (drflac_uint16)result;
2550 return DRFLAC_TRUE;
2551}
2552
2553#if 0
2554static drflac_bool32 drflac__read_int16(drflac_bs* bs, unsigned int bitCount, drflac_int16* pResult)
2555{
2556 drflac_int32 result;
2557
2558 DRFLAC_ASSERT(bs != NULL);
2559 DRFLAC_ASSERT(pResult != NULL);
2560 DRFLAC_ASSERT(bitCount > 0);
2561 DRFLAC_ASSERT(bitCount <= 16);
2562
2563 if (!drflac__read_int32(bs, bitCount, &result)) {
2564 return DRFLAC_FALSE;
2565 }
2566
2567 *pResult = (drflac_int16)result;
2568 return DRFLAC_TRUE;
2569}
2570#endif
2571
2572static drflac_bool32 drflac__read_uint8(drflac_bs* bs, unsigned int bitCount, drflac_uint8* pResult)
2573{
2574 drflac_uint32 result;
2575
2576 DRFLAC_ASSERT(bs != NULL);
2577 DRFLAC_ASSERT(pResult != NULL);
2578 DRFLAC_ASSERT(bitCount > 0);
2579 DRFLAC_ASSERT(bitCount <= 8);
2580
2581 if (!drflac__read_uint32(bs, bitCount, &result)) {
2582 return DRFLAC_FALSE;
2583 }
2584
2585 *pResult = (drflac_uint8)result;
2586 return DRFLAC_TRUE;
2587}
2588
2589static drflac_bool32 drflac__read_int8(drflac_bs* bs, unsigned int bitCount, drflac_int8* pResult)
2590{
2591 drflac_int32 result;
2592
2593 DRFLAC_ASSERT(bs != NULL);
2594 DRFLAC_ASSERT(pResult != NULL);
2595 DRFLAC_ASSERT(bitCount > 0);
2596 DRFLAC_ASSERT(bitCount <= 8);
2597
2598 if (!drflac__read_int32(bs, bitCount, &result)) {
2599 return DRFLAC_FALSE;
2600 }
2601
2602 *pResult = (drflac_int8)result;
2603 return DRFLAC_TRUE;
2604}
2605
2606
2607static drflac_bool32 drflac__seek_bits(drflac_bs* bs, size_t bitsToSeek)
2608{
2609 if (bitsToSeek <= DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
2610 bs->consumedBits += (drflac_uint32)bitsToSeek;
2611 bs->cache <<= bitsToSeek;
2612 return DRFLAC_TRUE;
2613 } else {
2614 /* It straddles the cached data. This function isn't called too frequently so I'm favouring simplicity here. */
2615 bitsToSeek -= DRFLAC_CACHE_L1_BITS_REMAINING(bs);
2616 bs->consumedBits += DRFLAC_CACHE_L1_BITS_REMAINING(bs);
2617 bs->cache = 0;
2618
2619 /* Simple case. Seek in groups of the same number as bits that fit within a cache line. */
2620#ifdef DRFLAC_64BIT
2621 while (bitsToSeek >= DRFLAC_CACHE_L1_SIZE_BITS(bs)) {
2622 drflac_uint64 bin;
2623 if (!drflac__read_uint64(bs, DRFLAC_CACHE_L1_SIZE_BITS(bs), &bin)) {
2624 return DRFLAC_FALSE;
2625 }
2626 bitsToSeek -= DRFLAC_CACHE_L1_SIZE_BITS(bs);
2627 }
2628#else
2629 while (bitsToSeek >= DRFLAC_CACHE_L1_SIZE_BITS(bs)) {
2630 drflac_uint32 bin;
2631 if (!drflac__read_uint32(bs, DRFLAC_CACHE_L1_SIZE_BITS(bs), &bin)) {
2632 return DRFLAC_FALSE;
2633 }
2634 bitsToSeek -= DRFLAC_CACHE_L1_SIZE_BITS(bs);
2635 }
2636#endif
2637
2638 /* Whole leftover bytes. */
2639 while (bitsToSeek >= 8) {
2640 drflac_uint8 bin;
2641 if (!drflac__read_uint8(bs, 8, &bin)) {
2642 return DRFLAC_FALSE;
2643 }
2644 bitsToSeek -= 8;
2645 }
2646
2647 /* Leftover bits. */
2648 if (bitsToSeek > 0) {
2649 drflac_uint8 bin;
2650 if (!drflac__read_uint8(bs, (drflac_uint32)bitsToSeek, &bin)) {
2651 return DRFLAC_FALSE;
2652 }
2653 bitsToSeek = 0; /* <-- Necessary for the assert below. */
2654 }
2655
2656 DRFLAC_ASSERT(bitsToSeek == 0);
2657 return DRFLAC_TRUE;
2658 }
2659}
2660
2661
2662/* This function moves the bit streamer to the first bit after the sync code (bit 15 of the of the frame header). It will also update the CRC-16. */
2663static drflac_bool32 drflac__find_and_seek_to_next_sync_code(drflac_bs* bs)
2664{
2665 DRFLAC_ASSERT(bs != NULL);
2666
2667 /*
2668 The sync code is always aligned to 8 bits. This is convenient for us because it means we can do byte-aligned movements. The first
2669 thing to do is align to the next byte.
2670 */
2671 if (!drflac__seek_bits(bs, DRFLAC_CACHE_L1_BITS_REMAINING(bs) & 7)) {
2672 return DRFLAC_FALSE;
2673 }
2674
2675 for (;;) {
2676 drflac_uint8 hi;
2677
2678#ifndef DR_FLAC_NO_CRC
2679 drflac__reset_crc16(bs);
2680#endif
2681
2682 if (!drflac__read_uint8(bs, 8, &hi)) {
2683 return DRFLAC_FALSE;
2684 }
2685
2686 if (hi == 0xFF) {
2687 drflac_uint8 lo;
2688 if (!drflac__read_uint8(bs, 6, &lo)) {
2689 return DRFLAC_FALSE;
2690 }
2691
2692 if (lo == 0x3E) {
2693 return DRFLAC_TRUE;
2694 } else {
2695 if (!drflac__seek_bits(bs, DRFLAC_CACHE_L1_BITS_REMAINING(bs) & 7)) {
2696 return DRFLAC_FALSE;
2697 }
2698 }
2699 }
2700 }
2701
2702 /* Should never get here. */
2703 /*return DRFLAC_FALSE;*/
2704}
2705
2706
2707#if defined(DRFLAC_HAS_LZCNT_INTRINSIC)
2708#define DRFLAC_IMPLEMENT_CLZ_LZCNT
2709#endif
2710#if defined(_MSC_VER) && _MSC_VER >= 1400 && (defined(DRFLAC_X64) || defined(DRFLAC_X86)) && !defined(__clang__)
2711#define DRFLAC_IMPLEMENT_CLZ_MSVC
2712#endif
2713#if defined(__WATCOMC__) && defined(__386__)
2714#define DRFLAC_IMPLEMENT_CLZ_WATCOM
2715#endif
2716#ifdef __MRC__
2717#include <intrinsics.h>
2718#define DRFLAC_IMPLEMENT_CLZ_MRC
2719#endif
2720
2721static DRFLAC_INLINE drflac_uint32 drflac__clz_software(drflac_cache_t x)
2722{
2723 drflac_uint32 n;
2724 static drflac_uint32 clz_table_4[] = {
2725 0,
2726 4,
2727 3, 3,
2728 2, 2, 2, 2,
2729 1, 1, 1, 1, 1, 1, 1, 1
2730 };
2731
2732 if (x == 0) {
2733 return sizeof(x)*8;
2734 }
2735
2736 n = clz_table_4[x >> (sizeof(x)*8 - 4)];
2737 if (n == 0) {
2738#ifdef DRFLAC_64BIT
2739 if ((x & ((drflac_uint64)0xFFFFFFFF << 32)) == 0) { n = 32; x <<= 32; }
2740 if ((x & ((drflac_uint64)0xFFFF0000 << 32)) == 0) { n += 16; x <<= 16; }
2741 if ((x & ((drflac_uint64)0xFF000000 << 32)) == 0) { n += 8; x <<= 8; }
2742 if ((x & ((drflac_uint64)0xF0000000 << 32)) == 0) { n += 4; x <<= 4; }
2743#else
2744 if ((x & 0xFFFF0000) == 0) { n = 16; x <<= 16; }
2745 if ((x & 0xFF000000) == 0) { n += 8; x <<= 8; }
2746 if ((x & 0xF0000000) == 0) { n += 4; x <<= 4; }
2747#endif
2748 n += clz_table_4[x >> (sizeof(x)*8 - 4)];
2749 }
2750
2751 return n - 1;
2752}
2753
2754#ifdef DRFLAC_IMPLEMENT_CLZ_LZCNT
2755static DRFLAC_INLINE drflac_bool32 drflac__is_lzcnt_supported(void)
2756{
2757 /* Fast compile time check for ARM. */
2758#if defined(DRFLAC_HAS_LZCNT_INTRINSIC) && defined(DRFLAC_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 5)
2759 return DRFLAC_TRUE;
2760#elif defined(__MRC__)
2761 return DRFLAC_TRUE;
2762#else
2763 /* If the compiler itself does not support the intrinsic then we'll need to return false. */
2764 #ifdef DRFLAC_HAS_LZCNT_INTRINSIC
2765 return drflac__gIsLZCNTSupported;
2766 #else
2767 return DRFLAC_FALSE;
2768 #endif
2769#endif
2770}
2771
2772static DRFLAC_INLINE drflac_uint32 drflac__clz_lzcnt(drflac_cache_t x)
2773{
2774 /*
2775 It's critical for competitive decoding performance that this function be highly optimal. With MSVC we can use the __lzcnt64() and __lzcnt() intrinsics
2776 to achieve good performance, however on GCC and Clang it's a little bit more annoying. The __builtin_clzl() and __builtin_clzll() intrinsics leave
2777 it undefined as to the return value when `x` is 0. We need this to be well defined as returning 32 or 64, depending on whether or not it's a 32- or
2778 64-bit build. To work around this we would need to add a conditional to check for the x = 0 case, but this creates unnecessary inefficiency. To work
2779 around this problem I have written some inline assembly to emit the LZCNT (x86) or CLZ (ARM) instruction directly which removes the need to include
2780 the conditional. This has worked well in the past, but for some reason Clang's MSVC compatible driver, clang-cl, does not seem to be handling this
2781 in the same way as the normal Clang driver. It seems that `clang-cl` is just outputting the wrong results sometimes, maybe due to some register
2782 getting clobbered?
2783
2784 I'm not sure if this is a bug with dr_flac's inlined assembly (most likely), a bug in `clang-cl` or just a misunderstanding on my part with inline
2785 assembly rules for `clang-cl`. If somebody can identify an error in dr_flac's inlined assembly I'm happy to get that fixed.
2786
2787 Fortunately there is an easy workaround for this. Clang implements MSVC-specific intrinsics for compatibility. It also defines _MSC_VER for extra
2788 compatibility. We can therefore just check for _MSC_VER and use the MSVC intrinsic which, fortunately for us, Clang supports. It would still be nice
2789 to know how to fix the inlined assembly for correctness sake, however.
2790 */
2791
2792#if defined(_MSC_VER) /*&& !defined(__clang__)*/ /* <-- Intentionally wanting Clang to use the MSVC __lzcnt64/__lzcnt intrinsics due to above ^. */
2793 #ifdef DRFLAC_64BIT
2794 return (drflac_uint32)__lzcnt64(x);
2795 #else
2796 return (drflac_uint32)__lzcnt(x);
2797 #endif
2798#else
2799 #if defined(__GNUC__) || defined(__clang__)
2800 #if defined(DRFLAC_X64)
2801 {
2802 drflac_uint64 r;
2803 __asm__ __volatile__ (
2804 "lzcnt{ %1, %0| %0, %1}" : "=r"(r) : "r"(x) : "cc"
2805 );
2806
2807 return (drflac_uint32)r;
2808 }
2809 #elif defined(DRFLAC_X86)
2810 {
2811 drflac_uint32 r;
2812 __asm__ __volatile__ (
2813 "lzcnt{l %1, %0| %0, %1}" : "=r"(r) : "r"(x) : "cc"
2814 );
2815
2816 return r;
2817 }
2818 #elif defined(DRFLAC_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 5) && !defined(__ARM_ARCH_6M__) && !defined(DRFLAC_64BIT) /* <-- I haven't tested 64-bit inline assembly, so only enabling this for the 32-bit build for now. */
2819 {
2820 unsigned int r;
2821 __asm__ __volatile__ (
2822 #if defined(DRFLAC_64BIT)
2823 "clz %w[out], %w[in]" : [out]"=r"(r) : [in]"r"(x) /* <-- This is untested. If someone in the community could test this, that would be appreciated! */
2824 #else
2825 "clz %[out], %[in]" : [out]"=r"(r) : [in]"r"(x)
2826 #endif
2827 );
2828
2829 return r;
2830 }
2831 #else
2832 if (x == 0) {
2833 return sizeof(x)*8;
2834 }
2835 #ifdef DRFLAC_64BIT
2836 return (drflac_uint32)__builtin_clzll((drflac_uint64)x);
2837 #else
2838 return (drflac_uint32)__builtin_clzl((drflac_uint32)x);
2839 #endif
2840 #endif
2841 #else
2842 /* Unsupported compiler. */
2843 #error "This compiler does not support the lzcnt intrinsic."
2844 #endif
2845#endif
2846}
2847#endif
2848
2849#ifdef DRFLAC_IMPLEMENT_CLZ_MSVC
2850#include <intrin.h> /* For BitScanReverse(). */
2851
2852static DRFLAC_INLINE drflac_uint32 drflac__clz_msvc(drflac_cache_t x)
2853{
2854 drflac_uint32 n;
2855
2856 if (x == 0) {
2857 return sizeof(x)*8;
2858 }
2859
2860#ifdef DRFLAC_64BIT
2861 _BitScanReverse64((unsigned long*)&n, x);
2862#else
2863 _BitScanReverse((unsigned long*)&n, x);
2864#endif
2865 return sizeof(x)*8 - n - 1;
2866}
2867#endif
2868
2869#ifdef DRFLAC_IMPLEMENT_CLZ_WATCOM
2870static __inline drflac_uint32 drflac__clz_watcom (drflac_uint32);
2871#ifdef DRFLAC_IMPLEMENT_CLZ_WATCOM_LZCNT
2872/* Use the LZCNT instruction (only available on some processors since the 2010s). */
2873#pragma aux drflac__clz_watcom_lzcnt = \
2874 "db 0F3h, 0Fh, 0BDh, 0C0h" /* lzcnt eax, eax */ \
2875 parm [eax] \
2876 value [eax] \
2877 modify nomemory;
2878#else
2879/* Use the 386+-compatible implementation. */
2880#pragma aux drflac__clz_watcom = \
2881 "bsr eax, eax" \
2882 "xor eax, 31" \
2883 parm [eax] nomemory \
2884 value [eax] \
2885 modify exact [eax] nomemory;
2886#endif
2887#endif
2888
2889static DRFLAC_INLINE drflac_uint32 drflac__clz(drflac_cache_t x)
2890{
2891#ifdef DRFLAC_IMPLEMENT_CLZ_LZCNT
2892 if (drflac__is_lzcnt_supported()) {
2893 return drflac__clz_lzcnt(x);
2894 } else
2895#endif
2896 {
2897#ifdef DRFLAC_IMPLEMENT_CLZ_MSVC
2898 return drflac__clz_msvc(x);
2899#elif defined(DRFLAC_IMPLEMENT_CLZ_WATCOM_LZCNT)
2900 return drflac__clz_watcom_lzcnt(x);
2901#elif defined(DRFLAC_IMPLEMENT_CLZ_WATCOM)
2902 return (x == 0) ? sizeof(x)*8 : drflac__clz_watcom(x);
2903#elif defined(__MRC__)
2904 return __cntlzw(x);
2905#else
2906 return drflac__clz_software(x);
2907#endif
2908 }
2909}
2910
2911
2912static DRFLAC_INLINE drflac_bool32 drflac__seek_past_next_set_bit(drflac_bs* bs, unsigned int* pOffsetOut)
2913{
2914 drflac_uint32 zeroCounter = 0;
2915 drflac_uint32 setBitOffsetPlus1;
2916
2917 while (bs->cache == 0) {
2918 zeroCounter += (drflac_uint32)DRFLAC_CACHE_L1_BITS_REMAINING(bs);
2919 if (!drflac__reload_cache(bs)) {
2920 return DRFLAC_FALSE;
2921 }
2922 }
2923
2924 if (bs->cache == 1) {
2925 /* Not catching this would lead to undefined behaviour: a shift of a 32-bit number by 32 or more is undefined */
2926 *pOffsetOut = zeroCounter + (drflac_uint32)DRFLAC_CACHE_L1_BITS_REMAINING(bs) - 1;
2927 if (!drflac__reload_cache(bs)) {
2928 return DRFLAC_FALSE;
2929 }
2930
2931 return DRFLAC_TRUE;
2932 }
2933
2934 setBitOffsetPlus1 = drflac__clz(bs->cache);
2935 setBitOffsetPlus1 += 1;
2936
2937 if (setBitOffsetPlus1 > DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
2938 /* This happens when we get to end of stream */
2939 return DRFLAC_FALSE;
2940 }
2941
2942 bs->consumedBits += setBitOffsetPlus1;
2943 bs->cache <<= setBitOffsetPlus1;
2944
2945 *pOffsetOut = zeroCounter + setBitOffsetPlus1 - 1;
2946 return DRFLAC_TRUE;
2947}
2948
2949
2950
2951static drflac_bool32 drflac__seek_to_byte(drflac_bs* bs, drflac_uint64 offsetFromStart)
2952{
2953 DRFLAC_ASSERT(bs != NULL);
2954 DRFLAC_ASSERT(offsetFromStart > 0);
2955
2956 /*
2957 Seeking from the start is not quite as trivial as it sounds because the onSeek callback takes a signed 32-bit integer (which
2958 is intentional because it simplifies the implementation of the onSeek callbacks), however offsetFromStart is unsigned 64-bit.
2959 To resolve we just need to do an initial seek from the start, and then a series of offset seeks to make up the remainder.
2960 */
2961 if (offsetFromStart > 0x7FFFFFFF) {
2962 drflac_uint64 bytesRemaining = offsetFromStart;
2963 if (!bs->onSeek(bs->pUserData, 0x7FFFFFFF, drflac_seek_origin_start)) {
2964 return DRFLAC_FALSE;
2965 }
2966 bytesRemaining -= 0x7FFFFFFF;
2967
2968 while (bytesRemaining > 0x7FFFFFFF) {
2969 if (!bs->onSeek(bs->pUserData, 0x7FFFFFFF, drflac_seek_origin_current)) {
2970 return DRFLAC_FALSE;
2971 }
2972 bytesRemaining -= 0x7FFFFFFF;
2973 }
2974
2975 if (bytesRemaining > 0) {
2976 if (!bs->onSeek(bs->pUserData, (int)bytesRemaining, drflac_seek_origin_current)) {
2977 return DRFLAC_FALSE;
2978 }
2979 }
2980 } else {
2981 if (!bs->onSeek(bs->pUserData, (int)offsetFromStart, drflac_seek_origin_start)) {
2982 return DRFLAC_FALSE;
2983 }
2984 }
2985
2986 /* The cache should be reset to force a reload of fresh data from the client. */
2987 drflac__reset_cache(bs);
2988 return DRFLAC_TRUE;
2989}
2990
2991
2992static drflac_result drflac__read_utf8_coded_number(drflac_bs* bs, drflac_uint64* pNumberOut, drflac_uint8* pCRCOut)
2993{
2994 drflac_uint8 crc;
2995 drflac_uint64 result;
2996 drflac_uint8 utf8[7] = {0};
2997 int byteCount;
2998 int i;
2999
3000 DRFLAC_ASSERT(bs != NULL);
3001 DRFLAC_ASSERT(pNumberOut != NULL);
3002 DRFLAC_ASSERT(pCRCOut != NULL);
3003
3004 crc = *pCRCOut;
3005
3006 if (!drflac__read_uint8(bs, 8, utf8)) {
3007 *pNumberOut = 0;
3008 return DRFLAC_AT_END;
3009 }
3010 crc = drflac_crc8(crc, utf8[0], 8);
3011
3012 if ((utf8[0] & 0x80) == 0) {
3013 *pNumberOut = utf8[0];
3014 *pCRCOut = crc;
3015 return DRFLAC_SUCCESS;
3016 }
3017
3018 /*byteCount = 1;*/
3019 if ((utf8[0] & 0xE0) == 0xC0) {
3020 byteCount = 2;
3021 } else if ((utf8[0] & 0xF0) == 0xE0) {
3022 byteCount = 3;
3023 } else if ((utf8[0] & 0xF8) == 0xF0) {
3024 byteCount = 4;
3025 } else if ((utf8[0] & 0xFC) == 0xF8) {
3026 byteCount = 5;
3027 } else if ((utf8[0] & 0xFE) == 0xFC) {
3028 byteCount = 6;
3029 } else if ((utf8[0] & 0xFF) == 0xFE) {
3030 byteCount = 7;
3031 } else {
3032 *pNumberOut = 0;
3033 return DRFLAC_CRC_MISMATCH; /* Bad UTF-8 encoding. */
3034 }
3035
3036 /* Read extra bytes. */
3037 DRFLAC_ASSERT(byteCount > 1);
3038
3039 result = (drflac_uint64)(utf8[0] & (0xFF >> (byteCount + 1)));
3040 for (i = 1; i < byteCount; ++i) {
3041 if (!drflac__read_uint8(bs, 8, utf8 + i)) {
3042 *pNumberOut = 0;
3043 return DRFLAC_AT_END;
3044 }
3045 crc = drflac_crc8(crc, utf8[i], 8);
3046
3047 result = (result << 6) | (utf8[i] & 0x3F);
3048 }
3049
3050 *pNumberOut = result;
3051 *pCRCOut = crc;
3052 return DRFLAC_SUCCESS;
3053}
3054
3055
3056static DRFLAC_INLINE drflac_uint32 drflac__ilog2_u32(drflac_uint32 x)
3057{
3058#if 1 /* Needs optimizing. */
3059 drflac_uint32 result = 0;
3060 while (x > 0) {
3061 result += 1;
3062 x >>= 1;
3063 }
3064
3065 return result;
3066#endif
3067}
3068
3069static DRFLAC_INLINE drflac_bool32 drflac__use_64_bit_prediction(drflac_uint32 bitsPerSample, drflac_uint32 order, drflac_uint32 precision)
3070{
3071 /* https://web.archive.org/web/20220205005724/https://github.com/ietf-wg-cellar/flac-specification/blob/37a49aa48ba4ba12e8757badfc59c0df35435fec/rfc_backmatter.md */
3072 return bitsPerSample + precision + drflac__ilog2_u32(order) > 32;
3073}
3074
3075
3076/*
3077The next two functions are responsible for calculating the prediction.
3078
3079When the bits per sample is >16 we need to use 64-bit integer arithmetic because otherwise we'll run out of precision. It's
3080safe to assume this will be slower on 32-bit platforms so we use a more optimal solution when the bits per sample is <=16.
3081*/
3082#if defined(__clang__)
3083__attribute__((no_sanitize("signed-integer-overflow")))
3084#endif
3085static DRFLAC_INLINE drflac_int32 drflac__calculate_prediction_32(drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pDecodedSamples)
3086{
3087 drflac_int32 prediction = 0;
3088
3089 DRFLAC_ASSERT(order <= 32);
3090
3091 /* 32-bit version. */
3092
3093 /* VC++ optimizes this to a single jmp. I've not yet verified this for other compilers. */
3094 switch (order)
3095 {
3096 case 32: prediction += coefficients[31] * pDecodedSamples[-32];
3097 case 31: prediction += coefficients[30] * pDecodedSamples[-31];
3098 case 30: prediction += coefficients[29] * pDecodedSamples[-30];
3099 case 29: prediction += coefficients[28] * pDecodedSamples[-29];
3100 case 28: prediction += coefficients[27] * pDecodedSamples[-28];
3101 case 27: prediction += coefficients[26] * pDecodedSamples[-27];
3102 case 26: prediction += coefficients[25] * pDecodedSamples[-26];
3103 case 25: prediction += coefficients[24] * pDecodedSamples[-25];
3104 case 24: prediction += coefficients[23] * pDecodedSamples[-24];
3105 case 23: prediction += coefficients[22] * pDecodedSamples[-23];
3106 case 22: prediction += coefficients[21] * pDecodedSamples[-22];
3107 case 21: prediction += coefficients[20] * pDecodedSamples[-21];
3108 case 20: prediction += coefficients[19] * pDecodedSamples[-20];
3109 case 19: prediction += coefficients[18] * pDecodedSamples[-19];
3110 case 18: prediction += coefficients[17] * pDecodedSamples[-18];
3111 case 17: prediction += coefficients[16] * pDecodedSamples[-17];
3112 case 16: prediction += coefficients[15] * pDecodedSamples[-16];
3113 case 15: prediction += coefficients[14] * pDecodedSamples[-15];
3114 case 14: prediction += coefficients[13] * pDecodedSamples[-14];
3115 case 13: prediction += coefficients[12] * pDecodedSamples[-13];
3116 case 12: prediction += coefficients[11] * pDecodedSamples[-12];
3117 case 11: prediction += coefficients[10] * pDecodedSamples[-11];
3118 case 10: prediction += coefficients[ 9] * pDecodedSamples[-10];
3119 case 9: prediction += coefficients[ 8] * pDecodedSamples[- 9];
3120 case 8: prediction += coefficients[ 7] * pDecodedSamples[- 8];
3121 case 7: prediction += coefficients[ 6] * pDecodedSamples[- 7];
3122 case 6: prediction += coefficients[ 5] * pDecodedSamples[- 6];
3123 case 5: prediction += coefficients[ 4] * pDecodedSamples[- 5];
3124 case 4: prediction += coefficients[ 3] * pDecodedSamples[- 4];
3125 case 3: prediction += coefficients[ 2] * pDecodedSamples[- 3];
3126 case 2: prediction += coefficients[ 1] * pDecodedSamples[- 2];
3127 case 1: prediction += coefficients[ 0] * pDecodedSamples[- 1];
3128 }
3129
3130 return (drflac_int32)(prediction >> shift);
3131}
3132
3133static DRFLAC_INLINE drflac_int32 drflac__calculate_prediction_64(drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pDecodedSamples)
3134{
3135 drflac_int64 prediction;
3136
3137 DRFLAC_ASSERT(order <= 32);
3138
3139 /* 64-bit version. */
3140
3141 /* This method is faster on the 32-bit build when compiling with VC++. See note below. */
3142#ifndef DRFLAC_64BIT
3143 if (order == 8)
3144 {
3145 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3146 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3147 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3148 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
3149 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
3150 prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
3151 prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
3152 prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
3153 }
3154 else if (order == 7)
3155 {
3156 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3157 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3158 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3159 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
3160 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
3161 prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
3162 prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
3163 }
3164 else if (order == 3)
3165 {
3166 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3167 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3168 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3169 }
3170 else if (order == 6)
3171 {
3172 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3173 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3174 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3175 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
3176 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
3177 prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
3178 }
3179 else if (order == 5)
3180 {
3181 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3182 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3183 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3184 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
3185 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
3186 }
3187 else if (order == 4)
3188 {
3189 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3190 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3191 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3192 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
3193 }
3194 else if (order == 12)
3195 {
3196 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3197 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3198 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3199 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
3200 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
3201 prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
3202 prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
3203 prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
3204 prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9];
3205 prediction += coefficients[9] * (drflac_int64)pDecodedSamples[-10];
3206 prediction += coefficients[10] * (drflac_int64)pDecodedSamples[-11];
3207 prediction += coefficients[11] * (drflac_int64)pDecodedSamples[-12];
3208 }
3209 else if (order == 2)
3210 {
3211 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3212 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3213 }
3214 else if (order == 1)
3215 {
3216 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3217 }
3218 else if (order == 10)
3219 {
3220 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3221 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3222 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3223 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
3224 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
3225 prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
3226 prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
3227 prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
3228 prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9];
3229 prediction += coefficients[9] * (drflac_int64)pDecodedSamples[-10];
3230 }
3231 else if (order == 9)
3232 {
3233 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3234 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3235 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3236 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
3237 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
3238 prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
3239 prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
3240 prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
3241 prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9];
3242 }
3243 else if (order == 11)
3244 {
3245 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3246 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3247 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3248 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
3249 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
3250 prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
3251 prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
3252 prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
3253 prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9];
3254 prediction += coefficients[9] * (drflac_int64)pDecodedSamples[-10];
3255 prediction += coefficients[10] * (drflac_int64)pDecodedSamples[-11];
3256 }
3257 else
3258 {
3259 int j;
3260
3261 prediction = 0;
3262 for (j = 0; j < (int)order; ++j) {
3263 prediction += coefficients[j] * (drflac_int64)pDecodedSamples[-j-1];
3264 }
3265 }
3266#endif
3267
3268 /*
3269 VC++ optimizes this to a single jmp instruction, but only the 64-bit build. The 32-bit build generates less efficient code for some
3270 reason. The ugly version above is faster so we'll just switch between the two depending on the target platform.
3271 */
3272#ifdef DRFLAC_64BIT
3273 prediction = 0;
3274 switch (order)
3275 {
3276 case 32: prediction += coefficients[31] * (drflac_int64)pDecodedSamples[-32];
3277 case 31: prediction += coefficients[30] * (drflac_int64)pDecodedSamples[-31];
3278 case 30: prediction += coefficients[29] * (drflac_int64)pDecodedSamples[-30];
3279 case 29: prediction += coefficients[28] * (drflac_int64)pDecodedSamples[-29];
3280 case 28: prediction += coefficients[27] * (drflac_int64)pDecodedSamples[-28];
3281 case 27: prediction += coefficients[26] * (drflac_int64)pDecodedSamples[-27];
3282 case 26: prediction += coefficients[25] * (drflac_int64)pDecodedSamples[-26];
3283 case 25: prediction += coefficients[24] * (drflac_int64)pDecodedSamples[-25];
3284 case 24: prediction += coefficients[23] * (drflac_int64)pDecodedSamples[-24];
3285 case 23: prediction += coefficients[22] * (drflac_int64)pDecodedSamples[-23];
3286 case 22: prediction += coefficients[21] * (drflac_int64)pDecodedSamples[-22];
3287 case 21: prediction += coefficients[20] * (drflac_int64)pDecodedSamples[-21];
3288 case 20: prediction += coefficients[19] * (drflac_int64)pDecodedSamples[-20];
3289 case 19: prediction += coefficients[18] * (drflac_int64)pDecodedSamples[-19];
3290 case 18: prediction += coefficients[17] * (drflac_int64)pDecodedSamples[-18];
3291 case 17: prediction += coefficients[16] * (drflac_int64)pDecodedSamples[-17];
3292 case 16: prediction += coefficients[15] * (drflac_int64)pDecodedSamples[-16];
3293 case 15: prediction += coefficients[14] * (drflac_int64)pDecodedSamples[-15];
3294 case 14: prediction += coefficients[13] * (drflac_int64)pDecodedSamples[-14];
3295 case 13: prediction += coefficients[12] * (drflac_int64)pDecodedSamples[-13];
3296 case 12: prediction += coefficients[11] * (drflac_int64)pDecodedSamples[-12];
3297 case 11: prediction += coefficients[10] * (drflac_int64)pDecodedSamples[-11];
3298 case 10: prediction += coefficients[ 9] * (drflac_int64)pDecodedSamples[-10];
3299 case 9: prediction += coefficients[ 8] * (drflac_int64)pDecodedSamples[- 9];
3300 case 8: prediction += coefficients[ 7] * (drflac_int64)pDecodedSamples[- 8];
3301 case 7: prediction += coefficients[ 6] * (drflac_int64)pDecodedSamples[- 7];
3302 case 6: prediction += coefficients[ 5] * (drflac_int64)pDecodedSamples[- 6];
3303 case 5: prediction += coefficients[ 4] * (drflac_int64)pDecodedSamples[- 5];
3304 case 4: prediction += coefficients[ 3] * (drflac_int64)pDecodedSamples[- 4];
3305 case 3: prediction += coefficients[ 2] * (drflac_int64)pDecodedSamples[- 3];
3306 case 2: prediction += coefficients[ 1] * (drflac_int64)pDecodedSamples[- 2];
3307 case 1: prediction += coefficients[ 0] * (drflac_int64)pDecodedSamples[- 1];
3308 }
3309#endif
3310
3311 return (drflac_int32)(prediction >> shift);
3312}
3313
3314
3315#if 0
3316/*
3317Reference implementation for reading and decoding samples with residual. This is intentionally left unoptimized for the
3318sake of readability and should only be used as a reference.
3319*/
3320static drflac_bool32 drflac__decode_samples_with_residual__rice__reference(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 lpcOrder, drflac_int32 lpcShift, drflac_uint32 lpcPrecision, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
3321{
3322 drflac_uint32 i;
3323
3324 DRFLAC_ASSERT(bs != NULL);
3325 DRFLAC_ASSERT(pSamplesOut != NULL);
3326
3327 for (i = 0; i < count; ++i) {
3328 drflac_uint32 zeroCounter = 0;
3329 for (;;) {
3330 drflac_uint8 bit;
3331 if (!drflac__read_uint8(bs, 1, &bit)) {
3332 return DRFLAC_FALSE;
3333 }
3334
3335 if (bit == 0) {
3336 zeroCounter += 1;
3337 } else {
3338 break;
3339 }
3340 }
3341
3342 drflac_uint32 decodedRice;
3343 if (riceParam > 0) {
3344 if (!drflac__read_uint32(bs, riceParam, &decodedRice)) {
3345 return DRFLAC_FALSE;
3346 }
3347 } else {
3348 decodedRice = 0;
3349 }
3350
3351 decodedRice |= (zeroCounter << riceParam);
3352 if ((decodedRice & 0x01)) {
3353 decodedRice = ~(decodedRice >> 1);
3354 } else {
3355 decodedRice = (decodedRice >> 1);
3356 }
3357
3358
3359 if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
3360 pSamplesOut[i] = decodedRice + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + i);
3361 } else {
3362 pSamplesOut[i] = decodedRice + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + i);
3363 }
3364 }
3365
3366 return DRFLAC_TRUE;
3367}
3368#endif
3369
3370#if 0
3371static drflac_bool32 drflac__read_rice_parts__reference(drflac_bs* bs, drflac_uint8 riceParam, drflac_uint32* pZeroCounterOut, drflac_uint32* pRiceParamPartOut)
3372{
3373 drflac_uint32 zeroCounter = 0;
3374 drflac_uint32 decodedRice;
3375
3376 for (;;) {
3377 drflac_uint8 bit;
3378 if (!drflac__read_uint8(bs, 1, &bit)) {
3379 return DRFLAC_FALSE;
3380 }
3381
3382 if (bit == 0) {
3383 zeroCounter += 1;
3384 } else {
3385 break;
3386 }
3387 }
3388
3389 if (riceParam > 0) {
3390 if (!drflac__read_uint32(bs, riceParam, &decodedRice)) {
3391 return DRFLAC_FALSE;
3392 }
3393 } else {
3394 decodedRice = 0;
3395 }
3396
3397 *pZeroCounterOut = zeroCounter;
3398 *pRiceParamPartOut = decodedRice;
3399 return DRFLAC_TRUE;
3400}
3401#endif
3402
3403#if 0
3404static DRFLAC_INLINE drflac_bool32 drflac__read_rice_parts(drflac_bs* bs, drflac_uint8 riceParam, drflac_uint32* pZeroCounterOut, drflac_uint32* pRiceParamPartOut)
3405{
3406 drflac_cache_t riceParamMask;
3407 drflac_uint32 zeroCounter;
3408 drflac_uint32 setBitOffsetPlus1;
3409 drflac_uint32 riceParamPart;
3410 drflac_uint32 riceLength;
3411
3412 DRFLAC_ASSERT(riceParam > 0); /* <-- riceParam should never be 0. drflac__read_rice_parts__param_equals_zero() should be used instead for this case. */
3413
3414 riceParamMask = DRFLAC_CACHE_L1_SELECTION_MASK(riceParam);
3415
3416 zeroCounter = 0;
3417 while (bs->cache == 0) {
3418 zeroCounter += (drflac_uint32)DRFLAC_CACHE_L1_BITS_REMAINING(bs);
3419 if (!drflac__reload_cache(bs)) {
3420 return DRFLAC_FALSE;
3421 }
3422 }
3423
3424 setBitOffsetPlus1 = drflac__clz(bs->cache);
3425 zeroCounter += setBitOffsetPlus1;
3426 setBitOffsetPlus1 += 1;
3427
3428 riceLength = setBitOffsetPlus1 + riceParam;
3429 if (riceLength < DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
3430 riceParamPart = (drflac_uint32)((bs->cache & (riceParamMask >> setBitOffsetPlus1)) >> DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, riceLength));
3431
3432 bs->consumedBits += riceLength;
3433 bs->cache <<= riceLength;
3434 } else {
3435 drflac_uint32 bitCountLo;
3436 drflac_cache_t resultHi;
3437
3438 bs->consumedBits += riceLength;
3439 bs->cache <<= setBitOffsetPlus1 & (DRFLAC_CACHE_L1_SIZE_BITS(bs)-1); /* <-- Equivalent to "if (setBitOffsetPlus1 < DRFLAC_CACHE_L1_SIZE_BITS(bs)) { bs->cache <<= setBitOffsetPlus1; }" */
3440
3441 /* It straddles the cached data. It will never cover more than the next chunk. We just read the number in two parts and combine them. */
3442 bitCountLo = bs->consumedBits - DRFLAC_CACHE_L1_SIZE_BITS(bs);
3443 resultHi = DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, riceParam); /* <-- Use DRFLAC_CACHE_L1_SELECT_AND_SHIFT_SAFE() if ever this function allows riceParam=0. */
3444
3445 if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
3446#ifndef DR_FLAC_NO_CRC
3447 drflac__update_crc16(bs);
3448#endif
3449 bs->cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
3450 bs->consumedBits = 0;
3451#ifndef DR_FLAC_NO_CRC
3452 bs->crc16Cache = bs->cache;
3453#endif
3454 } else {
3455 /* Slow path. We need to fetch more data from the client. */
3456 if (!drflac__reload_cache(bs)) {
3457 return DRFLAC_FALSE;
3458 }
3459 if (bitCountLo > DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
3460 /* This happens when we get to end of stream */
3461 return DRFLAC_FALSE;
3462 }
3463 }
3464
3465 riceParamPart = (drflac_uint32)(resultHi | DRFLAC_CACHE_L1_SELECT_AND_SHIFT_SAFE(bs, bitCountLo));
3466
3467 bs->consumedBits += bitCountLo;
3468 bs->cache <<= bitCountLo;
3469 }
3470
3471 pZeroCounterOut[0] = zeroCounter;
3472 pRiceParamPartOut[0] = riceParamPart;
3473
3474 return DRFLAC_TRUE;
3475}
3476#endif
3477
3478static DRFLAC_INLINE drflac_bool32 drflac__read_rice_parts_x1(drflac_bs* bs, drflac_uint8 riceParam, drflac_uint32* pZeroCounterOut, drflac_uint32* pRiceParamPartOut)
3479{
3480 drflac_uint32 riceParamPlus1 = riceParam + 1;
3481 /*drflac_cache_t riceParamPlus1Mask = DRFLAC_CACHE_L1_SELECTION_MASK(riceParamPlus1);*/
3482 drflac_uint32 riceParamPlus1Shift = DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, riceParamPlus1);
3483 drflac_uint32 riceParamPlus1MaxConsumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs) - riceParamPlus1;
3484
3485 /*
3486 The idea here is to use local variables for the cache in an attempt to encourage the compiler to store them in registers. I have
3487 no idea how this will work in practice...
3488 */
3489 drflac_cache_t bs_cache = bs->cache;
3490 drflac_uint32 bs_consumedBits = bs->consumedBits;
3491
3492 /* The first thing to do is find the first unset bit. Most likely a bit will be set in the current cache line. */
3493 drflac_uint32 lzcount = drflac__clz(bs_cache);
3494 if (lzcount < sizeof(bs_cache)*8) {
3495 pZeroCounterOut[0] = lzcount;
3496
3497 /*
3498 It is most likely that the riceParam part (which comes after the zero counter) is also on this cache line. When extracting
3499 this, we include the set bit from the unary coded part because it simplifies cache management. This bit will be handled
3500 outside of this function at a higher level.
3501 */
3502 extract_rice_param_part:
3503 bs_cache <<= lzcount;
3504 bs_consumedBits += lzcount;
3505
3506 if (bs_consumedBits <= riceParamPlus1MaxConsumedBits) {
3507 /* Getting here means the rice parameter part is wholly contained within the current cache line. */
3508 pRiceParamPartOut[0] = (drflac_uint32)(bs_cache >> riceParamPlus1Shift);
3509 bs_cache <<= riceParamPlus1;
3510 bs_consumedBits += riceParamPlus1;
3511 } else {
3512 drflac_uint32 riceParamPartHi;
3513 drflac_uint32 riceParamPartLo;
3514 drflac_uint32 riceParamPartLoBitCount;
3515
3516 /*
3517 Getting here means the rice parameter part straddles the cache line. We need to read from the tail of the current cache
3518 line, reload the cache, and then combine it with the head of the next cache line.
3519 */
3520
3521 /* Grab the high part of the rice parameter part. */
3522 riceParamPartHi = (drflac_uint32)(bs_cache >> riceParamPlus1Shift);
3523
3524 /* Before reloading the cache we need to grab the size in bits of the low part. */
3525 riceParamPartLoBitCount = bs_consumedBits - riceParamPlus1MaxConsumedBits;
3526 DRFLAC_ASSERT(riceParamPartLoBitCount > 0 && riceParamPartLoBitCount < 32);
3527
3528 /* Now reload the cache. */
3529 if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
3530 #ifndef DR_FLAC_NO_CRC
3531 drflac__update_crc16(bs);
3532 #endif
3533 bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
3534 bs_consumedBits = riceParamPartLoBitCount;
3535 #ifndef DR_FLAC_NO_CRC
3536 bs->crc16Cache = bs_cache;
3537 #endif
3538 } else {
3539 /* Slow path. We need to fetch more data from the client. */
3540 if (!drflac__reload_cache(bs)) {
3541 return DRFLAC_FALSE;
3542 }
3543 if (riceParamPartLoBitCount > DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
3544 /* This happens when we get to end of stream */
3545 return DRFLAC_FALSE;
3546 }
3547
3548 bs_cache = bs->cache;
3549 bs_consumedBits = bs->consumedBits + riceParamPartLoBitCount;
3550 }
3551
3552 /* We should now have enough information to construct the rice parameter part. */
3553 riceParamPartLo = (drflac_uint32)(bs_cache >> (DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, riceParamPartLoBitCount)));
3554 pRiceParamPartOut[0] = riceParamPartHi | riceParamPartLo;
3555
3556 bs_cache <<= riceParamPartLoBitCount;
3557 }
3558 } else {
3559 /*
3560 Getting here means there are no bits set on the cache line. This is a less optimal case because we just wasted a call
3561 to drflac__clz() and we need to reload the cache.
3562 */
3563 drflac_uint32 zeroCounter = (drflac_uint32)(DRFLAC_CACHE_L1_SIZE_BITS(bs) - bs_consumedBits);
3564 for (;;) {
3565 if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
3566 #ifndef DR_FLAC_NO_CRC
3567 drflac__update_crc16(bs);
3568 #endif
3569 bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
3570 bs_consumedBits = 0;
3571 #ifndef DR_FLAC_NO_CRC
3572 bs->crc16Cache = bs_cache;
3573 #endif
3574 } else {
3575 /* Slow path. We need to fetch more data from the client. */
3576 if (!drflac__reload_cache(bs)) {
3577 return DRFLAC_FALSE;
3578 }
3579
3580 bs_cache = bs->cache;
3581 bs_consumedBits = bs->consumedBits;
3582 }
3583
3584 lzcount = drflac__clz(bs_cache);
3585 zeroCounter += lzcount;
3586
3587 if (lzcount < sizeof(bs_cache)*8) {
3588 break;
3589 }
3590 }
3591
3592 pZeroCounterOut[0] = zeroCounter;
3593 goto extract_rice_param_part;
3594 }
3595
3596 /* Make sure the cache is restored at the end of it all. */
3597 bs->cache = bs_cache;
3598 bs->consumedBits = bs_consumedBits;
3599
3600 return DRFLAC_TRUE;
3601}
3602
3603static DRFLAC_INLINE drflac_bool32 drflac__seek_rice_parts(drflac_bs* bs, drflac_uint8 riceParam)
3604{
3605 drflac_uint32 riceParamPlus1 = riceParam + 1;
3606 drflac_uint32 riceParamPlus1MaxConsumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs) - riceParamPlus1;
3607
3608 /*
3609 The idea here is to use local variables for the cache in an attempt to encourage the compiler to store them in registers. I have
3610 no idea how this will work in practice...
3611 */
3612 drflac_cache_t bs_cache = bs->cache;
3613 drflac_uint32 bs_consumedBits = bs->consumedBits;
3614
3615 /* The first thing to do is find the first unset bit. Most likely a bit will be set in the current cache line. */
3616 drflac_uint32 lzcount = drflac__clz(bs_cache);
3617 if (lzcount < sizeof(bs_cache)*8) {
3618 /*
3619 It is most likely that the riceParam part (which comes after the zero counter) is also on this cache line. When extracting
3620 this, we include the set bit from the unary coded part because it simplifies cache management. This bit will be handled
3621 outside of this function at a higher level.
3622 */
3623 extract_rice_param_part:
3624 bs_cache <<= lzcount;
3625 bs_consumedBits += lzcount;
3626
3627 if (bs_consumedBits <= riceParamPlus1MaxConsumedBits) {
3628 /* Getting here means the rice parameter part is wholly contained within the current cache line. */
3629 bs_cache <<= riceParamPlus1;
3630 bs_consumedBits += riceParamPlus1;
3631 } else {
3632 /*
3633 Getting here means the rice parameter part straddles the cache line. We need to read from the tail of the current cache
3634 line, reload the cache, and then combine it with the head of the next cache line.
3635 */
3636
3637 /* Before reloading the cache we need to grab the size in bits of the low part. */
3638 drflac_uint32 riceParamPartLoBitCount = bs_consumedBits - riceParamPlus1MaxConsumedBits;
3639 DRFLAC_ASSERT(riceParamPartLoBitCount > 0 && riceParamPartLoBitCount < 32);
3640
3641 /* Now reload the cache. */
3642 if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
3643 #ifndef DR_FLAC_NO_CRC
3644 drflac__update_crc16(bs);
3645 #endif
3646 bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
3647 bs_consumedBits = riceParamPartLoBitCount;
3648 #ifndef DR_FLAC_NO_CRC
3649 bs->crc16Cache = bs_cache;
3650 #endif
3651 } else {
3652 /* Slow path. We need to fetch more data from the client. */
3653 if (!drflac__reload_cache(bs)) {
3654 return DRFLAC_FALSE;
3655 }
3656
3657 if (riceParamPartLoBitCount > DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
3658 /* This happens when we get to end of stream */
3659 return DRFLAC_FALSE;
3660 }
3661
3662 bs_cache = bs->cache;
3663 bs_consumedBits = bs->consumedBits + riceParamPartLoBitCount;
3664 }
3665
3666 bs_cache <<= riceParamPartLoBitCount;
3667 }
3668 } else {
3669 /*
3670 Getting here means there are no bits set on the cache line. This is a less optimal case because we just wasted a call
3671 to drflac__clz() and we need to reload the cache.
3672 */
3673 for (;;) {
3674 if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
3675 #ifndef DR_FLAC_NO_CRC
3676 drflac__update_crc16(bs);
3677 #endif
3678 bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
3679 bs_consumedBits = 0;
3680 #ifndef DR_FLAC_NO_CRC
3681 bs->crc16Cache = bs_cache;
3682 #endif
3683 } else {
3684 /* Slow path. We need to fetch more data from the client. */
3685 if (!drflac__reload_cache(bs)) {
3686 return DRFLAC_FALSE;
3687 }
3688
3689 bs_cache = bs->cache;
3690 bs_consumedBits = bs->consumedBits;
3691 }
3692
3693 lzcount = drflac__clz(bs_cache);
3694 if (lzcount < sizeof(bs_cache)*8) {
3695 break;
3696 }
3697 }
3698
3699 goto extract_rice_param_part;
3700 }
3701
3702 /* Make sure the cache is restored at the end of it all. */
3703 bs->cache = bs_cache;
3704 bs->consumedBits = bs_consumedBits;
3705
3706 return DRFLAC_TRUE;
3707}
3708
3709
3710static drflac_bool32 drflac__decode_samples_with_residual__rice__scalar_zeroorder(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
3711{
3712 drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
3713 drflac_uint32 zeroCountPart0;
3714 drflac_uint32 riceParamPart0;
3715 drflac_uint32 riceParamMask;
3716 drflac_uint32 i;
3717
3718 DRFLAC_ASSERT(bs != NULL);
3719 DRFLAC_ASSERT(pSamplesOut != NULL);
3720
3721 (void)bitsPerSample;
3722 (void)order;
3723 (void)shift;
3724 (void)coefficients;
3725
3726 riceParamMask = (drflac_uint32)~((~0UL) << riceParam);
3727
3728 i = 0;
3729 while (i < count) {
3730 /* Rice extraction. */
3731 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0)) {
3732 return DRFLAC_FALSE;
3733 }
3734
3735 /* Rice reconstruction. */
3736 riceParamPart0 &= riceParamMask;
3737 riceParamPart0 |= (zeroCountPart0 << riceParam);
3738 riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
3739
3740 pSamplesOut[i] = riceParamPart0;
3741
3742 i += 1;
3743 }
3744
3745 return DRFLAC_TRUE;
3746}
3747
3748static drflac_bool32 drflac__decode_samples_with_residual__rice__scalar(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 lpcOrder, drflac_int32 lpcShift, drflac_uint32 lpcPrecision, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
3749{
3750 drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
3751 drflac_uint32 zeroCountPart0 = 0;
3752 drflac_uint32 zeroCountPart1 = 0;
3753 drflac_uint32 zeroCountPart2 = 0;
3754 drflac_uint32 zeroCountPart3 = 0;
3755 drflac_uint32 riceParamPart0 = 0;
3756 drflac_uint32 riceParamPart1 = 0;
3757 drflac_uint32 riceParamPart2 = 0;
3758 drflac_uint32 riceParamPart3 = 0;
3759 drflac_uint32 riceParamMask;
3760 const drflac_int32* pSamplesOutEnd;
3761 drflac_uint32 i;
3762
3763 DRFLAC_ASSERT(bs != NULL);
3764 DRFLAC_ASSERT(pSamplesOut != NULL);
3765
3766 if (lpcOrder == 0) {
3767 return drflac__decode_samples_with_residual__rice__scalar_zeroorder(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut);
3768 }
3769
3770 riceParamMask = (drflac_uint32)~((~0UL) << riceParam);
3771 pSamplesOutEnd = pSamplesOut + (count & ~3);
3772
3773 if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
3774 while (pSamplesOut < pSamplesOutEnd) {
3775 /*
3776 Rice extraction. It's faster to do this one at a time against local variables than it is to use the x4 version
3777 against an array. Not sure why, but perhaps it's making more efficient use of registers?
3778 */
3779 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0) ||
3780 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart1, &riceParamPart1) ||
3781 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart2, &riceParamPart2) ||
3782 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart3, &riceParamPart3)) {
3783 return DRFLAC_FALSE;
3784 }
3785
3786 riceParamPart0 &= riceParamMask;
3787 riceParamPart1 &= riceParamMask;
3788 riceParamPart2 &= riceParamMask;
3789 riceParamPart3 &= riceParamMask;
3790
3791 riceParamPart0 |= (zeroCountPart0 << riceParam);
3792 riceParamPart1 |= (zeroCountPart1 << riceParam);
3793 riceParamPart2 |= (zeroCountPart2 << riceParam);
3794 riceParamPart3 |= (zeroCountPart3 << riceParam);
3795
3796 riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
3797 riceParamPart1 = (riceParamPart1 >> 1) ^ t[riceParamPart1 & 0x01];
3798 riceParamPart2 = (riceParamPart2 >> 1) ^ t[riceParamPart2 & 0x01];
3799 riceParamPart3 = (riceParamPart3 >> 1) ^ t[riceParamPart3 & 0x01];
3800
3801 pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 0);
3802 pSamplesOut[1] = riceParamPart1 + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 1);
3803 pSamplesOut[2] = riceParamPart2 + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 2);
3804 pSamplesOut[3] = riceParamPart3 + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 3);
3805
3806 pSamplesOut += 4;
3807 }
3808 } else {
3809 while (pSamplesOut < pSamplesOutEnd) {
3810 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0) ||
3811 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart1, &riceParamPart1) ||
3812 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart2, &riceParamPart2) ||
3813 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart3, &riceParamPart3)) {
3814 return DRFLAC_FALSE;
3815 }
3816
3817 riceParamPart0 &= riceParamMask;
3818 riceParamPart1 &= riceParamMask;
3819 riceParamPart2 &= riceParamMask;
3820 riceParamPart3 &= riceParamMask;
3821
3822 riceParamPart0 |= (zeroCountPart0 << riceParam);
3823 riceParamPart1 |= (zeroCountPart1 << riceParam);
3824 riceParamPart2 |= (zeroCountPart2 << riceParam);
3825 riceParamPart3 |= (zeroCountPart3 << riceParam);
3826
3827 riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
3828 riceParamPart1 = (riceParamPart1 >> 1) ^ t[riceParamPart1 & 0x01];
3829 riceParamPart2 = (riceParamPart2 >> 1) ^ t[riceParamPart2 & 0x01];
3830 riceParamPart3 = (riceParamPart3 >> 1) ^ t[riceParamPart3 & 0x01];
3831
3832 pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 0);
3833 pSamplesOut[1] = riceParamPart1 + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 1);
3834 pSamplesOut[2] = riceParamPart2 + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 2);
3835 pSamplesOut[3] = riceParamPart3 + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 3);
3836
3837 pSamplesOut += 4;
3838 }
3839 }
3840
3841 i = (count & ~3);
3842 while (i < count) {
3843 /* Rice extraction. */
3844 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0)) {
3845 return DRFLAC_FALSE;
3846 }
3847
3848 /* Rice reconstruction. */
3849 riceParamPart0 &= riceParamMask;
3850 riceParamPart0 |= (zeroCountPart0 << riceParam);
3851 riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
3852 /*riceParamPart0 = (riceParamPart0 >> 1) ^ (~(riceParamPart0 & 0x01) + 1);*/
3853
3854 /* Sample reconstruction. */
3855 if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
3856 pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 0);
3857 } else {
3858 pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 0);
3859 }
3860
3861 i += 1;
3862 pSamplesOut += 1;
3863 }
3864
3865 return DRFLAC_TRUE;
3866}
3867
3868#if defined(DRFLAC_SUPPORT_SSE2)
3869static DRFLAC_INLINE __m128i drflac__mm_packs_interleaved_epi32(__m128i a, __m128i b)
3870{
3871 __m128i r;
3872
3873 /* Pack. */
3874 r = _mm_packs_epi32(a, b);
3875
3876 /* a3a2 a1a0 b3b2 b1b0 -> a3a2 b3b2 a1a0 b1b0 */
3877 r = _mm_shuffle_epi32(r, _MM_SHUFFLE(3, 1, 2, 0));
3878
3879 /* a3a2 b3b2 a1a0 b1b0 -> a3b3 a2b2 a1b1 a0b0 */
3880 r = _mm_shufflehi_epi16(r, _MM_SHUFFLE(3, 1, 2, 0));
3881 r = _mm_shufflelo_epi16(r, _MM_SHUFFLE(3, 1, 2, 0));
3882
3883 return r;
3884}
3885#endif
3886
3887#if defined(DRFLAC_SUPPORT_SSE41)
3888static DRFLAC_INLINE __m128i drflac__mm_not_si128(__m128i a)
3889{
3890 return _mm_xor_si128(a, _mm_cmpeq_epi32(_mm_setzero_si128(), _mm_setzero_si128()));
3891}
3892
3893static DRFLAC_INLINE __m128i drflac__mm_hadd_epi32(__m128i x)
3894{
3895 __m128i x64 = _mm_add_epi32(x, _mm_shuffle_epi32(x, _MM_SHUFFLE(1, 0, 3, 2)));
3896 __m128i x32 = _mm_shufflelo_epi16(x64, _MM_SHUFFLE(1, 0, 3, 2));
3897 return _mm_add_epi32(x64, x32);
3898}
3899
3900static DRFLAC_INLINE __m128i drflac__mm_hadd_epi64(__m128i x)
3901{
3902 return _mm_add_epi64(x, _mm_shuffle_epi32(x, _MM_SHUFFLE(1, 0, 3, 2)));
3903}
3904
3905static DRFLAC_INLINE __m128i drflac__mm_srai_epi64(__m128i x, int count)
3906{
3907 /*
3908 To simplify this we are assuming count < 32. This restriction allows us to work on a low side and a high side. The low side
3909 is shifted with zero bits, whereas the right side is shifted with sign bits.
3910 */
3911 __m128i lo = _mm_srli_epi64(x, count);
3912 __m128i hi = _mm_srai_epi32(x, count);
3913
3914 hi = _mm_and_si128(hi, _mm_set_epi32(0xFFFFFFFF, 0, 0xFFFFFFFF, 0)); /* The high part needs to have the low part cleared. */
3915
3916 return _mm_or_si128(lo, hi);
3917}
3918
3919static drflac_bool32 drflac__decode_samples_with_residual__rice__sse41_32(drflac_bs* bs, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
3920{
3921 int i;
3922 drflac_uint32 riceParamMask;
3923 drflac_int32* pDecodedSamples = pSamplesOut;
3924 drflac_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3);
3925 drflac_uint32 zeroCountParts0 = 0;
3926 drflac_uint32 zeroCountParts1 = 0;
3927 drflac_uint32 zeroCountParts2 = 0;
3928 drflac_uint32 zeroCountParts3 = 0;
3929 drflac_uint32 riceParamParts0 = 0;
3930 drflac_uint32 riceParamParts1 = 0;
3931 drflac_uint32 riceParamParts2 = 0;
3932 drflac_uint32 riceParamParts3 = 0;
3933 __m128i coefficients128_0;
3934 __m128i coefficients128_4;
3935 __m128i coefficients128_8;
3936 __m128i samples128_0;
3937 __m128i samples128_4;
3938 __m128i samples128_8;
3939 __m128i riceParamMask128;
3940
3941 const drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
3942
3943 riceParamMask = (drflac_uint32)~((~0UL) << riceParam);
3944 riceParamMask128 = _mm_set1_epi32(riceParamMask);
3945
3946 /* Pre-load. */
3947 coefficients128_0 = _mm_setzero_si128();
3948 coefficients128_4 = _mm_setzero_si128();
3949 coefficients128_8 = _mm_setzero_si128();
3950
3951 samples128_0 = _mm_setzero_si128();
3952 samples128_4 = _mm_setzero_si128();
3953 samples128_8 = _mm_setzero_si128();
3954
3955 /*
3956 Pre-loading the coefficients and prior samples is annoying because we need to ensure we don't try reading more than
3957 what's available in the input buffers. It would be convenient to use a fall-through switch to do this, but this results
3958 in strict aliasing warnings with GCC. To work around this I'm just doing something hacky. This feels a bit convoluted
3959 so I think there's opportunity for this to be simplified.
3960 */
3961#if 1
3962 {
3963 int runningOrder = order;
3964
3965 /* 0 - 3. */
3966 if (runningOrder >= 4) {
3967 coefficients128_0 = _mm_loadu_si128((const __m128i*)(coefficients + 0));
3968 samples128_0 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 4));
3969 runningOrder -= 4;
3970 } else {
3971 switch (runningOrder) {
3972 case 3: coefficients128_0 = _mm_set_epi32(0, coefficients[2], coefficients[1], coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], pSamplesOut[-2], pSamplesOut[-3], 0); break;
3973 case 2: coefficients128_0 = _mm_set_epi32(0, 0, coefficients[1], coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], pSamplesOut[-2], 0, 0); break;
3974 case 1: coefficients128_0 = _mm_set_epi32(0, 0, 0, coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], 0, 0, 0); break;
3975 }
3976 runningOrder = 0;
3977 }
3978
3979 /* 4 - 7 */
3980 if (runningOrder >= 4) {
3981 coefficients128_4 = _mm_loadu_si128((const __m128i*)(coefficients + 4));
3982 samples128_4 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 8));
3983 runningOrder -= 4;
3984 } else {
3985 switch (runningOrder) {
3986 case 3: coefficients128_4 = _mm_set_epi32(0, coefficients[6], coefficients[5], coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], pSamplesOut[-6], pSamplesOut[-7], 0); break;
3987 case 2: coefficients128_4 = _mm_set_epi32(0, 0, coefficients[5], coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], pSamplesOut[-6], 0, 0); break;
3988 case 1: coefficients128_4 = _mm_set_epi32(0, 0, 0, coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], 0, 0, 0); break;
3989 }
3990 runningOrder = 0;
3991 }
3992
3993 /* 8 - 11 */
3994 if (runningOrder == 4) {
3995 coefficients128_8 = _mm_loadu_si128((const __m128i*)(coefficients + 8));
3996 samples128_8 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 12));
3997 runningOrder -= 4;
3998 } else {
3999 switch (runningOrder) {
4000 case 3: coefficients128_8 = _mm_set_epi32(0, coefficients[10], coefficients[9], coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], pSamplesOut[-10], pSamplesOut[-11], 0); break;
4001 case 2: coefficients128_8 = _mm_set_epi32(0, 0, coefficients[9], coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], pSamplesOut[-10], 0, 0); break;
4002 case 1: coefficients128_8 = _mm_set_epi32(0, 0, 0, coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], 0, 0, 0); break;
4003 }
4004 runningOrder = 0;
4005 }
4006
4007 /* Coefficients need to be shuffled for our streaming algorithm below to work. Samples are already in the correct order from the loading routine above. */
4008 coefficients128_0 = _mm_shuffle_epi32(coefficients128_0, _MM_SHUFFLE(0, 1, 2, 3));
4009 coefficients128_4 = _mm_shuffle_epi32(coefficients128_4, _MM_SHUFFLE(0, 1, 2, 3));
4010 coefficients128_8 = _mm_shuffle_epi32(coefficients128_8, _MM_SHUFFLE(0, 1, 2, 3));
4011 }
4012#else
4013 /* This causes strict-aliasing warnings with GCC. */
4014 switch (order)
4015 {
4016 case 12: ((drflac_int32*)&coefficients128_8)[0] = coefficients[11]; ((drflac_int32*)&samples128_8)[0] = pDecodedSamples[-12];
4017 case 11: ((drflac_int32*)&coefficients128_8)[1] = coefficients[10]; ((drflac_int32*)&samples128_8)[1] = pDecodedSamples[-11];
4018 case 10: ((drflac_int32*)&coefficients128_8)[2] = coefficients[ 9]; ((drflac_int32*)&samples128_8)[2] = pDecodedSamples[-10];
4019 case 9: ((drflac_int32*)&coefficients128_8)[3] = coefficients[ 8]; ((drflac_int32*)&samples128_8)[3] = pDecodedSamples[- 9];
4020 case 8: ((drflac_int32*)&coefficients128_4)[0] = coefficients[ 7]; ((drflac_int32*)&samples128_4)[0] = pDecodedSamples[- 8];
4021 case 7: ((drflac_int32*)&coefficients128_4)[1] = coefficients[ 6]; ((drflac_int32*)&samples128_4)[1] = pDecodedSamples[- 7];
4022 case 6: ((drflac_int32*)&coefficients128_4)[2] = coefficients[ 5]; ((drflac_int32*)&samples128_4)[2] = pDecodedSamples[- 6];
4023 case 5: ((drflac_int32*)&coefficients128_4)[3] = coefficients[ 4]; ((drflac_int32*)&samples128_4)[3] = pDecodedSamples[- 5];
4024 case 4: ((drflac_int32*)&coefficients128_0)[0] = coefficients[ 3]; ((drflac_int32*)&samples128_0)[0] = pDecodedSamples[- 4];
4025 case 3: ((drflac_int32*)&coefficients128_0)[1] = coefficients[ 2]; ((drflac_int32*)&samples128_0)[1] = pDecodedSamples[- 3];
4026 case 2: ((drflac_int32*)&coefficients128_0)[2] = coefficients[ 1]; ((drflac_int32*)&samples128_0)[2] = pDecodedSamples[- 2];
4027 case 1: ((drflac_int32*)&coefficients128_0)[3] = coefficients[ 0]; ((drflac_int32*)&samples128_0)[3] = pDecodedSamples[- 1];
4028 }
4029#endif
4030
4031 /* For this version we are doing one sample at a time. */
4032 while (pDecodedSamples < pDecodedSamplesEnd) {
4033 __m128i prediction128;
4034 __m128i zeroCountPart128;
4035 __m128i riceParamPart128;
4036
4037 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0) ||
4038 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts1, &riceParamParts1) ||
4039 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts2, &riceParamParts2) ||
4040 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts3, &riceParamParts3)) {
4041 return DRFLAC_FALSE;
4042 }
4043
4044 zeroCountPart128 = _mm_set_epi32(zeroCountParts3, zeroCountParts2, zeroCountParts1, zeroCountParts0);
4045 riceParamPart128 = _mm_set_epi32(riceParamParts3, riceParamParts2, riceParamParts1, riceParamParts0);
4046
4047 riceParamPart128 = _mm_and_si128(riceParamPart128, riceParamMask128);
4048 riceParamPart128 = _mm_or_si128(riceParamPart128, _mm_slli_epi32(zeroCountPart128, riceParam));
4049 riceParamPart128 = _mm_xor_si128(_mm_srli_epi32(riceParamPart128, 1), _mm_add_epi32(drflac__mm_not_si128(_mm_and_si128(riceParamPart128, _mm_set1_epi32(0x01))), _mm_set1_epi32(0x01))); /* <-- SSE2 compatible */
4050 /*riceParamPart128 = _mm_xor_si128(_mm_srli_epi32(riceParamPart128, 1), _mm_mullo_epi32(_mm_and_si128(riceParamPart128, _mm_set1_epi32(0x01)), _mm_set1_epi32(0xFFFFFFFF)));*/ /* <-- Only supported from SSE4.1 and is slower in my testing... */
4051
4052 if (order <= 4) {
4053 for (i = 0; i < 4; i += 1) {
4054 prediction128 = _mm_mullo_epi32(coefficients128_0, samples128_0);
4055
4056 /* Horizontal add and shift. */
4057 prediction128 = drflac__mm_hadd_epi32(prediction128);
4058 prediction128 = _mm_srai_epi32(prediction128, shift);
4059 prediction128 = _mm_add_epi32(riceParamPart128, prediction128);
4060
4061 samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4);
4062 riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4);
4063 }
4064 } else if (order <= 8) {
4065 for (i = 0; i < 4; i += 1) {
4066 prediction128 = _mm_mullo_epi32(coefficients128_4, samples128_4);
4067 prediction128 = _mm_add_epi32(prediction128, _mm_mullo_epi32(coefficients128_0, samples128_0));
4068
4069 /* Horizontal add and shift. */
4070 prediction128 = drflac__mm_hadd_epi32(prediction128);
4071 prediction128 = _mm_srai_epi32(prediction128, shift);
4072 prediction128 = _mm_add_epi32(riceParamPart128, prediction128);
4073
4074 samples128_4 = _mm_alignr_epi8(samples128_0, samples128_4, 4);
4075 samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4);
4076 riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4);
4077 }
4078 } else {
4079 for (i = 0; i < 4; i += 1) {
4080 prediction128 = _mm_mullo_epi32(coefficients128_8, samples128_8);
4081 prediction128 = _mm_add_epi32(prediction128, _mm_mullo_epi32(coefficients128_4, samples128_4));
4082 prediction128 = _mm_add_epi32(prediction128, _mm_mullo_epi32(coefficients128_0, samples128_0));
4083
4084 /* Horizontal add and shift. */
4085 prediction128 = drflac__mm_hadd_epi32(prediction128);
4086 prediction128 = _mm_srai_epi32(prediction128, shift);
4087 prediction128 = _mm_add_epi32(riceParamPart128, prediction128);
4088
4089 samples128_8 = _mm_alignr_epi8(samples128_4, samples128_8, 4);
4090 samples128_4 = _mm_alignr_epi8(samples128_0, samples128_4, 4);
4091 samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4);
4092 riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4);
4093 }
4094 }
4095
4096 /* We store samples in groups of 4. */
4097 _mm_storeu_si128((__m128i*)pDecodedSamples, samples128_0);
4098 pDecodedSamples += 4;
4099 }
4100
4101 /* Make sure we process the last few samples. */
4102 i = (count & ~3);
4103 while (i < (int)count) {
4104 /* Rice extraction. */
4105 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0)) {
4106 return DRFLAC_FALSE;
4107 }
4108
4109 /* Rice reconstruction. */
4110 riceParamParts0 &= riceParamMask;
4111 riceParamParts0 |= (zeroCountParts0 << riceParam);
4112 riceParamParts0 = (riceParamParts0 >> 1) ^ t[riceParamParts0 & 0x01];
4113
4114 /* Sample reconstruction. */
4115 pDecodedSamples[0] = riceParamParts0 + drflac__calculate_prediction_32(order, shift, coefficients, pDecodedSamples);
4116
4117 i += 1;
4118 pDecodedSamples += 1;
4119 }
4120
4121 return DRFLAC_TRUE;
4122}
4123
4124static drflac_bool32 drflac__decode_samples_with_residual__rice__sse41_64(drflac_bs* bs, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
4125{
4126 int i;
4127 drflac_uint32 riceParamMask;
4128 drflac_int32* pDecodedSamples = pSamplesOut;
4129 drflac_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3);
4130 drflac_uint32 zeroCountParts0 = 0;
4131 drflac_uint32 zeroCountParts1 = 0;
4132 drflac_uint32 zeroCountParts2 = 0;
4133 drflac_uint32 zeroCountParts3 = 0;
4134 drflac_uint32 riceParamParts0 = 0;
4135 drflac_uint32 riceParamParts1 = 0;
4136 drflac_uint32 riceParamParts2 = 0;
4137 drflac_uint32 riceParamParts3 = 0;
4138 __m128i coefficients128_0;
4139 __m128i coefficients128_4;
4140 __m128i coefficients128_8;
4141 __m128i samples128_0;
4142 __m128i samples128_4;
4143 __m128i samples128_8;
4144 __m128i prediction128;
4145 __m128i riceParamMask128;
4146
4147 const drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
4148
4149 DRFLAC_ASSERT(order <= 12);
4150
4151 riceParamMask = (drflac_uint32)~((~0UL) << riceParam);
4152 riceParamMask128 = _mm_set1_epi32(riceParamMask);
4153
4154 prediction128 = _mm_setzero_si128();
4155
4156 /* Pre-load. */
4157 coefficients128_0 = _mm_setzero_si128();
4158 coefficients128_4 = _mm_setzero_si128();
4159 coefficients128_8 = _mm_setzero_si128();
4160
4161 samples128_0 = _mm_setzero_si128();
4162 samples128_4 = _mm_setzero_si128();
4163 samples128_8 = _mm_setzero_si128();
4164
4165#if 1
4166 {
4167 int runningOrder = order;
4168
4169 /* 0 - 3. */
4170 if (runningOrder >= 4) {
4171 coefficients128_0 = _mm_loadu_si128((const __m128i*)(coefficients + 0));
4172 samples128_0 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 4));
4173 runningOrder -= 4;
4174 } else {
4175 switch (runningOrder) {
4176 case 3: coefficients128_0 = _mm_set_epi32(0, coefficients[2], coefficients[1], coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], pSamplesOut[-2], pSamplesOut[-3], 0); break;
4177 case 2: coefficients128_0 = _mm_set_epi32(0, 0, coefficients[1], coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], pSamplesOut[-2], 0, 0); break;
4178 case 1: coefficients128_0 = _mm_set_epi32(0, 0, 0, coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], 0, 0, 0); break;
4179 }
4180 runningOrder = 0;
4181 }
4182
4183 /* 4 - 7 */