merge upstream master into feature branch

This commit is contained in:
Cry dsch 2021-06-01 22:10:04 +02:00
commit eface0dc00
16 changed files with 3460 additions and 2698 deletions

View file

@ -24,7 +24,6 @@ endif()
set(raylib_public_headers
raylib.h
rlgl.h
physac.h
raymath.h
raudio.h
)

View file

@ -43,8 +43,8 @@
.PHONY: all clean install uninstall
# Define required raylib variables
RAYLIB_VERSION = 3.7.0
RAYLIB_API_VERSION = 370
RAYLIB_VERSION = 3.7.1
RAYLIB_API_VERSION = 371
# Define raylib source code path
RAYLIB_SRC_PATH ?= ../src

View file

@ -270,12 +270,6 @@
#include <emscripten/html5.h> // Emscripten HTML5 library
#endif
#if defined(SUPPORT_COMPRESSION_API)
// NOTE: Those declarations require stb_image and stb_image_write definitions, included in textures module
unsigned char *stbi_zlib_compress(unsigned char *data, int data_len, int *out_len, int quality);
char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen);
#endif
//----------------------------------------------------------------------------------
// Defines and Macros
//----------------------------------------------------------------------------------
@ -652,7 +646,7 @@ void InitWindow(int width, int height, const char *title)
#if defined(PLATFORM_UWP)
if (!UWPIsConfigured())
{
TRACELOG(LOG_ERROR, "UWP Functions have not been set yet, please set these before initializing raylib!");
TRACELOG(LOG_FATAL, "UWP Functions have not been set yet, please set these before initializing raylib!");
return;
}
#endif
@ -736,7 +730,12 @@ void InitWindow(int width, int height, const char *title)
// NOTE: returns true if window and graphic device has been initialized successfully
CORE.Window.ready = InitGraphicsDevice(width, height);
if (!CORE.Window.ready) return;
// If graphic device is no properly initialized, we end program
if (!CORE.Window.ready)
{
TRACELOG(LOG_FATAL, "Failed to initialize Graphic Device");
return;
}
// Init hi-res timer
InitTimer();
@ -2035,8 +2034,8 @@ void EndShaderMode(void)
rlSetShader(rlGetShaderDefault());
}
// Begin blending mode (alpha, additive, multiplied)
// NOTE: Only 3 blending modes supported, default blend mode is alpha
// Begin blending mode (alpha, additive, multiplied, subtract, custom)
// NOTE: Blend modes supported are enumerated in BlendMode enum
void BeginBlendMode(int mode)
{
rlSetBlendMode(mode);
@ -2179,8 +2178,8 @@ Shader LoadShader(const char *vsFileName, const char *fsFileName)
shader.id = rlLoadShaderCode(vShaderStr, fShaderStr);
if (vShaderStr != NULL) RL_FREE(vShaderStr);
if (fShaderStr != NULL) RL_FREE(fShaderStr);
if (vShaderStr != NULL) UnloadFileText(vShaderStr);
if (fShaderStr != NULL) UnloadFileText(fShaderStr);
// After shader loading, we TRY to set default location names
if (shader.id > 0)
@ -2801,8 +2800,8 @@ char **GetDirectoryFiles(const char *dirPath, int *fileCount)
ClearDirectoryFiles();
// Memory allocation for MAX_DIRECTORY_FILES
dirFilesPath = (char **)RL_MALLOC(sizeof(char *)*MAX_DIRECTORY_FILES);
for (int i = 0; i < MAX_DIRECTORY_FILES; i++) dirFilesPath[i] = (char *)RL_MALLOC(sizeof(char)*MAX_FILEPATH_LENGTH);
dirFilesPath = (char **)RL_MALLOC(MAX_DIRECTORY_FILES*sizeof(char *));
for (int i = 0; i < MAX_DIRECTORY_FILES; i++) dirFilesPath[i] = (char *)RL_MALLOC(MAX_FILEPATH_LENGTH*sizeof(char));
int counter = 0;
struct dirent *entity;
@ -3543,7 +3542,7 @@ static bool InitGraphicsDevice(int width, int height)
CORE.Window.display.width = mode->width;
CORE.Window.display.height = mode->height;
// Screen size security check
// Set screen width/height to the display width/height if they are 0
if (CORE.Window.screen.width == 0) CORE.Window.screen.width = CORE.Window.display.width;
if (CORE.Window.screen.height == 0) CORE.Window.screen.height = CORE.Window.display.height;
#endif // PLATFORM_DESKTOP
@ -4914,6 +4913,7 @@ static void SwapBuffers(void)
{
gbm_surface_release_buffer(CORE.Window.gbmSurface, CORE.Window.prevBO);
}
CORE.Window.prevBO = bo;
#endif // PLATFORM_DRM
#endif // PLATFORM_ANDROID || PLATFORM_RPI || PLATFORM_DRM || PLATFORM_UWP
@ -5151,11 +5151,11 @@ static void WindowDropCallback(GLFWwindow *window, int count, const char **paths
{
ClearDroppedFiles();
CORE.Window.dropFilesPath = (char **)RL_MALLOC(sizeof(char *)*count);
CORE.Window.dropFilesPath = (char **)RL_MALLOC(count*sizeof(char *));
for (int i = 0; i < count; i++)
{
CORE.Window.dropFilesPath[i] = (char *)RL_MALLOC(sizeof(char)*MAX_FILEPATH_LENGTH);
CORE.Window.dropFilesPath[i] = (char *)RL_MALLOC(MAX_FILEPATH_LENGTH*sizeof(char));
strcpy(CORE.Window.dropFilesPath[i], paths[i]);
}
@ -6268,15 +6268,15 @@ bool UWPIsConfigured()
{
bool pass = true;
if (uwpQueryTimeFunc == NULL) { TRACELOG(LOG_ERROR, "UWP: UWPSetQueryTimeFunc() must be called with a valid function before InitWindow()"); pass = false; }
if (uwpSleepFunc == NULL) { TRACELOG(LOG_ERROR, "UWP: UWPSetSleepFunc() must be called with a valid function before InitWindow()"); pass = false; }
if (uwpDisplaySizeFunc == NULL) { TRACELOG(LOG_ERROR, "UWP: UWPSetDisplaySizeFunc() must be called with a valid function before InitWindow()"); pass = false; }
if (uwpMouseLockFunc == NULL) { TRACELOG(LOG_ERROR, "UWP: UWPSetMouseLockFunc() must be called with a valid function before InitWindow()"); pass = false; }
if (uwpMouseUnlockFunc == NULL) { TRACELOG(LOG_ERROR, "UWP: UWPSetMouseUnlockFunc() must be called with a valid function before InitWindow()"); pass = false; }
if (uwpMouseShowFunc == NULL) { TRACELOG(LOG_ERROR, "UWP: UWPSetMouseShowFunc() must be called with a valid function before InitWindow()"); pass = false; }
if (uwpMouseHideFunc == NULL) { TRACELOG(LOG_ERROR, "UWP: UWPSetMouseHideFunc() must be called with a valid function before InitWindow()"); pass = false; }
if (uwpMouseSetPosFunc == NULL) { TRACELOG(LOG_ERROR, "UWP: UWPSetMouseSetPosFunc() must be called with a valid function before InitWindow()"); pass = false; }
if (uwpCoreWindow == NULL) { TRACELOG(LOG_ERROR, "UWP: A pointer to the UWP core window must be set before InitWindow()"); pass = false; }
if (uwpQueryTimeFunc == NULL) { TRACELOG(LOG_WARNING, "UWP: UWPSetQueryTimeFunc() must be called with a valid function before InitWindow()"); pass = false; }
if (uwpSleepFunc == NULL) { TRACELOG(LOG_WARNING, "UWP: UWPSetSleepFunc() must be called with a valid function before InitWindow()"); pass = false; }
if (uwpDisplaySizeFunc == NULL) { TRACELOG(LOG_WARNING, "UWP: UWPSetDisplaySizeFunc() must be called with a valid function before InitWindow()"); pass = false; }
if (uwpMouseLockFunc == NULL) { TRACELOG(LOG_WARNING, "UWP: UWPSetMouseLockFunc() must be called with a valid function before InitWindow()"); pass = false; }
if (uwpMouseUnlockFunc == NULL) { TRACELOG(LOG_WARNING, "UWP: UWPSetMouseUnlockFunc() must be called with a valid function before InitWindow()"); pass = false; }
if (uwpMouseShowFunc == NULL) { TRACELOG(LOG_WARNING, "UWP: UWPSetMouseShowFunc() must be called with a valid function before InitWindow()"); pass = false; }
if (uwpMouseHideFunc == NULL) { TRACELOG(LOG_WARNING, "UWP: UWPSetMouseHideFunc() must be called with a valid function before InitWindow()"); pass = false; }
if (uwpMouseSetPosFunc == NULL) { TRACELOG(LOG_WARNING, "UWP: UWPSetMouseSetPosFunc() must be called with a valid function before InitWindow()"); pass = false; }
if (uwpCoreWindow == NULL) { TRACELOG(LOG_WARNING, "UWP: A pointer to the UWP core window must be set before InitWindow()"); pass = false; }
return pass;
}

263
src/extras/easings.h Normal file
View file

@ -0,0 +1,263 @@
/*******************************************************************************************
*
* 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); }
EASEDEF float EaseLinearIn(float t, float b, float c, float d) { return (c*t/d + b); }
EASEDEF float EaseLinearOut(float t, float b, float c, float d) { return (c*t/d + b); }
EASEDEF float EaseLinearInOut(float t,float b, float c, float d) { return (c*t/d + b); }
// Sine Easing functions
EASEDEF float EaseSineIn(float t, float b, float c, float d) { return (-c*cosf(t/d*(PI/2.0f)) + c + b); }
EASEDEF float EaseSineOut(float t, float b, float c, float d) { return (c*sinf(t/d*(PI/2.0f)) + b); }
EASEDEF float EaseSineInOut(float t, float b, float c, float d) { return (-c/2.0f*(cosf(PI*t/d) - 1.0f) + b); }
// 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); }
EASEDEF float EaseCircOut(float t, float b, float c, float d) { t = t/d - 1.0f; return (c*sqrtf(1.0f - t*t) + b); }
EASEDEF float EaseCircInOut(float t, float b, float c, float d)
{
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); }
EASEDEF float EaseCubicOut(float t, float b, float c, float d) { t = t/d - 1.0f; return (c*(t*t*t + 1.0f) + b); }
EASEDEF float EaseCubicInOut(float t, float b, float c, float d)
{
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); }
EASEDEF float EaseQuadOut(float t, float b, float c, float d) { t /= d; return (-c*t*(t - 2.0f) + b); }
EASEDEF float EaseQuadInOut(float t, float b, float c, float d)
{
if ((t/=d/2) < 1) return (((c/2)*(t*t)) + b);
return (-c/2.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); }
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); }
EASEDEF float EaseExpoInOut(float t, float b, float c, float d)
{
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)
{
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)
{
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)
{
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)
{
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); }
EASEDEF float EaseBounceInOut(float t, float b, float c, float d)
{
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)
{
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)
{
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)
{
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

1988
src/extras/physac.h Normal file

File diff suppressed because it is too large Load diff

739
src/extras/rmem.h Normal file
View file

@ -0,0 +1,739 @@
/**********************************************************************************************
*
* 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;
}
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 > 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, iter, node);
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.
********/

2256
src/extras/rnet.h Normal file

File diff suppressed because it is too large Load diff

View file

@ -1027,7 +1027,7 @@ void DrawMeshInstanced(Mesh mesh, Material material, Matrix *transforms, int ins
if (instancing)
{
// Create instances buffer
instanceTransforms = RL_MALLOC(instances*sizeof(float16));
instanceTransforms = (float16 *)RL_MALLOC(instances*sizeof(float16));
// Fill buffer with instances transformations as float16 arrays
for (int i = 0; i < instances; i++) instanceTransforms[i] = MatrixToFloatV(transforms[i]);
@ -1461,9 +1461,9 @@ void UpdateModelAnimation(Model model, ModelAnimation anim, int frame)
animVertex = Vector3Subtract(animVertex, inTranslation);
animVertex = Vector3RotateByQuaternion(animVertex, QuaternionMultiply(outRotation, QuaternionInvert(inRotation)));
animVertex = Vector3Add(animVertex, outTranslation);
model.meshes[m].animVertices[vCounter] += animVertex.x * boneWeight;
model.meshes[m].animVertices[vCounter + 1] += animVertex.y * boneWeight;
model.meshes[m].animVertices[vCounter + 2] += animVertex.z * boneWeight;
model.meshes[m].animVertices[vCounter] += animVertex.x*boneWeight;
model.meshes[m].animVertices[vCounter + 1] += animVertex.y*boneWeight;
model.meshes[m].animVertices[vCounter + 2] += animVertex.z*boneWeight;
// Normals processing
// NOTE: We use meshes.baseNormals (default normal) to calculate meshes.normals (animated normals)
@ -1471,9 +1471,9 @@ void UpdateModelAnimation(Model model, ModelAnimation anim, int frame)
{
animNormal = (Vector3){ model.meshes[m].normals[vCounter], model.meshes[m].normals[vCounter + 1], model.meshes[m].normals[vCounter + 2] };
animNormal = Vector3RotateByQuaternion(animNormal, QuaternionMultiply(outRotation, QuaternionInvert(inRotation)));
model.meshes[m].animNormals[vCounter] += animNormal.x * boneWeight;
model.meshes[m].animNormals[vCounter + 1] += animNormal.y * boneWeight;
model.meshes[m].animNormals[vCounter + 2] += animNormal.z * boneWeight;
model.meshes[m].animNormals[vCounter] += animNormal.x*boneWeight;
model.meshes[m].animNormals[vCounter + 1] += animNormal.y*boneWeight;
model.meshes[m].animNormals[vCounter + 2] += animNormal.z*boneWeight;
}
boneCounter += 1;
}
@ -2982,41 +2982,41 @@ bool CheckCollisionBoxSphere(BoundingBox box, Vector3 center, float radius)
// Get collision info between ray and sphere
RayCollision GetRayCollisionSphere(Ray ray, Vector3 center, float radius)
{
RayCollision result = { 0 };
RayCollision collision = { 0 };
Vector3 raySpherePos = Vector3Subtract(center, ray.position);
float vector = Vector3DotProduct(raySpherePos, ray.direction);
float distance = Vector3Length(raySpherePos);
float d = radius*radius - (distance * distance - vector*vector);
result.hit = d >= 0.0f;
collision.hit = d >= 0.0f;
// Check if ray origin is inside the sphere to calculate the correct collision point
if (distance < radius) { // inside
result.distance = vector + sqrtf(d);
collision.distance = vector + sqrtf(d);
// Calculate collision point
result.point = Vector3Add(ray.position, Vector3Scale(ray.direction, result.distance));
collision.point = Vector3Add(ray.position, Vector3Scale(ray.direction, collision.distance));
// Calculate collision normal (pointing outwards)
result.normal = Vector3Negate(Vector3Normalize(Vector3Subtract(result.point, center)));
collision.normal = Vector3Negate(Vector3Normalize(Vector3Subtract(collision.point, center)));
} else { // outside
result.distance = vector - sqrtf(d);
collision.distance = vector - sqrtf(d);
// Calculate collision point
result.point = Vector3Add(ray.position, Vector3Scale(ray.direction, result.distance));
collision.point = Vector3Add(ray.position, Vector3Scale(ray.direction, collision.distance));
// Calculate collision normal (pointing inwards)
result.normal = Vector3Normalize(Vector3Subtract(result.point, center));
collision.normal = Vector3Normalize(Vector3Subtract(collision.point, center));
}
return result;
return collision;
}
// Get collision info between ray and bounding box
// Get collision info between ray and box
RayCollision GetRayCollisionBox(Ray ray, BoundingBox box)
{
RayCollision result = { 0 };
RayCollision collision = { 0 };
// Note: If ray.position is inside the box, the distance is negative (as if the ray was reversed)
// Reversing ray.direction will give use the correct result.
@ -3044,42 +3044,42 @@ RayCollision GetRayCollisionBox(Ray ray, BoundingBox box)
t[6] = (float)fmax(fmax(fmin(t[0], t[1]), fmin(t[2], t[3])), fmin(t[4], t[5]));
t[7] = (float)fmin(fmin(fmax(t[0], t[1]), fmax(t[2], t[3])), fmax(t[4], t[5]));
result.hit = !(t[7] < 0 || t[6] > t[7]);
result.distance = t[6];
result.point = Vector3Add(ray.position, Vector3Scale(ray.direction, result.distance));
collision.hit = !(t[7] < 0 || t[6] > t[7]);
collision.distance = t[6];
collision.point = Vector3Add(ray.position, Vector3Scale(ray.direction, collision.distance));
// Get box center point
result.normal = Vector3Lerp(box.min, box.max, 0.5f);
collision.normal = Vector3Lerp(box.min, box.max, 0.5f);
// Get vector center point->hit point
result.normal = Vector3Subtract(result.point, result.normal);
collision.normal = Vector3Subtract(collision.point, collision.normal);
// Scale vector to unit cube
// we use an additional .01 to fix numerical errors
result.normal = Vector3Scale(result.normal, 2.01f);
result.normal = Vector3Divide(result.normal, Vector3Subtract(box.max, box.min));
collision.normal = Vector3Scale(collision.normal, 2.01f);
collision.normal = Vector3Divide(collision.normal, Vector3Subtract(box.max, box.min));
// the relevant elemets of the vector are now slightly larger than 1.0f (or smaller than -1.0f)
// and the others are somewhere between -1.0 and 1.0
// casting to int is exactly our wanted normal!
result.normal.x = (int)result.normal.x;
result.normal.y = (int)result.normal.y;
result.normal.z = (int)result.normal.z;
collision.normal.x = (int)collision.normal.x;
collision.normal.y = (int)collision.normal.y;
collision.normal.z = (int)collision.normal.z;
result.normal = Vector3Normalize(result.normal);
collision.normal = Vector3Normalize(collision.normal);
if (insideBox) {
// Reset ray.direction
ray.direction = Vector3Negate(ray.direction);
// Fix result
result.distance *= -1.0f;
result.normal = Vector3Negate(result.normal);
collision.distance *= -1.0f;
collision.normal = Vector3Negate(collision.normal);
}
return result;
return collision;
}
// Get collision info between ray and mesh
RayCollision GetRayCollisionMesh(Ray ray, Mesh mesh, Matrix transform)
{
RayCollision result = { 0 };
RayCollision collision = { 0 };
// Check if mesh vertex data on CPU for testing
if (mesh.vertices != NULL)
@ -3114,17 +3114,18 @@ RayCollision GetRayCollisionMesh(Ray ray, Mesh mesh, Matrix transform)
if (triHitInfo.hit)
{
// Save the closest hit triangle
if ((!result.hit) || (result.distance > triHitInfo.distance)) result = triHitInfo;
if ((!collision.hit) || (collision.distance > triHitInfo.distance)) collision = triHitInfo;
}
}
}
return result;
return collision;
}
// Get collision info between ray and model
RayCollision GetRayCollisionModel(Ray ray, Model model)
{
RayCollision result = { 0 };
RayCollision collision = { 0 };
for (int m = 0; m < model.meshCount; m++)
{
@ -3133,11 +3134,11 @@ RayCollision GetRayCollisionModel(Ray ray, Model model)
if (meshHitInfo.hit)
{
// Save the closest hit mesh
if ((!result.hit) || (result.distance > meshHitInfo.distance)) result = meshHitInfo;
if ((!collision.hit) || (collision.distance > meshHitInfo.distance)) collision = meshHitInfo;
}
}
return result;
return collision;
}
// Get collision info between ray and triangle
@ -3147,10 +3148,11 @@ RayCollision GetRayCollisionTriangle(Ray ray, Vector3 p1, Vector3 p2, Vector3 p3
{
#define EPSILON 0.000001 // A small number
Vector3 edge1, edge2;
RayCollision collision = { 0 };
Vector3 edge1 = { 0 };
Vector3 edge2 = { 0 };
Vector3 p, q, tv;
float det, invDet, u, v, t;
RayCollision result = {0};
// Find vectors for two edges sharing V1
edge1 = Vector3Subtract(p2, p1);
@ -3163,7 +3165,7 @@ RayCollision GetRayCollisionTriangle(Ray ray, Vector3 p1, Vector3 p2, Vector3 p3
det = Vector3DotProduct(edge1, p);
// Avoid culling!
if ((det > -EPSILON) && (det < EPSILON)) return result;
if ((det > -EPSILON) && (det < EPSILON)) return collision;
invDet = 1.0f/det;
@ -3174,7 +3176,7 @@ RayCollision GetRayCollisionTriangle(Ray ray, Vector3 p1, Vector3 p2, Vector3 p3
u = Vector3DotProduct(tv, p)*invDet;
// The intersection lies outside of the triangle
if ((u < 0.0f) || (u > 1.0f)) return result;
if ((u < 0.0f) || (u > 1.0f)) return collision;
// Prepare to test v parameter
q = Vector3CrossProduct(tv, edge1);
@ -3183,20 +3185,20 @@ RayCollision GetRayCollisionTriangle(Ray ray, Vector3 p1, Vector3 p2, Vector3 p3
v = Vector3DotProduct(ray.direction, q)*invDet;
// The intersection lies outside of the triangle
if ((v < 0.0f) || ((u + v) > 1.0f)) return result;
if ((v < 0.0f) || ((u + v) > 1.0f)) return collision;
t = Vector3DotProduct(edge2, q)*invDet;
if (t > EPSILON)
{
// Ray hit, get hit point and normal
result.hit = true;
result.distance = t;
result.normal = Vector3Normalize(Vector3CrossProduct(edge1, edge2));
result.point = Vector3Add(ray.position, Vector3Scale(ray.direction, t));
collision.hit = true;
collision.distance = t;
collision.normal = Vector3Normalize(Vector3CrossProduct(edge1, edge2));
collision.point = Vector3Add(ray.position, Vector3Scale(ray.direction, t));
}
return result;
return collision;
}
// Get collision info between ray and quad
@ -3208,7 +3210,7 @@ RayCollision GetRayCollisionQuad(Ray ray, Vector3 p1, Vector3 p2, Vector3 p3, Ve
if (!result.hit) result = GetRayCollisionTriangle(ray, p2, p3, p4);
return result;
return collision;
}
//----------------------------------------------------------------------------------
@ -3228,11 +3230,11 @@ static Model LoadOBJ(const char *fileName)
tinyobj_material_t *materials = NULL;
unsigned int materialCount = 0;
char *fileData = LoadFileText(fileName);
char *fileText = LoadFileText(fileName);
if (fileData != NULL)
if (fileText != NULL)
{
unsigned int dataSize = (unsigned int)strlen(fileData);
unsigned int dataSize = (unsigned int)strlen(fileText);
char currentDir[1024] = { 0 };
strcpy(currentDir, GetWorkingDirectory());
const char *workingDir = GetDirectoryPath(fileName);
@ -3242,7 +3244,7 @@ static Model LoadOBJ(const char *fileName)
}
unsigned int flags = TINYOBJ_FLAG_TRIANGULATE;
int ret = tinyobj_parse_obj(&attrib, &meshes, &meshCount, &materials, &materialCount, fileData, dataSize, flags);
int ret = tinyobj_parse_obj(&attrib, &meshes, &meshCount, &materials, &materialCount, fileText, dataSize, flags);
if (ret != TINYOBJ_SUCCESS) TRACELOG(LOG_WARNING, "MODEL: [%s] Failed to load OBJ data", fileName);
else TRACELOG(LOG_INFO, "MODEL: [%s] OBJ data loaded successfully: %i meshes / %i materials", fileName, meshCount, materialCount);
@ -3369,9 +3371,9 @@ static Model LoadOBJ(const char *fileName)
tinyobj_shapes_free(meshes, meshCount);
tinyobj_materials_free(materials, materialCount);
RL_FREE(fileData);
UnloadFileText(fileText);
RL_FREE(matFaces);
RL_FREE(vCount);
RL_FREE(vtCount);
RL_FREE(vnCount);
@ -3481,7 +3483,7 @@ static Model LoadIQM(const char *fileName)
IQM_TANGENT = 3, // NOTE: Tangents unused by default
IQM_BLENDINDEXES = 4,
IQM_BLENDWEIGHTS = 5,
IQM_COLOR = 6, // NOTE: Vertex colors unused by default
IQM_COLOR = 6,
IQM_CUSTOM = 0x10 // NOTE: Custom vertex values unused by default
};
@ -3497,6 +3499,7 @@ static Model LoadIQM(const char *fileName)
float *text = NULL;
char *blendi = NULL;
unsigned char *blendw = NULL;
unsigned char *color = NULL;
// In case file can not be read, return an empty model
if (fileDataPtr == NULL) return model;
@ -3519,7 +3522,7 @@ static Model LoadIQM(const char *fileName)
//fileDataPtr += sizeof(IQMHeader); // Move file data pointer
// Meshes data processing
imesh = RL_MALLOC(sizeof(IQMMesh)*iqmHeader->num_meshes);
imesh = RL_MALLOC(iqmHeader->num_meshes*sizeof(IQMMesh));
//fseek(iqmFile, iqmHeader->ofs_meshes, SEEK_SET);
//fread(imesh, sizeof(IQMMesh)*iqmHeader->num_meshes, 1, iqmFile);
memcpy(imesh, fileDataPtr + iqmHeader->ofs_meshes, iqmHeader->num_meshes*sizeof(IQMMesh));
@ -3685,6 +3688,25 @@ static Model LoadIQM(const char *fileName)
}
}
} break;
case IQM_COLOR:
{
color = RL_MALLOC(iqmHeader->num_vertexes*4*sizeof(unsigned char));
//fseek(iqmFile, va[i].offset, SEEK_SET);
//fread(blendw, iqmHeader->num_vertexes*4*sizeof(unsigned char), 1, iqmFile);
memcpy(color, fileDataPtr + va[i].offset, iqmHeader->num_vertexes*4*sizeof(unsigned char));
for (unsigned int m = 0; m < iqmHeader->num_meshes; m++)
{
model.meshes[m].colors = RL_CALLOC(model.meshes[m].vertexCount*4, sizeof(unsigned char));
int vCounter = 0;
for (unsigned int i = imesh[m].first_vertex*4; i < (imesh[m].first_vertex + imesh[m].num_vertexes)*4; i++)
{
model.meshes[m].colors[vCounter] = color[i];
vCounter++;
}
}
} break;
}
}
@ -4324,6 +4346,40 @@ static Model LoadGLTF(const char *fileName)
TRACELOG(LOG_WARNING, "MODEL: [%s] glTF normals must be float or int", fileName);
}
}
else if (data->meshes[i].primitives[p].attributes[j].type == cgltf_attribute_type_color)
{
cgltf_accessor *acc = data->meshes[i].primitives[p].attributes[j].data;
model.meshes[primitiveIndex].colors = RL_MALLOC(acc->count*4*sizeof(unsigned char));
if (acc->component_type == cgltf_component_type_r_8u)
{
for (int a = 0; a < acc->count; a++)
{
GLTFReadValue(acc, a, model.meshes[primitiveIndex].colors + (a*4), 4, sizeof(unsigned char));
}
}
if (acc->component_type == cgltf_component_type_r_16u)
{
TRACELOG(LOG_WARNING, "MODEL: [%s] converting glTF colors to unsigned char", fileName);
for (int a = 0; a < acc->count; a++)
{
unsigned short readValue[4];
for (int a = 0; a < acc->count; a++)
{
GLTFReadValue(acc, a, readValue, 4, sizeof(unsigned short));
// 257 = 65535/255
model.meshes[primitiveIndex].colors[(a*4) + 0] = (unsigned char)(readValue[0] / 257);
model.meshes[primitiveIndex].colors[(a*4) + 1] = (unsigned char)(readValue[1] / 257);
model.meshes[primitiveIndex].colors[(a*4) + 2] = (unsigned char)(readValue[2] / 257);
model.meshes[primitiveIndex].colors[(a*4) + 3] = (unsigned char)(readValue[3] / 257);
}
}
}
else
{
TRACELOG(LOG_WARNING, "MODEL: [%s] glTF colors must be uchar or ushort", fileName);
}
}
}
cgltf_accessor *acc = data->meshes[i].primitives[p].indices;
@ -4489,8 +4545,8 @@ static void LoadGLTFBoneAttribute(Model* model, cgltf_accessor* jointsAccessor,
{
if (jointsAccessor->component_type == cgltf_component_type_r_16u)
{
model->meshes[primitiveIndex].boneIds = RL_MALLOC(sizeof(int)*jointsAccessor->count*4);
short* bones = RL_MALLOC(sizeof(short)*jointsAccessor->count*4);
model->meshes[primitiveIndex].boneIds = RL_MALLOC(jointsAccessor->count*4*sizeof(int));
short* bones = RL_MALLOC(jointsAccessor->count*4*sizeof(short));
for (unsigned int a = 0; a < jointsAccessor->count; a++)
{
@ -4514,8 +4570,8 @@ static void LoadGLTFBoneAttribute(Model* model, cgltf_accessor* jointsAccessor,
}
else if (jointsAccessor->component_type == cgltf_component_type_r_8u)
{
model->meshes[primitiveIndex].boneIds = RL_MALLOC(sizeof(int)*jointsAccessor->count*4);
unsigned char* bones = RL_MALLOC(sizeof(unsigned char)*jointsAccessor->count*4);
model->meshes[primitiveIndex].boneIds = RL_MALLOC(jointsAccessor->count*4*sizeof(int));
unsigned char* bones = RL_MALLOC(jointsAccessor->count*4*sizeof(unsigned char));
for (unsigned int a = 0; a < jointsAccessor->count; a++)
{

View file

@ -276,25 +276,27 @@ typedef struct tagBITMAPINFOHEADER {
// NOTE: Depends on data structure provided by the library
// in charge of reading the different file types
typedef enum {
MUSIC_AUDIO_NONE = 0,
MUSIC_AUDIO_WAV,
MUSIC_AUDIO_OGG,
MUSIC_AUDIO_FLAC,
MUSIC_AUDIO_MP3,
MUSIC_MODULE_XM,
MUSIC_MODULE_MOD
MUSIC_AUDIO_NONE = 0, // No audio context loaded
MUSIC_AUDIO_WAV, // WAV audio context
MUSIC_AUDIO_OGG, // OGG audio context
MUSIC_AUDIO_FLAC, // FLAC audio context
MUSIC_AUDIO_MP3, // MP3 audio context
MUSIC_MODULE_XM, // XM module audio context
MUSIC_MODULE_MOD // MOD module audio context
} MusicContextType;
#if defined(RAUDIO_STANDALONE)
// Trace log level
// NOTE: Organized by priority level
typedef enum {
LOG_ALL,
LOG_TRACE,
LOG_DEBUG,
LOG_INFO,
LOG_WARNING,
LOG_ERROR,
LOG_FATAL,
LOG_NONE
LOG_ALL = 0, // Display all logs
LOG_TRACE, // Trace logging, intended for internal use only
LOG_DEBUG, // Debug logging, used for internal debugging, it should be disabled on release builds
LOG_INFO, // Info logging, used for program execution info
LOG_WARNING, // Warning logging, used on recoverable failures
LOG_ERROR, // Error logging, used on unrecoverable failures
LOG_FATAL, // Fatal logging, used to abort program: exit(EXIT_FAILURE)
LOG_NONE // Disable logging
} TraceLogLevel;
#endif
@ -476,7 +478,7 @@ void InitAudioDevice(void)
// Init dummy audio buffers pool for multichannel sound playing
for (int i = 0; i < MAX_AUDIO_BUFFER_POOL_CHANNELS; i++)
{
// WARNING: An empty audioBuffer is created (data = 0)
// WARNING: An empty audio buffer is created (data = 0)
// AudioBuffer data just points to loaded sound data
AUDIO.MultiChannel.pool[i] = LoadAudioBuffer(AUDIO_DEVICE_FORMAT, AUDIO_DEVICE_CHANNELS, AUDIO.System.device.sampleRate, 0, AUDIO_BUFFER_USAGE_STATIC);
}
@ -1428,13 +1430,13 @@ Music LoadMusicStreamFromMemory(const char *fileType, unsigned char* data, int d
#if defined(SUPPORT_FILEFORMAT_MOD)
else if (TextIsEqual(fileExtLower, ".mod"))
{
jar_mod_context_t *ctxMod = RL_MALLOC(sizeof(jar_mod_context_t));
jar_mod_context_t *ctxMod = (jar_mod_context_t *)RL_MALLOC(sizeof(jar_mod_context_t));
int result = 0;
jar_mod_init(ctxMod);
// copy data to allocated memory for default UnloadMusicStream
unsigned char *newData = RL_MALLOC(dataSize);
// Copy data to allocated memory for default UnloadMusicStream
unsigned char *newData = (unsigned char *)RL_MALLOC(dataSize);
int it = dataSize/sizeof(unsigned char);
for (int i = 0; i < it; i++){
newData[i] = data[i];
@ -2073,6 +2075,7 @@ static ma_uint32 ReadAudioBufferFramesInMixingFormat(AudioBuffer *audioBuffer, f
// Sending audio data to device callback function
// This function will be called when miniaudio needs more data
// NOTE: All the mixing takes place here
static void OnSendAudioDataToDevice(ma_device *pDevice, void *pFramesOut, const void *pFramesInput, ma_uint32 frameCount)
{

View file

@ -81,7 +81,7 @@
#include <stdarg.h> // Required for: va_list - Only used by TraceLogCallback
#define RAYLIB_VERSION "3.7.0"
#define RAYLIB_VERSION "3.8-dev"
#if defined(_WIN32)
// Microsoft attibutes to tell compiler that symbols are imported/exported from a .dll
@ -160,13 +160,14 @@
// Temporal hacks to avoid breaking old codebases using
// deprecated raylib implementation or definitions
#define FormatText TextFormat
#define LoadText LoadFileText
#define GetExtension GetFileExtension
#define GetImageData LoadImageColors
#define FILTER_POINT TEXTURE_FILTER_POINT
#define FILTER_BILINEAR TEXTURE_FILTER_BILINEAR
#define MAP_DIFFUSE MATERIAL_MAP_DIFFUSE
#define SpriteFont Font
#define FormatText TextFormat
#define LoadText LoadFileText
#define GetExtension GetFileExtension
#define GetImageData LoadImageColors
#define FILTER_POINT TEXTURE_FILTER_POINT
#define FILTER_BILINEAR TEXTURE_FILTER_BILINEAR
#define MAP_DIFFUSE MATERIAL_MAP_DIFFUSE
#define UNCOMPRESSED_R8G8B8A8 PIXELFORMAT_UNCOMPRESSED_R8G8B8A8
//----------------------------------------------------------------------------------
@ -176,59 +177,58 @@
#if defined(__STDC__) && __STDC_VERSION__ >= 199901L
#include <stdbool.h>
#elif !defined(__cplusplus) && !defined(bool)
typedef enum { false, true } bool;
typedef enum bool { false, true } bool;
#endif
// Vector2 type
// Vector2, 2 components
typedef struct Vector2 {
float x;
float y;
float x; // Vector x component
float y; // Vector y component
} Vector2;
// Vector3 type
// Vector3, 3 components
typedef struct Vector3 {
float x;
float y;
float z;
float x; // Vector x component
float y; // Vector y component
float z; // Vector z component
} Vector3;
// Vector4 type
// Vector4, 4 components
typedef struct Vector4 {
float x;
float y;
float z;
float w;
float x; // Vector x component
float y; // Vector y component
float z; // Vector z component
float w; // Vector w component
} Vector4;
// Quaternion type, same as Vector4
// Quaternion, 4 components (Vector4 alias)
typedef Vector4 Quaternion;
// Matrix type (OpenGL style 4x4 - right handed, column major)
// Matrix, 4x4 components, column major, OpenGL style, right handed
typedef struct Matrix {
float m0, m4, m8, m12;
float m1, m5, m9, m13;
float m2, m6, m10, m14;
float m3, m7, m11, m15;
float m0, m4, m8, m12; // Matrix first row (4 components)
float m1, m5, m9, m13; // Matrix second row (4 components)
float m2, m6, m10, m14; // Matrix third row (4 components)
float m3, m7, m11, m15; // Matrix fourth row (4 components)
} Matrix;
// Color type, RGBA (32bit)
// Color, 4 components, R8G8B8A8 (32bit)
typedef struct Color {
unsigned char r;
unsigned char g;
unsigned char b;
unsigned char a;
unsigned char r; // Color red value
unsigned char g; // Color green value
unsigned char b; // Color blue value
unsigned char a; // Color alpha value
} Color;
// Rectangle type
// Rectangle, 4 components
typedef struct Rectangle {
float x;
float y;
float width;
float height;
float x; // Rectangle top-left corner position x
float y; // Rectangle top-left corner position y
float width; // Rectangle width
float height; // Rectangle height
} Rectangle;
// Image type, bpp always RGBA (32bit)
// NOTE: Data stored in CPU memory (RAM)
// Image, pixel data stored in CPU memory (RAM)
typedef struct Image {
void *data; // Image raw data
int width; // Image base width
@ -237,8 +237,7 @@ typedef struct Image {
int format; // Data format (PixelFormat type)
} Image;
// Texture type
// NOTE: Data stored in GPU memory
// Texture, tex data stored in GPU memory (VRAM)
typedef struct Texture {
unsigned int id; // OpenGL texture id
int width; // Texture base width
@ -247,23 +246,23 @@ typedef struct Texture {
int format; // Data format (PixelFormat type)
} Texture;
// Texture2D type, same as Texture
// Texture2D, same as Texture
typedef Texture Texture2D;
// TextureCubemap type, actually, same as Texture
// TextureCubemap, same as Texture
typedef Texture TextureCubemap;
// RenderTexture type, for texture rendering
// RenderTexture, fbo for texture rendering
typedef struct RenderTexture {
unsigned int id; // OpenGL framebuffer object id
Texture texture; // Color buffer attachment texture
Texture depth; // Depth buffer attachment texture
} RenderTexture;
// RenderTexture2D type, same as RenderTexture
// RenderTexture2D, same as RenderTexture
typedef RenderTexture RenderTexture2D;
// N-Patch layout info
// NPatchInfo, n-patch layout info
typedef struct NPatchInfo {
Rectangle source; // Texture source rectangle
int left; // Left border offset
@ -273,7 +272,7 @@ typedef struct NPatchInfo {
int layout; // Layout of the n-patch: 3x3, 1x3 or 3x1
} NPatchInfo;
// Font character info
// CharInfo, font character info
typedef struct CharInfo {
int value; // Character value (Unicode)
int offsetX; // Character offset X when drawing
@ -282,7 +281,7 @@ typedef struct CharInfo {
Image image; // Character image data
} CharInfo;
// Font type, includes texture and charSet array data
// Font, font texture and CharInfo array data
typedef struct Font {
int baseSize; // Base size (default chars height)
int charsCount; // Number of characters
@ -292,9 +291,7 @@ typedef struct Font {
CharInfo *chars; // Characters info data
} Font;
#define SpriteFont Font // SpriteFont type fallback, defaults to Font
// Camera type, defines a camera position/orientation in 3d space
// Camera, defines position/orientation in 3d space
typedef struct Camera3D {
Vector3 position; // Camera position
Vector3 target; // Camera target it looks-at
@ -305,7 +302,7 @@ typedef struct Camera3D {
typedef Camera3D Camera; // Camera type fallback, defaults to Camera3D
// Camera2D type, defines a 2d camera
// Camera2D, defines position/orientation in 2d space
typedef struct Camera2D {
Vector2 offset; // Camera offset (displacement from target)
Vector2 target; // Camera target (rotation and zoom origin)
@ -313,148 +310,145 @@ typedef struct Camera2D {
float zoom; // Camera zoom (scaling), should be 1.0f by default
} Camera2D;
// Vertex data definning a mesh
// NOTE: Data stored in CPU memory (and GPU)
// Mesh, vertex data and vao/vbo
typedef struct Mesh {
int vertexCount; // Number of vertices stored in arrays
int triangleCount; // Number of triangles stored (indexed or not)
int vertexCount; // Number of vertices stored in arrays
int triangleCount; // Number of triangles stored (indexed or not)
// Default vertex data
float *vertices; // Vertex position (XYZ - 3 components per vertex) (shader-location = 0)
float *texcoords; // Vertex texture coordinates (UV - 2 components per vertex) (shader-location = 1)
float *texcoords2; // Vertex second texture coordinates (useful for lightmaps) (shader-location = 5)
float *normals; // Vertex normals (XYZ - 3 components per vertex) (shader-location = 2)
float *tangents; // Vertex tangents (XYZW - 4 components per vertex) (shader-location = 4)
unsigned char *colors; // Vertex colors (RGBA - 4 components per vertex) (shader-location = 3)
unsigned short *indices;// Vertex indices (in case vertex data comes indexed)
float *vertices; // Vertex position (XYZ - 3 components per vertex) (shader-location = 0)
float *texcoords; // Vertex texture coordinates (UV - 2 components per vertex) (shader-location = 1)
float *texcoords2; // Vertex second texture coordinates (useful for lightmaps) (shader-location = 5)
float *normals; // Vertex normals (XYZ - 3 components per vertex) (shader-location = 2)
float *tangents; // Vertex tangents (XYZW - 4 components per vertex) (shader-location = 4)
unsigned char *colors; // Vertex colors (RGBA - 4 components per vertex) (shader-location = 3)
unsigned short *indices; // Vertex indices (in case vertex data comes indexed)
// Animation vertex data
float *animVertices; // Animated vertex positions (after bones transformations)
float *animNormals; // Animated normals (after bones transformations)
int *boneIds; // Vertex bone ids, up to 4 bones influence by vertex (skinning)
float *boneWeights; // Vertex bone weight, up to 4 bones influence by vertex (skinning)
float *animVertices; // Animated vertex positions (after bones transformations)
float *animNormals; // Animated normals (after bones transformations)
int *boneIds; // Vertex bone ids, up to 4 bones influence by vertex (skinning)
float *boneWeights; // Vertex bone weight, up to 4 bones influence by vertex (skinning)
// OpenGL identifiers
unsigned int vaoId; // OpenGL Vertex Array Object id
unsigned int *vboId; // OpenGL Vertex Buffer Objects id (default vertex data)
unsigned int vaoId; // OpenGL Vertex Array Object id
unsigned int *vboId; // OpenGL Vertex Buffer Objects id (default vertex data)
} Mesh;
// Shader type (generic)
// Shader
typedef struct Shader {
unsigned int id; // Shader program id
int *locs; // Shader locations array (MAX_SHADER_LOCATIONS)
unsigned int id; // Shader program id
int *locs; // Shader locations array (MAX_SHADER_LOCATIONS)
} Shader;
// Material texture map
// MaterialMap
typedef struct MaterialMap {
Texture2D texture; // Material map texture
Color color; // Material map color
float value; // Material map value
Texture2D texture; // Material map texture
Color color; // Material map color
float value; // Material map value
} MaterialMap;
// Material type (generic)
// Material, includes shader and maps
typedef struct Material {
Shader shader; // Material shader
MaterialMap *maps; // Material maps array (MAX_MATERIAL_MAPS)
float params[4]; // Material generic parameters (if required)
Shader shader; // Material shader
MaterialMap *maps; // Material maps array (MAX_MATERIAL_MAPS)
float params[4]; // Material generic parameters (if required)
} Material;
// Transformation properties
// Transform, vectex transformation data
typedef struct Transform {
Vector3 translation; // Translation
Quaternion rotation; // Rotation
Vector3 scale; // Scale
Vector3 translation; // Translation
Quaternion rotation; // Rotation
Vector3 scale; // Scale
} Transform;
// Bone information
// Bone, skeletal animation bone
typedef struct BoneInfo {
char name[32]; // Bone name
int parent; // Bone parent
char name[32]; // Bone name
int parent; // Bone parent
} BoneInfo;
// Model type
// Model, meshes, materials and animation data
typedef struct Model {
Matrix transform; // Local transform matrix
Matrix transform; // Local transform matrix
int meshCount; // Number of meshes
int materialCount; // Number of materials
Mesh *meshes; // Meshes array
Material *materials; // Materials array
int *meshMaterial; // Mesh material number
int meshCount; // Number of meshes
int materialCount; // Number of materials
Mesh *meshes; // Meshes array
Material *materials; // Materials array
int *meshMaterial; // Mesh material number
// Animation data
int boneCount; // Number of bones
BoneInfo *bones; // Bones information (skeleton)
Transform *bindPose; // Bones base transformation (pose)
int boneCount; // Number of bones
BoneInfo *bones; // Bones information (skeleton)
Transform *bindPose; // Bones base transformation (pose)
} Model;
// Model animation
// ModelAnimation
typedef struct ModelAnimation {
int boneCount; // Number of bones
int frameCount; // Number of animation frames
BoneInfo *bones; // Bones information (skeleton)
Transform **framePoses; // Poses array by frame
int boneCount; // Number of bones
int frameCount; // Number of animation frames
BoneInfo *bones; // Bones information (skeleton)
Transform **framePoses; // Poses array by frame
} ModelAnimation;
// Ray type (useful for raycast)
// Ray, ray for raycasting
typedef struct Ray {
Vector3 position; // Ray position (origin)
Vector3 direction; // Ray direction
Vector3 position; // Ray position (origin)
Vector3 direction; // Ray direction
} Ray;
// Raycast hit information
// RayCollision, ray hit information
typedef struct RayCollision {
bool hit; // Did the ray hit something?
float distance; // Distance to nearest hit
Vector3 point; // Point of nearest hit
Vector3 normal; // Surface normal of hit
bool hit; // Did the ray hit something?
float distance; // Distance to nearest hit
Vector3 point; // Point of nearest hit
Vector3 normal; // Surface normal of hit
} RayCollision;
// Bounding box type
// BoundingBox
typedef struct BoundingBox {
Vector3 min; // Minimum vertex box-corner
Vector3 max; // Maximum vertex box-corner
Vector3 min; // Minimum vertex box-corner
Vector3 max; // Maximum vertex box-corner
} BoundingBox;
// Wave type, defines audio wave data
// Wave, audio wave data
typedef struct Wave {
unsigned int sampleCount; // Total number of samples (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
unsigned int sampleCount; // Total number of samples (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;
// Audio stream type
// NOTE: Useful to create custom audio streams not bound to a specific file
// AudioStream, custom audio stream
typedef struct AudioStream {
rAudioBuffer *buffer; // Pointer to internal data used by the audio system
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)
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 source type
// Sound
typedef struct Sound {
AudioStream stream; // Audio stream
unsigned int sampleCount; // Total number of samples
AudioStream stream; // Audio stream
unsigned int sampleCount; // Total number of samples
} Sound;
// Music stream type (audio file streaming from memory)
// NOTE: Anything longer than ~10 seconds should be streamed
// Music, audio stream, anything longer than ~10 seconds should be streamed
typedef struct Music {
AudioStream stream; // Audio stream
unsigned int sampleCount; // Total number of samples
bool looping; // Music looping enable
AudioStream stream; // Audio stream
unsigned int sampleCount; // Total number of samples
bool looping; // Music looping enable
int ctxType; // Type of music context (audio filetype)
void *ctxData; // Audio context data, depends on type
int ctxType; // Type of music context (audio filetype)
void *ctxData; // Audio context data, depends on type
} Music;
// Head-Mounted-Display device parameters
// VrDeviceInfo, Head-Mounted-Display device parameters
typedef struct VrDeviceInfo {
int hResolution; // Horizontal resolution in pixels
int vResolution; // Vertical resolution in pixels
@ -468,7 +462,7 @@ typedef struct VrDeviceInfo {
float chromaAbCorrection[4]; // Chromatic aberration correction parameters
} VrDeviceInfo;
// VR Stereo rendering configuration for simulator
// VrStereoConfig, VR stereo rendering configuration for simulator
typedef struct VrStereoConfig {
Matrix projection[2]; // VR projection matrices (per eye)
Matrix viewOffset[2]; // VR view offset matrices (per eye)
@ -504,14 +498,15 @@ typedef enum {
} ConfigFlags;
// Trace log level
// NOTE: Organized by priority level
typedef enum {
LOG_ALL = 0, // Display all logs
LOG_TRACE,
LOG_DEBUG,
LOG_INFO,
LOG_WARNING,
LOG_ERROR,
LOG_FATAL,
LOG_TRACE, // Trace logging, intended for internal use only
LOG_DEBUG, // Debug logging, used for internal debugging, it should be disabled on release builds
LOG_INFO, // Info logging, used for program execution info
LOG_WARNING, // Warning logging, used on recoverable failures
LOG_ERROR, // Error logging, used on unrecoverable failures
LOG_FATAL, // Fatal logging, used to abort program: exit(EXIT_FAILURE)
LOG_NONE // Disable logging
} TraceLogLevel;
@ -871,7 +866,7 @@ typedef enum {
GESTURE_SWIPE_DOWN = 128,
GESTURE_PINCH_IN = 256,
GESTURE_PINCH_OUT = 512
} Gestures;
} Gesture;
// Camera system modes
typedef enum {
@ -898,9 +893,9 @@ typedef enum {
// Callbacks to hook some internal functions
// WARNING: This callbacks are intended for advance users
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 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 char *(*LoadFileTextCallback)(const char *fileName); // FileIO: Load text data
typedef bool (*SaveFileTextCallback)(const char *fileName, char *text); // FileIO: Save text data
@ -970,15 +965,15 @@ RLAPI bool IsCursorOnScreen(void); // Check if cu
RLAPI void ClearBackground(Color color); // Set background color (framebuffer clear color)
RLAPI void BeginDrawing(void); // Setup canvas (framebuffer) to start drawing
RLAPI void EndDrawing(void); // End canvas drawing and swap buffers (double buffering)
RLAPI void BeginMode2D(Camera2D camera); // Initialize 2D mode with custom camera (2D)
RLAPI void BeginMode2D(Camera2D camera); // Begin 2D mode with custom camera (2D)
RLAPI void EndMode2D(void); // Ends 2D mode with custom camera
RLAPI void BeginMode3D(Camera3D camera); // Initializes 3D mode with custom camera (3D)
RLAPI void BeginMode3D(Camera3D camera); // Begin 3D mode with custom camera (3D)
RLAPI void EndMode3D(void); // Ends 3D mode and returns to default 2D orthographic mode
RLAPI void BeginTextureMode(RenderTexture2D target); // Initializes render texture for drawing
RLAPI void BeginTextureMode(RenderTexture2D target); // Begin drawing to render texture
RLAPI void EndTextureMode(void); // Ends drawing to render texture
RLAPI void BeginShaderMode(Shader shader); // Begin custom shader drawing
RLAPI void EndShaderMode(void); // End custom shader drawing (use default shader)
RLAPI void BeginBlendMode(int mode); // Begin blending mode (alpha, additive, multiplied)
RLAPI void BeginBlendMode(int mode); // Begin blending mode (alpha, additive, multiplied, subtract, custom)
RLAPI void EndBlendMode(void); // End blending mode (reset to default: alpha blending)
RLAPI void BeginScissorMode(int x, int y, int width, int height); // Begin scissor mode (define screen area for following drawing)
RLAPI void EndScissorMode(void); // End scissor mode
@ -1021,7 +1016,7 @@ RLAPI int GetRandomValue(int min, int max); // Returns a r
RLAPI void TakeScreenshot(const char *fileName); // Takes a screenshot of current screen (filename extension defines format)
RLAPI void SetConfigFlags(unsigned int flags); // Setup init configuration flags (view FLAGS)
RLAPI void TraceLog(int logLevel, const char *text, ...); // Show trace log messages (LOG_DEBUG, LOG_INFO, LOG_WARNING, LOG_ERROR)
RLAPI void TraceLog(int logLevel, const char *text, ...); // Show trace log messages (LOG_DEBUG, LOG_INFO, LOG_WARNING, LOG_ERROR...)
RLAPI void SetTraceLogLevel(int logLevel); // Set the current threshold (minimum) log level
RLAPI void *MemAlloc(int size); // Internal memory allocator
RLAPI void *MemRealloc(void *ptr, int size); // Internal memory reallocator
@ -1040,12 +1035,12 @@ RLAPI unsigned char *LoadFileData(const char *fileName, unsigned int *bytesRead)
RLAPI void UnloadFileData(unsigned char *data); // Unload file data allocated by LoadFileData()
RLAPI bool SaveFileData(const char *fileName, void *data, unsigned int bytesToWrite); // Save data to file from byte array (write), returns true on success
RLAPI char *LoadFileText(const char *fileName); // Load text data from file (read), returns a '\0' terminated string
RLAPI void UnloadFileText(unsigned char *text); // Unload file text data allocated by LoadFileText()
RLAPI void UnloadFileText(char *text); // Unload file text data allocated by LoadFileText()
RLAPI bool SaveFileText(const char *fileName, char *text); // Save text data to file (write), string must be '\0' terminated, returns true on success
RLAPI bool FileExists(const char *fileName); // Check if file exists
RLAPI bool DirectoryExists(const char *dirPath); // Check if a directory path exists
RLAPI bool IsFileExtension(const char *fileName, const char *ext);// Check file extension (including point: .png, .wav)
RLAPI const char *GetFileExtension(const char *fileName); // Get pointer to extension for a filename string (includes dot: ".png")
RLAPI const char *GetFileExtension(const char *fileName); // Get pointer to extension for a filename string (includes dot: '.png')
RLAPI const char *GetFileName(const char *filePath); // Get pointer to filename for a path string
RLAPI const char *GetFileNameWithoutExt(const char *filePath); // Get filename string without extension (uses static string)
RLAPI const char *GetDirectoryPath(const char *filePath); // Get full path for a given fileName with path (uses static string)
@ -1143,7 +1138,7 @@ RLAPI void SetCameraMoveControls(int keyFront, int keyBack, int keyRight, int ke
// Set texture and rectangle to be used on shapes drawing
// NOTE: It can be useful when using basic shapes and one single font,
// defining a font char white rectangle would allow drawing everything in a single draw call
RLAPI void SetShapesTexture(Texture2D texture, Rectangle source);
RLAPI void SetShapesTexture(Texture2D texture, Rectangle source); // Set texture and rectangle to be used on shapes drawing
// Basic shapes drawing functions
RLAPI void DrawPixel(int posX, int posY, Color color); // Draw a pixel
@ -1202,7 +1197,7 @@ RLAPI Rectangle GetCollisionRec(Rectangle rec1, Rectangle rec2);
RLAPI Image LoadImage(const char *fileName); // Load image from file into CPU memory (RAM)
RLAPI Image LoadImageRaw(const char *fileName, int width, int height, int format, int headerSize); // Load image from RAW file data
RLAPI Image LoadImageAnim(const char *fileName, int *frames); // Load image sequence from file (frames appended to image.data)
RLAPI Image LoadImageFromMemory(const char *fileType, const unsigned char *fileData, int dataSize); // Load image from memory buffer, fileType refers to extension: i.e. ".png"
RLAPI Image LoadImageFromMemory(const char *fileType, const unsigned char *fileData, int dataSize); // Load image from memory buffer, fileType refers to extension: i.e. '.png'
RLAPI void UnloadImage(Image image); // Unload image from CPU memory (RAM)
RLAPI bool ExportImage(Image image, const char *fileName); // Export image data to file, returns true on success
RLAPI bool ExportImageAsCode(Image image, const char *fileName); // Export image as code file defining an array of bytes, returns true on success
@ -1232,7 +1227,7 @@ RLAPI void ImageAlphaPremultiply(Image *image);
RLAPI void ImageResize(Image *image, int newWidth, int newHeight); // Resize image (Bicubic scaling algorithm)
RLAPI void ImageResizeNN(Image *image, int newWidth,int newHeight); // Resize image (Nearest-Neighbor scaling algorithm)
RLAPI void ImageResizeCanvas(Image *image, int newWidth, int newHeight, int offsetX, int offsetY, Color fill); // Resize canvas and fill with color
RLAPI void ImageMipmaps(Image *image); // Generate all mipmap levels for a provided image
RLAPI void ImageMipmaps(Image *image); // Compute all mipmap levels for a provided image
RLAPI void ImageDither(Image *image, int rBpp, int gBpp, int bBpp, int aBpp); // Dither image data to 16bpp or lower (Floyd-Steinberg dithering)
RLAPI void ImageFlipVertical(Image *image); // Flip image vertically
RLAPI void ImageFlipHorizontal(Image *image); // Flip image horizontally
@ -1319,7 +1314,7 @@ RLAPI Font GetFontDefault(void);
RLAPI Font LoadFont(const char *fileName); // Load font from file into GPU memory (VRAM)
RLAPI Font LoadFontEx(const char *fileName, int fontSize, int *fontChars, int charsCount); // Load font from file with extended parameters
RLAPI Font LoadFontFromImage(Image image, Color key, int firstChar); // Load font from Image (XNA style)
RLAPI Font LoadFontFromMemory(const char *fileType, const unsigned char *fileData, int dataSize, int fontSize, int *fontChars, int charsCount); // Load font from memory buffer, fileType refers to extension: i.e. ".ttf"
RLAPI Font LoadFontFromMemory(const char *fileType, const unsigned char *fileData, int dataSize, int fontSize, int *fontChars, int charsCount); // Load font from memory buffer, fileType refers to extension: i.e. '.ttf'
RLAPI CharInfo *LoadFontData(const unsigned char *fileData, int dataSize, int fontSize, int *fontChars, int charsCount, int type); // Load font data for further use
RLAPI Image GenImageFontAtlas(const CharInfo *chars, Rectangle **recs, int charsCount, int fontSize, int padding, int packMethod); // Generate image font atlas using chars info
RLAPI void UnloadFontData(CharInfo *chars, int charsCount); // Unload font chars info data (RAM)
@ -1330,8 +1325,7 @@ RLAPI void DrawFPS(int posX, int posY);
RLAPI void DrawText(const char *text, int posX, int posY, int fontSize, Color color); // Draw text (using default font)
RLAPI void DrawTextEx(Font font, const char *text, Vector2 position, float fontSize, float spacing, Color tint); // Draw text using font and additional parameters
RLAPI void DrawTextRec(Font font, const char *text, Rectangle rec, float fontSize, float spacing, bool wordWrap, Color tint); // Draw text using font inside rectangle limits
RLAPI void DrawTextRecEx(Font font, const char *text, Rectangle rec, float fontSize, float spacing, bool wordWrap, Color tint,
int selectStart, int selectLength, Color selectTint, Color selectBackTint); // Draw text using font inside rectangle limits with support for text selection
RLAPI void DrawTextRecEx(Font font, const char *text, Rectangle rec, float fontSize, float spacing, bool wordWrap, Color tint, int selectStart, int selectLength, Color selectTint, Color selectBackTint); // Draw text using font inside rectangle limits with support for text selection
RLAPI void DrawTextCodepoint(Font font, int codepoint, Vector2 position, float fontSize, Color tint); // Draw one character (codepoint)
// Text misc. functions
@ -1433,7 +1427,7 @@ RLAPI Mesh GenMeshHeightmap(Image heightmap, Vector3 size);
RLAPI Mesh GenMeshCubicmap(Image cubicmap, Vector3 cubeSize); // Generate cubes-based map mesh from image data
// Mesh manipulation functions
RLAPI BoundingBox GetMeshBoundingBox(Mesh mesh); // Compute mesh bounding box limits
RLAPI BoundingBox GetMeshBoundingBox(Mesh mesh); // Compute mesh bounding box limits
RLAPI void MeshTangents(Mesh *mesh); // Compute mesh tangents
RLAPI void MeshBinormals(Mesh *mesh); // Compute mesh binormals
@ -1470,7 +1464,7 @@ RLAPI void SetMasterVolume(float volume); // Set mas
// Wave/Sound loading/unloading functions
RLAPI Wave LoadWave(const char *fileName); // Load wave data from file
RLAPI Wave LoadWaveFromMemory(const char *fileType, const unsigned char *fileData, int dataSize); // Load wave from memory buffer, fileType refers to extension: i.e. ".wav"
RLAPI Wave LoadWaveFromMemory(const char *fileType, const unsigned char *fileData, int dataSize); // Load wave from memory buffer, fileType refers to extension: i.e. '.wav'
RLAPI Sound LoadSound(const char *fileName); // Load sound from file
RLAPI Sound LoadSoundFromWave(Wave wave); // Load sound from wave data
RLAPI void UpdateSound(Sound sound, const void *data, int samplesCount);// Update sound buffer with new data

View file

@ -326,7 +326,7 @@ RMDEF Vector2 Vector2MoveTowards(Vector2 v, Vector2 target, float maxDistance)
float dy = target.y - v.y;
float value = (dx*dx) + (dy*dy);
if ((value == 0) || ((maxDistance >= 0) && (value <= maxDistance*maxDistance))) result = target;
if ((value == 0) || ((maxDistance >= 0) && (value <= maxDistance * maxDistance))) return target;
float dist = sqrtf(value);
@ -1389,23 +1389,28 @@ RMDEF Quaternion QuaternionFromMatrix(Matrix mat)
RMDEF Matrix QuaternionToMatrix(Quaternion q)
{
Matrix result = MatrixIdentity();
float a2 = q.x*q.x;
float b2 = q.y*q.y;
float c2 = q.z*q.z;
float ac = q.x*q.z;
float ab = q.x*q.y;
float bc = q.y*q.z;
float ad = q.w*q.x;
float bd = q.w*q.y;
float cd = q.w*q.z;
float a2 = 2*(q.x*q.x), b2=2*(q.y*q.y), c2=2*(q.z*q.z); //, d2=2*(q.w*q.w);
result.m0 = 1 - 2*(b2 + c2);
result.m1 = 2*(ab + cd);
result.m2 = 2*(ac - bd);
float ab = 2*(q.x*q.y), ac=2*(q.x*q.z), bc=2*(q.y*q.z);
float ad = 2*(q.x*q.w), bd=2*(q.y*q.w), cd=2*(q.z*q.w);
result.m4 = 2*(ab - cd);
result.m5 = 1 - 2*(a2 + c2);
result.m6 = 2*(bc + ad);
result.m0 = 1 - b2 - c2;
result.m1 = ab - cd;
result.m2 = ac + bd;
result.m4 = ab + cd;
result.m5 = 1 - a2 - c2;
result.m6 = bc - ad;
result.m8 = ac - bd;
result.m9 = bc + ad;
result.m10 = 1 - a2 - b2;
result.m8 = 2*(ac + bd);
result.m9 = 2*(bc - ad);
result.m10 = 1 - 2*(a2 + b2);
return result;
}

View file

@ -329,16 +329,17 @@ typedef enum {
int *locs; // Shader locations array (MAX_SHADER_LOCATIONS)
} Shader;
// TraceLog message types
// Trace log level
// NOTE: Organized by priority level
typedef enum {
LOG_ALL,
LOG_TRACE,
LOG_DEBUG,
LOG_INFO,
LOG_WARNING,
LOG_ERROR,
LOG_FATAL,
LOG_NONE
LOG_ALL = 0, // Display all logs
LOG_TRACE, // Trace logging, intended for internal use only
LOG_DEBUG, // Debug logging, used for internal debugging, it should be disabled on release builds
LOG_INFO, // Info logging, used for program execution info
LOG_WARNING, // Warning logging, used on recoverable failures
LOG_ERROR, // Error logging, used on unrecoverable failures
LOG_FATAL, // Fatal logging, used to abort program: exit(EXIT_FAILURE)
LOG_NONE // Disable logging
} TraceLogLevel;
// Texture formats (support depends on OpenGL version)
@ -1685,7 +1686,7 @@ void rlLoadExtensions(void *loader)
#if defined(SUPPORT_GL_DETAILS_INFO)
// Get supported extensions list
// WARNING: glGetStringi() not available on OpenGL 2.1
char **extList = RL_MALLOC(sizeof(char *)*numExt);
char **extList = RL_MALLOC(numExt*sizeof(char *));
TRACELOG(LOG_INFO, "GL: OpenGL extensions:");
for (int i = 0; i < numExt; i++)
{
@ -1966,7 +1967,7 @@ RenderBatch rlLoadRenderBatch(int numBuffers, int bufferElements)
#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)
// Initialize CPU (RAM) vertex buffers (position, texcoord, color data and indexes)
//--------------------------------------------------------------------------------------------
batch.vertexBuffer = (VertexBuffer *)RL_MALLOC(sizeof(VertexBuffer)*numBuffers);
batch.vertexBuffer = (VertexBuffer *)RL_MALLOC(numBuffers*sizeof(VertexBuffer));
for (int i = 0; i < numBuffers; i++)
{

View file

@ -1272,7 +1272,7 @@ const char *TextSubtext(const char *text, int position, int length)
// Replace text string
// REQUIRES: strstr(), strncpy(), strcpy()
// WARNING: Internally allocated memory must be freed by the user (if return != NULL)
// WARNING: Returned buffer must be freed by the user (if return != NULL)
char *TextReplace(char *text, const char *replace, const char *by)
{
// Sanity checks and initialization
@ -1297,14 +1297,14 @@ char *TextReplace(char *text, const char *replace, const char *by)
for (count = 0; (temp = strstr(insertPoint, replace)); count++) insertPoint = temp + replaceLen;
// Allocate returning string and point temp to it
temp = result = RL_MALLOC(TextLength(text) + (byLen - replaceLen)*count + 1);
temp = result = (char *)RL_MALLOC(TextLength(text) + (byLen - replaceLen)*count + 1);
if (!result) return NULL; // Memory could not be allocated
// First time through the loop, all the variable are set correctly from here on,
// temp points to the end of the result string
// insertPoint points to the next occurrence of replace in text
// text points to the remainder of text after "end of replace"
// - 'temp' points to the end of the result string
// - 'insertPoint' points to the next occurrence of replace in text
// - 'text' points to the remainder of text after "end of replace"
while (count--)
{
insertPoint = strstr(text, replace);
@ -1865,7 +1865,7 @@ static Font LoadBMFont(const char *fileName)
}
UnloadImage(imFont);
RL_FREE(fileText);
UnloadFileText(fileText);
if (font.texture.id == 0)
{

View file

@ -67,6 +67,7 @@
#include <stdlib.h> // Required for: malloc(), free()
#include <string.h> // Required for: strlen() [Used in ImageTextEx()]
#include <math.h> // Required for: fabsf()
#include <stdio.h> // Required for: sprintf() [Used in ExportImageAsCode()]
#include "utils.h" // Required for: fopen() Android mapping
@ -122,7 +123,7 @@
// NOTE: Used to read image data (multiple formats support)
#endif
#if (defined(SUPPORT_IMAGE_EXPORT) || defined(SUPPORT_COMPRESSION_API))
#if defined(SUPPORT_IMAGE_EXPORT)
#define STBIW_MALLOC RL_MALLOC
#define STBIW_FREE RL_FREE
#define STBIW_REALLOC RL_REALLOC
@ -459,6 +460,8 @@ bool ExportImageAsCode(Image image, const char *fileName)
{
bool success = false;
#if defined(SUPPORT_IMAGE_EXPORT)
#ifndef TEXT_BYTES_PER_LINE
#define TEXT_BYTES_PER_LINE 20
#endif
@ -500,6 +503,11 @@ bool ExportImageAsCode(Image image, const char *fileName)
success = SaveFileText(fileName, txtData);
RL_FREE(txtData);
#endif // SUPPORT_IMAGE_EXPORT
if (success != 0) TRACELOG(LOG_INFO, "FILEIO: [%s] Image exported successfully", fileName);
else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to export image", fileName);
return success;
}
@ -1354,7 +1362,7 @@ void ImageResize(Image *image, int newWidth, int newHeight)
if (fastPath)
{
int bytesPerPixel = GetPixelDataSize(1, 1, image->format);
unsigned char *output = RL_MALLOC(newWidth*newHeight*bytesPerPixel);
unsigned char *output = (unsigned char *)RL_MALLOC(newWidth*newHeight*bytesPerPixel);
switch (image->format)
{

View file

@ -155,7 +155,7 @@ void TraceLog(int logType, const char *text, ...)
va_end(args);
if (logType == LOG_ERROR) exit(1); // If error, exit program
if (logType == LOG_FATAL) exit(EXIT_FAILURE); // If fatal logging, exit program
#endif // SUPPORT_TRACELOG
}
@ -325,7 +325,7 @@ char *LoadFileText(const char *fileName)
}
// Unload file text data allocated by LoadFileText()
void UnloadFileText(unsigned char *text)
void UnloadFileText(char *text)
{
RL_FREE(text);
}

View file

@ -5,7 +5,7 @@
*
* LICENSE: zlib/libpng
*
* Copyright (c) 2020-2020 Reece Mackie (@Rover656)
* Copyright (c) 2020-2021 Reece Mackie (@Rover656)
*
* 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.