Merge branch 'raysan5:master' into master

This commit is contained in:
Luiz Pestana 2022-08-25 11:56:35 -03:00 • committed by GitHub
commit ad6be8f9d3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
30 changed files with 12940 additions and 51971 deletions

View file

@ -1,7 +1,7 @@
# Setup the project and settings
project(raylib C)
set(PROJECT_VERSION 4.0.0)
set(API_VERSION 400)
set(PROJECT_VERSION 4.2.0)
set(API_VERSION 420)
include(GNUInstallDirs)
include(JoinPaths)
@ -25,7 +25,6 @@ set(raylib_public_headers
raylib.h
rlgl.h
raymath.h
raudio.h
)
# Sources to be compiled

View file

@ -8,8 +8,8 @@
# PLATFORM_DESKTOP: OSX/macOS (arm64, x86_64)
# PLATFORM_DESKTOP: FreeBSD, OpenBSD, NetBSD, DragonFly
# PLATFORM_ANDROID: Android (arm, i686, arm64, x86_64)
# PLATFORM_RPI: Raspberry Pi (Raspbian)
# PLATFORM_DRM: Linux native mode, including Raspberry Pi 4 with V3D fkms driver
# PLATFORM_RPI: Raspberry Pi (deprecated - RPI OS Buster only)
# PLATFORM_DRM: Linux native mode, including Raspberry Pi (RPI OS Bullseye)
# PLATFORM_WEB: HTML5 (Chrome, Firefox)
# PLATFORM_NX: Switch LibNX
#
@ -46,8 +46,8 @@
PLATFORM ?= PLATFORM_DESKTOP
# Define required raylib variables
RAYLIB_VERSION = 4.0.0
RAYLIB_API_VERSION = 400
RAYLIB_VERSION = 4.2.0
RAYLIB_API_VERSION = 420
# Define raylib source code path
RAYLIB_SRC_PATH ?= ../src
@ -196,7 +196,7 @@ ifeq ($(PLATFORM),PLATFORM_WEB)
CLANG_PATH = $(EMSDK_PATH)/upstream/bin
PYTHON_PATH = $(EMSDK_PATH)/python/3.9.2-1_64bit
NODE_PATH = $(EMSDK_PATH)/node/14.15.5_64bit/bin
export PATH = $(EMSDK_PATH);$(EMSCRIPTEN_PATH);$(CLANG_PATH);$(NODE_PATH);$(PYTHON_PATH);C:\raylib\MinGW\bin:$$(PATH)
export PATH := $(EMSDK_PATH):$(EMSCRIPTEN_PATH):$(CLANG_PATH):$(NODE_PATH):$(PYTHON_PATH):C:\raylib\MinGW\bin:$(PATH)
endif
ifeq ($(PLATFORM),PLATFORM_ANDROID)
@ -334,6 +334,7 @@ ifneq ($(RAYLIB_CONFIG_FLAGS), NONE)
endif
ifeq ($(PLATFORM), PLATFORM_WEB)
# NOTE: When using multi-threading in the user code, it requires -pthread enabled
CFLAGS += -std=gnu99
else
CFLAGS += -std=c99
@ -479,11 +480,13 @@ endif
# Define library paths containing required libs: LDFLAGS
# NOTE: This is only required for dynamic library generation
#------------------------------------------------------------------------------------------------
LDFLAGS = -L. -L$(RAYLIB_RELEASE_PATH)
LDFLAGS = $(CUSTOM_LDFLAGS) -L. -L$(RAYLIB_RELEASE_PATH)
ifeq ($(PLATFORM),PLATFORM_DESKTOP)
ifeq ($(PLATFORM_OS),WINDOWS)
LDFLAGS += -Wl,--out-implib,$(RAYLIB_RELEASE_PATH)/lib$(RAYLIB_LIB_NAME)dll.a
ifneq ($(CC), tcc)
LDFLAGS += -Wl,--out-implib,$(RAYLIB_RELEASE_PATH)/lib$(RAYLIB_LIB_NAME)dll.a
endif
endif
ifeq ($(PLATFORM_OS),OSX)
LDFLAGS += -compatibility_version $(RAYLIB_API_VERSION) -current_version $(RAYLIB_VERSION)
@ -496,7 +499,7 @@ ifeq ($(PLATFORM),PLATFORM_DESKTOP)
endif
endif
ifeq ($(PLATFORM),PLATFORM_RPI)
LDFLAGS += -Wl,-soname,lib$(RAYLIB_LIB_NAME).so.$(RAYLIB_API_VERSION) -L$(RPI_TOOLCHAIN_SYSROOT)/opt/vc/lib
LDFLAGS += -Wl,-soname,lib$(RAYLIB_LIB_NAME).so.$(RAYLIB_API_VERSION) -L$(RPI_TOOLCHAIN_SYSROOT)/opt/vc/lib
endif
ifeq ($(PLATFORM),PLATFORM_DRM)
LDFLAGS += -Wl,-soname,lib$(RAYLIB_LIB_NAME).so.$(RAYLIB_API_VERSION)
@ -517,13 +520,19 @@ endif
#------------------------------------------------------------------------------------------------
ifeq ($(PLATFORM),PLATFORM_DESKTOP)
ifeq ($(PLATFORM_OS),WINDOWS)
LDLIBS = -static-libgcc -lopengl32 -lgdi32 -lwinmm
ifeq ($(CC), tcc)
LDLIBS = -lopengl32 -lgdi32 -lwinmm -lshell32
else
LDLIBS = -static-libgcc -lopengl32 -lgdi32 -lwinmm
endif
endif
ifeq ($(PLATFORM_OS),LINUX)
LDLIBS = -lGL -lc -lm -lpthread -ldl -lrt
ifeq ($(USE_WAYLAND_DISPLAY),FALSE)
LDLIBS += -lX11
endif
# TODO: On ARM 32bit arch, miniaudio requires atomics library
#LDLIBS += -latomic
endif
ifeq ($(PLATFORM_OS),OSX)
LDLIBS = -framework OpenGL -framework Cocoa -framework IOKit -framework CoreAudio -framework CoreVideo
@ -775,7 +784,6 @@ ifeq ($(ROOT),root)
cp --update raylib.h $(RAYLIB_H_INSTALL_PATH)/raylib.h
cp --update raymath.h $(RAYLIB_H_INSTALL_PATH)/raymath.h
cp --update rlgl.h $(RAYLIB_H_INSTALL_PATH)/rlgl.h
cp --update extras/physac.h $(RAYLIB_H_INSTALL_PATH)/physac.h
@echo "raylib development files installed/updated!"
else
@echo "This function currently works on GNU/Linux systems. Add yours today (^;"
@ -803,7 +811,6 @@ ifeq ($(ROOT),root)
rm --force --interactive --verbose $(RAYLIB_H_INSTALL_PATH)/raylib.h
rm --force --interactive --verbose $(RAYLIB_H_INSTALL_PATH)/raymath.h
rm --force --interactive --verbose $(RAYLIB_H_INSTALL_PATH)/rlgl.h
rm --force --interactive --verbose $(RAYLIB_H_INSTALL_PATH)/physac.h
@echo "raylib development files removed!"
else
@echo "This function currently works on GNU/Linux systems. Add yours today (^;"

View file

@ -6,7 +6,7 @@
*
* LICENSE: zlib/libpng
*
* Copyright (c) 2018-2021 Ahmad Fatoum & Ramon Santamaria (@raysan5)
* Copyright (c) 2018-2022 Ahmad Fatoum & Ramon Santamaria (@raysan5)
*
* This software is provided "as-is", without any express or implied warranty. In no event
* will the authors be held liable for any damages arising from the use of this software.
@ -46,8 +46,6 @@
#define SUPPORT_MOUSE_GESTURES 1
// Reconfigure standard input to receive key inputs, works with SSH connection.
#define SUPPORT_SSH_KEYBOARD_RPI 1
// Draw a mouse pointer on screen
//#define SUPPORT_MOUSE_CURSOR_POINT 1
// Setting a higher resolution can improve the accuracy of time-out intervals in wait functions.
// However, it can also reduce overall system performance, because the thread scheduler switches tasks more often.
#define SUPPORT_WINMM_HIGHRES_TIMER 1
@ -63,8 +61,6 @@
#define SUPPORT_GIF_RECORDING 1
// Support CompressData() and DecompressData() functions
#define SUPPORT_COMPRESSION_API 1
// Support saving binary data automatically to a generated storage.data file. This file is managed internally.
#define SUPPORT_DATA_STORAGE 1
// Support automatic generated events, loading and recording of those events when required
//#define SUPPORT_EVENTS_AUTOMATION 1
// Support custom frame control, only for advance users
@ -78,11 +74,8 @@
// rcore: Configuration values
//------------------------------------------------------------------------------------
#if defined(__linux__)
#define MAX_FILEPATH_LENGTH 4096 // Maximum length for filepaths (Linux PATH_MAX default value)
#else
#define MAX_FILEPATH_LENGTH 512 // Maximum length supported for filepaths
#endif
#define MAX_FILEPATH_CAPACITY 8192 // Maximum file paths capacity
#define MAX_FILEPATH_LENGTH 4096 // Maximum length for filepaths (Linux PATH_MAX default value)
#define MAX_KEYBOARD_KEYS 512 // Maximum number of keyboard keys supported
#define MAX_MOUSE_BUTTONS 8 // Maximum number of mouse buttons supported
@ -93,8 +86,6 @@
#define MAX_KEY_PRESSED_QUEUE 16 // Maximum number of keys in the key input queue
#define MAX_CHAR_PRESSED_QUEUE 16 // Maximum number of characters in the char input queue
#define STORAGE_DATA_FILE "storage.data" // Automatic storage filename
#define MAX_DECOMPRESSION_SIZE 64 // Max size allocated for decompression in MB
@ -205,6 +196,7 @@
#define SUPPORT_FILEFORMAT_IQM 1
#define SUPPORT_FILEFORMAT_GLTF 1
#define SUPPORT_FILEFORMAT_VOX 1
#define SUPPORT_FILEFORMAT_M3D 1
// Support procedural mesh generation functions, uses external par_shapes.h library
// NOTE: Some generated meshes DO NOT include generated texture coordinates
#define SUPPORT_MESH_GENERATION 1

452
src/external/cgltf.h vendored
View file

@ -1,7 +1,7 @@
/**
* cgltf - a single-file glTF 2.0 parser written in C99.
*
* Version: 1.11
* Version: 1.12
*
* Website: https://github.com/jkuhlmann/cgltf
*
@ -63,7 +63,7 @@
* By passing null for the output pointer, users can find out how many floats are required in the
* output buffer.
*
* `cgltf_accessor_num_components` is a tiny utility that tells you the dimensionality of
* `cgltf_num_components` is a tiny utility that tells you the dimensionality of
* a certain accessor type. This can be used before `cgltf_accessor_unpack_floats` to help allocate
* the necessary amount of memory.
*
@ -99,6 +99,7 @@ extern "C" {
#endif
typedef size_t cgltf_size;
typedef long long int cgltf_ssize;
typedef float cgltf_float;
typedef int cgltf_int;
typedef unsigned int cgltf_uint;
@ -109,6 +110,7 @@ typedef enum cgltf_file_type
cgltf_file_type_invalid,
cgltf_file_type_gltf,
cgltf_file_type_glb,
cgltf_file_type_max_enum
} cgltf_file_type;
typedef enum cgltf_result
@ -123,12 +125,13 @@ typedef enum cgltf_result
cgltf_result_io_error,
cgltf_result_out_of_memory,
cgltf_result_legacy_gltf,
cgltf_result_max_enum
} cgltf_result;
typedef struct cgltf_memory_options
{
void* (*alloc)(void* user, cgltf_size size);
void (*free) (void* user, void* ptr);
void* (*alloc_func)(void* user, cgltf_size size);
void (*free_func) (void* user, void* ptr);
void* user_data;
} cgltf_memory_options;
@ -152,6 +155,7 @@ typedef enum cgltf_buffer_view_type
cgltf_buffer_view_type_invalid,
cgltf_buffer_view_type_indices,
cgltf_buffer_view_type_vertices,
cgltf_buffer_view_type_max_enum
} cgltf_buffer_view_type;
typedef enum cgltf_attribute_type
@ -164,6 +168,8 @@ typedef enum cgltf_attribute_type
cgltf_attribute_type_color,
cgltf_attribute_type_joints,
cgltf_attribute_type_weights,
cgltf_attribute_type_custom,
cgltf_attribute_type_max_enum
} cgltf_attribute_type;
typedef enum cgltf_component_type
@ -175,6 +181,7 @@ typedef enum cgltf_component_type
cgltf_component_type_r_16u, /* UNSIGNED_SHORT */
cgltf_component_type_r_32u, /* UNSIGNED_INT */
cgltf_component_type_r_32f, /* FLOAT */
cgltf_component_type_max_enum
} cgltf_component_type;
typedef enum cgltf_type
@ -187,6 +194,7 @@ typedef enum cgltf_type
cgltf_type_mat2,
cgltf_type_mat3,
cgltf_type_mat4,
cgltf_type_max_enum
} cgltf_type;
typedef enum cgltf_primitive_type
@ -198,6 +206,7 @@ typedef enum cgltf_primitive_type
cgltf_primitive_type_triangles,
cgltf_primitive_type_triangle_strip,
cgltf_primitive_type_triangle_fan,
cgltf_primitive_type_max_enum
} cgltf_primitive_type;
typedef enum cgltf_alpha_mode
@ -205,6 +214,7 @@ typedef enum cgltf_alpha_mode
cgltf_alpha_mode_opaque,
cgltf_alpha_mode_mask,
cgltf_alpha_mode_blend,
cgltf_alpha_mode_max_enum
} cgltf_alpha_mode;
typedef enum cgltf_animation_path_type {
@ -213,18 +223,21 @@ typedef enum cgltf_animation_path_type {
cgltf_animation_path_type_rotation,
cgltf_animation_path_type_scale,
cgltf_animation_path_type_weights,
cgltf_animation_path_type_max_enum
} cgltf_animation_path_type;
typedef enum cgltf_interpolation_type {
cgltf_interpolation_type_linear,
cgltf_interpolation_type_step,
cgltf_interpolation_type_cubic_spline,
cgltf_interpolation_type_max_enum
} cgltf_interpolation_type;
typedef enum cgltf_camera_type {
cgltf_camera_type_invalid,
cgltf_camera_type_perspective,
cgltf_camera_type_orthographic,
cgltf_camera_type_max_enum
} cgltf_camera_type;
typedef enum cgltf_light_type {
@ -232,12 +245,14 @@ typedef enum cgltf_light_type {
cgltf_light_type_directional,
cgltf_light_type_point,
cgltf_light_type_spot,
cgltf_light_type_max_enum
} cgltf_light_type;
typedef enum cgltf_data_free_method {
cgltf_data_free_method_none,
cgltf_data_free_method_file_release,
cgltf_data_free_method_memory_free,
cgltf_data_free_method_max_enum
} cgltf_data_free_method;
typedef struct cgltf_extras {
@ -267,6 +282,7 @@ typedef enum cgltf_meshopt_compression_mode {
cgltf_meshopt_compression_mode_attributes,
cgltf_meshopt_compression_mode_triangles,
cgltf_meshopt_compression_mode_indices,
cgltf_meshopt_compression_mode_max_enum
} cgltf_meshopt_compression_mode;
typedef enum cgltf_meshopt_compression_filter {
@ -274,6 +290,7 @@ typedef enum cgltf_meshopt_compression_filter {
cgltf_meshopt_compression_filter_octahedral,
cgltf_meshopt_compression_filter_quaternion,
cgltf_meshopt_compression_filter_exponential,
cgltf_meshopt_compression_filter_max_enum
} cgltf_meshopt_compression_filter;
typedef struct cgltf_meshopt_compression
@ -474,6 +491,21 @@ typedef struct cgltf_sheen
cgltf_float sheen_roughness_factor;
} cgltf_sheen;
typedef struct cgltf_emissive_strength
{
cgltf_float emissive_strength;
} cgltf_emissive_strength;
typedef struct cgltf_iridescence
{
cgltf_float iridescence_factor;
cgltf_texture_view iridescence_texture;
cgltf_float iridescence_ior;
cgltf_float iridescence_thickness_min;
cgltf_float iridescence_thickness_max;
cgltf_texture_view iridescence_thickness_texture;
} cgltf_iridescence;
typedef struct cgltf_material
{
char* name;
@ -485,6 +517,8 @@ typedef struct cgltf_material
cgltf_bool has_ior;
cgltf_bool has_specular;
cgltf_bool has_sheen;
cgltf_bool has_emissive_strength;
cgltf_bool has_iridescence;
cgltf_pbr_metallic_roughness pbr_metallic_roughness;
cgltf_pbr_specular_glossiness pbr_specular_glossiness;
cgltf_clearcoat clearcoat;
@ -493,6 +527,8 @@ typedef struct cgltf_material
cgltf_sheen sheen;
cgltf_transmission transmission;
cgltf_volume volume;
cgltf_emissive_strength emissive_strength;
cgltf_iridescence iridescence;
cgltf_texture_view normal_texture;
cgltf_texture_view occlusion_texture;
cgltf_texture_view emissive_texture;
@ -524,6 +560,12 @@ typedef struct cgltf_draco_mesh_compression {
cgltf_size attributes_count;
} cgltf_draco_mesh_compression;
typedef struct cgltf_mesh_gpu_instancing {
cgltf_buffer_view* buffer_view;
cgltf_attribute* attributes;
cgltf_size attributes_count;
} cgltf_mesh_gpu_instancing;
typedef struct cgltf_primitive {
cgltf_primitive_type type;
cgltf_accessor* indices;
@ -628,6 +670,8 @@ struct cgltf_node {
cgltf_float scale[3];
cgltf_float matrix[16];
cgltf_extras extras;
cgltf_bool has_mesh_gpu_instancing;
cgltf_mesh_gpu_instancing mesh_gpu_instancing;
cgltf_size extensions_count;
cgltf_extension* extensions;
};
@ -779,8 +823,8 @@ cgltf_result cgltf_load_buffers(
cgltf_result cgltf_load_buffer_base64(const cgltf_options* options, cgltf_size size, const char* base64, void** out_data);
void cgltf_decode_string(char* string);
void cgltf_decode_uri(char* uri);
cgltf_size cgltf_decode_string(char* string);
cgltf_size cgltf_decode_uri(char* uri);
cgltf_result cgltf_validate(cgltf_data* data);
@ -829,6 +873,10 @@ cgltf_result cgltf_copy_extras_json(const cgltf_data* data, const cgltf_extras*
#include <stdlib.h> /* For malloc, free, atoi, atof */
#endif
#if CGLTF_VALIDATE_ENABLE_ASSERTS
#include <assert.h>
#endif
/* JSMN_PARENT_LINKS is necessary to make parsing large structures linear in input size */
#define JSMN_PARENT_LINKS
@ -920,7 +968,7 @@ static void* cgltf_calloc(cgltf_options* options, size_t element_size, cgltf_siz
{
return NULL;
}
void* result = options->memory.alloc(options->memory.user_data, element_size * count);
void* result = options->memory.alloc_func(options->memory.user_data, element_size * count);
if (!result)
{
return NULL;
@ -932,8 +980,8 @@ static void* cgltf_calloc(cgltf_options* options, size_t element_size, cgltf_siz
static 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)
{
(void)file_options;
void* (*memory_alloc)(void*, cgltf_size) = memory_options->alloc ? memory_options->alloc : &cgltf_default_alloc;
void (*memory_free)(void*, void*) = memory_options->free ? memory_options->free : &cgltf_default_free;
void* (*memory_alloc)(void*, cgltf_size) = memory_options->alloc_func ? memory_options->alloc_func : &cgltf_default_alloc;
void (*memory_free)(void*, void*) = memory_options->free_func ? memory_options->free_func : &cgltf_default_free;
FILE* file = fopen(path, "rb");
if (!file)
@ -948,11 +996,7 @@ static cgltf_result cgltf_default_file_read(const struct cgltf_memory_options* m
fseek(file, 0, SEEK_END);
#ifdef _WIN32
#ifdef __TINYC__
__int64 length = ftell(file);
#else
__int64 length = _ftelli64(file);
#endif
__int64 length = _ftelli64(file);
#else
long length = ftell(file);
#endif
@ -999,7 +1043,7 @@ static cgltf_result cgltf_default_file_read(const struct cgltf_memory_options* m
static void cgltf_default_file_release(const struct cgltf_memory_options* memory_options, const struct cgltf_file_options* file_options, void* data)
{
(void)file_options;
void (*memfree)(void*, void*) = memory_options->free ? memory_options->free : &cgltf_default_free;
void (*memfree)(void*, void*) = memory_options->free_func ? memory_options->free_func : &cgltf_default_free;
memfree(memory_options->user_data, data);
}
@ -1018,13 +1062,13 @@ cgltf_result cgltf_parse(const cgltf_options* options, const void* data, cgltf_s
}
cgltf_options fixed_options = *options;
if (fixed_options.memory.alloc == NULL)
if (fixed_options.memory.alloc_func == NULL)
{
fixed_options.memory.alloc = &cgltf_default_alloc;
fixed_options.memory.alloc_func = &cgltf_default_alloc;
}
if (fixed_options.memory.free == NULL)
if (fixed_options.memory.free_func == NULL)
{
fixed_options.memory.free = &cgltf_default_free;
fixed_options.memory.free_func = &cgltf_default_free;
}
uint32_t tmp;
@ -1189,8 +1233,8 @@ static void cgltf_combine_paths(char* path, const char* base, const char* uri)
static cgltf_result cgltf_load_buffer_file(const cgltf_options* options, cgltf_size size, const char* uri, const char* gltf_path, void** out_data)
{
void* (*memory_alloc)(void*, cgltf_size) = options->memory.alloc ? options->memory.alloc : &cgltf_default_alloc;
void (*memory_free)(void*, void*) = options->memory.free ? options->memory.free : &cgltf_default_free;
void* (*memory_alloc)(void*, cgltf_size) = options->memory.alloc_func ? options->memory.alloc_func : &cgltf_default_alloc;
void (*memory_free)(void*, void*) = options->memory.free_func ? options->memory.free_func : &cgltf_default_free;
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;
char* path = (char*)memory_alloc(options->memory.user_data, strlen(uri) + strlen(gltf_path) + 1);
@ -1216,8 +1260,8 @@ static cgltf_result cgltf_load_buffer_file(const cgltf_options* options, cgltf_s
cgltf_result cgltf_load_buffer_base64(const cgltf_options* options, cgltf_size size, const char* base64, void** out_data)
{
void* (*memory_alloc)(void*, cgltf_size) = options->memory.alloc ? options->memory.alloc : &cgltf_default_alloc;
void (*memory_free)(void*, void*) = options->memory.free ? options->memory.free : &cgltf_default_free;
void* (*memory_alloc)(void*, cgltf_size) = options->memory.alloc_func ? options->memory.alloc_func : &cgltf_default_alloc;
void (*memory_free)(void*, void*) = options->memory.free_func ? options->memory.free_func : &cgltf_default_free;
unsigned char* data = (unsigned char*)memory_alloc(options->memory.user_data, size);
if (!data)
@ -1270,25 +1314,29 @@ static int cgltf_unhex(char ch)
-1;
}
void cgltf_decode_string(char* string)
cgltf_size cgltf_decode_string(char* string)
{
char* read = strchr(string, '\\');
if (read == NULL)
char* read = string + strcspn(string, "\\");
if (*read == 0)
{
return;
return read - string;
}
char* write = string;
char* last = string;
while (read)
for (;;)
{
// Copy characters since last escaped sequence
cgltf_size written = read - last;
strncpy(write, last, written);
memmove(write, last, written);
write += written;
if (*read++ == 0)
{
break;
}
// jsmn already checked that all escape sequences are valid
++read;
switch (*read++)
{
case '\"': *write++ = '\"'; break;
@ -1330,13 +1378,14 @@ void cgltf_decode_string(char* string)
}
last = read;
read = strchr(read, '\\');
read += strcspn(read, "\\");
}
strcpy(write, last);
*write = 0;
return write - string;
}
void cgltf_decode_uri(char* uri)
cgltf_size cgltf_decode_uri(char* uri)
{
char* write = uri;
char* i = uri;
@ -1364,6 +1413,7 @@ void cgltf_decode_uri(char* uri)
}
*write = 0;
return write - uri;
}
cgltf_result cgltf_load_buffers(const cgltf_options* options, cgltf_data* data, const char* gltf_path)
@ -1699,10 +1749,10 @@ void cgltf_free_extensions(cgltf_data* data, cgltf_extension* extensions, cgltf_
{
for (cgltf_size i = 0; i < extensions_count; ++i)
{
data->memory.free(data->memory.user_data, extensions[i].name);
data->memory.free(data->memory.user_data, extensions[i].data);
data->memory.free_func(data->memory.user_data, extensions[i].name);
data->memory.free_func(data->memory.user_data, extensions[i].data);
}
data->memory.free(data->memory.user_data, extensions);
data->memory.free_func(data->memory.user_data, extensions);
}
void cgltf_free(cgltf_data* data)
@ -1714,16 +1764,16 @@ void cgltf_free(cgltf_data* data)
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;
data->memory.free(data->memory.user_data, data->asset.copyright);
data->memory.free(data->memory.user_data, data->asset.generator);
data->memory.free(data->memory.user_data, data->asset.version);
data->memory.free(data->memory.user_data, data->asset.min_version);
data->memory.free_func(data->memory.user_data, data->asset.copyright);
data->memory.free_func(data->memory.user_data, data->asset.generator);
data->memory.free_func(data->memory.user_data, data->asset.version);
data->memory.free_func(data->memory.user_data, data->asset.min_version);
cgltf_free_extensions(data, data->asset.extensions, data->asset.extensions_count);
for (cgltf_size i = 0; i < data->accessors_count; ++i)
{
data->memory.free(data->memory.user_data, data->accessors[i].name);
data->memory.free_func(data->memory.user_data, data->accessors[i].name);
if(data->accessors[i].is_sparse)
{
@ -1733,20 +1783,20 @@ void cgltf_free(cgltf_data* data)
}
cgltf_free_extensions(data, data->accessors[i].extensions, data->accessors[i].extensions_count);
}
data->memory.free(data->memory.user_data, data->accessors);
data->memory.free_func(data->memory.user_data, data->accessors);
for (cgltf_size i = 0; i < data->buffer_views_count; ++i)
{
data->memory.free(data->memory.user_data, data->buffer_views[i].name);
data->memory.free(data->memory.user_data, data->buffer_views[i].data);
data->memory.free_func(data->memory.user_data, data->buffer_views[i].name);
data->memory.free_func(data->memory.user_data, data->buffer_views[i].data);
cgltf_free_extensions(data, data->buffer_views[i].extensions, data->buffer_views[i].extensions_count);
}
data->memory.free(data->memory.user_data, data->buffer_views);
data->memory.free_func(data->memory.user_data, data->buffer_views);
for (cgltf_size i = 0; i < data->buffers_count; ++i)
{
data->memory.free(data->memory.user_data, data->buffers[i].name);
data->memory.free_func(data->memory.user_data, data->buffers[i].name);
if (data->buffers[i].data_free_method == cgltf_data_free_method_file_release)
{
@ -1754,74 +1804,74 @@ void cgltf_free(cgltf_data* data)
}
else if (data->buffers[i].data_free_method == cgltf_data_free_method_memory_free)
{
data->memory.free(data->memory.user_data, data->buffers[i].data);
data->memory.free_func(data->memory.user_data, data->buffers[i].data);
}
data->memory.free(data->memory.user_data, data->buffers[i].uri);
data->memory.free_func(data->memory.user_data, data->buffers[i].uri);
cgltf_free_extensions(data, data->buffers[i].extensions, data->buffers[i].extensions_count);
}
data->memory.free(data->memory.user_data, data->buffers);
data->memory.free_func(data->memory.user_data, data->buffers);
for (cgltf_size i = 0; i < data->meshes_count; ++i)
{
data->memory.free(data->memory.user_data, data->meshes[i].name);
data->memory.free_func(data->memory.user_data, data->meshes[i].name);
for (cgltf_size j = 0; j < data->meshes[i].primitives_count; ++j)
{
for (cgltf_size k = 0; k < data->meshes[i].primitives[j].attributes_count; ++k)
{
data->memory.free(data->memory.user_data, data->meshes[i].primitives[j].attributes[k].name);
data->memory.free_func(data->memory.user_data, data->meshes[i].primitives[j].attributes[k].name);
}
data->memory.free(data->memory.user_data, data->meshes[i].primitives[j].attributes);
data->memory.free_func(data->memory.user_data, data->meshes[i].primitives[j].attributes);
for (cgltf_size k = 0; k < data->meshes[i].primitives[j].targets_count; ++k)
{
for (cgltf_size m = 0; m < data->meshes[i].primitives[j].targets[k].attributes_count; ++m)
{
data->memory.free(data->memory.user_data, data->meshes[i].primitives[j].targets[k].attributes[m].name);
data->memory.free_func(data->memory.user_data, data->meshes[i].primitives[j].targets[k].attributes[m].name);
}
data->memory.free(data->memory.user_data, data->meshes[i].primitives[j].targets[k].attributes);
data->memory.free_func(data->memory.user_data, data->meshes[i].primitives[j].targets[k].attributes);
}
data->memory.free(data->memory.user_data, data->meshes[i].primitives[j].targets);
data->memory.free_func(data->memory.user_data, data->meshes[i].primitives[j].targets);
if (data->meshes[i].primitives[j].has_draco_mesh_compression)
{
for (cgltf_size k = 0; k < data->meshes[i].primitives[j].draco_mesh_compression.attributes_count; ++k)
{
data->memory.free(data->memory.user_data, data->meshes[i].primitives[j].draco_mesh_compression.attributes[k].name);
data->memory.free_func(data->memory.user_data, data->meshes[i].primitives[j].draco_mesh_compression.attributes[k].name);
}
data->memory.free(data->memory.user_data, data->meshes[i].primitives[j].draco_mesh_compression.attributes);
data->memory.free_func(data->memory.user_data, data->meshes[i].primitives[j].draco_mesh_compression.attributes);
}
data->memory.free(data->memory.user_data, data->meshes[i].primitives[j].mappings);
data->memory.free_func(data->memory.user_data, data->meshes[i].primitives[j].mappings);
cgltf_free_extensions(data, data->meshes[i].primitives[j].extensions, data->meshes[i].primitives[j].extensions_count);
}
data->memory.free(data->memory.user_data, data->meshes[i].primitives);
data->memory.free(data->memory.user_data, data->meshes[i].weights);
data->memory.free_func(data->memory.user_data, data->meshes[i].primitives);
data->memory.free_func(data->memory.user_data, data->meshes[i].weights);
for (cgltf_size j = 0; j < data->meshes[i].target_names_count; ++j)
{
data->memory.free(data->memory.user_data, data->meshes[i].target_names[j]);
data->memory.free_func(data->memory.user_data, data->meshes[i].target_names[j]);
}
cgltf_free_extensions(data, data->meshes[i].extensions, data->meshes[i].extensions_count);
data->memory.free(data->memory.user_data, data->meshes[i].target_names);
data->memory.free_func(data->memory.user_data, data->meshes[i].target_names);
}
data->memory.free(data->memory.user_data, data->meshes);
data->memory.free_func(data->memory.user_data, data->meshes);
for (cgltf_size i = 0; i < data->materials_count; ++i)
{
data->memory.free(data->memory.user_data, data->materials[i].name);
data->memory.free_func(data->memory.user_data, data->materials[i].name);
if(data->materials[i].has_pbr_metallic_roughness)
{
@ -1857,6 +1907,11 @@ void cgltf_free(cgltf_data* data)
cgltf_free_extensions(data, data->materials[i].sheen.sheen_color_texture.extensions, data->materials[i].sheen.sheen_color_texture.extensions_count);
cgltf_free_extensions(data, data->materials[i].sheen.sheen_roughness_texture.extensions, data->materials[i].sheen.sheen_roughness_texture.extensions_count);
}
if(data->materials[i].has_iridescence)
{
cgltf_free_extensions(data, data->materials[i].iridescence.iridescence_texture.extensions, data->materials[i].iridescence.iridescence_texture.extensions_count);
cgltf_free_extensions(data, data->materials[i].iridescence.iridescence_thickness_texture.extensions, data->materials[i].iridescence.iridescence_thickness_texture.extensions_count);
}
cgltf_free_extensions(data, data->materials[i].normal_texture.extensions, data->materials[i].normal_texture.extensions_count);
cgltf_free_extensions(data, data->materials[i].occlusion_texture.extensions, data->materials[i].occlusion_texture.extensions_count);
@ -1865,126 +1920,126 @@ void cgltf_free(cgltf_data* data)
cgltf_free_extensions(data, data->materials[i].extensions, data->materials[i].extensions_count);
}
data->memory.free(data->memory.user_data, data->materials);
data->memory.free_func(data->memory.user_data, data->materials);
for (cgltf_size i = 0; i < data->images_count; ++i)
{
data->memory.free(data->memory.user_data, data->images[i].name);
data->memory.free(data->memory.user_data, data->images[i].uri);
data->memory.free(data->memory.user_data, data->images[i].mime_type);
data->memory.free_func(data->memory.user_data, data->images[i].name);
data->memory.free_func(data->memory.user_data, data->images[i].uri);
data->memory.free_func(data->memory.user_data, data->images[i].mime_type);
cgltf_free_extensions(data, data->images[i].extensions, data->images[i].extensions_count);
}
data->memory.free(data->memory.user_data, data->images);
data->memory.free_func(data->memory.user_data, data->images);
for (cgltf_size i = 0; i < data->textures_count; ++i)
{
data->memory.free(data->memory.user_data, data->textures[i].name);
data->memory.free_func(data->memory.user_data, data->textures[i].name);
cgltf_free_extensions(data, data->textures[i].extensions, data->textures[i].extensions_count);
}
data->memory.free(data->memory.user_data, data->textures);
data->memory.free_func(data->memory.user_data, data->textures);
for (cgltf_size i = 0; i < data->samplers_count; ++i)
{
data->memory.free(data->memory.user_data, data->samplers[i].name);
data->memory.free_func(data->memory.user_data, data->samplers[i].name);
cgltf_free_extensions(data, data->samplers[i].extensions, data->samplers[i].extensions_count);
}
data->memory.free(data->memory.user_data, data->samplers);
data->memory.free_func(data->memory.user_data, data->samplers);
for (cgltf_size i = 0; i < data->skins_count; ++i)
{
data->memory.free(data->memory.user_data, data->skins[i].name);
data->memory.free(data->memory.user_data, data->skins[i].joints);
data->memory.free_func(data->memory.user_data, data->skins[i].name);
data->memory.free_func(data->memory.user_data, data->skins[i].joints);
cgltf_free_extensions(data, data->skins[i].extensions, data->skins[i].extensions_count);
}
data->memory.free(data->memory.user_data, data->skins);
data->memory.free_func(data->memory.user_data, data->skins);
for (cgltf_size i = 0; i < data->cameras_count; ++i)
{
data->memory.free(data->memory.user_data, data->cameras[i].name);
data->memory.free_func(data->memory.user_data, data->cameras[i].name);
cgltf_free_extensions(data, data->cameras[i].extensions, data->cameras[i].extensions_count);
}
data->memory.free(data->memory.user_data, data->cameras);
data->memory.free_func(data->memory.user_data, data->cameras);
for (cgltf_size i = 0; i < data->lights_count; ++i)
{
data->memory.free(data->memory.user_data, data->lights[i].name);
data->memory.free_func(data->memory.user_data, data->lights[i].name);
}
data->memory.free(data->memory.user_data, data->lights);
data->memory.free_func(data->memory.user_data, data->lights);
for (cgltf_size i = 0; i < data->nodes_count; ++i)
{
data->memory.free(data->memory.user_data, data->nodes[i].name);
data->memory.free(data->memory.user_data, data->nodes[i].children);
data->memory.free(data->memory.user_data, data->nodes[i].weights);
data->memory.free_func(data->memory.user_data, data->nodes[i].name);
data->memory.free_func(data->memory.user_data, data->nodes[i].children);
data->memory.free_func(data->memory.user_data, data->nodes[i].weights);
cgltf_free_extensions(data, data->nodes[i].extensions, data->nodes[i].extensions_count);
}
data->memory.free(data->memory.user_data, data->nodes);
data->memory.free_func(data->memory.user_data, data->nodes);
for (cgltf_size i = 0; i < data->scenes_count; ++i)
{
data->memory.free(data->memory.user_data, data->scenes[i].name);
data->memory.free(data->memory.user_data, data->scenes[i].nodes);
data->memory.free_func(data->memory.user_data, data->scenes[i].name);
data->memory.free_func(data->memory.user_data, data->scenes[i].nodes);
cgltf_free_extensions(data, data->scenes[i].extensions, data->scenes[i].extensions_count);
}
data->memory.free(data->memory.user_data, data->scenes);
data->memory.free_func(data->memory.user_data, data->scenes);
for (cgltf_size i = 0; i < data->animations_count; ++i)
{
data->memory.free(data->memory.user_data, data->animations[i].name);
data->memory.free_func(data->memory.user_data, data->animations[i].name);
for (cgltf_size j = 0; j < data->animations[i].samplers_count; ++j)
{
cgltf_free_extensions(data, data->animations[i].samplers[j].extensions, data->animations[i].samplers[j].extensions_count);
}
data->memory.free(data->memory.user_data, data->animations[i].samplers);
data->memory.free_func(data->memory.user_data, data->animations[i].samplers);
for (cgltf_size j = 0; j < data->animations[i].channels_count; ++j)
{
cgltf_free_extensions(data, data->animations[i].channels[j].extensions, data->animations[i].channels[j].extensions_count);
}
data->memory.free(data->memory.user_data, data->animations[i].channels);
data->memory.free_func(data->memory.user_data, data->animations[i].channels);
cgltf_free_extensions(data, data->animations[i].extensions, data->animations[i].extensions_count);
}
data->memory.free(data->memory.user_data, data->animations);
data->memory.free_func(data->memory.user_data, data->animations);
for (cgltf_size i = 0; i < data->variants_count; ++i)
{
data->memory.free(data->memory.user_data, data->variants[i].name);
data->memory.free_func(data->memory.user_data, data->variants[i].name);
}
data->memory.free(data->memory.user_data, data->variants);
data->memory.free_func(data->memory.user_data, data->variants);
cgltf_free_extensions(data, data->data_extensions, data->data_extensions_count);
for (cgltf_size i = 0; i < data->extensions_used_count; ++i)
{
data->memory.free(data->memory.user_data, data->extensions_used[i]);
data->memory.free_func(data->memory.user_data, data->extensions_used[i]);
}
data->memory.free(data->memory.user_data, data->extensions_used);
data->memory.free_func(data->memory.user_data, data->extensions_used);
for (cgltf_size i = 0; i < data->extensions_required_count; ++i)
{
data->memory.free(data->memory.user_data, data->extensions_required[i]);
data->memory.free_func(data->memory.user_data, data->extensions_required[i]);
}
data->memory.free(data->memory.user_data, data->extensions_required);
data->memory.free_func(data->memory.user_data, data->extensions_required);
file_release(&data->memory, &data->file, data->file_data);
data->memory.free(data->memory.user_data, data);
data->memory.free_func(data->memory.user_data, data);
}
void cgltf_node_transform_local(const cgltf_node* node, cgltf_float* out_matrix)
@ -2067,7 +2122,7 @@ void cgltf_node_transform_world(const cgltf_node* node, cgltf_float* out_matrix)
}
}
static cgltf_size cgltf_component_read_index(const void* in, cgltf_component_type component_type)
static cgltf_ssize cgltf_component_read_integer(const void* in, cgltf_component_type component_type)
{
switch (component_type)
{
@ -2078,7 +2133,7 @@ static cgltf_size cgltf_component_read_index(const void* in, cgltf_component_typ
case cgltf_component_type_r_32u:
return *((const uint32_t*) in);
case cgltf_component_type_r_32f:
return (cgltf_size)*((const float*) in);
return (cgltf_ssize)*((const float*) in);
case cgltf_component_type_r_8:
return *((const int8_t*) in);
case cgltf_component_type_r_8u:
@ -2088,6 +2143,23 @@ static cgltf_size cgltf_component_read_index(const void* in, cgltf_component_typ
}
}
static cgltf_size cgltf_component_read_index(const void* in, cgltf_component_type component_type)
{
switch (component_type)
{
case cgltf_component_type_r_16u:
return *((const uint16_t*) in);
case cgltf_component_type_r_32u:
return *((const uint32_t*) in);
case cgltf_component_type_r_32f:
return (cgltf_size)*((const float*) in);
case cgltf_component_type_r_8u:
return *((const uint8_t*) in);
default:
return 0;
}
}
static cgltf_float cgltf_component_read_float(const void* in, cgltf_component_type component_type, cgltf_bool normalized)
{
if (component_type == cgltf_component_type_r_32f)
@ -2113,7 +2185,7 @@ static cgltf_float cgltf_component_read_float(const void* in, cgltf_component_ty
}
}
return (cgltf_float)cgltf_component_read_index(in, component_type);
return (cgltf_float)cgltf_component_read_integer(in, component_type);
}
static cgltf_size cgltf_component_size(cgltf_component_type component_type);
@ -2471,7 +2543,7 @@ static int cgltf_parse_json_string(cgltf_options* options, jsmntok_t const* toke
return CGLTF_ERROR_JSON;
}
int size = tokens[i].end - tokens[i].start;
char* result = (char*)options->memory.alloc(options->memory.user_data, size + 1);
char* result = (char*)options->memory.alloc_func(options->memory.user_data, size + 1);
if (!result)
{
return CGLTF_ERROR_NOMEM;
@ -2526,6 +2598,12 @@ static int cgltf_parse_json_string_array(cgltf_options* options, jsmntok_t const
static void cgltf_parse_attribute_type(const char* name, cgltf_attribute_type* out_type, int* out_index)
{
if (*name == '_')
{
*out_type = cgltf_attribute_type_custom;
return;
}
const char* us = strchr(name, '_');
size_t len = us ? (size_t)(us - name) : strlen(name);
@ -2624,7 +2702,7 @@ static int cgltf_parse_json_unprocessed_extension(cgltf_options* options, jsmnto
}
cgltf_size name_length = tokens[i].end - tokens[i].start;
out_extension->name = (char*)options->memory.alloc(options->memory.user_data, name_length + 1);
out_extension->name = (char*)options->memory.alloc_func(options->memory.user_data, name_length + 1);
if (!out_extension->name)
{
return CGLTF_ERROR_NOMEM;
@ -2635,7 +2713,7 @@ static int cgltf_parse_json_unprocessed_extension(cgltf_options* options, jsmnto
size_t start = tokens[i].start;
size_t size = tokens[i].end - start;
out_extension->data = (char*)options->memory.alloc(options->memory.user_data, size + 1);
out_extension->data = (char*)options->memory.alloc_func(options->memory.user_data, size + 1);
if (!out_extension->data)
{
return CGLTF_ERROR_NOMEM;
@ -2716,6 +2794,37 @@ static int cgltf_parse_json_draco_mesh_compression(cgltf_options* options, jsmnt
return i;
}
static 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)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens + i, json_chunk, "attributes") == 0)
{
i = cgltf_parse_json_attribute_list(options, tokens, i + 1, json_chunk, &out_mesh_gpu_instancing->attributes, &out_mesh_gpu_instancing->attributes_count);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "bufferView") == 0)
{
++i;
out_mesh_gpu_instancing->buffer_view = CGLTF_PTRINDEX(cgltf_buffer_view, cgltf_json_to_int(tokens + i, json_chunk));
++i;
}
if (i < 0)
{
return i;
}
}
return i;
}
static 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)
{
(void)options;
@ -3842,6 +3951,100 @@ static int cgltf_parse_json_sheen(cgltf_options* options, jsmntok_t const* token
return i;
}
static int cgltf_parse_json_emissive_strength(jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_emissive_strength* out_emissive_strength)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
// Default
out_emissive_strength->emissive_strength = 1.f;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens + i, json_chunk, "emissiveStrength") == 0)
{
++i;
out_emissive_strength->emissive_strength = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else
{
i = cgltf_skip_json(tokens, i + 1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_iridescence(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_iridescence* out_iridescence)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
// Default
out_iridescence->iridescence_ior = 1.3f;
out_iridescence->iridescence_thickness_min = 100.f;
out_iridescence->iridescence_thickness_max = 400.f;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens + i, json_chunk, "iridescenceFactor") == 0)
{
++i;
out_iridescence->iridescence_factor = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "iridescenceTexture") == 0)
{
i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_iridescence->iridescence_texture);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "iridescenceIor") == 0)
{
++i;
out_iridescence->iridescence_ior = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "iridescenceThicknessMinimum") == 0)
{
++i;
out_iridescence->iridescence_thickness_min = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "iridescenceThicknessMaximum") == 0)
{
++i;
out_iridescence->iridescence_thickness_max = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "iridescenceThicknessTexture") == 0)
{
i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_iridescence->iridescence_thickness_texture);
}
else
{
i = cgltf_skip_json(tokens, i + 1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_image(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_image* out_image)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
@ -4039,6 +4242,10 @@ static int cgltf_parse_json_texture(cgltf_options* options, jsmntok_t const* tok
{
i = cgltf_skip_json(tokens, i + 1);
}
if (i < 0)
{
return i;
}
}
}
else
@ -4216,6 +4423,16 @@ static int cgltf_parse_json_material(cgltf_options* options, jsmntok_t const* to
out_material->has_sheen = 1;
i = cgltf_parse_json_sheen(options, tokens, i + 1, json_chunk, &out_material->sheen);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "KHR_materials_emissive_strength") == 0)
{
out_material->has_emissive_strength = 1;
i = cgltf_parse_json_emissive_strength(tokens, i + 1, json_chunk, &out_material->emissive_strength);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "KHR_materials_iridescence") == 0)
{
out_material->has_iridescence = 1;
i = cgltf_parse_json_iridescence(options, tokens, i + 1, json_chunk, &out_material->iridescence);
}
else
{
i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, &(out_material->extensions[out_material->extensions_count++]));
@ -5176,6 +5393,11 @@ static int cgltf_parse_json_node(cgltf_options* options, jsmntok_t const* tokens
}
}
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "EXT_mesh_gpu_instancing") == 0)
{
out_node->has_mesh_gpu_instancing = 1;
i = cgltf_parse_json_mesh_gpu_instancing(options, tokens, i + 1, json_chunk, &out_node->mesh_gpu_instancing);
}
else
{
i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, &(out_node->extensions[out_node->extensions_count++]));
@ -5903,7 +6125,7 @@ cgltf_result cgltf_parse_json(cgltf_options* options, const uint8_t* json_chunk,
options->json_token_count = token_count;
}
jsmntok_t* tokens = (jsmntok_t*)options->memory.alloc(options->memory.user_data, sizeof(jsmntok_t) * (options->json_token_count + 1));
jsmntok_t* tokens = (jsmntok_t*)options->memory.alloc_func(options->memory.user_data, sizeof(jsmntok_t) * (options->json_token_count + 1));
if (!tokens)
{
@ -5916,7 +6138,7 @@ cgltf_result cgltf_parse_json(cgltf_options* options, const uint8_t* json_chunk,
if (token_count <= 0)
{
options->memory.free(options->memory.user_data, tokens);
options->memory.free_func(options->memory.user_data, tokens);
return cgltf_result_invalid_json;
}
@ -5924,11 +6146,11 @@ cgltf_result cgltf_parse_json(cgltf_options* options, const uint8_t* json_chunk,
// for invalid JSON inputs this makes sure we don't perform out of bound reads of token data
tokens[token_count].type = JSMN_UNDEFINED;
cgltf_data* data = (cgltf_data*)options->memory.alloc(options->memory.user_data, sizeof(cgltf_data));
cgltf_data* data = (cgltf_data*)options->memory.alloc_func(options->memory.user_data, sizeof(cgltf_data));
if (!data)
{
options->memory.free(options->memory.user_data, tokens);
options->memory.free_func(options->memory.user_data, tokens);
return cgltf_result_out_of_memory;
}
@ -5938,7 +6160,7 @@ cgltf_result cgltf_parse_json(cgltf_options* options, const uint8_t* json_chunk,
int i = cgltf_parse_json_root(options, tokens, 0, json_chunk, data);
options->memory.free(options->memory.user_data, tokens);
options->memory.free_func(options->memory.user_data, tokens);
if (i < 0)
{
@ -6062,6 +6284,9 @@ static int cgltf_fixup_pointers(cgltf_data* data)
CGLTF_PTRFIXUP(data->materials[i].sheen.sheen_color_texture.texture, data->textures, data->textures_count);
CGLTF_PTRFIXUP(data->materials[i].sheen.sheen_roughness_texture.texture, data->textures, data->textures_count);
CGLTF_PTRFIXUP(data->materials[i].iridescence.iridescence_texture.texture, data->textures, data->textures_count);
CGLTF_PTRFIXUP(data->materials[i].iridescence.iridescence_thickness_texture.texture, data->textures, data->textures_count);
}
for (cgltf_size i = 0; i < data->buffer_views_count; ++i)
@ -6103,6 +6328,15 @@ static int cgltf_fixup_pointers(cgltf_data* data)
CGLTF_PTRFIXUP(data->nodes[i].skin, data->skins, data->skins_count);
CGLTF_PTRFIXUP(data->nodes[i].camera, data->cameras, data->cameras_count);
CGLTF_PTRFIXUP(data->nodes[i].light, data->lights, data->lights_count);
if (data->nodes[i].has_mesh_gpu_instancing)
{
CGLTF_PTRFIXUP_REQ(data->nodes[i].mesh_gpu_instancing.buffer_view, data->buffer_views, data->buffer_views_count);
for (cgltf_size m = 0; m < data->nodes[i].mesh_gpu_instancing.attributes_count; ++m)
{
CGLTF_PTRFIXUP_REQ(data->nodes[i].mesh_gpu_instancing.attributes[m].data, data->accessors, data->accessors_count);
}
}
}
for (cgltf_size i = 0; i < data->scenes_count; ++i)

View file

@ -92,9 +92,6 @@ extern "C" {
// @raysan5: Actually, only HWND handler needs to be defined
// Including windows.h could suppose symbols re-definition issues (i.e Rectangle type)
//#include <windows.h>
typedef void *PVOID;
typedef PVOID HANDLE;
typedef HANDLE HWND;
#elif defined(GLFW_EXPOSE_NATIVE_COCOA) || defined(GLFW_EXPOSE_NATIVE_NSGL)
#if defined(__OBJC__)
#import <Cocoa/Cocoa.h>

6530
src/external/m3d.h vendored Normal file

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -570,7 +570,7 @@ enum STBVorbisError
#if defined(_MSC_VER) || defined(__MINGW32__)
#include <malloc.h>
#endif
#if defined(__linux__) || defined(__linux) || defined(__EMSCRIPTEN__) || defined(__APPLE__)
#if defined(__linux__) || defined(__linux) || defined(__EMSCRIPTEN__) || defined(__APPLE__) || defined(__CYGWIN__)
#include <alloca.h>
#endif
#else // STB_VORBIS_NO_CRT

View file

@ -1,263 +0,0 @@
/*******************************************************************************************
*
* raylib easings (header only file)
*
* Useful easing functions for values animation
*
* This header uses:
* #define EASINGS_STATIC_INLINE // Inlines all functions code, so it runs faster.
* // This requires lots of memory on system.
* How to use:
* The four inputs t,b,c,d are defined as follows:
* t = current time (in any unit measure, but same unit as duration)
* b = starting value to interpolate
* c = the total change in value of b that needs to occur
* d = total time it should take to complete (duration)
*
* Example:
*
* int currentTime = 0;
* int duration = 100;
* float startPositionX = 0.0f;
* float finalPositionX = 30.0f;
* float currentPositionX = startPositionX;
*
* while (currentPositionX < finalPositionX)
* {
* currentPositionX = EaseSineIn(currentTime, startPositionX, finalPositionX - startPositionX, duration);
* currentTime++;
* }
*
* A port of Robert Penner's easing equations to C (http://robertpenner.com/easing/)
*
* Robert Penner License
* ---------------------------------------------------------------------------------
* Open source under the BSD License.
*
* Copyright (c) 2001 Robert Penner. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the author nor the names of contributors may be used
* to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ---------------------------------------------------------------------------------
*
* Copyright (c) 2015 Ramon Santamaria
*
* This software is provided "as-is", without any express or implied warranty. In no event
* will the authors be held liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose, including commercial
* applications, and to alter it and redistribute it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not claim that you
* wrote the original software. If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be misrepresented
* as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*
**********************************************************************************************/
#ifndef EASINGS_H
#define EASINGS_H
#define EASINGS_STATIC_INLINE // NOTE: By default, compile functions as static inline
#if defined(EASINGS_STATIC_INLINE)
#define EASEDEF static inline
#else
#define EASEDEF extern
#endif
#include <math.h> // Required for: sinf(), cosf(), sqrtf(), powf()
#ifndef PI
#define PI 3.14159265358979323846f //Required as PI is not always defined in math.h
#endif
#ifdef __cplusplus
extern "C" { // Prevents name mangling of functions
#endif
// Linear Easing functions
EASEDEF float EaseLinearNone(float t, float b, float c, float d) { return (c*t/d + b); } // Ease: Linear
EASEDEF float EaseLinearIn(float t, float b, float c, float d) { return (c*t/d + b); } // Ease: Linear In
EASEDEF float EaseLinearOut(float t, float b, float c, float d) { return (c*t/d + b); } // Ease: Linear Out
EASEDEF float EaseLinearInOut(float t, float b, float c, float d) { return (c*t/d + b); } // Ease: Linear In Out
// Sine Easing functions
EASEDEF float EaseSineIn(float t, float b, float c, float d) { return (-c*cosf(t/d*(PI/2.0f)) + c + b); } // Ease: Sine In
EASEDEF float EaseSineOut(float t, float b, float c, float d) { return (c*sinf(t/d*(PI/2.0f)) + b); } // Ease: Sine Out
EASEDEF float EaseSineInOut(float t, float b, float c, float d) { return (-c/2.0f*(cosf(PI*t/d) - 1.0f) + b); } // Ease: Sine Out
// Circular Easing functions
EASEDEF float EaseCircIn(float t, float b, float c, float d) { t /= d; return (-c*(sqrtf(1.0f - t*t) - 1.0f) + b); } // Ease: Circular In
EASEDEF float EaseCircOut(float t, float b, float c, float d) { t = t/d - 1.0f; return (c*sqrtf(1.0f - t*t) + b); } // Ease: Circular Out
EASEDEF float EaseCircInOut(float t, float b, float c, float d) // Ease: Circular In Out
{
if ((t/=d/2.0f) < 1.0f) return (-c/2.0f*(sqrtf(1.0f - t*t) - 1.0f) + b);
t -= 2.0f; return (c/2.0f*(sqrtf(1.0f - t*t) + 1.0f) + b);
}
// Cubic Easing functions
EASEDEF float EaseCubicIn(float t, float b, float c, float d) { t /= d; return (c*t*t*t + b); } // Ease: Cubic In
EASEDEF float EaseCubicOut(float t, float b, float c, float d) { t = t/d - 1.0f; return (c*(t*t*t + 1.0f) + b); } // Ease: Cubic Out
EASEDEF float EaseCubicInOut(float t, float b, float c, float d) // Ease: Cubic In Out
{
if ((t/=d/2.0f) < 1.0f) return (c/2.0f*t*t*t + b);
t -= 2.0f; return (c/2.0f*(t*t*t + 2.0f) + b);
}
// Quadratic Easing functions
EASEDEF float EaseQuadIn(float t, float b, float c, float d) { t /= d; return (c*t*t + b); } // Ease: Quadratic In
EASEDEF float EaseQuadOut(float t, float b, float c, float d) { t /= d; return (-c*t*(t - 2.0f) + b); } // Ease: Quadratic Out
EASEDEF float EaseQuadInOut(float t, float b, float c, float d) // Ease: Quadratic In Out
{
if ((t/=d/2) < 1) return (((c/2)*(t*t)) + b);
return (-c/2.0f*(((t - 1.0f)*(t - 3.0f)) - 1.0f) + b);
}
// Exponential Easing functions
EASEDEF float EaseExpoIn(float t, float b, float c, float d) { return (t == 0.0f) ? b : (c*powf(2.0f, 10.0f*(t/d - 1.0f)) + b); } // Ease: Exponential In
EASEDEF float EaseExpoOut(float t, float b, float c, float d) { return (t == d) ? (b + c) : (c*(-powf(2.0f, -10.0f*t/d) + 1.0f) + b); } // Ease: Exponential Out
EASEDEF float EaseExpoInOut(float t, float b, float c, float d) // Ease: Exponential In Out
{
if (t == 0.0f) return b;
if (t == d) return (b + c);
if ((t/=d/2.0f) < 1.0f) return (c/2.0f*powf(2.0f, 10.0f*(t - 1.0f)) + b);
return (c/2.0f*(-powf(2.0f, -10.0f*(t - 1.0f)) + 2.0f) + b);
}
// Back Easing functions
EASEDEF float EaseBackIn(float t, float b, float c, float d) // Ease: Back In
{
float s = 1.70158f;
float postFix = t/=d;
return (c*(postFix)*t*((s + 1.0f)*t - s) + b);
}
EASEDEF float EaseBackOut(float t, float b, float c, float d) // Ease: Back Out
{
float s = 1.70158f;
t = t/d - 1.0f;
return (c*(t*t*((s + 1.0f)*t + s) + 1.0f) + b);
}
EASEDEF float EaseBackInOut(float t, float b, float c, float d) // Ease: Back In Out
{
float s = 1.70158f;
if ((t/=d/2.0f) < 1.0f)
{
s *= 1.525f;
return (c/2.0f*(t*t*((s + 1.0f)*t - s)) + b);
}
float postFix = t-=2.0f;
s *= 1.525f;
return (c/2.0f*((postFix)*t*((s + 1.0f)*t + s) + 2.0f) + b);
}
// Bounce Easing functions
EASEDEF float EaseBounceOut(float t, float b, float c, float d) // Ease: Bounce Out
{
if ((t/=d) < (1.0f/2.75f))
{
return (c*(7.5625f*t*t) + b);
}
else if (t < (2.0f/2.75f))
{
float postFix = t-=(1.5f/2.75f);
return (c*(7.5625f*(postFix)*t + 0.75f) + b);
}
else if (t < (2.5/2.75))
{
float postFix = t-=(2.25f/2.75f);
return (c*(7.5625f*(postFix)*t + 0.9375f) + b);
}
else
{
float postFix = t-=(2.625f/2.75f);
return (c*(7.5625f*(postFix)*t + 0.984375f) + b);
}
}
EASEDEF float EaseBounceIn(float t, float b, float c, float d) { return (c - EaseBounceOut(d - t, 0.0f, c, d) + b); } // Ease: Bounce In
EASEDEF float EaseBounceInOut(float t, float b, float c, float d) // Ease: Bounce In Out
{
if (t < d/2.0f) return (EaseBounceIn(t*2.0f, 0.0f, c, d)*0.5f + b);
else return (EaseBounceOut(t*2.0f - d, 0.0f, c, d)*0.5f + c*0.5f + b);
}
// Elastic Easing functions
EASEDEF float EaseElasticIn(float t, float b, float c, float d) // Ease: Elastic In
{
if (t == 0.0f) return b;
if ((t/=d) == 1.0f) return (b + c);
float p = d*0.3f;
float a = c;
float s = p/4.0f;
float postFix = a*powf(2.0f, 10.0f*(t-=1.0f));
return (-(postFix*sinf((t*d-s)*(2.0f*PI)/p )) + b);
}
EASEDEF float EaseElasticOut(float t, float b, float c, float d) // Ease: Elastic Out
{
if (t == 0.0f) return b;
if ((t/=d) == 1.0f) return (b + c);
float p = d*0.3f;
float a = c;
float s = p/4.0f;
return (a*powf(2.0f,-10.0f*t)*sinf((t*d-s)*(2.0f*PI)/p) + c + b);
}
EASEDEF float EaseElasticInOut(float t, float b, float c, float d) // Ease: Elastic In Out
{
if (t == 0.0f) return b;
if ((t/=d/2.0f) == 2.0f) return (b + c);
float p = d*(0.3f*1.5f);
float a = c;
float s = p/4.0f;
if (t < 1.0f)
{
float postFix = a*powf(2.0f, 10.0f*(t-=1.0f));
return -0.5f*(postFix*sinf((t*d-s)*(2.0f*PI)/p)) + b;
}
float postFix = a*powf(2.0f, -10.0f*(t-=1.0f));
return (postFix*sinf((t*d-s)*(2.0f*PI)/p)*0.5f + c + b);
}
#ifdef __cplusplus
}
#endif
#endif // EASINGS_H

View file

@ -1,751 +0,0 @@
/**********************************************************************************************
*
* rmem - raylib memory pool and objects pool
*
* A quick, efficient, and minimal free list and arena-based allocator
*
* PURPOSE:
* - A quicker, efficient memory allocator alternative to 'malloc' and friends.
* - Reduce the possibilities of memory leaks for beginner developers using Raylib.
* - Being able to flexibly range check memory if necessary.
*
* CONFIGURATION:
*
* #define RMEM_IMPLEMENTATION
* Generates the implementation of the library into the included file.
* If not defined, the library is in header only mode and can be included in other headers
* or source files without problems. But only ONE file should hold the implementation.
*
*
* LICENSE: zlib/libpng
*
* Copyright (c) 2019 Kevin 'Assyrianic' Yonan (@assyrianic) and reviewed by Ramon Santamaria (@raysan5)
*
* This software is provided "as-is", without any express or implied warranty. In no event
* will the authors be held liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose, including commercial
* applications, and to alter it and redistribute it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not claim that you
* wrote the original software. If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be misrepresented
* as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*
**********************************************************************************************/
#ifndef RMEM_H
#define RMEM_H
#include <inttypes.h>
#include <stdbool.h>
//----------------------------------------------------------------------------------
// Defines and Macros
//----------------------------------------------------------------------------------
#if defined(_WIN32) && defined(BUILD_LIBTYPE_SHARED)
#define RMEMAPI __declspec(dllexport) // We are building library as a Win32 shared library (.dll)
#elif defined(_WIN32) && defined(USE_LIBTYPE_SHARED)
#define RMEMAPI __declspec(dllimport) // We are using library as a Win32 shared library (.dll)
#else
#define RMEMAPI // We are building or using library as a static library (or Linux shared library)
#endif
#define RMEM_VERSION "v1.3" // changelog at bottom of header.
//----------------------------------------------------------------------------------
// Types and Structures Definition
//----------------------------------------------------------------------------------
// Memory Pool
typedef struct MemNode MemNode;
struct MemNode {
size_t size;
MemNode *next, *prev;
};
// Freelist implementation
typedef struct AllocList {
MemNode *head, *tail;
size_t len;
} AllocList;
// Arena allocator.
typedef struct Arena {
uintptr_t mem, offs;
size_t size;
} Arena;
enum {
MEMPOOL_BUCKET_SIZE = 8,
MEMPOOL_BUCKET_BITS = (sizeof(uintptr_t) >> 1) + 1,
MEM_SPLIT_THRESHOLD = sizeof(uintptr_t) * 4
};
typedef struct MemPool {
AllocList large, buckets[MEMPOOL_BUCKET_SIZE];
Arena arena;
} MemPool;
// Object Pool
typedef struct ObjPool {
uintptr_t mem, offs;
size_t objSize, freeBlocks, memSize;
} ObjPool;
// Double-Ended Stack aka Deque
typedef struct BiStack {
uintptr_t mem, front, back;
size_t size;
} BiStack;
#if defined(__cplusplus)
extern "C" { // Prevents name mangling of functions
#endif
//------------------------------------------------------------------------------------
// Functions Declaration - Memory Pool
//------------------------------------------------------------------------------------
RMEMAPI MemPool CreateMemPool(size_t bytes);
RMEMAPI MemPool CreateMemPoolFromBuffer(void *buf, size_t bytes);
RMEMAPI void DestroyMemPool(MemPool *mempool);
RMEMAPI void *MemPoolAlloc(MemPool *mempool, size_t bytes);
RMEMAPI void *MemPoolRealloc(MemPool *mempool, void *ptr, size_t bytes);
RMEMAPI void MemPoolFree(MemPool *mempool, void *ptr);
RMEMAPI void MemPoolCleanUp(MemPool *mempool, void **ptrref);
RMEMAPI void MemPoolReset(MemPool *mempool);
RMEMAPI size_t GetMemPoolFreeMemory(const MemPool mempool);
//------------------------------------------------------------------------------------
// Functions Declaration - Object Pool
//------------------------------------------------------------------------------------
RMEMAPI ObjPool CreateObjPool(size_t objsize, size_t len);
RMEMAPI ObjPool CreateObjPoolFromBuffer(void *buf, size_t objsize, size_t len);
RMEMAPI void DestroyObjPool(ObjPool *objpool);
RMEMAPI void *ObjPoolAlloc(ObjPool *objpool);
RMEMAPI void ObjPoolFree(ObjPool *objpool, void *ptr);
RMEMAPI void ObjPoolCleanUp(ObjPool *objpool, void **ptrref);
//------------------------------------------------------------------------------------
// Functions Declaration - Double-Ended Stack
//------------------------------------------------------------------------------------
RMEMAPI BiStack CreateBiStack(size_t len);
RMEMAPI BiStack CreateBiStackFromBuffer(void *buf, size_t len);
RMEMAPI void DestroyBiStack(BiStack *destack);
RMEMAPI void *BiStackAllocFront(BiStack *destack, size_t len);
RMEMAPI void *BiStackAllocBack(BiStack *destack, size_t len);
RMEMAPI void BiStackResetFront(BiStack *destack);
RMEMAPI void BiStackResetBack(BiStack *destack);
RMEMAPI void BiStackResetAll(BiStack *destack);
RMEMAPI intptr_t BiStackMargins(BiStack destack);
#ifdef __cplusplus
}
#endif
#endif // RMEM_H
/***********************************************************************************
*
* RMEM IMPLEMENTATION
*
************************************************************************************/
#if defined(RMEM_IMPLEMENTATION)
#include <stdio.h> // Required for:
#include <stdlib.h> // Required for:
#include <string.h> // Required for:
//----------------------------------------------------------------------------------
// Defines and Macros
//----------------------------------------------------------------------------------
// Make sure restrict type qualifier for pointers is defined
// NOTE: Not supported by C++, it is a C only keyword
#if defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__) || defined(_MSC_VER)
#ifndef restrict
#define restrict __restrict
#endif
#endif
//----------------------------------------------------------------------------------
// Global Variables Definition
//----------------------------------------------------------------------------------
// ...
//----------------------------------------------------------------------------------
// Module specific Functions Declaration
//----------------------------------------------------------------------------------
static inline size_t __AlignSize(const size_t size, const size_t align)
{
return (size + (align - 1)) & -align;
}
static MemNode *__SplitMemNode(MemNode *const node, const size_t bytes)
{
uintptr_t n = ( uintptr_t )node;
MemNode *const r = ( MemNode* )(n + (node->size - bytes));
node->size -= bytes;
r->size = bytes;
return r;
}
static void __InsertMemNodeBefore(AllocList *const list, MemNode *const insert, MemNode *const curr)
{
insert->next = curr;
if (curr->prev==NULL) list->head = insert;
else
{
insert->prev = curr->prev;
curr->prev->next = insert;
}
curr->prev = insert;
}
static void __ReplaceMemNode(MemNode *const old, MemNode *const replace)
{
replace->prev = old->prev;
replace->next = old->next;
if( old->prev != NULL )
old->prev->next = replace;
if( old->next != NULL )
old->next->prev = replace;
}
static MemNode *__RemoveMemNode(AllocList *const list, MemNode *const node)
{
if (node->prev != NULL) node->prev->next = node->next;
else
{
list->head = node->next;
if (list->head != NULL) list->head->prev = NULL;
else list->tail = NULL;
}
if (node->next != NULL) node->next->prev = node->prev;
else
{
list->tail = node->prev;
if (list->tail != NULL) list->tail->next = NULL;
else list->head = NULL;
}
list->len--;
return node;
}
static MemNode *__FindMemNode(AllocList *const list, const size_t bytes)
{
for (MemNode *node = list->head; node != NULL; node = node->next)
{
if (node->size < bytes) continue;
// close in size - reduce fragmentation by not splitting.
else if (node->size <= bytes + MEM_SPLIT_THRESHOLD) return __RemoveMemNode(list, node);
else return __SplitMemNode(node, bytes);
}
return NULL;
}
static void __InsertMemNode(MemPool *const mempool, AllocList *const list, MemNode *const node, const bool is_bucket)
{
if (list->head == NULL)
{
list->head = node;
list->len++;
}
else
{
for (MemNode *iter = list->head; iter != NULL; iter = iter->next)
{
if (( uintptr_t )iter == mempool->arena.offs)
{
mempool->arena.offs += iter->size;
__RemoveMemNode(list, iter);
iter = list->head;
if (iter == NULL) {
list->head = node;
return;
}
}
const uintptr_t inode = ( uintptr_t )node;
const uintptr_t iiter = ( uintptr_t )iter;
const uintptr_t iter_end = iiter + iter->size;
const uintptr_t node_end = inode + node->size;
if (iter==node) return;
else if (iter < node)
{
// node was coalesced prior.
if (iter_end > inode) return;
else if (iter_end==inode && !is_bucket)
{
// if we can coalesce, do so.
iter->size += node->size;
return;
}
else if (iter->next == NULL)
{
// we reached the end of the free list -> append the node
iter->next = node;
node->prev = iter;
list->len++;
return;
}
}
else if (iter > node)
{
// Address sort, lowest to highest aka ascending order.
if (iiter < node_end) return;
else if (iter==list->head && !is_bucket)
{
if (iter_end==inode) iter->size += node->size;
else if (node_end==iiter)
{
node->size += list->head->size;
node->next = list->head->next;
node->prev = NULL;
list->head = node;
}
else
{
node->next = iter;
node->prev = NULL;
iter->prev = node;
list->head = node;
list->len++;
}
return;
}
else if (iter_end==inode && !is_bucket)
{
// if we can coalesce, do so.
iter->size += node->size;
return;
}
else
{
__InsertMemNodeBefore(list, node, iter);
list->len++;
return;
}
}
}
}
}
//----------------------------------------------------------------------------------
// Module Functions Definition - Memory Pool
//----------------------------------------------------------------------------------
MemPool CreateMemPool(const size_t size)
{
MemPool mempool = { 0 };
if (size == 0) return mempool;
else
{
// Align the mempool size to at least the size of an alloc node.
uint8_t *const restrict buf = malloc(size*sizeof *buf);
if (buf==NULL) return mempool;
else
{
mempool.arena.size = size;
mempool.arena.mem = ( uintptr_t )buf;
mempool.arena.offs = mempool.arena.mem + mempool.arena.size;
return mempool;
}
}
}
MemPool CreateMemPoolFromBuffer(void *const restrict buf, const size_t size)
{
MemPool mempool = { 0 };
if ((size == 0) || (buf == NULL) || (size <= sizeof(MemNode))) return mempool;
else
{
mempool.arena.size = size;
mempool.arena.mem = ( uintptr_t )buf;
mempool.arena.offs = mempool.arena.mem + mempool.arena.size;
return mempool;
}
}
void DestroyMemPool(MemPool *const restrict mempool)
{
if (mempool->arena.mem == 0) return;
else
{
void *const restrict ptr = ( void* )mempool->arena.mem;
free(ptr);
*mempool = (MemPool){ 0 };
}
}
void *MemPoolAlloc(MemPool *const mempool, const size_t size)
{
if ((size == 0) || (size > mempool->arena.size)) return NULL;
else
{
MemNode *new_mem = NULL;
const size_t ALLOC_SIZE = __AlignSize(size + sizeof *new_mem, sizeof(intptr_t));
const size_t BUCKET_SLOT = (ALLOC_SIZE >> MEMPOOL_BUCKET_BITS) - 1;
// If the size is small enough, let's check if our buckets has a fitting memory block.
if (BUCKET_SLOT < MEMPOOL_BUCKET_SIZE)
{
new_mem = __FindMemNode(&mempool->buckets[BUCKET_SLOT], ALLOC_SIZE);
}
else if (mempool->large.head != NULL)
{
new_mem = __FindMemNode(&mempool->large, ALLOC_SIZE);
}
if (new_mem == NULL)
{
// not enough memory to support the size!
if ((mempool->arena.offs - ALLOC_SIZE) < mempool->arena.mem) return NULL;
else
{
// Couldn't allocate from a freelist, allocate from available mempool.
// Subtract allocation size from the mempool.
mempool->arena.offs -= ALLOC_SIZE;
// Use the available mempool space as the new node.
new_mem = ( MemNode* )mempool->arena.offs;
new_mem->size = ALLOC_SIZE;
}
}
// Visual of the allocation block.
// --------------
// | mem size | lowest addr of block
// | next node | 12 byte (32-bit) header
// | prev node | 24 byte (64-bit) header
// |------------|
// | alloc'd |
// | memory |
// | space | highest addr of block
// --------------
new_mem->next = new_mem->prev = NULL;
uint8_t *const restrict final_mem = ( uint8_t* )new_mem + sizeof *new_mem;
return memset(final_mem, 0, new_mem->size - sizeof *new_mem);
}
}
void *MemPoolRealloc(MemPool *const restrict mempool, void *const ptr, const size_t size)
{
if (size > mempool->arena.size) return NULL;
// NULL ptr should make this work like regular Allocation.
else if (ptr == NULL) return MemPoolAlloc(mempool, size);
else if ((uintptr_t)ptr - sizeof(MemNode) < mempool->arena.mem) return NULL;
else
{
MemNode *const node = ( MemNode* )(( uint8_t* )ptr - sizeof *node);
const size_t NODE_SIZE = sizeof *node;
uint8_t *const resized_block = MemPoolAlloc(mempool, size);
if (resized_block == NULL) return NULL;
else
{
MemNode *const resized = ( MemNode* )(resized_block - sizeof *resized);
memmove(resized_block, ptr, (node->size > resized->size)? (resized->size - NODE_SIZE) : (node->size - NODE_SIZE));
MemPoolFree(mempool, ptr);
return resized_block;
}
}
}
void MemPoolFree(MemPool *const restrict mempool, void *const ptr)
{
const uintptr_t p = ( uintptr_t )ptr;
if ((ptr == NULL) || (p - sizeof(MemNode) < mempool->arena.mem)) return;
else
{
// Behind the actual pointer data is the allocation info.
const uintptr_t block = p - sizeof(MemNode);
MemNode *const mem_node = ( MemNode* )block;
const size_t BUCKET_SLOT = (mem_node->size >> MEMPOOL_BUCKET_BITS) - 1;
// Make sure the pointer data is valid.
if ((block < mempool->arena.offs) ||
((block - mempool->arena.mem) > mempool->arena.size) ||
(mem_node->size == 0) ||
(mem_node->size > mempool->arena.size)) return;
// If the mem_node is right at the arena offs, then merge it back to the arena.
else if (block == mempool->arena.offs)
{
mempool->arena.offs += mem_node->size;
}
else
{
// try to place it into bucket or large freelist.
struct AllocList *const l = (BUCKET_SLOT < MEMPOOL_BUCKET_SIZE) ? &mempool->buckets[BUCKET_SLOT] : &mempool->large;
__InsertMemNode(mempool, l, mem_node, (BUCKET_SLOT < MEMPOOL_BUCKET_SIZE));
}
}
}
void MemPoolCleanUp(MemPool *const restrict mempool, void **const ptrref)
{
if ((ptrref == NULL) || (*ptrref == NULL)) return;
else
{
MemPoolFree(mempool, *ptrref);
*ptrref = NULL;
}
}
size_t GetMemPoolFreeMemory(const MemPool mempool)
{
size_t total_remaining = mempool.arena.offs - mempool.arena.mem;
for (MemNode *n=mempool.large.head; n != NULL; n = n->next) total_remaining += n->size;
for (size_t i=0; i<MEMPOOL_BUCKET_SIZE; i++) for (MemNode *n = mempool.buckets[i].head; n != NULL; n = n->next) total_remaining += n->size;
return total_remaining;
}
void MemPoolReset(MemPool *const mempool)
{
mempool->large.head = mempool->large.tail = NULL;
mempool->large.len = 0;
for (size_t i = 0; i < MEMPOOL_BUCKET_SIZE; i++)
{
mempool->buckets[i].head = mempool->buckets[i].tail = NULL;
mempool->buckets[i].len = 0;
}
mempool->arena.offs = mempool->arena.mem + mempool->arena.size;
}
//----------------------------------------------------------------------------------
// Module Functions Definition - Object Pool
//----------------------------------------------------------------------------------
ObjPool CreateObjPool(const size_t objsize, const size_t len)
{
ObjPool objpool = { 0 };
if ((len == 0) || (objsize == 0)) return objpool;
else
{
const size_t aligned_size = __AlignSize(objsize, sizeof(size_t));
uint8_t *const restrict buf = calloc(len, aligned_size);
if (buf == NULL) return objpool;
objpool.objSize = aligned_size;
objpool.memSize = objpool.freeBlocks = len;
objpool.mem = ( uintptr_t )buf;
for (size_t i=0; i<objpool.freeBlocks; i++)
{
size_t *const restrict index = ( size_t* )(objpool.mem + (i*aligned_size));
*index = i + 1;
}
objpool.offs = objpool.mem;
return objpool;
}
}
ObjPool CreateObjPoolFromBuffer(void *const restrict buf, const size_t objsize, const size_t len)
{
ObjPool objpool = { 0 };
// If the object size isn't large enough to align to a size_t, then we can't use it.
const size_t aligned_size = __AlignSize(objsize, sizeof(size_t));
if ((buf == NULL) || (len == 0) || (objsize < sizeof(size_t)) || (objsize*len != aligned_size*len)) return objpool;
else
{
objpool.objSize = aligned_size;
objpool.memSize = objpool.freeBlocks = len;
objpool.mem = (uintptr_t)buf;
for (size_t i=0; i<objpool.freeBlocks; i++)
{
size_t *const restrict index = ( size_t* )(objpool.mem + (i*aligned_size));
*index = i + 1;
}
objpool.offs = objpool.mem;
return objpool;
}
}
void DestroyObjPool(ObjPool *const restrict objpool)
{
if (objpool->mem == 0) return;
else
{
void *const restrict ptr = ( void* )objpool->mem;
free(ptr);
*objpool = (ObjPool){0};
}
}
void *ObjPoolAlloc(ObjPool *const objpool)
{
if (objpool->freeBlocks > 0)
{
// For first allocation, head points to the very first index.
// Head = &pool[0];
// ret = Head == ret = &pool[0];
size_t *const restrict block = ( size_t* )objpool->offs;
objpool->freeBlocks--;
// after allocating, we set head to the address of the index that *Head holds.
// Head = &pool[*Head * pool.objsize];
objpool->offs = (objpool->freeBlocks != 0)? objpool->mem + (*block*objpool->objSize) : 0;
return memset(block, 0, objpool->objSize);
}
else return NULL;
}
void ObjPoolFree(ObjPool *const restrict objpool, void *const ptr)
{
uintptr_t block = (uintptr_t)ptr;
if ((ptr == NULL) || (block < objpool->mem) || (block > objpool->mem + objpool->memSize*objpool->objSize)) return;
else
{
// When we free our pointer, we recycle the pointer space to store the previous index and then we push it as our new head.
// *p = index of Head in relation to the buffer;
// Head = p;
size_t *const restrict index = ( size_t* )block;
*index = (objpool->offs != 0)? (objpool->offs - objpool->mem)/objpool->objSize : objpool->memSize;
objpool->offs = block;
objpool->freeBlocks++;
}
}
void ObjPoolCleanUp(ObjPool *const restrict objpool, void **const restrict ptrref)
{
if (ptrref == NULL) return;
else
{
ObjPoolFree(objpool, *ptrref);
*ptrref = NULL;
}
}
//----------------------------------------------------------------------------------
// Module Functions Definition - Double-Ended Stack
//----------------------------------------------------------------------------------
BiStack CreateBiStack(const size_t len)
{
BiStack destack = { 0 };
if (len == 0) return destack;
uint8_t *const buf = malloc(len*sizeof *buf);
if (buf==NULL) return destack;
destack.size = len;
destack.mem = ( uintptr_t )buf;
destack.front = destack.mem;
destack.back = destack.mem + len;
return destack;
}
BiStack CreateBiStackFromBuffer(void *const buf, const size_t len)
{
BiStack destack = { 0 };
if (len == 0 || buf == NULL) return destack;
else
{
destack.size = len;
destack.mem = destack.front = ( uintptr_t )buf;
destack.back = destack.mem + len;
return destack;
}
}
void DestroyBiStack(BiStack *const restrict destack)
{
if (destack->mem == 0) return;
else
{
uint8_t *const restrict buf = ( uint8_t* )destack->mem;
free(buf);
*destack = (BiStack){0};
}
}
void *BiStackAllocFront(BiStack *const restrict destack, const size_t len)
{
if (destack->mem == 0) return NULL;
else
{
const size_t ALIGNED_LEN = __AlignSize(len, sizeof(uintptr_t));
// front end arena is too high!
if (destack->front + ALIGNED_LEN >= destack->back) return NULL;
else
{
uint8_t *const restrict ptr = ( uint8_t* )destack->front;
destack->front += ALIGNED_LEN;
return ptr;
}
}
}
void *BiStackAllocBack(BiStack *const restrict destack, const size_t len)
{
if (destack->mem == 0) return NULL;
else
{
const size_t ALIGNED_LEN = __AlignSize(len, sizeof(uintptr_t));
// back end arena is too low
if (destack->back - ALIGNED_LEN <= destack->front) return NULL;
else
{
destack->back -= ALIGNED_LEN;
uint8_t *const restrict ptr = ( uint8_t* )destack->back;
return ptr;
}
}
}
void BiStackResetFront(BiStack *const destack)
{
if (destack->mem == 0) return;
else destack->front = destack->mem;
}
void BiStackResetBack(BiStack *const destack)
{
if (destack->mem == 0) return;
else destack->back = destack->mem + destack->size;
}
void BiStackResetAll(BiStack *const destack)
{
BiStackResetBack(destack);
BiStackResetFront(destack);
}
inline intptr_t BiStackMargins(const BiStack destack)
{
return destack.back - destack.front;
}
#endif // RMEM_IMPLEMENTATION
/*******
* Changelog
* v1.0: First Creation.
* v1.1: bug patches for the mempool and addition of object pool.
* v1.2: addition of bidirectional arena.
* v1.3:
* optimizations of allocators.
* renamed 'Stack' to 'Arena'.
* replaced certain define constants with an anonymous enum.
* refactored MemPool to no longer require active or deferred defragging.
********/

View file

@ -3,14 +3,14 @@
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>raylib web game</title>
<meta name="title" content="raylib web game">
<meta name="description" content="New raylib web videogame, developed using raylib videogames library">
<meta name="keywords" content="raylib, games, html5, programming, C, C++, library, learn, videogames">
<meta name="viewport" content="width=device-width">
<!-- Open Graph metatags for sharing -->
<meta property="og:title" content="raylib web game">
<meta property="og:image:type" content="image/png">
@ -26,10 +26,10 @@
<meta name="twitter:image" content="https://www.raylib.com/common/raylib_logo.png">
<meta name="twitter:url" content="https://www.raylib.com/games.html">
<meta name="twitter:description" content="New raylib web game, developed using raylib videogames library">
<!-- Favicon -->
<link rel="shortcut icon" href="https://www.raylib.com/favicon.ico">
<style>
body { margin: 0px; }
canvas.emscripten { border: 0px none; background-color: black; }
@ -70,7 +70,7 @@
element.scrollTop = element.scrollHeight; // focus on bottom
}
};
})(),
})(),
canvas: (function() {
var canvas = document.getElementById('canvas');
return canvas;

View file

@ -1,6 +1,6 @@
/**********************************************************************************************
*
* raudio v1.0 - A simple and easy-to-use audio library based on miniaudio
* raudio v1.1 - A simple and easy-to-use audio library based on miniaudio
*
* FEATURES:
* - Manage audio device (init/close)
@ -71,9 +71,9 @@
#if defined(RAUDIO_STANDALONE)
#include "raudio.h"
#include <stdarg.h> // Required for: va_list, va_start(), vfprintf(), va_end()
#else
#include "raylib.h" // Declares module functions
// Check if config flags have been externally provided on compilation line
#if !defined(EXTERNAL_CONFIG_FLAGS)
#include "config.h" // Defines module configuration flags
@ -187,21 +187,21 @@ typedef struct tagBITMAPINFOHEADER {
#if defined(RAUDIO_STANDALONE)
#ifndef TRACELOG
#define TRACELOG(level, ...) (void)0
#define TRACELOG(level, ...) printf(__VA_ARGS__)
#endif
// Allow custom memory allocators
#ifndef RL_MALLOC
#define RL_MALLOC(sz) malloc(sz)
#define RL_MALLOC(sz) malloc(sz)
#endif
#ifndef RL_CALLOC
#define RL_CALLOC(n,sz) calloc(n,sz)
#define RL_CALLOC(n,sz) calloc(n,sz)
#endif
#ifndef RL_REALLOC
#define RL_REALLOC(ptr,sz) realloc(ptr,sz)
#define RL_REALLOC(ptr,sz) realloc(ptr,sz)
#endif
#ifndef RL_FREE
#define RL_FREE(ptr) free(ptr)
#define RL_FREE(ptr) free(ptr)
#endif
#endif
@ -272,10 +272,6 @@ typedef struct tagBITMAPINFOHEADER {
#ifndef MAX_AUDIO_BUFFER_POOL_CHANNELS
#define MAX_AUDIO_BUFFER_POOL_CHANNELS 16 // Audio pool channels
#endif
#ifndef DEFAULT_AUDIO_BUFFER_SIZE
#define DEFAULT_AUDIO_BUFFER_SIZE 4096 // Default audio buffer size
#endif
//----------------------------------------------------------------------------------
// Types and Structures Definition
@ -320,7 +316,7 @@ typedef enum {
struct rAudioBuffer {
ma_data_converter converter; // Audio data converter
AudioCallback callback; // Audio buffer callback for buffer filling on audio threads
AudioCallback callback; // Audio buffer callback for buffer filling on audio threads
rAudioProcessor *processor; // Audio processor
float volume; // Audio buffer volume
@ -329,7 +325,7 @@ struct rAudioBuffer {
bool playing; // Audio buffer state: AUDIO_PLAYING
bool paused; // Audio buffer state: AUDIO_PAUSED
bool looping; // Audio buffer looping, always true for AudioStreams
bool looping; // Audio buffer looping, default to true for AudioStreams
int usage; // Audio buffer usage mode: STATIC or STREAM
bool isSubBufferProcessed[2]; // SubBuffer processed (virtual double buffer)
@ -360,6 +356,8 @@ typedef struct AudioData {
ma_device device; // miniaudio device
ma_mutex lock; // miniaudio mutex lock
bool isReady; // Check if audio device is ready
size_t pcmBufferSize; // Pre-allocated buffer size
void *pcmBuffer; // Pre-allocated buffer to read audio data from file/memory
} System;
struct {
AudioBuffer *first; // Pointer to first AudioBuffer in the list
@ -527,6 +525,7 @@ void CloseAudioDevice(void)
ma_context_uninit(&AUDIO.System.context);
AUDIO.System.isReady = false;
RL_FREE(AUDIO.System.pcmBuffer);
TRACELOG(LOG_INFO, "AUDIO: Device closed successfully");
}
@ -1169,8 +1168,8 @@ void WaveFormat(Wave *wave, int sampleRate, int sampleSize, int channels)
ma_format formatOut = ((sampleSize == 8)? ma_format_u8 : ((sampleSize == 16)? ma_format_s16 : ma_format_f32));
ma_uint32 frameCountIn = wave->frameCount;
ma_uint32 frameCount = (ma_uint32)ma_convert_frames(NULL, 0, formatOut, channels, sampleRate, NULL, frameCountIn, formatIn, wave->channels, wave->sampleRate);
if (frameCount == 0)
{
TRACELOG(LOG_WARNING, "WAVE: Failed to get frame count for format conversion");
@ -1190,6 +1189,7 @@ void WaveFormat(Wave *wave, int sampleRate, int sampleSize, int channels)
wave->sampleSize = sampleSize;
wave->sampleRate = sampleRate;
wave->channels = channels;
RL_FREE(wave->data);
wave->data = data;
}
@ -1638,7 +1638,7 @@ void UnloadMusicStream(Music music)
else if (music.ctxType == MUSIC_AUDIO_FLAC) drflac_free((drflac *)music.ctxData, NULL);
#endif
#if defined(SUPPORT_FILEFORMAT_MP3)
else if (music.ctxType == MUSIC_AUDIO_MP3) { drmp3_uninit((drmp3 *)music.ctxData); RL_FREE(music.ctxData); }
else if (music.ctxType == MUSIC_AUDIO_MP3) { drmp3_uninit((drmp3 *)music.ctxData); RL_FREE(music.ctxData); }
#endif
#if defined(SUPPORT_FILEFORMAT_XM)
else if (music.ctxType == MUSIC_MODULE_XM) jar_xm_free_context((jar_xm_context_t *)music.ctxData);
@ -1684,16 +1684,16 @@ void StopMusicStream(Music music)
switch (music.ctxType)
{
#if defined(SUPPORT_FILEFORMAT_WAV)
case MUSIC_AUDIO_WAV: drwav_seek_to_pcm_frame((drwav *)music.ctxData, 0); break;
case MUSIC_AUDIO_WAV: drwav_seek_to_first_pcm_frame((drwav *)music.ctxData); break;
#endif
#if defined(SUPPORT_FILEFORMAT_OGG)
case MUSIC_AUDIO_OGG: stb_vorbis_seek_start((stb_vorbis *)music.ctxData); break;
#endif
#if defined(SUPPORT_FILEFORMAT_FLAC)
case MUSIC_AUDIO_FLAC: drflac_seek_to_pcm_frame((drflac *)music.ctxData, 0); break;
case MUSIC_AUDIO_FLAC: drflac__seek_to_first_frame((drflac *)music.ctxData); break;
#endif
#if defined(SUPPORT_FILEFORMAT_MP3)
case MUSIC_AUDIO_MP3: drmp3_seek_to_pcm_frame((drmp3 *)music.ctxData, 0); break;
case MUSIC_AUDIO_MP3: drmp3_seek_to_start_of_stream((drmp3 *)music.ctxData); break;
#endif
#if defined(SUPPORT_FILEFORMAT_XM)
case MUSIC_MODULE_XM: jar_xm_reset((jar_xm_context_t *)music.ctxData); break;
@ -1738,64 +1738,107 @@ void UpdateMusicStream(Music music)
{
if (music.stream.buffer == NULL) return;
bool streamEnding = false;
unsigned int subBufferSizeInFrames = music.stream.buffer->sizeInFrames/2;
// NOTE: Using dynamic allocation because it could require more than 16KB
void *pcm = RL_CALLOC(subBufferSizeInFrames*music.stream.channels*music.stream.sampleSize/8, 1);
int frameCountToStream = 0; // Total size of data in frames to be streamed
// TODO: Get the framesLeft using framesProcessed... but first, get total frames processed correctly...
//ma_uint32 frameSizeInBytes = ma_get_bytes_per_sample(music.stream.buffer->dsp.formatConverterIn.config.formatIn)*music.stream.buffer->dsp.formatConverterIn.config.channels;
unsigned int framesLeft = music.frameCount - music.stream.buffer->framesProcessed;
while (IsAudioStreamProcessed(music.stream))
// On first call of this function we lazily pre-allocated a temp buffer to read audio files/memory data in
int frameSize = music.stream.channels*music.stream.sampleSize/8;
unsigned int pcmSize = subBufferSizeInFrames*frameSize;
if (AUDIO.System.pcmBufferSize < pcmSize)
{
if (framesLeft >= subBufferSizeInFrames) frameCountToStream = subBufferSizeInFrames;
else frameCountToStream = framesLeft;
RL_FREE(AUDIO.System.pcmBuffer);
AUDIO.System.pcmBuffer = RL_CALLOC(1, pcmSize);
AUDIO.System.pcmBufferSize = pcmSize;
}
// Check both sub-buffers to check if they require refilling
for (int i = 0; i < 2; i++)
{
if ((music.stream.buffer != NULL) && !music.stream.buffer->isSubBufferProcessed[i]) continue; // No refilling required, move to next sub-buffer
unsigned int framesLeft = music.frameCount - music.stream.buffer->framesProcessed; // Frames left to be processed
unsigned int framesToStream = 0; // Total frames to be streamed
if ((framesLeft >= subBufferSizeInFrames) || music.looping) framesToStream = subBufferSizeInFrames;
else framesToStream = framesLeft;
int frameCountStillNeeded = framesToStream;
int frameCountRedTotal = 0;
switch (music.ctxType)
{
#if defined(SUPPORT_FILEFORMAT_WAV)
case MUSIC_AUDIO_WAV:
{
// NOTE: Returns the number of samples to process (not required)
if (music.stream.sampleSize == 16) drwav_read_pcm_frames_s16((drwav *)music.ctxData, frameCountToStream, (short *)pcm);
else if (music.stream.sampleSize == 32) drwav_read_pcm_frames_f32((drwav *)music.ctxData, frameCountToStream, (float *)pcm);
if (music.stream.sampleSize == 16)
{
while (true)
{
int frameCountRed = drwav_read_pcm_frames_s16((drwav *)music.ctxData, frameCountStillNeeded, (short *)((char *)AUDIO.System.pcmBuffer + frameCountRedTotal*frameSize));
frameCountRedTotal += frameCountRed;
frameCountStillNeeded -= frameCountRed;
if (frameCountStillNeeded == 0) break;
else drwav_seek_to_first_pcm_frame((drwav *)music.ctxData);
}
}
else if (music.stream.sampleSize == 32)
{
while (true)
{
int frameCountRed = drwav_read_pcm_frames_f32((drwav *)music.ctxData, frameCountStillNeeded, (float *)((char *)AUDIO.System.pcmBuffer + frameCountRedTotal*frameSize));
frameCountRedTotal += frameCountRed;
frameCountStillNeeded -= frameCountRed;
if (frameCountStillNeeded == 0) break;
else drwav_seek_to_first_pcm_frame((drwav *)music.ctxData);
}
}
} break;
#endif
#if defined(SUPPORT_FILEFORMAT_OGG)
case MUSIC_AUDIO_OGG:
{
// NOTE: Returns the number of samples to process (be careful! we ask for number of shorts!)
stb_vorbis_get_samples_short_interleaved((stb_vorbis *)music.ctxData, music.stream.channels, (short *)pcm, frameCountToStream*music.stream.channels);
while (true)
{
int frameCountRed = stb_vorbis_get_samples_short_interleaved((stb_vorbis *)music.ctxData, music.stream.channels, (short *)((char *)AUDIO.System.pcmBuffer + frameCountRedTotal*frameSize), frameCountStillNeeded*music.stream.channels);
frameCountRedTotal += frameCountRed;
frameCountStillNeeded -= frameCountRed;
if (frameCountStillNeeded == 0) break;
else stb_vorbis_seek_start((stb_vorbis *)music.ctxData);
}
} break;
#endif
#if defined(SUPPORT_FILEFORMAT_FLAC)
case MUSIC_AUDIO_FLAC:
{
// NOTE: Returns the number of samples to process (not required)
drflac_read_pcm_frames_s16((drflac *)music.ctxData, frameCountToStream*music.stream.channels, (short *)pcm);
while (true)
{
int frameCountRed = drflac_read_pcm_frames_s16((drflac *)music.ctxData, frameCountStillNeeded, (short *)((char *)AUDIO.System.pcmBuffer + frameCountRedTotal*frameSize));
frameCountRedTotal += frameCountRed;
frameCountStillNeeded -= frameCountRed;
if (frameCountStillNeeded == 0) break;
else drflac__seek_to_first_frame((drflac *)music.ctxData);
}
} break;
#endif
#if defined(SUPPORT_FILEFORMAT_MP3)
case MUSIC_AUDIO_MP3:
{
drmp3_read_pcm_frames_f32((drmp3 *)music.ctxData, frameCountToStream, (float *)pcm);
while (true)
{
int frameCountRed = drmp3_read_pcm_frames_f32((drmp3 *)music.ctxData, frameCountStillNeeded, (float *)((char *)AUDIO.System.pcmBuffer + frameCountRedTotal*frameSize));
frameCountRedTotal += frameCountRed;
frameCountStillNeeded -= frameCountRed;
if (frameCountStillNeeded == 0) break;
else drmp3_seek_to_start_of_stream((drmp3 *)music.ctxData);
}
} break;
#endif
#if defined(SUPPORT_FILEFORMAT_XM)
case MUSIC_MODULE_XM:
{
// NOTE: Internally we consider 2 channels generation, so sampleCount/2
if (AUDIO_DEVICE_FORMAT == ma_format_f32) jar_xm_generate_samples((jar_xm_context_t *)music.ctxData, (float *)pcm, frameCountToStream);
else if (AUDIO_DEVICE_FORMAT == ma_format_s16) jar_xm_generate_samples_16bit((jar_xm_context_t *)music.ctxData, (short *)pcm, frameCountToStream);
else if (AUDIO_DEVICE_FORMAT == ma_format_u8) jar_xm_generate_samples_8bit((jar_xm_context_t *)music.ctxData, (char *)pcm, frameCountToStream);
if (AUDIO_DEVICE_FORMAT == ma_format_f32) jar_xm_generate_samples((jar_xm_context_t *)music.ctxData, (float *)AUDIO.System.pcmBuffer, framesToStream);
else if (AUDIO_DEVICE_FORMAT == ma_format_s16) jar_xm_generate_samples_16bit((jar_xm_context_t *)music.ctxData, (short *)AUDIO.System.pcmBuffer, framesToStream);
else if (AUDIO_DEVICE_FORMAT == ma_format_u8) jar_xm_generate_samples_8bit((jar_xm_context_t *)music.ctxData, (char *)AUDIO.System.pcmBuffer, framesToStream);
//jar_xm_reset((jar_xm_context_t *)music.ctxData);
} break;
#endif
@ -1803,38 +1846,33 @@ void UpdateMusicStream(Music music)
case MUSIC_MODULE_MOD:
{
// NOTE: 3rd parameter (nbsample) specify the number of stereo 16bits samples you want, so sampleCount/2
jar_mod_fillbuffer((jar_mod_context_t *)music.ctxData, (short *)pcm, frameCountToStream, 0);
jar_mod_fillbuffer((jar_mod_context_t *)music.ctxData, (short *)AUDIO.System.pcmBuffer, framesToStream, 0);
//jar_mod_seek_start((jar_mod_context_t *)music.ctxData);
} break;
#endif
default: break;
}
UpdateAudioStream(music.stream, pcm, frameCountToStream);
UpdateAudioStream(music.stream, AUDIO.System.pcmBuffer, framesToStream);
framesLeft -= frameCountToStream;
music.stream.buffer->framesProcessed = music.stream.buffer->framesProcessed%music.frameCount;
if (framesLeft <= 0)
if (framesLeft <= subBufferSizeInFrames)
{
streamEnding = true;
break;
if (!music.looping)
{
// Streaming is ending, we filled latest frames from input
StopMusicStream(music);
return;
}
}
}
// Free allocated pcm data
RL_FREE(pcm);
// Reset audio stream for looping
if (streamEnding)
{
StopMusicStream(music); // Stop music (and reset)
if (music.looping) PlayMusicStream(music); // Play again
}
else
{
// NOTE: In case window is minimized, music stream is stopped,
// just make sure to play again on window restore
if (IsMusicStreamPlaying(music)) PlayMusicStream(music);
}
// NOTE: In case window is minimized, music stream is stopped,
// just make sure to play again on window restore
if (IsMusicStreamPlaying(music)) PlayMusicStream(music);
}
// Check if any music is playing
@ -1889,7 +1927,13 @@ float GetMusicTimePlayed(Music music)
#endif
{
//ma_uint32 frameSizeInBytes = ma_get_bytes_per_sample(music.stream.buffer->dsp.formatConverterIn.config.formatIn)*music.stream.buffer->dsp.formatConverterIn.config.channels;
unsigned int framesPlayed = music.stream.buffer->framesProcessed;
int framesProcessed = (int)music.stream.buffer->framesProcessed;
int subBufferSize = (int)music.stream.buffer->sizeInFrames/2;
int framesInFirstBuffer = music.stream.buffer->isSubBufferProcessed[0]? 0 : subBufferSize;
int framesInSecondBuffer = music.stream.buffer->isSubBufferProcessed[1]? 0 : subBufferSize;
int framesSentToMix = music.stream.buffer->frameCursorPos%subBufferSize;
int framesPlayed = (framesProcessed - framesInFirstBuffer - framesInSecondBuffer + framesSentToMix)%(int)music.frameCount;
if (framesPlayed < 0) framesPlayed += music.frameCount;
secondsPlayed = (float)framesPlayed/music.stream.sampleRate;
}
}
@ -1964,16 +2008,14 @@ void UpdateAudioStream(AudioStream stream, const void *data, int frameCount)
ma_uint32 subBufferSizeInFrames = stream.buffer->sizeInFrames/2;
unsigned char *subBuffer = stream.buffer->data + ((subBufferSizeInFrames*stream.channels*(stream.sampleSize/8))*subBufferToUpdate);
// TODO: Get total frames processed on this buffer... DOES NOT WORK.
// Total frames processed in buffer is always the complete size, filled with 0 if required
stream.buffer->framesProcessed += subBufferSizeInFrames;
// Does this API expect a whole buffer to be updated in one go?
// Assuming so, but if not will need to change this logic.
if (subBufferSizeInFrames >= (ma_uint32)frameCount)
{
ma_uint32 framesToWrite = subBufferSizeInFrames;
if (framesToWrite > (ma_uint32)frameCount) framesToWrite = (ma_uint32)frameCount;
ma_uint32 framesToWrite = (ma_uint32)frameCount;
ma_uint32 bytesToWrite = framesToWrite*stream.channels*(stream.sampleSize/8);
memcpy(subBuffer, data, bytesToWrite);
@ -2232,7 +2274,7 @@ static ma_uint32 ReadAudioBufferFramesInMixingFormat(AudioBuffer *audioBuffer, f
ma_uint64 outputFramesToProcessThisIteration = frameCount - totalOutputFramesProcessed;
ma_uint64 inputFramesToProcessThisIteration = 0;
ma_result result = ma_data_converter_get_required_input_frame_count(&audioBuffer->converter, outputFramesToProcessThisIteration, &inputFramesToProcessThisIteration);
(void)ma_data_converter_get_required_input_frame_count(&audioBuffer->converter, outputFramesToProcessThisIteration, &inputFramesToProcessThisIteration);
if (inputFramesToProcessThisIteration > inputBufferFrameCap)
{
inputFramesToProcessThisIteration = inputBufferFrameCap;

View file

@ -1,201 +0,0 @@
/**********************************************************************************************
*
* raudio v1.0 - A simple and easy-to-use audio library based on miniaudio
*
* FEATURES:
* - Manage audio device (init/close)
* - Load and unload audio files
* - Format wave data (sample rate, size, channels)
* - Play/Stop/Pause/Resume loaded audio
* - Manage mixing channels
* - Manage raw audio context
*
* DEPENDENCIES:
* miniaudio.h - Audio device management lib (https://github.com/dr-soft/miniaudio)
* stb_vorbis.h - Ogg audio files loading (http://www.nothings.org/stb_vorbis/)
* dr_mp3.h - MP3 audio file loading (https://github.com/mackron/dr_libs)
* dr_flac.h - FLAC audio file loading (https://github.com/mackron/dr_libs)
* jar_xm.h - XM module file loading
* jar_mod.h - MOD audio file loading
*
* CONTRIBUTORS:
* David Reid (github: @mackron) (Nov. 2017):
* - Complete port to miniaudio library
*
* Joshua Reisenauer (github: @kd7tck) (2015)
* - XM audio module support (jar_xm)
* - MOD audio module support (jar_mod)
* - Mixing channels support
* - Raw audio context support
*
*
* LICENSE: zlib/libpng
*
* Copyright (c) 2014-2022 Ramon Santamaria (@raysan5)
*
* This software is provided "as-is", without any express or implied warranty. In no event
* will the authors be held liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose, including commercial
* applications, and to alter it and redistribute it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not claim that you
* wrote the original software. If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be misrepresented
* as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*
**********************************************************************************************/
#ifndef RAUDIO_H
#define RAUDIO_H
//----------------------------------------------------------------------------------
// Defines and Macros
//----------------------------------------------------------------------------------
// Allow custom memory allocators
#ifndef RL_MALLOC
#define RL_MALLOC(sz) malloc(sz)
#endif
#ifndef RL_CALLOC
#define RL_CALLOC(n,sz) calloc(n,sz)
#endif
#ifndef RL_FREE
#define RL_FREE(p) free(p)
#endif
//----------------------------------------------------------------------------------
// Types and Structures Definition
//----------------------------------------------------------------------------------
#ifndef __cplusplus
// Boolean type
#if !defined(_STDBOOL_H)
typedef enum { false, true } bool;
#define _STDBOOL_H
#endif
#endif
// Wave, audio wave data
typedef struct Wave {
unsigned int frameCount; // Total number of frames (considering channels)
unsigned int sampleRate; // Frequency (samples per second)
unsigned int sampleSize; // Bit depth (bits per sample): 8, 16, 32 (24 not supported)
unsigned int channels; // Number of channels (1-mono, 2-stereo, ...)
void *data; // Buffer data pointer
} Wave;
typedef struct rAudioBuffer rAudioBuffer;
// AudioStream, custom audio stream
typedef struct AudioStream {
rAudioBuffer *buffer; // Pointer to internal data used by the audio system
unsigned int sampleRate; // Frequency (samples per second)
unsigned int sampleSize; // Bit depth (bits per sample): 8, 16, 32 (24 not supported)
unsigned int channels; // Number of channels (1-mono, 2-stereo, ...)
} AudioStream;
// Sound
typedef struct Sound {
AudioStream stream; // Audio stream
unsigned int frameCount; // Total number of frames (considering channels)
} Sound;
// Music, audio stream, anything longer than ~10 seconds should be streamed
typedef struct Music {
AudioStream stream; // Audio stream
unsigned int frameCount; // Total number of frames (considering channels)
bool looping; // Music looping enable
int ctxType; // Type of music context (audio filetype)
void *ctxData; // Audio context data, depends on type
} Music;
//----------------------------------------------------------------------------------
// Global Variables Definition
//----------------------------------------------------------------------------------
//...
//----------------------------------------------------------------------------------
// Module Functions Declaration
//----------------------------------------------------------------------------------
#ifdef __cplusplus
extern "C" { // Prevents name mangling of functions
#endif
// Audio device management functions
void InitAudioDevice(void); // Initialize audio device and context
void CloseAudioDevice(void); // Close the audio device and context
bool IsAudioDeviceReady(void); // Check if audio device has been initialized successfully
void SetMasterVolume(float volume); // Set master volume (listener)
// Wave/Sound loading/unloading functions
Wave LoadWave(const char *fileName); // Load wave data from file
Wave LoadWaveFromMemory(const char *fileType, const unsigned char *fileData, int dataSize); // Load wave from memory buffer, fileType refers to extension: i.e. ".wav"
Sound LoadSound(const char *fileName); // Load sound from file
Sound LoadSoundFromWave(Wave wave); // Load sound from wave data
void UpdateSound(Sound sound, const void *data, int samplesCount);// Update sound buffer with new data
void UnloadWave(Wave wave); // Unload wave data
void UnloadSound(Sound sound); // Unload sound
bool ExportWave(Wave wave, const char *fileName); // Export wave data to file, returns true on success
bool ExportWaveAsCode(Wave wave, const char *fileName); // Export wave sample data to code (.h), returns true on success
// Wave/Sound management functions
void PlaySound(Sound sound); // Play a sound
void StopSound(Sound sound); // Stop playing a sound
void PauseSound(Sound sound); // Pause a sound
void ResumeSound(Sound sound); // Resume a paused sound
void PlaySoundMulti(Sound sound); // Play a sound (using multichannel buffer pool)
void StopSoundMulti(void); // Stop any sound playing (using multichannel buffer pool)
int GetSoundsPlaying(void); // Get number of sounds playing in the multichannel
bool IsSoundPlaying(Sound sound); // Check if a sound is currently playing
void SetSoundVolume(Sound sound, float volume); // Set volume for a sound (1.0 is max level)
void SetSoundPitch(Sound sound, float pitch); // Set pitch for a sound (1.0 is base level)
void SetSoundPan(Sound sound, float pan); // Set pan for a sound (0.0 to 1.0, 0.5=center)
void WaveFormat(Wave *wave, int sampleRate, int sampleSize, int channels); // Convert wave data to desired format
Wave WaveCopy(Wave wave); // Copy a wave to a new wave
void WaveCrop(Wave *wave, int initSample, int finalSample); // Crop a wave to defined samples range
float *LoadWaveSamples(Wave wave); // Load samples data from wave as a floats array
void UnloadWaveSamples(float *samples); // Unload samples data loaded with LoadWaveSamples()
// Music management functions
Music LoadMusicStream(const char *fileName); // Load music stream from file
Music LoadMusicStreamFromMemory(const char *fileType, unsigned char* data, int dataSize); // Load music stream from data
void UnloadMusicStream(Music music); // Unload music stream
void PlayMusicStream(Music music); // Start music playing
bool IsMusicStreamPlaying(Music music); // Check if music is playing
void UpdateMusicStream(Music music); // Updates buffers for music streaming
void StopMusicStream(Music music); // Stop music playing
void PauseMusicStream(Music music); // Pause music playing
void ResumeMusicStream(Music music); // Resume playing paused music
void SeekMusicStream(Music music, float position); // Seek music to a position (in seconds)
void SetMusicVolume(Music music, float volume); // Set volume for music (1.0 is max level)
void SetMusicPan(Music sound, float pan); // Set pan for a music (0.0 to 1.0, 0.5=center)
void SetMusicPitch(Music music, float pitch); // Set pitch for a music (1.0 is base level)
float GetMusicTimeLength(Music music); // Get music time length (in seconds)
float GetMusicTimePlayed(Music music); // Get current music time played (in seconds)
// AudioStream management functions
AudioStream LoadAudioStream(unsigned int sampleRate, unsigned int sampleSize, unsigned int channels); // Load audio stream (to stream raw audio pcm data)
void UpdateAudioStream(AudioStream stream, const void *data, int samplesCount); // Update audio stream buffers with data
void UnloadAudioStream(AudioStream stream); // Unload audio stream and free memory
bool IsAudioStreamProcessed(AudioStream stream); // Check if any audio stream buffers requires refill
void PlayAudioStream(AudioStream stream); // Play audio stream
void PauseAudioStream(AudioStream stream); // Pause audio stream
void ResumeAudioStream(AudioStream stream); // Resume audio stream
bool IsAudioStreamPlaying(AudioStream stream); // Check if audio stream is playing
void StopAudioStream(AudioStream stream); // Stop audio stream
void SetAudioStreamVolume(AudioStream stream, float volume); // Set volume for audio stream (1.0 is max level)
void SetAudioStreamPitch(AudioStream stream, float pitch); // Set pitch for audio stream (1.0 is base level)
void SetAudioStreamPan(AudioStream strean, float pan); // Set pan for audio stream (0.0 to 1.0, 0.5=center)
void SetAudioStreamBufferSizeDefault(int size); // Default size for new audio streams
#ifdef __cplusplus
}
#endif
#endif // RAUDIO_H

View file

@ -1,8 +1,8 @@
GLFW_ICON ICON "raylib.ico"
1 VERSIONINFO
FILEVERSION 4,0,0,0
PRODUCTVERSION 4,0,0,0
FILEVERSION 4,2,0,0
PRODUCTVERSION 4,2,0,0
BEGIN
BLOCK "StringFileInfo"
BEGIN
@ -11,12 +11,12 @@ BEGIN
BEGIN
//VALUE "CompanyName", "raylib technologies"
VALUE "FileDescription", "raylib dynamic library (www.raylib.com)"
VALUE "FileVersion", "4.0.0"
VALUE "FileVersion", "4.2.0"
VALUE "InternalName", "raylib.dll"
VALUE "LegalCopyright", "(c) 2022 Ramon Santamaria (@raysan5)"
VALUE "OriginalFilename", "raylib.dll"
VALUE "ProductName", "raylib"
VALUE "ProductVersion", "4.0.0"
VALUE "ProductVersion", "4.2.0"
END
END
BLOCK "VarFileInfo"

Binary file not shown.

View file

@ -1,6 +1,6 @@
/**********************************************************************************************
*
* raylib v4.2-dev - A simple and easy-to-use library to enjoy videogames programming (www.raylib.com)
* raylib v4.2 - A simple and easy-to-use library to enjoy videogames programming (www.raylib.com)
*
* FEATURES:
* - NO external dependencies, all required libraries included with raylib
@ -43,6 +43,7 @@
* [rmodels] par_shapes (Philip Rideout) for parametric 3d shapes generation
* [rmodels] tinyobj_loader_c (Syoyo Fujita) for models loading (OBJ, MTL)
* [rmodels] cgltf (Johannes Kuhlmann) for models loading (glTF)
* [rmodels] Model3D (bzt) for models loading (M3D, https://bztsrc.gitlab.io/model3d)
* [raudio] dr_wav (David Reid) for WAV audio file loading
* [raudio] dr_flac (David Reid) for FLAC audio file loading
* [raudio] dr_mp3 (David Reid) for MP3 audio file loading
@ -80,12 +81,15 @@
#include <stdarg.h> // Required for: va_list - Only used by TraceLogCallback
#define RAYLIB_VERSION "4.2-dev"
#define RAYLIB_VERSION "4.2"
// Function specifiers in case library is build/used as a shared library (Windows)
// NOTE: Microsoft specifiers to tell compiler that symbols are imported/exported from a .dll
#if defined(_WIN32)
#if defined(BUILD_LIBTYPE_SHARED)
#if defined(__TINYC__)
#define __declspec(x) __attribute__((x))
#endif
#define RLAPI __declspec(dllexport) // We are building the library as a Win32 shared library (.dll)
#elif defined(USE_LIBTYPE_SHARED)
#define RLAPI __declspec(dllimport) // We are using the library as a Win32 shared library (.dll)
@ -110,6 +114,7 @@
#endif
// Allow custom memory allocators
// NOTE: Require recompiling raylib sources
#ifndef RL_MALLOC
#define RL_MALLOC(sz) malloc(sz)
#endif
@ -482,6 +487,13 @@ typedef struct VrStereoConfig {
float scaleIn[2]; // VR distortion scale in
} VrStereoConfig;
// File path list
typedef struct FilePathList {
unsigned int capacity; // Filepaths max entries
unsigned int count; // Filepaths entries count
char **paths; // Filepaths entries
} FilePathList;
//----------------------------------------------------------------------------------
// Enumerators Definition
//----------------------------------------------------------------------------------
@ -501,6 +513,7 @@ typedef enum {
FLAG_WINDOW_ALWAYS_RUN = 0x00000100, // Set to allow windows running while minimized
FLAG_WINDOW_TRANSPARENT = 0x00000010, // Set to allow transparent framebuffer
FLAG_WINDOW_HIGHDPI = 0x00002000, // Set to support HighDPI
FLAG_WINDOW_MOUSE_PASSTHROUGH = 0x00004000, // Set to support mouse passthrough, only supported when FLAG_WINDOW_UNDECORATED
FLAG_MSAA_4X_HINT = 0x00000020, // Set to try enabling MSAA 4X
FLAG_INTERLACED_HINT = 0x00010000 // Set to try enabling interlaced video format (for V3D)
} ConfigFlags;
@ -890,8 +903,8 @@ typedef enum {
typedef void (*TraceLogCallback)(int logLevel, const char *text, va_list args); // Logging: Redirect trace log messages
typedef unsigned char *(*LoadFileDataCallback)(const char *fileName, unsigned int *bytesRead); // FileIO: Load binary data
typedef bool (*SaveFileDataCallback)(const char *fileName, void *data, unsigned int bytesToWrite); // FileIO: Save binary data
typedef char *(*LoadFileTextCallback)(const char *fileName); // FileIO: Load text data
typedef bool (*SaveFileTextCallback)(const char *fileName, char *text); // FileIO: Save text data
typedef char *(*LoadFileTextCallback)(const char *fileName); // FileIO: Load text data
typedef bool (*SaveFileTextCallback)(const char *fileName, char *text); // FileIO: Save text data
//------------------------------------------------------------------------------------
// Global Variables Definition
@ -939,8 +952,8 @@ RLAPI int GetRenderHeight(void); // Get current
RLAPI int GetMonitorCount(void); // Get number of connected monitors
RLAPI int GetCurrentMonitor(void); // Get current connected monitor
RLAPI Vector2 GetMonitorPosition(int monitor); // Get specified monitor position
RLAPI int GetMonitorWidth(int monitor); // Get specified monitor width (max available by monitor)
RLAPI int GetMonitorHeight(int monitor); // Get specified monitor height (max available by monitor)
RLAPI int GetMonitorWidth(int monitor); // Get specified monitor width (current video mode used by monitor)
RLAPI int GetMonitorHeight(int monitor); // Get specified monitor height (current video mode used by monitor)
RLAPI int GetMonitorPhysicalWidth(int monitor); // Get specified monitor physical width in millimetres
RLAPI int GetMonitorPhysicalHeight(int monitor); // Get specified monitor physical height in millimetres
RLAPI int GetMonitorRefreshRate(int monitor); // Get specified monitor refresh rate
@ -1030,6 +1043,8 @@ RLAPI void *MemAlloc(int size); // Internal me
RLAPI void *MemRealloc(void *ptr, int size); // Internal memory reallocator
RLAPI void MemFree(void *ptr); // Internal memory free
RLAPI void OpenURL(const char *url); // Open URL with default system browser (if available)
// Set custom callbacks
// WARNING: Callbacks setup is intended for advance users
RLAPI void SetTraceLogCallback(TraceLogCallback callback); // Set custom trace log
@ -1058,11 +1073,13 @@ RLAPI const char *GetPrevDirectoryPath(const char *dirPath); // Get previou
RLAPI const char *GetWorkingDirectory(void); // Get current working directory (uses static string)
RLAPI const char *GetApplicationDirectory(void); // Get the directory if the running application (uses static string)
RLAPI bool ChangeDirectory(const char *dir); // Change working directory, return true on success
RLAPI char **LoadDirectoryFiles(const char *dirPath, int *count); // Load directory filepaths
RLAPI void UnloadDirectoryFiles(void); // Unload directory filepaths
RLAPI bool IsPathFile(const char *path); // Check if a given path is a file or a directory
RLAPI FilePathList LoadDirectoryFiles(const char *dirPath); // Load directory filepaths
RLAPI FilePathList LoadDirectoryFilesEx(const char *basePath, const char *filter, bool scanSubdirs); // Load directory filepaths with extension filtering and recursive directory scan
RLAPI void UnloadDirectoryFiles(FilePathList files); // Unload filepaths
RLAPI bool IsFileDropped(void); // Check if a file has been dropped into window
RLAPI char **LoadDroppedFiles(int *count); // Load dropped filepaths
RLAPI void UnloadDroppedFiles(void); // Unload dropped filepaths
RLAPI FilePathList LoadDroppedFiles(void); // Load dropped filepaths
RLAPI void UnloadDroppedFiles(FilePathList files); // Unload dropped filepaths
RLAPI long GetFileModTime(const char *fileName); // Get file modification time (last write time)
// Compression/Encoding functionality
@ -1071,12 +1088,6 @@ RLAPI unsigned char *DecompressData(const unsigned char *compData, int compDataS
RLAPI char *EncodeDataBase64(const unsigned char *data, int dataSize, int *outputSize); // Encode data to Base64 string, memory must be MemFree()
RLAPI unsigned char *DecodeDataBase64(const unsigned char *data, int *outputSize); // Decode Base64 string data, memory must be MemFree()
// Persistent storage management
RLAPI bool SaveStorageValue(unsigned int position, int value); // Save integer value to storage file (to defined position), returns true on success
RLAPI int LoadStorageValue(unsigned int position); // Load integer value from storage file (from defined position)
RLAPI void OpenURL(const char *url); // Open URL with default system browser (if available)
//------------------------------------------------------------------------------------
// Input Handling Functions (Module: core)
//------------------------------------------------------------------------------------
@ -1114,7 +1125,8 @@ RLAPI Vector2 GetMouseDelta(void); // Get mouse delta
RLAPI void SetMousePosition(int x, int y); // Set mouse position XY
RLAPI void SetMouseOffset(int offsetX, int offsetY); // Set mouse offset
RLAPI void SetMouseScale(float scaleX, float scaleY); // Set mouse scaling
RLAPI float GetMouseWheelMove(void); // Get mouse wheel movement Y
RLAPI float GetMouseWheelMove(void); // Get mouse wheel movement for X or Y, whichever is larger
RLAPI Vector2 GetMouseWheelMoveV(void); // Get mouse wheel movement for both X and Y
RLAPI void SetMouseCursor(int cursor); // Set mouse cursor
// Input-related functions: touch
@ -1436,7 +1448,6 @@ RLAPI void DrawMeshInstanced(Mesh mesh, Material material, const Matrix *transfo
RLAPI bool ExportMesh(Mesh mesh, const char *fileName); // Export mesh data to file, returns true on success
RLAPI BoundingBox GetMeshBoundingBox(Mesh mesh); // Compute mesh bounding box limits
RLAPI void GenMeshTangents(Mesh *mesh); // Compute mesh tangents
RLAPI void GenMeshBinormals(Mesh *mesh); // Compute mesh binormals
// Mesh generation functions
RLAPI Mesh GenMeshPoly(int sides, float radius); // Generate polygonal mesh
@ -1548,8 +1559,8 @@ RLAPI void SetAudioStreamPan(AudioStream stream, float pan); // Set pan
RLAPI void SetAudioStreamBufferSizeDefault(int size); // Default size for new audio streams
RLAPI void SetAudioStreamCallback(AudioStream stream, AudioCallback callback); // Audio thread callback to request new data
RLAPI void AttachAudioStreamProcessor(AudioStream stream, AudioCallback processor);
RLAPI void DetachAudioStreamProcessor(AudioStream stream, AudioCallback processor);
RLAPI void AttachAudioStreamProcessor(AudioStream stream, AudioCallback processor); // Attach audio stream processor to stream
RLAPI void DetachAudioStreamProcessor(AudioStream stream, AudioCallback processor); // Detach audio stream processor from stream
#if defined(__cplusplus)
}

View file

@ -1,8 +1,8 @@
GLFW_ICON ICON "raylib.ico"
1 VERSIONINFO
FILEVERSION 4,0,0,0
PRODUCTVERSION 4,0,0,0
FILEVERSION 4,2,0,0
PRODUCTVERSION 4,2,0,0
BEGIN
BLOCK "StringFileInfo"
BEGIN
@ -11,12 +11,12 @@ BEGIN
BEGIN
//VALUE "CompanyName", "raylib technologies"
VALUE "FileDescription", "raylib application (www.raylib.com)"
VALUE "FileVersion", "4.0.0"
VALUE "FileVersion", "4.2.0"
VALUE "InternalName", "raylib app"
VALUE "LegalCopyright", "(c) 2022 Ramon Santamaria (@raysan5)"
//VALUE "OriginalFilename", "raylib_app.exe"
VALUE "ProductName", "raylib app"
VALUE "ProductVersion", "4.0.0"
VALUE "ProductVersion", "4.2.0"
END
END
BLOCK "VarFileInfo"

Binary file not shown.

View file

@ -158,7 +158,7 @@ typedef struct float16 {
float v[16];
} float16;
#include <math.h> // Required for: sinf(), cosf(), tan(), atan2f(), sqrtf(), fminf(), fmaxf(), fabs()
#include <math.h> // Required for: sinf(), cosf(), tan(), atan2f(), sqrtf(), floor(), fminf(), fmaxf(), fabs()
//----------------------------------------------------------------------------------
// Module Functions Definition - Utils math
@ -198,6 +198,14 @@ RMAPI float Remap(float value, float inputStart, float inputEnd, float outputSta
return result;
}
// Wrap input value from min to max
RMAPI float Wrap(float value, float min, float max)
{
float result = value - (max - min)*floorf((value - min)/(max - min));
return result;
}
// Check whether two given floats are almost equal
RMAPI int FloatEquals(float x, float y)
{
@ -449,7 +457,7 @@ RMAPI Vector2 Vector2Clamp(Vector2 v, Vector2 min, Vector2 max)
// Clamp the magnitude of the vector between two min and max values
RMAPI Vector2 Vector2ClampValue(Vector2 v, float min, float max)
{
Vector2 result = { 0 };
Vector2 result = v;
float length = (v.x*v.x) + (v.y*v.y);
if (length > 0.0f)
@ -745,6 +753,58 @@ RMAPI Vector3 Vector3RotateByQuaternion(Vector3 v, Quaternion q)
return result;
}
// Rotates a vector around an axis
RMAPI Vector3 Vector3RotateByAxisAngle(Vector3 v, Vector3 axis, float angle)
{
// Using Euler-Rodrigues Formula
// Ref.: https://en.wikipedia.org/w/index.php?title=Euler%E2%80%93Rodrigues_formula
Vector3 result = v;
// Vector3Normalize(axis);
float length = sqrtf(axis.x * axis.x + axis.y * axis.y + axis.z * axis.z);
if (length == 0.0f) length = 1.0f;
float ilength = 1.0f / length;
axis.x *= ilength;
axis.y *= ilength;
axis.z *= ilength;
angle /= 2.0f;
float a = sinf(angle);
float b = axis.x * a;
float c = axis.y * a;
float d = axis.z * a;
a = cosf(angle);
Vector3 w = { b, c, d };
// Vector3CrossProduct(w, v)
Vector3 wv = { w.y * v.z - w.z * v.y, w.z * v.x - w.x * v.z, w.x * v.y - w.y * v.x };
// Vector3CrossProduct(w, wv)
Vector3 wwv = { w.y * wv.z - w.z * wv.y, w.z * wv.x - w.x * wv.z, w.x * wv.y - w.y * wv.x };
// Vector3Scale(wv, 2 * a)
a *= 2;
wv.x *= a;
wv.y *= a;
wv.z *= a;
// Vector3Scale(wwv, 2)
wwv.x *= 2;
wwv.y *= 2;
wwv.z *= 2;
result.x += wv.x;
result.y += wv.y;
result.z += wv.z;
result.x += wwv.x;
result.y += wwv.y;
result.z += wwv.z;
return result;
}
// Calculate linear interpolation between two vectors
RMAPI Vector3 Vector3Lerp(Vector3 v1, Vector3 v2, float amount)
{
@ -943,7 +1003,7 @@ RMAPI Vector3 Vector3Clamp(Vector3 v, Vector3 min, Vector3 max)
// Clamp the magnitude of the vector between two values
RMAPI Vector3 Vector3ClampValue(Vector3 v, float min, float max)
{
Vector3 result = { 0 };
Vector3 result = v;
float length = (v.x*v.x) + (v.y*v.y) + (v.z*v.z);
if (length > 0.0f)
@ -1253,7 +1313,8 @@ RMAPI Matrix MatrixRotate(Vector3 axis, float angle)
return result;
}
// Get x-rotation matrix (angle in radians)
// Get x-rotation matrix
// NOTE: Angle must be provided in radians
RMAPI Matrix MatrixRotateX(float angle)
{
Matrix result = { 1.0f, 0.0f, 0.0f, 0.0f,
@ -1265,14 +1326,15 @@ RMAPI Matrix MatrixRotateX(float angle)
float sinres = sinf(angle);
result.m5 = cosres;
result.m6 = -sinres;
result.m9 = sinres;
result.m6 = sinres;
result.m9 = -sinres;
result.m10 = cosres;
return result;
}
// Get y-rotation matrix (angle in radians)
// Get y-rotation matrix
// NOTE: Angle must be provided in radians
RMAPI Matrix MatrixRotateY(float angle)
{
Matrix result = { 1.0f, 0.0f, 0.0f, 0.0f,
@ -1284,14 +1346,15 @@ RMAPI Matrix MatrixRotateY(float angle)
float sinres = sinf(angle);
result.m0 = cosres;
result.m2 = sinres;
result.m8 = -sinres;
result.m2 = -sinres;
result.m8 = sinres;
result.m10 = cosres;
return result;
}
// Get z-rotation matrix (angle in radians)
// Get z-rotation matrix
// NOTE: Angle must be provided in radians
RMAPI Matrix MatrixRotateZ(float angle)
{
Matrix result = { 1.0f, 0.0f, 0.0f, 0.0f,
@ -1303,74 +1366,76 @@ RMAPI Matrix MatrixRotateZ(float angle)
float sinres = sinf(angle);
result.m0 = cosres;
result.m1 = -sinres;
result.m4 = sinres;
result.m1 = sinres;
result.m4 = -sinres;
result.m5 = cosres;
return result;
}
// Get xyz-rotation matrix (angles in radians)
RMAPI Matrix MatrixRotateXYZ(Vector3 ang)
// Get xyz-rotation matrix
// NOTE: Angle must be provided in radians
RMAPI Matrix MatrixRotateXYZ(Vector3 angle)
{
Matrix result = { 1.0f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f }; // MatrixIdentity()
float cosz = cosf(-ang.z);
float sinz = sinf(-ang.z);
float cosy = cosf(-ang.y);
float siny = sinf(-ang.y);
float cosx = cosf(-ang.x);
float sinx = sinf(-ang.x);
float cosz = cosf(-angle.z);
float sinz = sinf(-angle.z);
float cosy = cosf(-angle.y);
float siny = sinf(-angle.y);
float cosx = cosf(-angle.x);
float sinx = sinf(-angle.x);
result.m0 = cosz*cosy;
result.m4 = (cosz*siny*sinx) - (sinz*cosx);
result.m8 = (cosz*siny*cosx) + (sinz*sinx);
result.m1 = (cosz*siny*sinx) - (sinz*cosx);
result.m2 = (cosz*siny*cosx) + (sinz*sinx);
result.m1 = sinz*cosy;
result.m4 = sinz*cosy;
result.m5 = (sinz*siny*sinx) + (cosz*cosx);
result.m9 = (sinz*siny*cosx) - (cosz*sinx);
result.m6 = (sinz*siny*cosx) - (cosz*sinx);
result.m2 = -siny;
result.m6 = cosy*sinx;
result.m8 = -siny;
result.m9 = cosy*sinx;
result.m10= cosy*cosx;
return result;
}
// Get zyx-rotation matrix (angles in radians)
RMAPI Matrix MatrixRotateZYX(Vector3 ang)
// Get zyx-rotation matrix
// NOTE: Angle must be provided in radians
RMAPI Matrix MatrixRotateZYX(Vector3 angle)
{
Matrix result = { 0 };
float cz = cosf(ang.z);
float sz = sinf(ang.z);
float cy = cosf(ang.y);
float sy = sinf(ang.y);
float cx = cosf(ang.x);
float sx = sinf(ang.x);
float cz = cosf(angle.z);
float sz = sinf(angle.z);
float cy = cosf(angle.y);
float sy = sinf(angle.y);
float cx = cosf(angle.x);
float sx = sinf(angle.x);
result.m0 = cz*cy;
result.m1 = cz*sy*sx - cx*sz;
result.m2 = sz*sx + cz*cx*sy;
result.m3 = 0;
result.m4 = cy*sz;
result.m5 = cz*cx + sz*sy*sx;
result.m6 = cx*sz*sy - cz*sx;
result.m7 = 0;
result.m8 = -sy;
result.m9 = cy*sx;
result.m10 = cy*cx;
result.m11 = 0;
result.m4 = cz*sy*sx - cx*sz;
result.m8 = sz*sx + cz*cx*sy;
result.m12 = 0;
result.m1 = cy*sz;
result.m5 = cz*cx + sz*sy*sx;
result.m9 = cx*sz*sy - cz*sx;
result.m13 = 0;
result.m2 = -sy;
result.m6 = cy*sx;
result.m10 = cy*cx;
result.m14 = 0;
result.m3 = 0;
result.m7 = 0;
result.m11 = 0;
result.m15 = 1;
return result;
@ -1420,7 +1485,7 @@ RMAPI Matrix MatrixFrustum(double left, double right, double bottom, double top,
}
// Get perspective projection matrix
// NOTE: Angle should be provided in radians
// NOTE: Fovy angle must be provided in radians
RMAPI Matrix MatrixPerspective(double fovy, double aspect, double near, double far)
{
Matrix result = { 0 };
@ -1794,30 +1859,60 @@ RMAPI Quaternion QuaternionFromMatrix(Matrix mat)
{
Quaternion result = { 0 };
if ((mat.m0 > mat.m5) && (mat.m0 > mat.m10))
{
float s = sqrtf(1.0f + mat.m0 - mat.m5 - mat.m10)*2;
float fourWSquaredMinus1 = mat.m0 + mat.m5 + mat.m10;
float fourXSquaredMinus1 = mat.m0 - mat.m5 - mat.m10;
float fourYSquaredMinus1 = mat.m5 - mat.m0 - mat.m10;
float fourZSquaredMinus1 = mat.m10 - mat.m0 - mat.m5;
result.x = 0.25f*s;
result.y = (mat.m4 + mat.m1)/s;
result.z = (mat.m2 + mat.m8)/s;
result.w = (mat.m9 - mat.m6)/s;
}
else if (mat.m5 > mat.m10)
int biggestIndex = 0;
float fourBiggestSquaredMinus1 = fourWSquaredMinus1;
if (fourXSquaredMinus1 > fourBiggestSquaredMinus1)
{
float s = sqrtf(1.0f + mat.m5 - mat.m0 - mat.m10)*2;
result.x = (mat.m4 + mat.m1)/s;
result.y = 0.25f*s;
result.z = (mat.m9 + mat.m6)/s;
result.w = (mat.m2 - mat.m8)/s;
fourBiggestSquaredMinus1 = fourXSquaredMinus1;
biggestIndex = 1;
}
else
if (fourYSquaredMinus1 > fourBiggestSquaredMinus1)
{
float s = sqrtf(1.0f + mat.m10 - mat.m0 - mat.m5)*2;
result.x = (mat.m2 + mat.m8)/s;
result.y = (mat.m9 + mat.m6)/s;
result.z = 0.25f*s;
result.w = (mat.m4 - mat.m1)/s;
fourBiggestSquaredMinus1 = fourYSquaredMinus1;
biggestIndex = 2;
}
if (fourZSquaredMinus1 > fourBiggestSquaredMinus1)
{
fourBiggestSquaredMinus1 = fourZSquaredMinus1;
biggestIndex = 3;
}
float biggestVal = sqrtf(fourBiggestSquaredMinus1 + 1.0f) * 0.5f;
float mult = 0.25f / biggestVal;
switch (biggestIndex)
{
case 0:
result.w = biggestVal;
result.x = (mat.m6 - mat.m9) * mult;
result.y = (mat.m8 - mat.m2) * mult;
result.z = (mat.m1 - mat.m4) * mult;
break;
case 1:
result.x = biggestVal;
result.w = (mat.m6 - mat.m9) * mult;
result.y = (mat.m1 + mat.m4) * mult;
result.z = (mat.m8 + mat.m2) * mult;
break;
case 2:
result.y = biggestVal;
result.w = (mat.m8 - mat.m2) * mult;
result.x = (mat.m1 + mat.m4) * mult;
result.z = (mat.m6 + mat.m9) * mult;
break;
case 3:
result.z = biggestVal;
result.w = (mat.m1 - mat.m4) * mult;
result.x = (mat.m8 + mat.m2) * mult;
result.y = (mat.m6 + mat.m9) * mult;
break;
}
return result;
@ -1857,7 +1952,7 @@ RMAPI Matrix QuaternionToMatrix(Quaternion q)
}
// Get rotation quaternion for an angle and axis
// NOTE: angle must be provided in radians
// NOTE: Angle must be provided in radians
RMAPI Quaternion QuaternionFromAxisAngle(Vector3 axis, float angle)
{
Quaternion result = { 0.0f, 0.0f, 0.0f, 1.0f };
@ -2001,10 +2096,14 @@ RMAPI Quaternion QuaternionTransform(Quaternion q, Matrix mat)
// Check whether two given quaternions are almost equal
RMAPI int QuaternionEquals(Quaternion p, Quaternion q)
{
int result = ((fabsf(p.x - q.x)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.x), fabsf(q.x))))) &&
int result = (((fabsf(p.x - q.x)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.x), fabsf(q.x))))) &&
((fabsf(p.y - q.y)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.y), fabsf(q.y))))) &&
((fabsf(p.z - q.z)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.z), fabsf(q.z))))) &&
((fabsf(p.w - q.w)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.w), fabsf(q.w)))));
((fabsf(p.w - q.w)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.w), fabsf(q.w)))))) ||
(((fabsf(p.x + q.x)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.x), fabsf(q.x))))) &&
((fabsf(p.y + q.y)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.y), fabsf(q.y))))) &&
((fabsf(p.z + q.z)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.z), fabsf(q.z))))) &&
((fabsf(p.w + q.w)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.w), fabsf(q.w))))));
return result;
}

View file

@ -103,7 +103,7 @@
// Module Functions Declaration
//----------------------------------------------------------------------------------
#ifdef __cplusplus
#if defined(__cplusplus)
extern "C" { // Prevents name mangling of functions
#endif
@ -119,7 +119,7 @@ void SetCameraMoveControls(int keyFront, int keyBack,
int keyUp, int keyDown); // Set camera move controls (1st person and 3rd person cameras)
#endif
#ifdef __cplusplus
#if defined(__cplusplus)
}
#endif
@ -150,7 +150,7 @@ void SetCameraMoveControls(int keyFront, int keyBack,
#endif
// Camera mouse movement sensitivity
#define CAMERA_MOUSE_MOVE_SENSITIVITY 0.003f
#define CAMERA_MOUSE_MOVE_SENSITIVITY 0.5f // TODO: it should be independant of framerate
#define CAMERA_MOUSE_SCROLL_SENSITIVITY 1.5f
// FREE_CAMERA
@ -163,7 +163,7 @@ void SetCameraMoveControls(int keyFront, int keyBack,
#define CAMERA_FREE_PANNING_DIVIDER 5.1f
// ORBITAL_CAMERA
#define CAMERA_ORBITAL_SPEED 0.01f // Radians per frame
#define CAMERA_ORBITAL_SPEED 0.5f // Radians per second
// FIRST_PERSON
//#define CAMERA_FIRST_PERSON_MOUSE_SENSITIVITY 0.003f
@ -171,9 +171,11 @@ void SetCameraMoveControls(int keyFront, int keyBack,
#define CAMERA_FIRST_PERSON_MIN_CLAMP 89.0f
#define CAMERA_FIRST_PERSON_MAX_CLAMP -89.0f
#define CAMERA_FIRST_PERSON_STEP_TRIGONOMETRIC_DIVIDER 8.0f
#define CAMERA_FIRST_PERSON_STEP_DIVIDER 30.0f
#define CAMERA_FIRST_PERSON_WAVING_DIVIDER 200.0f
// When walking, y-position of the player moves up-down at step frequency (swinging) but
// also the body slightly tilts left-right on every step, when all the body weight is left over one foot (tilting)
#define CAMERA_FIRST_PERSON_STEP_FREQUENCY 1.8f // Step frequency when walking (steps per second)
#define CAMERA_FIRST_PERSON_SWINGING_DELTA 0.03f // Maximum up-down swinging distance when walking
#define CAMERA_FIRST_PERSON_TILTING_DELTA 0.005f // Maximum left-right tilting distance when walking
// THIRD_PERSON
//#define CAMERA_THIRD_PERSON_MOUSE_SENSITIVITY 0.003f
@ -183,7 +185,7 @@ void SetCameraMoveControls(int keyFront, int keyBack,
#define CAMERA_THIRD_PERSON_OFFSET (Vector3){ 0.4f, 0.0f, 0.0f }
// PLAYER (used by camera)
#define PLAYER_MOVEMENT_SENSITIVITY 20.0f
#define PLAYER_MOVEMENT_SENSITIVITY 2.0f
//----------------------------------------------------------------------------------
// Types and Structures Definition
@ -204,7 +206,6 @@ typedef struct {
float targetDistance; // Camera distance from position to target
float playerEyesPosition; // Player eyes position from ground (in meters)
Vector2 angle; // Camera angle in plane XZ
Vector2 previousMousePosition; // Previous mouse position
// Camera movement control keys
int moveControl[6]; // Move controls (CAMERA_FIRST_PERSON)
@ -221,7 +222,6 @@ static CameraData CAMERA = { // Global CAMERA state context
.targetDistance = 0,
.playerEyesPosition = 1.85f,
.angle = { 0 },
.previousMousePosition = { 0 },
.moveControl = { 'W', 'S', 'D', 'A', 'E', 'Q' },
.smoothZoomControl = 341, // raylib: KEY_LEFT_CONTROL
.altControl = 342, // raylib: KEY_LEFT_ALT
@ -265,8 +265,6 @@ void SetCameraMode(Camera camera, int mode)
CAMERA.playerEyesPosition = camera.position.y; // Init player eyes position to camera Y position
CAMERA.previousMousePosition = GetMousePosition(); // Init mouse position
// Lock cursor for first person and third person cameras
if ((mode == CAMERA_FIRST_PERSON) || (mode == CAMERA_THIRD_PERSON)) DisableCursor();
else EnableCursor();
@ -281,13 +279,12 @@ void SetCameraMode(Camera camera, int mode)
// Keys: IsKeyDown()
void UpdateCamera(Camera *camera)
{
static int swingCounter = 0; // Used for 1st person swinging movement
static float swingCounter = 0.0f; // Used for 1st person swinging movement
// TODO: Compute CAMERA.targetDistance and CAMERA.angle here (?)
// Mouse movement detection
Vector2 mousePositionDelta = { 0.0f, 0.0f };
Vector2 mousePosition = GetMousePosition();
Vector2 mousePositionDelta = GetMouseDelta();
float mouseWheelMove = GetMouseWheelMove();
// Keys input detection
@ -302,14 +299,6 @@ void UpdateCamera(Camera *camera)
IsKeyDown(CAMERA.moveControl[MOVE_UP]),
IsKeyDown(CAMERA.moveControl[MOVE_DOWN]) };
if (CAMERA.mode != CAMERA_CUSTOM)
{
mousePositionDelta.x = mousePosition.x - CAMERA.previousMousePosition.x;
mousePositionDelta.y = mousePosition.y - CAMERA.previousMousePosition.y;
CAMERA.previousMousePosition = mousePosition;
}
// Support for multiple automatic camera modes
// NOTE: In case of CAMERA_CUSTOM nothing happens here, user must update it manually
switch (CAMERA.mode)
@ -402,7 +391,7 @@ void UpdateCamera(Camera *camera)
} break;
case CAMERA_ORBITAL: // Camera just orbits around target, only zoom allowed
{
CAMERA.angle.x += CAMERA_ORBITAL_SPEED; // Camera orbit angle
CAMERA.angle.x += CAMERA_ORBITAL_SPEED*GetFrameTime(); // Camera orbit angle
CAMERA.targetDistance -= (mouseWheelMove*CAMERA_MOUSE_SCROLL_SENSITIVITY); // Camera zoom
// Camera distance clamp
@ -419,20 +408,20 @@ void UpdateCamera(Camera *camera)
camera->position.x += (sinf(CAMERA.angle.x)*direction[MOVE_BACK] -
sinf(CAMERA.angle.x)*direction[MOVE_FRONT] -
cosf(CAMERA.angle.x)*direction[MOVE_LEFT] +
cosf(CAMERA.angle.x)*direction[MOVE_RIGHT])/PLAYER_MOVEMENT_SENSITIVITY;
cosf(CAMERA.angle.x)*direction[MOVE_RIGHT])*PLAYER_MOVEMENT_SENSITIVITY*GetFrameTime();
camera->position.y += (sinf(CAMERA.angle.y)*direction[MOVE_FRONT] -
sinf(CAMERA.angle.y)*direction[MOVE_BACK] +
1.0f*direction[MOVE_UP] - 1.0f*direction[MOVE_DOWN])/PLAYER_MOVEMENT_SENSITIVITY;
1.0f*direction[MOVE_UP] - 1.0f*direction[MOVE_DOWN])*PLAYER_MOVEMENT_SENSITIVITY*GetFrameTime();
camera->position.z += (cosf(CAMERA.angle.x)*direction[MOVE_BACK] -
cosf(CAMERA.angle.x)*direction[MOVE_FRONT] +
sinf(CAMERA.angle.x)*direction[MOVE_LEFT] -
sinf(CAMERA.angle.x)*direction[MOVE_RIGHT])/PLAYER_MOVEMENT_SENSITIVITY;
sinf(CAMERA.angle.x)*direction[MOVE_RIGHT])*PLAYER_MOVEMENT_SENSITIVITY*GetFrameTime();
// Camera orientation calculation
CAMERA.angle.x += (mousePositionDelta.x*-CAMERA_MOUSE_MOVE_SENSITIVITY);
CAMERA.angle.y += (mousePositionDelta.y*-CAMERA_MOUSE_MOVE_SENSITIVITY);
CAMERA.angle.x -= mousePositionDelta.x*CAMERA_MOUSE_MOVE_SENSITIVITY*GetFrameTime();
CAMERA.angle.y -= mousePositionDelta.y*CAMERA_MOUSE_MOVE_SENSITIVITY*GetFrameTime();
// Angle clamp
if (CAMERA.angle.y > CAMERA_FIRST_PERSON_MIN_CLAMP*DEG2RAD) CAMERA.angle.y = CAMERA_FIRST_PERSON_MIN_CLAMP*DEG2RAD;
@ -490,15 +479,17 @@ void UpdateCamera(Camera *camera)
camera->target.y = camera->position.y - matTransform.m13;
camera->target.z = camera->position.z - matTransform.m14;
// If movement detected (some key pressed), increase swinging
for (int i = 0; i < 6; i++) if (direction[i]) { swingCounter++; break; }
// Camera position update
// NOTE: On CAMERA_FIRST_PERSON player Y-movement is limited to player 'eyes position'
camera->position.y = CAMERA.playerEyesPosition - sinf(swingCounter/CAMERA_FIRST_PERSON_STEP_TRIGONOMETRIC_DIVIDER)/CAMERA_FIRST_PERSON_STEP_DIVIDER;
camera->position.y = CAMERA.playerEyesPosition;
camera->up.x = sinf(swingCounter/(CAMERA_FIRST_PERSON_STEP_TRIGONOMETRIC_DIVIDER*2))/CAMERA_FIRST_PERSON_WAVING_DIVIDER;
camera->up.z = -sinf(swingCounter/(CAMERA_FIRST_PERSON_STEP_TRIGONOMETRIC_DIVIDER*2))/CAMERA_FIRST_PERSON_WAVING_DIVIDER;
// Camera swinging (y-movement), only when walking (some key pressed)
for (int i = 0; i < 6; i++) if (direction[i]) { swingCounter += GetFrameTime(); break; }
camera->position.y -= sinf(2*PI*CAMERA_FIRST_PERSON_STEP_FREQUENCY*swingCounter)*CAMERA_FIRST_PERSON_SWINGING_DELTA;
// Camera waiving (xz-movement), only when walking (some key pressed)
camera->up.x = sinf(2*PI*CAMERA_FIRST_PERSON_STEP_FREQUENCY*swingCounter)*CAMERA_FIRST_PERSON_TILTING_DELTA;
camera->up.z = -sinf(2*PI*CAMERA_FIRST_PERSON_STEP_FREQUENCY*swingCounter)*CAMERA_FIRST_PERSON_TILTING_DELTA;
} break;
case CAMERA_THIRD_PERSON: // Camera moves as in a third-person game, following target at a distance, controls are configurable
@ -506,16 +497,16 @@ void UpdateCamera(Camera *camera)
camera->position.x += (sinf(CAMERA.angle.x)*direction[MOVE_BACK] -
sinf(CAMERA.angle.x)*direction[MOVE_FRONT] -
cosf(CAMERA.angle.x)*direction[MOVE_LEFT] +
cosf(CAMERA.angle.x)*direction[MOVE_RIGHT])/PLAYER_MOVEMENT_SENSITIVITY;
cosf(CAMERA.angle.x)*direction[MOVE_RIGHT])*PLAYER_MOVEMENT_SENSITIVITY*GetFrameTime();
camera->position.y += (sinf(CAMERA.angle.y)*direction[MOVE_FRONT] -
sinf(CAMERA.angle.y)*direction[MOVE_BACK] +
1.0f*direction[MOVE_UP] - 1.0f*direction[MOVE_DOWN])/PLAYER_MOVEMENT_SENSITIVITY;
1.0f*direction[MOVE_UP] - 1.0f*direction[MOVE_DOWN])*PLAYER_MOVEMENT_SENSITIVITY*GetFrameTime();
camera->position.z += (cosf(CAMERA.angle.x)*direction[MOVE_BACK] -
cosf(CAMERA.angle.x)*direction[MOVE_FRONT] +
sinf(CAMERA.angle.x)*direction[MOVE_LEFT] -
sinf(CAMERA.angle.x)*direction[MOVE_RIGHT])/PLAYER_MOVEMENT_SENSITIVITY;
sinf(CAMERA.angle.x)*direction[MOVE_RIGHT])*PLAYER_MOVEMENT_SENSITIVITY*GetFrameTime();
// Camera orientation calculation
CAMERA.angle.x += (mousePositionDelta.x*-CAMERA_MOUSE_MOVE_SENSITIVITY);

Some files were not shown because too many files have changed in this diff Show more