From b6021f11c2f89411d74456034c98f3073c4233e5 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Thu, 3 Mar 2016 16:15:25 +0000 Subject: [PATCH 01/15] Update gb.h - v0.02 Minor fixes to work with older versions of MSVC --- gb.h | 95 +++++++++++++++++++++++++++++++++++++----------------------- 1 file changed, 58 insertions(+), 37 deletions(-) diff --git a/gb.h b/gb.h index 96a686f..d70c8cc 100644 --- a/gb.h +++ b/gb.h @@ -1,4 +1,4 @@ -// gb.h - v0.01 - public domain C helper library - no warranty implied; use at your own risk +// gb.h - v0.02 - public domain C helper library - no warranty implied; use at your own risk // (Experimental) A C helper library geared towards game development /* @@ -33,6 +33,7 @@ TODO /* Version History: + 0.02 - Minor fixes 0.01 - Initial Version */ @@ -72,13 +73,14 @@ extern "C" { #ifndef GB_ASSERT #include #define GB_ASSERT(cond) assert(cond) +#define GB_ASSERT_MSG(cond, msg) assert((cond) && (msg)) #endif -#define GB_STATIC_ASSERT(cond, msg) typedef char gb__static_assertion_##msg[(!!(cond))*2-1] +#define GB_STATIC_ASSERT3(cond, msg) typedef char gb__static_assertion_##msg[(!!(cond))*2-1] // NOTE(bill): Token pasting madness -#define GB_COMPILE_TIME_ASSERT3(cond, line) GB_STATIC_ASSERT(cond, static_assertion_at_line_##line) -#define GB_COMPILE_TIME_ASSERT2(cond, line) GB_COMPILE_TIME_ASSERT3(cond, line) -#define GB_COMPILE_TIME_ASSERT(cond) GB_COMPILE_TIME_ASSERT2(cond, __LINE__) +#define GB_STATIC_ASSERT2(cond, line) GB_STATIC_ASSERT3(cond, static_assertion_at_line_##line) +#define GB_STATIC_ASSERT1(cond, line) GB_STATIC_ASSERT2(cond, line) +#define GB_STATIC_ASSERT(cond) GB_STATIC_ASSERT1(cond, __LINE__) #if !defined(GB_NO_STDIO) && defined(_MSC_VER) @@ -136,26 +138,37 @@ extern "C" { typedef int64_t s64; #endif -GB_COMPILE_TIME_ASSERT(sizeof(s8) == 1); -GB_COMPILE_TIME_ASSERT(sizeof(s16) == 2); -GB_COMPILE_TIME_ASSERT(sizeof(s32) == 4); -GB_COMPILE_TIME_ASSERT(sizeof(s64) == 8); +GB_STATIC_ASSERT(sizeof(s8) == 1); +GB_STATIC_ASSERT(sizeof(s16) == 2); +GB_STATIC_ASSERT(sizeof(s32) == 4); +GB_STATIC_ASSERT(sizeof(s64) == 8); typedef size_t usize; typedef uintptr_t uintptr; +typedef intptr_t intptr; typedef float f32; typedef double f64; -#include // NOTE(bill): To get false/true +#if defined(_MSC_VER) && _MSC_VER < 1900 + #ifndef false + #define false 0 + #endif + + #ifndef true + #define true 1 + #endif +#else + #include // NOTE(bill): To get false/true +#endif // Boolean Types typedef s8 b8; typedef s32 b32; - +#ifndef U8_MIN #define U8_MIN 0u #define U8_MAX 0xffu #define S8_MIN (-0x7f - 1) @@ -175,7 +188,7 @@ typedef s32 b32; #define U64_MAX 0xffffffffffffffffull #define S64_MIN (-0x7fffffffffffffffll - 1) #define S64_MAX 0x7fffffffffffffffll - +#endif @@ -185,7 +198,7 @@ typedef s32 b32; #endif // NOTE(bill): Allows for easy grep of casts -// NOTE(bill): Still not as type safe as C++ static_cast, reinterpret_cast, const_cast +// NOTE(bill): Still not as type safe as C++ static_cast, reinterpret_cast, and const_cast, but I don't need them #ifndef cast #define cast(x) (x) #endif @@ -271,7 +284,10 @@ typedef enum gb_Allocation_Type GB_ALLOCATION_TYPE_RESIZE, } gb_Allocation_Type; + +#ifndef GB_ALLOCATOR_PROCEDURE #define GB_ALLOCATOR_PROCEDURE(name) void *name(void *allocator_data, gb_Allocation_Type type, usize size, usize alignment, void *old_memory, usize old_size, u32 options) +#endif typedef GB_ALLOCATOR_PROCEDURE(gb_Allocator_Procedure); typedef struct gb_Allocator @@ -471,27 +487,30 @@ gb_init_pool(gb_Pool *pool, gb_Allocator backing, usize num_blocks, usize block_ void gb_init_pool_align(gb_Pool *pool, gb_Allocator backing, usize num_blocks, usize block_size, usize block_align) { - memset(pool, 0, sizeof(gb_Pool)); + usize actual_block_size, pool_size, block_index; + u8 *data, *curr; pool->backing = backing; pool->block_size = block_size; pool->block_align = block_align; - usize actual_block_size = block_size + block_align; - usize pool_size = num_blocks * actual_block_size; + actual_block_size = block_size + block_align; + pool_size = num_blocks * actual_block_size; - u8 *data = cast(u8 *)gb_alloc_align(backing, pool_size, block_align); + data = cast(u8 *)gb_alloc_align(backing, pool_size, block_align); // Init intrusive freelist - u8 *curr = data; - for (usize block_index = 0; block_index < num_blocks-1; block_index++) { + curr = data; + for (block_index = 0; block_index < num_blocks-1; block_index++) { uintptr *next = cast(uintptr *)curr; *next = cast(uintptr)curr + actual_block_size; curr += actual_block_size; } - uintptr *end = cast(uintptr*)curr; - *end = cast(uintptr)NULL; + { + uintptr *end = cast(uintptr*)curr; + *end = cast(uintptr)NULL; + } pool->physical_start = data; pool->free_list = data; @@ -646,22 +665,23 @@ gb_string_make_length(gb_Allocator a, void const *init_str, gb_String_Size num_b gb_String_Size header_size = sizeof(gb_String_Header); void *ptr = gb_alloc(a, header_size + num_bytes + 1); - gb_String str; - gb_String_Header *header; + if (ptr == NULL) { + return NULL; + } else { + gb_String str = cast(char *)ptr + header_size; + gb_String_Header *header = GB_STRING_HEADER(str); + // Zero all data first + if (!init_str) gb_zero_size(ptr, header_size + num_bytes + 1); + header->allocator = a; + header->length = num_bytes; + header->capacity = num_bytes; - if (!init_str) gb_zero_size(ptr, header_size + num_bytes + 1); - if (ptr == NULL) return NULL; + if (num_bytes && init_str) + memcpy(str, init_str, num_bytes); + str[num_bytes] = '\0'; // Just in case - str = cast(char *)ptr + header_size; - header = GB_STRING_HEADER(str); - header->allocator = a; - header->length = num_bytes; - header->capacity = num_bytes; - if (num_bytes && init_str) - memcpy(str, init_str, num_bytes); - str[num_bytes] = '\0'; - - return str; + return str; + } } gb_inline void @@ -746,6 +766,7 @@ gb__string_realloc(gb_Allocator a, void *ptr, gb_String_Size old_size, gb_String if (old_size == new_size) { return ptr; } else { + // TODO(bill): Use gb_resize here?? void *new_ptr = gb_alloc(a, new_size); if (!new_ptr) return NULL; @@ -785,8 +806,8 @@ gb_string_make_space_for(gb_String str, gb_String_Size add_len) gb_inline gb_String_Size gb_string_allocation_size(gb_String const str) { - gb_String_Size cap = gb_string_capacity(str); - return sizeof(gb_String_Header) + cap; + gb_String_Size result = gb_string_capacity(str) + cast(gb_String_Size)sizeof(gb_String_Header); + return result; } From f4bed43039010fd21c728952c1f856707444832f Mon Sep 17 00:00:00 2001 From: gingerBill Date: Fri, 8 Apr 2016 21:40:22 +0100 Subject: [PATCH 02/15] gb_math.h - v0.04 - Namespace everything with gb --- gb_math.h | 1824 +++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 1484 insertions(+), 340 deletions(-) diff --git a/gb_math.h b/gb_math.h index 9158181..09bf18e 100644 --- a/gb_math.h +++ b/gb_math.h @@ -1,8 +1,10 @@ -// gb_math.h - v0.03 - public domain C math library - no warranty implied; use at your own risk +// gb_math.h - v0.04 - public domain C math library - no warranty implied; use at your own risk // A C math library geared towards game development +// use '#define GB_MATH_IMPLEMENTATION' before including to create the implementation in _ONE_ file /* Version History: + 0.04 - Namespace everything with gb 0.03 - Complete Replacement 0.01 - Initial Version @@ -21,380 +23,1049 @@ CONTENTS - Vec(2,3,4) - Mat(2,3,4) - Float(2,3,4) + - gbQuat - Rect(2,3) - Aabb(2,3) + - gb_half (16-bit floating point) (storage only) - Operations - Functions - Type Functions - Random - -TODO - - Complex - - Quaternion - - More Math Functions + - Hash */ #ifndef GB_MATH_INCLUDE_GB_MATH_H #define GB_MATH_INCLUDE_GB_MATH_H #include +#include +#include +#include -#ifdef GB_MATH_STATIC -#define GB_MATH_DEF static -#else -#define GB_MATH_DEF extern +#ifndef GB_MATH_DEF + #ifdef GB_MATH_STATIC + #define GB_MATH_DEF static + #else + #define GB_MATH_DEF extern + #endif #endif -typedef union Vec2 -{ +typedef union gbVec2 { struct { float x, y; }; float e[2]; -} Vec2; +} gbVec2; -typedef union Vec3 -{ +typedef union gbVec3 { struct { float x, y, z; }; struct { float r, g, b; }; - Vec2 xy; + gbVec2 xy; float e[2]; -} Vec3; +} gbVec3; -typedef union Vec4 -{ +typedef union gbVec4 { struct { float x, y, z, w; }; struct { float r, g, b, a; }; - struct { Vec2 xy, zw; }; - Vec3 xyz; - Vec3 rgb; + struct { gbVec2 xy, zw; }; + gbVec3 xyz; + gbVec3 rgb; float e[4]; -} Vec4; +} gbVec4; -typedef union Mat2 -{ - struct { Vec2 x, y; }; - Vec4 col[2]; +typedef union gbMat2 { + struct { gbVec2 x, y; }; + gbVec4 col[2]; float e[4]; -} Mat2; +} gbMat2; -typedef union Mat3 -{ - struct { Vec3 x, y, z; }; - Vec4 col[3]; +typedef union gbMat3 { + struct { gbVec3 x, y, z; }; + gbVec3 col[3]; float e[9]; -} Mat3; +} gbMat3; -typedef union Mat4 -{ - struct { Vec4 x, y, z, w; }; - Vec4 col[4]; +typedef union gbMat4 { + struct { gbVec4 x, y, z, w; }; + gbVec4 col[4]; float e[16]; -} Mat4; +} gbMat4; + + +typedef union gbQuat { + struct { float x, y, z, w; }; + gbVec4 xyzw; + gbVec3 xyz; + float e[4]; +} gbQuat; - -typedef float Float2[2]; -typedef float Float3[3]; -typedef float Float4[4]; +typedef float gbFloat2[2]; +typedef float gbFloat3[3]; +typedef float gbFloat4[4]; -typedef struct Rect2 { Vec2 pos, dim; } Rect2; -typedef struct Rect3 { Vec3 pos, dim; } Rect3; +typedef struct gbRect2 { gbVec2 pos, dim; } gbRect2; +typedef struct gbRect3 { gbVec3 pos, dim; } gbRect3; -typedef struct Aabb2 { Vec2 center, half_size; } Aabb2; -typedef struct Aabb3 { Vec3 center, half_size; } Aabb3; +typedef struct gbAabb2 { gbVec2 centre, half_size; } gbAabb2; +typedef struct gbAabb3 { gbVec3 centre, half_size; } gbAabb3; #if defined(_MSC_VER) - typedef unsigned __int8 gb_math_u8; typedef unsigned __int32 gb_math_u32; typedef unsigned __int64 gb_math_u64; #else - #include - typedef uint8_t gb_math_u8; - typedef uint32_t gb_math_u32; - typedef uint64_t gb_math_u64; + #if defined(GB_USE_STDINT) + #include + typedef uint32_t gb_math_u32; + typedef uint64_t gb_math_u64; + #else + typedef unsigned int gb_math_u32; + typedef unsigned long long gb_math_u64; + #endif #endif +typedef short gb_half; + + // Constants -#define MATH_TAU 6.28318530718f +#ifndef GB_MATH_CONSTANTS +#define GB_MATH_CONSTANTS + #define GB_MATH_EPSILON 1.19209290e-7f + #define GB_MATH_ZERO 0.0f + #define GB_MATH_ONE 1.0f + #define GB_MATH_TWO_THIRDS 0.666666666666666666666666666666666666667f + + #define GB_MATH_TAU 6.28318530717958647692528676655900576f + #define GB_MATH_PI 3.14159265358979323846264338327950288f + #define GB_MATH_ONE_OVER_TAU 0.636619772367581343075535053490057448f + #define GB_MATH_ONE_OVER_PI 0.159154943091895335768883763372514362f + + #define GB_MATH_E 2.71828182845904523536f + #define GB_MATH_SQRT_TWO 1.41421356237309504880168872420969808f + #define GB_MATH_SQRT_THREE 1.73205080756887729352744634150587236f + #define GB_MATH_SQRT_FIVE 2.23606797749978969640917366873127623f + + #define GB_LOG_TWO 0.693147180559945309417232121458176568f + #define GB_LOG_TEN 2.30258509299404568401799145468436421f +#endif + #if defined(__cplusplus) extern "C" { #endif -// Vector +// Basic +GB_MATH_DEF float gb_clamp(float a, float lower, float upper); +GB_MATH_DEF float gb_clamp01(float a); -GB_MATH_DEF Vec2 vec2_zero(void); -GB_MATH_DEF Vec2 vec2(float x, float y); -GB_MATH_DEF Vec2 vec2v(float x[2]); +GB_MATH_DEF float gb_as_radians(float degrees); +GB_MATH_DEF float gb_as_degrees(float radians); -GB_MATH_DEF Vec3 vec3_zero(void); -GB_MATH_DEF Vec3 vec3(float x, float y, float z); -GB_MATH_DEF Vec3 vec3v(float x[3]); +// NOTE(bill): Because to interpolate angles +GB_MATH_DEF float gb_angle_diff(float radians_a, float radians_b); -GB_MATH_DEF Vec4 vec4_zero(void); -GB_MATH_DEF Vec4 vec4(float x, float y, float z, float w); -GB_MATH_DEF Vec4 vec4v(float x[4]); +#define gb_min(a, b) ((a) < (b) ? (a) : (b)) +#define gb_max(a, b) ((a) > (b) ? (a) : (b)) -GB_MATH_DEF void vec2_add(Vec2 *d, Vec2 v0, Vec2 v1); -GB_MATH_DEF void vec2_sub(Vec2 *d, Vec2 v0, Vec2 v1); -GB_MATH_DEF void vec2_mul(Vec2 *d, Vec2 v, float s); -GB_MATH_DEF void vec2_div(Vec2 *d, Vec2 v, float s); +GB_MATH_DEF float gb_sqrt(float a); +GB_MATH_DEF float gb_inv_sqrt(float a); // NOTE(bill): Fast inverse square root -GB_MATH_DEF void vec3_add(Vec3 *d, Vec3 v0, Vec3 v1); -GB_MATH_DEF void vec3_sub(Vec3 *d, Vec3 v0, Vec3 v1); -GB_MATH_DEF void vec3_mul(Vec3 *d, Vec3 v, float s); -GB_MATH_DEF void vec3_div(Vec3 *d, Vec3 v, float s); +GB_MATH_DEF float gb_sin(float radians); +GB_MATH_DEF float gb_cos(float radians); +GB_MATH_DEF float gb_tan(float radians); +GB_MATH_DEF float gb_arcsin(float a); +GB_MATH_DEF float gb_arccos(float a); +GB_MATH_DEF float gb_arctan(float a); +GB_MATH_DEF float gb_arctan2(float y, float x); -GB_MATH_DEF void vec4_add(Vec4 *d, Vec4 v0, Vec4 v1); -GB_MATH_DEF void vec4_sub(Vec4 *d, Vec4 v0, Vec4 v1); -GB_MATH_DEF void vec4_mul(Vec4 *d, Vec4 v, float s); -GB_MATH_DEF void vec4_div(Vec4 *d, Vec4 v, float s); -GB_MATH_DEF void vec2_addeq(Vec2 *d, Vec2 v); -GB_MATH_DEF void vec2_subeq(Vec2 *d, Vec2 v); -GB_MATH_DEF void vec2_muleq(Vec2 *d, float s); -GB_MATH_DEF void vec2_diveq(Vec2 *d, float s); +GB_MATH_DEF float gb_exp(float x); +GB_MATH_DEF float gb_exp2(float x); +GB_MATH_DEF float gb_log(float x); +GB_MATH_DEF float gb_log2(float x); +GB_MATH_DEF float gb_fast_exp(float x); // NOTE(bill): Only valid from -1 <= x <= +1 +GB_MATH_DEF float gb_fast_exp2(float x); // NOTE(bill): Only valid from -1 <= x <= +1 +GB_MATH_DEF float gb_pow(float x, float y); // x^y -GB_MATH_DEF void vec3_addeq(Vec3 *d, Vec3 v); -GB_MATH_DEF void vec3_subeq(Vec3 *d, Vec3 v); -GB_MATH_DEF void vec3_muleq(Vec3 *d, float s); -GB_MATH_DEF void vec3_diveq(Vec3 *d, float s); -GB_MATH_DEF void vec4_addeq(Vec4 *d, Vec4 v); -GB_MATH_DEF void vec4_subeq(Vec4 *d, Vec4 v); -GB_MATH_DEF void vec4_muleq(Vec4 *d, float s); -GB_MATH_DEF void vec4_diveq(Vec4 *d, float s); +GB_MATH_DEF float gb_half_to_float(gb_half value); +GB_MATH_DEF gb_half gb_float_to_half(float value); -GB_MATH_DEF float vec2_dot(Vec2 v0, Vec2 v1); -GB_MATH_DEF float vec3_dot(Vec3 v0, Vec3 v1); -GB_MATH_DEF float vec4_dot(Vec4 v0, Vec4 v1); +// Vec -GB_MATH_DEF void vec2_cross(float *d, Vec2 v0, Vec2 v1); -GB_MATH_DEF void vec3_cross(Vec3 *d, Vec3 v0, Vec3 v1); +GB_MATH_DEF gbVec2 gb_vec2_zero(void); +GB_MATH_DEF gbVec2 gb_vec2(float x, float y); +GB_MATH_DEF gbVec2 gb_vec2v(float x[2]); -GB_MATH_DEF float vec2_mag2(Vec2 v); -GB_MATH_DEF float vec3_mag2(Vec3 v); -GB_MATH_DEF float vec4_mag2(Vec4 v); +GB_MATH_DEF gbVec3 gb_vec3_zero(void); +GB_MATH_DEF gbVec3 gb_vec3(float x, float y, float z); +GB_MATH_DEF gbVec3 gb_vec3v(float x[3]); -GB_MATH_DEF float vec2_mag(Vec2 v); -GB_MATH_DEF float vec3_mag(Vec3 v); -GB_MATH_DEF float vec4_mag(Vec4 v); +GB_MATH_DEF gbVec4 gb_vec4_zero(void); +GB_MATH_DEF gbVec4 gb_vec4(float x, float y, float z, float w); +GB_MATH_DEF gbVec4 gb_vec4v(float x[4]); -GB_MATH_DEF void vec2_norm(Vec2 *d, Vec2 v); -GB_MATH_DEF void vec3_norm(Vec3 *d, Vec3 v); -GB_MATH_DEF void vec4_norm(Vec4 *d, Vec4 v); -GB_MATH_DEF float vec2_aspect(Vec2 v); +GB_MATH_DEF void gb_vec2_add(gbVec2 *d, gbVec2 v0, gbVec2 v1); +GB_MATH_DEF void gb_vec2_sub(gbVec2 *d, gbVec2 v0, gbVec2 v1); +GB_MATH_DEF void gb_vec2_mul(gbVec2 *d, gbVec2 v, float s); +GB_MATH_DEF void gb_vec2_div(gbVec2 *d, gbVec2 v, float s); + +GB_MATH_DEF void gb_vec3_add(gbVec3 *d, gbVec3 v0, gbVec3 v1); +GB_MATH_DEF void gb_vec3_sub(gbVec3 *d, gbVec3 v0, gbVec3 v1); +GB_MATH_DEF void gb_vec3_mul(gbVec3 *d, gbVec3 v, float s); +GB_MATH_DEF void gb_vec3_div(gbVec3 *d, gbVec3 v, float s); + +GB_MATH_DEF void gb_vec4_add(gbVec4 *d, gbVec4 v0, gbVec4 v1); +GB_MATH_DEF void gb_vec4_sub(gbVec4 *d, gbVec4 v0, gbVec4 v1); +GB_MATH_DEF void gb_vec4_mul(gbVec4 *d, gbVec4 v, float s); +GB_MATH_DEF void gb_vec4_div(gbVec4 *d, gbVec4 v, float s); + +GB_MATH_DEF void gb_vec2_addeq(gbVec2 *d, gbVec2 v); +GB_MATH_DEF void gb_vec2_subeq(gbVec2 *d, gbVec2 v); +GB_MATH_DEF void gb_vec2_muleq(gbVec2 *d, float s); +GB_MATH_DEF void gb_vec2_diveq(gbVec2 *d, float s); + +GB_MATH_DEF void gb_vec3_addeq(gbVec3 *d, gbVec3 v); +GB_MATH_DEF void gb_vec3_subeq(gbVec3 *d, gbVec3 v); +GB_MATH_DEF void gb_vec3_muleq(gbVec3 *d, float s); +GB_MATH_DEF void gb_vec3_diveq(gbVec3 *d, float s); + +GB_MATH_DEF void gb_vec4_addeq(gbVec4 *d, gbVec4 v); +GB_MATH_DEF void gb_vec4_subeq(gbVec4 *d, gbVec4 v); +GB_MATH_DEF void gb_vec4_muleq(gbVec4 *d, float s); +GB_MATH_DEF void gb_vec4_diveq(gbVec4 *d, float s); + +GB_MATH_DEF float gb_vec2_dot(gbVec2 v0, gbVec2 v1); +GB_MATH_DEF float gb_vec3_dot(gbVec3 v0, gbVec3 v1); +GB_MATH_DEF float gb_vec4_dot(gbVec4 v0, gbVec4 v1); + +GB_MATH_DEF void gb_vec2_cross(float *d, gbVec2 v0, gbVec2 v1); +GB_MATH_DEF void gb_vec3_cross(gbVec3 *d, gbVec3 v0, gbVec3 v1); + +GB_MATH_DEF float gb_vec2_mag2(gbVec2 v); +GB_MATH_DEF float gb_vec3_mag2(gbVec3 v); +GB_MATH_DEF float gb_vec4_mag2(gbVec4 v); + +GB_MATH_DEF float gb_vec2_mag(gbVec2 v); +GB_MATH_DEF float gb_vec3_mag(gbVec3 v); +GB_MATH_DEF float gb_vec4_mag(gbVec4 v); + +GB_MATH_DEF void gb_vec2_norm(gbVec2 *d, gbVec2 v); +GB_MATH_DEF void gb_vec3_norm(gbVec3 *d, gbVec3 v); +GB_MATH_DEF void gb_vec4_norm(gbVec4 *d, gbVec4 v); + +GB_MATH_DEF void gb_vec2_norm0(gbVec2 *d, gbVec2 v); +GB_MATH_DEF void gb_vec3_norm0(gbVec3 *d, gbVec3 v); +GB_MATH_DEF void gb_vec4_norm0(gbVec4 *d, gbVec4 v); + +GB_MATH_DEF void gb_vec2_reflect(gbVec2 *d, gbVec2 i, gbVec2 n); +GB_MATH_DEF void gb_vec3_reflect(gbVec3 *d, gbVec3 i, gbVec3 n); +GB_MATH_DEF void gb_vec2_refract(gbVec2 *d, gbVec2 i, gbVec2 n, float eta); +GB_MATH_DEF void gb_vec3_refract(gbVec3 *d, gbVec3 i, gbVec3 n, float eta); + +GB_MATH_DEF float gb_vec2_aspect_ratio(gbVec2 v); // Matrix -GB_MATH_DEF void mat2_identity(Mat2 *m); -GB_MATH_DEF void float22_identity(float m[2][2]); +GB_MATH_DEF void gb_mat2_identity(gbMat2 *m); +GB_MATH_DEF void gb_float22_identity(float m[2][2]); -GB_MATH_DEF void mat2_transpose(Mat2 *m); -GB_MATH_DEF void mat2_mul(Mat2 *out, Mat2 *m1, Mat2 *m2); -GB_MATH_DEF void mat2_mul_vec2(Vec2 *out, Mat2 *m, Vec2 in); +GB_MATH_DEF void gb_mat2_transpose(gbMat2 *m); +GB_MATH_DEF void gb_mat2_mul(gbMat2 *out, gbMat2 *m1, gbMat2 *m2); +GB_MATH_DEF void gb_mat2_mul_vec2(gbVec2 *out, gbMat2 *m, gbVec2 in); -GB_MATH_DEF Mat2 *mat2_v(Vec2 m[2]); -GB_MATH_DEF Mat2 *mat2_f(float m[2][2]); -GB_MATH_DEF Float2 *float22_m(Mat2 *m); -GB_MATH_DEF Float2 *float22_v(Vec2 m[2]); -GB_MATH_DEF Float2 *float22_4(float m[4]); +GB_MATH_DEF gbMat2 *gb_mat2_v(gbVec2 m[2]); +GB_MATH_DEF gbMat2 *gb_mat2_f(float m[2][2]); +GB_MATH_DEF gbFloat2 *gb_float22_m(gbMat2 *m); +GB_MATH_DEF gbFloat2 *gb_float22_v(gbVec2 m[2]); +GB_MATH_DEF gbFloat2 *gb_float22_4(float m[4]); -GB_MATH_DEF void float22_transpose(float (*vec)[2]); -GB_MATH_DEF void float22_mul(float (*out)[2], float (*mat1)[2], float (*mat2)[2]); -GB_MATH_DEF void float22_mul_vec2(Vec2 *out, float m[2][2], Vec2 in); +GB_MATH_DEF void gb_float22_transpose(float (*vec)[2]); +GB_MATH_DEF void gb_float22_mul(float (*out)[2], float (*mat1)[2], float (*mat2)[2]); +GB_MATH_DEF void gb_float22_mul_vec2(gbVec2 *out, float m[2][2], gbVec2 in); -GB_MATH_DEF void mat3_identity(Mat3 *m); -GB_MATH_DEF void float33_identity(float m[3][3]); +GB_MATH_DEF void gb_mat3_identity(gbMat3 *m); +GB_MATH_DEF void gb_float33_identity(float m[3][3]); -GB_MATH_DEF void mat3_transpose(Mat3 *m); -GB_MATH_DEF void mat3_mul(Mat3 *out, Mat3 *m1, Mat3 *m2); -GB_MATH_DEF void mat3_mul_vec3(Vec3 *out, Mat3 *m, Vec3 in); +GB_MATH_DEF void gb_mat3_transpose(gbMat3 *m); +GB_MATH_DEF void gb_mat3_mul(gbMat3 *out, gbMat3 *m1, gbMat3 *m2); +GB_MATH_DEF void gb_mat3_mul_vec3(gbVec3 *out, gbMat3 *m, gbVec3 in); -GB_MATH_DEF Mat3 *mat3_v(Vec3 m[3]); -GB_MATH_DEF Mat3 *mat3_f(float m[3][3]); -GB_MATH_DEF Float3 *float33_m(Mat3 *m); -GB_MATH_DEF Float3 *float33_v(Vec3 m[3]); -GB_MATH_DEF Float3 *float33_9(float m[9]); +GB_MATH_DEF gbMat3 *gb_mat3_v(gbVec3 m[3]); +GB_MATH_DEF gbMat3 *gb_mat3_f(float m[3][3]); +GB_MATH_DEF gbFloat3 *gb_float33_m(gbMat3 *m); +GB_MATH_DEF gbFloat3 *gb_float33_v(gbVec3 m[3]); +GB_MATH_DEF gbFloat3 *gb_float33_9(float m[9]); -GB_MATH_DEF void float33_transpose(float (*vec)[3]); -GB_MATH_DEF void float33_mul(float (*out)[3], float (*mat1)[3], float (*mat2)[3]); -GB_MATH_DEF void float33_mul_vec3(Vec3 *out, float m[3][3], Vec3 in); +GB_MATH_DEF void gb_float33_transpose(float (*vec)[3]); +GB_MATH_DEF void gb_float33_mul(float (*out)[3], float (*mat1)[3], float (*mat2)[3]); +GB_MATH_DEF void gb_float33_mul_vec3(gbVec3 *out, float m[3][3], gbVec3 in); -GB_MATH_DEF void mat4_identity(Mat4 *m); -GB_MATH_DEF void float44_identity(float m[4][4]); +GB_MATH_DEF void gb_mat4_identity(gbMat4 *m); +GB_MATH_DEF void gb_float44_identity(float m[4][4]); -GB_MATH_DEF void mat4_transpose(Mat4 *m); -GB_MATH_DEF void mat4_mul(Mat4 *out, Mat4 *m1, Mat4 *m2); -GB_MATH_DEF void mat4_mul_vec4(Vec4 *out, Mat4 *m, Vec4 in); +GB_MATH_DEF void gb_mat4_transpose(gbMat4 *m); +GB_MATH_DEF void gb_mat4_mul(gbMat4 *out, gbMat4 *m1, gbMat4 *m2); +GB_MATH_DEF void gb_mat4_mul_vec4(gbVec4 *out, gbMat4 *m, gbVec4 in); -GB_MATH_DEF Mat4 *mat4_v(Vec4 m[4]); -GB_MATH_DEF Mat4 *mat4_f(float m[4][4]); -GB_MATH_DEF Float4 *float44_m(Mat4 *m); -GB_MATH_DEF Float4 *float44_v(Vec4 m[4]); -GB_MATH_DEF Float4 *float44_16(float m[16]); +GB_MATH_DEF gbMat4 *gb_mat4_v(gbVec4 m[4]); +GB_MATH_DEF gbMat4 *gb_mat4_f(float m[4][4]); +GB_MATH_DEF gbFloat4 *gb_float44_m(gbMat4 *m); +GB_MATH_DEF gbFloat4 *gb_float44_v(gbVec4 m[4]); +GB_MATH_DEF gbFloat4 *gb_float44_16(float m[16]); -GB_MATH_DEF void float44_transpose(float (*vec)[4]); -GB_MATH_DEF void float44_mul(float (*out)[4], float (*mat1)[4], float (*mat2)[4]); -GB_MATH_DEF void float44_mul_vec4(Vec4 *out, float m[4][4], Vec4 in); +GB_MATH_DEF void gb_float44_transpose(float (*vec)[4]); +GB_MATH_DEF void gb_float44_mul(float (*out)[4], float (*mat1)[4], float (*mat2)[4]); +GB_MATH_DEF void gb_float44_mul_vec4(gbVec4 *out, float m[4][4], gbVec4 in); -// Hermite Interpolations -GB_MATH_DEF float lerp(float a, float b, float t); -GB_MATH_DEF float smooth_step(float a, float b, float t); -GB_MATH_DEF float smoother_step(float a, float b, float t); +GB_MATH_DEF void gb_mat4_translate(gbMat4 *out, gbVec3 v); +GB_MATH_DEF void gb_mat4_rotate(gbMat4 *out, gbVec3 v, float angle_radians); +GB_MATH_DEF void gb_mat4_scale(gbMat4 *out, gbVec3 v); +GB_MATH_DEF void gb_mat4_scalef(gbMat4 *out, float s); +GB_MATH_DEF void gb_mat4_ortho2d(gbMat4 *out, float left, float right, float bottom, float top); +GB_MATH_DEF void gb_mat4_ortho3d(gbMat4 *out, float left, float right, float bottom, float top, float z_near, float z_far); +GB_MATH_DEF void gb_mat4_perspective(gbMat4 *out, float fovy, float aspect, float z_near, float z_far); +GB_MATH_DEF void gb_mat4_infinite_perspective(gbMat4 *out, float fovy, float aspect, float z_near); -GB_MATH_DEF void vec2_lerp(Vec2 *d, Vec2 a, Vec2 b, float t); -GB_MATH_DEF void vec3_lerp(Vec3 *d, Vec3 a, Vec3 b, float t); -GB_MATH_DEF void vec4_lerp(Vec4 *d, Vec4 a, Vec4 b, float t); +GB_MATH_DEF void gb_mat4_look_at(gbMat4 *out, gbVec3 eye, gbVec3 centre, gbVec3 up); -// Angles -GB_MATH_DEF float to_radians(float degrees); -GB_MATH_DEF float to_degrees(float radians); -// Projections -// NOTE(bill): Uses OpenGL Projection Conventions (-1 to 1) -// NOTE(bill): If Direct3D is needed, use custom projection to shift-z to (0 to 1) -GB_MATH_DEF void mat4_ortho2d(Mat4 *out, float left, float right, float bottom, float top); -GB_MATH_DEF void mat4_ortho3d(Mat4 *out, float left, float right, float bottom, float top, float z_near, float z_far); +GB_MATH_DEF gbQuat gb_quat(float x, float y, float z, float w); +GB_MATH_DEF gbQuat gb_quatv(float e[4]); +GB_MATH_DEF gbQuat gb_quat_axis_angle(gbVec3 axis, float angle_radians); +GB_MATH_DEF gbQuat gb_quat_euler_angles(float pitch, float yaw, float roll); +GB_MATH_DEF gbQuat gb_quat_identity(void); -#ifndef MURMUR64_SEED -#define MURMUR64_SEED 0x9747b28c +GB_MATH_DEF void gb_quat_add(gbQuat *d, gbQuat q0, gbQuat q1); +GB_MATH_DEF void gb_quat_sub(gbQuat *d, gbQuat q0, gbQuat q1); +GB_MATH_DEF void gb_quat_mul(gbQuat *d, gbQuat q0, gbQuat q1); +GB_MATH_DEF void gb_quat_div(gbQuat *d, gbQuat q0, gbQuat q1); + +GB_MATH_DEF void gb_quat_mulf(gbQuat *d, gbQuat q, float s); +GB_MATH_DEF void gb_quat_divf(gbQuat *d, gbQuat q, float s); + + +GB_MATH_DEF void gb_quat_addeq(gbQuat *d, gbQuat q); +GB_MATH_DEF void gb_quat_subeq(gbQuat *d, gbQuat q); +GB_MATH_DEF void gb_quat_muleq(gbQuat *d, gbQuat q); +GB_MATH_DEF void gb_quat_diveq(gbQuat *d, gbQuat q); + + +GB_MATH_DEF void gb_quat_muleqf(gbQuat *d, float s); +GB_MATH_DEF void gb_quat_diveqf(gbQuat *d, float s); + + + + +GB_MATH_DEF float gb_quat_dot(gbQuat q0, gbQuat q1); +GB_MATH_DEF float gb_quat_mag(gbQuat q); + +GB_MATH_DEF void gb_quat_norm(gbQuat *d, gbQuat q); +GB_MATH_DEF void gb_quat_conj(gbQuat *d, gbQuat q); +GB_MATH_DEF void gb_quat_inverse(gbQuat *d, gbQuat q); + +GB_MATH_DEF void gb_quat_axis(gbVec3 *axis, gbQuat q); +GB_MATH_DEF float gb_quat_angle(gbQuat q); + +GB_MATH_DEF float gb_quat_pitch(gbQuat q); +GB_MATH_DEF float gb_quat_yaw(gbQuat q); +GB_MATH_DEF float gb_quat_roll(gbQuat q); + +// Rotate v by q +GB_MATH_DEF void gb_quat_rotate_vec3(gbVec3 *d, gbQuat q, gbVec3 v); +GB_MATH_DEF void gb_mat4_from_quat(gbMat4 *out, gbQuat q); +GB_MATH_DEF void gb_quat_from_mat4(gbQuat *out, gbMat4 *m); + + + +// Interpolations +GB_MATH_DEF float gb_lerp(float a, float b, float t); +GB_MATH_DEF float gb_smooth_step(float a, float b, float t); +GB_MATH_DEF float gb_smoother_step(float a, float b, float t); + +GB_MATH_DEF void gb_vec2_lerp(gbVec2 *d, gbVec2 a, gbVec2 b, float t); +GB_MATH_DEF void gb_vec3_lerp(gbVec3 *d, gbVec3 a, gbVec3 b, float t); +GB_MATH_DEF void gb_vec4_lerp(gbVec4 *d, gbVec4 a, gbVec4 b, float t); + +GB_MATH_DEF void gb_quat_lerp(gbQuat *d, gbQuat a, gbQuat b, float t); +GB_MATH_DEF void gb_quat_nlerp(gbQuat *d, gbQuat a, gbQuat b, float t); +GB_MATH_DEF void gb_quat_slerp(gbQuat *d, gbQuat a, gbQuat b, float t); +GB_MATH_DEF void gb_quat_slerp_approx(gbQuat *d, gbQuat a, gbQuat b, float t); +GB_MATH_DEF void gb_quat_nquad(gbQuat *d, gbQuat p, gbQuat a, gbQuat b, gbQuat q, float t); +GB_MATH_DEF void gb_quat_squad(gbQuat *d, gbQuat p, gbQuat a, gbQuat b, gbQuat q, float t); +GB_MATH_DEF void gb_quat_squad_approx(gbQuat *d, gbQuat p, gbQuat a, gbQuat b, gbQuat q, float t); + +// Rects +GB_MATH_DEF gbRect2 gb_rect2(gbVec2 pos, gbVec2 dim); +GB_MATH_DEF gbRect3 gb_rect3(gbVec3 pos, gbVec3 dim); + +GB_MATH_DEF int gb_rect2_contains(gbRect2 a, float x, float y); +GB_MATH_DEF int gb_rect2_contains_vec2(gbRect2 a, gbVec2 p); +GB_MATH_DEF int gb_rect2_intersects(gbRect2 a, gbRect2 b); +GB_MATH_DEF int gb_rect2_intersection_result(gbRect2 a, gbRect2 b, gbRect2 *intersection); + + +#ifndef GB_MURMUR64_DEFAULT_SEED +#define GB_MURMUR64_DEFAULT_SEED 0x9747b28c #endif // Hashing -GB_MATH_DEF gb_math_u64 hash_murmur64(void const *key, size_t num_bytes); +GB_MATH_DEF gb_math_u64 gb_hash_murmur64(void const *key, size_t num_bytes, u64 seed); // Random // TODO(bill): Use a generator for the random numbers -GB_MATH_DEF float random_range_float(float min_inc, float max_inc); -GB_MATH_DEF int random_range_int(int min_inc, int max_inc); +GB_MATH_DEF float gb_random_range_float(float min_inc, float max_inc); +GB_MATH_DEF int gb_random_range_int(int min_inc, int max_inc); #if defined(__cplusplus) } #endif +#if defined(__cplusplus) && defined(GB_MATH_USE_OPERATOR_OVERLOADS) + +bool operator==(gbVec2 a, gbVec2 b) { return (a.x == b.x) && (a.y == b.y); } +bool operator!=(gbVec2 a, gbVec2 b) { return !operator==(a, b); } + +gbVec2 operator+(gbVec2 a) { return a; } +gbVec2 operator-(gbVec2 a) { gbVec2 r = {-a.x, -a.y}; return r; } + +gbVec2 operator+(gbVec2 a, gbVec2 b) { gbVec2 r; gb_vec2_add(&r, a, b); return r; } +gbVec2 operator-(gbVec2 a, gbVec2 b) { gbVec2 r; gb_vec2_sub(&r, a, b); return r; } + +gbVec2 operator*(gbVec2 a, float scalar) { gbVec2 r; gb_vec2_mul(&r, a, scalar); return r; } +gbVec2 operator*(float scalar, gbVec2 a) { return operator*(a, scalar); } + +gbVec2 operator/(gbVec2 a, float scalar) { return operator*(a, 1.0f/scalar); } + +// Hadamard Product +gbVec2 operator*(gbVec2 a, gbVec2 b) { gbVec2 r = {a.x*b.x, a.y*b.y}; return r; } +gbVec2 operator/(gbVec2 a, gbVec2 b) { gbVec2 r = {a.x/b.x, a.y/b.y}; return r; } + +gbVec2 &operator+=(gbVec2 &a, gbVec2 b) { return (a = a + b); } +gbVec2 &operator-=(gbVec2 &a, gbVec2 b) { return (a = a - b); } +gbVec2 &operator*=(gbVec2 &a, float scalar) { return (a = a * scalar); } +gbVec2 &operator/=(gbVec2 &a, float scalar) { return (a = a / scalar); } + + +bool operator==(gbVec3 a, gbVec3 b) { return (a.x == b.x) && (a.y == b.y) && (a.z == b.z); } +bool operator!=(gbVec3 a, gbVec3 b) { return !operator==(a, b); } + +gbVec3 operator+(gbVec3 a) { return a; } +gbVec3 operator-(gbVec3 a) { gbVec3 r = {-a.x, -a.y, -a.z}; return r; } + +gbVec3 operator+(gbVec3 a, gbVec3 b) { gbVec3 r; gb_vec3_add(&r, a, b); return r; } +gbVec3 operator-(gbVec3 a, gbVec3 b) { gbVec3 r; gb_vec3_sub(&r, a, b); return r; } + +gbVec3 operator*(gbVec3 a, float scalar) { gbVec3 r; gb_vec3_mul(&r, a, scalar); return r; } +gbVec3 operator*(float scalar, gbVec3 a) { return operator*(a, scalar); } + +gbVec3 operator/(gbVec3 a, float scalar) { return operator*(a, 1.0f/scalar); } + +// Hadamard Product +gbVec3 operator*(gbVec3 a, gbVec3 b) { gbVec3 r = {a.x*b.x, a.y*b.y, a.z*b.z}; return r; } +gbVec3 operator/(gbVec3 a, gbVec3 b) { gbVec3 r = {a.x/b.x, a.y/b.y, a.z/b.z}; return r; } + +gbVec3 &operator+=(gbVec3 &a, gbVec3 b) { return (a = a + b); } +gbVec3 &operator-=(gbVec3 &a, gbVec3 b) { return (a = a - b); } +gbVec3 &operator*=(gbVec3 &a, float scalar) { return (a = a * scalar); } +gbVec3 &operator/=(gbVec3 &a, float scalar) { return (a = a / scalar); } + + +bool operator==(gbVec4 a, gbVec4 b) { return (a.x == b.x) && (a.y == b.y) && (a.z == b.z) && (a.w == b.w); } +bool operator!=(gbVec4 a, gbVec4 b) { return !operator==(a, b); } + +gbVec4 operator+(gbVec4 a) { return a; } +gbVec4 operator-(gbVec4 a) { gbVec4 r = {-a.x, -a.y, -a.z, -a.w}; return r; } + +gbVec4 operator+(gbVec4 a, gbVec4 b) { gbVec4 r; gb_vec4_add(&r, a, b); return r; } +gbVec4 operator-(gbVec4 a, gbVec4 b) { gbVec4 r; gb_vec4_sub(&r, a, b); return r; } + +gbVec4 operator*(gbVec4 a, float scalar) { gbVec4 r; gb_vec4_mul(&r, a, scalar); return r; } +gbVec4 operator*(float scalar, gbVec4 a) { return operator*(a, scalar); } + +gbVec4 operator/(gbVec4 a, float scalar) { return operator*(a, 1.0f/scalar); } + +// Hadamard Product +gbVec4 operator*(gbVec4 a, gbVec4 b) { gbVec4 r = {a.x*b.x, a.y*b.y, a.z*b.z, a.w*b.w}; return r; } +gbVec4 operator/(gbVec4 a, gbVec4 b) { gbVec4 r = {a.x/b.x, a.y/b.y, a.z/b.z, a.w/b.w}; return r; } + +gbVec4 &operator+=(gbVec4 &a, gbVec4 b) { return (a = a + b); } +gbVec4 &operator-=(gbVec4 &a, gbVec4 b) { return (a = a - b); } +gbVec4 &operator*=(gbVec4 &a, float scalar) { return (a = a * scalar); } +gbVec4 &operator/=(gbVec4 &a, float scalar) { return (a = a / scalar); } + + +gbMat2 operator+(gbMat2 const &a, gbMat2 const &b) +{ + int i, j; + gbMat2 r = {}; + for (j = 0; j < 2; j++) { + for (i = 0; i < 2; i++) + r.e[2*j+i] = a.e[2*j+i] + b.e[2*j+i]; + } + return r; +} + +gbMat2 operator-(gbMat2 const &a, gbMat2 const &b) +{ + int i, j; + gbMat2 r = {}; + for (j = 0; j < 2; j++) { + for (i = 0; i < 2; i++) + r.e[2*j+i] = a.e[2*j+i] - b.e[2*j+i]; + } + return r; +} + +gbMat2 operator*(gbMat2 const &a, gbMat2 const &b) { gbMat2 r; gb_mat2_mul(&r, (gbMat2 *)&a, (gbMat2 *)&b); return r; } +gbVec2 operator*(gbMat2 const &a, gbVec2 v) { gbVec2 r; gb_mat2_mul_vec2(&r, (gbMat2 *)&a, v); return r; } +gbMat2 operator*(gbMat2 const &a, float scalar) +{ + gbMat2 r = {}; + int i; + for (i = 0; i < 2*2; i++) r.e[i] = a.e[i] * scalar; + return r; +} +gbMat2 operator*(float scalar, gbMat2 const &a) { return operator*(a, scalar); } +gbMat2 operator/(gbMat2 const &a, float scalar) { return operator*(a, 1.0f/scalar); } + +gbMat2& operator+=(gbMat2& a, gbMat2 const &b) { return (a = a + b); } +gbMat2& operator-=(gbMat2& a, gbMat2 const &b) { return (a = a - b); } +gbMat2& operator*=(gbMat2& a, gbMat2 const &b) { return (a = a * b); } + + + +gbMat3 operator+(gbMat3 const &a, gbMat3 const &b) +{ + int i, j; + gbMat3 r = {}; + for (j = 0; j < 3; j++) { + for (i = 0; i < 3; i++) + r.e[3*j+i] = a.e[3*j+i] + b.e[3*j+i]; + } + return r; +} + +gbMat3 operator-(gbMat3 const &a, gbMat3 const &b) +{ + int i, j; + gbMat3 r = {}; + for (j = 0; j < 3; j++) { + for (i = 0; i < 3; i++) + r.e[3*j+i] = a.e[3*j+i] - b.e[3*j+i]; + } + return r; +} + +gbMat3 operator*(gbMat3 const &a, gbMat3 const &b) { gbMat3 r; gb_mat3_mul(&r, (gbMat3 *)&a, (gbMat3 *)&b); return r; } +gbVec3 operator*(gbMat3 const &a, gbVec3 v) { gbVec3 r; gb_mat3_mul_vec3(&r, (gbMat3 *)&a, v); return r; } +gbMat3 operator*(gbMat3 const &a, float scalar) +{ + gbMat3 r = {}; + int i; + for (i = 0; i < 3*3; i++) r.e[i] = a.e[i] * scalar; + return r; +} +gbMat3 operator*(float scalar, gbMat3 const &a) { return operator*(a, scalar); } +gbMat3 operator/(gbMat3 const &a, float scalar) { return operator*(a, 1.0f/scalar); } + +gbMat3& operator+=(gbMat3& a, gbMat3 const &b) { return (a = a + b); } +gbMat3& operator-=(gbMat3& a, gbMat3 const &b) { return (a = a - b); } +gbMat3& operator*=(gbMat3& a, gbMat3 const &b) { return (a = a * b); } + + + +gbMat4 operator+(gbMat4 const &a, gbMat4 const &b) +{ + int i, j; + gbMat4 r = {}; + for (j = 0; j < 4; j++) { + for (i = 0; i < 4; i++) + r.e[4*j+i] = a.e[4*j+i] + b.e[4*j+i]; + } + return r; +} + +gbMat4 operator-(gbMat4 const &a, gbMat4 const &b) +{ + int i, j; + gbMat4 r = {}; + for (j = 0; j < 4; j++) { + for (i = 0; i < 4; i++) + r.e[4*j+i] = a.e[4*j+i] - b.e[4*j+i]; + } + return r; +} + +gbMat4 operator*(gbMat4 const &a, gbMat4 const &b) { gbMat4 r; gb_mat4_mul(&r, (gbMat4 *)&a, (gbMat4 *)&b); return r; } +gbVec4 operator*(gbMat4 const &a, gbVec4 v) { gbVec4 r; gb_mat4_mul_vec4(&r, (gbMat4 *)&a, v); return r; } +gbMat4 operator*(gbMat4 const &a, float scalar) +{ + gbMat4 r = {}; + int i; + for (i = 0; i < 4*4; i++) r.e[i] = a.e[i] * scalar; + return r; +} +gbMat4 operator*(float scalar, gbMat4 const &a) { return operator*(a, scalar); } +gbMat4 operator/(gbMat4 const &a, float scalar) { return operator*(a, 1.0f/scalar); } + +gbMat4& operator+=(gbMat4 &a, gbMat4 const &b) { return (a = a + b); } +gbMat4& operator-=(gbMat4 &a, gbMat4 const &b) { return (a = a - b); } +gbMat4& operator*=(gbMat4 &a, gbMat4 const &b) { return (a = a * b); } + + + +bool operator==(gbQuat a, gbQuat b) { return a.xyzw == b.xyzw; } +bool operator!=(gbQuat a, gbQuat b) { return !operator==(a, b); } + +gbQuat operator+(gbQuat q) { return q; } +gbQuat operator-(gbQuat q) { return gb_quat(-q.x, -q.y, -q.z, -q.w); } + +gbQuat operator+(gbQuat a, gbQuat b) { gbQuat r; gb_quat_add(&r, a, b); return r; } +gbQuat operator-(gbQuat a, gbQuat b) { gbQuat r; gb_quat_sub(&r, a, b); return r; } + +gbQuat operator*(gbQuat a, gbQuat b) { gbQuat r; gb_quat_mul(&r, a, b); return r; } +gbQuat operator*(gbQuat q, float s) { gbQuat r; gb_quat_mulf(&r, q, s); return r; } +gbQuat operator*(float s, gbQuat q) { return operator*(q, s); } +gbQuat operator/(gbQuat q, float s) { gbQuat r; gb_quat_divf(&r, q, s); return r; } + +gbQuat &operator+=(gbQuat &a, gbQuat b) { gb_quat_addeq(&a, b); return a; } +gbQuat &operator-=(gbQuat &a, gbQuat b) { gb_quat_subeq(&a, b); return a; } +gbQuat &operator*=(gbQuat &a, gbQuat b) { gb_quat_muleq(&a, b); return a; } +gbQuat &operator/=(gbQuat &a, gbQuat b) { gb_quat_diveq(&a, b); return a; } + +gbQuat &operator*=(gbQuat &a, float b) { gb_quat_muleqf(&a, b); return a; } +gbQuat &operator/=(gbQuat &a, float b) { gb_quat_diveqf(&a, b); return a; } + +// Rotate v by a +gbVec3 operator*(gbQuat q, gbVec3 v) { gbVec3 r; gb_quat_rotate_vec3(&r, q, v); return r; } + +#endif + + + #endif // GB_MATH_INCLUDE_GB_MATH_H //////////////////// // // +// // +// // +// // +// // +// // +// // +// // +// // +// // +// // +// // +// // +// // +// // +// // // Implementation // // // +// // +// // +// // +// // +// // +// // +// // +// // +// // +// // +// // +// // +// // +// // //////////////////// #if defined(GB_MATH_IMPLEMENTATION) -#include -#define VEC2_2OP(a,c,post) \ - a->x = c.x post; \ +float gb_clamp(float a, float lower, float upper) { return a < lower ? lower : a > upper ? upper : a; } +float gb_clamp01(float a) { return gb_clamp(a, 0.0f, 1.0f); } + + +float gb_as_radians(float degrees) { return degrees * GB_MATH_TAU / 360.0f; } +float gb_as_degrees(float radians) { return radians * 360.0f / GB_MATH_TAU; } + +float +gb_angle_diff(float radians_a, float radians_b) +{ + float delta = fmodf(radians_b-radians_a, GB_MATH_TAU); + delta = fmodf(delta + 1.5f*GB_MATH_TAU, GB_MATH_TAU); + delta -= 0.5f*GB_MATH_TAU; + return delta; +} + + +float gb_sqrt(float a) { return sqrtf(a); } +float +gb_inv_sqrt(float a) +{ + int i; + float x2, y; + float const three_halfs = 1.5f; + + x2 = a * 0.5f; + y = a; + i = *(int *)&y; // Evil floating point bit level hacking + i = 0x5f375a86 - (i >> 1); // What the fuck? + y = *(float *)&i; + y = y * (three_halfs - (x2 * y * y)); // 1st iteration + y = y * (three_halfs - (x2 * y * y)); // 2nd iteration, this can be removed + + return y; +} + +float gb_sin(float radians) { return sinf(radians); } +float gb_cos(float radians) { return cosf(radians); } +float gb_tan(float radians) { return tanf(radians); } +float gb_arcsin(float a) { return asinf(a); } +float gb_arccos(float a) { return acosf(a); } +float gb_arctan(float a) { return atanf(a); } +float gb_arctan2(float y, float x) { return atan2f(y, x); } + + + +float gb_exp(float x) { return expf(x); } +float gb_exp2(float x) { return gb_exp(0.69314718055994530941723212145818f * x); } +float gb_log(float x) { return logf(x); } +float gb_log2(float x) { return gb_log(x) / 0.69314718055994530941723212145818f; } + +float +gb_fast_exp(float x) +{ + float e = 1.0f + x * (1.0f + x * 0.5f * (1.0f + x * 0.3333333333f * (1.0f + x * 0.25 * (1.0f + x * 0.2f)))); + return e; +} + +float gb_fast_exp2(float x) { return gb_fast_exp(0.69314718055994530941723212145818f * x); } + +// TODO(bill): Should this be gb_exp(y * gb_log(x)) ??? +float gb_pow(float x, float y) { return powf(x, y); } + + +typedef union { + unsigned int i; + float f; +} gb_uif32; + +float +gb_half_to_float(gb_half value) +{ + gb_uif32 result; + int s = (value >> 15) & 0x00000001; + int e = (value >> 10) & 0x0000001f; + int m = value & 0x000003ff; + + if (e == 0) { + if(m == 0) { + // Plus or minus zero + gb_uif32 result; + result.i = (unsigned int)(s << 31); + return result.f; + } else { + // Denormalized number + while (!(m & 0x00000400)) { + m <<= 1; + e -= 1; + } + + e += 1; + m &= ~0x00000400; + } + } else if (e == 31) { + if (m == 0) { + // Positive or negative infinity + gb_uif32 result; + result.i = (unsigned int)((s << 31) | 0x7f800000); + return result.f; + } else { + // Nan + gb_uif32 result; + result.i = (unsigned int)((s << 31) | 0x7f800000 | (m << 13)); + return result.f; + } + } + + // Normalized number + + e = e + (127 - 15); + m = m << 13; + + // + // Assemble s, e and m. + // + + result.i = (unsigned int)((s << 31) | (e << 23) | m); + return result.f; +} + +gb_half +gb_float_to_half(float value) +{ + gb_uif32 v; + int i, s, e, m; + + v.f = value; + i = (int)v.i; + + s = (i >> 16) & 0x00008000; + e = ((i >> 23) & 0x000000ff) - (127 - 15); + m = i & 0x007fffff; + + + if (e <= 0) { + if (e < -10) { + return (gb_half)s; + } + m = (m | 0x00800000) >> (1 - e); + + if (m & 0x00001000) + m += 0x00002000; + + return (gb_half)(s | (m >> 13)); + } else if (e == 0xff - (127 - 15)) { + if (m == 0) { + // infinity + return (gb_half)(s | 0x7c00); + } else { + // NAN + m >>= 13; + return (gb_half)(s | 0x7c00 | m | (m == 0)); + } + } else { + if (m & 0x00001000) { + m += 0x00002000; + if (m & 0x00800000) { + m = 0; + e += 1; + } + } + + if (e > 30) { + float volatile f = 1e10; + for (unsigned int j = 0; j < 10; j++) + f *= f; // NOTE(bill): Cause overflow + + return (gb_half)(s | 0x7c00); + } + + return (gb_half)(s | (e << 10) | (m >> 13)); + } +} + + + + + + + +#define GB_VEC2_2OP(a,c,post) \ + a->x = c.x post; \ a->y = c.y post; -#define VEC2_3OP(a,b,op,c,post) \ - a->x = b.x op c.x post; \ +#define GB_VEC2_3OP(a,b,op,c,post) \ + a->x = b.x op c.x post; \ a->y = b.y op c.y post; -#define VEC3_2OP(a,c,post) \ - a->x = c.x post; \ - a->y = c.y post; \ +#define GB_VEC3_2OP(a,c,post) \ + a->x = c.x post; \ + a->y = c.y post; \ a->z = c.z post; -#define VEC3_3OP(a,b,op,c,post) \ - a->x = b.x op c.x post; \ - a->y = b.y op c.y post; \ +#define GB_VEC3_3OP(a,b,op,c,post) \ + a->x = b.x op c.x post; \ + a->y = b.y op c.y post; \ a->z = b.z op c.z post; -#define VEC4_2OP(a,c,post) \ - a->x = c.x post; \ - a->y = c.y post; \ - a->z = c.z post; \ +#define GB_VEC4_2OP(a,c,post) \ + a->x = c.x post; \ + a->y = c.y post; \ + a->z = c.z post; \ a->w = c.w post; -#define VEC4_3OP(a,b,op,c,post) \ - a->x = b.x op c.x post; \ - a->y = b.y op c.y post; \ - a->z = b.z op c.z post; \ +#define GB_VEC4_3OP(a,b,op,c,post) \ + a->x = b.x op c.x post; \ + a->y = b.y op c.y post; \ + a->z = b.z op c.z post; \ a->w = b.w op c.w post; -Vec2 vec2_zero(void) { Vec2 v = {0, 0}; return v; } -Vec2 vec2(float x, float y) { Vec2 v = {x, y}; return v; } -Vec2 vec2v(float x[2]) { Vec2 v = {x[0], x[1]}; return v; } +gbVec2 gb_vec2_zero(void) { gbVec2 v = {0, 0}; return v; } +gbVec2 gb_vec2(float x, float y) { gbVec2 v = {x, y}; return v; } +gbVec2 gb_vec2v(float x[2]) { gbVec2 v = {x[0], x[1]}; return v; } -Vec3 vec3_zero(void) { Vec3 v = {0, 0, 0}; return v; } -Vec3 vec3(float x, float y, float z) { Vec3 v = {x, y, z}; return v; } -Vec3 vec3v(float x[3]) { Vec3 v = {x[0], x[1], x[2]}; return v; } +gbVec3 gb_vec3_zero(void) { gbVec3 v = {0, 0, 0}; return v; } +gbVec3 gb_vec3(float x, float y, float z) { gbVec3 v = {x, y, z}; return v; } +gbVec3 gb_vec3v(float x[3]) { gbVec3 v = {x[0], x[1], x[2]}; return v; } -Vec4 vec4_zero(void) { Vec4 v = {0, 0, 0, 0}; return v; } -Vec4 vec4(float x, float y, float z, float w) { Vec4 v = {x, y, z, w}; return v; } -Vec4 vec4v(float x[4]) { Vec4 v = {x[0], x[1], x[2], x[3]}; return v; } +gbVec4 gb_vec4_zero(void) { gbVec4 v = {0, 0, 0, 0}; return v; } +gbVec4 gb_vec4(float x, float y, float z, float w) { gbVec4 v = {x, y, z, w}; return v; } +gbVec4 gb_vec4v(float x[4]) { gbVec4 v = {x[0], x[1], x[2], x[3]}; return v; } -void vec2_add(Vec2 *d, Vec2 v0, Vec2 v1) { VEC2_3OP(d,v0,+,v1,+0); } -void vec2_sub(Vec2 *d, Vec2 v0, Vec2 v1) { VEC2_3OP(d,v0,-,v1,+0); } -void vec2_mul(Vec2 *d, Vec2 v, float s) { VEC2_2OP(d,v,* s); } -void vec2_div(Vec2 *d, Vec2 v, float s) { VEC2_2OP(d,v,/ s); } +void gb_vec2_add(gbVec2 *d, gbVec2 v0, gbVec2 v1) { GB_VEC2_3OP(d,v0,+,v1,+0); } +void gb_vec2_sub(gbVec2 *d, gbVec2 v0, gbVec2 v1) { GB_VEC2_3OP(d,v0,-,v1,+0); } +void gb_vec2_mul(gbVec2 *d, gbVec2 v, float s) { GB_VEC2_2OP(d,v,* s); } +void gb_vec2_div(gbVec2 *d, gbVec2 v, float s) { GB_VEC2_2OP(d,v,/ s); } -void vec3_add(Vec3 *d, Vec3 v0, Vec3 v1) { VEC3_3OP(d,v0,+,v1,+0); } -void vec3_sub(Vec3 *d, Vec3 v0, Vec3 v1) { VEC3_3OP(d,v0,-,v1,+0); } -void vec3_mul(Vec3 *d, Vec3 v, float s) { VEC3_2OP(d,v,* s); } -void vec3_div(Vec3 *d, Vec3 v, float s) { VEC3_2OP(d,v,/ s); } +void gb_vec3_add(gbVec3 *d, gbVec3 v0, gbVec3 v1) { GB_VEC3_3OP(d,v0,+,v1,+0); } +void gb_vec3_sub(gbVec3 *d, gbVec3 v0, gbVec3 v1) { GB_VEC3_3OP(d,v0,-,v1,+0); } +void gb_vec3_mul(gbVec3 *d, gbVec3 v, float s) { GB_VEC3_2OP(d,v,* s); } +void gb_vec3_div(gbVec3 *d, gbVec3 v, float s) { GB_VEC3_2OP(d,v,/ s); } -void vec4_add(Vec4 *d, Vec4 v0, Vec4 v1) { VEC4_3OP(d,v0,+,v1,+0); } -void vec4_sub(Vec4 *d, Vec4 v0, Vec4 v1) { VEC4_3OP(d,v0,-,v1,+0); } -void vec4_mul(Vec4 *d, Vec4 v, float s) { VEC4_2OP(d,v,* s); } -void vec4_div(Vec4 *d, Vec4 v, float s) { VEC4_2OP(d,v,/ s); } +void gb_vec4_add(gbVec4 *d, gbVec4 v0, gbVec4 v1) { GB_VEC4_3OP(d,v0,+,v1,+0); } +void gb_vec4_sub(gbVec4 *d, gbVec4 v0, gbVec4 v1) { GB_VEC4_3OP(d,v0,-,v1,+0); } +void gb_vec4_mul(gbVec4 *d, gbVec4 v, float s) { GB_VEC4_2OP(d,v,* s); } +void gb_vec4_div(gbVec4 *d, gbVec4 v, float s) { GB_VEC4_2OP(d,v,/ s); } -void vec2_addeq(Vec2 *d, Vec2 v) { VEC2_3OP(d,(*d),+,v,+0); } -void vec2_subeq(Vec2 *d, Vec2 v) { VEC2_3OP(d,(*d),-,v,+0); } -void vec2_muleq(Vec2 *d, float s) { VEC2_2OP(d,(*d),* s); } -void vec2_diveq(Vec2 *d, float s) { VEC2_2OP(d,(*d),/ s); } +void gb_vec2_addeq(gbVec2 *d, gbVec2 v) { GB_VEC2_3OP(d,(*d),+,v,+0); } +void gb_vec2_subeq(gbVec2 *d, gbVec2 v) { GB_VEC2_3OP(d,(*d),-,v,+0); } +void gb_vec2_muleq(gbVec2 *d, float s) { GB_VEC2_2OP(d,(*d),* s); } +void gb_vec2_diveq(gbVec2 *d, float s) { GB_VEC2_2OP(d,(*d),/ s); } -void vec3_addeq(Vec3 *d, Vec3 v) { VEC3_3OP(d,(*d),+,v,+0); } -void vec3_subeq(Vec3 *d, Vec3 v) { VEC3_3OP(d,(*d),-,v,+0); } -void vec3_muleq(Vec3 *d, float s) { VEC3_2OP(d,(*d),* s); } -void vec3_diveq(Vec3 *d, float s) { VEC3_2OP(d,(*d),/ s); } +void gb_vec3_addeq(gbVec3 *d, gbVec3 v) { GB_VEC3_3OP(d,(*d),+,v,+0); } +void gb_vec3_subeq(gbVec3 *d, gbVec3 v) { GB_VEC3_3OP(d,(*d),-,v,+0); } +void gb_vec3_muleq(gbVec3 *d, float s) { GB_VEC3_2OP(d,(*d),* s); } +void gb_vec3_diveq(gbVec3 *d, float s) { GB_VEC3_2OP(d,(*d),/ s); } -void vec4_addeq(Vec4 *d, Vec4 v) { VEC4_3OP(d,(*d),+,v,+0); } -void vec4_subeq(Vec4 *d, Vec4 v) { VEC4_3OP(d,(*d),-,v,+0); } -void vec4_muleq(Vec4 *d, float s) { VEC4_2OP(d,(*d),* s); } -void vec4_diveq(Vec4 *d, float s) { VEC4_2OP(d,(*d),/ s); } +void gb_vec4_addeq(gbVec4 *d, gbVec4 v) { GB_VEC4_3OP(d,(*d),+,v,+0); } +void gb_vec4_subeq(gbVec4 *d, gbVec4 v) { GB_VEC4_3OP(d,(*d),-,v,+0); } +void gb_vec4_muleq(gbVec4 *d, float s) { GB_VEC4_2OP(d,(*d),* s); } +void gb_vec4_diveq(gbVec4 *d, float s) { GB_VEC4_2OP(d,(*d),/ s); } -float vec2_dot(Vec2 v0, Vec2 v1) { return v0.x*v1.x + v0.y*v1.y; } -float vec3_dot(Vec3 v0, Vec3 v1) { return v0.x*v1.x + v0.y*v1.y + v0.z*v1.z; } -float vec4_dot(Vec4 v0, Vec4 v1) { return v0.x*v1.x + v0.y*v1.y + v0.z*v1.z + v0.w*v1.w; } +float gb_vec2_dot(gbVec2 v0, gbVec2 v1) { return v0.x*v1.x + v0.y*v1.y; } +float gb_vec3_dot(gbVec3 v0, gbVec3 v1) { return v0.x*v1.x + v0.y*v1.y + v0.z*v1.z; } +float gb_vec4_dot(gbVec4 v0, gbVec4 v1) { return v0.x*v1.x + v0.y*v1.y + v0.z*v1.z + v0.w*v1.w; } -void vec2_cross(float *d, Vec2 v0, Vec2 v1) { *d = v0.x*v1.y - v1.x*v0.y; } -void vec3_cross(Vec3 *d, Vec3 v0, Vec3 v1) { d->x = v0.y*v1.z - v0.z*v1.y; +void gb_vec2_cross(float *d, gbVec2 v0, gbVec2 v1) { *d = v0.x*v1.y - v1.x*v0.y; } +void gb_vec3_cross(gbVec3 *d, gbVec3 v0, gbVec3 v1) { d->x = v0.y*v1.z - v0.z*v1.y; d->y = v0.z*v1.x - v0.x*v1.z; d->z = v0.x*v1.y - v0.y*v1.x; } -float vec2_mag2(Vec2 v) { return vec2_dot(v, v); } -float vec3_mag2(Vec3 v) { return vec3_dot(v, v); } -float vec4_mag2(Vec4 v) { return vec4_dot(v, v); } +float gb_vec2_mag2(gbVec2 v) { return gb_vec2_dot(v, v); } +float gb_vec3_mag2(gbVec3 v) { return gb_vec3_dot(v, v); } +float gb_vec4_mag2(gbVec4 v) { return gb_vec4_dot(v, v); } // TODO(bill): Create custom sqrt function -float vec2_mag(Vec2 v) { return sqrtf(vec2_dot(v, v)); } -float vec3_mag(Vec3 v) { return sqrtf(vec3_dot(v, v)); } -float vec4_mag(Vec4 v) { return sqrtf(vec4_dot(v, v)); } +float gb_vec2_mag(gbVec2 v) { return gb_sqrt(gb_vec2_dot(v, v)); } +float gb_vec3_mag(gbVec3 v) { return gb_sqrt(gb_vec3_dot(v, v)); } +float gb_vec4_mag(gbVec4 v) { return gb_sqrt(gb_vec4_dot(v, v)); } // TODO(bill): Should I calculate inv_sqrt directly? -void vec2_norm(Vec2 *d, Vec2 v) { vec2_div(d, v, vec2_mag(v)); } -void vec3_norm(Vec3 *d, Vec3 v) { vec3_div(d, v, vec3_mag(v)); } -void vec4_norm(Vec4 *d, Vec4 v) { vec4_div(d, v, vec4_mag(v)); } +void +gb_vec2_norm(gbVec2 *d, gbVec2 v) +{ + float mag = gb_vec2_mag(v); + gb_vec2_div(d, v, mag); +} +void +gb_vec3_norm(gbVec3 *d, gbVec3 v) +{ + float mag = gb_vec3_mag(v); + gb_vec3_div(d, v, mag); +} +void +gb_vec4_norm(gbVec4 *d, gbVec4 v) +{ + float mag = gb_vec4_mag(v); + gb_vec4_div(d, v, mag); +} -float vec2_aspect(Vec2 v) +void +gb_vec2_norm0(gbVec2 *d, gbVec2 v) +{ + float mag = gb_vec2_mag(v); + if (mag > 0) + gb_vec2_div(d, v, mag); + else + *d = gb_vec2_zero(); +} +void +gb_vec3_norm0(gbVec3 *d, gbVec3 v) +{ + float mag = gb_vec3_mag(v); + if (mag > 0) + gb_vec3_div(d, v, mag); + else + *d = gb_vec3_zero(); +} +void +gb_vec4_norm0(gbVec4 *d, gbVec4 v) +{ + float mag = gb_vec4_mag(v); + if (mag > 0) + gb_vec4_div(d, v, mag); + else + *d = gb_vec4_zero(); +} + + +void +gb_vec2_reflect(gbVec2 *d, gbVec2 i, gbVec2 n) +{ + gbVec2 b = n; + gb_vec2_muleq(&b, 2.0f*gb_vec2_dot(n, i)); + gb_vec2_sub(d, i, b); +} + +void +gb_vec3_reflect(gbVec3 *d, gbVec3 i, gbVec3 n) +{ + gbVec3 b = n; + gb_vec3_muleq(&b, 2.0f*gb_vec3_dot(n, i)); + gb_vec3_sub(d, i, b); +} + +void +gb_vec2_refract(gbVec2 *d, gbVec2 i, gbVec2 n, float eta) +{ + gbVec2 a, b; + float dv, k; + + dv = gb_vec2_dot(n, i); + k = 1.0f - eta*eta * (1.0f - dv*dv); + gb_vec2_mul(&a, i, eta); + gb_vec2_mul(&b, n, eta*dv*gb_sqrt(k)); + gb_vec2_sub(d, a, b); + gb_vec2_muleq(d, (float)(k >= 0.0f)); +} + +void +gb_vec3_refract(gbVec3 *d, gbVec3 i, gbVec3 n, float eta) +{ + gbVec3 a, b; + float dv, k; + + dv = gb_vec3_dot(n, i); + k = 1.0f - eta*eta * (1.0f - dv*dv); + gb_vec3_mul(&a, i, eta); + gb_vec3_mul(&b, n, eta*dv*gb_sqrt(k)); + gb_vec3_sub(d, a, b); + gb_vec3_muleq(d, (float)(k >= 0.0f)); +} + + + + + +float +gb_vec2_aspect_ratio(gbVec2 v) { if (v.y < 0.0001f) return 0.0f; @@ -405,34 +1076,34 @@ float vec2_aspect(Vec2 v) -void mat2_transpose(Mat2 *m) { float22_transpose(float22_m(m)); } -void mat2_identity(Mat2 *m) { float22_identity(float22_m(m)); } -void mat2_mul(Mat2 *out, Mat2 *m1, Mat2 *m2) { float22_mul(float22_m(out), float22_m(m1), float22_m(m2)); } +void gb_mat2_transpose(gbMat2 *m) { gb_float22_transpose(gb_float22_m(m)); } +void gb_mat2_identity(gbMat2 *m) { gb_float22_identity(gb_float22_m(m)); } +void gb_mat2_mul(gbMat2 *out, gbMat2 *m1, gbMat2 *m2) { gb_float22_mul(gb_float22_m(out), gb_float22_m(m1), gb_float22_m(m2)); } void -float22_identity(float m[2][2]) +gb_float22_identity(float m[2][2]) { m[0][0] = 1; m[0][1] = 0; m[1][0] = 0; m[1][1] = 1; } void -mat2_mul_vec2(Vec2 *out, Mat2 *m, Vec2 in) +gb_mat2_mul_vec2(gbVec2 *out, gbMat2 *m, gbVec2 in) { - float22_mul_vec2(out, float22_m(m), in); + gb_float22_mul_vec2(out, gb_float22_m(m), in); } -Mat2 *mat2_v(Vec2 m[2]) { return (Mat2 *)m; } -Mat2 *mat2_f(float m[2][2]) { return (Mat2 *)m; } +gbMat2 *gb_mat2_v(gbVec2 m[2]) { return (gbMat2 *)m; } +gbMat2 *gb_mat2_f(float m[2][2]) { return (gbMat2 *)m; } -Float2 *float22_m(Mat2 *m) { return (Float2 *)m; } -Float2 *float22_v(Vec2 m[2]) { return (Float2 *)m; } -Float2 *float22_4(float m[4]) { return (Float2 *)m; } +gbFloat2 *gb_float22_m(gbMat2 *m) { return (gbFloat2 *)m; } +gbFloat2 *gb_float22_v(gbVec2 m[2]) { return (gbFloat2 *)m; } +gbFloat2 *gb_float22_4(float m[4]) { return (gbFloat2 *)m; } void -float22_transpose(float (*vec)[2]) +gb_float22_transpose(float (*vec)[2]) { - int i, j; + unsigned int i, j; for (j = 0; j < 2; j++) { for (i = j + 1; i < 2; i++) { float t = vec[i][j]; @@ -443,9 +1114,9 @@ float22_transpose(float (*vec)[2]) } void -float22_mul(float (*out)[2], float (*mat1)[2], float (*mat2)[2]) +gb_float22_mul(float (*out)[2], float (*mat1)[2], float (*mat2)[2]) { - int i, j; + unsigned int i, j; float temp1[2][2], temp2[2][2]; if (mat1 == out) { memcpy(temp1, mat1, sizeof(temp1)); mat1 = temp1; } if (mat2 == out) { memcpy(temp2, mat2, sizeof(temp2)); mat2 = temp2; } @@ -458,10 +1129,10 @@ float22_mul(float (*out)[2], float (*mat1)[2], float (*mat2)[2]) } void -float22_mul_vec2(Vec2 *out, float m[2][2], Vec2 v) +gb_float22_mul_vec2(gbVec2 *out, float m[2][2], gbVec2 v) { - out->x = m[0][0] * v.x + m[0][1] * v.y; - out->y = m[1][0] * v.x + m[1][1] * v.y; + out->x = m[0][0]*v.x + m[0][1]*v.y; + out->y = m[1][0]*v.x + m[1][1]*v.y; } @@ -469,35 +1140,31 @@ float22_mul_vec2(Vec2 *out, float m[2][2], Vec2 v) -void mat3_transpose(Mat3 *m) { float33_transpose(float33_m(m)); } -void mat3_identity(Mat3 *m) { float33_identity(float33_m(m)); } -void mat3_mul(Mat3 *out, Mat3 *m1, Mat3 *m2) { float33_mul(float33_m(out), float33_m(m1), float33_m(m2)); } +void gb_mat3_transpose(gbMat3 *m) { gb_float33_transpose(gb_float33_m(m)); } +void gb_mat3_identity(gbMat3 *m) { gb_float33_identity(gb_float33_m(m)); } +void gb_mat3_mul(gbMat3 *out, gbMat3 *m1, gbMat3 *m2) { gb_float33_mul(gb_float33_m(out), gb_float33_m(m1), gb_float33_m(m2)); } void -float33_identity(float m[3][3]) +gb_float33_identity(float m[3][3]) { m[0][0] = 1; m[0][1] = 0; m[0][2] = 0; m[1][0] = 0; m[1][1] = 1; m[1][2] = 0; m[2][0] = 0; m[2][1] = 0; m[2][2] = 1; } -void -mat3_mul_vec3(Vec3 *out, Mat3 *m, Vec3 in) -{ - float33_mul_vec3(out, float33_m(m), in); -} +void gb_mat3_mul_vec3(gbVec3 *out, gbMat3 *m, gbVec3 in) { gb_float33_mul_vec3(out, gb_float33_m(m), in); } -Mat3 *mat3_v(Vec3 m[3]) { return (Mat3 *)m; } -Mat3 *mat3_f(float m[3][3]) { return (Mat3 *)m; } +gbMat3 *gb_mat3_v(gbVec3 m[3]) { return (gbMat3 *)m; } +gbMat3 *gb_mat3_f(float m[3][3]) { return (gbMat3 *)m; } -Float3 *float33_m(Mat3 *m) { return (Float3 *)m; } -Float3 *float33_v(Vec3 m[3]) { return (Float3 *)m; } -Float3 *float33_16(float m[9]) { return (Float3 *)m; } +gbFloat3 *gb_float33_m(gbMat3 *m) { return (gbFloat3 *)m; } +gbFloat3 *gb_float33_v(gbVec3 m[3]) { return (gbFloat3 *)m; } +gbFloat3 *gb_float33_16(float m[9]) { return (gbFloat3 *)m; } void -float33_transpose(float (*vec)[3]) +gb_float33_transpose(float (*vec)[3]) { - int i, j; + unsigned int i, j; for (j = 0; j < 3; j++) { for (i = j + 1; i < 3; i++) { float t = vec[i][j]; @@ -508,9 +1175,9 @@ float33_transpose(float (*vec)[3]) } void -float33_mul(float (*out)[3], float (*mat1)[3], float (*mat2)[3]) +gb_float33_mul(float (*out)[3], float (*mat1)[3], float (*mat2)[3]) { - int i, j; + unsigned int i, j; float temp1[3][3], temp2[3][3]; if (mat1 == out) { memcpy(temp1, mat1, sizeof(temp1)); mat1 = temp1; } if (mat2 == out) { memcpy(temp2, mat2, sizeof(temp2)); mat2 = temp2; } @@ -524,11 +1191,11 @@ float33_mul(float (*out)[3], float (*mat1)[3], float (*mat2)[3]) } void -float33_mul_vec3(Vec3 *out, float m[3][3], Vec3 v) +gb_float33_mul_vec3(gbVec3 *out, float m[3][3], gbVec3 v) { - out->x = m[0][0] * v.x + m[0][1] * v.y + m[0][2] * v.z; - out->y = m[1][0] * v.x + m[1][1] * v.y + m[1][2] * v.z; - out->z = m[2][0] * v.x + m[2][1] * v.y + m[2][2] * v.z; + out->x = m[0][0]*v.x + m[0][1]*v.y + m[0][2]*v.z; + out->y = m[1][0]*v.x + m[1][1]*v.y + m[1][2]*v.z; + out->z = m[2][0]*v.x + m[2][1]*v.y + m[2][2]*v.z; } @@ -539,12 +1206,12 @@ float33_mul_vec3(Vec3 *out, float m[3][3], Vec3 v) -void mat4_transpose(Mat4 *m) { float44_transpose(float44_m(m)); } -void mat4_identity(Mat4 *m) { float44_identity(float44_m(m)); } -void mat4_mul(Mat4 *out, Mat4 *m1, Mat4 *m2) { float44_mul(float44_m(out), float44_m(m1), float44_m(m2)); } +void gb_mat4_transpose(gbMat4 *m) { gb_float44_transpose(gb_float44_m(m)); } +void gb_mat4_identity(gbMat4 *m) { gb_float44_identity(gb_float44_m(m)); } +void gb_mat4_mul(gbMat4 *out, gbMat4 *m1, gbMat4 *m2) { gb_float44_mul(gb_float44_m(out), gb_float44_m(m1), gb_float44_m(m2)); } void -float44_identity(float m[4][4]) +gb_float44_identity(float m[4][4]) { m[0][0] = 1; m[0][1] = 0; m[0][2] = 0; m[0][3] = 0; m[1][0] = 0; m[1][1] = 1; m[1][2] = 0; m[1][3] = 0; @@ -553,22 +1220,22 @@ float44_identity(float m[4][4]) } void -mat4_mul_vec4(Vec4 *out, Mat4 *m, Vec4 in) +gb_mat4_mul_vec4(gbVec4 *out, gbMat4 *m, gbVec4 in) { - float44_mul_vec4(out, float44_m(m), in); + gb_float44_mul_vec4(out, gb_float44_m(m), in); } -Mat4 *mat4_v(Vec4 m[4]) { return (Mat4 *)m; } -Mat4 *mat4_f(float m[4][4]) { return (Mat4 *)m; } +gbMat4 *gb_mat4_v(gbVec4 m[4]) { return (gbMat4 *)m; } +gbMat4 *gb_mat4_f(float m[4][4]) { return (gbMat4 *)m; } -Float4 *float44_m(Mat4 *m) { return (Float4 *)m; } -Float4 *float44_v(Vec4 m[4]) { return (Float4 *)m; } -Float4 *float44_16(float m[16]) { return (Float4 *)m; } +gbFloat4 *gb_float44_m(gbMat4 *m) { return (gbFloat4 *)m; } +gbFloat4 *gb_float44_v(gbVec4 m[4]) { return (gbFloat4 *)m; } +gbFloat4 *gb_float44_16(float m[16]) { return (gbFloat4 *)m; } void -float44_transpose(float (*vec)[4]) +gb_float44_transpose(float (*vec)[4]) { - int i, j; + unsigned int i, j; for (j = 0; j < 4; j++) { for (i = j + 1; i < 4; i++) { float t = vec[i][j]; @@ -579,9 +1246,9 @@ float44_transpose(float (*vec)[4]) } void -float44_mul(float (*out)[4], float (*mat1)[4], float (*mat2)[4]) +gb_float44_mul(float (*out)[4], float (*mat1)[4], float (*mat2)[4]) { - int i, j; + unsigned int i, j; float temp1[4][4], temp2[4][4]; if (mat1 == out) { memcpy(temp1, mat1, sizeof(temp1)); mat1 = temp1; } if (mat2 == out) { memcpy(temp2, mat2, sizeof(temp2)); mat2 = temp2; } @@ -596,44 +1263,81 @@ float44_mul(float (*out)[4], float (*mat1)[4], float (*mat2)[4]) } void -float44_mul_vec4(Vec4 *out, float m[4][4], Vec4 v) +gb_float44_mul_vec4(gbVec4 *out, float m[4][4], gbVec4 v) { - out->x = m[0][0] * v.x + m[0][1] * v.y + m[0][2] * v.z + m[0][3] * v.w; - out->y = m[1][0] * v.x + m[1][1] * v.y + m[1][2] * v.z + m[1][3] * v.w; - out->z = m[2][0] * v.x + m[2][1] * v.y + m[2][2] * v.z + m[2][3] * v.w; - out->w = m[3][0] * v.x + m[3][1] * v.y + m[3][2] * v.z + m[3][3] * v.w; + out->x = m[0][0]*v.x + m[0][1]*v.y + m[0][2]*v.z + m[0][3]*v.w; + out->y = m[1][0]*v.x + m[1][1]*v.y + m[1][2]*v.z + m[1][3]*v.w; + out->z = m[2][0]*v.x + m[2][1]*v.y + m[2][2]*v.z + m[2][3]*v.w; + out->w = m[3][0]*v.x + m[3][1]*v.y + m[3][2]*v.z + m[3][3]*v.w; } +void +gb_mat4_translate(gbMat4 *out, gbVec3 v) +{ + gb_mat4_identity(out); + out->col[3].xyz = v; + out->col[3].w = 1; +} -float lerp(float a, float b, float t) { return a*(1.0f-t) + b*t; } -float smooth_step(float a, float b, float t) { float x = (t - a)/(b - a); return x*x*(3.0f - 2.0f*x); } -float smoother_step(float a, float b, float t) { float x = (t - a)/(b - a); return x*x*x*(x*(6.0f*x - 15.0f) + 10.0f); } +void +gb_mat4_rotate(gbMat4 *out, gbVec3 v, float angle_radians) +{ + float c, s; + gbVec3 axis, t; + gbFloat4 *rot; -#define VEC_LERPN(N, d, a, b, t) Vec##N db; vec##N##_mul(&db, b, t); vec##N##_add(d, a, db) -void vec2_lerp(Vec2 *d, Vec2 a, Vec2 b, float t) { VEC_LERPN(2, d, a, b, t); } -void vec3_lerp(Vec3 *d, Vec3 a, Vec3 b, float t) { VEC_LERPN(3, d, a, b, t); } -void vec4_lerp(Vec4 *d, Vec4 a, Vec4 b, float t) { VEC_LERPN(4, d, a, b, t); } + c = gb_cos(angle_radians); + s = gb_sin(angle_radians); + gb_vec3_norm(&axis, v); + gb_vec3_mul(&t, axis, 1.0f-c); + gb_mat4_identity(out); + rot = gb_float44_m(out); + rot[0][0] = c + t.x*axis.x; + rot[0][1] = 0 + t.x*axis.y + s*axis.z; + rot[0][2] = 0 + t.x*axis.z - s*axis.y; + rot[0][3] = 0; + rot[1][0] = 0 + t.y*axis.x - s*axis.z; + rot[1][1] = c + t.y*axis.y; + rot[1][2] = 0 + t.y*axis.z + s*axis.x; + rot[1][3] = 0; -float to_radians(float degrees) { return degrees * MATH_TAU / 360.0f; } -float to_degrees(float radians) { return radians * 360.0f / MATH_TAU; } - - + rot[2][0] = 0 + t.z*axis.x + s*axis.y; + rot[2][1] = 0 + t.z*axis.y - s*axis.x; + rot[2][2] = c + t.z*axis.z; + rot[2][3] = 0; +} +void +gb_mat4_scale(gbMat4 *out, gbVec3 v) +{ + gb_mat4_identity(out); + out->e[0] = v.x; + out->e[5] = v.y; + out->e[10] = v.z; +} +void +gb_mat4_scalef(gbMat4 *out, float s) +{ + gb_mat4_identity(out); + out->e[0] = s; + out->e[5] = s; + out->e[10] = s; +} void -mat4_ortho2d(Mat4 *out, float left, float right, float bottom, float top) +gb_mat4_ortho2d(gbMat4 *out, float left, float right, float bottom, float top) { - Float4 *m; - mat4_identity(out); - m = float44_m(out); + gbFloat4 *m; + gb_mat4_identity(out); + m = gb_float44_m(out); m[0][0] = 2.0f / (right - left); m[1][1] = 2.0f / (top - bottom); @@ -643,37 +1347,480 @@ mat4_ortho2d(Mat4 *out, float left, float right, float bottom, float top) } void -mat4_ortho3d(Mat4 *out, float left, float right, float bottom, float top, float z_near, float z_far) +gb_mat4_ortho3d(gbMat4 *out, float left, float right, float bottom, float top, float z_near, float z_far) { - Float4 *m; - mat4_identity(out); - m = float44_m(out); + gbFloat4 *m; + gb_mat4_identity(out); + m = gb_float44_m(out); m[0][0] = +2.0f / (right - left); m[1][1] = +2.0f / (top - bottom); m[2][2] = -2.0f / (z_far - z_near); - m[3][0] = -(right + left) / (right - left); - m[3][1] = -(top + bottom) / (top - bottom); + m[3][0] = -(right + left) / (right - left); + m[3][1] = -(top + bottom) / (top - bottom); m[3][2] = -(z_far + z_near) / (z_far - z_near); } +void +gb_mat4_perspective(gbMat4 *out, float fovy, float aspect, float z_near, float z_far) +{ + float tan_half_fovy = gb_tan(0.5f * fovy); + + gbFloat4 *m = gb_float44_m(out); + memset(m, 0, sizeof(gbMat4)); + + m[0][0] = 1.0f / (aspect*tan_half_fovy); + m[1][1] = 1.0f / (tan_half_fovy); + m[2][2] = -(z_far + z_near) / (z_far - z_near); + m[2][3] = -1.0f; + m[3][2] = -2.0f*z_far*z_near / (z_far - z_near); +} + +void +gb_mat4_infinite_perspective(gbMat4 *out, float fovy, float aspect, float z_near) +{ + float range = gb_tan(0.5f * fovy) * z_near; + float left = -range * aspect; + float right = range * aspect; + float bottom = -range; + float top = range; + + gbFloat4 *m = gb_float44_m(out); + memset(m, 0, sizeof(gbMat4)); + + m[0][0] = (2.0f*z_near) / (right - left); + m[1][1] = (2.0f*z_near) / (top - bottom); + m[2][2] = -1.0f; + m[2][3] = -1.0f; + m[3][2] = -2.0f*z_near; +} + +void +gb_mat4_look_at(gbMat4 *out, gbVec3 eye, gbVec3 centre, gbVec3 up) +{ + gbVec3 f, s, u; + gbFloat4 *m; + + gb_vec3_sub(&f, centre, eye); + gb_vec3_norm(&f, f); + + gb_vec3_cross(&s, f, up); + gb_vec3_norm(&s, s); + + gb_vec3_cross(&u, s, f); + + gb_mat4_identity(out); + m = gb_float44_m(out); + + m[0][0] = +s.x; + m[1][0] = +s.y; + m[2][0] = +s.z; + + m[0][1] = +u.x; + m[1][1] = +u.y; + m[2][1] = +u.z; + + m[0][2] = -f.x; + m[1][2] = -f.y; + m[2][2] = -f.z; + + m[3][0] = gb_vec3_dot(s, eye); + m[3][1] = gb_vec3_dot(u, eye); + m[3][2] = gb_vec3_dot(f, eye); +} + + + + + + + + + + + + +gbQuat gb_quat(float x, float y, float z, float w) { gbQuat q = {x, y, z, w}; return q; } +gbQuat gb_quatv(float e[4]) { gbQuat q = {e[0], e[1], e[2], e[3]}; return q; } + +gbQuat +gb_quat_axis_angle(gbVec3 axis, float angle_radians) +{ + gbQuat q; + gb_vec3_norm(&q.xyz, axis); + gb_vec3_muleq(&q.xyz, gb_sin(0.5f*angle_radians)); + q.w = gb_cos(0.5f*angle_radians); + return q; +} + +gbQuat +gb_quat_euler_angles(float pitch, float yaw, float roll) +{ + // TODO(bill): Do without multiplication, i.e. make it faster + gbQuat q, p, y, r; + p = gb_quat_axis_angle(gb_vec3(1, 0, 0), pitch); + y = gb_quat_axis_angle(gb_vec3(0, 1, 0), yaw); + r = gb_quat_axis_angle(gb_vec3(0, 0, 1), roll); + + gb_quat_mul(&q, y, p); + gb_quat_muleq(&q, r); + + return q; +} + +gbQuat gb_quat_identity(void) { gbQuat q = {0, 0, 0, 1}; return q; } + + +void gb_quat_add(gbQuat *d, gbQuat q0, gbQuat q1) { gb_vec4_add(&d->xyzw, q0.xyzw, q1.xyzw); } +void gb_quat_sub(gbQuat *d, gbQuat q0, gbQuat q1) { gb_vec4_sub(&d->xyzw, q0.xyzw, q1.xyzw); } + +void +gb_quat_mul(gbQuat *d, gbQuat q0, gbQuat q1) +{ + d->x = q0.w * q1.x + q0.x * q1.w + q0.y * q1.z - q0.z * q1.y; + d->y = q0.w * q1.y - q0.x * q1.z + q0.y * q1.w + q0.z * q1.x; + d->z = q0.w * q1.z + q0.x * q1.y - q0.y * q1.x + q0.z * q1.w; + d->w = q0.w * q1.w - q0.x * q1.x - q0.y * q1.y - q0.z * q1.z; +} + +void gb_quat_div(gbQuat *d, gbQuat q0, gbQuat q1){ gbQuat iq1; gb_quat_inverse(&iq1, q1); gb_quat_mul(d, q0, iq1); } + +void gb_quat_mulf(gbQuat *d, gbQuat q0, float s) { gb_vec4_mul(&d->xyzw, q0.xyzw, s); } +void gb_quat_divf(gbQuat *d, gbQuat q0, float s) { gb_vec4_div(&d->xyzw, q0.xyzw, s); } + + +void gb_quat_addeq(gbQuat *d, gbQuat q) { gb_vec4_addeq(&d->xyzw, q.xyzw); } +void gb_quat_subeq(gbQuat *d, gbQuat q) { gb_vec4_subeq(&d->xyzw, q.xyzw); } +void gb_quat_muleq(gbQuat *d, gbQuat q) { gb_quat_mul(d, *d, q); } +void gb_quat_diveq(gbQuat *d, gbQuat q) { gb_quat_div(d, *d, q); } + + +void gb_quat_muleqf(gbQuat *d, float s) { gb_vec4_muleq(&d->xyzw, s); } +void gb_quat_diveqf(gbQuat *d, float s) { gb_vec4_diveq(&d->xyzw, s); } + +float gb_quat_dot(gbQuat q0, gbQuat q1) { float r = gb_vec3_dot(q0.xyz, q1.xyz) + q0.w*q1.w; return r; } +float gb_quat_mag(gbQuat q) { float r = gb_sqrt(gb_quat_dot(q, q)); return r; } + +void gb_quat_norm(gbQuat *d, gbQuat q) { gb_quat_divf(d, q, gb_quat_mag(q)); } +void gb_quat_conj(gbQuat *d, gbQuat q) { d->xyz = gb_vec3(-q.x, -q.y, -q.z); d->w = q.w; } +void gb_quat_inverse(gbQuat *d, gbQuat q) { gb_quat_conj(d, q); gb_quat_diveqf(d, gb_quat_dot(q, q)); } + + +void +gb_quat_axis(gbVec3 *axis, gbQuat q) +{ + gbQuat n; gb_quat_norm(&n, q); + gb_vec3_div(axis, n.xyz, gb_sin(gb_arccos(q.w))); +} + +float +gb_quat_angle(gbQuat q) +{ + float mag = gb_quat_mag(q); + float c = q.w * (1.0f/mag); + float angle = 2.0f*gb_arccos(c); + return angle; +} + + +float gb_quat_roll(gbQuat q) { return gb_arctan2(2.0f*q.x*q.y + q.z*q.w, q.x*q.x + q.w*q.w - q.y*q.y - q.z*q.z); } +float gb_quat_pitch(gbQuat q) { return gb_arctan2(2.0f*q.y*q.z + q.w*q.x, q.w*q.w - q.x*q.x - q.y*q.y + q.z*q.z); } +float gb_quat_yaw(gbQuat q) { return gb_arcsin(-2.0f*(q.x*q.z - q.w*q.y)); } + +void +gb_quat_rotate_vec3(gbVec3 *d, gbQuat q, gbVec3 v) +{ + // gbVec3 t = 2.0f * cross(q.xyz, v); + // *d = q.w*t + v + cross(q.xyz, t); + gbVec3 t, p; + gb_vec3_cross(&t, q.xyz, v); + gb_vec3_muleq(&t, 2.0f); + + gb_vec3_cross(&p, q.xyz, t); + + gb_vec3_mul(d, t, q.w); + gb_vec3_addeq(d, v); + gb_vec3_addeq(d, p); +} + + +void +gb_mat4_from_quat(gbMat4 *out, gbQuat q) +{ + gbFloat4 *m; + gbQuat a; + float xx, yy, zz, + xy, xz, yz, + wx, wy, wz; + + gb_quat_norm(&a, q); + xx = a.x*a.x; yy = a.y*a.y; zz = a.z*a.z; + xy = a.x*a.y; xz = a.x*a.z; yz = a.y*a.z; + wx = a.w*a.x; wy = a.w*a.y; wz = a.w*a.z; + + gb_mat4_identity(out); + m = gb_float44_m(out); + + m[0][0] = 1.0f - 2.0f*(yy + zz); + m[0][1] = 2.0f*(xy + wz); + m[0][2] = 2.0f*(xz - wy); + + m[1][0] = 2.0f*(xy - wz); + m[1][1] = 1.0f - 2.0f*(xx + zz); + m[1][2] = 2.0f*(yz + wx); + + m[2][0] = 2.0f*(xz + wy); + m[2][1] = 2.0f*(yz - wx); + m[2][2] = 1.0f - 2.0f*(xx + yy); +} + +void +gb_quat_from_mat4(gbQuat *out, gbMat4 *mat) +{ + gbFloat4 *m; + float four_x_squared_minus_1, four_y_squared_minus_1, + four_z_squared_minus_1, four_w_squared_minus_1, + four_biggest_squared_minus_1; + unsigned int biggest_index = 0; + float biggest_value, mult; + + m = gb_float44_m(mat); + + four_x_squared_minus_1 = m[0][0] - m[1][1] - m[2][2]; + four_y_squared_minus_1 = m[1][1] - m[0][0] - m[2][2]; + four_z_squared_minus_1 = m[2][2] - m[0][0] - m[1][1]; + four_w_squared_minus_1 = m[0][0] + m[1][1] + m[2][2]; + + four_biggest_squared_minus_1 = four_w_squared_minus_1; + if (four_x_squared_minus_1 > four_biggest_squared_minus_1) { + four_biggest_squared_minus_1 = four_x_squared_minus_1; + biggest_index = 1; + } + if (four_y_squared_minus_1 > four_biggest_squared_minus_1) { + four_biggest_squared_minus_1 = four_y_squared_minus_1; + biggest_index = 2; + } + if (four_z_squared_minus_1 > four_biggest_squared_minus_1) { + four_biggest_squared_minus_1 = four_z_squared_minus_1; + biggest_index = 3; + } + + biggest_value = gb_sqrt(four_biggest_squared_minus_1 + 1.0f) * 0.5f; + mult = 0.25f / biggest_value; + + switch (biggest_index) { + case 0: + out->w = biggest_value; + out->x = (m[1][2] - m[2][1]) * mult; + out->y = (m[2][0] - m[0][2]) * mult; + out->z = (m[0][1] - m[1][0]) * mult; + break; + case 1: + out->w = (m[1][2] - m[2][1]) * mult; + out->x = biggest_value; + out->y = (m[0][1] + m[1][0]) * mult; + out->z = (m[2][0] + m[0][2]) * mult; + break; + case 2: + out->w = (m[2][0] - m[0][2]) * mult; + out->x = (m[0][1] + m[1][0]) * mult; + out->y = biggest_value; + out->z = (m[1][2] + m[2][1]) * mult; + break; + case 3: + out->w = (m[0][1] - m[1][0]) * mult; + out->x = (m[2][0] + m[0][2]) * mult; + out->y = (m[1][2] + m[2][1]) * mult; + out->z = biggest_value; + break; + default: + // NOTE(bill): This shouldn't fucking happen!!! + break; + } + +} + + + + + + +float gb_lerp(float a, float b, float t) { return a*(1.0f-t) + b*t; } +float gb_smooth_step(float a, float b, float t) { float x = (t - a)/(b - a); return x*x*(3.0f - 2.0f*x); } +float gb_smoother_step(float a, float b, float t) { float x = (t - a)/(b - a); return x*x*x*(x*(6.0f*x - 15.0f) + 10.0f); } + + +#define GB_VEC_LERPN(N, d, a, b, t) \ + gbVec##N db; \ + gb_vec##N##_sub(&db, b, a); \ + gb_vec##N##_muleq(&db, t); \ + gb_vec##N##_add(d, a, db) +void gb_vec2_lerp(gbVec2 *d, gbVec2 a, gbVec2 b, float t) { GB_VEC_LERPN(2, d, a, b, t); } +void gb_vec3_lerp(gbVec3 *d, gbVec3 a, gbVec3 b, float t) { GB_VEC_LERPN(3, d, a, b, t); } +void gb_vec4_lerp(gbVec4 *d, gbVec4 a, gbVec4 b, float t) { GB_VEC_LERPN(4, d, a, b, t); } + + + +void gb_quat_lerp(gbQuat *d, gbQuat a, gbQuat b, float t) { gb_vec4_lerp(&d->xyzw, a.xyzw, b.xyzw, t); } +void gb_quat_nlerp(gbQuat *d, gbQuat a, gbQuat b, float t) { gb_quat_lerp(d, a, b, t); gb_quat_norm(d, *d); } + +void +gb_quat_slerp(gbQuat *d, gbQuat a, gbQuat b, float t) +{ + gbQuat x, y, z; + float cos_theta, angle; + float s1, s0, is; + + z = b; + cos_theta = gb_quat_dot(a, b); + + if (cos_theta < 0.0f) { + z = gb_quat(-b.x, -b.y, -b.z, -b.w); + cos_theta = -cos_theta; + } + + if (cos_theta > 1.0f) { + // NOTE(bill): Use lerp not nlerp as it's not a real angle or they are not normalized + gb_quat_lerp(d, a, b, t); + } + + angle = gb_arccos(cos_theta); + + s1 = gb_sin(1.0f - t*angle); + s0 = gb_sin(t*angle); + is = 1.0f/gb_sin(angle); + gb_quat_mulf(&x, z, s1); + gb_quat_mulf(&y, z, s0); + gb_quat_add(d, x, y); + gb_quat_muleqf(d, is); +} + +void +gb_quat_slerp_approx(gbQuat *d, gbQuat a, gbQuat b, float t) +{ + // NOTE(bill): Derived by taylor expanding the geometric interpolation equation + float tp = t + (1.0f - gb_quat_dot(a, b))/3.0f * t*(-2.0f*t*t + 3.0f*t - 1.0f); + return gb_quat_nlerp(d, a, b, tp); +} + +void +gb_quat_nquad(gbQuat *d, gbQuat p, gbQuat a, gbQuat b, gbQuat q, float t) +{ + gbQuat x, y; + gb_quat_nlerp(&x, p, q, t); + gb_quat_nlerp(&y, a, b, t); + gb_quat_nlerp(d, x, y, 2.0f*t*(1.0f-t)); +} + +void +gb_quat_squad(gbQuat *d, gbQuat p, gbQuat a, gbQuat b, gbQuat q, float t) +{ + gbQuat x, y; + gb_quat_slerp(&x, p, q, t); + gb_quat_slerp(&y, a, b, t); + gb_quat_slerp(d, x, y, 2.0f*t*(1.0f-t)); +} + +void +gb_quat_squad_approx(gbQuat *d, gbQuat p, gbQuat a, gbQuat b, gbQuat q, float t) +{ + gbQuat x, y; + gb_quat_slerp_approx(&x, p, q, t); + gb_quat_slerp_approx(&y, a, b, t); + gb_quat_slerp_approx(d, x, y, 2.0f*t*(1.0f-t)); +} + + + + + + + +gbRect2 +gb_rect2(gbVec2 pos, gbVec2 dim) +{ + gbRect2 r; + r.pos = pos; + r.dim = dim; + return r; +} + +gbRect3 +gb_rect3(gbVec3 pos, gbVec3 dim) +{ + gbRect3 r; + r.pos = pos; + r.dim = dim; + return r; +} + +int +gb_rect2_contains(gbRect2 a, float x, float y) +{ + float min_x = gb_min(a.pos.x, a.pos.x+a.dim.x); + float max_x = gb_max(a.pos.x, a.pos.x+a.dim.x); + float min_y = gb_min(a.pos.y, a.pos.y+a.dim.y); + float max_y = gb_max(a.pos.y, a.pos.y+a.dim.y); + int result = (x >= min_x) & (x < max_x) & (y >= min_y) & (y < max_y); + return result; +} + +int gb_rect2_contains_vec2(gbRect2 a, gbVec2 p) { return gb_rect2_contains(a, p.x, p.y); } + +int +gb_rect2_intersects(gbRect2 a, gbRect2 b) +{ + gbRect2 r = {0}; + return gb_rect2_intersection_result(a, b, &r); +} + +int +gb_rect2_intersection_result(gbRect2 a, gbRect2 b, gbRect2 *intersection) +{ + float a_min_x = gb_min(a.pos.x, a.pos.x+a.dim.x); + float a_max_x = gb_max(a.pos.x, a.pos.x+a.dim.x); + float a_min_y = gb_min(a.pos.y, a.pos.y+a.dim.y); + float a_max_y = gb_max(a.pos.y, a.pos.y+a.dim.y); + + float b_min_x = gb_min(b.pos.x, b.pos.x+b.dim.x); + float b_max_x = gb_max(b.pos.x, b.pos.x+b.dim.x); + float b_min_y = gb_min(b.pos.y, b.pos.y+b.dim.y); + float b_max_y = gb_max(b.pos.y, b.pos.y+b.dim.y); + + float x0 = gb_max(a_min_x, b_min_x); + float y0 = gb_max(a_min_y, b_min_y); + float x1 = gb_min(a_max_x, b_max_x); + float y1 = gb_min(a_max_y, b_max_y); + + if ((x0 < x1) && (y0 < y1)) { + gbRect2 r = gb_rect2(gb_vec2(x0, y0), gb_vec2(x1-x0, y1-y0)); + *intersection = r; + return 1; + } else { + gbRect2 r = {0}; + *intersection = r; + return 0; + } +} + + #if defined(__x86_64__) || defined(__ppc64__) - u64 - hash_murmur64(void const *key, size_t num_bytes) + gb_math_u64 + gb_hash_murmur64(void const *key, size_t num_bytes, u64 seed) { - u64 const m = 0xc6a4a7935bd1e995ULL; - int const r = 47; + gb_math_u64 const m = 0xc6a4a7935bd1e995ULL; + gb_math_u64 const r = 47; - u64 h = MURMUR64_SEED ^ (num_bytes * m); + gb_math_u64 h = seed ^ (num_bytes * m); - u64 *data = (u64 *)(key); - u64 *end = data + (num_bytes / 8); - u8 *data2; + gb_math_u64 *data = (gb_math_u64 *)(key); + gb_math_u64 *end = data + (num_bytes / 8); + unsigned char *data2; while (data != end) { - u64 k = *data++; + gb_math_u64 k = *data++; k *= m; k ^= k >> r; k *= m; @@ -681,16 +1828,16 @@ mat4_ortho3d(Mat4 *out, float left, float right, float bottom, float top, float h *= m; } - data2 = (u8 *)data; + data2 = (unsigned char *)data; switch (num_bytes & 7) { - case 7: h ^= (u64)data2[6] << 48; - case 6: h ^= (u64)data2[5] << 40; - case 5: h ^= (u64)data2[4] << 32; - case 4: h ^= (u64)data2[3] << 24; - case 3: h ^= (u64)data2[2] << 16; - case 2: h ^= (u64)data2[1] << 8; - case 1: h ^= (u64)data2[0]; + case 7: h ^= (gb_math_u64)data2[6] << 48; + case 6: h ^= (gb_math_u64)data2[5] << 40; + case 5: h ^= (gb_math_u64)data2[4] << 32; + case 4: h ^= (gb_math_u64)data2[3] << 24; + case 3: h ^= (gb_math_u64)data2[2] << 16; + case 2: h ^= (gb_math_u64)data2[1] << 8; + case 1: h ^= (gb_math_u64)data2[0]; h *= m; }; @@ -702,14 +1849,14 @@ mat4_ortho3d(Mat4 *out, float left, float right, float bottom, float top, float } #else gb_math_u64 - hash_murmur64(void const *key, size_t num_bytes) + gb_hash_murmur64(void const *key, size_t num_bytes, u64 seed) { gb_math_u32 const m = 0x5bd1e995; gb_math_u32 const r = 24; gb_math_u64 h = 0; - gb_math_u32 h1 = (gb_math_u32)MURMUR64_SEED ^ (gb_math_u32)num_bytes; - gb_math_u32 h2 = (gb_math_u32)((gb_math_u64)MURMUR64_SEED >> 32); + gb_math_u32 h1 = (gb_math_u32)seed ^ (gb_math_u32)num_bytes; + gb_math_u32 h2 = (gb_math_u32)((gb_math_u64)seed >> 32); gb_math_u32 *data = (gb_math_u32 *)key; @@ -744,9 +1891,10 @@ mat4_ortho3d(Mat4 *out, float left, float right, float bottom, float top, float } switch (num_bytes) { - case 3: h2 ^= (gb_math_u32)((gb_math_u8 *)(data)[2]) << 16; - case 2: h2 ^= (gb_math_u32)((gb_math_u8 *)(data)[1]) << 8; - case 1: h2 ^= (gb_math_u32)((gb_math_u8 *)(data)[0]) << 0; + gb_math_u32 a, b, c; + case 3: c = data[2]; h2 ^= c << 16; + case 2: b = data[1]; h2 ^= b << 8; + case 1: a = data[0]; h2 ^= a << 0; h2 *= m; }; @@ -768,21 +1916,17 @@ mat4_ortho3d(Mat4 *out, float left, float right, float bottom, float top, float // TODO(bill): Make better random number generators float -random_range_float(float min_inc, float max_inc) +gb_random_range_float(float min_inc, float max_inc) { - static int random_value = 0xdeadbeef; // Random Value - float result; - random_value = random_value * 2147001325 + 715136305; // BCPL generator - result = *(float *)&random_value; // bits - result /= 4294967295.0f; - result *= (max_inc - min_inc); + int int_result = gb_random_range_int(0, INT_MAX); + float result = int_result/(float)INT_MAX; + result *= max_inc - min_inc; result += min_inc; - return result; } int -random_range_int(int min_inc, int max_inc) +gb_random_range_int(int min_inc, int max_inc) { static int random_value = 0xdeadbeef; // Random Value int diff, result; From 24d6605d1758445fe9de2dff172b7bceb6d95a39 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Fri, 8 Apr 2016 21:40:53 +0100 Subject: [PATCH 03/15] Delete gb_math.hpp --- gb_math.hpp | 3882 --------------------------------------------------- 1 file changed, 3882 deletions(-) delete mode 100644 gb_math.hpp diff --git a/gb_math.hpp b/gb_math.hpp deleted file mode 100644 index b81bde9..0000000 --- a/gb_math.hpp +++ /dev/null @@ -1,3882 +0,0 @@ -// gb_math.hpp - v0.03a - public domain C++11 math library - no warranty implied; use at your own risk -// A C++11 math library geared towards game development -// This is meant to be used the gb.hpp library but it doesn't have to be - -/* -Version History: - 0.04 - Change const position convention - 0.03a - Remove templated clamp - 0.03 - Remove templated min/max/clamp - 0.02b - Typo fixes - 0.02a - Better `static` keywords - 0.02 - More Angle Units and templated min/max/clamp/lerp - 0.01 - Initial Version - -LICENSE - This software is in the public domain. Where that dedication is not - recognized, you are granted a perpetual, irrevocable license to copy, - distribute, and modify this file as you see fit. - -WARNING - - This library is _slightly_ experimental and features may not work as expected. - - This also means that many functions are not documented. - - This library was developed in conjunction with `gb.hpp` - -CONTENTS: - - Common Macros - - Assert - - Types - - Vector(2,3,4) - - Complex - - Quaternion - - Matrix(2,3,4) - - Euler_Angles - - Transform - - Aabb - - Sphere - - Plane - - Operations - - Functions & Constants - - Type Functions - - Random -*/ - -#ifndef GB_MATH_INCLUDE_GB_MATH_HPP -#define GB_MATH_INCLUDE_GB_MATH_HPP - -#if !defined(__cplusplus) && __cplusplus >= 201103L - #error This library is only for C++11 and above -#endif - -// NOTE(bill): Because static means three different things in C/C++ -// Great Design(!) -#ifndef global_variable -#define global_variable static -#define internal_linkage static -#define local_persist static -#endif - -#if defined(_MSC_VER) - #define _ALLOW_KEYWORD_MACROS - - #ifndef alignof // Needed for MSVC 2013 'cause Microsoft "loves" standards - #define alignof(x) __alignof(x) - #endif -#endif - - -//////////////////////////////// -/// /// -/// System OS /// -/// /// -//////////////////////////////// -#if defined(_WIN32) || defined(_WIN64) - #ifndef GB_SYSTEM_WINDOWS - #define GB_SYSTEM_WINDOWS 1 - #endif -#elif defined(__APPLE__) && defined(__MACH__) - #ifndef GB_SYSTEM_OSX - #define GB_SYSTEM_OSX 1 - #endif -#elif defined(__unix__) - #ifndef GB_SYSTEM_UNIX - #define GB_SYSTEM_UNIX 1 - #endif - - #if defined(__linux__) - #ifndef GB_SYSTEM_LINUX - #define GB_SYSTEM_LINUX 1 - #endif - #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) - #ifndef GB_SYSTEM_FREEBSD - #define GB_SYSTEM_FREEBSD 1 - #endif - #else - #error This UNIX operating system is not supported by gb.hpp - #endif -#else - #error This operating system is not supported by gb.hpp -#endif - - -#if defined(_MSC_VER) - // Microsoft Visual Studio - #define GB_COMPILER_MSVC 1 -#elif defined(__clang__) - // Clang - #define GB_COMPILER_CLANG 1 -#elif defined(__GNUC__) || defined(__GNUG__) && !(defined(__clang__) || defined(__INTEL_COMPILER)) - // GNU GCC/G++ Compiler - #define GB_COMPILER_GNU_GCC 1 -#elif defined(__INTEL_COMPILER) - // Intel C++ Compiler - #define GB_COMPILER_INTEL 1 -#endif - -//////////////////////////////// -/// /// -/// Environment Bit Size /// -/// /// -//////////////////////////////// -#if defined(_WIN32) || defined(_WIN64) - #if defined(_WIN64) - #ifndef GB_ARCH_64_BIT - #define GB_ARCH_64_BIT 1 - #endif - #else - #ifndef GB_ARCH_32_BIT - #define GB_ARCH_32_BIT 1 - #endif - #endif -#endif - -// TODO(bill): Check if this KEPLER_ENVIRONMENT works on clang -#if defined(__GNUC__) - #if defined(__x86_64__) || defined(__ppc64__) - #ifndef GB_ARCH_64_BIT - #define GB_ARCH_64_BIT 1 - #endif - #else - #ifndef GB_ARCH_32_BIT - #define GB_ARCH_32_BIT 1 - #endif - #endif -#endif - - - -#ifndef GB_EDIAN_ORDER -#define GB_EDIAN_ORDER - #define GB_IS_BIG_EDIAN (!*(unsigned char*)&(unsigned short){1}) - #define GB_IS_LITTLE_EDIAN (!GB_IS_BIG_EDIAN) -#endif - -#ifndef GB_IS_POWER_OF_TWO -#define GB_IS_POWER_OF_TWO(x) ((x) != 0) && !((x) & ((x) - 1)) -#endif - - -#if !defined(GB_HAS_NO_CONSTEXPR) - #if defined(_GNUC_VER) && _GNUC_VER < 406 // Less than gcc 4.06 - #define GB_HAS_NO_CONSTEXPR 1 - #elif defined(_MSC_VER) && _MSC_VER < 1900 // Less than Visual Studio 2015/MSVC++ 14.0 - #define GB_HAS_NO_CONSTEXPR 1 - #elif !defined(__GXX_EXPERIMENTAL_CXX0X__) && __cplusplus < 201103L - #define GB_HAS_NO_CONSTEXPR 1 - #endif -#endif - -#if defined(GB_HAS_NO_CONSTEXPR) - #define GB_CONSTEXPR -#else - #define GB_CONSTEXPR constexpr -#endif - -#ifndef GB_FORCE_INLINE - #if defined(_MSC_VER) - #define GB_FORCE_INLINE __forceinline - #else - #define GB_FORCE_INLINE __attribute__ ((__always_inline__)) - #endif -#endif - -#if defined(GB_SYSTEM_WINDOWS) - #define NOMINMAX 1 - #define VC_EXTRALEAN 1 - #define WIN32_EXTRA_LEAN 1 - #define WIN32_LEAN_AND_MEAN 1 - - #include - #include - - #undef NOMINMAX - #undef VC_EXTRALEAN - #undef WIN32_EXTRA_LEAN - #undef WIN32_LEAN_AND_MEAN -#else - // -#endif - - -#if !defined(GB_ASSERT) - #if !defined(NDEBUG) - #define GB_ASSERT(x, ...) ((void)(::gb__assert_handler((x), #x, __FILE__, __LINE__, ##__VA_ARGS__))) - - /// Helper function used as a better alternative to assert which allows for - /// optional printf style error messages - extern "C" inline void - gb__assert_handler(bool condition, const char* condition_str, - const char* filename, size_t line, - const char* error_text = nullptr, ...) - { - if (condition) - return; - - fprintf(stderr, "ASSERT! %s(%lu): %s", filename, line, condition_str); - if (error_text) - { - fprintf(stderr, " - "); - - va_list args; - va_start(args, error_text); - vfprintf(stderr, error_text, args); - va_end(args); - } - fprintf(stderr, "\n"); - // TODO(bill): Get a better way to abort - *(int*)0 = 0; - } - - #else - #define GB_ASSERT(x, ...) ((void)sizeof(x)) - #endif -#endif - -#if !defined(__GB_NAMESPACE_PREFIX) && !defined(GB_NO_GB_NAMESPACE) - #define __GB_NAMESPACE_PREFIX gb -#else - #define __GB_NAMESPACE_PREFIX -#endif - -#if defined(GB_NO_GB_NAMESPACE) - #define __GB_NAMESPACE_START - #define __GB_NAMESPACE_END -#else - #define __GB_NAMESPACE_START namespace __GB_NAMESPACE_PREFIX { - #define __GB_NAMESPACE_END } // namespace __GB_NAMESPACE_PREFIX -#endif - - -#if !defined(GB_BASIC_WITHOUT_NAMESPACE) -__GB_NAMESPACE_START -#endif // GB_BASIC_WITHOUT_NAMESPACE - -//////////////////////////////// -/// /// -/// Types /// -/// /// -//////////////////////////////// - - -#ifndef GB_BASIC_TYPES -#define GB_BASIC_TYPES - #if defined(_MSC_VER) - using u8 = unsigned __int8; - using s8 = signed __int8; - using u16 = unsigned __int16; - using s16 = signed __int16; - using u32 = unsigned __int32; - using s32 = signed __int32; - using u64 = unsigned __int64; - using s64 = signed __int64; - #else - using u8 = unsigned char; - using s8 = signed char; - using u16 = unsigned short; - using s16 = signed short; - using u32 = unsigned int; - using s32 = signed int; - using u64 = unsigned long long; - using s64 = signed long long; - #endif - - static_assert( sizeof(u8) == 1, "u8 is not 8 bits"); - static_assert(sizeof(u16) == 2, "u16 is not 16 bits"); - static_assert(sizeof(u32) == 4, "u32 is not 32 bits"); - static_assert(sizeof(u64) == 8, "u64 is not 64 bits"); - - using f32 = float; - using f64 = double; - - #if defined(GB_B8_AS_BOOL) - using b8 = bool; - #else - using b8 = s8; - #endif - using b32 = s32; - - // NOTE(bill): (std::)size_t is not used not because it's a bad concept but on - // the platforms that I will be using: - // sizeof(size_t) == sizeof(usize) == sizeof(ssize) - // NOTE(bill): This also allows for a signed version of size_t which is similar - // to ptrdiff_t - // NOTE(bill): If (u)intptr is a better fit, please use that. - // NOTE(bill): Also, I hate the `_t` suffix - #if defined(GB_ARCH_64_BIT) - using ssize = s64; - using usize = u64; - #elif defined(GB_ARCH_32_BIT) - using usize = s32; - using usize = u32; - #else - #error Unknown architecture bit size - #endif - - static_assert(sizeof(usize) == sizeof(size_t), - "`usize` is not the same size as `size_t`"); - static_assert(sizeof(ssize) == sizeof(usize), - "`ssize` is not the same size as `usize`"); - - using intptr = intptr_t; - using uintptr = uintptr_t; - - using ptrdiff = ptrdiff_t; - -#endif - -#if !defined(GB_U8_MIN) - #define GB_U8_MIN 0u - #define GB_U8_MAX 0xffu - #define GB_S8_MIN (-0x7f - 1) - #define GB_S8_MAX 0x7f - - #define GB_U16_MIN 0u - #define GB_U16_MAX 0xffffu - #define GB_S16_MIN (-0x7fff - 1) - #define GB_S16_MAX 0x7fff - - #define GB_U32_MIN 0u - #define GB_U32_MAX 0xffffffffu - #define GB_S32_MIN (-0x7fffffff - 1) - #define GB_S32_MAX 0x7fffffff - - #define GB_U64_MIN 0ull - #define GB_U64_MAX 0xffffffffffffffffull - #define GB_S64_MIN (-0x7fffffffffffffffll - 1) - #define GB_S64_MAX 0x7fffffffffffffffll -#endif - -#if defined(GB_ARCH_64_BIT) && !defined(GB_USIZE_MIX) - #define GB_USIZE_MIX GB_U64_MIN - #define GB_USIZE_MAX GB_U64_MAX - - #define GB_SSIZE_MIX GB_S64_MIN - #define GB_SSIZE_MAX GB_S64_MAX -#elif defined(GB_ARCH_32_BIT) && !defined(GB_USIZE_MIX) - #define GB_USIZE_MIX GB_U32_MIN - #define GB_USIZE_MAX GB_U32_MAX - - #define GB_SSIZE_MIX GB_S32_MIN - #define GB_SSIZE_MAX GB_S32_MAX -#endif - -#if defined(GB_BASIC_WITHOUT_NAMESPACE) && !defined(U8_MIN) - #define U8_MIN 0u - #define U8_MAX 0xffu - #define S8_MIN (-0x7f - 1) - #define S8_MAX 0x7f - - #define U16_MIN 0u - #define U16_MAX 0xffffu - #define S16_MIN (-0x7fff - 1) - #define S16_MAX 0x7fff - - #define U32_MIN 0u - #define U32_MAX 0xffffffffu - #define S32_MIN (-0x7fffffff - 1) - #define S32_MAX 0x7fffffff - - #define U64_MIN 0ull - #define U64_MAX 0xffffffffffffffffull - #define S64_MIN (-0x7fffffffffffffffll - 1) - #define S64_MAX 0x7fffffffffffffffll - - #if defined(GB_ARCH_64_BIT) && !defined(GB_USIZE_MIX) - #define USIZE_MIX U64_MIN - #define USIZE_MAX U64_MAX - - #define SSIZE_MIX S64_MIN - #define SSIZE_MAX S64_MAX - #elif defined(GB_ARCH_32_BIT) && !defined(GB_USIZE_MIX) - #define USIZE_MIX U32_MIN - #define USIZE_MAX U32_MAX - - #define SSIZE_MIX S32_MIN - #define SSIZE_MAX S32_MAX - #endif -#endif - - - -#if !defined(GB_BASIC_WITHOUT_NAMESPACE) -__GB_NAMESPACE_END -#endif // GB_BASIC_WITHOUT_NAMESPACE - -__GB_NAMESPACE_START -#ifndef GB_SPECIAL_CASTS -#define GB_SPECIAL_CASTS - // IMPORTANT NOTE(bill): Very similar to doing `*(T*)(&u)` but easier/clearer to write - // however, it can be dangerous if sizeof(T) > sizeof(U) e.g. unintialized memory, undefined behavior - // *(T*)(&u) ~~ pseudo_cast(u) - template - inline T - pseudo_cast(U const& u) - { - return reinterpret_cast(u); - } - - // NOTE(bill): Very similar to doing `*(T*)(&u)` - template - inline Dest - bit_cast(Source const& source) - { - static_assert(sizeof(Dest) <= sizeof(Source), - "bit_cast(Source const&) - sizeof(Dest) <= sizeof(Source)"); - Dest dest; - ::memcpy(&dest, &source, sizeof(Dest)); - return dest; - } -#endif -// FORENOTE(bill): There used to be a magic_cast that was equivalent to -// a C-style cast but I removed it as I could not get it work as intented -// for everything using only C++ style casts - -#if !defined(GB_CASTS_WITHOUT_NAMESPACE) -__GB_NAMESPACE_END -#endif // GB_CASTS_WITHOUT_NAMESPACE - -__GB_NAMESPACE_START -//////////////////////////////// -/// /// -/// Math Types /// -/// /// -//////////////////////////////// - -// TODO(bill): Should the math part be a separate library? - -struct Vector2 -{ - union - { - struct { f32 x, y; }; - f32 data[2]; - }; - - inline f32 operator[](usize index) const { return data[index]; } - inline f32& operator[](usize index) { return data[index]; } -}; - -struct Vector3 -{ - union - { - struct { f32 x, y, z; }; - struct { f32 r, g, b; }; - Vector2 xy; - f32 data[3]; - }; - - inline f32 operator[](usize index) const { return data[index]; } - inline f32& operator[](usize index) { return data[index]; } -}; - -struct Vector4 -{ - union - { - struct { f32 x, y, z, w; }; - struct { f32 r, g, b, a; }; - struct { Vector2 xy, zw; }; - Vector3 xyz; - Vector3 rgb; - f32 data[4]; - }; - - inline f32 operator[](usize index) const { return data[index]; } - inline f32& operator[](usize index) { return data[index]; } -}; - -struct Complex -{ - union - { - struct { f32 x, y; }; - struct { f32 real, imag; }; - f32 data[2]; - }; - - inline f32 operator[](usize index) const { return data[index]; } - inline f32& operator[](usize index) { return data[index]; } -}; - -struct Quaternion -{ - union - { - struct { f32 x, y, z, w; }; - Vector3 xyz; - f32 data[4]; - }; - - inline f32 operator[](usize index) const { return data[index]; } - inline f32& operator[](usize index) { return data[index]; } -}; - -struct Matrix2 -{ - union - { - struct { Vector2 x, y; }; - Vector2 columns[2]; - f32 data[4]; - }; - - inline Vector2 operator[](usize index) const { return columns[index]; } - inline Vector2& operator[](usize index) { return columns[index]; } -}; - -struct Matrix3 -{ - union - { - struct { Vector3 x, y, z; }; - Vector3 columns[3]; - f32 data[9]; - }; - - inline Vector3 operator[](usize index) const { return columns[index]; } - inline Vector3& operator[](usize index) { return columns[index]; } -}; - -struct Matrix4 -{ - union - { - struct { Vector4 x, y, z, w; }; - Vector4 columns[4]; - f32 data[16]; - }; - - inline Vector4 operator[](usize index) const { return columns[index]; } - inline Vector4& operator[](usize index) { return columns[index]; } -}; - -struct Angle -{ - f32 radians; -}; - -struct Euler_Angles -{ - Angle pitch, yaw, roll; -}; - -struct Transform -{ - Vector3 position; - Quaternion orientation; - f32 scale; - // NOTE(bill): Scale is only f32 to make sizeof(Transform) == 32 bytes -}; - -struct Aabb -{ - Vector3 center; - Vector3 half_size; -}; - -struct Oobb -{ - Matrix4 transform; - Aabb aabb; -}; - -struct Sphere -{ - Vector3 center; - f32 radius; -}; - -struct Plane -{ - Vector3 normal; - f32 distance; // negative distance to origin -}; - -//////////////////////////////// -/// /// -/// Math Type Op Overloads /// -/// /// -//////////////////////////////// - -// Vector2 Operators -bool operator==(Vector2 a, Vector2 b); -bool operator!=(Vector2 a, Vector2 b); - -Vector2 operator+(Vector2 a); -Vector2 operator-(Vector2 a); - -Vector2 operator+(Vector2 a, Vector2 b); -Vector2 operator-(Vector2 a, Vector2 b); - -Vector2 operator*(Vector2 a, f32 scalar); -Vector2 operator*(f32 scalar, Vector2 a); - -Vector2 operator/(Vector2 a, f32 scalar); - -Vector2 operator*(Vector2 a, Vector2 b); // Hadamard Product -Vector2 operator/(Vector2 a, Vector2 b); // Hadamard Product - -Vector2& operator+=(Vector2& a, Vector2 b); -Vector2& operator-=(Vector2& a, Vector2 b); -Vector2& operator*=(Vector2& a, f32 scalar); -Vector2& operator/=(Vector2& a, f32 scalar); - -// Vector3 Operators -bool operator==(Vector3 a, Vector3 b); -bool operator!=(Vector3 a, Vector3 b); - -Vector3 operator+(Vector3 a); -Vector3 operator-(Vector3 a); - -Vector3 operator+(Vector3 a, Vector3 b); -Vector3 operator-(Vector3 a, Vector3 b); - -Vector3 operator*(Vector3 a, f32 scalar); -Vector3 operator*(f32 scalar, Vector3 a); - -Vector3 operator/(Vector3 a, f32 scalar); - -Vector3 operator*(Vector3 a, Vector3 b); // Hadamard Product -Vector3 operator/(Vector3 a, Vector3 b); // Hadamard Product - -Vector3& operator+=(Vector3& a, Vector3 b); -Vector3& operator-=(Vector3& a, Vector3 b); -Vector3& operator*=(Vector3& a, f32 scalar); -Vector3& operator/=(Vector3& a, f32 scalar); - -// Vector4 Operators -bool operator==(Vector4 a, Vector4 b); -bool operator!=(Vector4 a, Vector4 b); - -Vector4 operator+(Vector4 a); -Vector4 operator-(Vector4 a); - -Vector4 operator+(Vector4 a, Vector4 b); -Vector4 operator-(Vector4 a, Vector4 b); - -Vector4 operator*(Vector4 a, f32 scalar); -Vector4 operator*(f32 scalar, Vector4 a); - -Vector4 operator/(Vector4 a, f32 scalar); - -Vector4 operator*(Vector4 a, Vector4 b); // Hadamard Product -Vector4 operator/(Vector4 a, Vector4 b); // Hadamard Product - -Vector4& operator+=(Vector4& a, Vector4 b); -Vector4& operator-=(Vector4& a, Vector4 b); -Vector4& operator*=(Vector4& a, f32 scalar); -Vector4& operator/=(Vector4& a, f32 scalar); - -// Complex Operators -bool operator==(Complex a, Complex b); -bool operator!=(Complex a, Complex b); - -Complex operator+(Complex a); -Complex operator-(Complex a); - -Complex operator+(Complex a, Complex b); -Complex operator-(Complex a, Complex b); - -Complex operator*(Complex a, Complex b); -Complex operator*(Complex a, f32 s); -Complex operator*(f32 s, Complex a); - -Complex operator/(Complex a, f32 s); - -// Quaternion Operators -bool operator==(Quaternion a, Quaternion b); -bool operator!=(Quaternion a, Quaternion b); - -Quaternion operator+(Quaternion a); -Quaternion operator-(Quaternion a); - -Quaternion operator+(Quaternion a, Quaternion b); -Quaternion operator-(Quaternion a, Quaternion b); - -Quaternion operator*(Quaternion a, Quaternion b); -Quaternion operator*(Quaternion a, f32 s); -Quaternion operator*(f32 s, Quaternion a); - -Quaternion operator/(Quaternion a, f32 s); - -Vector3 operator*(Quaternion a, Vector3 v); // Rotate v by a - -// Matrix2 Operators -bool operator==(Matrix2 a, Matrix2 b); -bool operator!=(Matrix2 a, Matrix2 b); - -Matrix2 operator+(Matrix2 a); -Matrix2 operator-(Matrix2 a); - -Matrix2 operator+(Matrix2 a, Matrix2 b); -Matrix2 operator-(Matrix2 a, Matrix2 b); - -Matrix2 operator*(Matrix2 a, Matrix2 b); -Vector2 operator*(Matrix2 a, Vector2 v); -Matrix2 operator*(Matrix2 a, f32 scalar); -Matrix2 operator*(f32 scalar, Matrix2 a); - -Matrix2 operator/(Matrix2 a, f32 scalar); - -Matrix2& operator+=(Matrix2& a, Matrix2 b); -Matrix2& operator-=(Matrix2& a, Matrix2 b); -Matrix2& operator*=(Matrix2& a, Matrix2 b); - -// Matrix3 Operators -bool operator==(Matrix3 const& a, Matrix3 const& b); -bool operator!=(Matrix3 const& a, Matrix3 const& b); - -Matrix3 operator+(Matrix3 const& a); -Matrix3 operator-(Matrix3 const& a); - -Matrix3 operator+(Matrix3 const& a, Matrix3 const& b); -Matrix3 operator-(Matrix3 const& a, Matrix3 const& b); - -Matrix3 operator*(Matrix3 const& a, Matrix3 const& b); -Vector3 operator*(Matrix3 const& a, Vector3 v); -Matrix3 operator*(Matrix3 const& a, f32 scalar); -Matrix3 operator*(f32 scalar, Matrix3 const& a); - -Matrix3 operator/(Matrix3 const& a, f32 scalar); - -Matrix3& operator+=(Matrix3& a, Matrix3 const& b); -Matrix3& operator-=(Matrix3& a, Matrix3 const& b); -Matrix3& operator*=(Matrix3& a, Matrix3 const& b); - -// Matrix4 Operators -bool operator==(Matrix4 const& a, Matrix4 const& b); -bool operator!=(Matrix4 const& a, Matrix4 const& b); - -Matrix4 operator+(Matrix4 const& a); -Matrix4 operator-(Matrix4 const& a); - -Matrix4 operator+(Matrix4 const& a, Matrix4 const& b); -Matrix4 operator-(Matrix4 const& a, Matrix4 const& b); - -Matrix4 operator*(Matrix4 const& a, Matrix4 const& b); -Vector4 operator*(Matrix4 const& a, Vector4 v); -Matrix4 operator*(Matrix4 const& a, f32 scalar); -Matrix4 operator*(f32 scalar, Matrix4 const& a); - -Matrix4 operator/(Matrix4 const& a, f32 scalar); - -Matrix4& operator+=(Matrix4& a, Matrix4 const& b); -Matrix4& operator-=(Matrix4& a, Matrix4 const& b); -Matrix4& operator*=(Matrix4& a, Matrix4 const& b); - -// Angle Operators -bool operator==(Angle a, Angle b); -bool operator!=(Angle a, Angle b); - -Angle operator+(Angle a); -Angle operator-(Angle a); - -Angle operator+(Angle a, Angle b); -Angle operator-(Angle a, Angle b); - -Angle operator*(Angle a, f32 scalar); -Angle operator*(f32 scalar, Angle a); - -Angle operator/(Angle a, f32 scalar); - -f32 operator/(Angle a, Angle b); - -Angle& operator+=(Angle& a, Angle b); -Angle& operator-=(Angle& a, Angle b); -Angle& operator*=(Angle& a, f32 scalar); -Angle& operator/=(Angle& a, f32 scalar); - -// Transform Operators -// World = Parent * Local -Transform operator*(Transform const& ps, Transform const& ls); -Transform& operator*=(Transform& ps, Transform const& ls); -// Local = World / Parent -Transform operator/(Transform const& ws, Transform const& ps); -Transform& operator/=(Transform& ws, Transform const& ps); - -namespace angle -{ -Angle radians(f32 r); -Angle degrees(f32 d); -Angle turns(f32 t); -Angle grads(f32 g); -Angle gons(f32 g); - -f32 as_radians(Angle a); -f32 as_degrees(Angle a); -f32 as_turns(Angle a); -f32 as_grads(Angle a); -f32 as_gons(Angle a); -} // namespace angle - -////////////////////////////////// -/// /// -/// Math Functions & Constants /// -/// /// -////////////////////////////////// -extern Vector2 const VECTOR2_ZERO; -extern Vector3 const VECTOR3_ZERO; -extern Vector4 const VECTOR4_ZERO; -extern Complex const COMPLEX_ZERO; -extern Quaternion const QUATERNION_IDENTITY; -extern Matrix2 const MATRIX2_IDENTITY; -extern Matrix3 const MATRIX3_IDENTITY; -extern Matrix4 const MATRIX4_IDENTITY; -extern Euler_Angles const EULER_ANGLES_ZERO; -extern Transform const TRANSFORM_IDENTITY; - -namespace math -{ -extern f32 const ZERO; -extern f32 const ONE; -extern f32 const THIRD; -extern f32 const TWO_THIRDS; -extern f32 const E; -extern f32 const PI; -extern f32 const TAU; -extern f32 const SQRT_2; -extern f32 const SQRT_3; -extern f32 const SQRT_5; - -extern f32 const F32_PRECISION; - -// Power -f32 sqrt(f32 x); -f32 pow(f32 x, f32 y); -f32 cbrt(f32 x); -f32 fast_inv_sqrt(f32 x); - -// Trigonometric -f32 sin(Angle a); -f32 cos(Angle a); -f32 tan(Angle a); - -Angle arcsin(f32 x); -Angle arccos(f32 x); -Angle arctan(f32 x); -Angle arctan2(f32 y, f32 x); - -// Hyperbolic -f32 sinh(f32 x); -f32 cosh(f32 x); -f32 tanh(f32 x); - -f32 arsinh(f32 x); -f32 arcosh(f32 x); -f32 artanh(f32 x); - -// Rounding -f32 ceil(f32 x); -f32 floor(f32 x); -f32 mod(f32 x, f32 y); -f32 truncate(f32 x); -f32 round(f32 x); - -s32 sign(s32 x); -s64 sign(s64 x); -f32 sign(f32 x); - -// Other -f32 abs(f32 x); -s8 abs( s8 x); -s16 abs(s16 x); -s32 abs(s32 x); -s64 abs(s64 x); - -bool is_infinite(f32 x); -bool is_nan(f32 x); - -s32 kronecker_delta(s32 i, s32 j); -s64 kronecker_delta(s64 i, s64 j); -f32 kronecker_delta(f32 i, f32 j); - -// NOTE(bill): Just incase -#undef min -#undef max - -f32 min(f32 x, f32 y); -s32 min(s32 x, s32 y); -s64 min(s64 x, s64 y); - -f32 max(f32 x, f32 y); -s32 max(s32 x, s32 y); -s64 max(s64 x, s64 y); - -f32 clamp(f32 x, f32 min, f32 max); -s32 clamp(s32 x, s32 min, s32 max); -s64 clamp(s64 x, s64 min, s64 max); - -// TODO(bill): Should this be a template or just normal function overloading? -template -T lerp(T const& x, T const& y, f32 t); - -bool equals(f32 a, f32 b, f32 precision = F32_PRECISION); - -// Vector2 functions -f32 dot(Vector2 a, Vector2 b); -f32 cross(Vector2 a, Vector2 b); - -f32 magnitude(Vector2 a); -Vector2 normalize(Vector2 a); - -Vector2 hadamard(Vector2 a, Vector2 b); - -f32 aspect_ratio(Vector2 a); - -// Vector3 functions -f32 dot(Vector3 a, Vector3 b); -Vector3 cross(Vector3 a, Vector3 b); - -f32 magnitude(Vector3 a); -Vector3 normalize(Vector3 a); - -Vector3 hadamard(Vector3 a, Vector3 b); - -// Vector4 functions -f32 dot(Vector4 a, Vector4 b); - -f32 magnitude(Vector4 a); -Vector4 normalize(Vector4 a); - -Vector4 hadamard(Vector4 a, Vector4 b); - -// Complex functions -f32 dot(Complex a, Complex b); - -f32 magnitude(Complex a); -f32 norm(Complex a); -Complex normalize(Complex a); - -Complex conjugate(Complex a); -Complex inverse(Complex a); - -f32 complex_angle(Complex a); -inline f32 complex_argument(Complex a) { return complex_angle(a); } -Complex magnitude_angle(f32 magnitude, Angle a); -inline Complex complex_polar(f32 magnitude, Angle a) { return magnitude_angle(magnitude, a); } - -// Quaternion functions -f32 dot(Quaternion a, Quaternion b); -Quaternion cross(Quaternion a, Quaternion b); - -f32 magnitude(Quaternion a); -f32 norm(Quaternion a); -Quaternion normalize(Quaternion a); - -Quaternion conjugate(Quaternion a); -Quaternion inverse(Quaternion a); - -Angle quaternion_angle(Quaternion a); -Vector3 quaternion_axis(Quaternion a); -Quaternion axis_angle(Vector3 axis, Angle a); - -Angle quaternion_roll(Quaternion a); -Angle quaternion_pitch(Quaternion a); -Angle quaternion_yaw(Quaternion a); - -Euler_Angles quaternion_to_euler_angles(Quaternion a); -Quaternion euler_angles_to_quaternion(Euler_Angles const& e, - Vector3 x_axis = {1, 0, 0}, - Vector3 y_axis = {0, 1, 0}, - Vector3 z_axis = {0, 0, 1}); - -// Spherical Linear Interpolation -Quaternion slerp(Quaternion x, Quaternion y, f32 t); - -// Shoemake's Quaternion Curves -// Sqherical Cubic Interpolation -Quaternion squad(Quaternion p, - Quaternion a, - Quaternion b, - Quaternion q, - f32 t); -// Matrix2 functions -Matrix2 transpose(Matrix2 m); -f32 determinant(Matrix2 m); -Matrix2 inverse(Matrix2 m); -Matrix2 hadamard(Matrix2 a, const Matrix2&b); -Matrix4 matrix2_to_matrix4(Matrix2 m); - -// Matrix3 functions -Matrix3 transpose(Matrix3 const& m); -f32 determinant(Matrix3 const& m); -Matrix3 inverse(Matrix3 const& m); -Matrix3 hadamard(Matrix3 const& a, const Matrix3&b); -Matrix4 matrix3_to_matrix4(Matrix3 const& m); - -// Matrix4 functions -Matrix4 transpose(Matrix4 const& m); -f32 determinant(Matrix4 const& m); -Matrix4 inverse(Matrix4 const& m); -Matrix4 hadamard(Matrix4 const& a, const Matrix4&b); -bool is_affine(Matrix4 const& m); - -Matrix4 quaternion_to_matrix4(Quaternion a); -Quaternion matrix4_to_quaternion(Matrix4 const& m); - -Matrix4 translate(Vector3 v); -Matrix4 rotate(Vector3 v, Angle angle); -Matrix4 scale(Vector3 v); -Matrix4 ortho(f32 left, f32 right, f32 bottom, f32 top); -Matrix4 ortho(f32 left, f32 right, f32 bottom, f32 top, f32 z_near, f32 z_far); -Matrix4 perspective(Angle fovy, f32 aspect, f32 z_near, f32 z_far); -Matrix4 infinite_perspective(Angle fovy, f32 aspect, f32 z_near); - -Matrix4 -look_at_matrix4(Vector3 eye, Vector3 center, Vector3 up = {0, 1, 0}); - -Quaternion -look_at_quaternion(Vector3 eye, Vector3 center, Vector3 up = {0, 1, 0}); - -// Transform Functions -Vector3 transform_point(Transform const& transform, Vector3 point); -Transform inverse(Transform const& t); -Matrix4 transform_to_matrix4(Transform const& t); -} // namespace math - -namespace aabb -{ -Aabb calculate(void const* vertices, usize num_vertices, usize stride, usize offset); - -f32 surface_area(Aabb const& aabb); -f32 volume(Aabb const& aabb); - -Sphere to_sphere(Aabb const& aabb); - -bool contains(Aabb const& aabb, Vector3 point); -bool contains(Aabb const& a, Aabb const& b); -bool intersects(Aabb const& a, Aabb const& b); - -Aabb transform_affine(Aabb const& aabb, Matrix4 const& m); -} // namespace aabb - -namespace sphere -{ -Sphere calculate_min_bounding_sphere(void const* vertices, usize num_vertices, usize stride, usize offset, f32 step); -Sphere calculate_max_bounding_sphere(void const* vertices, usize num_vertices, usize stride, usize offset); - -f32 surface_area(Sphere s); -f32 volume(Sphere s); - -Aabb to_aabb(Sphere sphere); - -bool contains_point(Sphere s, Vector3 point); - -f32 ray_intersection(Vector3 from, Vector3 dir, Sphere s); -} // namespace sphere - -namespace plane -{ -f32 ray_intersection(Vector3 from, Vector3 dir, Plane p); - -bool intersection3(Plane p1, Plane p2, Plane p3, Vector3* ip); -} // namespace plane - - -#if !defined(GB_MATH_NO_RANDOM) - -namespace random -{ -struct Random // NOTE(bill): Mt19937_64 -{ - s64 seed; - u32 index; - s64 mt[312]; -}; - -Random make(s64 seed); - -void set_seed(Random* r, s64 seed); - -s64 next(Random* r); - -void next_from_device(void* buffer, u32 length_in_bytes); - -s32 next_s32(Random* r); -u32 next_u32(Random* r); -f32 next_f32(Random* r); -s64 next_s64(Random* r); -u64 next_u64(Random* r); -f64 next_f64(Random* r); - -s32 uniform_s32(Random* r, s32 min_inc, s32 max_inc); -u32 uniform_u32(Random* r, u32 min_inc, u32 max_inc); -f32 uniform_f32(Random* r, f32 min_inc, f32 max_inc); -s64 uniform_s64(Random* r, s64 min_inc, s64 max_inc); -u64 uniform_u64(Random* r, u64 min_inc, u64 max_inc); -f64 uniform_f64(Random* r, f64 min_inc, f64 max_inc); - - -// TODO(bill): Should these noise functions be in the `random` module? -f32 perlin_3d(f32 x, f32 y, f32 z, s32 x_wrap = 0, s32 y_wrap = 0, s32 z_wrap = 0); - -// TODO(bill): Implement simplex noise -// f32 simplex_2d_octave(f32 x, f32 y, f32 octaves, f32 persistence, f32 scale); -// f32 simplex_3d_octave(f32 x, f32 y, f32 z, f32 octaves, f32 persistence, f32 scale); -// f32 simplex_4d_octave(f32 x, f32 y, f32 z, f32 w, f32 octaves, f32 persistence, f32 scale); - -} // namespace random - -#endif - -namespace math -{ -template inline T lerp(T const& x, T const& y, f32 t) { return x + (y - x) * t; } -} // namespace math - -__GB_NAMESPACE_END - -#endif // GB_INCLUDE_GB_HPP - -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// So long and thanks for all the fish! -/// -/// -/// -/// -/// -//////////////////////////////// -/// /// -/// Implemenation /// -/// /// -//////////////////////////////// -#if defined(GB_MATH_IMPLEMENTATION) - -#include - -__GB_NAMESPACE_START - -//////////////////////////////// -/// /// -/// Math /// -/// /// -//////////////////////////////// - -Vector2 const VECTOR2_ZERO = Vector2{0, 0}; -Vector3 const VECTOR3_ZERO = Vector3{0, 0, 0}; -Vector4 const VECTOR4_ZERO = Vector4{0, 0, 0, 0}; -Complex const COMPLEX_ZERO = Complex{0, 0}; -Quaternion const QUATERNION_IDENTITY = Quaternion{0, 0, 0, 1}; -Matrix2 const MATRIX2_IDENTITY = Matrix2{1, 0, - 0, 1}; -Matrix3 const MATRIX3_IDENTITY = Matrix3{1, 0, 0, - 0, 1, 0, - 0, 0, 1}; -Matrix4 const MATRIX4_IDENTITY = Matrix4{1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1}; -Euler_Angles const EULER_ANGLES_ZERO = Euler_Angles{0, 0, 0}; -Transform const TRANSFORM_IDENTITY = Transform{VECTOR3_ZERO, QUATERNION_IDENTITY, 1}; - -//////////////////////////////// -/// Math Type Op Overloads /// -//////////////////////////////// - -// Vector2 Operators -inline bool -operator==(Vector2 a, Vector2 b) -{ - return (a.x == b.x) && (a.y == b.y); -} - -inline bool -operator!=(Vector2 a, Vector2 b) -{ - return !operator==(a, b); -} - -inline Vector2 -operator+(Vector2 a) -{ - return a; -} - -inline Vector2 -operator-(Vector2 a) -{ - return {-a.x, -a.y}; -} - -inline Vector2 -operator+(Vector2 a, Vector2 b) -{ - return {a.x + b.x, a.y + b.y}; -} - -inline Vector2 -operator-(Vector2 a, Vector2 b) -{ - return {a.x - b.x, a.y - b.y}; -} - -inline Vector2 -operator*(Vector2 a, f32 scalar) -{ - return {a.x * scalar, a.y * scalar}; -} - -inline Vector2 -operator*(f32 scalar, Vector2 a) -{ - return {a.x * scalar, a.y * scalar}; -} - -inline Vector2 -operator/(Vector2 a, f32 scalar) -{ - return {a.x / scalar, a.y / scalar}; -} - -inline Vector2 -operator*(Vector2 a, Vector2 b) // Hadamard Product -{ - return {a.x * b.x, a.y * b.y}; -} - -inline Vector2 -operator/(Vector2 a, Vector2 b) // Hadamard Product -{ - return {a.x / b.x, a.y / b.y}; -} - -inline Vector2& -operator+=(Vector2& a, Vector2 b) -{ - a.x += b.x; - a.y += b.y; - - return a; -} - -inline Vector2& -operator-=(Vector2& a, Vector2 b) -{ - a.x -= b.x; - a.y -= b.y; - - return a; -} - -inline Vector2& -operator*=(Vector2& a, f32 scalar) -{ - a.x *= scalar; - a.y *= scalar; - - return a; -} - -inline Vector2& -operator/=(Vector2& a, f32 scalar) -{ - a.x /= scalar; - a.y /= scalar; - - return a; -} - -// Vector3 Operators -inline bool -operator==(Vector3 a, Vector3 b) -{ - return (a.x == b.x) && (a.y == b.y) && (a.z == b.z); -} - -inline bool -operator!=(Vector3 a, Vector3 b) -{ - return !operator==(a, b); -} - -inline Vector3 -operator+(Vector3 a) -{ - return a; -} - -inline Vector3 -operator-(Vector3 a) -{ - return {-a.x, -a.y, -a.z}; -} - -inline Vector3 -operator+(Vector3 a, Vector3 b) -{ - return {a.x + b.x, a.y + b.y, a.z + b.z}; -} - -inline Vector3 -operator-(Vector3 a, Vector3 b) -{ - return {a.x - b.x, a.y - b.y, a.z - b.z}; -} - -inline Vector3 -operator*(Vector3 a, f32 scalar) -{ - return {a.x * scalar, a.y * scalar, a.z * scalar}; -} - -inline Vector3 -operator*(f32 scalar, Vector3 a) -{ - return {a.x * scalar, a.y * scalar, a.z * scalar}; -} - -inline Vector3 -operator/(Vector3 a, f32 scalar) -{ - return {a.x / scalar, a.y / scalar, a.z / scalar}; -} - -inline Vector3 -operator*(Vector3 a, Vector3 b) // Hadamard Product -{ - return {a.x * b.x, a.y * b.y, a.z * b.z}; -} - -inline Vector3 -operator/(Vector3 a, Vector3 b) // Hadamard Product -{ - return {a.x / b.x, a.y / b.y, a.z / b.z}; -} - -inline Vector3& -operator+=(Vector3& a, Vector3 b) -{ - a.x += b.x; - a.y += b.y; - a.z += b.z; - - return a; -} - -inline Vector3& -operator-=(Vector3& a, Vector3 b) -{ - a.x -= b.x; - a.y -= b.y; - a.z -= b.z; - - return a; -} - -inline Vector3& -operator*=(Vector3& a, f32 scalar) -{ - a.x *= scalar; - a.y *= scalar; - a.z *= scalar; - - return a; -} - -inline Vector3& -operator/=(Vector3& a, f32 scalar) -{ - a.x /= scalar; - a.y /= scalar; - a.z /= scalar; - - return a; -} - -// Vector4 Operators -inline bool -operator==(Vector4 a, Vector4 b) -{ - return (a.x == b.x) && (a.y == b.y) && (a.z == b.z) && (a.w == b.w); -} - -inline bool -operator!=(Vector4 a, Vector4 b) -{ - return !operator==(a, b); -} - -inline Vector4 -operator+(Vector4 a) -{ - return a; -} - -inline Vector4 -operator-(Vector4 a) -{ - return {-a.x, -a.y, -a.z, -a.w}; -} - -inline Vector4 -operator+(Vector4 a, Vector4 b) -{ - return {a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w}; -} - -inline Vector4 -operator-(Vector4 a, Vector4 b) -{ - return {a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w}; -} - -inline Vector4 -operator*(Vector4 a, f32 scalar) -{ - return {a.x * scalar, a.y * scalar, a.z * scalar, a.w * scalar}; -} - -inline Vector4 -operator*(f32 scalar, Vector4 a) -{ - return {a.x * scalar, a.y * scalar, a.z * scalar, a.w * scalar}; -} - -inline Vector4 -operator/(Vector4 a, f32 scalar) -{ - return {a.x / scalar, a.y / scalar, a.z / scalar, a.w / scalar}; -} - -inline Vector4 -operator*(Vector4 a, Vector4 b) // Hadamard Product -{ - return {a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w}; -} - -inline Vector4 -operator/(Vector4 a, Vector4 b) // Hadamard Product -{ - return {a.x / b.x, a.y / b.y, a.z / b.z, a.w / b.w}; -} - -inline Vector4& -operator+=(Vector4& a, Vector4 b) -{ - a.x += b.x; - a.y += b.y; - a.z += b.z; - a.w += b.w; - - return a; -} - -inline Vector4& -operator-=(Vector4& a, Vector4 b) -{ - a.x -= b.x; - a.y -= b.y; - a.z -= b.z; - a.w -= b.w; - - return a; -} - -inline Vector4& -operator*=(Vector4& a, f32 scalar) -{ - a.x *= scalar; - a.y *= scalar; - a.z *= scalar; - a.w *= scalar; - - return a; -} - -inline Vector4& -operator/=(Vector4& a, f32 scalar) -{ - a.x /= scalar; - a.y /= scalar; - a.z /= scalar; - a.w /= scalar; - - return a; -} - -// Complex Operators -inline bool -operator==(Complex a, Complex b) -{ - return (a.x == b.x) && (a.y == b.y); -} - -inline bool -operator!=(Complex a, Complex b) -{ - return !operator==(a, b); -} - -inline Complex -operator+(Complex a) -{ - return a; -} - -inline Complex -operator-(Complex a) -{ - return {-a.x, -a.y}; -} - -inline Complex -operator+(Complex a, Complex b) -{ - return {a.x + b.x, a.y + b.y}; -} - -inline Complex -operator-(Complex a, Complex b) -{ - return {a.x - b.x, a.y - b.y}; - -} - -inline Complex -operator*(Complex a, Complex b) -{ - Complex c = {}; - - c.x = a.x * b.x - a.y * b.y; - c.y = a.y * b.x - a.y * b.x; - - return c; -} - -inline Complex -operator*(Complex a, f32 s) -{ - return {a.x * s, a.y * s}; -} - -inline Complex -operator*(f32 s, Complex a) -{ - return {a.x * s, a.y * s}; -} - -inline Complex -operator/(Complex a, f32 s) -{ - return {a.x / s, a.y / s}; -} - -// Quaternion Operators -inline bool -operator==(Quaternion a, Quaternion b) -{ - return (a.x == b.x) && (a.y == b.y) && (a.z == b.z) && (a.w == b.w); -} - -inline bool -operator!=(Quaternion a, Quaternion b) -{ - return !operator==(a, b); -} - -inline Quaternion -operator+(Quaternion a) -{ - return {+a.x, +a.y, +a.z, +a.w}; -} - -inline Quaternion -operator-(Quaternion a) -{ - return {-a.x, -a.y, -a.z, -a.w}; -} - -inline Quaternion -operator+(Quaternion a, Quaternion b) -{ - return {a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w}; -} - -inline Quaternion -operator-(Quaternion a, Quaternion b) -{ - return {a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w}; - -} - -inline Quaternion -operator*(Quaternion a, Quaternion b) -{ - Quaternion q = {}; - - q.x = a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y; - q.y = a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x; - q.z = a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w; - q.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z; - - return q; -} - -inline Quaternion -operator*(Quaternion a, f32 s) -{ - return {a.x * s, a.y * s, a.z * s, a.w * s}; -} - -inline Quaternion -operator*(f32 s, Quaternion a) -{ - return {a.x * s, a.y * s, a.z * s, a.w * s}; -} - -inline Quaternion -operator/(Quaternion a, f32 s) -{ - return {a.x / s, a.y / s, a.z / s, a.w / s}; -} - -inline Vector3 -operator*(Quaternion a, Vector3 v) // Rotate v by q -{ - // return (q * Quaternion{v.x, v.y, v.z, 0} * math::conjugate(q)).xyz; // More Expensive - const Vector3 t = 2.0f * math::cross(a.xyz, v); - return (v + a.w * t + math::cross(a.xyz, t)); -} - -// Matrix2 Operators -inline bool -operator==(Matrix2 a, Matrix2 b) -{ - for (usize i = 0; i < 4; i++) - { - if (a[i] != b[i]) - return false; - } - return true; -} - -inline bool -operator!=(Matrix2 a, Matrix2 b) -{ - return !operator==(a, b); -} - -inline Matrix2 -operator+(Matrix2 a) -{ - return a; -} - -inline Matrix2 -operator-(Matrix2 a) -{ - return {-a.x, -a.y}; -} - -inline Matrix2 -operator+(Matrix2 a, Matrix2 b) -{ - Matrix2 mat; - mat[0] = a[0] + b[0]; - mat[1] = a[1] + b[1]; - return mat; -} - -inline Matrix2 -operator-(Matrix2 a, Matrix2 b) -{ - Matrix2 mat; - mat[0] = a[0] - b[0]; - mat[1] = a[1] - b[1]; - return mat; -} - -inline Matrix2 -operator*(Matrix2 a, Matrix2 b) -{ - Matrix2 result; - result[0] = a[0] * b[0][0] + a[1] * b[0][1]; - result[1] = a[0] * b[1][0] + a[1] * b[1][1]; - return result; -} - -inline Vector2 -operator*(Matrix2 a, Vector2 v) -{ - return Vector2{a[0][0] * v.x + a[1][0] * v.y, - a[0][1] * v.x + a[1][1] * v.y}; -} - -inline Matrix2 -operator*(Matrix2 a, f32 scalar) -{ - Matrix2 mat; - mat[0] = a[0] * scalar; - mat[1] = a[1] * scalar; - return mat; -} - -inline Matrix2 -operator*(f32 scalar, Matrix2 a) -{ - Matrix2 mat; - mat[0] = a[0] * scalar; - mat[1] = a[1] * scalar; - return mat; -} - -inline Matrix2 -operator/(Matrix2 a, f32 scalar) -{ - Matrix2 mat; - mat[0] = a[0] / scalar; - mat[1] = a[1] / scalar; - return mat; -} - -inline Matrix2& -operator+=(Matrix2& a, Matrix2 b) -{ - return (a = a + b); -} - -inline Matrix2& -operator-=(Matrix2& a, Matrix2 b) -{ - return (a = a - b); -} - -inline Matrix2& -operator*=(Matrix2& a, Matrix2 b) -{ - return (a = a * b); -} - - -// Matrix3 Operators -inline bool -operator==(Matrix3 const& a, Matrix3 const& b) -{ - for (usize i = 0; i < 3; i++) - { - if (a[i] != b[i]) - return false; - } - return true; -} - -inline bool -operator!=(Matrix3 const& a, Matrix3 const& b) -{ - return !operator==(a, b); -} - -inline Matrix3 -operator+(Matrix3 const& a) -{ - return a; -} - -inline Matrix3 -operator-(Matrix3 const& a) -{ - return {-a.x, -a.y, -a.z}; -} - -inline Matrix3 -operator+(Matrix3 const& a, Matrix3 const& b) -{ - Matrix3 mat; - mat[0] = a[0] + b[0]; - mat[1] = a[1] + b[1]; - mat[2] = a[2] + b[2]; - return mat; -} - -inline Matrix3 -operator-(Matrix3 const& a, Matrix3 const& b) -{ - Matrix3 mat; - mat[0] = a[0] - b[0]; - mat[1] = a[1] - b[1]; - mat[2] = a[2] - b[2]; - return mat; -} - -inline Matrix3 -operator*(Matrix3 const& a, Matrix3 const& b) -{ - Matrix3 result; - result[0] = a[0] * b[0][0] + a[1] * b[0][1] + a[2] * b[0][2]; - result[1] = a[0] * b[1][0] + a[1] * b[1][1] + a[2] * b[1][2]; - result[2] = a[0] * b[2][0] + a[1] * b[2][1] + a[2] * b[2][2]; - return result; -} - -inline Vector3 -operator*(Matrix3 const& a, Vector3 v) -{ - return Vector3{a[0][0] * v.x + a[1][0] * v.y + a[2][0] * v.z, - a[0][1] * v.x + a[1][1] * v.y + a[2][1] * v.z, - a[0][2] * v.x + a[1][2] * v.y + a[2][2] * v.z}; -} - -inline Matrix3 -operator*(Matrix3 const& a, f32 scalar) -{ - Matrix3 mat; - mat[0] = a[0] * scalar; - mat[1] = a[1] * scalar; - mat[2] = a[2] * scalar; - return mat; -} - -inline Matrix3 -operator*(f32 scalar, Matrix3 const& a) -{ - Matrix3 mat; - mat[0] = a[0] * scalar; - mat[1] = a[1] * scalar; - mat[2] = a[2] * scalar; - return mat; -} - -inline Matrix3 -operator/(Matrix3 const& a, f32 scalar) -{ - Matrix3 mat; - mat[0] = a[0] / scalar; - mat[1] = a[1] / scalar; - mat[2] = a[2] / scalar; - return mat; -} - -inline Matrix3& -operator+=(Matrix3& a, Matrix3 const& b) -{ - return (a = a + b); -} - -inline Matrix3& -operator-=(Matrix3& a, Matrix3 const& b) -{ - return (a = a - b); -} - -inline Matrix3& -operator*=(Matrix3& a, Matrix3 const& b) -{ - return (a = a * b); -} - - -// Matrix4 Operators -inline bool -operator==(Matrix4 const& a, Matrix4 const& b) -{ - for (usize i = 0; i < 4; i++) - { - if (a[i] != b[i]) - return false; - } - return true; -} - -inline bool -operator!=(Matrix4 const& a, Matrix4 const& b) -{ - return !operator==(a, b); -} - -inline Matrix4 -operator+(Matrix4 const& a) -{ - return a; -} - -inline Matrix4 -operator-(Matrix4 const& a) -{ - return {-a.x, -a.y, -a.z, -a.w}; -} - -inline Matrix4 -operator+(Matrix4 const& a, Matrix4 const& b) -{ - Matrix4 mat; - mat[0] = a[0] + b[0]; - mat[1] = a[1] + b[1]; - mat[2] = a[2] + b[2]; - mat[3] = a[3] + b[3]; - return mat; -} - -inline Matrix4 -operator-(Matrix4 const& a, Matrix4 const& b) -{ - Matrix4 mat; - mat[0] = a[0] - b[0]; - mat[1] = a[1] - b[1]; - mat[2] = a[2] - b[2]; - mat[3] = a[3] - b[3]; - return mat; -} - -inline Matrix4 -operator*(Matrix4 const& a, Matrix4 const& b) -{ - Matrix4 result; - result[0] = a[0] * b[0][0] + a[1] * b[0][1] + a[2] * b[0][2] + a[3] * b[0][3]; - result[1] = a[0] * b[1][0] + a[1] * b[1][1] + a[2] * b[1][2] + a[3] * b[1][3]; - result[2] = a[0] * b[2][0] + a[1] * b[2][1] + a[2] * b[2][2] + a[3] * b[2][3]; - result[3] = a[0] * b[3][0] + a[1] * b[3][1] + a[2] * b[3][2] + a[3] * b[3][3]; - return result; -} - -inline Vector4 -operator*(Matrix4 const& a, Vector4 v) -{ - return Vector4{a[0][0] * v.x + a[1][0] * v.y + a[2][0] * v.z + a[3][0] * v.w, - a[0][1] * v.x + a[1][1] * v.y + a[2][1] * v.z + a[3][1] * v.w, - a[0][2] * v.x + a[1][2] * v.y + a[2][2] * v.z + a[3][2] * v.w, - a[0][3] * v.x + a[1][3] * v.y + a[2][3] * v.z + a[3][3] * v.w}; -} - -inline Matrix4 -operator*(Matrix4 const& a, f32 scalar) -{ - Matrix4 mat; - mat[0] = a[0] * scalar; - mat[1] = a[1] * scalar; - mat[2] = a[2] * scalar; - mat[3] = a[3] * scalar; - return mat; -} - -inline Matrix4 -operator*(f32 scalar, Matrix4 const& a) -{ - Matrix4 mat; - mat[0] = a[0] * scalar; - mat[1] = a[1] * scalar; - mat[2] = a[2] * scalar; - mat[3] = a[3] * scalar; - return mat; -} - -inline Matrix4 -operator/(Matrix4 const& a, f32 scalar) -{ - Matrix4 mat; - mat[0] = a[0] / scalar; - mat[1] = a[1] / scalar; - mat[2] = a[2] / scalar; - mat[3] = a[3] / scalar; - return mat; -} - -inline Matrix4& -operator+=(Matrix4& a, Matrix4 const& b) -{ - return (a = a + b); -} - -inline Matrix4& -operator-=(Matrix4& a, Matrix4 const& b) -{ - return (a = a - b); -} - -inline Matrix4& -operator*=(Matrix4& a, Matrix4 const& b) -{ - return (a = a * b); -} - -// Angle Operators -inline bool -operator==(Angle a, Angle b) -{ - return a.radians == b.radians; -} - -inline bool -operator!=(Angle a, Angle b) -{ - return !operator==(a, b); -} - -inline Angle -operator+(Angle a) -{ - return {+a.radians}; -} - -inline Angle -operator-(Angle a) -{ - return {-a.radians}; -} - -inline Angle -operator+(Angle a, Angle b) -{ - return {a.radians + b.radians}; -} - -inline Angle -operator-(Angle a, Angle b) -{ - return {a.radians - b.radians}; -} - -inline Angle -operator*(Angle a, f32 scalar) -{ - return {a.radians * scalar}; -} - -inline Angle -operator*(f32 scalar, Angle a) -{ - return {a.radians * scalar}; -} - -inline Angle -operator/(Angle a, f32 scalar) -{ - return {a.radians / scalar}; -} - -inline f32 -operator/(Angle a, Angle b) -{ - return a.radians / b.radians; -} - -inline Angle& -operator+=(Angle& a, Angle b) -{ - return (a = a + b); -} - -inline Angle& -operator-=(Angle& a, Angle b) -{ - return (a = a - b); -} - -inline Angle& -operator*=(Angle& a, f32 scalar) -{ - return (a = a * scalar); -} - -inline Angle& -operator/=(Angle& a, f32 scalar) -{ - return (a = a / scalar); -} - - -// Transform Operators -// World = Parent * Local -Transform -operator*(Transform const& ps, Transform const& ls) -{ - Transform ws; - - ws.position = ps.position + ps.orientation * (ps.scale * ls.position); - ws.orientation = ps.orientation * ls.orientation; - // ws.scale = ps.scale * (ps.orientation * ls.scale); // Vector3 scale - ws.scale = ps.scale * ls.scale; - - return ws; -} - -inline Transform& -operator*=(Transform& ps, Transform const& ls) -{ - return (ps = ps * ls); -} - -// Local = World / Parent -Transform -operator/(Transform const& ws, Transform const& ps) -{ - Transform ls; - - const Quaternion ps_conjugate = math::conjugate(ps.orientation); - - ls.position = (ps_conjugate * (ws.position - ps.position)) / ps.scale; - ls.orientation = ps_conjugate * ws.orientation; - // ls.scale = ps_conjugate * (ws.scale / ps.scale); // Vector3 scale - ls.scale = ws.scale / ps.scale; - - return ls; -} - -inline Transform& -operator/=(Transform& ws, Transform const& ps) -{ - return (ws = ws / ps); -} - - -namespace angle -{ -inline Angle radians(f32 r) { return {r}; } -inline Angle degrees(f32 d) { return {d * math::TAU / 360.0f}; } -inline Angle turns(f32 t) { return {t * math::TAU}; } -inline Angle grads(f32 g) { return {g * math::TAU / 400.0f}; } -inline Angle gons(f32 g) { return {g * math::TAU / 400.0f}; } - -inline f32 as_radians(Angle a) { return a.radians; } -inline f32 as_degrees(Angle a) { return a.radians * (360.0f / math::TAU); } -inline f32 as_turns(Angle a) { return a.radians * ( 1.0f / math::TAU); } -inline f32 as_grads(Angle a) { return a.radians * (400.0f / math::TAU); } -inline f32 as_gons(Angle a) { return a.radians * (400.0f / math::TAU); } -} // namespace angle - -//////////////////////////////// -/// /// -/// Math Functions /// -/// /// -//////////////////////////////// - - -namespace math -{ -f32 const ZERO = 0.0f; -f32 const ONE = 1.0f; -f32 const THIRD = 0.33333333f; -f32 const TWO_THIRDS = 0.66666667f; -f32 const E = 2.718281828f; -f32 const PI = 3.141592654f; -f32 const TAU = 6.283185307f; -f32 const SQRT_2 = 1.414213562f; -f32 const SQRT_3 = 1.732050808f; -f32 const SQRT_5 = 2.236067978f; - -f32 const F32_PRECISION = 1.0e-7f; - -// Power -inline f32 sqrt(f32 x) { return ::sqrtf(x); } -inline f32 pow(f32 x, f32 y) { return static_cast(::powf(x, y)); } -inline f32 cbrt(f32 x) { return static_cast(::cbrtf(x)); } - -inline f32 -fast_inv_sqrt(f32 x) -{ - const f32 THREE_HALFS = 1.5f; - - const f32 x2 = x * 0.5f; - f32 y = x; - u32 i = bit_cast(y); // Evil floating point bit level hacking - // i = 0x5f3759df - (i >> 1); // What the fuck? Old - i = 0x5f375a86 - (i >> 1); // What the fuck? Improved! - y = bit_cast(i); - y = y * (THREE_HALFS - (x2 * y * y)); // 1st iteration - // y = y * (THREE_HALFS - (x2 * y * y)); // 2nd iteration, this can be removed - - return y; -} - -// Trigonometric -inline f32 sin(Angle a) { return ::sinf(angle::as_radians(a)); } -inline f32 cos(Angle a) { return ::cosf(angle::as_radians(a)); } -inline f32 tan(Angle a) { return ::tanf(angle::as_radians(a)); } - -inline Angle arcsin(f32 x) { return angle::radians(::asinf(x)); } -inline Angle arccos(f32 x) { return angle::radians(::acosf(x)); } -inline Angle arctan(f32 x) { return angle::radians(::atanf(x)); } -inline Angle arctan2(f32 y, f32 x) { return angle::radians(::atan2f(y, x)); } - -// Hyperbolic -inline f32 sinh(f32 x) { return ::sinhf(x); } -inline f32 cosh(f32 x) { return ::coshf(x); } -inline f32 tanh(f32 x) { return ::tanhf(x); } - -inline f32 arsinh(f32 x) { return ::asinhf(x); } -inline f32 arcosh(f32 x) { return ::acoshf(x); } -inline f32 artanh(f32 x) { return ::atanhf(x); } - -// Rounding -inline f32 ceil(f32 x) { return ::ceilf(x); } -inline f32 floor(f32 x) { return ::floorf(x); } -inline f32 mod(f32 x, f32 y) { return ::fmodf(x, y); } -inline f32 truncate(f32 x) { return ::truncf(x); } -inline f32 round(f32 x) { return ::roundf(x); } - -inline s32 sign(s32 x) { return x >= 0 ? +1 : -1; } -inline s64 sign(s64 x) { return x >= 0 ? +1 : -1; } -inline f32 sign(f32 x) { return x >= 0.0f ? +1.0f : -1.0f; } - -// Other -inline f32 -abs(f32 x) -{ - u32 i = bit_cast(x); - i &= 0x7FFFFFFFul; - return bit_cast(i); -} - -inline s8 -abs(s8 x) -{ - u8 i = bit_cast(x); - i &= 0x7Fu; - return bit_cast(i); -} - -inline s16 -abs(s16 x) -{ - u16 i = bit_cast(x); - i &= 0x7FFFu; - return bit_cast(i); -} - -inline s32 -abs(s32 x) -{ - u32 i = bit_cast(x); - i &= 0x7FFFFFFFul; - return bit_cast(i); -} - -inline s64 -abs(s64 x) -{ - u64 i = bit_cast(x); - i &= 0x7FFFFFFFFFFFFFFFull; - return bit_cast(i); -} - -inline bool -is_infinite(f32 x) -{ - return isinf(x); -} - -inline bool -is_nan(f32 x) -{ - return isnan(x); -} - -inline s32 -kronecker_delta(s32 i, s32 j) -{ - return static_cast(i == j); -} - -inline s64 -kronecker_delta(s64 i, s64 j) -{ - return static_cast(i == j); -} - -inline f32 -kronecker_delta(f32 i, f32 j) -{ - return static_cast(i == j); -} - -inline f32 -min(f32 x, f32 y) -{ - // TODO(bill): Check if this is even good - return x < y ? x : y; -} - -inline s32 -min(s32 x, s32 y) -{ - return y + ((x-y) & (x-y)>>31); -} - -inline s64 -min(s64 x, s64 y) -{ - return y + ((x-y) & (x-y)>>63); -} - -inline f32 -max(f32 x, f32 y) -{ - // TODO(bill): Check if this is even good - return x > y ? x : y; -} - -inline s32 -max(s32 x, s32 y) -{ - return x - ((x-y) & (x-y)>>31); -} - -inline s64 -max(s64 x, s64 y) -{ - return x - ((x-y) & (x-y)>>63); -} - -inline f32 -clamp(f32 x, f32 min, f32 max) -{ - const f32 t = x < min ? min : x; - return t > max ? max : t; -} - -inline s32 -clamp(s32 x, s32 min, s32 max) -{ - const s32 t = x < min ? min : x; - return t > max ? max : t; -} - -inline s64 -clamp(s64 x, s64 min, s64 max) -{ - const s64 t = x < min ? min : x; - return t > max ? max : t; -} - -inline bool -equals(f32 a, f32 b, f32 precision) -{ - return ((b <= (a + precision)) && (b >= (a - precision))); -} - -// Vector2 functions -inline f32 -dot(Vector2 a, Vector2 b) -{ - return a.x * b.x + a.y * b.y; -} - -inline f32 -cross(Vector2 a, Vector2 b) -{ - return a.x * b.y - a.y * b.x; -} - -inline f32 -magnitude(Vector2 a) -{ - return math::sqrt(math::dot(a, a)); -} - -inline Vector2 -normalize(Vector2 a) -{ - f32 m = magnitude(a); - if (m > 0) - return a * (1.0f / m); - return {}; -} - -inline Vector2 -hadamard(Vector2 a, Vector2 b) -{ - return {a.x * b.x, a.y * b.y}; -} - -inline f32 -aspect_ratio(Vector2 a) -{ - return a.x / a.y; -} - - -inline Matrix4 -matrix2_to_matrix4(Matrix2 m) -{ - Matrix4 result = MATRIX4_IDENTITY; - result[0][0] = m[0][0]; - result[0][1] = m[0][1]; - result[1][0] = m[1][0]; - result[1][1] = m[1][1]; - return result; -} - -// Vector3 functions -inline f32 -dot(Vector3 a, Vector3 b) -{ - return a.x * b.x + a.y * b.y + a.z * b.z; -} - -inline Vector3 -cross(Vector3 a, Vector3 b) -{ - return Vector3{ - a.y * b.z - b.y * a.z, // x - a.z * b.x - b.z * a.x, // y - a.x * b.y - b.x * a.y // z - }; -} - -inline f32 -magnitude(Vector3 a) -{ - return math::sqrt(math::dot(a, a)); -} - -inline Vector3 -normalize(Vector3 a) -{ - f32 m = magnitude(a); - if (m > 0) - return a * (1.0f / m); - return {}; -} - -inline Vector3 -hadamard(Vector3 a, Vector3 b) -{ - return {a.x * b.x, a.y * b.y, a.z * b.z}; -} - -inline Matrix4 -matrix3_to_matrix4(Matrix3 const& m) -{ - Matrix4 result = MATRIX4_IDENTITY; - result[0][0] = m[0][0]; - result[0][1] = m[0][1]; - result[0][2] = m[0][2]; - result[1][0] = m[1][0]; - result[1][1] = m[1][1]; - result[1][2] = m[1][2]; - result[2][0] = m[2][0]; - result[2][1] = m[2][1]; - result[2][2] = m[2][2]; - return result; -} - -// Vector4 functions -inline f32 -dot(Vector4 a, Vector4 b) -{ - return a.x*b.x + a.y*b.y + a.z*b.z + a.w*b.w; -} - -inline f32 -magnitude(Vector4 a) -{ - return math::sqrt(math::dot(a, a)); -} - -inline Vector4 -normalize(Vector4 a) -{ - f32 m = magnitude(a); - if (m > 0) - return a * (1.0f / m); - return {}; -} - -inline Vector4 -hadamard(Vector4 a, Vector4 b) -{ - return {a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w}; -} - -// Complex Functions -inline f32 -dot(Complex a, Complex b) -{ - return a.real * b.real + a.imag * b.imag; -} - -inline f32 -magnitude(Complex a) -{ - return math::sqrt(norm(a)); -} - -inline f32 -norm(Complex a) -{ - return math::dot(a, a); -} - -inline Complex -normalize(Complex a) -{ - f32 m = magnitude(a); - if (m > 0) - return a / magnitude(a); - return COMPLEX_ZERO; -} - -inline Complex -conjugate(Complex a) -{ - return {a.real, -a.imag}; -} - -inline Complex -inverse(Complex a) -{ - f32 m = norm(a); - if (m > 0) - return conjugate(a) / norm(a); - return COMPLEX_ZERO; -} - -inline f32 -complex_angle(Complex a) -{ - return atan2f(a.imag, a.real); -} - -inline Complex -magnitude_angle(f32 magnitude, Angle a) -{ - f32 real = magnitude * math::cos(a); - f32 imag = magnitude * math::sin(a); - return {real, imag}; -} - -// Quaternion functions -inline f32 -dot(Quaternion a, Quaternion b) -{ - return math::dot(a.xyz, b.xyz) + a.w*b.w; -} - -inline Quaternion -cross(Quaternion a, Quaternion b) -{ - return Quaternion{a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y, - a.w * b.y + a.y * b.w + a.z * b.x - a.x * b.z, - a.w * b.z + a.z * b.w + a.x * b.y - a.y * b.x, - a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z}; -} - -inline f32 -magnitude(Quaternion a) -{ - return math::sqrt(math::dot(a, a)); -} - -inline f32 -norm(Quaternion a) -{ - return math::dot(a, a); -} - -inline Quaternion -normalize(Quaternion a) -{ - f32 m = magnitude(a); - if (m > 0) - return a * (1.0f / m); - return {}; -} - -inline Quaternion -conjugate(Quaternion a) -{ - return {-a.x, -a.y, -a.z, a.w}; -} - -inline Quaternion -inverse(Quaternion a) -{ - f32 m = 1.0f / dot(a, a); - return math::conjugate(a) * m; -} - -inline Angle -quaternion_angle(Quaternion a) -{ - return 2.0f * math::arccos(a.w); -} - -inline Vector3 -quaternion_axis(Quaternion a) -{ - f32 s2 = 1.0f - a.w * a.w; - - if (s2 <= 0.0f) - return {0, 0, 1}; - - f32 invs2 = 1.0f / math::sqrt(s2); - - return a.xyz * invs2; -} - -inline Quaternion -axis_angle(Vector3 axis, Angle angle) -{ - Vector3 a = math::normalize(axis); - f32 s = math::sin(0.5f * angle); - - Quaternion q; - q.xyz = a * s; - q.w = math::cos(0.5f * angle); - - return q; -} - -inline Angle -quaternion_roll(Quaternion a) -{ - return math::arctan2(2.0f * a.x * a.y + a.z * a.w, - a.x * a.x + a.w * a.w - a.y * a.y - a.z * a.z); -} - -inline Angle -quaternion_pitch(Quaternion a) -{ - return math::arctan2(2.0f * a.y * a.z + a.w * a.x, - a.w * a.w - a.x * a.x - a.y * a.y + a.z * a.z); -} - -inline Angle -quaternion_yaw(Quaternion a) -{ - return math::arcsin(-2.0f * (a.x * a.z - a.w * a.y)); - -} - -inline Euler_Angles -quaternion_to_euler_angles(Quaternion a) -{ - return {quaternion_pitch(a), quaternion_yaw(a), quaternion_roll(a)}; -} - -inline Quaternion -euler_angles_to_quaternion(Euler_Angles const& e, - Vector3 x_axis, - Vector3 y_axis, - Vector3 z_axis) -{ - Quaternion p = axis_angle(x_axis, e.pitch); - Quaternion y = axis_angle(y_axis, e.yaw); - Quaternion r = axis_angle(z_axis, e.roll); - - return y * p * r; -} - - -// Spherical Linear Interpolation -inline Quaternion -slerp(Quaternion x, Quaternion y, f32 t) -{ - Quaternion z = y; - - f32 cos_theta = dot(x, y); - - if (cos_theta < 0.0f) - { - z = -y; - cos_theta = -cos_theta; - } - - if (cos_theta > 1.0f) - { - return Quaternion{lerp(x.x, y.x, t), - lerp(x.y, y.y, t), - lerp(x.z, y.z, t), - lerp(x.w, y.w, t)}; - } - - Angle angle = math::arccos(cos_theta); - - Quaternion result = math::sin(angle::radians(1.0f) - (t * angle)) * x + math::sin(t * angle) * z; - return result * (1.0f / math::sin(angle)); -} - -// Shoemake's Quaternion Curves -// Sqherical Cubic Interpolation -inline Quaternion -squad(Quaternion p, - Quaternion a, - Quaternion b, - Quaternion q, - f32 t) -{ - return slerp(slerp(p, q, t), slerp(a, b, t), 2.0f * t * (1.0f - t)); -} - -// Matrix2 functions -inline Matrix2 -transpose(Matrix2 m) -{ - Matrix2 result; - for (usize i = 0; i < 2; i++) - { - for (usize j = 0; j < 2; j++) - result[i][j] = m[j][i]; - } - return result; -} - -inline f32 -determinant(Matrix2 m) -{ - return m[0][0] * m[1][1] - m[1][0] * m[0][1]; -} - -inline Matrix2 -inverse(Matrix2 m) -{ - f32 inv_det = 1.0f / (m[0][0] * m[1][1] - m[1][0] * m[0][1]); - Matrix2 result; - result[0][0] = m[1][1] * inv_det; - result[0][1] = -m[0][1] * inv_det; - result[1][0] = -m[1][0] * inv_det; - result[1][1] = m[0][0] * inv_det; - return result; -} - -inline Matrix2 -hadamard(Matrix2 a, const Matrix2&b) -{ - Matrix2 result; - result[0] = a[0] * b[0]; - result[1] = a[1] * b[1]; - return result; -} - -// Matrix3 functions -inline Matrix3 -transpose(Matrix3 const& m) -{ - Matrix3 result; - - for (usize i = 0; i < 3; i++) - { - for (usize j = 0; j < 3; j++) - result[i][j] = m[j][i]; - } - return result; -} - -inline f32 -determinant(Matrix3 const& m) -{ - return (+m[0][0] * (m[1][1] * m[2][2] - m[2][1] * m[1][2]) - -m[1][0] * (m[0][1] * m[2][2] - m[2][1] * m[0][2]) - +m[2][0] * (m[0][1] * m[1][2] - m[1][1] * m[0][2])); -} - -inline Matrix3 -inverse(Matrix3 const& m) -{ - f32 inv_det = 1.0f / ( - + m[0][0] * (m[1][1] * m[2][2] - m[2][1] * m[1][2]) - - m[1][0] * (m[0][1] * m[2][2] - m[2][1] * m[0][2]) - + m[2][0] * (m[0][1] * m[1][2] - m[1][1] * m[0][2])); - - Matrix3 result; - - result[0][0] = +(m[1][1] * m[2][2] - m[2][1] * m[1][2]) * inv_det; - result[1][0] = -(m[1][0] * m[2][2] - m[2][0] * m[1][2]) * inv_det; - result[2][0] = +(m[1][0] * m[2][1] - m[2][0] * m[1][1]) * inv_det; - result[0][1] = -(m[0][1] * m[2][2] - m[2][1] * m[0][2]) * inv_det; - result[1][1] = +(m[0][0] * m[2][2] - m[2][0] * m[0][2]) * inv_det; - result[2][1] = -(m[0][0] * m[2][1] - m[2][0] * m[0][1]) * inv_det; - result[0][2] = +(m[0][1] * m[1][2] - m[1][1] * m[0][2]) * inv_det; - result[1][2] = -(m[0][0] * m[1][2] - m[1][0] * m[0][2]) * inv_det; - result[2][2] = +(m[0][0] * m[1][1] - m[1][0] * m[0][1]) * inv_det; - - return result; -} - -inline Matrix3 -hadamard(Matrix3 const& a, const Matrix3&b) -{ - Matrix3 result; - result[0] = a[0] * b[0]; - result[1] = a[1] * b[1]; - result[2] = a[2] * b[2]; - return result; -} - -// Matrix4 functions -inline Matrix4 -transpose(Matrix4 const& m) -{ - Matrix4 result; - - for (usize i = 0; i < 4; i++) - { - for (usize j = 0; j < 4; j++) - result[i][j] = m[j][i]; - } - return result; -} - -f32 -determinant(Matrix4 const& m) -{ - f32 coef00 = m[2][2] * m[3][3] - m[3][2] * m[2][3]; - f32 coef02 = m[1][2] * m[3][3] - m[3][2] * m[1][3]; - f32 coef03 = m[1][2] * m[2][3] - m[2][2] * m[1][3]; - - f32 coef04 = m[2][1] * m[3][3] - m[3][1] * m[2][3]; - f32 coef06 = m[1][1] * m[3][3] - m[3][1] * m[1][3]; - f32 coef07 = m[1][1] * m[2][3] - m[2][1] * m[1][3]; - - f32 coef08 = m[2][1] * m[3][2] - m[3][1] * m[2][2]; - f32 coef10 = m[1][1] * m[3][2] - m[3][1] * m[1][2]; - f32 coef11 = m[1][1] * m[2][2] - m[2][1] * m[1][2]; - - f32 coef12 = m[2][0] * m[3][3] - m[3][0] * m[2][3]; - f32 coef14 = m[1][0] * m[3][3] - m[3][0] * m[1][3]; - f32 coef15 = m[1][0] * m[2][3] - m[2][0] * m[1][3]; - - f32 coef16 = m[2][0] * m[3][2] - m[3][0] * m[2][2]; - f32 coef18 = m[1][0] * m[3][2] - m[3][0] * m[1][2]; - f32 coef19 = m[1][0] * m[2][2] - m[2][0] * m[1][2]; - - f32 coef20 = m[2][0] * m[3][1] - m[3][0] * m[2][1]; - f32 coef22 = m[1][0] * m[3][1] - m[3][0] * m[1][1]; - f32 coef23 = m[1][0] * m[2][1] - m[2][0] * m[1][1]; - - Vector4 fac0 = {coef00, coef00, coef02, coef03}; - Vector4 fac1 = {coef04, coef04, coef06, coef07}; - Vector4 fac2 = {coef08, coef08, coef10, coef11}; - Vector4 fac3 = {coef12, coef12, coef14, coef15}; - Vector4 fac4 = {coef16, coef16, coef18, coef19}; - Vector4 fac5 = {coef20, coef20, coef22, coef23}; - - Vector4 vec0 = {m[1][0], m[0][0], m[0][0], m[0][0]}; - Vector4 vec1 = {m[1][1], m[0][1], m[0][1], m[0][1]}; - Vector4 vec2 = {m[1][2], m[0][2], m[0][2], m[0][2]}; - Vector4 vec3 = {m[1][3], m[0][3], m[0][3], m[0][3]}; - - Vector4 inv0 = vec1 * fac0 - vec2 * fac1 + vec3 * fac2; - Vector4 inv1 = vec0 * fac0 - vec2 * fac3 + vec3 * fac4; - Vector4 inv2 = vec0 * fac1 - vec1 * fac3 + vec3 * fac5; - Vector4 inv3 = vec0 * fac2 - vec1 * fac4 + vec2 * fac5; - - Vector4 signA = {+1, -1, +1, -1}; - Vector4 signB = {-1, +1, -1, +1}; - Matrix4 inverse = {inv0 * signA, inv1 * signB, inv2 * signA, inv3 * signB}; - - Vector4 row0 = {inverse[0][0], inverse[1][0], inverse[2][0], inverse[3][0]}; - - Vector4 dot0 = m[0] * row0; - f32 dot1 = (dot0[0] + dot0[1]) + (dot0[2] + dot0[3]); - return dot1; -} - -Matrix4 -inverse(Matrix4 const& m) -{ - f32 coef00 = m[2][2] * m[3][3] - m[3][2] * m[2][3]; - f32 coef02 = m[1][2] * m[3][3] - m[3][2] * m[1][3]; - f32 coef03 = m[1][2] * m[2][3] - m[2][2] * m[1][3]; - f32 coef04 = m[2][1] * m[3][3] - m[3][1] * m[2][3]; - f32 coef06 = m[1][1] * m[3][3] - m[3][1] * m[1][3]; - f32 coef07 = m[1][1] * m[2][3] - m[2][1] * m[1][3]; - f32 coef08 = m[2][1] * m[3][2] - m[3][1] * m[2][2]; - f32 coef10 = m[1][1] * m[3][2] - m[3][1] * m[1][2]; - f32 coef11 = m[1][1] * m[2][2] - m[2][1] * m[1][2]; - f32 coef12 = m[2][0] * m[3][3] - m[3][0] * m[2][3]; - f32 coef14 = m[1][0] * m[3][3] - m[3][0] * m[1][3]; - f32 coef15 = m[1][0] * m[2][3] - m[2][0] * m[1][3]; - f32 coef16 = m[2][0] * m[3][2] - m[3][0] * m[2][2]; - f32 coef18 = m[1][0] * m[3][2] - m[3][0] * m[1][2]; - f32 coef19 = m[1][0] * m[2][2] - m[2][0] * m[1][2]; - f32 coef20 = m[2][0] * m[3][1] - m[3][0] * m[2][1]; - f32 coef22 = m[1][0] * m[3][1] - m[3][0] * m[1][1]; - f32 coef23 = m[1][0] * m[2][1] - m[2][0] * m[1][1]; - - Vector4 fac0 = {coef00, coef00, coef02, coef03}; - Vector4 fac1 = {coef04, coef04, coef06, coef07}; - Vector4 fac2 = {coef08, coef08, coef10, coef11}; - Vector4 fac3 = {coef12, coef12, coef14, coef15}; - Vector4 fac4 = {coef16, coef16, coef18, coef19}; - Vector4 fac5 = {coef20, coef20, coef22, coef23}; - - Vector4 vec0 = {m[1][0], m[0][0], m[0][0], m[0][0]}; - Vector4 vec1 = {m[1][1], m[0][1], m[0][1], m[0][1]}; - Vector4 vec2 = {m[1][2], m[0][2], m[0][2], m[0][2]}; - Vector4 vec3 = {m[1][3], m[0][3], m[0][3], m[0][3]}; - - Vector4 inv0 = vec1 * fac0 - vec2 * fac1 + vec3 * fac2; - Vector4 inv1 = vec0 * fac0 - vec2 * fac3 + vec3 * fac4; - Vector4 inv2 = vec0 * fac1 - vec1 * fac3 + vec3 * fac5; - Vector4 inv3 = vec0 * fac2 - vec1 * fac4 + vec2 * fac5; - - Vector4 signA = {+1, -1, +1, -1}; - Vector4 signB = {-1, +1, -1, +1}; - Matrix4 inverse = {inv0 * signA, inv1 * signB, inv2 * signA, inv3 * signB}; - - Vector4 row0 = {inverse[0][0], inverse[1][0], inverse[2][0], inverse[3][0]}; - - Vector4 dot0 = m[0] * row0; - f32 dot1 = (dot0[0] + dot0[1]) + (dot0[2] + dot0[3]); - - f32 oneOverDeterminant = 1.0f / dot1; - - return inverse * oneOverDeterminant; -} - -inline Matrix4 -hadamard(Matrix4 const& a, Matrix4 const& b) -{ - Matrix4 result; - - result[0] = a[0] * b[0]; - result[1] = a[1] * b[1]; - result[2] = a[2] * b[2]; - result[3] = a[3] * b[3]; - - return result; -} - -inline bool -is_affine(Matrix4 const& m) -{ - // E.g. No translation - return (equals(m.columns[3].x, 0)) & - (equals(m.columns[3].y, 0)) & - (equals(m.columns[3].z, 0)) & - (equals(m.columns[3].w, 1.0f)); -} - - -inline Matrix4 -quaternion_to_matrix4(Quaternion q) -{ - Matrix4 mat = MATRIX4_IDENTITY; - - Quaternion a = math::normalize(q); - - f32 xx = a.x * a.x; - f32 yy = a.y * a.y; - f32 zz = a.z * a.z; - f32 xy = a.x * a.y; - f32 xz = a.x * a.z; - f32 yz = a.y * a.z; - f32 wx = a.w * a.x; - f32 wy = a.w * a.y; - f32 wz = a.w * a.z; - - mat[0][0] = 1.0f - 2.0f * (yy + zz); - mat[0][1] = 2.0f * (xy + wz); - mat[0][2] = 2.0f * (xz - wy); - - mat[1][0] = 2.0f * (xy - wz); - mat[1][1] = 1.0f - 2.0f * (xx + zz); - mat[1][2] = 2.0f * (yz + wx); - - mat[2][0] = 2.0f * (xz + wy); - mat[2][1] = 2.0f * (yz - wx); - mat[2][2] = 1.0f - 2.0f * (xx + yy); - - return mat; -} - -Quaternion -matrix4_to_quaternion(Matrix4 const& m) -{ - f32 four_x_squared_minus_1 = m[0][0] - m[1][1] - m[2][2]; - f32 four_y_squared_minus_1 = m[1][1] - m[0][0] - m[2][2]; - f32 four_z_squared_minus_1 = m[2][2] - m[0][0] - m[1][1]; - f32 four_w_squared_minus_1 = m[0][0] + m[1][1] + m[2][2]; - - s32 biggestIndex = 0; - f32 four_biggest_squared_minus_1 = four_w_squared_minus_1; - if (four_x_squared_minus_1 > four_biggest_squared_minus_1) - { - four_biggest_squared_minus_1 = four_x_squared_minus_1; - biggestIndex = 1; - } - if (four_y_squared_minus_1 > four_biggest_squared_minus_1) - { - four_biggest_squared_minus_1 = four_y_squared_minus_1; - biggestIndex = 2; - } - if (four_z_squared_minus_1 > four_biggest_squared_minus_1) - { - four_biggest_squared_minus_1 = four_z_squared_minus_1; - biggestIndex = 3; - } - - f32 biggestVal = math::sqrt(four_biggest_squared_minus_1 + 1.0f) * 0.5f; - f32 mult = 0.25f / biggestVal; - - Quaternion q = QUATERNION_IDENTITY; - - switch (biggestIndex) - { - case 0: - { - q.w = biggestVal; - q.x = (m[1][2] - m[2][1]) * mult; - q.y = (m[2][0] - m[0][2]) * mult; - q.z = (m[0][1] - m[1][0]) * mult; - } - break; - case 1: - { - q.w = (m[1][2] - m[2][1]) * mult; - q.x = biggestVal; - q.y = (m[0][1] + m[1][0]) * mult; - q.z = (m[2][0] + m[0][2]) * mult; - } - break; - case 2: - { - q.w = (m[2][0] - m[0][2]) * mult; - q.x = (m[0][1] + m[1][0]) * mult; - q.y = biggestVal; - q.z = (m[1][2] + m[2][1]) * mult; - } - break; - case 3: - { - q.w = (m[0][1] - m[1][0]) * mult; - q.x = (m[2][0] + m[0][2]) * mult; - q.y = (m[1][2] + m[2][1]) * mult; - q.z = biggestVal; - } - break; - default: // Should never actually get here. Just for sanities sake. - { - GB_ASSERT(false, "How did you get here?!"); - } - break; - } - - return q; -} - - -inline Matrix4 -translate(Vector3 v) -{ - Matrix4 result = MATRIX4_IDENTITY; - result[3].xyz = v; - result[3].w = 1; - return result; -} - -inline Matrix4 -rotate(Vector3 v, Angle angle) -{ - const f32 c = math::cos(angle); - const f32 s = math::sin(angle); - - const Vector3 axis = math::normalize(v); - const Vector3 t = (1.0f - c) * axis; - - Matrix4 rot = MATRIX4_IDENTITY; - - rot[0][0] = c + t.x * axis.x; - rot[0][1] = 0 + t.x * axis.y + s * axis.z; - rot[0][2] = 0 + t.x * axis.z - s * axis.y; - rot[0][3] = 0; - - rot[1][0] = 0 + t.y * axis.x - s * axis.z; - rot[1][1] = c + t.y * axis.y; - rot[1][2] = 0 + t.y * axis.z + s * axis.x; - rot[1][3] = 0; - - rot[2][0] = 0 + t.z * axis.x + s * axis.y; - rot[2][1] = 0 + t.z * axis.y - s * axis.x; - rot[2][2] = c + t.z * axis.z; - rot[2][3] = 0; - - return rot; -} - -inline Matrix4 -scale(Vector3 v) -{ - return { v.x, 0, 0, 0, - 0, v.y, 0, 0, - 0, 0, v.z, 0, - 0, 0, 0, 1 }; -} - -inline Matrix4 -ortho(f32 left, f32 right, f32 bottom, f32 top) -{ - return ortho(left, right, bottom, top, -1.0f, 1.0f); -} - -inline Matrix4 -ortho(f32 left, f32 right, f32 bottom, f32 top, f32 z_near, f32 z_far) -{ - Matrix4 result = MATRIX4_IDENTITY; - - result[0][0] = 2.0f / (right - left); - result[1][1] = 2.0f / (top - bottom); - result[2][2] = -2.0f / (z_far - z_near); - result[3][0] = -(right + left) / (right - left); - result[3][1] = -(top + bottom) / (top - bottom); - result[3][2] = -(z_far + z_near) / (z_far - z_near); - - return result; -} - -inline Matrix4 -perspective(Angle fovy, f32 aspect, f32 z_near, f32 z_far) -{ - GB_ASSERT(math::abs(aspect) > 0.0f, - "math::perspective `fovy` is %f rad", angle::as_radians(fovy)); - - f32 tan_half_fovy = math::tan(0.5f * fovy); - - Matrix4 result = {}; - result[0][0] = 1.0f / (aspect * tan_half_fovy); - result[1][1] = 1.0f / (tan_half_fovy); - result[2][2] = -(z_far + z_near) / (z_far - z_near); - result[2][3] = -1.0f; - result[3][2] = -2.0f * z_far * z_near / (z_far - z_near); - - return result; -} - -inline Matrix4 -infinite_perspective(Angle fovy, f32 aspect, f32 z_near) -{ - f32 range = math::tan(0.5f * fovy) * z_near; - f32 left = -range * aspect; - f32 right = range * aspect; - f32 bottom = -range; - f32 top = range; - - Matrix4 result = {}; - - result[0][0] = (2.0f * z_near) / (right - left); - result[1][1] = (2.0f * z_near) / (top - bottom); - result[2][2] = -1.0f; - result[2][3] = -1.0f; - result[3][2] = -2.0f * z_near; - - return result; -} - - -inline Matrix4 -look_at_matrix4(Vector3 eye, Vector3 center, Vector3 up) -{ - const Vector3 f = math::normalize(center - eye); - const Vector3 s = math::normalize(math::cross(f, up)); - const Vector3 u = math::cross(s, f); - - Matrix4 result = MATRIX4_IDENTITY; - - result[0][0] = +s.x; - result[1][0] = +s.y; - result[2][0] = +s.z; - - result[0][1] = +u.x; - result[1][1] = +u.y; - result[2][1] = +u.z; - - result[0][2] = -f.x; - result[1][2] = -f.y; - result[2][2] = -f.z; - - result[3][0] = -math::dot(s, eye); - result[3][1] = -math::dot(u, eye); - result[3][2] = +math::dot(f, eye); - - return result; -} - - -inline Quaternion -look_at_quaternion(Vector3 eye, Vector3 center, Vector3 up) -{ - if (math::equals(math::magnitude(center - eye), 0, 0.001f)) - return QUATERNION_IDENTITY; // You cannot look at where you are! - -#if 1 - return matrix4_to_quaternion(look_at_matrix4(eye, center, up)); -#else - // TODO(bill): Thoroughly test this look_at_quaternion! - // Is it more efficient that that a converting a Matrix4 to a Quaternion? - Vector3 forward_l = math::normalize(center - eye); - Vector3 forward_w = {1, 0, 0}; - Vector3 axis = math::cross(forward_l, forward_w); - - f32 angle = math::acos(math::dot(forward_l, forward_w)); - - Vector3 third = math::cross(axis, forward_w); - if (math::dot(third, forward_l) < 0) - angle = -angle; - - Quaternion q1 = math::axis_angle(axis, angle); - - Vector3 up_l = q1 * math::normalize(up); - Vector3 right = math::normalize(math::cross(forward_l, up)); - Vector3 up_w = math::normalize(math::cross(right, forward_l)); - - Vector3 axis2 = math::cross(up_l, up_w); - f32 angle2 = math::acos(math::dot(up_l, up_w)); - - Quaternion q2 = math::axis_angle(axis2, angle2); - - return q2 * q1; -#endif -} - -// Transform Functions -inline Vector3 -transform_point(Transform const& transform, Vector3 point) -{ - return (math::conjugate(transform.orientation) * (transform.position - point)) / transform.scale; -} - -inline Transform -inverse(Transform const& t) -{ - const Quaternion inv_orientation = math::conjugate(t.orientation); - - Transform inv_transform; - - inv_transform.position = (inv_orientation * -t.position) / t.scale; - inv_transform.orientation = inv_orientation; - // inv_transform.scale = inv_orientation * (Vector3{1, 1, 1} / t.scale); // Vector3 scale - inv_transform.scale = 1.0f / t.scale; - - return inv_transform; -} - -inline Matrix4 -transform_to_matrix4(Transform const& t) -{ - return math::translate(t.position) * - math::quaternion_to_matrix4(t.orientation) * - math::scale({t.scale, t.scale, t.scale}); -} -} // namespace math - - -namespace aabb -{ -inline Aabb -calculate(void const* vertices, usize num_vertices, usize stride, usize offset) -{ - Vector3 min; - Vector3 max; - const u8* vertex = reinterpret_cast(vertices); - vertex += offset; - Vector3 position = pseudo_cast(vertex); - min.x = max.x = position.x; - min.y = max.y = position.y; - min.z = max.z = position.z; - vertex += stride; - - for (usize i = 1; i < num_vertices; i++) - { - position = pseudo_cast(vertex); - vertex += stride; - - Vector3 p = position; - min.x = math::min(p.x, min.x); - min.y = math::min(p.y, min.y); - min.z = math::min(p.z, min.z); - max.x = math::max(p.x, max.x); - max.y = math::max(p.y, max.y); - max.z = math::max(p.z, max.z); - } - - Aabb aabb; - - aabb.center = 0.5f * (min + max); - aabb.half_size = 0.5f * (max - min); - - return aabb; -} - -inline f32 -surface_area(Aabb const& aabb) -{ - Vector3 h = aabb.half_size * 2.0f; - f32 s = 0.0f; - s += h.x * h.y; - s += h.y * h.z; - s += h.z * h.x; - s *= 3.0f; - return s; -} - -inline f32 -volume(Aabb const& aabb) -{ - Vector3 h = aabb.half_size * 2.0f; - return h.x * h.y * h.z; -} - -inline Sphere -to_sphere(Aabb const& aabb) -{ - Sphere s; - s.center = aabb.center; - s.radius = math::magnitude(aabb.half_size); - return s; -} - - -inline bool -contains(Aabb const& aabb, Vector3 point) -{ - Vector3 distance = aabb.center - point; - - // NOTE(bill): & is faster than && - return (math::abs(distance.x) <= aabb.half_size.x) & - (math::abs(distance.y) <= aabb.half_size.y) & - (math::abs(distance.z) <= aabb.half_size.z); -} - -inline bool -contains(Aabb const& a, Aabb const& b) -{ - Vector3 dist = a.center - b.center; - - // NOTE(bill): & is faster than && - return (math::abs(dist.x) + b.half_size.x <= a.half_size.x) & - (math::abs(dist.y) + b.half_size.y <= a.half_size.y) & - (math::abs(dist.z) + b.half_size.z <= a.half_size.z); -} - - -inline bool -intersects(Aabb const& a, Aabb const& b) -{ - Vector3 dist = a.center - b.center; - Vector3 sum_half_sizes = a.half_size + b.half_size; - - // NOTE(bill): & is faster than && - return (math::abs(dist.x) <= sum_half_sizes.x) & - (math::abs(dist.y) <= sum_half_sizes.y) & - (math::abs(dist.z) <= sum_half_sizes.z); -} - -inline Aabb -transform_affine(Aabb const& aabb, Matrix4 const& m) -{ - GB_ASSERT(math::is_affine(m), - "Passed Matrix4 must be an affine matrix"); - - Aabb result; - Vector4 ac; - ac.xyz = aabb.center; - ac.w = 1; - result.center = (m * ac).xyz; - - Vector3 hs = aabb.half_size; - f32 x = math::abs(m[0][0] * hs.x + math::abs(m[0][1]) * hs.y + math::abs(m[0][2]) * hs.z); - f32 y = math::abs(m[1][0] * hs.x + math::abs(m[1][1]) * hs.y + math::abs(m[1][2]) * hs.z); - f32 z = math::abs(m[2][0] * hs.x + math::abs(m[2][1]) * hs.y + math::abs(m[2][2]) * hs.z); - - result.half_size.x = math::is_infinite(math::abs(hs.x)) ? hs.x : x; - result.half_size.y = math::is_infinite(math::abs(hs.y)) ? hs.y : y; - result.half_size.z = math::is_infinite(math::abs(hs.z)) ? hs.z : z; - - return result; -} -} // namespace aabb - -namespace sphere -{ -Sphere -calculate_min_bounding(void const* vertices, usize num_vertices, usize stride, usize offset, f32 step) -{ -#if !defined(GB_MATH_NO_RANDOM) - auto gen = random::make(0); -#endif - - u8 const* vertex = reinterpret_cast(vertices); - vertex += offset; - - Vector3 position = pseudo_cast(vertex[0]); - Vector3 center = position; - center += pseudo_cast(vertex[1 * stride]); - center *= 0.5f; - - Vector3 d = position - center; - f32 max_dist_sq = math::dot(d, d); - f32 radius_step = step * 0.37f; - - bool done; - do - { - done = true; -#if !defined(GB_MATH_NO_RANDOM) - for (u32 i = 0, index = random::uniform_u32(&gen, 0, num_vertices-1); - i < num_vertices; - i++, index = (index + 1)%num_vertices) -#else - for (u32 i = 0, index = num_vertices/2; - i < num_vertices; - i++, index = (index + 1)%num_vertices) -#endif - { - Vector3 position = pseudo_cast(vertex[index * stride]); - - d = position - center; - f32 dist_sq = math::dot(d, d); - - if (dist_sq > max_dist_sq) - { - done = false; - - center = d * radius_step; - max_dist_sq = math::lerp(max_dist_sq, dist_sq, step); - - break; - } - } - } - while (!done); - - Sphere result; - - result.center = center; - result.radius = math::sqrt(max_dist_sq); - - return result; -} - -Sphere -calculate_max_bounding(void const* vertices, usize num_vertices, usize stride, usize offset) -{ - Aabb aabb = aabb::calculate(vertices, num_vertices, stride, offset); - - Vector3 center = aabb.center; - - f32 max_dist_sq = 0.0f; - const u8* vertex = reinterpret_cast(vertices); - vertex += offset; - - for (usize i = 0; i < num_vertices; i++) - { - Vector3 position = pseudo_cast(vertex); - vertex += stride; - - Vector3 d = position - center; - f32 dist_sq = math::dot(d, d); - max_dist_sq = math::max(dist_sq, max_dist_sq); - } - - Sphere sphere; - sphere.center = center; - sphere.radius = math::sqrt(max_dist_sq); - - return sphere; -} - -inline f32 -surface_area(Sphere s) -{ - return 2.0f * math::TAU * s.radius * s.radius; -} - -inline f32 -volume(Sphere s) -{ - return math::TWO_THIRDS * math::TAU * s.radius * s.radius * s.radius; -} - -inline Aabb -to_aabb(Sphere s) -{ - Aabb a; - a.center = s.center; - a.half_size.x = s.radius * math::SQRT_3; - a.half_size.y = s.radius * math::SQRT_3; - a.half_size.z = s.radius * math::SQRT_3; - return a; -} - -inline bool -contains_point(Sphere s, Vector3 point) -{ - Vector3 dr = point - s.center; - f32 distance = math::dot(dr, dr); - return distance < s.radius * s.radius; -} - -inline f32 -ray_intersection(Vector3 from, Vector3 dir, Sphere s) -{ - Vector3 v = s.center - from; - f32 b = math::dot(v, dir); - f32 det = (s.radius * s.radius) - math::dot(v, v) + (b * b); - - if (det < 0.0 || b < s.radius) - return -1.0f; - return b - math::sqrt(det); -} -} // namespace sphere - -namespace plane -{ -inline f32 -ray_intersection(Vector3 from, Vector3 dir, Plane p) -{ - f32 nd = math::dot(dir, p.normal); - f32 orpn = math::dot(from, p.normal); - f32 dist = -1.0f; - - if (nd < 0.0f) - dist = (-p.distance - orpn) / nd; - - return dist > 0.0f ? dist : -1.0f; -} - -inline bool -intersection3(Plane p1, Plane p2, Plane p3, Vector3* ip) -{ - f32 den = -math::dot(math::cross(p1.normal, p2.normal), p3.normal); - - if (math::equals(den, 0.0f)) - return false; - - Vector3 res = p1.distance * math::cross(p2.normal, p3.normal) - + p2.distance * math::cross(p3.normal, p1.normal) - + p3.distance * math::cross(p1.normal, p2.normal); - *ip = res / den; - - return true; -} -} // namespace plane - -#if !defined(GB_MATH_NO_RANDOM) -namespace random -{ -inline Random -make(s64 seed) -{ - Random r = {}; - set_seed(&r, seed); - return r; -} - -void -set_seed(Random* r, s64 seed) -{ - r->seed = seed; - r->mt[0] = seed; - for (u64 i = 1; i < 312; i++) - r->mt[i] = 6364136223846793005ull * (r->mt[i-1] ^ r->mt[i-1] >> 62) + i; -} - -s64 -next(Random* r) -{ - const u64 MAG01[2] = {0ull, 0xb5026f5aa96619e9ull}; - - u64 x; - if (r->index > 312) - { - u32 i = 0; - for (; i < 312-156; i++) - { - x = (r->mt[i] & 0xffffffff80000000ull) | (r->mt[i+1] & 0x7fffffffull); - r->mt[i] = r->mt[i+156] ^ (x>>1) ^ MAG01[(u32)(x & 1ull)]; - } - for (; i < 312-1; i++) - { - x = (r->mt[i] & 0xffffffff80000000ull) | (r->mt[i+1] & 0x7fffffffull); - r->mt[i] = r->mt[i + (312-156)] ^ (x >> 1) ^ MAG01[(u32)(x & 1ull)]; - } - x = (r->mt[312-1] & 0xffffffff80000000ull) | (r->mt[0] & 0x7fffffffull); - r->mt[312-1] = r->mt[156-1] ^ (x>>1) ^ MAG01[(u32)(x & 1ull)]; - - r->index = 0; - } - - x = r->mt[r->index++]; - - x ^= (x >> 29) & 0x5555555555555555ull; - x ^= (x << 17) & 0x71d67fffeda60000ull; - x ^= (x << 37) & 0xfff7eee000000000ull; - x ^= (x >> 43); - - return x; -} - -void -next_from_device(void* buffer, u32 length_in_bytes) -{ -#if defined(GB_SYSTEM_WINDOWS) - HCRYPTPROV prov; - - bool ok = CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT); - GB_ASSERT(ok, "CryptAcquireContext"); - ok = CryptGenRandom(prov, length_in_bytes, reinterpret_cast(&buffer)); - GB_ASSERT(ok, "CryptGenRandom"); - - CryptReleaseContext(prov, 0); - -#else - #error Implement random::next_from_device() -#endif -} - -inline s32 -next_s32(Random* r) -{ - return bit_cast(random::next(r)); -} - -inline u32 -next_u32(Random* r) -{ - return bit_cast(random::next(r)); -} - -inline f32 -next_f32(Random* r) -{ - return bit_cast(random::next(r)); -} - -inline s64 -next_s64(Random* r) -{ - return random::next(r); -} - -inline u64 -next_u64(Random* r) -{ - return bit_cast(random::next(r)); -} - -inline f64 -next_f64(Random* r) -{ - return bit_cast(random::next(r)); -} - -inline s32 -uniform_s32(Random* r, s32 min_inc, s32 max_inc) -{ - return (random::next_s32(r) & (max_inc - min_inc + 1)) + min_inc; -} - -inline u32 -uniform_u32(Random* r, u32 min_inc, u32 max_inc) -{ - return (random::next_u32(r) & (max_inc - min_inc + 1)) + min_inc; -} - -inline f32 -uniform_f32(Random* r, f32 min_inc, f32 max_inc) -{ - f64 n = (random::next_s64(r) >> 11) * (1.0/4503599627370495.0); - return static_cast(n * (max_inc - min_inc + 1.0) + min_inc); -} - -inline s64 -uniform_s64(Random* r, s64 min_inc, s64 max_inc) -{ - return (random::next_s32(r) & (max_inc - min_inc + 1)) + min_inc; -} - -inline u64 -uniform_u64(Random* r, u64 min_inc, u64 max_inc) -{ - return (random::next_u64(r) & (max_inc - min_inc + 1)) + min_inc; -} - -inline f64 -uniform_f64(Random* r, f64 min_inc, f64 max_inc) -{ - f64 n = (random::next_s64(r) >> 11) * (1.0/4503599627370495.0); - return (n * (max_inc - min_inc + 1.0) + min_inc); -} - - -global_variable const s32 g_perlin_randtab[512] = -{ - 23, 125, 161, 52, 103, 117, 70, 37, 247, 101, 203, 169, 124, 126, 44, 123, - 152, 238, 145, 45, 171, 114, 253, 10, 192, 136, 4, 157, 249, 30, 35, 72, - 175, 63, 77, 90, 181, 16, 96, 111, 133, 104, 75, 162, 93, 56, 66, 240, - 8, 50, 84, 229, 49, 210, 173, 239, 141, 1, 87, 18, 2, 198, 143, 57, - 225, 160, 58, 217, 168, 206, 245, 204, 199, 6, 73, 60, 20, 230, 211, 233, - 94, 200, 88, 9, 74, 155, 33, 15, 219, 130, 226, 202, 83, 236, 42, 172, - 165, 218, 55, 222, 46, 107, 98, 154, 109, 67, 196, 178, 127, 158, 13, 243, - 65, 79, 166, 248, 25, 224, 115, 80, 68, 51, 184, 128, 232, 208, 151, 122, - 26, 212, 105, 43, 179, 213, 235, 148, 146, 89, 14, 195, 28, 78, 112, 76, - 250, 47, 24, 251, 140, 108, 186, 190, 228, 170, 183, 139, 39, 188, 244, 246, - 132, 48, 119, 144, 180, 138, 134, 193, 82, 182, 120, 121, 86, 220, 209, 3, - 91, 241, 149, 85, 205, 150, 113, 216, 31, 100, 41, 164, 177, 214, 153, 231, - 38, 71, 185, 174, 97, 201, 29, 95, 7, 92, 54, 254, 191, 118, 34, 221, - 131, 11, 163, 99, 234, 81, 227, 147, 156, 176, 17, 142, 69, 12, 110, 62, - 27, 255, 0, 194, 59, 116, 242, 252, 19, 21, 187, 53, 207, 129, 64, 135, - 61, 40, 167, 237, 102, 223, 106, 159, 197, 189, 215, 137, 36, 32, 22, 5, - -// Copy - 23, 125, 161, 52, 103, 117, 70, 37, 247, 101, 203, 169, 124, 126, 44, 123, - 152, 238, 145, 45, 171, 114, 253, 10, 192, 136, 4, 157, 249, 30, 35, 72, - 175, 63, 77, 90, 181, 16, 96, 111, 133, 104, 75, 162, 93, 56, 66, 240, - 8, 50, 84, 229, 49, 210, 173, 239, 141, 1, 87, 18, 2, 198, 143, 57, - 225, 160, 58, 217, 168, 206, 245, 204, 199, 6, 73, 60, 20, 230, 211, 233, - 94, 200, 88, 9, 74, 155, 33, 15, 219, 130, 226, 202, 83, 236, 42, 172, - 165, 218, 55, 222, 46, 107, 98, 154, 109, 67, 196, 178, 127, 158, 13, 243, - 65, 79, 166, 248, 25, 224, 115, 80, 68, 51, 184, 128, 232, 208, 151, 122, - 26, 212, 105, 43, 179, 213, 235, 148, 146, 89, 14, 195, 28, 78, 112, 76, - 250, 47, 24, 251, 140, 108, 186, 190, 228, 170, 183, 139, 39, 188, 244, 246, - 132, 48, 119, 144, 180, 138, 134, 193, 82, 182, 120, 121, 86, 220, 209, 3, - 91, 241, 149, 85, 205, 150, 113, 216, 31, 100, 41, 164, 177, 214, 153, 231, - 38, 71, 185, 174, 97, 201, 29, 95, 7, 92, 54, 254, 191, 118, 34, 221, - 131, 11, 163, 99, 234, 81, 227, 147, 156, 176, 17, 142, 69, 12, 110, 62, - 27, 255, 0, 194, 59, 116, 242, 252, 19, 21, 187, 53, 207, 129, 64, 135, - 61, 40, 167, 237, 102, 223, 106, 159, 197, 189, 215, 137, 36, 32, 22, 5, -}; - - -internal_linkage f32 -perlin_grad(s32 hash, f32 x, f32 y, f32 z) -{ - local_persist const f32 basis[12][4] = - { - { 1, 1, 0}, - {-1, 1, 0}, - { 1,-1, 0}, - {-1,-1, 0}, - { 1, 0, 1}, - {-1, 0, 1}, - { 1, 0,-1}, - {-1, 0,-1}, - { 0, 1, 1}, - { 0,-1, 1}, - { 0, 1,-1}, - { 0,-1,-1}, - }; - - local_persist const u8 indices[64] = - { - 0,1,2,3,4,5,6,7,8,9,10,11, - 0,9,1,11, - 0,1,2,3,4,5,6,7,8,9,10,11, - 0,1,2,3,4,5,6,7,8,9,10,11, - 0,1,2,3,4,5,6,7,8,9,10,11, - 0,1,2,3,4,5,6,7,8,9,10,11, - }; - - const f32* grad = basis[indices[hash & 63]]; - return grad[0]*x + grad[1]*y + grad[2]*z; -} - - -inline f32 -perlin_3d(f32 x, f32 y, f32 z, s32 x_wrap, s32 y_wrap, s32 z_wrap) -{ - u32 x_mask = (x_wrap-1) & 255; - u32 y_mask = (y_wrap-1) & 255; - u32 z_mask = (z_wrap-1) & 255; - - s32 px = static_cast(math::floor(x)); - s32 py = static_cast(math::floor(y)); - s32 pz = static_cast(math::floor(z)); - - s32 x0 = (px) & x_mask; - s32 x1 = (px+1) & x_mask; - s32 y0 = (py) & y_mask; - s32 y1 = (py+1) & y_mask; - s32 z0 = (pz) & z_mask; - s32 z1 = (pz+1) & z_mask; - - x -= px; - y -= py; - z -= pz; - -#define GB__PERLIN_EASE(t) (((6*t - 15)*t + 10)*t*t*t) - f32 u = GB__PERLIN_EASE(x); - f32 v = GB__PERLIN_EASE(y); - f32 w = GB__PERLIN_EASE(z); -#undef GB__PERLIN_EASE - - s32 r0 = g_perlin_randtab[x0]; - s32 r1 = g_perlin_randtab[x1]; - - s32 r00 = g_perlin_randtab[r0 + y0]; - s32 r01 = g_perlin_randtab[r0 + y1]; - s32 r10 = g_perlin_randtab[r1 + y0]; - s32 r11 = g_perlin_randtab[r1 + y1]; - - f32 n000 = perlin_grad(g_perlin_randtab[r00 + z0], x, y, z ); - f32 n001 = perlin_grad(g_perlin_randtab[r00 + z1], x, y, z - 1); - f32 n010 = perlin_grad(g_perlin_randtab[r01 + z0], x, y - 1, z ); - f32 n011 = perlin_grad(g_perlin_randtab[r01 + z1], x, y - 1, z - 1); - f32 n100 = perlin_grad(g_perlin_randtab[r10 + z0], x - 1, y, z ); - f32 n101 = perlin_grad(g_perlin_randtab[r10 + z1], x - 1, y, z - 1); - f32 n110 = perlin_grad(g_perlin_randtab[r11 + z0], x - 1, y - 1, z ); - f32 n111 = perlin_grad(g_perlin_randtab[r11 + z1], x - 1, y - 1, z - 1); - - f32 n00 = math::lerp(n000, n001, w); - f32 n01 = math::lerp(n010, n011, w); - f32 n10 = math::lerp(n100, n101, w); - f32 n11 = math::lerp(n110, n111, w); - - f32 n0 = math::lerp(n00, n01, v); - f32 n1 = math::lerp(n10, n11, v); - - return math::lerp(n0, n1, u); -} - -} // namespace random -#endif - -__GB_NAMESPACE_END - -#endif // GB_MATH_IMPLEMENTATION From eec27b33ed34a33fad9433e1e72d0d599b78f983 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Fri, 8 Apr 2016 21:41:31 +0100 Subject: [PATCH 04/15] Update README.md --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index 03f3d63..ac7d035 100644 --- a/README.md +++ b/README.md @@ -5,11 +5,10 @@ gb single-file public domain libraries for C & C++ library | latest version | category | languages | description ----------------|----------------|----------|-----------|------------- **gb_string.h** | 0.93 | strings | C, C++ | A better string library for C & C++ +**gb_math.h** | 0.04 | math | C | A C vector math library geared towards game development **gb.h** | 0.01 | misc | C | A C helper library geared towards game development (NOT a port of gb.hpp) -**gb_math.h** | 0.04 | math | C | A C vector math library geared towards game development (NOT A PORT OF gb_math.hpp) **gb_ini.h** | 0.91a | misc | C, C++ | A simple ini file loader library for C & C++ **gb.hpp** | 0.32 | misc | C++11 | (Experimental) A C++11 helper library without STL geared towards game development -**gb_math.hpp** | 0.04 | math | C++11 | A C++11 math library geared towards game development ## FAQ From c58b8e1fe750b2c867c1ad65dda9bf5223e36ede Mon Sep 17 00:00:00 2001 From: gingerBill Date: Fri, 8 Apr 2016 22:41:14 +0100 Subject: [PATCH 05/15] gb_math.h v0.04a - Minor bug fixes --- gb_math.h | 95 +++++++++++++++++++++++++++++-------------------------- 1 file changed, 50 insertions(+), 45 deletions(-) diff --git a/gb_math.h b/gb_math.h index 09bf18e..debc376 100644 --- a/gb_math.h +++ b/gb_math.h @@ -1,9 +1,10 @@ -// gb_math.h - v0.04 - public domain C math library - no warranty implied; use at your own risk +// gb_math.h - v0.04a - public domain C math library - no warranty implied; use at your own risk // A C math library geared towards game development // use '#define GB_MATH_IMPLEMENTATION' before including to create the implementation in _ONE_ file /* Version History: + 0.04a - Minor bug fixes 0.04 - Namespace everything with gb 0.03 - Complete Replacement 0.01 - Initial Version @@ -20,12 +21,12 @@ WARNING CONTENTS - Common Macros - Types - - Vec(2,3,4) - - Mat(2,3,4) - - Float(2,3,4) + - gbVec(2,3,4) + - gbMat(2,3,4) + - gbFloat(2,3,4) - gbQuat - Rect(2,3) - - Aabb(2,3) + - gbAabb(2,3) - gb_half (16-bit floating point) (storage only) - Operations - Functions @@ -37,6 +38,7 @@ CONTENTS #ifndef GB_MATH_INCLUDE_GB_MATH_H #define GB_MATH_INCLUDE_GB_MATH_H +// TODO(bill): What of this do I actually need? And can include elsewhere (e.g. implementation) #include #include #include @@ -148,8 +150,8 @@ typedef short gb_half; #define GB_MATH_SQRT_THREE 1.73205080756887729352744634150587236f #define GB_MATH_SQRT_FIVE 2.23606797749978969640917366873127623f - #define GB_LOG_TWO 0.693147180559945309417232121458176568f - #define GB_LOG_TEN 2.30258509299404568401799145468436421f + #define GB_MATH_LOG_TWO 0.693147180559945309417232121458176568f + #define GB_MATH_LOG_TEN 2.30258509299404568401799145468436421f #endif @@ -161,8 +163,8 @@ extern "C" { GB_MATH_DEF float gb_clamp(float a, float lower, float upper); GB_MATH_DEF float gb_clamp01(float a); -GB_MATH_DEF float gb_as_radians(float degrees); -GB_MATH_DEF float gb_as_degrees(float radians); +GB_MATH_DEF float gb_to_radians(float degrees); +GB_MATH_DEF float gb_to_degrees(float radians); // NOTE(bill): Because to interpolate angles GB_MATH_DEF float gb_angle_diff(float radians_a, float radians_b); @@ -171,7 +173,7 @@ GB_MATH_DEF float gb_angle_diff(float radians_a, float radians_b); #define gb_max(a, b) ((a) > (b) ? (a) : (b)) GB_MATH_DEF float gb_sqrt(float a); -GB_MATH_DEF float gb_inv_sqrt(float a); // NOTE(bill): Fast inverse square root +GB_MATH_DEF float gb_quake_inv_sqrt(float a); // NOTE(bill): It's probably better to use 1.0f/gb_sqrt(a) GB_MATH_DEF float gb_sin(float radians); GB_MATH_DEF float gb_cos(float radians); @@ -506,7 +508,7 @@ gbVec4 &operator/=(gbVec4 &a, float scalar) { return (a = a / scalar); } gbMat2 operator+(gbMat2 const &a, gbMat2 const &b) { int i, j; - gbMat2 r = {}; + gbMat2 r = {0}; for (j = 0; j < 2; j++) { for (i = 0; i < 2; i++) r.e[2*j+i] = a.e[2*j+i] + b.e[2*j+i]; @@ -517,7 +519,7 @@ gbMat2 operator+(gbMat2 const &a, gbMat2 const &b) gbMat2 operator-(gbMat2 const &a, gbMat2 const &b) { int i, j; - gbMat2 r = {}; + gbMat2 r = {0}; for (j = 0; j < 2; j++) { for (i = 0; i < 2; i++) r.e[2*j+i] = a.e[2*j+i] - b.e[2*j+i]; @@ -529,7 +531,7 @@ gbMat2 operator*(gbMat2 const &a, gbMat2 const &b) { gbMat2 r; gb_mat2_mul(&r, ( gbVec2 operator*(gbMat2 const &a, gbVec2 v) { gbVec2 r; gb_mat2_mul_vec2(&r, (gbMat2 *)&a, v); return r; } gbMat2 operator*(gbMat2 const &a, float scalar) { - gbMat2 r = {}; + gbMat2 r = {0}; int i; for (i = 0; i < 2*2; i++) r.e[i] = a.e[i] * scalar; return r; @@ -546,7 +548,7 @@ gbMat2& operator*=(gbMat2& a, gbMat2 const &b) { return (a = a * b); } gbMat3 operator+(gbMat3 const &a, gbMat3 const &b) { int i, j; - gbMat3 r = {}; + gbMat3 r = {0}; for (j = 0; j < 3; j++) { for (i = 0; i < 3; i++) r.e[3*j+i] = a.e[3*j+i] + b.e[3*j+i]; @@ -557,7 +559,7 @@ gbMat3 operator+(gbMat3 const &a, gbMat3 const &b) gbMat3 operator-(gbMat3 const &a, gbMat3 const &b) { int i, j; - gbMat3 r = {}; + gbMat3 r = {0}; for (j = 0; j < 3; j++) { for (i = 0; i < 3; i++) r.e[3*j+i] = a.e[3*j+i] - b.e[3*j+i]; @@ -569,7 +571,7 @@ gbMat3 operator*(gbMat3 const &a, gbMat3 const &b) { gbMat3 r; gb_mat3_mul(&r, ( gbVec3 operator*(gbMat3 const &a, gbVec3 v) { gbVec3 r; gb_mat3_mul_vec3(&r, (gbMat3 *)&a, v); return r; } gbMat3 operator*(gbMat3 const &a, float scalar) { - gbMat3 r = {}; + gbMat3 r = {0}; int i; for (i = 0; i < 3*3; i++) r.e[i] = a.e[i] * scalar; return r; @@ -586,7 +588,7 @@ gbMat3& operator*=(gbMat3& a, gbMat3 const &b) { return (a = a * b); } gbMat4 operator+(gbMat4 const &a, gbMat4 const &b) { int i, j; - gbMat4 r = {}; + gbMat4 r = {0}; for (j = 0; j < 4; j++) { for (i = 0; i < 4; i++) r.e[4*j+i] = a.e[4*j+i] + b.e[4*j+i]; @@ -597,7 +599,7 @@ gbMat4 operator+(gbMat4 const &a, gbMat4 const &b) gbMat4 operator-(gbMat4 const &a, gbMat4 const &b) { int i, j; - gbMat4 r = {}; + gbMat4 r = {0}; for (j = 0; j < 4; j++) { for (i = 0; i < 4; i++) r.e[4*j+i] = a.e[4*j+i] - b.e[4*j+i]; @@ -609,7 +611,7 @@ gbMat4 operator*(gbMat4 const &a, gbMat4 const &b) { gbMat4 r; gb_mat4_mul(&r, ( gbVec4 operator*(gbMat4 const &a, gbVec4 v) { gbVec4 r; gb_mat4_mul_vec4(&r, (gbMat4 *)&a, v); return r; } gbMat4 operator*(gbMat4 const &a, float scalar) { - gbMat4 r = {}; + gbMat4 r = {0}; int i; for (i = 0; i < 4*4; i++) r.e[i] = a.e[i] * scalar; return r; @@ -688,6 +690,7 @@ gbVec3 operator*(gbQuat q, gbVec3 v) { gbVec3 r; gb_quat_rotate_vec3(&r, q, v); // // // // // // +// // //////////////////// #if defined(GB_MATH_IMPLEMENTATION) @@ -697,8 +700,8 @@ float gb_clamp(float a, float lower, float upper) { return a < lower ? lower : a float gb_clamp01(float a) { return gb_clamp(a, 0.0f, 1.0f); } -float gb_as_radians(float degrees) { return degrees * GB_MATH_TAU / 360.0f; } -float gb_as_degrees(float radians) { return radians * 360.0f / GB_MATH_TAU; } +float gb_to_radians(float degrees) { return degrees * GB_MATH_TAU / 360.0f; } +float gb_to_degrees(float radians) { return radians * 360.0f / GB_MATH_TAU; } float gb_angle_diff(float radians_a, float radians_b) @@ -711,8 +714,9 @@ gb_angle_diff(float radians_a, float radians_b) float gb_sqrt(float a) { return sqrtf(a); } + float -gb_inv_sqrt(float a) +gb_quake_inv_sqrt(float a) { int i; float x2, y; @@ -740,18 +744,19 @@ float gb_arctan2(float y, float x) { return atan2f(y, x); } float gb_exp(float x) { return expf(x); } -float gb_exp2(float x) { return gb_exp(0.69314718055994530941723212145818f * x); } +float gb_exp2(float x) { return gb_exp(GB_MATH_LOG_TWO * x); } float gb_log(float x) { return logf(x); } -float gb_log2(float x) { return gb_log(x) / 0.69314718055994530941723212145818f; } +float gb_log2(float x) { return gb_log(x) / GB_MATH_LOG_TWO; } float gb_fast_exp(float x) { - float e = 1.0f + x * (1.0f + x * 0.5f * (1.0f + x * 0.3333333333f * (1.0f + x * 0.25 * (1.0f + x * 0.2f)))); + // NOTE(bill): Only works in the range -1 <= x <= +1 + float e = 1.0f + x*(1.0f + x*0.5f*(1.0f + x*0.3333333333f*(1.0f + x*0.25*(1.0f + x*0.2f)))); return e; } -float gb_fast_exp2(float x) { return gb_fast_exp(0.69314718055994530941723212145818f * x); } +float gb_fast_exp2(float x) { return gb_fast_exp(GB_MATH_LOG_TWO * x); } // TODO(bill): Should this be gb_exp(y * gb_log(x)) ??? float gb_pow(float x, float y) { return powf(x, y); } @@ -773,7 +778,6 @@ gb_half_to_float(gb_half value) if (e == 0) { if(m == 0) { // Plus or minus zero - gb_uif32 result; result.i = (unsigned int)(s << 31); return result.f; } else { @@ -789,26 +793,18 @@ gb_half_to_float(gb_half value) } else if (e == 31) { if (m == 0) { // Positive or negative infinity - gb_uif32 result; result.i = (unsigned int)((s << 31) | 0x7f800000); return result.f; } else { // Nan - gb_uif32 result; result.i = (unsigned int)((s << 31) | 0x7f800000 | (m << 13)); return result.f; } } - // Normalized number - e = e + (127 - 15); m = m << 13; - // - // Assemble s, e and m. - // - result.i = (unsigned int)((s << 31) | (e << 23) | m); return result.f; } @@ -828,9 +824,7 @@ gb_float_to_half(float value) if (e <= 0) { - if (e < -10) { - return (gb_half)s; - } + if (e < -10) return (gb_half)s; m = (m | 0x00800000) >> (1 - e); if (m & 0x00001000) @@ -839,10 +833,9 @@ gb_float_to_half(float value) return (gb_half)(s | (m >> 13)); } else if (e == 0xff - (127 - 15)) { if (m == 0) { - // infinity - return (gb_half)(s | 0x7c00); + return (gb_half)(s | 0x7c00); // NOTE(bill): infinity } else { - // NAN + // NOTE(bill): NAN m >>= 13; return (gb_half)(s | 0x7c00 | m | (m == 0)); } @@ -856,7 +849,7 @@ gb_float_to_half(float value) } if (e > 30) { - float volatile f = 1e10; + float volatile f = 1e12f; for (unsigned int j = 0; j < 10; j++) f *= f; // NOTE(bill): Cause overflow @@ -949,6 +942,16 @@ void gb_vec4_muleq(gbVec4 *d, float s) { GB_VEC4_2OP(d,(*d),* s); } void gb_vec4_diveq(gbVec4 *d, float s) { GB_VEC4_2OP(d,(*d),/ s); } +#undef GB_VEC2_2OP +#undef GB_VEC2_3OP +#undef GB_VEC3_3OP +#undef GB_VEC3_2OP +#undef GB_VEC4_2OP +#undef GB_VEC4_3OP + + + + float gb_vec2_dot(gbVec2 v0, gbVec2 v1) { return v0.x*v1.x + v0.y*v1.y; } float gb_vec3_dot(gbVec3 v0, gbVec3 v1) { return v0.x*v1.x + v0.y*v1.y + v0.z*v1.z; } float gb_vec4_dot(gbVec4 v0, gbVec4 v1) { return v0.x*v1.x + v0.y*v1.y + v0.z*v1.z + v0.w*v1.w; } @@ -1660,7 +1663,7 @@ void gb_vec2_lerp(gbVec2 *d, gbVec2 a, gbVec2 b, float t) { GB_VEC_LERPN(2, d, a void gb_vec3_lerp(gbVec3 *d, gbVec3 a, gbVec3 b, float t) { GB_VEC_LERPN(3, d, a, b, t); } void gb_vec4_lerp(gbVec4 *d, gbVec4 a, gbVec4 b, float t) { GB_VEC_LERPN(4, d, a, b, t); } - +#undef GB_VEC_LERPN void gb_quat_lerp(gbQuat *d, gbQuat a, gbQuat b, float t) { gb_vec4_lerp(&d->xyzw, a.xyzw, b.xyzw, t); } void gb_quat_nlerp(gbQuat *d, gbQuat a, gbQuat b, float t) { gb_quat_lerp(d, a, b, t); gb_quat_norm(d, *d); } @@ -1700,6 +1703,8 @@ void gb_quat_slerp_approx(gbQuat *d, gbQuat a, gbQuat b, float t) { // NOTE(bill): Derived by taylor expanding the geometric interpolation equation + // Even works okay for nearly anti-parallel versors!!! + // NOTE(bill): Extra interations cannot be used as they require angle^4 which is not worth it to approximate float tp = t + (1.0f - gb_quat_dot(a, b))/3.0f * t*(-2.0f*t*t + 3.0f*t - 1.0f); return gb_quat_nlerp(d, a, b, tp); } @@ -1918,8 +1923,8 @@ gb_rect2_intersection_result(gbRect2 a, gbRect2 b, gbRect2 *intersection) float gb_random_range_float(float min_inc, float max_inc) { - int int_result = gb_random_range_int(0, INT_MAX); - float result = int_result/(float)INT_MAX; + int int_result = gb_random_range_int(0, INT_MAX-1); // Prevent integer overflow + float result = int_result/(float)(INT_MAX-1); result *= max_inc - min_inc; result += min_inc; return result; From 386f6371d7c4ec7030f3bcf29d4b26d3be3f8a15 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Fri, 8 Apr 2016 22:44:18 +0100 Subject: [PATCH 06/15] Update gb_math.h --- gb_math.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/gb_math.h b/gb_math.h index debc376..d7d528a 100644 --- a/gb_math.h +++ b/gb_math.h @@ -25,7 +25,7 @@ CONTENTS - gbMat(2,3,4) - gbFloat(2,3,4) - gbQuat - - Rect(2,3) + - gbRect(2,3) - gbAabb(2,3) - gb_half (16-bit floating point) (storage only) - Operations @@ -174,6 +174,7 @@ GB_MATH_DEF float gb_angle_diff(float radians_a, float radians_b); GB_MATH_DEF float gb_sqrt(float a); GB_MATH_DEF float gb_quake_inv_sqrt(float a); // NOTE(bill): It's probably better to use 1.0f/gb_sqrt(a) + // And for simd, there is usually isqrt functions too! GB_MATH_DEF float gb_sin(float radians); GB_MATH_DEF float gb_cos(float radians); From f2ee608bd5e16e4efdaec66e3f5841dcca784c39 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Fri, 8 Apr 2016 23:05:38 +0100 Subject: [PATCH 07/15] Fix strict aliasing in gb_quake_inv_sqrt --- gb_math.h | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/gb_math.h b/gb_math.h index d7d528a..2ab2e96 100644 --- a/gb_math.h +++ b/gb_math.h @@ -1,9 +1,10 @@ -// gb_math.h - v0.04a - public domain C math library - no warranty implied; use at your own risk +// gb_math.h - v0.04b - public domain C math library - no warranty implied; use at your own risk // A C math library geared towards game development // use '#define GB_MATH_IMPLEMENTATION' before including to create the implementation in _ONE_ file /* Version History: + 0.04b - Fix strict aliasing in gb_quake_inv_sqrt 0.04a - Minor bug fixes 0.04 - Namespace everything with gb 0.03 - Complete Replacement @@ -719,19 +720,20 @@ float gb_sqrt(float a) { return sqrtf(a); } float gb_quake_inv_sqrt(float a) { - int i; - float x2, y; + union { + int i; + float f; + } t; + float x2; float const three_halfs = 1.5f; x2 = a * 0.5f; - y = a; - i = *(int *)&y; // Evil floating point bit level hacking - i = 0x5f375a86 - (i >> 1); // What the fuck? - y = *(float *)&i; - y = y * (three_halfs - (x2 * y * y)); // 1st iteration - y = y * (three_halfs - (x2 * y * y)); // 2nd iteration, this can be removed + t.f = a; + t.i = 0x5f375a86 - (t.i >> 1); // What the fuck? + t.f = t.f * (three_halfs - (x2 * t.f * t.f)); // 1st iteration + t.f = t.f * (three_halfs - (x2 * t.f * t.f)); // 2nd iteration, this can be removed - return y; + return t.f; } float gb_sin(float radians) { return sinf(radians); } From 5116635d04cc0357f8e6d7a4e163a37acc516cdb Mon Sep 17 00:00:00 2001 From: gingerBill Date: Fri, 8 Apr 2016 23:12:26 +0100 Subject: [PATCH 08/15] Update gb_math.h --- gb_math.h | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/gb_math.h b/gb_math.h index 2ab2e96..a43d948 100644 --- a/gb_math.h +++ b/gb_math.h @@ -421,7 +421,7 @@ GB_MATH_DEF int gb_rect2_intersection_result(gbRect2 a, gbRect2 b, gbRect2 *inte #define GB_MURMUR64_DEFAULT_SEED 0x9747b28c #endif // Hashing -GB_MATH_DEF gb_math_u64 gb_hash_murmur64(void const *key, size_t num_bytes, u64 seed); +GB_MATH_DEF gb_math_u64 gb_hash_murmur64(void const *key, size_t num_bytes, gb_math_u64 seed); // Random // TODO(bill): Use a generator for the random numbers @@ -853,7 +853,8 @@ gb_float_to_half(float value) if (e > 30) { float volatile f = 1e12f; - for (unsigned int j = 0; j < 10; j++) + unsigned int j; + for (j = 0; j < 10; j++) f *= f; // NOTE(bill): Cause overflow return (gb_half)(s | 0x7c00); @@ -1709,7 +1710,7 @@ gb_quat_slerp_approx(gbQuat *d, gbQuat a, gbQuat b, float t) // Even works okay for nearly anti-parallel versors!!! // NOTE(bill): Extra interations cannot be used as they require angle^4 which is not worth it to approximate float tp = t + (1.0f - gb_quat_dot(a, b))/3.0f * t*(-2.0f*t*t + 3.0f*t - 1.0f); - return gb_quat_nlerp(d, a, b, tp); + gb_quat_nlerp(d, a, b, tp); } void @@ -1816,7 +1817,7 @@ gb_rect2_intersection_result(gbRect2 a, gbRect2 b, gbRect2 *intersection) #if defined(__x86_64__) || defined(__ppc64__) gb_math_u64 - gb_hash_murmur64(void const *key, size_t num_bytes, u64 seed) + gb_hash_murmur64(void const *key, size_t num_bytes, gb_math_u64 seed) { gb_math_u64 const m = 0xc6a4a7935bd1e995ULL; gb_math_u64 const r = 47; @@ -1857,7 +1858,7 @@ gb_rect2_intersection_result(gbRect2 a, gbRect2 b, gbRect2 *intersection) } #else gb_math_u64 - gb_hash_murmur64(void const *key, size_t num_bytes, u64 seed) + gb_hash_murmur64(void const *key, size_t num_bytes, gb_math_u64 seed) { gb_math_u32 const m = 0x5bd1e995; gb_math_u32 const r = 24; From d840be2431961db20c78172c869a6b56a8d08ac1 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Fri, 8 Apr 2016 23:28:48 +0100 Subject: [PATCH 09/15] Use 64-bit murmur64 version on WIN64 --- gb_math.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/gb_math.h b/gb_math.h index a43d948..04f670d 100644 --- a/gb_math.h +++ b/gb_math.h @@ -1,9 +1,10 @@ -// gb_math.h - v0.04b - public domain C math library - no warranty implied; use at your own risk +// gb_math.h - v0.04c - public domain C math library - no warranty implied; use at your own risk // A C math library geared towards game development // use '#define GB_MATH_IMPLEMENTATION' before including to create the implementation in _ONE_ file /* Version History: + 0.04c - Use 64-bit murmur64 version on WIN64 0.04b - Fix strict aliasing in gb_quake_inv_sqrt 0.04a - Minor bug fixes 0.04 - Namespace everything with gb @@ -1814,8 +1815,7 @@ gb_rect2_intersection_result(gbRect2 a, gbRect2 b, gbRect2 *intersection) } -#if defined(__x86_64__) || defined(__ppc64__) - +#if defined(_WIN64) || defined(__x86_64__) || defined(__ppc64__) gb_math_u64 gb_hash_murmur64(void const *key, size_t num_bytes, gb_math_u64 seed) { From 24eb70c5c965924346f7f33156e9293937604d4a Mon Sep 17 00:00:00 2001 From: gingerBill Date: Fri, 8 Apr 2016 23:29:11 +0100 Subject: [PATCH 10/15] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ac7d035..f26823f 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ gb single-file public domain libraries for C & C++ library | latest version | category | languages | description ----------------|----------------|----------|-----------|------------- **gb_string.h** | 0.93 | strings | C, C++ | A better string library for C & C++ -**gb_math.h** | 0.04 | math | C | A C vector math library geared towards game development +**gb_math.h** | 0.04c | math | C | A C vector math library geared towards game development **gb.h** | 0.01 | misc | C | A C helper library geared towards game development (NOT a port of gb.hpp) **gb_ini.h** | 0.91a | misc | C, C++ | A simple ini file loader library for C & C++ **gb.hpp** | 0.32 | misc | C++11 | (Experimental) A C++11 helper library without STL geared towards game development From 047348c585528f4e9940c793a7b54c01bd5ed2fb Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sun, 10 Apr 2016 23:44:24 +0100 Subject: [PATCH 11/15] License Update --- gb_math.h | 85 ++++++++++++++++++++++++++----------------------------- 1 file changed, 40 insertions(+), 45 deletions(-) diff --git a/gb_math.h b/gb_math.h index 04f670d..6e363c0 100644 --- a/gb_math.h +++ b/gb_math.h @@ -1,9 +1,10 @@ -// gb_math.h - v0.04c - public domain C math library - no warranty implied; use at your own risk +// gb_math.h - v0.04d - public domain C math library - no warranty implied; use at your own risk // A C math library geared towards game development // use '#define GB_MATH_IMPLEMENTATION' before including to create the implementation in _ONE_ file /* Version History: + 0.04d - License Update 0.04c - Use 64-bit murmur64 version on WIN64 0.04b - Fix strict aliasing in gb_quake_inv_sqrt 0.04a - Minor bug fixes @@ -12,10 +13,9 @@ Version History: 0.01 - Initial Version LICENSE - This software is in the public domain. Where that dedication is not - recognized, you are granted a perpetual, irrevocable license to copy, - distribute, and modify this file as you see fit. - + This software is dual-licensed to the public domain and under the following + license: you are granted a perpetual, irrevocable license to copy, modify, + publish, and distribute this file as you see fit. WARNING - This library is _slightly_ experimental and features may not work as expected. - This also means that many functions are not documented. @@ -45,6 +45,7 @@ CONTENTS #include #include #include +#include // memcpy, memmove, etc. #ifndef GB_MATH_DEF #ifdef GB_MATH_STATIC @@ -152,8 +153,8 @@ typedef short gb_half; #define GB_MATH_SQRT_THREE 1.73205080756887729352744634150587236f #define GB_MATH_SQRT_FIVE 2.23606797749978969640917366873127623f - #define GB_MATH_LOG_TWO 0.693147180559945309417232121458176568f - #define GB_MATH_LOG_TEN 2.30258509299404568401799145468436421f + #define GB_MATH_LOG_TWO 0.693147180559945309417232121458176568f + #define GB_MATH_LOG_TEN 2.30258509299404568401799145468436421f #endif @@ -171,8 +172,12 @@ GB_MATH_DEF float gb_to_degrees(float radians); // NOTE(bill): Because to interpolate angles GB_MATH_DEF float gb_angle_diff(float radians_a, float radians_b); +#ifndef gb_min #define gb_min(a, b) ((a) < (b) ? (a) : (b)) +#endif +#ifndef gb_max #define gb_max(a, b) ((a) > (b) ? (a) : (b)) +#endif GB_MATH_DEF float gb_sqrt(float a); GB_MATH_DEF float gb_quake_inv_sqrt(float a); // NOTE(bill): It's probably better to use 1.0f/gb_sqrt(a) @@ -775,12 +780,12 @@ float gb_half_to_float(gb_half value) { gb_uif32 result; - int s = (value >> 15) & 0x00000001; - int e = (value >> 10) & 0x0000001f; - int m = value & 0x000003ff; + int s = (value >> 15) & 0x001; + int e = (value >> 10) & 0x01f; + int m = value & 0x3ff; if (e == 0) { - if(m == 0) { + if (m == 0) { // Plus or minus zero result.i = (unsigned int)(s << 31); return result.f; @@ -917,34 +922,34 @@ gbVec4 gb_vec4v(float x[4]) { gbVec4 v = {x[0], x[1], x[2 void gb_vec2_add(gbVec2 *d, gbVec2 v0, gbVec2 v1) { GB_VEC2_3OP(d,v0,+,v1,+0); } void gb_vec2_sub(gbVec2 *d, gbVec2 v0, gbVec2 v1) { GB_VEC2_3OP(d,v0,-,v1,+0); } -void gb_vec2_mul(gbVec2 *d, gbVec2 v, float s) { GB_VEC2_2OP(d,v,* s); } -void gb_vec2_div(gbVec2 *d, gbVec2 v, float s) { GB_VEC2_2OP(d,v,/ s); } +void gb_vec2_mul(gbVec2 *d, gbVec2 v, float s) { GB_VEC2_2OP(d,v,* s); } +void gb_vec2_div(gbVec2 *d, gbVec2 v, float s) { GB_VEC2_2OP(d,v,/ s); } void gb_vec3_add(gbVec3 *d, gbVec3 v0, gbVec3 v1) { GB_VEC3_3OP(d,v0,+,v1,+0); } void gb_vec3_sub(gbVec3 *d, gbVec3 v0, gbVec3 v1) { GB_VEC3_3OP(d,v0,-,v1,+0); } -void gb_vec3_mul(gbVec3 *d, gbVec3 v, float s) { GB_VEC3_2OP(d,v,* s); } -void gb_vec3_div(gbVec3 *d, gbVec3 v, float s) { GB_VEC3_2OP(d,v,/ s); } +void gb_vec3_mul(gbVec3 *d, gbVec3 v, float s) { GB_VEC3_2OP(d,v,* s); } +void gb_vec3_div(gbVec3 *d, gbVec3 v, float s) { GB_VEC3_2OP(d,v,/ s); } void gb_vec4_add(gbVec4 *d, gbVec4 v0, gbVec4 v1) { GB_VEC4_3OP(d,v0,+,v1,+0); } void gb_vec4_sub(gbVec4 *d, gbVec4 v0, gbVec4 v1) { GB_VEC4_3OP(d,v0,-,v1,+0); } -void gb_vec4_mul(gbVec4 *d, gbVec4 v, float s) { GB_VEC4_2OP(d,v,* s); } -void gb_vec4_div(gbVec4 *d, gbVec4 v, float s) { GB_VEC4_2OP(d,v,/ s); } +void gb_vec4_mul(gbVec4 *d, gbVec4 v, float s) { GB_VEC4_2OP(d,v,* s); } +void gb_vec4_div(gbVec4 *d, gbVec4 v, float s) { GB_VEC4_2OP(d,v,/ s); } -void gb_vec2_addeq(gbVec2 *d, gbVec2 v) { GB_VEC2_3OP(d,(*d),+,v,+0); } -void gb_vec2_subeq(gbVec2 *d, gbVec2 v) { GB_VEC2_3OP(d,(*d),-,v,+0); } -void gb_vec2_muleq(gbVec2 *d, float s) { GB_VEC2_2OP(d,(*d),* s); } -void gb_vec2_diveq(gbVec2 *d, float s) { GB_VEC2_2OP(d,(*d),/ s); } +void gb_vec2_addeq(gbVec2 *d, gbVec2 v) { GB_VEC2_3OP(d,(*d),+,v,+0); } +void gb_vec2_subeq(gbVec2 *d, gbVec2 v) { GB_VEC2_3OP(d,(*d),-,v,+0); } +void gb_vec2_muleq(gbVec2 *d, float s) { GB_VEC2_2OP(d,(*d),* s); } +void gb_vec2_diveq(gbVec2 *d, float s) { GB_VEC2_2OP(d,(*d),/ s); } -void gb_vec3_addeq(gbVec3 *d, gbVec3 v) { GB_VEC3_3OP(d,(*d),+,v,+0); } -void gb_vec3_subeq(gbVec3 *d, gbVec3 v) { GB_VEC3_3OP(d,(*d),-,v,+0); } -void gb_vec3_muleq(gbVec3 *d, float s) { GB_VEC3_2OP(d,(*d),* s); } -void gb_vec3_diveq(gbVec3 *d, float s) { GB_VEC3_2OP(d,(*d),/ s); } +void gb_vec3_addeq(gbVec3 *d, gbVec3 v) { GB_VEC3_3OP(d,(*d),+,v,+0); } +void gb_vec3_subeq(gbVec3 *d, gbVec3 v) { GB_VEC3_3OP(d,(*d),-,v,+0); } +void gb_vec3_muleq(gbVec3 *d, float s) { GB_VEC3_2OP(d,(*d),* s); } +void gb_vec3_diveq(gbVec3 *d, float s) { GB_VEC3_2OP(d,(*d),/ s); } -void gb_vec4_addeq(gbVec4 *d, gbVec4 v) { GB_VEC4_3OP(d,(*d),+,v,+0); } -void gb_vec4_subeq(gbVec4 *d, gbVec4 v) { GB_VEC4_3OP(d,(*d),-,v,+0); } -void gb_vec4_muleq(gbVec4 *d, float s) { GB_VEC4_2OP(d,(*d),* s); } -void gb_vec4_diveq(gbVec4 *d, float s) { GB_VEC4_2OP(d,(*d),/ s); } +void gb_vec4_addeq(gbVec4 *d, gbVec4 v) { GB_VEC4_3OP(d,(*d),+,v,+0); } +void gb_vec4_subeq(gbVec4 *d, gbVec4 v) { GB_VEC4_3OP(d,(*d),-,v,+0); } +void gb_vec4_muleq(gbVec4 *d, float s) { GB_VEC4_2OP(d,(*d),* s); } +void gb_vec4_diveq(gbVec4 *d, float s) { GB_VEC4_2OP(d,(*d),/ s); } #undef GB_VEC2_2OP @@ -1072,13 +1077,7 @@ gb_vec3_refract(gbVec3 *d, gbVec3 i, gbVec3 n, float eta) -float -gb_vec2_aspect_ratio(gbVec2 v) -{ - if (v.y < 0.0001f) - return 0.0f; - return v.x/v.y; -} +float gb_vec2_aspect_ratio(gbVec2 v) { return (v.y < 0.0001f) ? 0.0f : v.x/v.y; } @@ -1095,18 +1094,14 @@ gb_float22_identity(float m[2][2]) m[1][0] = 0; m[1][1] = 1; } -void -gb_mat2_mul_vec2(gbVec2 *out, gbMat2 *m, gbVec2 in) -{ - gb_float22_mul_vec2(out, gb_float22_m(m), in); -} +void gb_mat2_mul_vec2(gbVec2 *out, gbMat2 *m, gbVec2 in) { gb_float22_mul_vec2(out, gb_float22_m(m), in); } -gbMat2 *gb_mat2_v(gbVec2 m[2]) { return (gbMat2 *)m; } +gbMat2 *gb_mat2_v(gbVec2 m[2]) { return (gbMat2 *)m; } gbMat2 *gb_mat2_f(float m[2][2]) { return (gbMat2 *)m; } -gbFloat2 *gb_float22_m(gbMat2 *m) { return (gbFloat2 *)m; } -gbFloat2 *gb_float22_v(gbVec2 m[2]) { return (gbFloat2 *)m; } -gbFloat2 *gb_float22_4(float m[4]) { return (gbFloat2 *)m; } +gbFloat2 *gb_float22_m(gbMat2 *m) { return (gbFloat2 *)m; } +gbFloat2 *gb_float22_v(gbVec2 m[2]) { return (gbFloat2 *)m; } +gbFloat2 *gb_float22_4(float m[4]) { return (gbFloat2 *)m; } void gb_float22_transpose(float (*vec)[2]) From ce56da2ff4c0a5b02be4f9d03f0b20106acf91de Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sun, 10 Apr 2016 23:44:42 +0100 Subject: [PATCH 12/15] New gb.h!!!! --- gb.h | 1844 +++++++++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 1444 insertions(+), 400 deletions(-) diff --git a/gb.h b/gb.h index d70c8cc..ed16d80 100644 --- a/gb.h +++ b/gb.h @@ -1,149 +1,175 @@ -// gb.h - v0.02 - public domain C helper library - no warranty implied; use at your own risk -// (Experimental) A C helper library geared towards game development +/* gb.h - v0.02 - Ginger Bill's C Helper Library - public domain + - no warranty implied; use at your own risk + + This is a single header file with a bunch of useful stuff + to replace the C/C++ standard library + +=========================================================================== + YOU MUST + + #define GB_IMPLEMENTATION + + in EXACTLY _one_ C or C++ file that includes this header, BEFORE the + include like this: + + #define GB_IMPLEMENTATION + #include "gb.h" + + All other files should just #include "gb.h" without #define +=========================================================================== + + +Version History: + 0.02 - Change naming convention and gbArray(Type) + 0.01 - Initial Version -/* LICENSE - This software is in the public domain. Where that dedication is not - recognized, you are granted a perpetual, irrevocable license to copy, - distribute, and modify this file as you see fit. + This software is dual-licensed to the public domain and under the following + license: you are granted a perpetual, irrevocable license to copy, modify, + publish, and distribute this file as you see fit. WARNING - - This library is _highly_ experimental and features may not work as expected. + - This library is _slightly_ experimental and features may not work as expected. - This also means that many functions are not documented. -CONTENTS - - Common Macros - - Assert - - Types - - Cast macro (easy grepping) - - Memory - - Custom Allocation - - gb_Allocator - - gb_Arena - - gb_Pool - - gb_String +CREDITS + Written by Ginger Bill -TODO - - Mutex - - Atomics - - Semaphore - - Thread - - OS Types and Functions (File/IO/OS/etc.) -*/ - -/* -Version History: - 0.02 - Minor fixes - 0.01 - Initial Version */ #ifndef GB_INCLUDE_GB_H #define GB_INCLUDE_GB_H + +#if defined(_WIN32) && !defined(__MINGW32__) + #ifndef _CRT_SECURE_NO_WARNINGS + #define _CRT_SECURE_NO_WARNINGS + #endif +#endif + +#include +#include +#include +#include +#include // NOTE(bill): For memcpy, memmove, memcmp, etc. + +#if !defined(GB_NO_STDLIB) +#include +#endif + #if defined(__cplusplus) extern "C" { #endif -#include -#include - -// NOTE(bill): Because static means three different things in C/C++ -// Great design(!) -#ifndef local_persist -#define global static -#define internal static -#define local_persist static -#endif - -// NOTE(bill): If I put gb_inline, I _want_ it inlined -#ifndef gb_inline - #if defined(_MSC_VER) - #define gb_inline __forceinline +#ifndef GB_DEF + #ifdef GB_STATIC + #define GB_DEF static #else - #define gb_inline __attribute__ ((__always_inline__)) + #define GB_DEF extern #endif #endif - -#if !defined(GB_NO_STDIO) -#include +#if defined(_WIN32) || defined(_WIN64) + #if defined(_WIN64) + #ifndef GB_ARCH_64_BIT + #define GB_ARCH_64_BIT 1 + #endif + #else + #ifndef GB_ARCH_32_BIT + #define GB_ARCH_32_BIT 1 + #endif + #endif #endif -#ifndef GB_ASSERT -#include -#define GB_ASSERT(cond) assert(cond) -#define GB_ASSERT_MSG(cond, msg) assert((cond) && (msg)) +// TODO(bill): Check if this works on clang +#if defined(__GNUC__) + #if defined(__x86_64__) || defined(__ppc64__) + #ifndef GB_ARCH_64_BIT + #define GB_ARCH_64_BIT 1 + #endif + #else + #ifndef GB_ARCH_32_BIT + #define GB_ARCH_32_BIT 1 + #endif + #endif #endif -#define GB_STATIC_ASSERT3(cond, msg) typedef char gb__static_assertion_##msg[(!!(cond))*2-1] -// NOTE(bill): Token pasting madness -#define GB_STATIC_ASSERT2(cond, line) GB_STATIC_ASSERT3(cond, static_assertion_at_line_##line) -#define GB_STATIC_ASSERT1(cond, line) GB_STATIC_ASSERT2(cond, line) -#define GB_STATIC_ASSERT(cond) GB_STATIC_ASSERT1(cond, __LINE__) +#ifndef GB_EDIAN_ORDER +#define GB_EDIAN_ORDER + #define GB_IS_BIG_EDIAN (!*(u8*)&(u16){1}) + #define GB_IS_LITTLE_EDIAN (!GB_IS_BIG_EDIAN) +#endif -#if !defined(GB_NO_STDIO) && defined(_MSC_VER) - // snprintf_msvc - gb_inline int - gb__vsnprintf_compatible(char* buffer, size_t size, char const *format, va_list args) - { - int result = -1; - if (size > 0) - result = _vsnprintf_s(buffer, size, _TRUNCATE, format, args); - if (result == -1) - return _vscprintf(format, args); - return result; - } - - gb_inline int - gb__snprintf_compatible(char* buffer, size_t size, char const *format, ...) - { - int result = -1; - va_list args; - va_start(args, format); - result = gb__vsnprintf_compatible(buffer, size, format, args); - va_end(args); - return result; - } - - #if !defined(GB_DO_NOT_USE_MSVC_SPRINTF_FIX) - #define snprintf gb__snprintf_compatible - #define vsnprintf gb__vsnprintf_compatible - #endif /* GB_DO_NOT_USE_MSVC_SPRINTF_FIX */ -#endif /* !defined(GB_NO_STDIO) */ +#if defined(_WIN32) || defined(_WIN64) + #ifndef GB_SYSTEM_WINDOWS + #define GB_SYSTEM_WINDOWS 1 + #endif +#elif defined(__APPLE__) && defined(__MACH__) + #ifndef GB_SYSTEM_OSX + #define GB_SYSTEM_OSX 1 + #endif +#elif defined(__unix__) + #ifndef GB_SYSTEM_UNIX + #define GB_SYSTEM_UNIX 1 + #endif + #if defined(__linux__) + #ifndef GB_SYSTEM_LINUX + #define GB_SYSTEM_LINUX 1 + #endif + #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) + #ifndef GB_SYSTEM_FREEBSD + #define GB_SYSTEM_FREEBSD 1 + #endif + #else + #error This UNIX operating system is not supported + #endif +#else + #error This operating system is not supported +#endif +#ifndef GB_STATIC_ASSERT + #define GB_STATIC_ASSERT3(cond, msg) typedef char static_assertion_##msg[(!!(cond))*2-1] + // NOTE(bill): Token pasting madness!! + #define GB_STATIC_ASSERT2(cond, line) GB_STATIC_ASSERT3(cond, static_assertion_at_line_##line) + #define GB_STATIC_ASSERT1(cond, line) GB_STATIC_ASSERT2(cond, line) + #define GB_STATIC_ASSERT(cond) GB_STATIC_ASSERT1(cond, __LINE__) +#endif #if defined(_MSC_VER) - typedef unsigned __int8 u8; - typedef signed __int8 s8; + typedef unsigned __int8 u8; + typedef signed __int8 i8; typedef unsigned __int16 u16; - typedef signed __int16 s16; + typedef signed __int16 i16; typedef unsigned __int32 u32; - typedef signed __int32 s32; + typedef signed __int32 i32; typedef unsigned __int64 u64; - typedef signed __int64 s64; + typedef signed __int64 i64; #else #include - typedef uint8_t u8; - typedef int8_t s8; + typedef uint8_t u8; + typedef int8_t i8; typedef uint16_t u16; - typedef int16_t s16; + typedef int16_t i16; typedef uint32_t u32; - typedef int32_t s32; + typedef int32_t i32; typedef uint64_t u64; - typedef int64_t s64; + typedef int64_t i64; #endif -GB_STATIC_ASSERT(sizeof(s8) == 1); -GB_STATIC_ASSERT(sizeof(s16) == 2); -GB_STATIC_ASSERT(sizeof(s32) == 4); -GB_STATIC_ASSERT(sizeof(s64) == 8); +GB_STATIC_ASSERT(sizeof(u8) == 1); +GB_STATIC_ASSERT(sizeof(u16) == 2); +GB_STATIC_ASSERT(sizeof(u32) == 4); +GB_STATIC_ASSERT(sizeof(u64) == 8); -typedef size_t usize; +typedef size_t usize; +typedef ptrdiff_t isize; + +GB_STATIC_ASSERT(sizeof(usize) == sizeof(isize)); typedef uintptr_t uintptr; typedef intptr_t intptr; @@ -151,23 +177,32 @@ typedef intptr_t intptr; typedef float f32; typedef double f64; -#if defined(_MSC_VER) && _MSC_VER < 1900 - #ifndef false - #define false 0 - #endif +GB_STATIC_ASSERT(sizeof(f32) == 4); +GB_STATIC_ASSERT(sizeof(f64) == 8); - #ifndef true - #define true 1 +typedef u16 char16; +typedef u32 char32; + + +// NOTE(bill): I think C99 and C++ `bool` is stupid for numerous reasons but there are too many +// to write in this small comment. +typedef i32 b32; // NOTE(bill): Use this in structs if a boolean _is_ needed to be aligned well +typedef i8 b8; + +// NOTE(bill): Get true and false +#if !defined(__cplusplus) + #if defined(_MSC_VER) && _MSC_VER <= 1800 + #ifndef false + #define false 0 + #endif + #ifndef true + #define true 1 + #endif + #else + #include #endif -#else - #include // NOTE(bill): To get false/true #endif -// Boolean Types -typedef s8 b8; -typedef s32 b32; - - #ifndef U8_MIN #define U8_MIN 0u #define U8_MAX 0xffu @@ -186,32 +221,49 @@ typedef s32 b32; #define U64_MIN 0ull #define U64_MAX 0xffffffffffffffffull -#define S64_MIN (-0x7fffffffffffffffll - 1) -#define S64_MAX 0x7fffffffffffffffll +#define I64_MIN (-0x7fffffffffffffffll - 1) +#define I64_MAX 0x7fffffffffffffffll + +#if defined(GB_ARCH_32_BIT) + #define USIZE_MIX U32_MIN + #define USIZE_MAX U32_MAX + + #define ISIZE_MIX S32_MIN + #define ISIZE_MAX S32_MAX +#elif defined(GB_ARCH_64_BIT) + #define USIZE_MIX U64_MIN + #define USIZE_MAX U64_MAX + + #define ISIZE_MIX I64_MIN + #define ISIZE_MAX I64_MAX +#else + #error Unknown architecture size +#endif + #endif - -#ifndef COUNT_OF -#define COUNT_OF(x) (sizeof((x)) / sizeof(0[(x)])) -#endif - -// NOTE(bill): Allows for easy grep of casts -// NOTE(bill): Still not as type safe as C++ static_cast, reinterpret_cast, and const_cast, but I don't need them -#ifndef cast -#define cast(x) (x) -#endif - #ifndef NULL -#define NULL ((void *)0) + #if defined(__cplusplus) + #if __cplusplus >= 201103L + #define NULL nullptr + #else + #define NULL 0 + #endif + #else + #define NULL ((void *)0) + #endif #endif -#ifndef GB_UNUSED -#define GB_UNUSED(x) ((void)(sizeof(x))) + + +#if !defined(__cplusplus) && defined(_MSC_VER) && _MSC_VER <= 1800 + #define inline __inline #endif -#ifndef gb_inline + +#if !defined(gb_inline) #if defined(_MSC_VER) #define gb_inline __forceinline #else @@ -219,9 +271,174 @@ typedef s32 b32; #endif #endif +#if !defined(gb_no_inline) + #if defined(_MSC_VER) + #define gb_no_inline __declspec(noinline) + #else + #define gb_no_inline __attribute__ ((noinline)) + #endif +#endif + +#ifndef GB_EXTERN + #if defined(__cplusplus) + #define GB_EXTERN extern "C" + #else + #define GB_EXTERN extern + #endif +#endif +// NOTE(bill): Easy to grep +// NOTE(bill): Not needed in macros +#ifndef cast +#define cast(Type) (Type) +#endif + + +#ifndef gb_size_of +#define gb_size_of(x) cast(i64)(sizeof(x)) +#endif + +#ifndef gb_count_of +#define gb_count_of(x) ((gb_size_of(x)/gb_size_of(0[x])) / ((usize)(!(gb_size_of(x) % gb_size_of(0[x]))))) +#endif + +#ifndef gb_offset_of +#define gb_offset_of(Type, element) ((usize)&(((Type *)0)->element)) +#endif + +#if defined(__cplusplus) +extern "C++" { + #ifndef gb_align_of + template struct gb_Alignment_Trick { char c; T member; }; + #define gb_align_of(Type) offset_of(gb_Alignment_Trick, member) + #endif +} +#else + #ifndef gb_align_of + #define gb_align_of(Type) offs(struct { char c; Type member; }, member) + #endif +#endif + +#ifndef gb_swap +#define gb_swap(Type, a, b) do { Type tmp = (a); (a) = (b); (b) = tmp; } while (0) +#endif + +// NOTE(bill): Because static means 3/4 different things in C/C++. Great design (!) +#ifndef gb_global +#define gb_global static +#define gb_internal static +#define gb_local_persist static +#endif + + +#ifndef gb_unused +#define gb_unused(x) ((void)(gb_size_of(x))) +#endif + + + + +//////////////////////////////////////////////////////////////// +// +// Defer statement +// - Akin to D's SCOPE_EXIT or similar to Go's defer but scope-based +// +//////////////////////////////////////////////////////////////// +#if defined(__cplusplus) +extern "C++" { + // NOTE(bill): Stupid fucking templates + template struct gbRemove_Reference { typedef T Type; }; + template struct gbRemove_Reference { typedef T Type; }; + template struct gbRemove_Reference { typedef T Type; }; + + // NOTE(bill): "Move" semantics - invented because the C++ committee are idiots (as a collective not as indiviuals (well a least some aren't)) + template gb_inline T &&gb_forward_ownership(typename gbRemove_Reference::Type &t) { return static_cast(t); } + template gb_inline T &&gb_forward_ownership(typename gbRemove_Reference::Type &&t) { return static_cast(t); } + + template + struct gbImpl_Defer { + F f; + gbImpl_Defer(F &&f) : f(gb_forward_ownership(f)) {} + ~gbImpl_Defer() { f(); } + }; + template gbImpl_Defer gb_defer_func(F &&f) { return gbImpl_Defer(gb_forward_ownership(f)); } + + #ifndef defer + #define GB_DEFER_1(x, y) x##y + #define GB_DEFER_2(x, y) GB_DEFER_1(x, y) + #define GB_DEFER_3(x) GB_DEFER_2(x, __COUNTER__) + #define defer(code) auto GB_DEFER_3(_defer_) = gb_defer_func([&](){code;}) + #endif +} +#endif + + + + +#ifndef gb_min +#define gb_min(a, b) ((a) < (b) ? (a) : (b)) +#endif + +#ifndef gb_max +#define gb_max(a, b) ((a) > (b) ? (a) : (b)) +#endif + + + + +//////////////////////////////// +// // +// Debug // +// // +//////////////////////////////// + + +#ifndef GB_DEBUG_TRAP + #if defined(_MSC_VER) + #define GB_DEBUG_TRAP() __debugbreak() + #else + #define GB_DEBUG_TRAP() __builtin_trap() + #endif +#endif + +// TODO(bill): This relies upon variadic macros which are not supported in MSVC 2003 and below, check for it if needed +#ifndef GB_ASSERT_MSG +#define GB_ASSERT_MSG(cond, msg, ...) do { \ + if (!(cond)) { \ + gb_assert_handler(#cond, __FILE__, (long long)__LINE__, msg, ##__VA_ARGS__); \ + GB_DEBUG_TRAP(); \ + } \ +} while (0) +#endif + +#ifndef GB_ASSERT +#define GB_ASSERT(cond) GB_ASSERT_MSG(cond, NULL) +#endif + +#ifndef GB_PANIC +#define GB_PANIC(msg, ...) GB_ASSERT_MSG(0, msg, ##__VA_ARGS__) +#endif + +GB_DEF void gb_assert_handler(char const *condition, + char const *file, long long line, + char const *msg, ...); + + + + + +//////////////////////////////// +// // +// Printing // +// // +//////////////////////////////// + +GB_DEF int gb_sprintf(char const *fmt, ...); +GB_DEF int gb_snprintf(char *str, usize n, char const *fmt, ...); +GB_DEF int gb_vsprintf(char const *fmt, va_list v); +GB_DEF int gb_vsnprintf(char *str, usize n, char const *fmt, va_list v); @@ -231,42 +448,45 @@ typedef s32 b32; // // //////////////////////////////// -#include // For memcpy/memmove/memset/etc. - -#ifndef GB_IS_POWER_OF_TWO -#define GB_IS_POWER_OF_TWO(x) ((x) != 0) && !((x) & ((x)-1)) +#ifndef gb_align_to +#define gb_align_to(value, alignment) (((value) + ((alignment)-1)) & ~((alignment) - 1)) #endif -void *gb_align_forward(void *ptr, usize align); +#ifndef gb_is_power_of_two +#define gb_is_power_of_two(x) ((x) != 0) && !((x) & ((x)-1)) +#endif -void gb_zero_size(void *ptr, usize size); -#define gb_zero_struct(t) gb_zero_size((t), sizeof(*(t))) // NOTE(bill): Pass pointer of struct -#define gb_zero_array(a, count) gb_zero_size((a), sizeof((a)[0])*count) +GB_DEF void *gb_align_forward(void *ptr, usize alignment); +GB_DEF void gb_zero_size(void *ptr, usize size); -#if defined(GB_IMPLEMENTATION) -gb_inline void * -gb_align_forward(void *ptr, usize align) -{ - uintptr p; - usize modulo; +#ifndef gb_zero_struct +#define gb_zero_struct(t) gb_zero_size((t), gb_size_of(*(t))) // NOTE(bill): Pass pointer of struct +#define gb_zero_array(a, count) gb_zero_size((a), gb_size_of((a)[0])*count) +#endif - GB_ASSERT(GB_IS_POWER_OF_TWO(align)); - - p = cast(uintptr)ptr; - modulo = p % align; - if (modulo) p += (align - modulo); - return cast(void *)p; -} - -gb_inline void gb_zero_size(void *ptr, usize size) { memset(ptr, 0, size); } - -#endif // GB_IMPLEMENTATION +GB_DEF void *gb_memcpy(void *dest, void const *source, usize size); +GB_DEF void *gb_memmove(void *dest, void const *source, usize size); +#ifndef gb_kilobytes +#define gb_kilobytes(x) ( (x) * (i64)(1024)) +#define gb_megabytes(x) (gb_kilobytes(x) * (i64)(1024)) +#define gb_gigabytes(x) (gb_megabytes(x) * (i64)(1024)) +#define gb_terabytes(x) (gb_gigabytes(x) * (i64)(1024)) +#endif +// Mutex +typedef struct gbMutex { void *handle; } gbMutex; + +GB_DEF gbMutex gb_make_mutex(void); +GB_DEF void gb_destroy_mutex(gbMutex *m); +GB_DEF void gb_lock_mutex(gbMutex *m); +GB_DEF void gb_try_lock_mutex(gbMutex *m); +GB_DEF void gb_unlock_mutex(gbMutex *m); + @@ -276,78 +496,106 @@ gb_inline void gb_zero_size(void *ptr, usize size) { memset(ptr, 0, size); } // // //////////////////////////////// -typedef enum gb_Allocation_Type -{ +typedef enum gbAllocation_Type { GB_ALLOCATION_TYPE_ALLOC, GB_ALLOCATION_TYPE_FREE, GB_ALLOCATION_TYPE_FREE_ALL, GB_ALLOCATION_TYPE_RESIZE, -} gb_Allocation_Type; +} gbAllocation_Type; +// NOTE(bill): This is useful so you can define an allocator of the same type and parameters +#define GB_ALLOCATOR_PROC(name) \ +void *name(void *allocator_data, gbAllocation_Type type, \ + usize size, usize alignment, \ + void *old_memory, usize old_size, \ + u32 options) +typedef GB_ALLOCATOR_PROC(gbAllocator_Proc); -#ifndef GB_ALLOCATOR_PROCEDURE -#define GB_ALLOCATOR_PROCEDURE(name) void *name(void *allocator_data, gb_Allocation_Type type, usize size, usize alignment, void *old_memory, usize old_size, u32 options) -#endif -typedef GB_ALLOCATOR_PROCEDURE(gb_Allocator_Procedure); - -typedef struct gb_Allocator -{ - gb_Allocator_Procedure *procedure; +typedef struct gbAllocator { + gbAllocator_Proc *proc; void *data; -} gb_Allocator; +} gbAllocator; -#ifndef GB_DEFAULT_ALIGNMENT -#define GB_DEFAULT_ALIGNMENT 8 +#ifndef GB_DEFAULT_MEMORY_ALIGNMENT +#define GB_DEFAULT_MEMORY_ALIGNMENT 4 #endif -gb_inline void *gb_alloc_align(gb_Allocator a, usize size, usize alignment) { return a.procedure(a.data, GB_ALLOCATION_TYPE_ALLOC, size, alignment, NULL, 0, 0); } -gb_inline void *gb_alloc(gb_Allocator a, usize size) { return gb_alloc_align(a, size, GB_DEFAULT_ALIGNMENT); } -gb_inline void gb_free(gb_Allocator a, void *ptr) { a.procedure(a.data, GB_ALLOCATION_TYPE_FREE, 0, 0, ptr, 0, 0); } -gb_inline void gb_free_all(gb_Allocator a) { a.procedure(a.data, GB_ALLOCATION_TYPE_FREE_ALL, 0, 0, NULL, 0, 0); } -gb_inline void *gb_resize(gb_Allocator a, void *ptr, usize new_size) { return a.procedure(a.data, GB_ALLOCATION_TYPE_RESIZE, new_size, 0, ptr, 0, 0); } +GB_DEF void *gb_alloc_align(gbAllocator a, usize size, usize alignment); +GB_DEF void *gb_alloc(gbAllocator a, usize size); +GB_DEF void gb_free(gbAllocator a, void *ptr); +GB_DEF void gb_free_all(gbAllocator a); +GB_DEF void *gb_resize(gbAllocator a, void *ptr, usize old_size, usize new_size); +GB_DEF void *gb_resize_align(gbAllocator a, void *ptr, usize old_size, usize new_size, usize alignment); -gb_inline void *gb_alloc_copy(gb_Allocator a, void* src, usize size) { return memcpy(gb_alloc(a, size), src, size); } -gb_inline void *gb_alloc_align_copy(gb_Allocator a, void* src, usize size, usize alignment) { return memcpy(gb_alloc_align(a, size, alignment), src, size); } +GB_DEF void *gb_alloc_copy(gbAllocator a, void const *src, usize size); +GB_DEF void *gb_alloc_align_copy(gbAllocator a, void const *src, usize size, usize alignment); -#define gb_alloc_struct(allocator, Type) (Type *)gb_alloc_align(allocator, sizeof(Type)) -#define gb_alloc_array(allocator, Type, count) (Type *)gb_alloc(allocator, sizeof(Type) * (count)) +GB_DEF char *gb_alloc_cstring(gbAllocator a, char const *str, usize len); + + +// NOTE(bill): These are very useful and the type case has saved me from numerous bugs +#ifndef gb_alloc_struct +#define gb_alloc_struct(allocator, Type) (Type *)gb_alloc_align(allocator, gb_size_of(Type)) +#define gb_alloc_array(allocator, Type, count) (Type *)gb_alloc(allocator, gb_size_of(Type) * (count)) +#endif -typedef struct gb_Arena -{ - gb_Allocator backing; + +#if !defined(GB_NO_STDLIB) + +GB_DEF gbAllocator gb_malloc_allocator(void); +GB_DEF GB_ALLOCATOR_PROC(gb_malloc_allocator_proc); + +#endif + + + + + +typedef struct gbArena { + gbAllocator backing; void *physical_start; usize total_size; - usize total_allocated_count; - usize prev_allocated_count; + usize total_allocated; u32 temp_count; -} gb_Arena; + b32 clear_allocations_to_zero; +} gbArena; -void gb_init_arena_from_memory(gb_Arena *arena, void *start, usize size); -void gb_init_arena_from_allocator(gb_Arena *arena, gb_Allocator backing, usize size); -void gb_free_arena(gb_Arena *arena); +GB_DEF void gb_arena_init_from_memory(gbArena *arena, void *start, usize size); +GB_DEF void gb_arena_init_from_allocator(gbArena *arena, gbAllocator backing, usize size); +GB_DEF void gb_arena_init_subarena(gbArena *arena, gbArena *parent_arena, usize size); +GB_DEF void gb_arena_free(gbArena *arena); -gb_Allocator gb_make_arena_allocator(gb_Arena *arena); -GB_ALLOCATOR_PROCEDURE(gb_arena_allocator_procedure); +GB_DEF usize gb_arena_alignment_of(gbArena *arena, usize alignment); +GB_DEF usize gb_arena_size_remaining(gbArena *arena, usize alignment); +GB_DEF void gb_arena_check(gbArena *arena); + + +GB_DEF gbAllocator gb_arena_allocator(gbArena *arena); +GB_DEF GB_ALLOCATOR_PROC(gb_arena_allocator_proc); -typedef struct gb_Temp_Arena_Memory -{ - gb_Arena *arena; +typedef struct gbTemp_Arena_Memory { + gbArena *arena; usize original_count; -} gb_Temp_Arena_Memory; +} gbTemp_Arena_Memory; -gb_Temp_Arena_Memory gb_begin_temp_arena_memory(gb_Arena *arena); -void gb_end_temp_arena_memory(gb_Temp_Arena_Memory tmp_mem); +GB_DEF gbTemp_Arena_Memory gb_begin_temp_arena_memory(gbArena *arena); +GB_DEF void gb_end_temp_arena_memory(gbTemp_Arena_Memory tmp_mem); -typedef struct gb_Pool -{ - gb_Allocator backing; + + + + + + +typedef struct gbPool { + gbAllocator backing; void *physical_start; void *free_list; @@ -355,70 +603,592 @@ typedef struct gb_Pool usize block_size; usize block_align; usize total_size; -} gb_Pool; +} gbPool; -void gb_init_pool(gb_Pool *pool, gb_Allocator backing, usize num_blocks, usize block_size); -void gb_init_pool_align(gb_Pool *pool, gb_Allocator backing, usize num_blocks, usize block_size, usize block_align); -void gb_free_pool(gb_Pool *pool); +GB_DEF void gb_pool_init(gbPool *pool, gbAllocator backing, usize num_blocks, usize block_size); +GB_DEF void gb_pool_init_align(gbPool *pool, gbAllocator backing, usize num_blocks, usize block_size, usize block_align); +GB_DEF void gb_pool_free(gbPool *pool); -gb_Allocator gb_make_pool_allocator(gb_Pool *pool); -GB_ALLOCATOR_PROCEDURE(gb_pool_allocator_procedure); +GB_DEF gbAllocator gb_pool_allocator(gbPool *pool); +GB_DEF GB_ALLOCATOR_PROC(gb_pool_allocator_proc); + + +//////////////////////////////////////// +// // +// Char Functions // +// // +//////////////////////////////////////// + +GB_DEF char gb_char_to_lower(char c); +GB_DEF char gb_char_to_upper(char c); +GB_DEF b32 gb_char_is_space(char c); +GB_DEF b32 gb_char_is_digit(char c); +GB_DEF b32 gb_char_is_hex_digit(char c); +GB_DEF b32 gb_char_is_alpha(char c); +GB_DEF b32 gb_char_is_alphanumeric(char c); + + +// + +GB_DEF void gb_to_lower(char *str); +GB_DEF void gb_to_upper(char *str); + +GB_DEF usize gb_strlen(char const *str); +GB_DEF char *gb_strncpy(char *dest, char const *source, usize len); +GB_DEF int gb_strncmp(char const *s1, char const *s2, usize len); + + +//////////////////////////////////////// +// // +// Windows UTF-8 Handling // +// // +//////////////////////////////////////// +// Windows doesn't handle 8 bit filenames well ('cause Micro$hit) + +GB_DEF char16 *gb_from_utf8(char16 *buffer, char *str, usize len); +GB_DEF char *gb_to_utf8(char *buffer, char16 *str, usize len); +//////////////////////////////////////// +// // +// gbString - C Read-Only-Compatible // +// // +//////////////////////////////////////// + + +// Pascal like strings in C +typedef char *gbString; + +#ifndef GB_STRING_SIZE +#define GB_STRING_SIZE +typedef u32 gbString_Size; +#endif + + +// This is stored at the beginning of the string +// NOTE(bill): It is (2*gb_size_of(gbString_Size) + 2*gb_size_of(void*)) (default: 16B (32bit), 24B (64bit)) +// NOTE(bill): If you only need a small string, just use a standard c string +typedef struct gbString_Header { + gbAllocator allocator; + gbString_Size length; + gbString_Size capacity; +} gbString_Header; + +#define GB_STRING_HEADER(str) (cast(gbString_Header *)str - 1) + +GB_DEF gbString gb_string_make(gbAllocator a, char const *str); +GB_DEF gbString gb_string_make_length(gbAllocator a, void const *str, gbString_Size num_bytes); +GB_DEF void gb_string_free(gbString str); + +GB_DEF gbString gb_string_duplicate(gbAllocator a, gbString const str); + +GB_DEF gbString_Size gb_string_length(gbString const str); +GB_DEF gbString_Size gb_string_capacity(gbString const str); +GB_DEF gbString_Size gb_string_available_space(gbString const str); + +GB_DEF void gb_string_clear(gbString str); + +GB_DEF gbString gb_string_append_string(gbString str, gbString const other); +GB_DEF gbString gb_string_append_string_length(gbString str, void const *other, gbString_Size num_bytes); +GB_DEF gbString gb_string_append_cstring(gbString str, char const *other); + +GB_DEF gbString gb_string_set(gbString str, char const *cstr); + +GB_DEF gbString gb_string_make_space_for(gbString str, gbString_Size add_len); +GB_DEF gbString_Size gb_string_allocation_size(gbString const str); + +GB_DEF b32 gb_strings_are_equal(gbString const lhs, gbString const rhs); + +GB_DEF gbString gb_string_trim(gbString str, char const *cut_set); +GB_DEF gbString gb_string_trim_space(gbString str); /* Whitespace ` \t\r\n\v\f` */ + + + + +//////////////////////////////// +// // +// // +// // +// Dynamic Array (POD Types) // +// // +// // +// // +//////////////////////////////// + +// NOTE(bill): I know this is a macro hell but C is an old (and shit) language with no proper arrays +// Also why the fuck not?! It fucking works! + +// NOTE(bill): Typedef every array +// e.g. typedef gbArray(int) gb_int_array; +#ifndef gbArray + +#define gbArray(Type) struct { \ + gbAllocator allocator; \ + i64 count; \ + i64 capacity; \ + Type *e; \ +} + + +typedef gbArray(void) gbVoid_Array; // NOTE(bill): Used to generic stuff + +/* Available Procedures for gbArray(Type) + gb_array_init + gb_array_free + gb_array_set_capacity + gb_array_grow + gb_array_append + gb_array_appendv + gb_array_pop + gb_array_clear + gb_array_resize + gb_array_reserve +*/ + +#define gb_array_init(x, allocator_) do { gb_zero_struct(x); (x)->allocator = allocator_; } while (0) + +#define gb_array_free(x) do { \ + if ((x)->allocator.proc) { \ + gbAllocator a = (x)->allocator; \ + gb_free(a, (x)->e); \ + gb_array_init((x), a); \ + } \ +} while (0) + +#define gb_array_set_capacity(array, capacity) gb__array_set_capacity((array), (capacity), gb_size_of((array)->e[0])) +// NOTE(bill): Do not use directly the thing below, use the macro +GB_DEF void gb__array_set_capacity(void *array, i64 capacity, usize element_size); + +// TODO(bill): Decide on a decent growing formula for gbArray +// Is 2*c+8 good enough +#define gb_array_grow(x, min_capacity) do { \ + i64 capacity = 2*(x)->capacity + 8; \ + if (capacity < min_capacity) \ + capacity = min_capacity; \ + gb_array_set_capacity(x, capacity); \ +} while (0) + + +#define gb_array_append(x, item) do { \ + if ((x)->capacity < (x)->count+1) \ + gb_array_grow(x, 0); \ + (x)->e[(x)->count++] = item; \ +} while (0) + +#define gb_array_appendv(x, items, item_count) do { \ + GB_ASSERT(gb_size_of(items[0]) == gb_size_of((x)->e[0])); \ + if ((x)->capacity < (x)->count+item_count) \ + gb_array_grow(x, (x)->count+item_count); \ + gb_memcpy((x)->e[a->count], items, gb_size_of((x)->e[0])*item_count); \ + (x)->count += item_count; \ +} while (0) + + + +#define gb_array_pop(x) do { GB_ASSERT((x)->count > 0); (x)->count--; } while (0) +#define gb_array_clear(x) do { (x)->count = 0; } while (0) + +#define gb_array_resize(x, count) do { \ + if ((x)->capacity < count) \ + gb_array_grow(x, count); \ + (x)->count = count; \ +} while (0) + + +#define gb_array_reserve(x, capacity) do { \ + if ((x)->capacity < capacity) \ + gb_array_set_capacity(x, capacity); \ +} while (0) + + +gb_no_inline void +gb__array_set_capacity(void *array_, i64 capacity, usize element_size) +{ + // NOTE(bill): I know this is unsafe so don't call this function directly + gbVoid_Array *a = cast(gbVoid_Array *)array_; + void *new_elements = NULL; + + GB_ASSERT(element_size > 0); + + if (capacity == a->capacity) + return; + + if (capacity < a->count) { + if (a->capacity < capacity) { + i64 new_capacity = 2*a->capacity + 8; + if (new_capacity < capacity) + new_capacity = capacity; + gb__array_set_capacity(a, new_capacity, element_size); + } + a->count = capacity; + } + + if (capacity > 0) { + new_elements = gb_alloc(a->allocator, element_size*capacity); + gb_memcpy(new_elements, a->e, element_size*a->count); + } + gb_free(a->allocator, a->e); + a->e = new_elements; + a->capacity = capacity; +} + +#endif + + +//////////////////////////////// +// // +// File Handling // +// // +//////////////////////////////// + +typedef struct gbFile { + FILE *handle; // File to fread/fwrite +} gbFile; + +GB_DEF b32 gb_file_create(gbFile *file, char const *filepath); // TODO(bill): Give file permissions +GB_DEF b32 gb_file_open(gbFile *file, char const *filepath); +GB_DEF b32 gb_file_close(gbFile *file); +GB_DEF b32 gb_file_read_at(gbFile *file, void *buffer, usize size, i64 offset); +GB_DEF b32 gb_file_write_at(gbFile *file, void const *buffer, usize size, i64 offset); +GB_DEF i64 gb_file_size(gbFile *file); + + +typedef struct gbFile_Contents { + void *data; + usize size; +} gbFile_Contents; + +GB_DEF gbFile_Contents gb_read_entire_file_contents(gbAllocator a, char const *filepath, b32 zero_terminate); + + +#if defined(__cplusplus) +} +#endif + +#endif /* GB_INCLUDE_GB_H */ + +//////////////////////////////// +// // +// // +// // +// // +// // +// // +// // +// // +// // +// // +// // +// Implementation // +// // +// // +// // +// // +// // +// // +// // +// // +// // +// // +// // +//////////////////////////////// + #if defined(GB_IMPLEMENTATION) -gb_inline void -gb_init_arena_from_memory(gb_Arena *arena, void *start, usize size) +#if defined(__cplusplus) +extern "C" { +#endif + + +int +gb_vsnprintf(char *str, usize n, char const *fmt, va_list v) { - arena->backing.procedure = NULL; + int res; + #if defined(_WIN32) + res = _vsnprintf(str, n, fmt, v); + #else + res = vsnprintf(str, n, fmt, v) + #endif + if (n) str[n-1] = 0; + // NOTE(bill): Unix returns length output would require, Windows returns negative when truncated. + return (res >= cast(int)n || res < 0) ? -1 : res; +} + + +int +gb_snprintf(char *str, usize n, char const *fmt, ...) +{ + int res; + va_list v; + va_start(v,fmt); + res = gb_vsnprintf(str, n, fmt, v); + va_end(v); + return res; +} + + +int +gb_vsprintf(char const *fmt, va_list v) +{ + gb_local_persist char buffer[1024]; + int res; + res = gb_vsnprintf(buffer, gb_size_of(buffer), fmt, v); + return res; +} + +int +gb_sprintf(char const *fmt, ...) +{ + gb_local_persist char buffer[1024]; + int res; + va_list v; + va_start(v, fmt); + res = gb_vsnprintf(buffer, gb_size_of(buffer), fmt, v); + va_end(v); + return res; +} + + + + + + + + + + + + + +void +gb_assert_handler(char const *condition, + char const *file, long long line, + char const *msg, ...) +{ + fprintf(stderr, "%s:%lld: Assert Failure: ", file, line); + if (condition) + fprintf(stderr, "`%s` ", condition); + + if (msg) { + va_list args; + va_start(args, msg); + vfprintf(stderr, msg, args); + va_end(args); + } + + fprintf(stderr, "\n"); +} + + + +gb_inline void * +gb_align_forward(void *ptr, usize align) +{ + uintptr p; + usize modulo; + + GB_ASSERT(gb_is_power_of_two(align)); + + p = cast(uintptr)ptr; + modulo = p % align; + if (modulo) p += (align - modulo); + return cast(void *)p; +} + +gb_inline void +gb_zero_size(void *ptr, usize size) +{ + memset(ptr, 0, size); +} + + +gb_inline void *gb_memcpy(void *dest, void const *source, usize size) { return memcpy(dest, source, size); } +gb_inline void *gb_memmove(void *dest, void const *source, usize size) { return memmove(dest, source, size); } + + + + + +gb_inline void *gb_alloc_align(gbAllocator a, usize size, usize alignment) { return a.proc(a.data, GB_ALLOCATION_TYPE_ALLOC, size, alignment, NULL, 0, 0); } +gb_inline void *gb_alloc(gbAllocator a, usize size) { return gb_alloc_align(a, size, GB_DEFAULT_MEMORY_ALIGNMENT); } +gb_inline void gb_free(gbAllocator a, void *ptr) { a.proc(a.data, GB_ALLOCATION_TYPE_FREE, 0, 0, ptr, 0, 0); } +gb_inline void gb_free_all(gbAllocator a) { a.proc(a.data, GB_ALLOCATION_TYPE_FREE_ALL, 0, 0, NULL, 0, 0); } +gb_inline void *gb_resize(gbAllocator a, void *ptr, usize old_size, usize new_size) { return gb_resize_align(a, ptr, old_size, new_size, GB_DEFAULT_MEMORY_ALIGNMENT); } +gb_inline void *gb_resize_align(gbAllocator a, void *ptr, usize old_size, usize new_size, usize alignment) { return a.proc(a.data, GB_ALLOCATION_TYPE_RESIZE, new_size, alignment, ptr, old_size, 0); }; + +gb_inline void *gb_alloc_copy(gbAllocator a, void const *src, usize size) { return gb_memcpy(gb_alloc(a, size), src, size); } +gb_inline void *gb_alloc_align_copy(gbAllocator a, void const *src, usize size, usize alignment) { return gb_memcpy(gb_alloc_align(a, size, alignment), src, size); } + +gb_inline char * +gb_alloc_cstring(gbAllocator a, char const *str, usize len) +{ + char *result; + if (len == 0) len = strlen(str); + result = cast(char *)gb_alloc_copy(a, str, len+1); + result[len] = '\0'; + return result; +} + + + + + + + + + + +#if !defined(GB_NO_STDLIB) + +gb_inline gbAllocator +gb_malloc_allocator(void) +{ + gbAllocator allocator; + allocator.proc = gb_malloc_allocator_proc; + allocator.data = NULL; // N/A + return allocator; +} + +GB_ALLOCATOR_PROC(gb_malloc_allocator_proc) +{ + gb_unused(options); + + switch (type) { + case GB_ALLOCATION_TYPE_ALLOC: { + #if defined(_MSC_VER) + return _aligned_malloc(size, alignment); + #else + void *ptr = NULL; + void *original_block; // Original block + void **aligned_block; // Aligned block + usize offset = (alignment-1) + sizeof(void *); + original_block = cast(void *)malloc(size + offset); + if (original_block) { + uintptr t = (cast(uintptr)original_block + offset) & ~(alignment-1); + aligned_block = cast(void **)t - 1; + aligned_block[-1] = original_block; + ptr = cast(void *)aligned_block; + } + return ptr; + #endif + } break; + + case GB_ALLOCATION_TYPE_FREE: { + #if defined(_MSC_VER) + _aligned_free(old_memory); + #else + free((cast(void **)old_memory)[-1]); + #endif + + } break; + + case GB_ALLOCATION_TYPE_FREE_ALL: + // N/A + break; + + case GB_ALLOCATION_TYPE_RESIZE: { + #if defined(_MSC_VER) + return _aligned_realloc(old_memory, size, alignment); + #else + gbAllocator a = gb_malloc_allocator(); + void *new_memory = gb_alloc_align(a, size, alignment); + gb_memmove(new_memory, old_memory, gb_min(size, old_size)); + gb_free(a, old_memory); + return new_memory; + #endif + } break; + } + + return NULL; // NOTE(bill): Default return value +} + +#endif + + + + +gb_inline void +gb_arena_init_from_memory(gbArena *arena, void *start, usize size) +{ + arena->backing.proc = NULL; arena->backing.data = NULL; arena->physical_start = start; arena->total_size = size; - arena->total_allocated_count = 0; + arena->total_allocated = 0; arena->temp_count = 0; } gb_inline void -gb_init_arena_from_allocator(gb_Arena *arena, gb_Allocator backing, usize size) +gb_arena_init_from_allocator(gbArena *arena, gbAllocator backing, usize size) { arena->backing = backing; - arena->physical_start = gb_alloc(backing, size); + arena->physical_start = gb_alloc(backing, size); // NOTE(bill): Uses default alignment arena->total_size = size; - arena->total_allocated_count = 0; + arena->total_allocated = 0; arena->temp_count = 0; } +gb_inline void gb_arena_init_subarena(gbArena *arena, gbArena *parent_arena, usize size) { gb_arena_init_from_allocator(arena, gb_arena_allocator(parent_arena), size); } + + gb_inline void -gb_free_arena(gb_Arena *arena) +gb_arena_free(gbArena *arena) { - if (arena->backing.procedure) { + if (arena->backing.proc) { gb_free(arena->backing, arena->physical_start); arena->physical_start = NULL; } } - - -gb_inline gb_Allocator -gb_make_arena_allocator(gb_Arena *arena) +gb_inline usize +gb_arena_alignment_of(gbArena *arena, usize alignment) { - gb_Allocator allocator; - allocator.procedure = gb_arena_allocator_procedure; + usize alignment_offset, result_pointer, mask; + GB_ASSERT(gb_is_power_of_two(alignment)); + + alignment_offset = 0; + result_pointer = cast(usize)arena->physical_start + arena->total_allocated; + mask = alignment - 1; + if (result_pointer & mask) + alignment_offset = alignment - (result_pointer & mask); + + return alignment_offset; +} + +gb_inline usize +gb_arena_size_remaining(gbArena *arena, usize alignment) +{ + usize result = arena->total_size - (arena->total_allocated + gb_arena_alignment_of(arena, alignment)); + return result; +} + +gb_inline void gb_arena_check(gbArena *arena) { GB_ASSERT(arena->temp_count == 0); } + + + + + + +gb_inline gbAllocator +gb_arena_allocator(gbArena *arena) +{ + gbAllocator allocator; + allocator.proc = gb_arena_allocator_proc; allocator.data = arena; return allocator; } -GB_ALLOCATOR_PROCEDURE(gb_arena_allocator_procedure) +GB_ALLOCATOR_PROC(gb_arena_allocator_proc) { - gb_Arena *arena = cast(gb_Arena *)allocator_data; + gbArena *arena = cast(gbArena *)allocator_data; - GB_UNUSED(options); - GB_UNUSED(old_size); + gb_unused(options); + gb_unused(old_size); switch (type) { case GB_ALLOCATION_TYPE_ALLOC: { @@ -426,29 +1196,31 @@ GB_ALLOCATOR_PROCEDURE(gb_arena_allocator_procedure) usize actual_size = size + alignment; // NOTE(bill): Out of memory - if (arena->total_allocated_count + actual_size > cast(usize)arena->total_size) + if (arena->total_allocated + actual_size > cast(usize)arena->total_size) return NULL; - ptr = gb_align_forward(cast(u8 *)arena->physical_start + arena->total_allocated_count, alignment); - arena->prev_allocated_count = arena->total_allocated_count; - arena->total_allocated_count += actual_size; + ptr = gb_align_forward(cast(u8 *)arena->physical_start + arena->total_allocated, alignment); + arena->total_allocated += actual_size; + if (arena->clear_allocations_to_zero) + gb_zero_size(ptr, size); return ptr; } break; - case GB_ALLOCATION_TYPE_FREE: { + case GB_ALLOCATION_TYPE_FREE: // NOTE(bill): Free all at once // NOTE(bill): Use Temp_Arena_Memory if you want to free a block - } break; + break; case GB_ALLOCATION_TYPE_FREE_ALL: - arena->total_allocated_count = 0; + arena->total_allocated = 0; break; case GB_ALLOCATION_TYPE_RESIZE: { - // TODO(bill): Check if ptr is at the top - void *ptr = gb_alloc_align(gb_make_arena_allocator(arena), size, alignment); - memcpy(ptr, old_memory, size); - return ptr; + gbAllocator a = gb_arena_allocator(arena); + void *new_memory = gb_alloc_align(a, size, alignment); + gb_memmove(new_memory, old_memory, gb_min(size, old_size)); + gb_free(a, old_memory); + return new_memory; } break; } @@ -456,39 +1228,42 @@ GB_ALLOCATOR_PROCEDURE(gb_arena_allocator_procedure) } -gb_inline gb_Temp_Arena_Memory -gb_begin_temp_arena_memory(gb_Arena *arena) +gb_inline gbTemp_Arena_Memory +gb_begin_temp_arena_memory(gbArena *arena) { - gb_Temp_Arena_Memory tmp; + gbTemp_Arena_Memory tmp; tmp.arena = arena; - tmp.original_count = arena->total_allocated_count; + tmp.original_count = arena->total_allocated; arena->temp_count++; return tmp; } gb_inline void -gb_end_temp_arena_memory(gb_Temp_Arena_Memory tmp) +gb_end_temp_arena_memory(gbTemp_Arena_Memory tmp) { - GB_ASSERT(tmp.arena->total_allocated_count >= tmp.original_count); + GB_ASSERT(tmp.arena->total_allocated >= tmp.original_count); GB_ASSERT(tmp.arena->temp_count > 0); - tmp.arena->total_allocated_count = tmp.original_count; + tmp.arena->total_allocated = tmp.original_count; tmp.arena->temp_count--; } -void -gb_init_pool(gb_Pool *pool, gb_Allocator backing, usize num_blocks, usize block_size) +gb_inline void +gb_pool_init(gbPool *pool, gbAllocator backing, usize num_blocks, usize block_size) { - gb_init_pool_align(pool, backing, num_blocks, block_size, GB_DEFAULT_ALIGNMENT); + gb_pool_init_align(pool, backing, num_blocks, block_size, GB_DEFAULT_MEMORY_ALIGNMENT); } void -gb_init_pool_align(gb_Pool *pool, gb_Allocator backing, usize num_blocks, usize block_size, usize block_align) +gb_pool_init_align(gbPool *pool, gbAllocator backing, usize num_blocks, usize block_size, usize block_align) { usize actual_block_size, pool_size, block_index; u8 *data, *curr; + uintptr *end; + + gb_zero_struct(pool); pool->backing = backing; pool->block_size = block_size; @@ -507,39 +1282,37 @@ gb_init_pool_align(gb_Pool *pool, gb_Allocator backing, usize num_blocks, usize curr += actual_block_size; } - { - uintptr *end = cast(uintptr*)curr; - *end = cast(uintptr)NULL; - } + end = cast(uintptr*)curr; + *end = cast(uintptr)NULL; pool->physical_start = data; pool->free_list = data; } -void -gb_free_pool(gb_Pool *pool) +gb_inline void +gb_pool_free(gbPool *pool) { - if (pool->backing.procedure) { + if (pool->backing.proc) { gb_free(pool->backing, pool->physical_start); } } -gb_Allocator -gb_make_pool_allocator(gb_Pool *pool) +gb_inline gbAllocator +gb_pool_allocator(gbPool *pool) { - gb_Allocator allocator; - allocator.procedure = gb_pool_allocator_procedure; + gbAllocator allocator; + allocator.proc = gb_pool_allocator_proc; allocator.data = pool; return allocator; } -GB_ALLOCATOR_PROCEDURE(gb_pool_allocator_procedure) +GB_ALLOCATOR_PROC(gb_pool_allocator_proc) { - gb_Pool *pool = cast(gb_Pool *)allocator_data; + gbPool *pool = cast(gbPool *)allocator_data; - GB_UNUSED(options); - GB_UNUSED(old_size); + gb_unused(options); + gb_unused(old_size); switch (type) { case GB_ALLOCATION_TYPE_ALLOC: { @@ -566,13 +1339,13 @@ GB_ALLOCATOR_PROCEDURE(gb_pool_allocator_procedure) pool->total_size -= pool->block_size; } break; - case GB_ALLOCATION_TYPE_FREE_ALL: { + case GB_ALLOCATION_TYPE_FREE_ALL: // TODO(bill): - } break; + break; - case GB_ALLOCATION_TYPE_RESIZE: { + case GB_ALLOCATION_TYPE_RESIZE: // NOTE(bill): Cannot resize - } break; + break; } return NULL; @@ -584,170 +1357,180 @@ GB_ALLOCATOR_PROCEDURE(gb_pool_allocator_procedure) - - - - -#endif // GB_IMPLEMENTATION - - -//////////////////////////////// -// // -// gb_String - C Compatible // -// // -//////////////////////////////// - - -// Pascal like strings in C -typedef char *gb_String; - -#ifndef GB_STRING_SIZE -#define GB_STRING_SIZE -typedef u32 gb_String_Size; -#endif - - -// This is stored at the beginning of the string -// NOTE(bill): It is (2*sizeof(gb_String_Size) + 2*sizeof(void*)) (default: 16B (32bit), 24B (64bit)) -// NOTE(bill): If you only need a small string, just use a standard c string -typedef struct gb_String_Header +gb_inline char +gb_char_to_lower(char c) { - gb_Allocator allocator; - gb_String_Size length; - gb_String_Size capacity; -} gb_String_Header; + if (c >= 'A' && c <= 'Z') + return 'a' + (c - 'A'); + return c; +} -#define GB_STRING_HEADER(str) (cast(gb_String_Header *)str - 1) - -gb_String gb_string_make(gb_Allocator a, char const *str); -gb_String gb_string_make_length(gb_Allocator a, void const *str, gb_String_Size num_bytes); -void gb_string_free(gb_String str); - -gb_String gb_string_duplicate(gb_Allocator a, gb_String const str); - -gb_String_Size gb_string_length(gb_String const str); -gb_String_Size gb_string_capacity(gb_String const str); -gb_String_Size gb_string_available_space(gb_String const str); - -void gb_string_clear(gb_String str); - -gb_String gb_string_append_string(gb_String str, gb_String const other); -gb_String gb_string_append_string_length(gb_String str, void const *other, gb_String_Size num_bytes); -gb_String gb_string_append_cstring(gb_String str, char const *other); - -gb_String gb_string_set(gb_String str, char const *cstr); - -gb_String gb_string_make_space_for(gb_String str, gb_String_Size add_len); -gb_String_Size gb_string_allocation_size(gb_String const str); - -b32 gb_strings_are_equal(gb_String const lhs, gb_String const rhs); - -gb_String gb_string_trim(gb_String str, char const *cut_set); -gb_String gb_string_trim_space(gb_String str); /* Whitespace ` \t\r\n\v\f` */ - - -#if defined(GB_IMPLEMENTATION) - -gb_inline void gb__string_set_length(gb_String str, gb_String_Size len) { GB_STRING_HEADER(str)->length = len; } -gb_inline void gb__string_set_capacity(gb_String str, gb_String_Size cap) { GB_STRING_HEADER(str)->capacity = cap; } - - -gb_inline gb_String -gb_string_make(gb_Allocator a, char const *str) +gb_inline char +gb_char_to_upper(char c) { - gb_String_Size len = cast(gb_String_Size)(str ? strlen(str) : 0); + if (c >= 'a' && c <= 'z') + return 'A' + (c - 'a'); + return c; +} + +gb_inline b32 +gb_char_is_space(char c) +{ + if (c == ' ' || + c == '\t' || + c == '\n' || + c == '\r' || + c == '\f' || + c == '\v') + return true; + return false; +} + +gb_inline b32 +gb_char_is_digit(char c) +{ + if (c >= '0' && c <= '9') + return true; + return false; +} + +gb_inline b32 +gb_char_is_hex_digit(char c) +{ + if (gb_char_is_digit(c) || + (c >= 'a' && c <= 'f') || + (c >= 'A' && c <= 'F')) + return true; + return false; +} + +gb_inline b32 +gb_char_is_alpha(char c) +{ + if ((c >= 'A' && c <= 'Z') || + (c >= 'a' && c <= 'z')) + return true; + return false; +} + +gb_inline b32 +gb_char_is_alphanumeric(char c) +{ + return gb_char_is_alpha(c) || gb_char_is_digit(c); +} + + + + + + + + + + + + + + +gb_inline void gb__string_set_length(gbString str, gbString_Size len) { GB_STRING_HEADER(str)->length = len; } +gb_inline void gb__string_set_capacity(gbString str, gbString_Size cap) { GB_STRING_HEADER(str)->capacity = cap; } + + +gb_inline gbString +gb_string_make(gbAllocator a, char const *str) +{ + gbString_Size len = cast(gbString_Size)(str ? strlen(str) : 0); return gb_string_make_length(a, str, len); } -gb_String -gb_string_make_length(gb_Allocator a, void const *init_str, gb_String_Size num_bytes) +gbString +gb_string_make_length(gbAllocator a, void const *init_str, gbString_Size num_bytes) { - gb_String_Size header_size = sizeof(gb_String_Header); + gbString_Size header_size = gb_size_of(gbString_Header); void *ptr = gb_alloc(a, header_size + num_bytes + 1); - if (ptr == NULL) { - return NULL; - } else { - gb_String str = cast(char *)ptr + header_size; - gb_String_Header *header = GB_STRING_HEADER(str); - // Zero all data first - if (!init_str) gb_zero_size(ptr, header_size + num_bytes + 1); - header->allocator = a; - header->length = num_bytes; - header->capacity = num_bytes; + gbString str; + gbString_Header *header; - if (num_bytes && init_str) - memcpy(str, init_str, num_bytes); - str[num_bytes] = '\0'; // Just in case + if (!init_str) gb_zero_size(ptr, header_size + num_bytes + 1); + if (ptr == NULL) return NULL; - return str; - } + str = cast(char *)ptr + header_size; + header = GB_STRING_HEADER(str); + header->allocator = a; + header->length = num_bytes; + header->capacity = num_bytes; + if (num_bytes && init_str) + gb_memcpy(str, init_str, num_bytes); + str[num_bytes] = '\0'; + + return str; } gb_inline void -gb_string_free(gb_String str) +gb_string_free(gbString str) { if (str) { - gb_String_Header *header; + gbString_Header *header; header = GB_STRING_HEADER(str); gb_free(header->allocator, header); } } -gb_inline gb_String gb_string_duplicate(gb_Allocator a, gb_String const str) { return gb_string_make_length(a, str, gb_string_length(str)); } +gb_inline gbString gb_string_duplicate(gbAllocator a, gbString const str) { return gb_string_make_length(a, str, gb_string_length(str)); } -gb_inline gb_String_Size gb_string_length(gb_String const str) { return GB_STRING_HEADER(str)->length; } -gb_inline gb_String_Size gb_string_capacity(gb_String const str) { return GB_STRING_HEADER(str)->capacity; } +gb_inline gbString_Size gb_string_length(gbString const str) { return GB_STRING_HEADER(str)->length; } +gb_inline gbString_Size gb_string_capacity(gbString const str) { return GB_STRING_HEADER(str)->capacity; } -gb_inline gb_String_Size -gb_string_available_space(gb_String const str) +gb_inline gbString_Size +gb_string_available_space(gbString const str) { - gb_String_Header *h = GB_STRING_HEADER(str); + gbString_Header *h = GB_STRING_HEADER(str); if (h->capacity > h->length) return h->capacity - h->length; return 0; } -gb_inline void gb_string_clear(gb_String str) { gb__string_set_length(str, 0); str[0] = '\0'; } +gb_inline void gb_string_clear(gbString str) { gb__string_set_length(str, 0); str[0] = '\0'; } -gb_inline gb_String gb_string_append_string(gb_String str, gb_String const other) { return gb_string_append_string_length(str, other, gb_string_length(other)); } +gb_inline gbString gb_string_append_string(gbString str, gbString const other) { return gb_string_append_string_length(str, other, gb_string_length(other)); } -gb_String -gb_string_append_string_length(gb_String str, void const *other, gb_String_Size other_len) +gbString +gb_string_append_string_length(gbString str, void const *other, gbString_Size other_len) { - gb_String_Size curr_len = gb_string_length(str); + gbString_Size curr_len = gb_string_length(str); str = gb_string_make_space_for(str, other_len); if (str == NULL) return NULL; - memcpy(str + curr_len, other, other_len); + gb_memcpy(str + curr_len, other, other_len); str[curr_len + other_len] = '\0'; gb__string_set_length(str, curr_len + other_len); return str; } -gb_inline gb_String -gb_string_append_cstring(gb_String str, char const *other) +gb_inline gbString +gb_string_append_cstring(gbString str, char const *other) { - return gb_string_append_string_length(str, other, cast(gb_String_Size)strlen(other)); + return gb_string_append_string_length(str, other, cast(gbString_Size)strlen(other)); } -gb_String -gb_string_set(gb_String str, char const *cstr) +gbString +gb_string_set(gbString str, char const *cstr) { - gb_String_Size len = cast(gb_String_Size)strlen(cstr); + gbString_Size len = cast(gbString_Size)strlen(cstr); if (gb_string_capacity(str) < len) { str = gb_string_make_space_for(str, len - gb_string_length(str)); if (str == NULL) return NULL; } - memcpy(str, cstr, len); + gb_memcpy(str, cstr, len); str[len] = '\0'; gb__string_set_length(str, len); @@ -755,8 +1538,8 @@ gb_string_set(gb_String str, char const *cstr) } -local_persist void * -gb__string_realloc(gb_Allocator a, void *ptr, gb_String_Size old_size, gb_String_Size new_size) +gb_internal void * +gb__string_realloc(gbAllocator a, void *ptr, gbString_Size old_size, gbString_Size new_size) { if (!ptr) return gb_alloc(a, new_size); @@ -766,12 +1549,11 @@ gb__string_realloc(gb_Allocator a, void *ptr, gb_String_Size old_size, gb_String if (old_size == new_size) { return ptr; } else { - // TODO(bill): Use gb_resize here?? void *new_ptr = gb_alloc(a, new_size); if (!new_ptr) return NULL; - memcpy(new_ptr, ptr, old_size); + gb_memcpy(new_ptr, ptr, old_size); gb_free(a, ptr); return new_ptr; } @@ -779,19 +1561,19 @@ gb__string_realloc(gb_Allocator a, void *ptr, gb_String_Size old_size, gb_String -gb_String -gb_string_make_space_for(gb_String str, gb_String_Size add_len) +gbString +gb_string_make_space_for(gbString str, gbString_Size add_len) { - gb_String_Size available = gb_string_available_space(str); + gbString_Size available = gb_string_available_space(str); // Return if there is enough space left if (available >= add_len) { return str; } else { - gb_String_Size new_len = gb_string_length(str) + add_len; + gbString_Size new_len = gb_string_length(str) + add_len; void *ptr = GB_STRING_HEADER(str); - gb_String_Size old_size = sizeof(struct gb_String_Header) + gb_string_length(str) + 1; - gb_String_Size new_size = sizeof(struct gb_String_Header) + new_len + 1; + gbString_Size old_size = gb_size_of(gbString_Header) + gb_string_length(str) + 1; + gbString_Size new_size = gb_size_of(gbString_Header) + new_len + 1; void *new_ptr = gb__string_realloc(GB_STRING_HEADER(str)->allocator, ptr, old_size, new_size); if (new_ptr == NULL) return NULL; @@ -803,18 +1585,18 @@ gb_string_make_space_for(gb_String str, gb_String_Size add_len) } } -gb_inline gb_String_Size -gb_string_allocation_size(gb_String const str) +gb_inline gbString_Size +gb_string_allocation_size(gbString const str) { - gb_String_Size result = gb_string_capacity(str) + cast(gb_String_Size)sizeof(gb_String_Header); - return result; + gbString_Size cap = gb_string_capacity(str); + return gb_size_of(gbString_Header) + cap; } gb_inline b32 -gb_strings_are_equal(gb_String const lhs, gb_String const rhs) +gb_strings_are_equal(gbString const lhs, gbString const rhs) { - gb_String_Size lhs_len, rhs_len, i; + gbString_Size lhs_len, rhs_len, i; lhs_len = gb_string_length(lhs); rhs_len = gb_string_length(rhs); if (lhs_len != rhs_len) @@ -829,11 +1611,11 @@ gb_strings_are_equal(gb_String const lhs, gb_String const rhs) } -gb_String -gb_string_trim(gb_String str, char const *cut_set) +gbString +gb_string_trim(gbString str, char const *cut_set) { char *start, *end, *start_pos, *end_pos; - gb_String_Size len; + gbString_Size len; start_pos = start = str; end_pos = end = str + gb_string_length(str) - 1; @@ -843,10 +1625,10 @@ gb_string_trim(gb_String str, char const *cut_set) while (end_pos > start_pos && strchr(cut_set, *end_pos)) end_pos--; - len = cast(gb_String_Size)((start_pos > end_pos) ? 0 : ((end_pos - start_pos)+1)); + len = cast(gbString_Size)((start_pos > end_pos) ? 0 : ((end_pos - start_pos)+1)); if (str != start_pos) - memmove(str, start_pos, len); + gb_memmove(str, start_pos, len); str[len] = '\0'; gb__string_set_length(str, len); @@ -854,23 +1636,285 @@ gb_string_trim(gb_String str, char const *cut_set) return str; } -gb_inline gb_String gb_string_trim_space(gb_String str) { return gb_string_trim(str, " \t\r\n\v\f"); } +gb_inline gbString gb_string_trim_space(gbString str) { return gb_string_trim(str, " \t\r\n\v\f"); } -#endif + +gb_inline void +gb_to_lower(char *str) +{ + while (*str) { + *str = gb_char_to_lower(*str); + str++; + } +} + +gb_inline void +gb_to_upper(char *str) +{ + while (*str) { + *str = gb_char_to_upper(*str); + str++; + } +} + + +gb_inline usize +gb_strlen(char const *str) +{ + char const *end; + for (end = str; *end; end++) { + // + } + return (end - str); +} + +gb_inline char * +gb_strncpy(char *dest, char const *source, usize len) +{ + char *str = dest; + while (len > 0 && *source) { + *str++ = *source++; + len--; + } + while (len > 0) { + *str++ = '\0'; + len--; + } + return dest; +} + +gb_inline int +gb_strncmp(char const *s1, char const *s2, usize len) +{ + for(; len > 0; s1++, s2++, len--) { + if (*s1 != *s2) + return ((cast(uintptr)s1 < cast(uintptr)s2) ? -1 : +1); + else if (*s1 == '\0') + return 0; + } + return 0; +} + + + + +//////////////////////////////////////// +// // +// Windows UTF-8 Handling // +// // +//////////////////////////////////////// + + +char16 * +gb_from_utf8(char16 *buffer, char *s, usize len) +{ + u8 *str = cast(u8 *)s; + u32 c; + usize i = 0; + len--; + while (*str) { + if (i >= len) + return NULL; + if (!(*str & 0x80)) { + buffer[i++] = *str++; + } else if ((*str & 0xe0) == 0xc0) { + if (*str < 0xc2) + return NULL; + c = (*str++ & 0x1f) << 6; + if ((*str & 0xc0) != 0x80) + return NULL; + buffer[i++] = c + (*str++ & 0x3f); + } else if ((*str & 0xf0) == 0xe0) { + if (*str == 0xe0 && + (str[1] < 0xa0 || str[1] > 0xbf)) + return NULL; + if (*str == 0xed && str[1] > 0x9f) // str[1] < 0x80 is checked below + return NULL; + c = (*str++ & 0x0f) << 12; + if ((*str & 0xc0) != 0x80) + return NULL; + c += (*str++ & 0x3f) << 6; + if ((*str & 0xc0) != 0x80) + return NULL; + buffer[i++] = c + (*str++ & 0x3f); + } else if ((*str & 0xf8) == 0xf0) { + if (*str > 0xf4) + return NULL; + if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) + return NULL; + if (*str == 0xf4 && str[1] > 0x8f) // str[1] < 0x80 is checked below + return NULL; + c = (*str++ & 0x07) << 18; + if ((*str & 0xc0) != 0x80) + return NULL; + c += (*str++ & 0x3f) << 12; + if ((*str & 0xc0) != 0x80) + return NULL; + c += (*str++ & 0x3f) << 6; + if ((*str & 0xc0) != 0x80) + return NULL; + c += (*str++ & 0x3f); + // UTF-8 encodings of values used in surrogate pairs are invalid + if ((c & 0xfffff800) == 0xd800) + return NULL; + if (c >= 0x10000) { + c -= 0x10000; + if (i+2 > len) + return NULL; + buffer[i++] = 0xd800 | (0x3ff & (c>>10)); + buffer[i++] = 0xdc00 | (0x3ff & (c )); + } + } else { + return NULL; + } + } + buffer[i] = 0; + return buffer; +} + +char * +gb_to_utf8(char *buffer, char16 *str, usize len) +{ + usize i = 0; + len--; + while (*str) { + if (*str < 0x80) { + if (i+1 > len) + return NULL; + buffer[i++] = (char) *str++; + } else if (*str < 0x800) { + if (i+2 > len) + return NULL; + buffer[i++] = 0xc0 + (*str >> 6); + buffer[i++] = 0x80 + (*str & 0x3f); + str += 1; + } else if (*str >= 0xd800 && *str < 0xdc00) { + u32 c; + if (i+4 > len) + return NULL; + c = ((str[0] - 0xd800) << 10) + ((str[1]) - 0xdc00) + 0x10000; + buffer[i++] = 0xf0 + (c >> 18); + buffer[i++] = 0x80 + ((c >> 12) & 0x3f); + buffer[i++] = 0x80 + ((c >> 6) & 0x3f); + buffer[i++] = 0x80 + ((c ) & 0x3f); + str += 2; + } else if (*str >= 0xdc00 && *str < 0xe000) { + return NULL; + } else { + if (i+3 > len) + return NULL; + buffer[i++] = 0xe0 + (*str >> 12); + buffer[i++] = 0x80 + ((*str >> 6) & 0x3f); + buffer[i++] = 0x80 + ((*str ) & 0x3f); + str += 1; + } + } + buffer[i] = 0; + return buffer; +} //////////////////////////////// // // -// Unfinished code // +// File Handling // // // //////////////////////////////// +gb_inline b32 +gb_create_file(gbFile *file, char const *filepath) +{ + file->handle = fopen(filepath, "wb"); + return (file->handle != NULL); // TODO(bill): Handle fopen errors +} + +gb_inline b32 +gb_open_file(gbFile *file, char const *filepath) +{ + file->handle = fopen(filepath, "rb"); + return (file->handle != NULL); // TODO(bill): Handle fopen errors +} + +gb_inline b32 +gb_close_file(gbFile *file) +{ + b32 result = true; + if (file && file->handle) + result = fclose(file->handle) != 0; // TODO(bill): Handle fclose errors + return result; +} + +gb_inline b32 +gb_read_file_at(gbFile *file, void *buffer, usize size, i64 offset) +{ + i64 prev_cursor_pos = ftell(file->handle); + fseek(file->handle, offset, SEEK_SET); + fread(buffer, 1, size, file->handle); + fseek(file->handle, prev_cursor_pos, SEEK_SET); + return true; +} + +gb_inline b32 +gb_write_file_at(gbFile *file, void const *buffer, usize size, i64 offset) +{ + usize written_size; + + i64 prev_cursor_pos = ftell(file->handle); + fseek(file->handle, offset, SEEK_SET); + + written_size = fwrite(buffer, 1, size, file->handle); + fseek(file->handle, prev_cursor_pos, SEEK_SET); + if (written_size != size) { + GB_PANIC("Failed to write file data"); + return false; + } + + return true; +} + +gb_inline i64 +gb_file_size(gbFile *file) +{ + usize result_size; + + fseek(file->handle, 0, SEEK_END); + result_size = cast(usize)ftell(file->handle); + fseek(file->handle, 0, SEEK_SET); + return result_size; +} + + + + + +gbFile_Contents +gb_read_entire_file_contents(gbAllocator a, char const *filepath, b32 zero_terminate) +{ + gbFile_Contents result = {0}; + gbFile file = {0}; + if (gb_open_file(&file, filepath)) { + i64 file_size = gb_file_size(&file); + if (file_size > 0) { + result.data = gb_alloc(a, zero_terminate ? file_size+1 : file_size); + result.size = file_size; + gb_read_file_at(&file, result.data, result.size, 0); + if (zero_terminate) + (cast(u8 *)(result.data))[file_size] = '\0'; + } + gb_close_file(&file); + } + + return result; +} + + + + + #if defined(__cplusplus) } #endif - -#endif // GB_INCLUDE_GB_H +#endif /* GB_IMPLEMENTATION */ From dc5fe7638c42b59b8c07c0c0529a084bfd68b284 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Tue, 12 Apr 2016 21:52:09 +0100 Subject: [PATCH 13/15] Update gb.h --- gb.h | 918 ++++++++++++++++++++++++++++++++++------------------------- 1 file changed, 529 insertions(+), 389 deletions(-) diff --git a/gb.h b/gb.h index ed16d80..9a51b0f 100644 --- a/gb.h +++ b/gb.h @@ -1,5 +1,5 @@ -/* gb.h - v0.02 - Ginger Bill's C Helper Library - public domain - - no warranty implied; use at your own risk +/* gb.h - v0.02a - Ginger Bill's C Helper Library - public domain + - no warranty implied; use at your own risk This is a single header file with a bunch of useful stuff to replace the C/C++ standard library @@ -18,8 +18,16 @@ All other files should just #include "gb.h" without #define =========================================================================== +Conventions used: + gbTypes_Are_Like_This (None core types) + gb_functions_and_variables_like_this + Prefer // Comments + Never use _t suffix for types + Private "things" will have prefix `gbpriv` (e.g. Things the user shouldn't be touch if they don't know what they are doing) + Version History: + 0.02a - Bug fixes 0.02 - Change naming convention and gbArray(Type) 0.01 - Initial Version @@ -62,11 +70,30 @@ CREDITS extern "C" { #endif + +#ifndef GB_EXTERN + #if defined(__cplusplus) + #define GB_EXTERN extern "C" + #else + #define GB_EXTERN extern + #endif +#endif + +#ifndef GB_DLL_EXPORT +#define GB_DLL_EXPORT __declspec(dllexport) +#endif + +#ifndef GB_DLL_IMPORT +#define GB_DLL_IMPORT __declspec(dllimport) +#endif + + +// NOTE(bill): Redefine for DLL, etc. #ifndef GB_DEF #ifdef GB_STATIC #define GB_DEF static #else - #define GB_DEF extern + #define GB_DEF GB_EXTERN #endif #endif @@ -161,6 +188,11 @@ extern "C" { typedef int64_t i64; #endif +GB_STATIC_ASSERT(sizeof(u8) == sizeof(i8)); +GB_STATIC_ASSERT(sizeof(u16) == sizeof(i16)); +GB_STATIC_ASSERT(sizeof(u32) == sizeof(i32)); +GB_STATIC_ASSERT(sizeof(u64) == sizeof(i64)); + GB_STATIC_ASSERT(sizeof(u8) == 1); GB_STATIC_ASSERT(sizeof(u16) == 2); GB_STATIC_ASSERT(sizeof(u32) == 4); @@ -177,6 +209,7 @@ typedef intptr_t intptr; typedef float f32; typedef double f64; + GB_STATIC_ASSERT(sizeof(f32) == 4); GB_STATIC_ASSERT(sizeof(f64) == 8); @@ -187,7 +220,7 @@ typedef u32 char32; // NOTE(bill): I think C99 and C++ `bool` is stupid for numerous reasons but there are too many // to write in this small comment. typedef i32 b32; // NOTE(bill): Use this in structs if a boolean _is_ needed to be aligned well -typedef i8 b8; +typedef i8 b8; // TODO(bill): Do I really want a 8-bit boolean ever? // NOTE(bill): Get true and false #if !defined(__cplusplus) @@ -206,18 +239,18 @@ typedef i8 b8; #ifndef U8_MIN #define U8_MIN 0u #define U8_MAX 0xffu -#define S8_MIN (-0x7f - 1) -#define S8_MAX 0x7f +#define I8_MIN (-0x7f - 1) +#define I8_MAX 0x7f #define U16_MIN 0u #define U16_MAX 0xffffu -#define S16_MIN (-0x7fff - 1) -#define S16_MAX 0x7fff +#define I16_MIN (-0x7fff - 1) +#define I16_MAX 0x7fff #define U32_MIN 0u #define U32_MAX 0xffffffffu -#define S32_MIN (-0x7fffffff - 1) -#define S32_MAX 0x7fffffff +#define I32_MIN (-0x7fffffff - 1) +#define I32_MAX 0x7fffffff #define U64_MIN 0ull #define U64_MAX 0xffffffffffffffffull @@ -240,6 +273,13 @@ typedef i8 b8; #error Unknown architecture size #endif +#define F32_MIN 1.17549435e-38f +#define F32_MAX 3.40282347e+38f + +#define F64_MIN 2.2250738585072014e-308 +#define F64_MAX 1.7976931348623157e+308 + + #endif @@ -258,8 +298,9 @@ typedef i8 b8; -#if !defined(__cplusplus) && defined(_MSC_VER) && _MSC_VER <= 1800 - #define inline __inline +#if !defined(__cplusplus) && defined(_MSC_VER) && _MSC_VER <= 1800 + #define inline __inline + #define restrict __restrict #endif @@ -279,16 +320,6 @@ typedef i8 b8; #endif #endif -#ifndef GB_EXTERN - #if defined(__cplusplus) - #define GB_EXTERN extern "C" - #else - #define GB_EXTERN extern - #endif -#endif - - - // NOTE(bill): Easy to grep // NOTE(bill): Not needed in macros #ifndef cast @@ -296,40 +327,47 @@ typedef i8 b8; #endif +// NOTE(bill): Because a signed sizeof is more useful #ifndef gb_size_of -#define gb_size_of(x) cast(i64)(sizeof(x)) +#define gb_size_of(x) (isize)(sizeof(x)) #endif #ifndef gb_count_of -#define gb_count_of(x) ((gb_size_of(x)/gb_size_of(0[x])) / ((usize)(!(gb_size_of(x) % gb_size_of(0[x]))))) +#define gb_count_of(x) ((gb_size_of(x)/gb_size_of(0[x])) / ((isize)(!(gb_size_of(x) % gb_size_of(0[x]))))) #endif #ifndef gb_offset_of -#define gb_offset_of(Type, element) ((usize)&(((Type *)0)->element)) +#define gb_offset_of(Type, element) ((isize)&(((Type *)0)->element)) #endif #if defined(__cplusplus) extern "C++" { - #ifndef gb_align_of - template struct gb_Alignment_Trick { char c; T member; }; - #define gb_align_of(Type) offset_of(gb_Alignment_Trick, member) +#ifndef gb_align_of + #if __cplusplus >= 201103L + #define gb_align_of(Type) (isize)alignof(Type) + #else + // NOTE(bill): Fucking Templates! + template struct gbAlignment_Trick { char c; T member; }; + #define gb_align_of(Type) gb_offset_of(gbAlignment_Trick, member) #endif +#endif } #else #ifndef gb_align_of - #define gb_align_of(Type) offs(struct { char c; Type member; }, member) + #define gb_align_of(Type) gb_offset_of(struct { char c; Type member; }, member) #endif #endif +// NOTE(bill): I do which I had a type_of that was portable #ifndef gb_swap #define gb_swap(Type, a, b) do { Type tmp = (a); (a) = (b); (b) = tmp; } while (0) #endif // NOTE(bill): Because static means 3/4 different things in C/C++. Great design (!) #ifndef gb_global -#define gb_global static -#define gb_internal static -#define gb_local_persist static +#define gb_global static // Global variables +#define gb_internal static // Internal linkage +#define gb_local_persist static // Local Persisting variables #endif @@ -340,12 +378,14 @@ extern "C++" { + + //////////////////////////////////////////////////////////////// // // Defer statement -// - Akin to D's SCOPE_EXIT or similar to Go's defer but scope-based +// Akin to D's SCOPE_EXIT or +// similar to Go's defer but scope-based // -//////////////////////////////////////////////////////////////// #if defined(__cplusplus) extern "C++" { // NOTE(bill): Stupid fucking templates @@ -354,16 +394,17 @@ extern "C++" { template struct gbRemove_Reference { typedef T Type; }; // NOTE(bill): "Move" semantics - invented because the C++ committee are idiots (as a collective not as indiviuals (well a least some aren't)) - template gb_inline T &&gb_forward_ownership(typename gbRemove_Reference::Type &t) { return static_cast(t); } - template gb_inline T &&gb_forward_ownership(typename gbRemove_Reference::Type &&t) { return static_cast(t); } + template inline T &&gb_forward_ownership(typename gbRemove_Reference::Type &t) { return static_cast(t); } + template inline T &&gb_forward_ownership(typename gbRemove_Reference::Type &&t) { return static_cast(t); } + template inline T &&gb_move_ownership(T &&t) { return static::Type &&>(t); } template - struct gbImpl_Defer { + struct gbprivDefer { F f; - gbImpl_Defer(F &&f) : f(gb_forward_ownership(f)) {} - ~gbImpl_Defer() { f(); } + gbprivDefer(F &&f) : f(gb_forward_ownership(f)) {} + ~gbprivDefer() { f(); } }; - template gbImpl_Defer gb_defer_func(F &&f) { return gbImpl_Defer(gb_forward_ownership(f)); } + template gbprivDefer gb_defer_func(F &&f) { return gbprivDefer(gb_forward_ownership(f)); } #ifndef defer #define GB_DEFER_1(x, y) x##y @@ -375,6 +416,22 @@ extern "C++" { #endif +//////////////////////////////// +// +// Macro Fun! +// +// + +#ifndef GB_JOIN_MACROS +#define GB_JOIN_MACROS + #define GB_JOIN2_IND(a, b) a##b + #define GB_JOIN3_IND(a, b, c) a##b##c + + #define GB_JOIN2(a, b) GB_JOIN2_IND(a, b) + #define GB_JOIN3(a, b, c) GB_JOIN3_IND(a, b, c) +#endif + + #ifndef gb_min @@ -389,10 +446,10 @@ extern "C++" { //////////////////////////////// -// // -// Debug // -// // -//////////////////////////////// +// +// Debug +// +// #ifndef GB_DEBUG_TRAP @@ -407,7 +464,7 @@ extern "C++" { #ifndef GB_ASSERT_MSG #define GB_ASSERT_MSG(cond, msg, ...) do { \ if (!(cond)) { \ - gb_assert_handler(#cond, __FILE__, (long long)__LINE__, msg, ##__VA_ARGS__); \ + gb_assert_handler(#cond, __FILE__, cast(i64)__LINE__, msg, ##__VA_ARGS__); \ GB_DEBUG_TRAP(); \ } \ } while (0) @@ -421,32 +478,42 @@ extern "C++" { #define GB_PANIC(msg, ...) GB_ASSERT_MSG(0, msg, ##__VA_ARGS__) #endif -GB_DEF void gb_assert_handler(char const *condition, - char const *file, long long line, - char const *msg, ...); +GB_DEF void gb_assert_handler(char const *condition, char const *file, i64 line, char const *msg, ...); //////////////////////////////// -// // -// Printing // -// // -//////////////////////////////// +// +// Printing +// +// -GB_DEF int gb_sprintf(char const *fmt, ...); -GB_DEF int gb_snprintf(char *str, usize n, char const *fmt, ...); -GB_DEF int gb_vsprintf(char const *fmt, va_list v); -GB_DEF int gb_vsnprintf(char *str, usize n, char const *fmt, va_list v); +// Some compilers support applying printf-style warnings to user functions. +#if defined(__clang__) || defined(__GNUC__) +#define GB_PRINTF_ARGS(FMT) __attribute__((format(printf, FMT, (FMT+1)))) +#else +#define GB_PRINTF_ARGS(FMT) +#endif + +GB_DEF int gb_printf(char const *fmt, ...) GB_PRINTF_ARGS(1); +GB_DEF int gb_printf_var(char const *fmt, va_list v); +GB_DEF int gb_fprintf(FILE *f, char const *fmt, ...) GB_PRINTF_ARGS(2); +GB_DEF int gb_fprintf_var(FILE *f, char const *fmt, va_list v); +GB_DEF int gb_sprintf(char const *fmt, ...) GB_PRINTF_ARGS(1); +GB_DEF int gb_sprintf_var(char const *fmt, va_list v); +GB_DEF int gb_snprintf(char *str, isize n, char const *fmt, ...) GB_PRINTF_ARGS(3); +GB_DEF int gb_snprintf_var(char *str, isize n, char const *fmt, va_list v); -//////////////////////////////// -// // -// Memory // -// // -//////////////////////////////// + +//////////////////////////////////////////////////////////////// +// +// Memory +// +// #ifndef gb_align_to #define gb_align_to(value, alignment) (((value) + ((alignment)-1)) & ~((alignment) - 1)) @@ -456,17 +523,18 @@ GB_DEF int gb_vsnprintf(char *str, usize n, char const *fmt, va_list v); #define gb_is_power_of_two(x) ((x) != 0) && !((x) & ((x)-1)) #endif -GB_DEF void *gb_align_forward(void *ptr, usize alignment); +GB_DEF void *gb_align_forward(void *ptr, isize alignment); -GB_DEF void gb_zero_size(void *ptr, usize size); +GB_DEF void gb_zero_size(void *ptr, isize size); #ifndef gb_zero_struct #define gb_zero_struct(t) gb_zero_size((t), gb_size_of(*(t))) // NOTE(bill): Pass pointer of struct #define gb_zero_array(a, count) gb_zero_size((a), gb_size_of((a)[0])*count) #endif -GB_DEF void *gb_memcpy(void *dest, void const *source, usize size); -GB_DEF void *gb_memmove(void *dest, void const *source, usize size); +GB_DEF void *gb_memcpy(void *dest, void const *source, isize size); +GB_DEF void *gb_memmove(void *dest, void const *source, isize size); +GB_DEF void *gb_memset(void *data, u8 byte_value, isize size); @@ -478,23 +546,26 @@ GB_DEF void *gb_memmove(void *dest, void const *source, usize size); #endif +#if 0 +// NOTE(bill): Is it possible in C (easily) to create a mutex where the zero value is +// an unlocked mutex be default and also does not require make/destroy ever? // Mutex typedef struct gbMutex { void *handle; } gbMutex; -GB_DEF gbMutex gb_make_mutex(void); -GB_DEF void gb_destroy_mutex(gbMutex *m); -GB_DEF void gb_lock_mutex(gbMutex *m); -GB_DEF void gb_try_lock_mutex(gbMutex *m); -GB_DEF void gb_unlock_mutex(gbMutex *m); +GB_DEF gbMutex gb_mutex_make(void); +GB_DEF void gb_mutex_destroy(gbMutex *m); +GB_DEF void gb_mutex_lock(gbMutex *m); +GB_DEF void gb_mutex_try_lock(gbMutex *m); +GB_DEF void gb_mutex_unlock(gbMutex *m); +#endif - -//////////////////////////////// -// // -// Custom Allocation // -// // -//////////////////////////////// +//////////////////////////////////////////////////////////////// +// +// Custom Allocation +// +// typedef enum gbAllocation_Type { GB_ALLOCATION_TYPE_ALLOC, @@ -506,10 +577,10 @@ typedef enum gbAllocation_Type { // NOTE(bill): This is useful so you can define an allocator of the same type and parameters #define GB_ALLOCATOR_PROC(name) \ void *name(void *allocator_data, gbAllocation_Type type, \ - usize size, usize alignment, \ - void *old_memory, usize old_size, \ - u32 options) -typedef GB_ALLOCATOR_PROC(gbAllocator_Proc); + isize size, isize alignment, \ + void *old_memory, isize old_size, \ + u64 options) +;typedef GB_ALLOCATOR_PROC(gbAllocator_Proc); typedef struct gbAllocator { gbAllocator_Proc *proc; @@ -520,17 +591,17 @@ typedef struct gbAllocator { #define GB_DEFAULT_MEMORY_ALIGNMENT 4 #endif -GB_DEF void *gb_alloc_align(gbAllocator a, usize size, usize alignment); -GB_DEF void *gb_alloc(gbAllocator a, usize size); +GB_DEF void *gb_alloc_align(gbAllocator a, isize size, isize alignment); +GB_DEF void *gb_alloc(gbAllocator a, isize size); GB_DEF void gb_free(gbAllocator a, void *ptr); GB_DEF void gb_free_all(gbAllocator a); -GB_DEF void *gb_resize(gbAllocator a, void *ptr, usize old_size, usize new_size); -GB_DEF void *gb_resize_align(gbAllocator a, void *ptr, usize old_size, usize new_size, usize alignment); +GB_DEF void *gb_resize(gbAllocator a, void *ptr, isize old_size, isize new_size); +GB_DEF void *gb_resize_align(gbAllocator a, void *ptr, isize old_size, isize new_size, isize alignment); -GB_DEF void *gb_alloc_copy(gbAllocator a, void const *src, usize size); -GB_DEF void *gb_alloc_align_copy(gbAllocator a, void const *src, usize size, usize alignment); +GB_DEF void *gb_alloc_copy(gbAllocator a, void const *src, isize size); +GB_DEF void *gb_alloc_copy_align(gbAllocator a, void const *src, isize size, isize alignment); -GB_DEF char *gb_alloc_cstring(gbAllocator a, char const *str, usize len); +GB_DEF char *gb_alloc_cstring(gbAllocator a, char const *str); // NOTE(bill): These are very useful and the type case has saved me from numerous bugs @@ -557,19 +628,18 @@ GB_DEF GB_ALLOCATOR_PROC(gb_malloc_allocator_proc); typedef struct gbArena { gbAllocator backing; void *physical_start; - usize total_size; - usize total_allocated; + isize total_size; + isize total_allocated; u32 temp_count; - b32 clear_allocations_to_zero; } gbArena; -GB_DEF void gb_arena_init_from_memory(gbArena *arena, void *start, usize size); -GB_DEF void gb_arena_init_from_allocator(gbArena *arena, gbAllocator backing, usize size); -GB_DEF void gb_arena_init_subarena(gbArena *arena, gbArena *parent_arena, usize size); +GB_DEF void gb_arena_init_from_memory(gbArena *arena, void *start, isize size); +GB_DEF void gb_arena_init_from_allocator(gbArena *arena, gbAllocator backing, isize size); +GB_DEF void gb_arena_init_subarena(gbArena *arena, gbArena *parent_arena, isize size); GB_DEF void gb_arena_free(gbArena *arena); -GB_DEF usize gb_arena_alignment_of(gbArena *arena, usize alignment); -GB_DEF usize gb_arena_size_remaining(gbArena *arena, usize alignment); +GB_DEF isize gb_arena_alignment_of(gbArena *arena, isize alignment); +GB_DEF isize gb_arena_size_remaining(gbArena *arena, isize alignment); GB_DEF void gb_arena_check(gbArena *arena); @@ -580,11 +650,11 @@ GB_DEF GB_ALLOCATOR_PROC(gb_arena_allocator_proc); typedef struct gbTemp_Arena_Memory { gbArena *arena; - usize original_count; + isize original_count; } gbTemp_Arena_Memory; -GB_DEF gbTemp_Arena_Memory gb_begin_temp_arena_memory(gbArena *arena); -GB_DEF void gb_end_temp_arena_memory(gbTemp_Arena_Memory tmp_mem); +GB_DEF gbTemp_Arena_Memory gb_temp_arena_memory_begin(gbArena *arena); +GB_DEF void gb_temp_arena_memory_end(gbTemp_Arena_Memory tmp_mem); @@ -600,13 +670,13 @@ typedef struct gbPool { void *physical_start; void *free_list; - usize block_size; - usize block_align; - usize total_size; + isize block_size; + isize block_align; + isize total_size; } gbPool; -GB_DEF void gb_pool_init(gbPool *pool, gbAllocator backing, usize num_blocks, usize block_size); -GB_DEF void gb_pool_init_align(gbPool *pool, gbAllocator backing, usize num_blocks, usize block_size, usize block_align); +GB_DEF void gb_pool_init(gbPool *pool, gbAllocator backing, isize num_blocks, isize block_size); +GB_DEF void gb_pool_init_align(gbPool *pool, gbAllocator backing, isize num_blocks, isize block_size, isize block_align); GB_DEF void gb_pool_free(gbPool *pool); @@ -614,11 +684,11 @@ GB_DEF gbAllocator gb_pool_allocator(gbPool *pool); GB_DEF GB_ALLOCATOR_PROC(gb_pool_allocator_proc); -//////////////////////////////////////// -// // -// Char Functions // -// // -//////////////////////////////////////// +//////////////////////////////////////////////////////////////// +// +// Char Functions +// +// GB_DEF char gb_char_to_lower(char c); GB_DEF char gb_char_to_upper(char c); @@ -634,71 +704,65 @@ GB_DEF b32 gb_char_is_alphanumeric(char c); GB_DEF void gb_to_lower(char *str); GB_DEF void gb_to_upper(char *str); -GB_DEF usize gb_strlen(char const *str); -GB_DEF char *gb_strncpy(char *dest, char const *source, usize len); -GB_DEF int gb_strncmp(char const *s1, char const *s2, usize len); +GB_DEF isize gb_strlen(char const *str); +GB_DEF char *gb_strncpy(char *dest, char const *source, isize len); +GB_DEF int gb_strncmp(char const *s1, char const *s2, isize len); -//////////////////////////////////////// -// // -// Windows UTF-8 Handling // -// // -//////////////////////////////////////// +//////////////////////////////////////////////////////////////// +// +// Windows UTF-8 Handling +// +// // Windows doesn't handle 8 bit filenames well ('cause Micro$hit) -GB_DEF char16 *gb_from_utf8(char16 *buffer, char *str, usize len); -GB_DEF char *gb_to_utf8(char *buffer, char16 *str, usize len); +GB_DEF char16 *gb_from_utf8(char16 *buffer, char *str, isize len); +GB_DEF char *gb_to_utf8(char *buffer, char16 *str, isize len); -//////////////////////////////////////// -// // -// gbString - C Read-Only-Compatible // -// // -//////////////////////////////////////// +//////////////////////////////////////////////////////////////// +// +// gbString - C Read-Only-Compatible +// +// // Pascal like strings in C typedef char *gbString; -#ifndef GB_STRING_SIZE -#define GB_STRING_SIZE -typedef u32 gbString_Size; -#endif - // This is stored at the beginning of the string -// NOTE(bill): It is (2*gb_size_of(gbString_Size) + 2*gb_size_of(void*)) (default: 16B (32bit), 24B (64bit)) -// NOTE(bill): If you only need a small string, just use a standard c string +// NOTE(bill): If you only need a small string, just use a standard c string or change the size typedef struct gbString_Header { - gbAllocator allocator; - gbString_Size length; - gbString_Size capacity; + gbAllocator allocator; + isize length; + isize capacity; } gbString_Header; -#define GB_STRING_HEADER(str) (cast(gbString_Header *)str - 1) +#define GB_STRING_HEADER(str) ((gbString_Header *)str - 1) GB_DEF gbString gb_string_make(gbAllocator a, char const *str); -GB_DEF gbString gb_string_make_length(gbAllocator a, void const *str, gbString_Size num_bytes); +GB_DEF gbString gb_string_make_length(gbAllocator a, void const *str, isize num_bytes); GB_DEF void gb_string_free(gbString str); GB_DEF gbString gb_string_duplicate(gbAllocator a, gbString const str); -GB_DEF gbString_Size gb_string_length(gbString const str); -GB_DEF gbString_Size gb_string_capacity(gbString const str); -GB_DEF gbString_Size gb_string_available_space(gbString const str); +GB_DEF isize gb_string_length(gbString const str); +GB_DEF isize gb_string_capacity(gbString const str); +GB_DEF isize gb_string_available_space(gbString const str); GB_DEF void gb_string_clear(gbString str); GB_DEF gbString gb_string_append_string(gbString str, gbString const other); -GB_DEF gbString gb_string_append_string_length(gbString str, void const *other, gbString_Size num_bytes); +GB_DEF gbString gb_string_append_string_length(gbString str, void const *other, isize num_bytes); GB_DEF gbString gb_string_append_cstring(gbString str, char const *other); GB_DEF gbString gb_string_set(gbString str, char const *cstr); -GB_DEF gbString gb_string_make_space_for(gbString str, gbString_Size add_len); -GB_DEF gbString_Size gb_string_allocation_size(gbString const str); +GB_DEF gbString gb_string_make_space_for(gbString str, isize add_len); +GB_DEF isize gb_string_allocation_size(gbString const str); GB_DEF b32 gb_strings_are_equal(gbString const lhs, gbString const rhs); @@ -708,59 +772,56 @@ GB_DEF gbString gb_string_trim_space(gbString str); /* Whitespace ` \t\r\n\v\f` -//////////////////////////////// -// // -// // -// // -// Dynamic Array (POD Types) // -// // -// // -// // -//////////////////////////////// +////////////////////////////////////////////////////////////////// +// +// Dynamic Array (POD Types) +// +// // NOTE(bill): I know this is a macro hell but C is an old (and shit) language with no proper arrays -// Also why the fuck not?! It fucking works! +// Also why the fuck not?! It fucking works! And it has custom allocation, which is already better than C++! -// NOTE(bill): Typedef every array -// e.g. typedef gbArray(int) gb_int_array; -#ifndef gbArray +// NOTE(bill): Typedef every array or you get anonymous structures everywhere! +// e.g. typedef gbArray(int) gb_Int_Array; +#ifndef GB_ARRAY_TYPE +#define GB_ARRAY_TYPE #define gbArray(Type) struct { \ gbAllocator allocator; \ - i64 count; \ - i64 capacity; \ - Type *e; \ + isize count; \ + isize capacity; \ + Type *data; \ } typedef gbArray(void) gbVoid_Array; // NOTE(bill): Used to generic stuff -/* Available Procedures for gbArray(Type) - gb_array_init - gb_array_free - gb_array_set_capacity - gb_array_grow - gb_array_append - gb_array_appendv - gb_array_pop - gb_array_clear - gb_array_resize - gb_array_reserve -*/ +// Available Procedures for gbArray(Type) +// gb_array_init +// gb_array_free +// gb_array_set_capacity +// gb_array_grow +// gb_array_append +// gb_array_appendv +// gb_array_pop +// gb_array_clear +// gb_array_resize +// gb_array_reserve +// #define gb_array_init(x, allocator_) do { gb_zero_struct(x); (x)->allocator = allocator_; } while (0) #define gb_array_free(x) do { \ if ((x)->allocator.proc) { \ gbAllocator a = (x)->allocator; \ - gb_free(a, (x)->e); \ + gb_free(a, (x)->data); \ gb_array_init((x), a); \ } \ } while (0) -#define gb_array_set_capacity(array, capacity) gb__array_set_capacity((array), (capacity), gb_size_of((array)->e[0])) +#define gb_array_set_capacity(array, capacity) gbprivarray_set_capacity((array), (capacity), gb_size_of((array)->data[0])) // NOTE(bill): Do not use directly the thing below, use the macro -GB_DEF void gb__array_set_capacity(void *array, i64 capacity, usize element_size); +GB_DEF void gbprivarray_set_capacity(void *array, i64 capacity, isize element_size); // TODO(bill): Decide on a decent growing formula for gbArray // Is 2*c+8 good enough @@ -775,15 +836,15 @@ GB_DEF void gb__array_set_capacity(void *array, i64 capacity, usize element_size #define gb_array_append(x, item) do { \ if ((x)->capacity < (x)->count+1) \ gb_array_grow(x, 0); \ - (x)->e[(x)->count++] = item; \ + (x)->data[(x)->count++] = item; \ } while (0) -#define gb_array_appendv(x, items, item_count) do { \ - GB_ASSERT(gb_size_of(items[0]) == gb_size_of((x)->e[0])); \ - if ((x)->capacity < (x)->count+item_count) \ - gb_array_grow(x, (x)->count+item_count); \ - gb_memcpy((x)->e[a->count], items, gb_size_of((x)->e[0])*item_count); \ - (x)->count += item_count; \ +#define gb_array_appendv(x, items, item_count) do { \ + GB_ASSERT(gb_size_of(items[0]) == gb_size_of((x)->data[0])); \ + if ((x)->capacity < (x)->count+item_count) \ + gb_array_grow(x, (x)->count+item_count); \ + gb_memcpy((x)->data[a->count], items, gb_size_of((x)->data[0])*item_count); \ + (x)->count += item_count; \ } while (0) @@ -798,51 +859,83 @@ GB_DEF void gb__array_set_capacity(void *array, i64 capacity, usize element_size } while (0) -#define gb_array_reserve(x, capacity) do { \ - if ((x)->capacity < capacity) \ - gb_array_set_capacity(x, capacity); \ +#define gb_array_reserve(x, new_capacity) do { \ + if ((x)->capacity < new_capacity) \ + gb_array_set_capacity(x, new_capacity); \ } while (0) -gb_no_inline void -gb__array_set_capacity(void *array_, i64 capacity, usize element_size) -{ - // NOTE(bill): I know this is unsafe so don't call this function directly - gbVoid_Array *a = cast(gbVoid_Array *)array_; - void *new_elements = NULL; +#endif /* GB_ARRAY_TYPE */ - GB_ASSERT(element_size > 0); - if (capacity == a->capacity) - return; - if (capacity < a->count) { - if (a->capacity < capacity) { - i64 new_capacity = 2*a->capacity + 8; - if (new_capacity < capacity) - new_capacity = capacity; - gb__array_set_capacity(a, new_capacity, element_size); - } - a->count = capacity; - } - if (capacity > 0) { - new_elements = gb_alloc(a->allocator, element_size*capacity); - gb_memcpy(new_elements, a->e, element_size*a->count); - } - gb_free(a->allocator, a->e); - a->e = new_elements; - a->capacity = capacity; + + + + +//////////////////////////////////////////////////////////////// +// +// +// Hash_Table (POD Types) +// +// + + +// TODO(bill): Hash Table and make it decent!!! + +// NOTE(bill): All keys are u64 +#ifndef GB_HASH_TABLE_TYPE +#define GB_HASH_TABLE_TYPE + +#define gbHash_Table_Entry(Type) struct { \ + u64 key; \ + Type value; \ } -#endif +#define gbHash_Table(Type) struct { \ + gbArray(isize) hashes; \ + gbArray(gbHash_Table_Entry(Type)) entries; \ +} + +#define gb_hash_table_init(h, allocator) do { \ + gb_array_init((h)->hashes, allocator); \ + gb_array_init((h)->entries, allocator); \ +} while (0) + +#define gb_hash_table_free(h) do { \ + gb_free(&(h)->hashes); \ + gb_free(&(h)->entries); \ +} while (0) -//////////////////////////////// -// // -// File Handling // -// // -//////////////////////////////// + +/* TODO(bill): Hash_Table Procs + gb_hash_table_init(h, allocator) + gb_hash_table_free(h) + + gb_hash_table_has(h, key) // Return false/true + gb_hash_table_get(h, key) // Return entries index + gb_hash_table_set(h, key, value) + gb_hash_table_remove(h, key) + gb_hash_table_reserve(h, capacity) + gb_hash_table_clear(h) + +*/ + + + + + +#endif /* GB_HASH_TABLE_TYPE */ + + + +//////////////////////////////////////////////////////////////// +// +// File Handling +// +// typedef struct gbFile { FILE *handle; // File to fread/fwrite @@ -851,14 +944,14 @@ typedef struct gbFile { GB_DEF b32 gb_file_create(gbFile *file, char const *filepath); // TODO(bill): Give file permissions GB_DEF b32 gb_file_open(gbFile *file, char const *filepath); GB_DEF b32 gb_file_close(gbFile *file); -GB_DEF b32 gb_file_read_at(gbFile *file, void *buffer, usize size, i64 offset); -GB_DEF b32 gb_file_write_at(gbFile *file, void const *buffer, usize size, i64 offset); +GB_DEF b32 gb_file_read_at(gbFile *file, void *buffer, isize size, i64 offset); +GB_DEF b32 gb_file_write_at(gbFile *file, void const *buffer, isize size, i64 offset); GB_DEF i64 gb_file_size(gbFile *file); typedef struct gbFile_Contents { void *data; - usize size; + isize size; } gbFile_Contents; GB_DEF gbFile_Contents gb_read_entire_file_contents(gbAllocator a, char const *filepath, b32 zero_terminate); @@ -870,31 +963,31 @@ GB_DEF gbFile_Contents gb_read_entire_file_contents(gbAllocator a, char const *f #endif /* GB_INCLUDE_GB_H */ -//////////////////////////////// -// // -// // -// // -// // -// // -// // -// // -// // -// // -// // -// // -// Implementation // -// // -// // -// // -// // -// // -// // -// // -// // -// // -// // -// // -//////////////////////////////// +//////////////////////////////////////////////////////////////// +// +// +// +// +// +// +// +// +// +// +// +// Implementation +// +// +// +// +// +// +// +// +// +// +// +//////////////////////////////////////////////////////////////// #if defined(GB_IMPLEMENTATION) @@ -904,38 +997,25 @@ extern "C" { int -gb_vsnprintf(char *str, usize n, char const *fmt, va_list v) -{ - int res; - #if defined(_WIN32) - res = _vsnprintf(str, n, fmt, v); - #else - res = vsnprintf(str, n, fmt, v) - #endif - if (n) str[n-1] = 0; - // NOTE(bill): Unix returns length output would require, Windows returns negative when truncated. - return (res >= cast(int)n || res < 0) ? -1 : res; -} - - -int -gb_snprintf(char *str, usize n, char const *fmt, ...) +gb_printf(char const *fmt, ...) { int res; va_list v; - va_start(v,fmt); - res = gb_vsnprintf(str, n, fmt, v); + va_start(v, fmt); + res = gb_fprintf_var(stdout, fmt, v); va_end(v); return res; } int -gb_vsprintf(char const *fmt, va_list v) +gb_fprintf(FILE *f, char const *fmt, ...) { - gb_local_persist char buffer[1024]; int res; - res = gb_vsnprintf(buffer, gb_size_of(buffer), fmt, v); + va_list v; + va_start(v, fmt); + res = gb_fprintf_var(stdout, fmt, v); + va_end(v); return res; } @@ -946,11 +1026,48 @@ gb_sprintf(char const *fmt, ...) int res; va_list v; va_start(v, fmt); - res = gb_vsnprintf(buffer, gb_size_of(buffer), fmt, v); + res = gb_snprintf_var(buffer, gb_size_of(buffer), fmt, v); va_end(v); return res; } +int +gb_snprintf(char *str, isize n, char const *fmt, ...) +{ + int res; + va_list v; + va_start(v,fmt); + res = gb_snprintf_var(str, n, fmt, v); + va_end(v); + return res; +} + + +gb_inline int gb_printf_var(char const *fmt, va_list v) { return gb_fprintf_var(stdout, fmt, v); } +gb_inline int gb_fprintf_var(FILE *f, char const *fmt, va_list v) { return vfprintf(f, fmt, v); } + +gb_inline int +gb_sprintf_var(char const *fmt, va_list v) +{ + gb_local_persist char buffer[1024]; + int res; + res = gb_snprintf_var(buffer, gb_size_of(buffer), fmt, v); + return res; +} + +gb_inline int +gb_snprintf_var(char *str, isize n, char const *fmt, va_list v) +{ + int res; +#if defined(_WIN32) + res = _vsnprintf(str, n, fmt, v); +#else + res = vsnprintf(str, n, fmt, v) +#endif + if (n) str[n-1] = 0; + // NOTE(bill): Unix returns length output would require, Windows returns negative when truncated. + return (res >= n || res < 0) ? -1 : res; +} @@ -964,31 +1081,29 @@ gb_sprintf(char const *fmt, ...) void -gb_assert_handler(char const *condition, - char const *file, long long line, - char const *msg, ...) +gb_assert_handler(char const *condition, char const *file, i64 line, char const *msg, ...) { - fprintf(stderr, "%s:%lld: Assert Failure: ", file, line); + gb_fprintf(stderr, "%s:%d: Assert Failure: ", file, cast(int)line); if (condition) - fprintf(stderr, "`%s` ", condition); + gb_fprintf(stderr, "`%s` ", condition); if (msg) { va_list args; va_start(args, msg); - vfprintf(stderr, msg, args); + gb_fprintf(stderr, msg, args); va_end(args); } - fprintf(stderr, "\n"); + gb_fprintf(stderr, "\n"); } gb_inline void * -gb_align_forward(void *ptr, usize align) +gb_align_forward(void *ptr, isize align) { uintptr p; - usize modulo; + isize modulo; GB_ASSERT(gb_is_power_of_two(align)); @@ -998,35 +1113,32 @@ gb_align_forward(void *ptr, usize align) return cast(void *)p; } -gb_inline void -gb_zero_size(void *ptr, usize size) -{ - memset(ptr, 0, size); -} +gb_inline void gb_zero_size(void *ptr, isize size) { gb_memset(ptr, 0, size); } -gb_inline void *gb_memcpy(void *dest, void const *source, usize size) { return memcpy(dest, source, size); } -gb_inline void *gb_memmove(void *dest, void const *source, usize size) { return memmove(dest, source, size); } +gb_inline void *gb_memcpy(void *dest, void const *source, isize size) { return memcpy(dest, source, size); } +gb_inline void *gb_memmove(void *dest, void const *source, isize size) { return memmove(dest, source, size); } +gb_inline void *gb_memset(void *data, u8 byte_value, isize size) { return memset(data, byte_value, size); } -gb_inline void *gb_alloc_align(gbAllocator a, usize size, usize alignment) { return a.proc(a.data, GB_ALLOCATION_TYPE_ALLOC, size, alignment, NULL, 0, 0); } -gb_inline void *gb_alloc(gbAllocator a, usize size) { return gb_alloc_align(a, size, GB_DEFAULT_MEMORY_ALIGNMENT); } +gb_inline void *gb_alloc_align(gbAllocator a, isize size, isize alignment) { return a.proc(a.data, GB_ALLOCATION_TYPE_ALLOC, size, alignment, NULL, 0, 0); } +gb_inline void *gb_alloc(gbAllocator a, isize size) { return gb_alloc_align(a, size, GB_DEFAULT_MEMORY_ALIGNMENT); } gb_inline void gb_free(gbAllocator a, void *ptr) { a.proc(a.data, GB_ALLOCATION_TYPE_FREE, 0, 0, ptr, 0, 0); } gb_inline void gb_free_all(gbAllocator a) { a.proc(a.data, GB_ALLOCATION_TYPE_FREE_ALL, 0, 0, NULL, 0, 0); } -gb_inline void *gb_resize(gbAllocator a, void *ptr, usize old_size, usize new_size) { return gb_resize_align(a, ptr, old_size, new_size, GB_DEFAULT_MEMORY_ALIGNMENT); } -gb_inline void *gb_resize_align(gbAllocator a, void *ptr, usize old_size, usize new_size, usize alignment) { return a.proc(a.data, GB_ALLOCATION_TYPE_RESIZE, new_size, alignment, ptr, old_size, 0); }; +gb_inline void *gb_resize(gbAllocator a, void *ptr, isize old_size, isize new_size) { return gb_resize_align(a, ptr, old_size, new_size, GB_DEFAULT_MEMORY_ALIGNMENT); } +gb_inline void *gb_resize_align(gbAllocator a, void *ptr, isize old_size, isize new_size, isize alignment) { return a.proc(a.data, GB_ALLOCATION_TYPE_RESIZE, new_size, alignment, ptr, old_size, 0); }; -gb_inline void *gb_alloc_copy(gbAllocator a, void const *src, usize size) { return gb_memcpy(gb_alloc(a, size), src, size); } -gb_inline void *gb_alloc_align_copy(gbAllocator a, void const *src, usize size, usize alignment) { return gb_memcpy(gb_alloc_align(a, size, alignment), src, size); } +gb_inline void *gb_alloc_copy(gbAllocator a, void const *src, isize size) { return gb_memcpy(gb_alloc(a, size), src, size); } +gb_inline void *gb_alloc_copy_align(gbAllocator a, void const *src, isize size, isize alignment) { return gb_memcpy(gb_alloc_align(a, size, alignment), src, size); } gb_inline char * -gb_alloc_cstring(gbAllocator a, char const *str, usize len) +gb_alloc_cstring(gbAllocator a, char const *str) { char *result; - if (len == 0) len = strlen(str); + isize len = gb_strlen(str); result = cast(char *)gb_alloc_copy(a, str, len+1); result[len] = '\0'; return result; @@ -1064,7 +1176,7 @@ GB_ALLOCATOR_PROC(gb_malloc_allocator_proc) void *ptr = NULL; void *original_block; // Original block void **aligned_block; // Aligned block - usize offset = (alignment-1) + sizeof(void *); + isize offset = (alignment-1) + sizeof(void *); original_block = cast(void *)malloc(size + offset); if (original_block) { uintptr t = (cast(uintptr)original_block + offset) & ~(alignment-1); @@ -1090,15 +1202,25 @@ GB_ALLOCATOR_PROC(gb_malloc_allocator_proc) break; case GB_ALLOCATION_TYPE_RESIZE: { - #if defined(_MSC_VER) + gbAllocator a = gb_malloc_allocator(); + if (!old_memory) return gb_alloc_align(a, size, alignment); + + if (size < old_size) + size = old_size; + + if (old_size == size) { + return old_memory; + } else { +#if defined(_MSC_VER) return _aligned_realloc(old_memory, size, alignment); - #else - gbAllocator a = gb_malloc_allocator(); +#else void *new_memory = gb_alloc_align(a, size, alignment); + if (!new_memory) return NULL; gb_memmove(new_memory, old_memory, gb_min(size, old_size)); gb_free(a, old_memory); return new_memory; - #endif +#endif + } } break; } @@ -1111,7 +1233,7 @@ GB_ALLOCATOR_PROC(gb_malloc_allocator_proc) gb_inline void -gb_arena_init_from_memory(gbArena *arena, void *start, usize size) +gb_arena_init_from_memory(gbArena *arena, void *start, isize size) { arena->backing.proc = NULL; arena->backing.data = NULL; @@ -1122,7 +1244,7 @@ gb_arena_init_from_memory(gbArena *arena, void *start, usize size) } gb_inline void -gb_arena_init_from_allocator(gbArena *arena, gbAllocator backing, usize size) +gb_arena_init_from_allocator(gbArena *arena, gbAllocator backing, isize size) { arena->backing = backing; arena->physical_start = gb_alloc(backing, size); // NOTE(bill): Uses default alignment @@ -1131,7 +1253,7 @@ gb_arena_init_from_allocator(gbArena *arena, gbAllocator backing, usize size) arena->temp_count = 0; } -gb_inline void gb_arena_init_subarena(gbArena *arena, gbArena *parent_arena, usize size) { gb_arena_init_from_allocator(arena, gb_arena_allocator(parent_arena), size); } +gb_inline void gb_arena_init_subarena(gbArena *arena, gbArena *parent_arena, isize size) { gb_arena_init_from_allocator(arena, gb_arena_allocator(parent_arena), size); } gb_inline void @@ -1144,14 +1266,14 @@ gb_arena_free(gbArena *arena) } -gb_inline usize -gb_arena_alignment_of(gbArena *arena, usize alignment) +gb_inline isize +gb_arena_alignment_of(gbArena *arena, isize alignment) { - usize alignment_offset, result_pointer, mask; + isize alignment_offset, result_pointer, mask; GB_ASSERT(gb_is_power_of_two(alignment)); alignment_offset = 0; - result_pointer = cast(usize)arena->physical_start + arena->total_allocated; + result_pointer = cast(isize)arena->physical_start + arena->total_allocated; mask = alignment - 1; if (result_pointer & mask) alignment_offset = alignment - (result_pointer & mask); @@ -1159,10 +1281,10 @@ gb_arena_alignment_of(gbArena *arena, usize alignment) return alignment_offset; } -gb_inline usize -gb_arena_size_remaining(gbArena *arena, usize alignment) +gb_inline isize +gb_arena_size_remaining(gbArena *arena, isize alignment) { - usize result = arena->total_size - (arena->total_allocated + gb_arena_alignment_of(arena, alignment)); + isize result = arena->total_size - (arena->total_allocated + gb_arena_alignment_of(arena, alignment)); return result; } @@ -1193,22 +1315,21 @@ GB_ALLOCATOR_PROC(gb_arena_allocator_proc) switch (type) { case GB_ALLOCATION_TYPE_ALLOC: { void *ptr; - usize actual_size = size + alignment; + isize actual_size = size + alignment; // NOTE(bill): Out of memory - if (arena->total_allocated + actual_size > cast(usize)arena->total_size) + if (arena->total_allocated + actual_size > cast(isize)arena->total_size) return NULL; ptr = gb_align_forward(cast(u8 *)arena->physical_start + arena->total_allocated, alignment); arena->total_allocated += actual_size; - if (arena->clear_allocations_to_zero) - gb_zero_size(ptr, size); return ptr; } break; case GB_ALLOCATION_TYPE_FREE: // NOTE(bill): Free all at once // NOTE(bill): Use Temp_Arena_Memory if you want to free a block + // TODO(bill): Free it if it's on top of the stack break; case GB_ALLOCATION_TYPE_FREE_ALL: @@ -1216,11 +1337,22 @@ GB_ALLOCATOR_PROC(gb_arena_allocator_proc) break; case GB_ALLOCATION_TYPE_RESIZE: { + // TODO(bill): Check if ptr is on top of stack and just extend gbAllocator a = gb_arena_allocator(arena); - void *new_memory = gb_alloc_align(a, size, alignment); - gb_memmove(new_memory, old_memory, gb_min(size, old_size)); - gb_free(a, old_memory); - return new_memory; + if (!old_memory) return gb_alloc_align(a, size, alignment); + + if (size < old_size) + size = old_size; + + if (old_size == size) { + return old_memory; + } else { + void *new_memory = gb_alloc_align(a, size, alignment); + if (!new_memory) return NULL; + gb_memmove(new_memory, old_memory, gb_min(size, old_size)); + gb_free(a, old_memory); + return new_memory; + } } break; } @@ -1229,7 +1361,7 @@ GB_ALLOCATOR_PROC(gb_arena_allocator_proc) gb_inline gbTemp_Arena_Memory -gb_begin_temp_arena_memory(gbArena *arena) +gb_temp_arena_memory_begin(gbArena *arena) { gbTemp_Arena_Memory tmp; tmp.arena = arena; @@ -1239,7 +1371,7 @@ gb_begin_temp_arena_memory(gbArena *arena) } gb_inline void -gb_end_temp_arena_memory(gbTemp_Arena_Memory tmp) +gb_temp_arena_memory_end(gbTemp_Arena_Memory tmp) { GB_ASSERT(tmp.arena->total_allocated >= tmp.original_count); GB_ASSERT(tmp.arena->temp_count > 0); @@ -1251,15 +1383,15 @@ gb_end_temp_arena_memory(gbTemp_Arena_Memory tmp) gb_inline void -gb_pool_init(gbPool *pool, gbAllocator backing, usize num_blocks, usize block_size) +gb_pool_init(gbPool *pool, gbAllocator backing, isize num_blocks, isize block_size) { gb_pool_init_align(pool, backing, num_blocks, block_size, GB_DEFAULT_MEMORY_ALIGNMENT); } void -gb_pool_init_align(gbPool *pool, gbAllocator backing, usize num_blocks, usize block_size, usize block_align) +gb_pool_init_align(gbPool *pool, gbAllocator backing, isize num_blocks, isize block_size, isize block_align) { - usize actual_block_size, pool_size, block_index; + isize actual_block_size, pool_size, block_index; u8 *data, *curr; uintptr *end; @@ -1282,7 +1414,7 @@ gb_pool_init_align(gbPool *pool, gbAllocator backing, usize num_blocks, usize bl curr += actual_block_size; } - end = cast(uintptr*)curr; + end = cast(uintptr *)curr; *end = cast(uintptr)NULL; pool->physical_start = data; @@ -1432,21 +1564,21 @@ gb_char_is_alphanumeric(char c) -gb_inline void gb__string_set_length(gbString str, gbString_Size len) { GB_STRING_HEADER(str)->length = len; } -gb_inline void gb__string_set_capacity(gbString str, gbString_Size cap) { GB_STRING_HEADER(str)->capacity = cap; } +gb_inline void gbprivstring_set_length(gbString str, isize len) { GB_STRING_HEADER(str)->length = len; } +gb_inline void gbprivstring_set_capacity(gbString str, isize cap) { GB_STRING_HEADER(str)->capacity = cap; } gb_inline gbString gb_string_make(gbAllocator a, char const *str) { - gbString_Size len = cast(gbString_Size)(str ? strlen(str) : 0); + isize len = str ? gb_strlen(str) : 0; return gb_string_make_length(a, str, len); } gbString -gb_string_make_length(gbAllocator a, void const *init_str, gbString_Size num_bytes) +gb_string_make_length(gbAllocator a, void const *init_str, isize num_bytes) { - gbString_Size header_size = gb_size_of(gbString_Header); + isize header_size = gb_size_of(gbString_Header); void *ptr = gb_alloc(a, header_size + num_bytes + 1); gbString str; @@ -1480,10 +1612,10 @@ gb_string_free(gbString str) gb_inline gbString gb_string_duplicate(gbAllocator a, gbString const str) { return gb_string_make_length(a, str, gb_string_length(str)); } -gb_inline gbString_Size gb_string_length(gbString const str) { return GB_STRING_HEADER(str)->length; } -gb_inline gbString_Size gb_string_capacity(gbString const str) { return GB_STRING_HEADER(str)->capacity; } +gb_inline isize gb_string_length(gbString const str) { return GB_STRING_HEADER(str)->length; } +gb_inline isize gb_string_capacity(gbString const str) { return GB_STRING_HEADER(str)->capacity; } -gb_inline gbString_Size +gb_inline isize gb_string_available_space(gbString const str) { gbString_Header *h = GB_STRING_HEADER(str); @@ -1493,14 +1625,14 @@ gb_string_available_space(gbString const str) } -gb_inline void gb_string_clear(gbString str) { gb__string_set_length(str, 0); str[0] = '\0'; } +gb_inline void gb_string_clear(gbString str) { gbprivstring_set_length(str, 0); str[0] = '\0'; } gb_inline gbString gb_string_append_string(gbString str, gbString const other) { return gb_string_append_string_length(str, other, gb_string_length(other)); } gbString -gb_string_append_string_length(gbString str, void const *other, gbString_Size other_len) +gb_string_append_string_length(gbString str, void const *other, isize other_len) { - gbString_Size curr_len = gb_string_length(str); + isize curr_len = gb_string_length(str); str = gb_string_make_space_for(str, other_len); if (str == NULL) @@ -1508,7 +1640,7 @@ gb_string_append_string_length(gbString str, void const *other, gbString_Size ot gb_memcpy(str + curr_len, other, other_len); str[curr_len + other_len] = '\0'; - gb__string_set_length(str, curr_len + other_len); + gbprivstring_set_length(str, curr_len + other_len); return str; } @@ -1516,14 +1648,14 @@ gb_string_append_string_length(gbString str, void const *other, gbString_Size ot gb_inline gbString gb_string_append_cstring(gbString str, char const *other) { - return gb_string_append_string_length(str, other, cast(gbString_Size)strlen(other)); + return gb_string_append_string_length(str, other, cast(isize)strlen(other)); } gbString gb_string_set(gbString str, char const *cstr) { - gbString_Size len = cast(gbString_Size)strlen(cstr); + isize len = gb_strlen(cstr); if (gb_string_capacity(str) < len) { str = gb_string_make_space_for(str, len - gb_string_length(str)); if (str == NULL) @@ -1532,63 +1664,41 @@ gb_string_set(gbString str, char const *cstr) gb_memcpy(str, cstr, len); str[len] = '\0'; - gb__string_set_length(str, len); + gbprivstring_set_length(str, len); return str; } -gb_internal void * -gb__string_realloc(gbAllocator a, void *ptr, gbString_Size old_size, gbString_Size new_size) -{ - if (!ptr) return gb_alloc(a, new_size); - - if (new_size < old_size) - new_size = old_size; - - if (old_size == new_size) { - return ptr; - } else { - void *new_ptr = gb_alloc(a, new_size); - if (!new_ptr) - return NULL; - - gb_memcpy(new_ptr, ptr, old_size); - gb_free(a, ptr); - return new_ptr; - } -} - - gbString -gb_string_make_space_for(gbString str, gbString_Size add_len) +gb_string_make_space_for(gbString str, isize add_len) { - gbString_Size available = gb_string_available_space(str); + isize available = gb_string_available_space(str); // Return if there is enough space left if (available >= add_len) { return str; } else { - gbString_Size new_len = gb_string_length(str) + add_len; + isize new_len = gb_string_length(str) + add_len; void *ptr = GB_STRING_HEADER(str); - gbString_Size old_size = gb_size_of(gbString_Header) + gb_string_length(str) + 1; - gbString_Size new_size = gb_size_of(gbString_Header) + new_len + 1; + isize old_size = gb_size_of(gbString_Header) + gb_string_length(str) + 1; + isize new_size = gb_size_of(gbString_Header) + new_len + 1; - void *new_ptr = gb__string_realloc(GB_STRING_HEADER(str)->allocator, ptr, old_size, new_size); + void *new_ptr = gb_resize(GB_STRING_HEADER(str)->allocator, ptr, old_size, new_size); if (new_ptr == NULL) return NULL; str = cast(char *)(GB_STRING_HEADER(new_ptr) + 1); - gb__string_set_capacity(str, new_len); + gbprivstring_set_capacity(str, new_len); return str; } } -gb_inline gbString_Size +gb_inline isize gb_string_allocation_size(gbString const str) { - gbString_Size cap = gb_string_capacity(str); + isize cap = gb_string_capacity(str); return gb_size_of(gbString_Header) + cap; } @@ -1596,7 +1706,7 @@ gb_string_allocation_size(gbString const str) gb_inline b32 gb_strings_are_equal(gbString const lhs, gbString const rhs) { - gbString_Size lhs_len, rhs_len, i; + isize lhs_len, rhs_len, i; lhs_len = gb_string_length(lhs); rhs_len = gb_string_length(rhs); if (lhs_len != rhs_len) @@ -1615,7 +1725,7 @@ gbString gb_string_trim(gbString str, char const *cut_set) { char *start, *end, *start_pos, *end_pos; - gbString_Size len; + isize len; start_pos = start = str; end_pos = end = str + gb_string_length(str) - 1; @@ -1625,13 +1735,13 @@ gb_string_trim(gbString str, char const *cut_set) while (end_pos > start_pos && strchr(cut_set, *end_pos)) end_pos--; - len = cast(gbString_Size)((start_pos > end_pos) ? 0 : ((end_pos - start_pos)+1)); + len = cast(isize)((start_pos > end_pos) ? 0 : ((end_pos - start_pos)+1)); if (str != start_pos) gb_memmove(str, start_pos, len); str[len] = '\0'; - gb__string_set_length(str, len); + gbprivstring_set_length(str, len); return str; } @@ -1659,7 +1769,7 @@ gb_to_upper(char *str) } -gb_inline usize +gb_inline isize gb_strlen(char const *str) { char const *end; @@ -1670,7 +1780,7 @@ gb_strlen(char const *str) } gb_inline char * -gb_strncpy(char *dest, char const *source, usize len) +gb_strncpy(char *dest, char const *source, isize len) { char *str = dest; while (len > 0 && *source) { @@ -1685,7 +1795,7 @@ gb_strncpy(char *dest, char const *source, usize len) } gb_inline int -gb_strncmp(char const *s1, char const *s2, usize len) +gb_strncmp(char const *s1, char const *s2, isize len) { for(; len > 0; s1++, s2++, len--) { if (*s1 != *s2) @@ -1699,19 +1809,19 @@ gb_strncmp(char const *s1, char const *s2, usize len) -//////////////////////////////////////// -// // -// Windows UTF-8 Handling // -// // -//////////////////////////////////////// +//////////////////////////////////////////////////////////////// +// +// Windows UTF-8 Handling +// +// char16 * -gb_from_utf8(char16 *buffer, char *s, usize len) +gb_from_utf8(char16 *buffer, char *s, isize len) { u8 *str = cast(u8 *)s; u32 c; - usize i = 0; + isize i = 0; len--; while (*str) { if (i >= len) @@ -1774,9 +1884,9 @@ gb_from_utf8(char16 *buffer, char *s, usize len) } char * -gb_to_utf8(char *buffer, char16 *str, usize len) +gb_to_utf8(char *buffer, char16 *str, isize len) { - usize i = 0; + isize i = 0; len--; while (*str) { if (*str < 0x80) { @@ -1823,21 +1933,21 @@ gb_to_utf8(char *buffer, char16 *str, usize len) //////////////////////////////// gb_inline b32 -gb_create_file(gbFile *file, char const *filepath) +gb_file_create(gbFile *file, char const *filepath) { file->handle = fopen(filepath, "wb"); return (file->handle != NULL); // TODO(bill): Handle fopen errors } gb_inline b32 -gb_open_file(gbFile *file, char const *filepath) +gb_file_open(gbFile *file, char const *filepath) { file->handle = fopen(filepath, "rb"); return (file->handle != NULL); // TODO(bill): Handle fopen errors } gb_inline b32 -gb_close_file(gbFile *file) +gb_file_close(gbFile *file) { b32 result = true; if (file && file->handle) @@ -1846,7 +1956,7 @@ gb_close_file(gbFile *file) } gb_inline b32 -gb_read_file_at(gbFile *file, void *buffer, usize size, i64 offset) +gb_file_read_at(gbFile *file, void *buffer, isize size, i64 offset) { i64 prev_cursor_pos = ftell(file->handle); fseek(file->handle, offset, SEEK_SET); @@ -1856,9 +1966,9 @@ gb_read_file_at(gbFile *file, void *buffer, usize size, i64 offset) } gb_inline b32 -gb_write_file_at(gbFile *file, void const *buffer, usize size, i64 offset) +gb_file_write_at(gbFile *file, void const *buffer, isize size, i64 offset) { - usize written_size; + isize written_size; i64 prev_cursor_pos = ftell(file->handle); fseek(file->handle, offset, SEEK_SET); @@ -1876,10 +1986,10 @@ gb_write_file_at(gbFile *file, void const *buffer, usize size, i64 offset) gb_inline i64 gb_file_size(gbFile *file) { - usize result_size; + i64 result_size; fseek(file->handle, 0, SEEK_END); - result_size = cast(usize)ftell(file->handle); + result_size = cast(i64)ftell(file->handle); fseek(file->handle, 0, SEEK_SET); return result_size; } @@ -1893,16 +2003,16 @@ gb_read_entire_file_contents(gbAllocator a, char const *filepath, b32 zero_termi { gbFile_Contents result = {0}; gbFile file = {0}; - if (gb_open_file(&file, filepath)) { + if (gb_file_open(&file, filepath)) { i64 file_size = gb_file_size(&file); if (file_size > 0) { result.data = gb_alloc(a, zero_terminate ? file_size+1 : file_size); result.size = file_size; - gb_read_file_at(&file, result.data, result.size, 0); + gb_file_read_at(&file, result.data, result.size, 0); if (zero_terminate) (cast(u8 *)(result.data))[file_size] = '\0'; } - gb_close_file(&file); + gb_file_close(&file); } return result; @@ -1911,6 +2021,36 @@ gb_read_entire_file_contents(gbAllocator a, char const *filepath, b32 zero_termi +gb_no_inline void +gbprivarray_set_capacity(void *array_, isize capacity, isize element_size) +{ + // NOTE(bill): I know this is unsafe so don't call this function directly + gbVoid_Array *a = cast(gbVoid_Array *)array_; + void *data = NULL; + + GB_ASSERT(element_size > 0); + + if (capacity == a->capacity) + return; + + if (capacity < a->count) { + if (a->capacity < capacity) { + isize new_capacity = 2*a->capacity + 8; + if (new_capacity < capacity) + new_capacity = capacity; + gbprivarray_set_capacity(a, new_capacity, element_size); + } + a->count = capacity; + } + + if (capacity > 0) { + data = gb_alloc(a->allocator, element_size*capacity); + gb_memcpy(data, a->data, element_size*a->count); + } + gb_free(a->allocator, a->data); + a->data = data; + a->capacity = capacity; +} From d7b6d601d1f553c1795308ed6062dbb97d25c0c2 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Tue, 12 Apr 2016 21:52:56 +0100 Subject: [PATCH 14/15] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index f26823f..1e8f048 100644 --- a/README.md +++ b/README.md @@ -5,10 +5,10 @@ gb single-file public domain libraries for C & C++ library | latest version | category | languages | description ----------------|----------------|----------|-----------|------------- **gb_string.h** | 0.93 | strings | C, C++ | A better string library for C & C++ -**gb_math.h** | 0.04c | math | C | A C vector math library geared towards game development -**gb.h** | 0.01 | misc | C | A C helper library geared towards game development (NOT a port of gb.hpp) +**gb_math.h** | 0.04d | math | C | A C vector math library geared towards game development +**gb.h** | 0.02a | misc | C | A C helper library geared towards game development (NOT a port of gb.hpp) **gb_ini.h** | 0.91a | misc | C, C++ | A simple ini file loader library for C & C++ -**gb.hpp** | 0.32 | misc | C++11 | (Experimental) A C++11 helper library without STL geared towards game development +**gb.hpp** | 0.32 | misc | C++11 | (To be retired soon) (Experimental) A C++11 helper library without STL geared towards game development ## FAQ From a78da2bf506c4a5abacf6418660664b39ad6d4e1 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Tue, 12 Apr 2016 22:46:06 +0100 Subject: [PATCH 15/15] Update gb.h --- gb.h | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/gb.h b/gb.h index 9a51b0f..ebdda44 100644 --- a/gb.h +++ b/gb.h @@ -819,9 +819,9 @@ typedef gbArray(void) gbVoid_Array; // NOTE(bill): Used to generic stuff } \ } while (0) -#define gb_array_set_capacity(array, capacity) gbprivarray_set_capacity((array), (capacity), gb_size_of((array)->data[0])) +#define gb_array_set_capacity(array, capacity) gbpriv_array_set_capacity((array), (capacity), gb_size_of((array)->data[0])) // NOTE(bill): Do not use directly the thing below, use the macro -GB_DEF void gbprivarray_set_capacity(void *array, i64 capacity, isize element_size); +GB_DEF void gbpriv_array_set_capacity(void *array, i64 capacity, isize element_size); // TODO(bill): Decide on a decent growing formula for gbArray // Is 2*c+8 good enough @@ -1564,8 +1564,8 @@ gb_char_is_alphanumeric(char c) -gb_inline void gbprivstring_set_length(gbString str, isize len) { GB_STRING_HEADER(str)->length = len; } -gb_inline void gbprivstring_set_capacity(gbString str, isize cap) { GB_STRING_HEADER(str)->capacity = cap; } +gb_inline void gbpriv_string_set_length(gbString str, isize len) { GB_STRING_HEADER(str)->length = len; } +gb_inline void gbpriv_string_set_capacity(gbString str, isize cap) { GB_STRING_HEADER(str)->capacity = cap; } gb_inline gbString @@ -1625,7 +1625,7 @@ gb_string_available_space(gbString const str) } -gb_inline void gb_string_clear(gbString str) { gbprivstring_set_length(str, 0); str[0] = '\0'; } +gb_inline void gb_string_clear(gbString str) { gbpriv_string_set_length(str, 0); str[0] = '\0'; } gb_inline gbString gb_string_append_string(gbString str, gbString const other) { return gb_string_append_string_length(str, other, gb_string_length(other)); } @@ -1640,7 +1640,7 @@ gb_string_append_string_length(gbString str, void const *other, isize other_len) gb_memcpy(str + curr_len, other, other_len); str[curr_len + other_len] = '\0'; - gbprivstring_set_length(str, curr_len + other_len); + gbpriv_string_set_length(str, curr_len + other_len); return str; } @@ -1664,7 +1664,7 @@ gb_string_set(gbString str, char const *cstr) gb_memcpy(str, cstr, len); str[len] = '\0'; - gbprivstring_set_length(str, len); + gbpriv_string_set_length(str, len); return str; } @@ -1689,7 +1689,7 @@ gb_string_make_space_for(gbString str, isize add_len) if (new_ptr == NULL) return NULL; str = cast(char *)(GB_STRING_HEADER(new_ptr) + 1); - gbprivstring_set_capacity(str, new_len); + gbpriv_string_set_capacity(str, new_len); return str; } @@ -1741,7 +1741,7 @@ gb_string_trim(gbString str, char const *cut_set) gb_memmove(str, start_pos, len); str[len] = '\0'; - gbprivstring_set_length(str, len); + gbpriv_string_set_length(str, len); return str; } @@ -2022,7 +2022,7 @@ gb_read_entire_file_contents(gbAllocator a, char const *filepath, b32 zero_termi gb_no_inline void -gbprivarray_set_capacity(void *array_, isize capacity, isize element_size) +gbpriv_array_set_capacity(void *array_, isize capacity, isize element_size) { // NOTE(bill): I know this is unsafe so don't call this function directly gbVoid_Array *a = cast(gbVoid_Array *)array_; @@ -2038,7 +2038,7 @@ gbprivarray_set_capacity(void *array_, isize capacity, isize element_size) isize new_capacity = 2*a->capacity + 8; if (new_capacity < capacity) new_capacity = capacity; - gbprivarray_set_capacity(a, new_capacity, element_size); + gbpriv_array_set_capacity(a, new_capacity, element_size); } a->count = capacity; }