diff --git a/raylib/cgo.go b/raylib/cgo.go index 60e7130..88562e0 100644 --- a/raylib/cgo.go +++ b/raylib/cgo.go @@ -1,6 +1,6 @@ package rl /* -#cgo CFLAGS: -std=gnu99 -Wno-missing-braces -Wno-unused-result -Wno-implicit-function-declaration +#cgo CFLAGS: -std=gnu99 -Wno-missing-braces -Wno-unused-result -Wno-implicit-function-declaration -Wno-int-to-pointer-cast */ import "C" diff --git a/raylib/config.h b/raylib/config.h index 4017e62..4edaa59 100644 --- a/raylib/config.h +++ b/raylib/config.h @@ -6,7 +6,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2018-2023 Ahmad Fatoum & Ramon Santamaria (@raysan5) +* Copyright (c) 2018-2024 Ahmad Fatoum & Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. @@ -81,6 +81,7 @@ #define MAX_GAMEPADS 4 // Maximum number of gamepads supported #define MAX_GAMEPAD_AXIS 8 // Maximum number of axis supported (per gamepad) #define MAX_GAMEPAD_BUTTONS 32 // Maximum number of buttons supported (per gamepad) +#define MAX_GAMEPAD_VIBRATION_TIME 2.0f // Maximum vibration time in seconds #define MAX_TOUCH_POINTS 8 // Maximum number of touch points supported #define MAX_KEY_PRESSED_QUEUE 16 // Maximum number of keys in the key input queue #define MAX_CHAR_PRESSED_QUEUE 16 // Maximum number of characters in the char input queue @@ -111,14 +112,22 @@ #define RL_CULL_DISTANCE_NEAR 0.01 // Default projection matrix near cull distance #define RL_CULL_DISTANCE_FAR 1000.0 // Default projection matrix far cull distance +// Default shader vertex attribute locations +#define RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION 0 +#define RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD 1 +#define RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL 2 +#define RL_DEFAULT_SHADER_ATTRIB_LOCATION_COLOR 3 +#define RL_DEFAULT_SHADER_ATTRIB_LOCATION_TANGENT 4 +#define RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD2 5 + // Default shader vertex attribute names to set location points // NOTE: When a new shader is loaded, the following locations are tried to be set for convenience -#define RL_DEFAULT_SHADER_ATTRIB_NAME_POSITION "vertexPosition" // Bound by default to shader location: 0 -#define RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD "vertexTexCoord" // Bound by default to shader location: 1 -#define RL_DEFAULT_SHADER_ATTRIB_NAME_NORMAL "vertexNormal" // Bound by default to shader location: 2 -#define RL_DEFAULT_SHADER_ATTRIB_NAME_COLOR "vertexColor" // Bound by default to shader location: 3 -#define RL_DEFAULT_SHADER_ATTRIB_NAME_TANGENT "vertexTangent" // Bound by default to shader location: 4 -#define RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD2 "vertexTexCoord2" // Bound by default to shader location: 5 +#define RL_DEFAULT_SHADER_ATTRIB_NAME_POSITION "vertexPosition" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION +#define RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD "vertexTexCoord" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD +#define RL_DEFAULT_SHADER_ATTRIB_NAME_NORMAL "vertexNormal" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL +#define RL_DEFAULT_SHADER_ATTRIB_NAME_COLOR "vertexColor" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_LOCATION_COLOR +#define RL_DEFAULT_SHADER_ATTRIB_NAME_TANGENT "vertexTangent" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_LOCATION_TANGENT +#define RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD2 "vertexTexCoord2" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD2 #define RL_DEFAULT_SHADER_UNIFORM_NAME_MVP "mvp" // model-view-projection matrix #define RL_DEFAULT_SHADER_UNIFORM_NAME_VIEW "matView" // view matrix @@ -138,6 +147,10 @@ // Some lines-based shapes could still use lines #define SUPPORT_QUADS_DRAW_MODE 1 +// rshapes: Configuration values +//------------------------------------------------------------------------------------ +#define SPLINE_SEGMENT_DIVISIONS 24 // Spline segments subdivisions + //------------------------------------------------------------------------------------ // Module: rtextures - Configuration Flags @@ -175,8 +188,9 @@ // NOTE: If enabled, uses external module functions to load default raylib font #define SUPPORT_DEFAULT_FONT 1 // Selected desired font fileformats to be supported for loading -#define SUPPORT_FILEFORMAT_FNT 1 #define SUPPORT_FILEFORMAT_TTF 1 +#define SUPPORT_FILEFORMAT_FNT 1 +#define SUPPORT_FILEFORMAT_BDF 1 // Support text management functions // If not defined, still some functions are supported: TextLength(), TextFormat() diff --git a/raylib/external/cgltf.h b/raylib/external/cgltf.h index ddec501..3231201 100644 --- a/raylib/external/cgltf.h +++ b/raylib/external/cgltf.h @@ -63,9 +63,14 @@ * By passing null for the output pointer, users can find out how many floats are required in the * output buffer. * + * `cgltf_accessor_unpack_indices` reads in the index data from an accessor. Assumes that + * `cgltf_load_buffers` has already been called. By passing null for the output pointer, users can + * find out how many indices are required in the output buffer. Returns 0 if the accessor is + * sparse or if the output component size is less than the accessor's component size. + * * `cgltf_num_components` is a tiny utility that tells you the dimensionality of * a certain accessor type. This can be used before `cgltf_accessor_unpack_floats` to help allocate - * the necessary amount of memory. `cgltf_component_size` and `cgltf_calc_size` exist for + * the necessary amount of memory. `cgltf_component_size` and `cgltf_calc_size` exist for * similar purposes. * * `cgltf_accessor_read_float` reads a certain element from a non-sparse accessor and converts it to @@ -75,7 +80,7 @@ * * `cgltf_accessor_read_uint` is similar to its floating-point counterpart, but limited to reading * vector types and does not support matrix types. The passed-in element size is the number of uints - * in the output buffer, which should be in the range [1, 4]. Returns false if the passed-in + * in the output buffer, which should be in the range [1, 4]. Returns false if the passed-in * element_size is too small, or if the accessor is sparse. * * `cgltf_accessor_read_index` is similar to its floating-point counterpart, but it returns size_t @@ -197,6 +202,7 @@ typedef enum cgltf_type typedef enum cgltf_primitive_type { + cgltf_primitive_type_invalid, cgltf_primitive_type_points, cgltf_primitive_type_lines, cgltf_primitive_type_line_loop, @@ -499,6 +505,11 @@ typedef struct cgltf_anisotropy cgltf_texture_view anisotropy_texture; } cgltf_anisotropy; +typedef struct cgltf_dispersion +{ + cgltf_float dispersion; +} cgltf_dispersion; + typedef struct cgltf_material { char* name; @@ -513,6 +524,7 @@ typedef struct cgltf_material cgltf_bool has_emissive_strength; cgltf_bool has_iridescence; cgltf_bool has_anisotropy; + cgltf_bool has_dispersion; cgltf_pbr_metallic_roughness pbr_metallic_roughness; cgltf_pbr_specular_glossiness pbr_specular_glossiness; cgltf_clearcoat clearcoat; @@ -524,6 +536,7 @@ typedef struct cgltf_material cgltf_emissive_strength emissive_strength; cgltf_iridescence iridescence; cgltf_anisotropy anisotropy; + cgltf_dispersion dispersion; cgltf_texture_view normal_texture; cgltf_texture_view occlusion_texture; cgltf_texture_view emissive_texture; @@ -838,7 +851,7 @@ cgltf_size cgltf_component_size(cgltf_component_type component_type); cgltf_size cgltf_calc_size(cgltf_type type, cgltf_component_type component_type); cgltf_size cgltf_accessor_unpack_floats(const cgltf_accessor* accessor, cgltf_float* out, cgltf_size float_count); -cgltf_size cgltf_accessor_unpack_indices(const cgltf_accessor* accessor, cgltf_uint* out, cgltf_size index_count); +cgltf_size cgltf_accessor_unpack_indices(const cgltf_accessor* accessor, void* out, cgltf_size out_component_size, cgltf_size index_count); /* this function is deprecated and will be removed in the future; use cgltf_extras::data instead */ cgltf_result cgltf_copy_extras_json(const cgltf_data* data, const cgltf_extras* extras, char* dest, cgltf_size* dest_size); @@ -938,8 +951,8 @@ static int jsmn_parse(jsmn_parser *parser, const char *js, size_t len, jsmntok_t #ifndef CGLTF_CONSTS -static const cgltf_size GlbHeaderSize = 12; -static const cgltf_size GlbChunkHeaderSize = 8; +#define GlbHeaderSize 12 +#define GlbChunkHeaderSize 8 static const uint32_t GlbVersion = 2; static const uint32_t GlbMagic = 0x46546C67; static const uint32_t GlbMagicJsonChunk = 0x4E4F534A; @@ -1033,7 +1046,7 @@ static cgltf_result cgltf_default_file_read(const struct cgltf_memory_options* m fclose(file); return cgltf_result_out_of_memory; } - + cgltf_size read_size = fread(file_data, 1, file_size, file); fclose(file); @@ -1141,7 +1154,7 @@ cgltf_result cgltf_parse(const cgltf_options* options, const void* data, cgltf_s // JSON chunk: length uint32_t json_length; memcpy(&json_length, json_chunk, 4); - if (GlbHeaderSize + GlbChunkHeaderSize + json_length > size) + if (json_length > size - GlbHeaderSize - GlbChunkHeaderSize) { return cgltf_result_data_too_short; } @@ -1158,7 +1171,7 @@ cgltf_result cgltf_parse(const cgltf_options* options, const void* data, cgltf_s const void* bin = NULL; cgltf_size bin_size = 0; - if (GlbHeaderSize + GlbChunkHeaderSize + json_length + GlbChunkHeaderSize <= size) + if (GlbChunkHeaderSize <= size - GlbHeaderSize - GlbChunkHeaderSize - json_length) { // We can read another chunk const uint8_t* bin_chunk = json_chunk + json_length; @@ -1166,7 +1179,7 @@ cgltf_result cgltf_parse(const cgltf_options* options, const void* data, cgltf_s // Bin chunk: length uint32_t bin_length; memcpy(&bin_length, bin_chunk, 4); - if (GlbHeaderSize + GlbChunkHeaderSize + json_length + GlbChunkHeaderSize + bin_length > size) + if (bin_length > size - GlbHeaderSize - GlbChunkHeaderSize - json_length - GlbChunkHeaderSize) { return cgltf_result_data_too_short; } @@ -1552,6 +1565,9 @@ cgltf_result cgltf_validate(cgltf_data* data) { cgltf_accessor* accessor = &data->accessors[i]; + CGLTF_ASSERT_IF(data->accessors[i].component_type == cgltf_component_type_invalid, cgltf_result_invalid_gltf); + CGLTF_ASSERT_IF(data->accessors[i].type == cgltf_type_invalid, cgltf_result_invalid_gltf); + cgltf_size element_size = cgltf_calc_size(accessor->type, accessor->component_type); if (accessor->buffer_view) @@ -1565,7 +1581,7 @@ cgltf_result cgltf_validate(cgltf_data* data) { cgltf_accessor_sparse* sparse = &accessor->sparse; - cgltf_size indices_component_size = cgltf_calc_size(cgltf_type_scalar, sparse->indices_component_type); + cgltf_size indices_component_size = cgltf_component_size(sparse->indices_component_type); cgltf_size indices_req_size = sparse->indices_byte_offset + indices_component_size * sparse->count; cgltf_size values_req_size = sparse->values_byte_offset + element_size * sparse->count; @@ -1631,43 +1647,48 @@ cgltf_result cgltf_validate(cgltf_data* data) for (cgltf_size j = 0; j < data->meshes[i].primitives_count; ++j) { + CGLTF_ASSERT_IF(data->meshes[i].primitives[j].type == cgltf_primitive_type_invalid, cgltf_result_invalid_gltf); CGLTF_ASSERT_IF(data->meshes[i].primitives[j].targets_count != data->meshes[i].primitives[0].targets_count, cgltf_result_invalid_gltf); - if (data->meshes[i].primitives[j].attributes_count) + CGLTF_ASSERT_IF(data->meshes[i].primitives[j].attributes_count == 0, cgltf_result_invalid_gltf); + + cgltf_accessor* first = data->meshes[i].primitives[j].attributes[0].data; + + CGLTF_ASSERT_IF(first->count == 0, cgltf_result_invalid_gltf); + + for (cgltf_size k = 0; k < data->meshes[i].primitives[j].attributes_count; ++k) { - cgltf_accessor* first = data->meshes[i].primitives[j].attributes[0].data; + CGLTF_ASSERT_IF(data->meshes[i].primitives[j].attributes[k].data->count != first->count, cgltf_result_invalid_gltf); + } - for (cgltf_size k = 0; k < data->meshes[i].primitives[j].attributes_count; ++k) + for (cgltf_size k = 0; k < data->meshes[i].primitives[j].targets_count; ++k) + { + for (cgltf_size m = 0; m < data->meshes[i].primitives[j].targets[k].attributes_count; ++m) { - CGLTF_ASSERT_IF(data->meshes[i].primitives[j].attributes[k].data->count != first->count, cgltf_result_invalid_gltf); + CGLTF_ASSERT_IF(data->meshes[i].primitives[j].targets[k].attributes[m].data->count != first->count, cgltf_result_invalid_gltf); } + } - for (cgltf_size k = 0; k < data->meshes[i].primitives[j].targets_count; ++k) - { - for (cgltf_size m = 0; m < data->meshes[i].primitives[j].targets[k].attributes_count; ++m) - { - CGLTF_ASSERT_IF(data->meshes[i].primitives[j].targets[k].attributes[m].data->count != first->count, cgltf_result_invalid_gltf); - } - } + cgltf_accessor* indices = data->meshes[i].primitives[j].indices; - cgltf_accessor* indices = data->meshes[i].primitives[j].indices; + CGLTF_ASSERT_IF(indices && + indices->component_type != cgltf_component_type_r_8u && + indices->component_type != cgltf_component_type_r_16u && + indices->component_type != cgltf_component_type_r_32u, cgltf_result_invalid_gltf); - CGLTF_ASSERT_IF(indices && - indices->component_type != cgltf_component_type_r_8u && - indices->component_type != cgltf_component_type_r_16u && - indices->component_type != cgltf_component_type_r_32u, cgltf_result_invalid_gltf); + CGLTF_ASSERT_IF(indices && indices->type != cgltf_type_scalar, cgltf_result_invalid_gltf); + CGLTF_ASSERT_IF(indices && indices->stride != cgltf_component_size(indices->component_type), cgltf_result_invalid_gltf); - if (indices && indices->buffer_view && indices->buffer_view->buffer->data) - { - cgltf_size index_bound = cgltf_calc_index_bound(indices->buffer_view, indices->offset, indices->component_type, indices->count); + if (indices && indices->buffer_view && indices->buffer_view->buffer->data) + { + cgltf_size index_bound = cgltf_calc_index_bound(indices->buffer_view, indices->offset, indices->component_type, indices->count); - CGLTF_ASSERT_IF(index_bound >= first->count, cgltf_result_data_too_short); - } + CGLTF_ASSERT_IF(index_bound >= first->count, cgltf_result_data_too_short); + } - for (cgltf_size k = 0; k < data->meshes[i].primitives[j].mappings_count; ++k) - { - CGLTF_ASSERT_IF(data->meshes[i].primitives[j].mappings[k].variant >= data->variants_count, cgltf_result_invalid_gltf); - } + for (cgltf_size k = 0; k < data->meshes[i].primitives[j].mappings_count; ++k) + { + CGLTF_ASSERT_IF(data->meshes[i].primitives[j].mappings[k].variant >= data->variants_count, cgltf_result_invalid_gltf); } } } @@ -1724,10 +1745,15 @@ cgltf_result cgltf_validate(cgltf_data* data) cgltf_size values = channel->sampler->interpolation == cgltf_interpolation_type_cubic_spline ? 3 : 1; - CGLTF_ASSERT_IF(channel->sampler->input->count * components * values != channel->sampler->output->count, cgltf_result_data_too_short); + CGLTF_ASSERT_IF(channel->sampler->input->count * components * values != channel->sampler->output->count, cgltf_result_invalid_gltf); } } + for (cgltf_size i = 0; i < data->variants_count; ++i) + { + CGLTF_ASSERT_IF(!data->variants[i].name, cgltf_result_invalid_gltf); + } + return cgltf_result_success; } @@ -1902,7 +1928,7 @@ void cgltf_free(cgltf_data* data) data->memory.free_func(data->memory.user_data, data->materials); - for (cgltf_size i = 0; i < data->images_count; ++i) + for (cgltf_size i = 0; i < data->images_count; ++i) { data->memory.free_func(data->memory.user_data, data->images[i].name); data->memory.free_func(data->memory.user_data, data->images[i].uri); @@ -2550,7 +2576,7 @@ cgltf_size cgltf_animation_channel_index(const cgltf_animation* animation, const return (cgltf_size)(object - animation->channels); } -cgltf_size cgltf_accessor_unpack_indices(const cgltf_accessor* accessor, cgltf_uint* out, cgltf_size index_count) +cgltf_size cgltf_accessor_unpack_indices(const cgltf_accessor* accessor, void* out, cgltf_size out_component_size, cgltf_size index_count) { if (out == NULL) { @@ -2558,6 +2584,7 @@ cgltf_size cgltf_accessor_unpack_indices(const cgltf_accessor* accessor, cgltf_u } index_count = accessor->count < index_count ? accessor->count : index_count; + cgltf_size index_component_size = cgltf_component_size(accessor->component_type); if (accessor->is_sparse) { @@ -2567,6 +2594,10 @@ cgltf_size cgltf_accessor_unpack_indices(const cgltf_accessor* accessor, cgltf_u { return 0; } + if (index_component_size > out_component_size) + { + return 0; + } const uint8_t* element = cgltf_buffer_view_data(accessor->buffer_view); if (element == NULL) { @@ -2574,18 +2605,29 @@ cgltf_size cgltf_accessor_unpack_indices(const cgltf_accessor* accessor, cgltf_u } element += accessor->offset; - if (accessor->component_type == cgltf_component_type_r_32u && accessor->stride == sizeof(cgltf_uint)) + if (index_component_size == out_component_size && accessor->stride == out_component_size) { - memcpy(out, element, index_count * sizeof(cgltf_uint)); + memcpy(out, element, index_count * index_component_size); + return index_count; } - else - { - cgltf_uint* dest = out; - for (cgltf_size index = 0; index < index_count; index++, dest++, element += accessor->stride) + // The component size of the output array is larger than the component size of the index data, so index data will be padded. + switch (out_component_size) + { + case 2: + for (cgltf_size index = 0; index < index_count; index++, element += accessor->stride) { - *dest = (cgltf_uint)cgltf_component_read_index(element, accessor->component_type); + ((uint16_t*)out)[index] = (uint16_t)cgltf_component_read_index(element, accessor->component_type); } + break; + case 4: + for (cgltf_size index = 0; index < index_count; index++, element += accessor->stride) + { + ((uint32_t*)out)[index] = (uint32_t)cgltf_component_read_index(element, accessor->component_type); + } + break; + default: + break; } return index_count; @@ -2596,7 +2638,7 @@ cgltf_size cgltf_accessor_unpack_indices(const cgltf_accessor* accessor, cgltf_u #define CGLTF_ERROR_LEGACY -3 #define CGLTF_CHECK_TOKTYPE(tok_, type_) if ((tok_).type != (type_)) { return CGLTF_ERROR_JSON; } -#define CGLTF_CHECK_TOKTYPE_RETTYPE(tok_, type_, ret_) if ((tok_).type != (type_)) { return (ret_)CGLTF_ERROR_JSON; } +#define CGLTF_CHECK_TOKTYPE_RET(tok_, type_, ret_) if ((tok_).type != (type_)) { return ret_; } #define CGLTF_CHECK_KEY(tok_) if ((tok_).type != JSMN_STRING || (tok_).size == 0) { return CGLTF_ERROR_JSON; } /* checking size for 0 verifies that a value follows the key */ #define CGLTF_PTRINDEX(type, idx) (type*)((cgltf_size)idx + 1) @@ -2623,12 +2665,13 @@ static int cgltf_json_to_int(jsmntok_t const* tok, const uint8_t* json_chunk) static cgltf_size cgltf_json_to_size(jsmntok_t const* tok, const uint8_t* json_chunk) { - CGLTF_CHECK_TOKTYPE_RETTYPE(*tok, JSMN_PRIMITIVE, cgltf_size); + CGLTF_CHECK_TOKTYPE_RET(*tok, JSMN_PRIMITIVE, 0); char tmp[128]; int size = (size_t)(tok->end - tok->start) < sizeof(tmp) ? (int)(tok->end - tok->start) : (int)(sizeof(tmp) - 1); strncpy(tmp, (const char*)json_chunk + tok->start, size); tmp[size] = 0; - return (cgltf_size)CGLTF_ATOLL(tmp); + long long res = CGLTF_ATOLL(tmp); + return res < 0 ? 0 : (cgltf_size)res; } static cgltf_float cgltf_json_to_float(jsmntok_t const* tok, const uint8_t* json_chunk) @@ -2810,6 +2853,11 @@ static void cgltf_parse_attribute_type(const char* name, cgltf_attribute_type* o if (us && *out_type != cgltf_attribute_type_invalid) { *out_index = CGLTF_ATOI(us + 1); + if (*out_index < 0) + { + *out_type = cgltf_attribute_type_invalid; + *out_index = 0; + } } } @@ -3142,6 +3190,31 @@ static int cgltf_parse_json_material_mappings(cgltf_options* options, jsmntok_t return i; } +static cgltf_primitive_type cgltf_json_to_primitive_type(jsmntok_t const* tok, const uint8_t* json_chunk) +{ + int type = cgltf_json_to_int(tok, json_chunk); + + switch (type) + { + case 0: + return cgltf_primitive_type_points; + case 1: + return cgltf_primitive_type_lines; + case 2: + return cgltf_primitive_type_line_loop; + case 3: + return cgltf_primitive_type_line_strip; + case 4: + return cgltf_primitive_type_triangles; + case 5: + return cgltf_primitive_type_triangle_strip; + case 6: + return cgltf_primitive_type_triangle_fan; + default: + return cgltf_primitive_type_invalid; + } +} + static int cgltf_parse_json_primitive(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_primitive* out_prim) { CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); @@ -3158,9 +3231,7 @@ static int cgltf_parse_json_primitive(cgltf_options* options, jsmntok_t const* t if (cgltf_json_strcmp(tokens+i, json_chunk, "mode") == 0) { ++i; - out_prim->type - = (cgltf_primitive_type) - cgltf_json_to_int(tokens+i, json_chunk); + out_prim->type = cgltf_json_to_primitive_type(tokens+i, json_chunk); ++i; } else if (cgltf_json_strcmp(tokens+i, json_chunk, "indices") == 0) @@ -3410,7 +3481,7 @@ static int cgltf_parse_json_accessor_sparse(jsmntok_t const* tokens, int i, cons if (cgltf_json_strcmp(tokens+i, json_chunk, "count") == 0) { ++i; - out_sparse->count = cgltf_json_to_int(tokens + i, json_chunk); + out_sparse->count = cgltf_json_to_size(tokens + i, json_chunk); ++i; } else if (cgltf_json_strcmp(tokens+i, json_chunk, "indices") == 0) @@ -3546,8 +3617,7 @@ static int cgltf_parse_json_accessor(cgltf_options* options, jsmntok_t const* to else if (cgltf_json_strcmp(tokens+i, json_chunk, "count") == 0) { ++i; - out_accessor->count = - cgltf_json_to_int(tokens+i, json_chunk); + out_accessor->count = cgltf_json_to_size(tokens+i, json_chunk); ++i; } else if (cgltf_json_strcmp(tokens+i, json_chunk, "type") == 0) @@ -3700,7 +3770,7 @@ static int cgltf_parse_json_texture_view(cgltf_options* options, jsmntok_t const out_texture_view->texcoord = cgltf_json_to_int(tokens + i, json_chunk); ++i; } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "scale") == 0) + else if (cgltf_json_strcmp(tokens + i, json_chunk, "scale") == 0) { ++i; out_texture_view->scale = cgltf_json_to_float(tokens + i, json_chunk); @@ -3769,11 +3839,11 @@ static int cgltf_parse_json_pbr_metallic_roughness(cgltf_options* options, jsmnt if (cgltf_json_strcmp(tokens+i, json_chunk, "metallicFactor") == 0) { ++i; - out_pbr->metallic_factor = + out_pbr->metallic_factor = cgltf_json_to_float(tokens + i, json_chunk); ++i; } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "roughnessFactor") == 0) + else if (cgltf_json_strcmp(tokens+i, json_chunk, "roughnessFactor") == 0) { ++i; out_pbr->roughness_factor = @@ -4234,6 +4304,37 @@ static int cgltf_parse_json_anisotropy(cgltf_options* options, jsmntok_t const* return i; } +static int cgltf_parse_json_dispersion(jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_dispersion* out_dispersion) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + int size = tokens[i].size; + ++i; + + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens + i, json_chunk, "dispersion") == 0) + { + ++i; + out_dispersion->dispersion = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else + { + i = cgltf_skip_json(tokens, i + 1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + static int cgltf_parse_json_image(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_image* out_image) { CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); @@ -4241,11 +4342,11 @@ static int cgltf_parse_json_image(cgltf_options* options, jsmntok_t const* token int size = tokens[i].size; ++i; - for (int j = 0; j < size; ++j) + for (int j = 0; j < size; ++j) { CGLTF_CHECK_KEY(tokens[i]); - if (cgltf_json_strcmp(tokens + i, json_chunk, "uri") == 0) + if (cgltf_json_strcmp(tokens + i, json_chunk, "uri") == 0) { i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_image->uri); } @@ -4325,7 +4426,7 @@ static int cgltf_parse_json_sampler(cgltf_options* options, jsmntok_t const* tok = cgltf_json_to_int(tokens + i, json_chunk); ++i; } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "wrapT") == 0) + else if (cgltf_json_strcmp(tokens + i, json_chunk, "wrapT") == 0) { ++i; out_sampler->wrap_t @@ -4375,7 +4476,7 @@ static int cgltf_parse_json_texture(cgltf_options* options, jsmntok_t const* tok out_texture->sampler = CGLTF_PTRINDEX(cgltf_sampler, cgltf_json_to_int(tokens + i, json_chunk)); ++i; } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "source") == 0) + else if (cgltf_json_strcmp(tokens + i, json_chunk, "source") == 0) { ++i; out_texture->image = CGLTF_PTRINDEX(cgltf_image, cgltf_json_to_int(tokens + i, json_chunk)); @@ -4627,6 +4728,11 @@ static int cgltf_parse_json_material(cgltf_options* options, jsmntok_t const* to out_material->has_anisotropy = 1; i = cgltf_parse_json_anisotropy(options, tokens, i + 1, json_chunk, &out_material->anisotropy); } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "KHR_materials_dispersion") == 0) + { + out_material->has_dispersion = 1; + i = cgltf_parse_json_dispersion(tokens, i + 1, json_chunk, &out_material->dispersion); + } else { i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, &(out_material->extensions[out_material->extensions_count++])); @@ -4786,7 +4892,7 @@ static int cgltf_parse_json_meshopt_compression(cgltf_options* options, jsmntok_ else if (cgltf_json_strcmp(tokens+i, json_chunk, "count") == 0) { ++i; - out_meshopt_compression->count = cgltf_json_to_int(tokens+i, json_chunk); + out_meshopt_compression->count = cgltf_json_to_size(tokens+i, json_chunk); ++i; } else if (cgltf_json_strcmp(tokens+i, json_chunk, "mode") == 0) diff --git a/raylib/external/rl_gputex.h b/raylib/external/rl_gputex.h index 2cbe596..c577305 100644 --- a/raylib/external/rl_gputex.h +++ b/raylib/external/rl_gputex.h @@ -229,7 +229,7 @@ void *rl_load_dds_from_memory(const unsigned char *file_data, unsigned int file_ } } } - else if (header->ddspf.flags == 0x40 && header->ddspf.rgb_bit_count == 24) // DDS_RGB, no compressed + else if ((header->ddspf.flags == 0x40) && (header->ddspf.rgb_bit_count == 24)) // DDS_RGB, no compressed { int data_size = image_pixel_size*3*sizeof(unsigned char); image_data = RL_MALLOC(data_size); @@ -238,7 +238,7 @@ void *rl_load_dds_from_memory(const unsigned char *file_data, unsigned int file_ *format = PIXELFORMAT_UNCOMPRESSED_R8G8B8; } - else if (header->ddspf.flags == 0x41 && header->ddspf.rgb_bit_count == 32) // DDS_RGBA, no compressed + else if ((header->ddspf.flags == 0x41) && (header->ddspf.rgb_bit_count == 32)) // DDS_RGBA, no compressed { int data_size = image_pixel_size*4*sizeof(unsigned char); image_data = RL_MALLOC(data_size); diff --git a/raylib/external/rprand.h b/raylib/external/rprand.h index c9b460c..ded6708 100644 --- a/raylib/external/rprand.h +++ b/raylib/external/rprand.h @@ -147,8 +147,13 @@ RPRANDAPI void rprand_unload_sequence(int *sequence); // Unload pseudo //---------------------------------------------------------------------------------- // Global Variables Definition //---------------------------------------------------------------------------------- -static uint64_t rprand_seed = 0; // SplitMix64 actual seed -static uint32_t rprand_state[4] = { 0 }; // Xoshiro128** state, nitialized by SplitMix64 +static uint64_t rprand_seed = 0xAABBCCDD; // SplitMix64 default seed (aligned to rprand_state) +static uint32_t rprand_state[4] = { // Xoshiro128** state, initialized by SplitMix64 + 0x96ea83c1, + 0x218b21e5, + 0xaa91febd, + 0x976414d4 +}; //---------------------------------------------------------------------------------- // Module internal functions declaration @@ -200,10 +205,9 @@ int *rprand_load_sequence(unsigned int count, int min, int max) for (unsigned int i = 0; i < count;) { - value = ((int)rprand_xoshiro()%(abs(max - min) + 1)) + min; - value_is_dup = false; + value = ((unsigned int)rprand_xoshiro()%(abs(max - min) + 1)) + min; - for (int j = 0; j < i; j++) + for (unsigned int j = 0; j < i; j++) { if (sequence[j] == value) { @@ -217,6 +221,8 @@ int *rprand_load_sequence(unsigned int count, int min, int max) sequence[i] = value; i++; } + + value_is_dup = false; } return sequence; diff --git a/raylib/external/sinfl.h b/raylib/external/sinfl.h index 16589c1..3c71737 100644 --- a/raylib/external/sinfl.h +++ b/raylib/external/sinfl.h @@ -171,7 +171,7 @@ extern int zsinflate(void *out, int cap, const void *in, int size); static int sinfl_bsr(unsigned n) { -#ifdef _MSC_VER +#if defined(_MSC_VER) && !defined(__clang__) _BitScanReverse(&n, n); return n; #elif defined(__GNUC__) || defined(__clang__) @@ -231,13 +231,13 @@ sinfl_refill(struct sinfl *s) { } static int sinfl_peek(struct sinfl *s, int cnt) { - assert(cnt >= 0 && cnt <= 56); - assert(cnt <= s->bitcnt); + //assert(cnt >= 0 && cnt <= 56); // @raysan5: commented to avoid crash on decompression + //assert(cnt <= s->bitcnt); return s->bitbuf & ((1ull << cnt) - 1); } static void sinfl_eat(struct sinfl *s, int cnt) { - assert(cnt <= s->bitcnt); + //assert(cnt <= s->bitcnt); // @raysan5: commented s->bitbuf >>= cnt; s->bitcnt -= cnt; } diff --git a/raylib/external/vox_loader.h b/raylib/external/vox_loader.h index 6df10b5..0d328c0 100644 --- a/raylib/external/vox_loader.h +++ b/raylib/external/vox_loader.h @@ -123,6 +123,7 @@ typedef struct { // Arrays for mesh build ArrayVector3 vertices; + ArrayVector3 normals; ArrayUShort indices; ArrayColor colors; @@ -292,6 +293,16 @@ const VoxVector3 SolidVertex[] = { {1, 1, 1} //7 }; +const VoxVector3 FacesPerSideNormal[] = { + { -1, 0, 0 }, //-X + {1, 0, 0 }, //+X + {0,-1, 0}, //-Y + {0, 1, 0}, //+Y + {0, 0, -1}, //-Z + {0, 0, 1}, //+Z +}; + + // Allocated VoxArray3D size static void Vox_AllocArray(VoxArray3D* pvoxarray, int _sx, int _sy, int _sz) { @@ -508,6 +519,11 @@ static void Vox_Build_Voxel(VoxArray3D* pvoxArray, int x, int y, int z, int matI insertArrayVector3(&pvoxArray->vertices, vertComputed[v2]); insertArrayVector3(&pvoxArray->vertices, vertComputed[v3]); + insertArrayVector3(&pvoxArray->normals, FacesPerSideNormal[i]); + insertArrayVector3(&pvoxArray->normals, FacesPerSideNormal[i]); + insertArrayVector3(&pvoxArray->normals, FacesPerSideNormal[i]); + insertArrayVector3(&pvoxArray->normals, FacesPerSideNormal[i]); + VoxColor col = pvoxArray->palette[matID]; insertArrayColor(&pvoxArray->colors, col); @@ -653,6 +669,7 @@ int Vox_LoadFromMemory(unsigned char* pvoxData, unsigned int voxDataSize, VoxArr // Init Arrays initArrayVector3(&pvoxarray->vertices, 3 * 1024); + initArrayVector3(&pvoxarray->normals, 3 * 1024); initArrayUShort(&pvoxarray->indices, 3 * 1024); initArrayColor(&pvoxarray->colors, 3 * 1024); diff --git a/raylib/platforms/rcore_android.c b/raylib/platforms/rcore_android.c index e0b7fd2..f7b304e 100644 --- a/raylib/platforms/rcore_android.c +++ b/raylib/platforms/rcore_android.c @@ -27,7 +27,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2013-2023 Ramon Santamaria (@raysan5) and contributors +* Copyright (c) 2013-2024 Ramon Santamaria (@raysan5) and contributors * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. @@ -77,6 +77,175 @@ extern CoreData CORE; // Global CORE state context static PlatformData platform = { 0 }; // Platform specific data +//---------------------------------------------------------------------------------- +// Local Variables Definition +//---------------------------------------------------------------------------------- +#define KEYCODE_MAP_SIZE 162 +static const KeyboardKey KeycodeMap[KEYCODE_MAP_SIZE] = { + KEY_NULL, // AKEYCODE_UNKNOWN + 0, // AKEYCODE_SOFT_LEFT + 0, // AKEYCODE_SOFT_RIGHT + 0, // AKEYCODE_HOME + KEY_BACK, // AKEYCODE_BACK + 0, // AKEYCODE_CALL + 0, // AKEYCODE_ENDCALL + KEY_ZERO, // AKEYCODE_0 + KEY_ONE, // AKEYCODE_1 + KEY_TWO, // AKEYCODE_2 + KEY_THREE, // AKEYCODE_3 + KEY_FOUR, // AKEYCODE_4 + KEY_FIVE, // AKEYCODE_5 + KEY_SIX, // AKEYCODE_6 + KEY_SEVEN, // AKEYCODE_7 + KEY_EIGHT, // AKEYCODE_8 + KEY_NINE, // AKEYCODE_9 + 0, // AKEYCODE_STAR + 0, // AKEYCODE_POUND + KEY_UP, // AKEYCODE_DPAD_UP + KEY_DOWN, // AKEYCODE_DPAD_DOWN + KEY_LEFT, // AKEYCODE_DPAD_LEFT + KEY_RIGHT, // AKEYCODE_DPAD_RIGHT + 0, // AKEYCODE_DPAD_CENTER + KEY_VOLUME_UP, // AKEYCODE_VOLUME_UP + KEY_VOLUME_DOWN, // AKEYCODE_VOLUME_DOWN + 0, // AKEYCODE_POWER + 0, // AKEYCODE_CAMERA + 0, // AKEYCODE_CLEAR + KEY_A, // AKEYCODE_A + KEY_B, // AKEYCODE_B + KEY_C, // AKEYCODE_C + KEY_D, // AKEYCODE_D + KEY_E, // AKEYCODE_E + KEY_F, // AKEYCODE_F + KEY_G, // AKEYCODE_G + KEY_H, // AKEYCODE_H + KEY_I, // AKEYCODE_I + KEY_J, // AKEYCODE_J + KEY_K, // AKEYCODE_K + KEY_L, // AKEYCODE_L + KEY_M, // AKEYCODE_M + KEY_N, // AKEYCODE_N + KEY_O, // AKEYCODE_O + KEY_P, // AKEYCODE_P + KEY_Q, // AKEYCODE_Q + KEY_R, // AKEYCODE_R + KEY_S, // AKEYCODE_S + KEY_T, // AKEYCODE_T + KEY_U, // AKEYCODE_U + KEY_V, // AKEYCODE_V + KEY_W, // AKEYCODE_W + KEY_X, // AKEYCODE_X + KEY_Y, // AKEYCODE_Y + KEY_Z, // AKEYCODE_Z + KEY_COMMA, // AKEYCODE_COMMA + KEY_PERIOD, // AKEYCODE_PERIOD + KEY_LEFT_ALT, // AKEYCODE_ALT_LEFT + KEY_RIGHT_ALT, // AKEYCODE_ALT_RIGHT + KEY_LEFT_SHIFT, // AKEYCODE_SHIFT_LEFT + KEY_RIGHT_SHIFT, // AKEYCODE_SHIFT_RIGHT + KEY_TAB, // AKEYCODE_TAB + KEY_SPACE, // AKEYCODE_SPACE + 0, // AKEYCODE_SYM + 0, // AKEYCODE_EXPLORER + 0, // AKEYCODE_ENVELOPE + KEY_ENTER, // AKEYCODE_ENTER + KEY_BACKSPACE, // AKEYCODE_DEL + KEY_GRAVE, // AKEYCODE_GRAVE + KEY_MINUS, // AKEYCODE_MINUS + KEY_EQUAL, // AKEYCODE_EQUALS + KEY_LEFT_BRACKET, // AKEYCODE_LEFT_BRACKET + KEY_RIGHT_BRACKET, // AKEYCODE_RIGHT_BRACKET + KEY_BACKSLASH, // AKEYCODE_BACKSLASH + KEY_SEMICOLON, // AKEYCODE_SEMICOLON + KEY_APOSTROPHE, // AKEYCODE_APOSTROPHE + KEY_SLASH, // AKEYCODE_SLASH + 0, // AKEYCODE_AT + 0, // AKEYCODE_NUM + 0, // AKEYCODE_HEADSETHOOK + 0, // AKEYCODE_FOCUS + 0, // AKEYCODE_PLUS + KEY_MENU, // AKEYCODE_MENU + 0, // AKEYCODE_NOTIFICATION + 0, // AKEYCODE_SEARCH + 0, // AKEYCODE_MEDIA_PLAY_PAUSE + 0, // AKEYCODE_MEDIA_STOP + 0, // AKEYCODE_MEDIA_NEXT + 0, // AKEYCODE_MEDIA_PREVIOUS + 0, // AKEYCODE_MEDIA_REWIND + 0, // AKEYCODE_MEDIA_FAST_FORWARD + 0, // AKEYCODE_MUTE + KEY_PAGE_UP, // AKEYCODE_PAGE_UP + KEY_PAGE_DOWN, // AKEYCODE_PAGE_DOWN + 0, // AKEYCODE_PICTSYMBOLS + 0, // AKEYCODE_SWITCH_CHARSET + 0, // AKEYCODE_BUTTON_A + 0, // AKEYCODE_BUTTON_B + 0, // AKEYCODE_BUTTON_C + 0, // AKEYCODE_BUTTON_X + 0, // AKEYCODE_BUTTON_Y + 0, // AKEYCODE_BUTTON_Z + 0, // AKEYCODE_BUTTON_L1 + 0, // AKEYCODE_BUTTON_R1 + 0, // AKEYCODE_BUTTON_L2 + 0, // AKEYCODE_BUTTON_R2 + 0, // AKEYCODE_BUTTON_THUMBL + 0, // AKEYCODE_BUTTON_THUMBR + 0, // AKEYCODE_BUTTON_START + 0, // AKEYCODE_BUTTON_SELECT + 0, // AKEYCODE_BUTTON_MODE + KEY_ESCAPE, // AKEYCODE_ESCAPE + KEY_DELETE, // AKEYCODE_FORWARD_DELL + KEY_LEFT_CONTROL, // AKEYCODE_CTRL_LEFT + KEY_RIGHT_CONTROL, // AKEYCODE_CTRL_RIGHT + KEY_CAPS_LOCK, // AKEYCODE_CAPS_LOCK + KEY_SCROLL_LOCK, // AKEYCODE_SCROLL_LOCK + KEY_LEFT_SUPER, // AKEYCODE_META_LEFT + KEY_RIGHT_SUPER, // AKEYCODE_META_RIGHT + 0, // AKEYCODE_FUNCTION + KEY_PRINT_SCREEN, // AKEYCODE_SYSRQ + KEY_PAUSE, // AKEYCODE_BREAK + KEY_HOME, // AKEYCODE_MOVE_HOME + KEY_END, // AKEYCODE_MOVE_END + KEY_INSERT, // AKEYCODE_INSERT + 0, // AKEYCODE_FORWARD + 0, // AKEYCODE_MEDIA_PLAY + 0, // AKEYCODE_MEDIA_PAUSE + 0, // AKEYCODE_MEDIA_CLOSE + 0, // AKEYCODE_MEDIA_EJECT + 0, // AKEYCODE_MEDIA_RECORD + KEY_F1, // AKEYCODE_F1 + KEY_F2, // AKEYCODE_F2 + KEY_F3, // AKEYCODE_F3 + KEY_F4, // AKEYCODE_F4 + KEY_F5, // AKEYCODE_F5 + KEY_F6, // AKEYCODE_F6 + KEY_F7, // AKEYCODE_F7 + KEY_F8, // AKEYCODE_F8 + KEY_F9, // AKEYCODE_F9 + KEY_F10, // AKEYCODE_F10 + KEY_F11, // AKEYCODE_F11 + KEY_F12, // AKEYCODE_F12 + KEY_NUM_LOCK, // AKEYCODE_NUM_LOCK + KEY_KP_0, // AKEYCODE_NUMPAD_0 + KEY_KP_1, // AKEYCODE_NUMPAD_1 + KEY_KP_2, // AKEYCODE_NUMPAD_2 + KEY_KP_3, // AKEYCODE_NUMPAD_3 + KEY_KP_4, // AKEYCODE_NUMPAD_4 + KEY_KP_5, // AKEYCODE_NUMPAD_5 + KEY_KP_6, // AKEYCODE_NUMPAD_6 + KEY_KP_7, // AKEYCODE_NUMPAD_7 + KEY_KP_8, // AKEYCODE_NUMPAD_8 + KEY_KP_9, // AKEYCODE_NUMPAD_9 + KEY_KP_DIVIDE, // AKEYCODE_NUMPAD_DIVIDE + KEY_KP_MULTIPLY, // AKEYCODE_NUMPAD_MULTIPLY + KEY_KP_SUBTRACT, // AKEYCODE_NUMPAD_SUBTRACT + KEY_KP_ADD, // AKEYCODE_NUMPAD_ADD + KEY_KP_DECIMAL, // AKEYCODE_NUMPAD_DOT + 0, // AKEYCODE_NUMPAD_COMMA + KEY_KP_ENTER, // AKEYCODE_NUMPAD_ENTER + KEY_KP_EQUAL // AKEYCODE_NUMPAD_EQUALS +}; + //---------------------------------------------------------------------------------- // Module Internal Functions Declaration //---------------------------------------------------------------------------------- @@ -446,6 +615,12 @@ int SetGamepadMappings(const char *mappings) return 0; } +// Set gamepad vibration +void SetGamepadVibration(int gamepad, float leftMotor, float rightMotor) +{ + TRACELOG(LOG_WARNING, "GamepadSetVibration() not implemented on target platform"); +} + // Set mouse position XY void SetMousePosition(int x, int y) { @@ -478,6 +653,16 @@ void PollInputEvents(void) CORE.Input.Gamepad.lastButtonPressed = 0; // GAMEPAD_BUTTON_UNKNOWN //CORE.Input.Gamepad.axisCount = 0; + for (int i = 0; i < MAX_GAMEPADS; i++) + { + if (CORE.Input.Gamepad.ready[i]) // Check if gamepad is available + { + // Register previous gamepad states + for (int k = 0; k < MAX_GAMEPAD_BUTTONS; k++) + CORE.Input.Gamepad.previousButtonState[i][k] = CORE.Input.Gamepad.currentButtonState[i][k]; + } + } + // Register previous touch states for (int i = 0; i < MAX_TOUCH_POINTS; i++) CORE.Input.Touch.previousTouchState[i] = CORE.Input.Touch.currentTouchState[i]; @@ -1018,17 +1203,21 @@ static int32_t AndroidInputCallback(struct android_app *app, AInputEvent *event) return 1; // Handled gamepad button } - // Save current button and its state - // NOTE: Android key action is 0 for down and 1 for up - if (AKeyEvent_getAction(event) == AKEY_EVENT_ACTION_DOWN) + KeyboardKey key = (keycode > 0 && keycode < KEYCODE_MAP_SIZE) ? KeycodeMap[keycode] : KEY_NULL; + if (key != KEY_NULL) { - CORE.Input.Keyboard.currentKeyState[keycode] = 1; // Key down + // Save current key and its state + // NOTE: Android key action is 0 for down and 1 for up + if (AKeyEvent_getAction(event) == AKEY_EVENT_ACTION_DOWN) + { + CORE.Input.Keyboard.currentKeyState[key] = 1; // Key down - CORE.Input.Keyboard.keyPressedQueue[CORE.Input.Keyboard.keyPressedQueueCount] = keycode; - CORE.Input.Keyboard.keyPressedQueueCount++; + CORE.Input.Keyboard.keyPressedQueue[CORE.Input.Keyboard.keyPressedQueueCount] = key; + CORE.Input.Keyboard.keyPressedQueueCount++; + } + else if (AKeyEvent_getAction(event) == AKEY_EVENT_ACTION_MULTIPLE) CORE.Input.Keyboard.keyRepeatInFrame[key] = 1; + else CORE.Input.Keyboard.currentKeyState[key] = 0; // Key up } - else if (AKeyEvent_getAction(event) == AKEY_EVENT_ACTION_MULTIPLE) CORE.Input.Keyboard.keyRepeatInFrame[keycode] = 1; - else CORE.Input.Keyboard.currentKeyState[keycode] = 0; // Key up if (keycode == AKEYCODE_POWER) { diff --git a/raylib/platforms/rcore_desktop.c b/raylib/platforms/rcore_desktop.c index 05c390f..f087741 100644 --- a/raylib/platforms/rcore_desktop.c +++ b/raylib/platforms/rcore_desktop.c @@ -30,7 +30,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2013-2023 Ramon Santamaria (@raysan5) and contributors +* Copyright (c) 2013-2024 Ramon Santamaria (@raysan5) and contributors * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. @@ -74,7 +74,6 @@ //#define GLFW_EXPOSE_NATIVE_X11 // WARNING: Exposing Xlib.h > X.h results in dup symbols for Font type //#define GLFW_EXPOSE_NATIVE_WAYLAND - //#define GLFW_EXPOSE_NATIVE_MIR #include "GLFW/glfw3native.h" // Required for: glfwGetX11Window() #endif #if defined(__APPLE__) @@ -85,15 +84,6 @@ #include "GLFW/glfw3native.h" // Required for: glfwGetCocoaWindow() #endif -//---------------------------------------------------------------------------------- -// Defines and Macros -//---------------------------------------------------------------------------------- -// TODO: HACK: Added flag if not provided by GLFW when using external library -// Latest GLFW release (GLFW 3.3.8) does not implement this flag, it was added for 3.4.0-dev -#if !defined(GLFW_MOUSE_PASSTHROUGH) - #define GLFW_MOUSE_PASSTHROUGH 0x0002000D -#endif - //---------------------------------------------------------------------------------- // Types and Structures Definition //---------------------------------------------------------------------------------- @@ -123,13 +113,14 @@ static void WindowIconifyCallback(GLFWwindow *window, int iconified); static void WindowMaximizeCallback(GLFWwindow* window, int maximized); // GLFW3 Window Maximize Callback, runs when window is maximized static void WindowFocusCallback(GLFWwindow *window, int focused); // GLFW3 WindowFocus Callback, runs when window get/lose focus static void WindowDropCallback(GLFWwindow *window, int count, const char **paths); // GLFW3 Window Drop Callback, runs when drop files into window +static void WindowContentScaleCallback(GLFWwindow *window, float scalex, float scaley); // GLFW3 Window Content Scale Callback, runs when window changes scale // Input callbacks events static void KeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods); // GLFW3 Keyboard Callback, runs on key pressed -static void CharCallback(GLFWwindow *window, unsigned int key); // GLFW3 Char Key Callback, runs on key pressed (get char value) +static void CharCallback(GLFWwindow *window, unsigned int codepoint); // GLFW3 Char Callback, runs on key pressed (get codepoint value) static void MouseButtonCallback(GLFWwindow *window, int button, int action, int mods); // GLFW3 Mouse Button Callback, runs on mouse button pressed static void MouseCursorPosCallback(GLFWwindow *window, double x, double y); // GLFW3 Cursor Position Callback, runs on mouse move -static void MouseScrollCallback(GLFWwindow *window, double xoffset, double yoffset); // GLFW3 Srolling Callback, runs on mouse wheel +static void MouseScrollCallback(GLFWwindow *window, double xoffset, double yoffset); // GLFW3 Scrolling Callback, runs on mouse wheel static void CursorEnterCallback(GLFWwindow *window, int enter); // GLFW3 Cursor Enter Callback, cursor enters client area static void JoystickCallback(int jid, int event); // GLFW3 Joystick Connected/Disconnected Callback @@ -941,31 +932,8 @@ Vector2 GetWindowPosition(void) // Get window scale DPI factor for current monitor Vector2 GetWindowScaleDPI(void) { - float xdpi = 1.0; - float ydpi = 1.0; - Vector2 scale = { 1.0f, 1.0f }; - Vector2 windowPos = GetWindowPosition(); - - int monitorCount = 0; - GLFWmonitor **monitors = glfwGetMonitors(&monitorCount); - - // Check window monitor - for (int i = 0; i < monitorCount; i++) - { - glfwGetMonitorContentScale(monitors[i], &xdpi, &ydpi); - - int xpos, ypos, width, height; - glfwGetMonitorWorkarea(monitors[i], &xpos, &ypos, &width, &height); - - if ((windowPos.x >= xpos) && (windowPos.x < xpos + width) && - (windowPos.y >= ypos) && (windowPos.y < ypos + height)) - { - scale.x = xdpi; - scale.y = ydpi; - break; - } - } - + Vector2 scale = {0}; + glfwGetWindowContentScale(platform.handle, &scale.x, &scale.y); return scale; } @@ -1004,6 +972,8 @@ void EnableCursor(void) // Set cursor position in the middle SetMousePosition(CORE.Window.screen.width/2, CORE.Window.screen.height/2); + if (glfwRawMouseMotionSupported()) glfwSetInputMode(platform.handle, GLFW_RAW_MOUSE_MOTION, GLFW_FALSE); + CORE.Input.Mouse.cursorHidden = false; } @@ -1015,6 +985,8 @@ void DisableCursor(void) // Set cursor position in the middle SetMousePosition(CORE.Window.screen.width/2, CORE.Window.screen.height/2); + if (glfwRawMouseMotionSupported()) glfwSetInputMode(platform.handle, GLFW_RAW_MOUSE_MOTION, GLFW_TRUE); + CORE.Input.Mouse.cursorHidden = true; } @@ -1072,6 +1044,12 @@ int SetGamepadMappings(const char *mappings) return glfwUpdateGamepadMappings(mappings); } +// Set gamepad vibration +void SetGamepadVibration(int gamepad, float leftMotor, float rightMotor) +{ + TRACELOG(LOG_WARNING, "GamepadSetVibration() not available on target platform"); +} + // Set mouse position XY void SetMousePosition(int x, int y) { @@ -1137,7 +1115,7 @@ void PollInputEvents(void) //for (int i = 0; i < MAX_TOUCH_POINTS; i++) CORE.Input.Touch.position[i] = (Vector2){ 0, 0 }; // Map touch position to mouse position for convenience - // WARNING: If the target desktop device supports touch screen, this behavious should be reviewed! + // WARNING: If the target desktop device supports touch screen, this behaviour should be reviewed! // TODO: GLFW does not support multi-touch input just yet // https://www.codeproject.com/Articles/668404/Programming-for-Multi-Touch // https://docs.microsoft.com/en-us/windows/win32/wintouch/getting-started-with-multi-touch-messages @@ -1240,6 +1218,19 @@ void PollInputEvents(void) // Module Internal Functions Definition //---------------------------------------------------------------------------------- +static void SetDimensionsFromMonitor(GLFWmonitor *monitor) +{ + const GLFWvidmode *mode = glfwGetVideoMode(monitor); + + // Default display resolution to that of the current mode + CORE.Window.display.width = mode->width; + CORE.Window.display.height = mode->height; + + // Set screen width/height to the display width/height if they are 0 + if (CORE.Window.screen.width == 0) CORE.Window.screen.width = CORE.Window.display.width; + if (CORE.Window.screen.height == 0) CORE.Window.screen.height = CORE.Window.display.height; +} + // Initialize platform: graphics, inputs and more int InitPlatform(void) { @@ -1380,26 +1371,22 @@ int InitPlatform(void) // REF: https://github.com/raysan5/raylib/issues/1554 glfwSetJoystickCallback(NULL); - // Find monitor resolution - GLFWmonitor *monitor = glfwGetPrimaryMonitor(); - if (!monitor) - { - TRACELOG(LOG_WARNING, "GLFW: Failed to get primary monitor"); - return -1; - } - - const GLFWvidmode *mode = glfwGetVideoMode(monitor); - - CORE.Window.display.width = mode->width; - CORE.Window.display.height = mode->height; - - // Set screen width/height to the display width/height if they are 0 - if (CORE.Window.screen.width == 0) CORE.Window.screen.width = CORE.Window.display.width; - if (CORE.Window.screen.height == 0) CORE.Window.screen.height = CORE.Window.display.height; - + GLFWmonitor *monitor = NULL; if (CORE.Window.fullscreen) { - // remember center for switchinging from fullscreen to window + // According to glfwCreateWindow(), if the user does not have a choice, fullscreen applications + // should default to the primary monitor. + + monitor = glfwGetPrimaryMonitor(); + if (!monitor) + { + TRACELOG(LOG_WARNING, "GLFW: Failed to get primary monitor"); + return -1; + } + + SetDimensionsFromMonitor(monitor); + + // Remember center for switching from fullscreen to window if ((CORE.Window.screen.height == CORE.Window.display.height) && (CORE.Window.screen.width == CORE.Window.display.width)) { // If screen width/height equal to the display, we can't calculate the window pos for toggling full-screened/windowed. @@ -1418,7 +1405,7 @@ int InitPlatform(void) // Obtain recommended CORE.Window.display.width/CORE.Window.display.height from a valid videomode for the monitor int count = 0; - const GLFWvidmode *modes = glfwGetVideoModes(glfwGetPrimaryMonitor(), &count); + const GLFWvidmode *modes = glfwGetVideoModes(monitor, &count); // Get closest video mode to desired CORE.Window.screen.width/CORE.Window.screen.height for (int i = 0; i < count; i++) @@ -1448,21 +1435,55 @@ int InitPlatform(void) // HighDPI monitors are properly considered in a following similar function: SetupViewport() SetupFramebuffer(CORE.Window.display.width, CORE.Window.display.height); - platform.handle = glfwCreateWindow(CORE.Window.display.width, CORE.Window.display.height, (CORE.Window.title != 0)? CORE.Window.title : " ", glfwGetPrimaryMonitor(), NULL); + platform.handle = glfwCreateWindow(CORE.Window.display.width, CORE.Window.display.height, (CORE.Window.title != 0)? CORE.Window.title : " ", monitor, NULL); // NOTE: Full-screen change, not working properly... //glfwSetWindowMonitor(platform.handle, glfwGetPrimaryMonitor(), 0, 0, CORE.Window.screen.width, CORE.Window.screen.height, GLFW_DONT_CARE); } else { - // If we are windowed fullscreen, ensures that window does not minimize when focus is lost - if ((CORE.Window.screen.height == CORE.Window.display.height) && (CORE.Window.screen.width == CORE.Window.display.width)) + // No-fullscreen window creation + bool wantWindowedFullscreen = (CORE.Window.screen.height == 0) && (CORE.Window.screen.width == 0); + + // If we are windowed fullscreen, ensures that window does not minimize when focus is lost. + // This hinting code will not work if the user already specified the correct monitor dimensions; + // at this point we don't know the monitor's dimensions. (Though, how did the user then?) + if (wantWindowedFullscreen) { glfwWindowHint(GLFW_AUTO_ICONIFY, 0); } - // No-fullscreen window creation - platform.handle = glfwCreateWindow(CORE.Window.screen.width, CORE.Window.screen.height, (CORE.Window.title != 0)? CORE.Window.title : " ", NULL, NULL); + // Default to at least one pixel in size, as creation with a zero dimension is not allowed. + int creationWidth = CORE.Window.screen.width != 0 ? CORE.Window.screen.width : 1; + int creationHeight = CORE.Window.screen.height != 0 ? CORE.Window.screen.height : 1; + + platform.handle = glfwCreateWindow(creationWidth, creationHeight, (CORE.Window.title != 0)? CORE.Window.title : " ", NULL, NULL); + + // After the window was created, determine the monitor that the window manager assigned. + // Derive display sizes, and, if possible, window size in case it was zero at beginning. + + int monitorCount = 0; + int monitorIndex = GetCurrentMonitor(); + GLFWmonitor **monitors = glfwGetMonitors(&monitorCount); + + if (monitorIndex < monitorCount) + { + monitor = monitors[monitorIndex]; + SetDimensionsFromMonitor(monitor); + + TRACELOG(LOG_INFO, "wantWindowed: %d, size: %dx%d", wantWindowedFullscreen, CORE.Window.screen.width, CORE.Window.screen.height); + if (wantWindowedFullscreen) + { + glfwSetWindowSize(platform.handle, CORE.Window.screen.width, CORE.Window.screen.height); + } + } + else + { + // The monitor for the window-manager-created window can not be determined, so it can not be centered. + glfwTerminate(); + TRACELOG(LOG_WARNING, "GLFW: Failed to determine Monitor to center Window"); + return -1; + } if (platform.handle) { @@ -1537,7 +1558,21 @@ int InitPlatform(void) // If graphic device is no properly initialized, we end program if (!CORE.Window.ready) { TRACELOG(LOG_FATAL, "PLATFORM: Failed to initialize graphic device"); return -1; } - else SetWindowPosition(GetMonitorWidth(GetCurrentMonitor())/2 - CORE.Window.screen.width/2, GetMonitorHeight(GetCurrentMonitor())/2 - CORE.Window.screen.height/2); + else + { + // Try to center window on screen but avoiding window-bar outside of screen + int monitorX = 0; + int monitorY = 0; + int monitorWidth = 0; + int monitorHeight = 0; + glfwGetMonitorWorkarea(monitor, &monitorX, &monitorY, &monitorWidth, &monitorHeight); + + int posX = monitorX + (monitorWidth - (int)CORE.Window.screen.width)/2; + int posY = monitorY + (monitorHeight - (int)CORE.Window.screen.height)/2; + if (posX < monitorX) posX = monitorX; + if (posY < monitorY) posY = monitorY; + SetWindowPosition(posX, posY); + } // Load OpenGL extensions // NOTE: GL procedures address loader is required to load extensions @@ -1553,6 +1588,11 @@ int InitPlatform(void) glfwSetWindowFocusCallback(platform.handle, WindowFocusCallback); glfwSetDropCallback(platform.handle, WindowDropCallback); + if ((CORE.Window.flags & FLAG_WINDOW_HIGHDPI) > 0) + { + glfwSetWindowContentScaleCallback(platform.handle, WindowContentScaleCallback); + } + // Set input callback events glfwSetKeyCallback(platform.handle, KeyCallback); glfwSetCharCallback(platform.handle, CharCallback); @@ -1581,6 +1621,17 @@ int InitPlatform(void) CORE.Storage.basePath = GetWorkingDirectory(); //---------------------------------------------------------------------------- + char* glfwPlatform = ""; + switch (glfwGetPlatform()) + { + case GLFW_PLATFORM_WIN32: glfwPlatform = "Win32"; break; + case GLFW_PLATFORM_COCOA: glfwPlatform = "Cocoa"; break; + case GLFW_PLATFORM_WAYLAND: glfwPlatform = "Wayland"; break; + case GLFW_PLATFORM_X11: glfwPlatform = "X11"; break; + case GLFW_PLATFORM_NULL: glfwPlatform = "Null"; break; + } + + TRACELOG(LOG_INFO, "GLFW platform: %s", glfwPlatform); TRACELOG(LOG_INFO, "PLATFORM: DESKTOP (GLFW): Initialized successfully"); return 0; @@ -1638,6 +1689,11 @@ static void WindowSizeCallback(GLFWwindow *window, int width, int height) // NOTE: Postprocessing texture is not scaled to new size } +static void WindowContentScaleCallback(GLFWwindow *window, float scalex, float scaley) +{ + CORE.Window.screenScale = MatrixScale(scalex, scaley, 1.0f); +} + // GLFW3 WindowIconify Callback, runs when window is minimized/restored static void WindowIconifyCallback(GLFWwindow *window, int iconified) { @@ -1714,10 +1770,10 @@ static void KeyCallback(GLFWwindow *window, int key, int scancode, int action, i if ((key == CORE.Input.Keyboard.exitKey) && (action == GLFW_PRESS)) glfwSetWindowShouldClose(platform.handle, GLFW_TRUE); } -// GLFW3 Char Key Callback, runs on key down (gets equivalent unicode char value) -static void CharCallback(GLFWwindow *window, unsigned int key) +// GLFW3 Char Callback, get unicode codepoint value +static void CharCallback(GLFWwindow *window, unsigned int codepoint) { - //TRACELOG(LOG_DEBUG, "Char Callback: KEY:%i(%c)", key, key); + //TRACELOG(LOG_DEBUG, "Char Callback: Codepoint: %i", codepoint); // NOTE: Registers any key down considering OS keyboard layout but // does not detect action events, those should be managed by user... @@ -1728,7 +1784,7 @@ static void CharCallback(GLFWwindow *window, unsigned int key) if (CORE.Input.Keyboard.charPressedQueueCount < MAX_CHAR_PRESSED_QUEUE) { // Add character to the queue - CORE.Input.Keyboard.charPressedQueue[CORE.Input.Keyboard.charPressedQueueCount] = key; + CORE.Input.Keyboard.charPressedQueue[CORE.Input.Keyboard.charPressedQueueCount] = codepoint; CORE.Input.Keyboard.charPressedQueueCount++; } } @@ -1739,6 +1795,7 @@ static void MouseButtonCallback(GLFWwindow *window, int button, int action, int // WARNING: GLFW could only return GLFW_PRESS (1) or GLFW_RELEASE (0) for now, // but future releases may add more actions (i.e. GLFW_REPEAT) CORE.Input.Mouse.currentButtonState[button] = action; + CORE.Input.Touch.currentTouchState[button] = action; #if defined(SUPPORT_GESTURES_SYSTEM) && defined(SUPPORT_MOUSE_GESTURES) // Process mouse events as touches to be able to use mouse-gestures diff --git a/raylib/platforms/rcore_desktop_sdl.c b/raylib/platforms/rcore_desktop_sdl.c index 96e5570..9dfdd53 100644 --- a/raylib/platforms/rcore_desktop_sdl.c +++ b/raylib/platforms/rcore_desktop_sdl.c @@ -29,7 +29,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2013-2023 Ramon Santamaria (@raysan5) and contributors +* Copyright (c) 2013-2024 Ramon Santamaria (@raysan5) and contributors * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. @@ -48,8 +48,14 @@ * **********************************************************************************************/ -#include "SDL.h" // SDL base library (window/rendered, input, timming... functionality) -#include "SDL_opengl.h" // SDL OpenGL functionality (if required, instead of internal renderer) +#include "SDL.h" // SDL base library (window/rendered, input, timing... functionality) + +#if defined(GRAPHICS_API_OPENGL_ES2) + // It seems it does not need to be included to work + //#include "SDL_opengles2.h" +#else + #include "SDL_opengl.h" // SDL OpenGL functionality (if required, instead of internal renderer) +#endif //---------------------------------------------------------------------------------- // Types and Structures Definition @@ -58,7 +64,7 @@ typedef struct { SDL_Window *window; SDL_GLContext glContext; - SDL_Joystick *gamepad; + SDL_Joystick *gamepad[MAX_GAMEPADS]; SDL_Cursor *cursor; bool cursorRelative; } PlatformData; @@ -493,9 +499,9 @@ void SetWindowIcon(Image image) bmask = 0x001F, amask = 0; depth = 16, pitch = image.width * 2; break; - case PIXELFORMAT_UNCOMPRESSED_R8G8B8: - rmask = 0xFF0000, gmask = 0x00FF00; - bmask = 0x0000FF, amask = 0; + case PIXELFORMAT_UNCOMPRESSED_R8G8B8: // Uses BGR for 24-bit + rmask = 0x0000FF, gmask = 0x00FF00; + bmask = 0xFF0000, amask = 0; depth = 24, pitch = image.width * 3; break; case PIXELFORMAT_UNCOMPRESSED_R5G5B5A1: @@ -592,7 +598,7 @@ void SetWindowMonitor(int monitor) // NOTE: // 1. SDL started supporting moving exclusive fullscreen windows between displays on SDL3, // see commit https://github.com/libsdl-org/SDL/commit/3f5ef7dd422057edbcf3e736107e34be4b75d9ba - // 2. A workround for SDL2 is leaving fullscreen, moving the window, then entering full screen again. + // 2. A workaround for SDL2 is leaving fullscreen, moving the window, then entering full screen again. const bool wasFullscreen = ((CORE.Window.flags & FLAG_FULLSCREEN_MODE) > 0) ? true : false; const int screenWidth = CORE.Window.screen.width; @@ -611,7 +617,7 @@ void SetWindowMonitor(int monitor) // ending up positioned partly outside the target display. // 2. The workaround for that is, previously to moving the window, // setting the window size to the target display size, so they match. - // 3. It was't done here because we can't assume changing the window size automatically + // 3. It wasn't done here because we can't assume changing the window size automatically // is acceptable behavior by the user. SDL_SetWindowPosition(platform.window, usableBounds.x, usableBounds.y); CORE.Window.position.x = usableBounds.x; @@ -932,9 +938,26 @@ int SetGamepadMappings(const char *mappings) return SDL_GameControllerAddMapping(mappings); } +// Set gamepad vibration +void SetGamepadVibration(int gamepad, float leftMotor, float rightMotor) +{ + //Limit input values to between 0.0f and 1.0f + leftMotor = (0.0f > leftMotor) ? 0.0f : leftMotor; + rightMotor = (0.0f > rightMotor) ? 0.0f : rightMotor; + leftMotor = (1.0f < leftMotor) ? 1.0f : leftMotor; + rightMotor = (1.0f < rightMotor) ? 1.0f : rightMotor; + + if (IsGamepadAvailable(gamepad)) + { + SDL_JoystickRumble(platform.gamepad[gamepad], (Uint16)(leftMotor*65535.0f), (Uint16)(rightMotor*65535.0f), (Uint32)(MAX_GAMEPAD_VIBRATION_TIME*1000.0f)); + } +} + // Set mouse position XY void SetMousePosition(int x, int y) { + SDL_WarpMouseInWindow(platform.window, x, y); + CORE.Input.Mouse.currentPosition = (Vector2){ (float)x, (float)y }; CORE.Input.Mouse.previousPosition = CORE.Input.Mouse.currentPosition; } @@ -948,6 +971,22 @@ void SetMouseCursor(int cursor) CORE.Input.Mouse.cursor = cursor; } +static void UpdateTouchPointsSDL(SDL_TouchFingerEvent event) +{ + CORE.Input.Touch.pointCount = SDL_GetNumTouchFingers(event.touchId); + + for (int i = 0; i < CORE.Input.Touch.pointCount; i++) + { + SDL_Finger *finger = SDL_GetTouchFinger(event.touchId, i); + CORE.Input.Touch.pointId[i] = finger->id; + CORE.Input.Touch.position[i].x = finger->x*CORE.Window.screen.width; + CORE.Input.Touch.position[i].y = finger->y*CORE.Window.screen.height; + CORE.Input.Touch.currentTouchState[i] = 1; + } + + for (int i = CORE.Input.Touch.pointCount; i < MAX_TOUCH_POINTS; i++) CORE.Input.Touch.currentTouchState[i] = 0; +} + // Register all input events void PollInputEvents(void) { @@ -961,9 +1000,6 @@ void PollInputEvents(void) CORE.Input.Keyboard.keyPressedQueueCount = 0; CORE.Input.Keyboard.charPressedQueueCount = 0; - // Reset key repeats - for (int i = 0; i < MAX_KEYBOARD_KEYS; i++) CORE.Input.Keyboard.keyRepeatInFrame[i] = 0; - // Reset mouse wheel CORE.Input.Mouse.currentWheelMove.x = 0; CORE.Input.Mouse.currentWheelMove.y = 0; @@ -973,25 +1009,27 @@ void PollInputEvents(void) else CORE.Input.Mouse.previousPosition = CORE.Input.Mouse.currentPosition; // Reset last gamepad button/axis registered state - CORE.Input.Gamepad.lastButtonPressed = GAMEPAD_BUTTON_UNKNOWN; - for (int i = 0; i < MAX_GAMEPADS; i++) CORE.Input.Gamepad.axisCount[i] = 0; + for (int i = 0; (i < SDL_NumJoysticks()) && (i < MAX_GAMEPADS); i++) + { + // Check if gamepad is available + if (CORE.Input.Gamepad.ready[i]) + { + // Register previous gamepad button states + for (int k = 0; k < MAX_GAMEPAD_BUTTONS; k++) + { + CORE.Input.Gamepad.previousButtonState[i][k] = CORE.Input.Gamepad.currentButtonState[i][k]; + } + } + } // Register previous touch states for (int i = 0; i < MAX_TOUCH_POINTS; i++) CORE.Input.Touch.previousTouchState[i] = CORE.Input.Touch.currentTouchState[i]; - // Reset touch positions - // TODO: It resets on target platform the mouse position and not filled again until a move-event, - // so, if mouse is not moved it returns a (0, 0) position... this behaviour should be reviewed! - //for (int i = 0; i < MAX_TOUCH_POINTS; i++) CORE.Input.Touch.position[i] = (Vector2){ 0, 0 }; - // Map touch position to mouse position for convenience - // WARNING: If the target desktop device supports touch screen, this behavious should be reviewed! - // https://www.codeproject.com/Articles/668404/Programming-for-Multi-Touch - // https://docs.microsoft.com/en-us/windows/win32/wintouch/getting-started-with-multi-touch-messages CORE.Input.Touch.position[0] = CORE.Input.Mouse.currentPosition; int touchAction = -1; // 0-TOUCH_ACTION_UP, 1-TOUCH_ACTION_DOWN, 2-TOUCH_ACTION_MOVE - bool gestureUpdate = false; // Flag to note gestures require to update + bool realTouch = false; // Flag to differentiate real touch gestures from mouse ones // Register previous keys states // NOTE: Android supports up to 260 keys @@ -1004,7 +1042,7 @@ void PollInputEvents(void) // Register previous mouse states for (int i = 0; i < MAX_MOUSE_BUTTONS; i++) CORE.Input.Mouse.previousButtonState[i] = CORE.Input.Mouse.currentButtonState[i]; - // Poll input events for current plaform + // Poll input events for current platform //----------------------------------------------------------------------------- /* // WARNING: Indexes into this array are obtained by using SDL_Scancode values, not SDL_Keycode values @@ -1070,11 +1108,17 @@ void PollInputEvents(void) CORE.Window.currentFbo.height = height; CORE.Window.resizedLastFrame = true; } break; + case SDL_WINDOWEVENT_ENTER: + { + CORE.Input.Mouse.cursorOnScreen = true; + } break; case SDL_WINDOWEVENT_LEAVE: + { + CORE.Input.Mouse.cursorOnScreen = false; + } break; case SDL_WINDOWEVENT_HIDDEN: case SDL_WINDOWEVENT_MINIMIZED: case SDL_WINDOWEVENT_FOCUS_LOST: - case SDL_WINDOWEVENT_ENTER: case SDL_WINDOWEVENT_SHOWN: case SDL_WINDOWEVENT_FOCUS_GAINED: case SDL_WINDOWEVENT_MAXIMIZED: @@ -1087,7 +1131,19 @@ void PollInputEvents(void) case SDL_KEYDOWN: { KeyboardKey key = ConvertScancodeToKey(event.key.keysym.scancode); - if (key != KEY_NULL) CORE.Input.Keyboard.currentKeyState[key] = 1; + + if (key != KEY_NULL) { + // If key was up, add it to the key pressed queue + if ((CORE.Input.Keyboard.currentKeyState[key] == 0) && (CORE.Input.Keyboard.keyPressedQueueCount < MAX_KEY_PRESSED_QUEUE)) + { + CORE.Input.Keyboard.keyPressedQueue[CORE.Input.Keyboard.keyPressedQueueCount] = key; + CORE.Input.Keyboard.keyPressedQueueCount++; + } + + CORE.Input.Keyboard.currentKeyState[key] = 1; + } + + if (event.key.repeat) CORE.Input.Keyboard.keyRepeatInFrame[key] = 1; // TODO: Put exitKey verification outside the switch? if (CORE.Input.Keyboard.currentKeyState[CORE.Input.Keyboard.exitKey]) @@ -1102,6 +1158,21 @@ void PollInputEvents(void) if (key != KEY_NULL) CORE.Input.Keyboard.currentKeyState[key] = 0; } break; + case SDL_TEXTINPUT: + { + // NOTE: event.text.text data comes an UTF-8 text sequence but we register codepoints (int) + + int codepointSize = 0; + + // Check if there is space available in the queue + if (CORE.Input.Keyboard.charPressedQueueCount < MAX_CHAR_PRESSED_QUEUE) + { + // Add character (codepoint) to the queue + CORE.Input.Keyboard.charPressedQueue[CORE.Input.Keyboard.charPressedQueueCount] = GetCodepointNext(event.text.text, &codepointSize); + CORE.Input.Keyboard.charPressedQueueCount++; + } + } break; + // Check mouse events case SDL_MOUSEBUTTONDOWN: { @@ -1112,9 +1183,9 @@ void PollInputEvents(void) else if (btn == 1) btn = 2; CORE.Input.Mouse.currentButtonState[btn] = 1; + CORE.Input.Touch.currentTouchState[btn] = 1; touchAction = 1; - gestureUpdate = true; } break; case SDL_MOUSEBUTTONUP: { @@ -1125,9 +1196,9 @@ void PollInputEvents(void) else if (btn == 1) btn = 2; CORE.Input.Mouse.currentButtonState[btn] = 0; + CORE.Input.Touch.currentTouchState[btn] = 0; touchAction = 0; - gestureUpdate = true; } break; case SDL_MOUSEWHEEL: { @@ -1150,24 +1221,160 @@ void PollInputEvents(void) CORE.Input.Touch.position[0] = CORE.Input.Mouse.currentPosition; touchAction = 2; - gestureUpdate = true; + } break; + + case SDL_FINGERDOWN: + { + UpdateTouchPointsSDL(event.tfinger); + touchAction = 1; + realTouch = true; + } break; + case SDL_FINGERUP: + { + UpdateTouchPointsSDL(event.tfinger); + touchAction = 0; + realTouch = true; + } break; + case SDL_FINGERMOTION: + { + UpdateTouchPointsSDL(event.tfinger); + touchAction = 2; + realTouch = true; } break; // Check gamepad events + case SDL_JOYDEVICEADDED: + { + int jid = event.jdevice.which; + + if (!CORE.Input.Gamepad.ready[jid] && (jid < MAX_GAMEPADS)) + { + platform.gamepad[jid] = SDL_JoystickOpen(jid); + + if (platform.gamepad[jid]) + { + CORE.Input.Gamepad.ready[jid] = true; + CORE.Input.Gamepad.axisCount[jid] = SDL_JoystickNumAxes(platform.gamepad[jid]); + CORE.Input.Gamepad.axisState[jid][GAMEPAD_AXIS_LEFT_TRIGGER] = -1.0f; + CORE.Input.Gamepad.axisState[jid][GAMEPAD_AXIS_RIGHT_TRIGGER] = -1.0f; + strncpy(CORE.Input.Gamepad.name[jid], SDL_JoystickName(platform.gamepad[jid]), 63); + CORE.Input.Gamepad.name[jid][63] = '\0'; + } + else + { + TRACELOG(LOG_WARNING, "PLATFORM: Unable to open game controller [ERROR: %s]", SDL_GetError()); + } + } + } break; + case SDL_JOYDEVICEREMOVED: + { + int jid = event.jdevice.which; + + if (jid == SDL_JoystickInstanceID(platform.gamepad[jid])) + { + SDL_JoystickClose(platform.gamepad[jid]); + platform.gamepad[jid] = SDL_JoystickOpen(0); + CORE.Input.Gamepad.ready[jid] = false; + memset(CORE.Input.Gamepad.name[jid], 0, 64); + } + } break; + case SDL_JOYBUTTONDOWN: + { + int button = -1; + + switch (event.jbutton.button) + { + case SDL_CONTROLLER_BUTTON_Y: button = GAMEPAD_BUTTON_RIGHT_FACE_UP; break; + case SDL_CONTROLLER_BUTTON_B: button = GAMEPAD_BUTTON_RIGHT_FACE_RIGHT; break; + case SDL_CONTROLLER_BUTTON_A: button = GAMEPAD_BUTTON_RIGHT_FACE_DOWN; break; + case SDL_CONTROLLER_BUTTON_X: button = GAMEPAD_BUTTON_RIGHT_FACE_LEFT; break; + + case SDL_CONTROLLER_BUTTON_LEFTSHOULDER: button = GAMEPAD_BUTTON_LEFT_TRIGGER_1; break; + case SDL_CONTROLLER_BUTTON_RIGHTSHOULDER: button = GAMEPAD_BUTTON_RIGHT_TRIGGER_1; break; + + case SDL_CONTROLLER_BUTTON_BACK: button = GAMEPAD_BUTTON_MIDDLE_LEFT; break; + case SDL_CONTROLLER_BUTTON_GUIDE: button = GAMEPAD_BUTTON_MIDDLE; break; + case SDL_CONTROLLER_BUTTON_START: button = GAMEPAD_BUTTON_MIDDLE_RIGHT; break; + + case SDL_CONTROLLER_BUTTON_DPAD_UP: button = GAMEPAD_BUTTON_LEFT_FACE_UP; break; + case SDL_CONTROLLER_BUTTON_DPAD_RIGHT: button = GAMEPAD_BUTTON_LEFT_FACE_RIGHT; break; + case SDL_CONTROLLER_BUTTON_DPAD_DOWN: button = GAMEPAD_BUTTON_LEFT_FACE_DOWN; break; + case SDL_CONTROLLER_BUTTON_DPAD_LEFT: button = GAMEPAD_BUTTON_LEFT_FACE_LEFT; break; + + case SDL_CONTROLLER_BUTTON_LEFTSTICK: button = GAMEPAD_BUTTON_LEFT_THUMB; break; + case SDL_CONTROLLER_BUTTON_RIGHTSTICK: button = GAMEPAD_BUTTON_RIGHT_THUMB; break; + default: break; + } + + if (button >= 0) + { + CORE.Input.Gamepad.currentButtonState[event.jbutton.which][button] = 1; + CORE.Input.Gamepad.lastButtonPressed = button; + } + } break; + case SDL_JOYBUTTONUP: + { + int button = -1; + + switch (event.jbutton.button) + { + case SDL_CONTROLLER_BUTTON_Y: button = GAMEPAD_BUTTON_RIGHT_FACE_UP; break; + case SDL_CONTROLLER_BUTTON_B: button = GAMEPAD_BUTTON_RIGHT_FACE_RIGHT; break; + case SDL_CONTROLLER_BUTTON_A: button = GAMEPAD_BUTTON_RIGHT_FACE_DOWN; break; + case SDL_CONTROLLER_BUTTON_X: button = GAMEPAD_BUTTON_RIGHT_FACE_LEFT; break; + + case SDL_CONTROLLER_BUTTON_LEFTSHOULDER: button = GAMEPAD_BUTTON_LEFT_TRIGGER_1; break; + case SDL_CONTROLLER_BUTTON_RIGHTSHOULDER: button = GAMEPAD_BUTTON_RIGHT_TRIGGER_1; break; + + case SDL_CONTROLLER_BUTTON_BACK: button = GAMEPAD_BUTTON_MIDDLE_LEFT; break; + case SDL_CONTROLLER_BUTTON_GUIDE: button = GAMEPAD_BUTTON_MIDDLE; break; + case SDL_CONTROLLER_BUTTON_START: button = GAMEPAD_BUTTON_MIDDLE_RIGHT; break; + + case SDL_CONTROLLER_BUTTON_DPAD_UP: button = GAMEPAD_BUTTON_LEFT_FACE_UP; break; + case SDL_CONTROLLER_BUTTON_DPAD_RIGHT: button = GAMEPAD_BUTTON_LEFT_FACE_RIGHT; break; + case SDL_CONTROLLER_BUTTON_DPAD_DOWN: button = GAMEPAD_BUTTON_LEFT_FACE_DOWN; break; + case SDL_CONTROLLER_BUTTON_DPAD_LEFT: button = GAMEPAD_BUTTON_LEFT_FACE_LEFT; break; + + case SDL_CONTROLLER_BUTTON_LEFTSTICK: button = GAMEPAD_BUTTON_LEFT_THUMB; break; + case SDL_CONTROLLER_BUTTON_RIGHTSTICK: button = GAMEPAD_BUTTON_RIGHT_THUMB; break; + default: break; + } + + if (button >= 0) + { + CORE.Input.Gamepad.currentButtonState[event.jbutton.which][button] = 0; + if (CORE.Input.Gamepad.lastButtonPressed == button) CORE.Input.Gamepad.lastButtonPressed = 0; + } + } break; case SDL_JOYAXISMOTION: { - // Motion on gamepad 0 - if (event.jaxis.which == 0) + int axis = -1; + + switch (event.jaxis.axis) { - // X axis motion - if (event.jaxis.axis == 0) + case SDL_CONTROLLER_AXIS_LEFTX: axis = GAMEPAD_AXIS_LEFT_X; break; + case SDL_CONTROLLER_AXIS_LEFTY: axis = GAMEPAD_AXIS_LEFT_Y; break; + case SDL_CONTROLLER_AXIS_RIGHTX: axis = GAMEPAD_AXIS_RIGHT_X; break; + case SDL_CONTROLLER_AXIS_RIGHTY: axis = GAMEPAD_AXIS_RIGHT_Y; break; + case SDL_CONTROLLER_AXIS_TRIGGERLEFT: axis = GAMEPAD_AXIS_LEFT_TRIGGER; break; + case SDL_CONTROLLER_AXIS_TRIGGERRIGHT: axis = GAMEPAD_AXIS_RIGHT_TRIGGER; break; + default: break; + } + + if (axis >= 0) + { + // SDL axis value range is -32768 to 32767, we normalize it to RayLib's -1.0 to 1.0f range + float value = event.jaxis.value / (float) 32767; + CORE.Input.Gamepad.axisState[event.jaxis.which][axis] = value; + + // Register button state for triggers in addition to their axes + if ((axis == GAMEPAD_AXIS_LEFT_TRIGGER) || (axis == GAMEPAD_AXIS_RIGHT_TRIGGER)) { - //... - } - // Y axis motion - else if (event.jaxis.axis == 1) - { - //... + int button = (axis == GAMEPAD_AXIS_LEFT_TRIGGER) ? GAMEPAD_BUTTON_LEFT_TRIGGER_2 : GAMEPAD_BUTTON_RIGHT_TRIGGER_2; + int pressed = (value > 0.1f); + CORE.Input.Gamepad.currentButtonState[event.jaxis.which][button] = pressed; + if (pressed) CORE.Input.Gamepad.lastButtonPressed = button; + else if (CORE.Input.Gamepad.lastButtonPressed == button) CORE.Input.Gamepad.lastButtonPressed = 0; } } } break; @@ -1175,7 +1382,7 @@ void PollInputEvents(void) } #if defined(SUPPORT_GESTURES_SYSTEM) - if (gestureUpdate) + if (touchAction > -1) { // Process mouse events as touches to be able to use mouse-gestures GestureEvent gestureEvent = { 0 }; @@ -1190,7 +1397,7 @@ void PollInputEvents(void) gestureEvent.pointCount = 1; // Register touch points position, only one point registered - if (touchAction == 2) gestureEvent.position[0] = CORE.Input.Touch.position[0]; + if (touchAction == 2 || realTouch) gestureEvent.position[0] = CORE.Input.Touch.position[0]; else gestureEvent.position[0] = GetMousePosition(); // Normalize gestureEvent.position[0] for CORE.Window.screen.width and CORE.Window.screen.height @@ -1199,6 +1406,8 @@ void PollInputEvents(void) // Gesture data is sent to gestures-system for processing ProcessGestureEvent(gestureEvent); + + touchAction = -1; } #endif } @@ -1212,8 +1421,9 @@ void PollInputEvents(void) // Initialize platform: graphics, inputs and more int InitPlatform(void) { - // Initialize SDL internal global state - int result = SDL_Init(SDL_INIT_EVERYTHING); + // Initialize SDL internal global state, only required systems + // NOTE: Not all systems need to be initialized, SDL_INIT_AUDIO is not required, managed by miniaudio + int result = SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_EVENTS | SDL_INIT_GAMECONTROLLER); if (result < 0) { TRACELOG(LOG_WARNING, "SDL: Failed to initialize SDL"); return -1; } // Initialize graphic device: display/window and graphic context @@ -1265,11 +1475,7 @@ int InitPlatform(void) { SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); -#if defined(__APPLE__) - SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG); // OSX Requires forward compatibility -#else SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); -#endif } else if (rlGetVersion() == RL_OPENGL_43) { @@ -1310,7 +1516,7 @@ int InitPlatform(void) // Init OpenGL context platform.glContext = SDL_GL_CreateContext(platform.window); - // Check window and glContext have been initialized succesfully + // Check window and glContext have been initialized successfully if ((platform.window != NULL) && (platform.glContext != NULL)) { CORE.Window.ready = true; @@ -1345,19 +1551,38 @@ int InitPlatform(void) // Initialize input events system //---------------------------------------------------------------------------- - if (SDL_NumJoysticks() >= 1) + // Initialize gamepads + for (int i = 0; (i < SDL_NumJoysticks()) && (i < MAX_GAMEPADS); i++) { - platform.gamepad = SDL_JoystickOpen(0); - //if (platform.gamepadgamepad == NULL) TRACELOG(LOG_WARNING, "PLATFORM: Unable to open game controller [ERROR: %s]", SDL_GetError()); + platform.gamepad[i] = SDL_JoystickOpen(i); + if (platform.gamepad[i]) + { + CORE.Input.Gamepad.ready[i] = true; + CORE.Input.Gamepad.axisCount[i] = SDL_JoystickNumAxes(platform.gamepad[i]); + CORE.Input.Gamepad.axisState[i][GAMEPAD_AXIS_LEFT_TRIGGER] = -1.0f; + CORE.Input.Gamepad.axisState[i][GAMEPAD_AXIS_RIGHT_TRIGGER] = -1.0f; + strncpy(CORE.Input.Gamepad.name[i], SDL_JoystickName(platform.gamepad[i]), 63); + CORE.Input.Gamepad.name[i][63] = '\0'; + } + else TRACELOG(LOG_WARNING, "PLATFORM: Unable to open game controller [ERROR: %s]", SDL_GetError()); } + // Disable mouse events being interpreted as touch events + // NOTE: This is wanted because there are SDL_FINGER* events available which provide unique data + // Due to the way PollInputEvents() and rgestures.h are currently implemented, setting this won't break SUPPORT_MOUSE_GESTURES + SDL_SetHint(SDL_HINT_TOUCH_MOUSE_EVENTS, "0"); + SDL_EventState(SDL_DROPFILE, SDL_ENABLE); //---------------------------------------------------------------------------- - // Initialize timming system + // Initialize timing system //---------------------------------------------------------------------------- // NOTE: No need to call InitTimer(), let SDL manage it internally CORE.Time.previous = GetTime(); // Get time as double + + #if defined(_WIN32) && defined(SUPPORT_WINMM_HIGHRES_TIMER) && !defined(SUPPORT_BUSY_WAIT_LOOP) + SDL_SetHint(SDL_HINT_TIMER_RESOLUTION, "1"); // SDL equivalent of timeBeginPeriod() and timeEndPeriod() + #endif //---------------------------------------------------------------------------- // Initialize storage system diff --git a/raylib/platforms/rcore_drm.c b/raylib/platforms/rcore_drm.c index bdfc9e0..ba60714 100644 --- a/raylib/platforms/rcore_drm.c +++ b/raylib/platforms/rcore_drm.c @@ -29,7 +29,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2013-2023 Ramon Santamaria (@raysan5) and contributors +* Copyright (c) 2013-2024 Ramon Santamaria (@raysan5) and contributors * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. @@ -59,39 +59,37 @@ #include // Linux: Keycodes constants definition (KEY_A, ...) #include // Linux: Joystick support library -#include // Generic Buffer Management (native platform for EGL on DRM) -#include // Direct Rendering Manager user-level library interface -#include // Direct Rendering Manager mode setting (KMS) interface +// WARNING: Both 'linux/input.h' and 'raylib.h' define KEY_F12 +// To avoid conflict with the capturing code in rcore.c we undefine the macro KEY_F12, +// so the enum KEY_F12 from raylib is used +#undef KEY_F12 -#include "EGL/egl.h" // Native platform windowing system interface -#include "EGL/eglext.h" // EGL extensions +#include // Generic Buffer Management (native platform for EGL on DRM) +#include // Direct Rendering Manager user-level library interface +#include // Direct Rendering Manager mode setting (KMS) interface + +#include "EGL/egl.h" // Native platform windowing system interface +#include "EGL/eglext.h" // EGL extensions + +#ifndef EGL_OPENGL_ES3_BIT + #define EGL_OPENGL_ES3_BIT 0x40 +#endif //---------------------------------------------------------------------------------- // Defines and Macros //---------------------------------------------------------------------------------- #define USE_LAST_TOUCH_DEVICE // When multiple touchscreens are connected, only use the one with the highest event number -#define DEFAULT_GAMEPAD_DEV "/dev/input/js" // Gamepad input (base dev for all gamepads: js0, js1, ...) #define DEFAULT_EVDEV_PATH "/dev/input/" // Path to the linux input events +// So actually the biggest key is KEY_CNT but we only really map the keys up to +// KEY_ALS_TOGGLE +#define KEYMAP_SIZE KEY_ALS_TOGGLE + //---------------------------------------------------------------------------------- // Types and Structures Definition //---------------------------------------------------------------------------------- -typedef struct { - pthread_t threadId; // Event reading thread id - - int fd; // File descriptor to the device it is assigned to - int eventNum; // Number of 'event' device - Rectangle absRange; // Range of values for absolute pointing devices (touchscreens) - int touchSlot; // Hold the touch slot number of the currently being sent multitouch block - bool isMouse; // True if device supports relative X Y movements - bool isTouch; // True if device supports absolute X Y movements and has BTN_TOUCH - bool isMultitouch; // True if device supports multiple absolute movevents and has BTN_TOUCH - bool isKeyboard; // True if device has letter keycodes - bool isGamepad; // True if device has gamepad buttons -} InputEventWorker; - typedef struct { // Display data int fd; // File descriptor for /dev/dri/... @@ -108,9 +106,6 @@ typedef struct { EGLContext context; // Graphic context, mode in which drawing can be done EGLConfig config; // Graphic config - // Input data - InputEventWorker eventWorker[10]; // List of worker threads for every monitored "/dev/input/event" - // Keyboard data int defaultKeyboardMode; // Default keyboard mode bool eventKeyboardMode; // Keyboard in event mode @@ -128,9 +123,10 @@ typedef struct { int touchSlot; // Hold the touch slot number of the currently being sent multitouch block // Gamepad data - pthread_t gamepadThreadId; // Gamepad reading thread id int gamepadStreamFd[MAX_GAMEPADS]; // Gamepad device file descriptor - + int gamepadAbsAxisRange[MAX_GAMEPADS][MAX_GAMEPAD_AXIS][2]; // [0] = min, [1] = range value of the axis + int gamepadAbsAxisMap[MAX_GAMEPADS][ABS_CNT]; // Maps the axes gamepads from the evdev api to a sequential one + int gamepadCount; // The number of gamepads registered } PlatformData; //---------------------------------------------------------------------------------- @@ -143,55 +139,98 @@ static PlatformData platform = { 0 }; // Platform specific data //---------------------------------------------------------------------------------- // Local Variables Definition //---------------------------------------------------------------------------------- -// Scancode to keycode mapping for US keyboards -// TODO: Replace this with a keymap from the X11 to get the correct regional map for the keyboard: -// Currently non US keyboards will have the wrong mapping for some keys -static const int keymapUS[] = { - 0, 256, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 45, 61, 259, 258, 81, 87, 69, 82, 84, - 89, 85, 73, 79, 80, 91, 93, 257, 341, 65, 83, 68, 70, 71, 72, 74, 75, 76, 59, 39, 96, - 340, 92, 90, 88, 67, 86, 66, 78, 77, 44, 46, 47, 344, 332, 342, 32, 280, 290, 291, - 292, 293, 294, 295, 296, 297, 298, 299, 282, 281, 327, 328, 329, 333, 324, 325, - 326, 334, 321, 322, 323, 320, 330, 0, 85, 86, 300, 301, 89, 90, 91, 92, 93, 94, 95, - 335, 345, 331, 283, 346, 101, 268, 265, 266, 263, 262, 269, 264, 267, 260, 261, - 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 347, 127, - 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, - 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, - 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, - 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, - 192, 193, 194, 0, 0, 0, 0, 0, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, - 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, - 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, - 243, 244, 245, 246, 247, 248, 0, 0, 0, 0, 0, 0, 0 -}; // NOTE: The complete evdev EV_KEY list can be found at /usr/include/linux/input-event-codes.h // TODO: Complete the LUT with all unicode decimal values -static const int EvkeyToUnicodeLUT[] = { +// TODO: Replace this with a keymap from the X11 to get the correct regional map for the keyboard: +// Currently non US keyboards will have the wrong mapping for some keys +// NOTE: Replacing this with the keymap from X11 would probably be useless, as people use the drm +// backend to *avoid* X11 +static const int evkeyToUnicodeLUT[] = { 0, 27, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 45, 61, 8, 0, 113, 119, 101, 114, 116, 121, 117, 105, 111, 112, 0, 0, 13, 0, 97, 115, 100, 102, 103, 104, 106, 107, 108, 59, 39, 96, 0, 92, 122, 120, 99, 118, 98, 110, 109, 44, 46, 47, 0, 0, 0, 32 // LUT currently incomplete, just mapped the most essential keys }; +// This is the map used to map any keycode returned from linux to a raylib code from 'raylib.h' +// NOTE: Use short here to save a little memory +static const short linuxToRaylibMap[KEYMAP_SIZE] = { + // We don't map those with designated initialization, because we would getting + // into loads of naming conflicts + 0, 256, 49, 50, 51, 52, 53, 54, + 55, 56, 57, 48, 45, 61, 259, 258, + 81, 87, 69, 82, 84, 89, 85, 73, + 79, 80, 91, 93, 257, 341, 65, 83, + 68, 70, 71, 72, 74, 75, 76, 59, + 39, 96, 340, 92, 90, 88, 67, 86, + 66, 78, 77, 44, 46, 47, 344, 332, + 342, 32, 280, 290, 291, 292, 293, 294, + 295, 296, 297, 298, 299, 282, 281, 327, + 328, 329, 333, 324, 325, 326, 334, 321, + 322, 323, 320, 330, 0, 85, 86, 300, + 301, 89, 90, 91, 92, 93, 94, 95, + 335, 345, 331, 283, 346, 101, 268, 265, + 266, 263, 262, 269, 264, 267, 260, 261, + 112, 113, 114, 115, 116, 117, 118, 119, + 120, 121, 122, 123, 124, 125, 347, 127, + 128, 129, 130, 131, 132, 133, 134, 135, + 136, 137, 138, 139, 140, 141, 142, 143, + 144, 145, 146, 147, 148, 149, 150, 151, + 152, 153, 154, 155, 156, 157, 158, 159, + 160, 161, 162, 163, 164, 165, 166, 167, + 168, 169, 170, 171, 172, 173, 174, 175, + 176, 177, 178, 179, 180, 181, 182, 183, + 184, 185, 186, 187, 188, 189, 190, 191, + 192, 193, 194, 0, 0, 0, 0, 0, + 200, 201, 202, 203, 204, 205, 206, 207, + 208, 209, 210, 211, 212, 213, 214, 215, + 216, 217, 218, 219, 220, 221, 222, 223, + 224, 225, 226, 227, 228, 229, 230, 231, + 232, 233, 234, 235, 236, 237, 238, 239, + 240, 241, 242, 243, 244, 245, 246, 247, + 248, 0, 0, 0, 0, 0, 0, 0, + + // Gamepads are mapped according to: + // https://www.kernel.org/doc/html/next/input/gamepad.html + // Those mappings are standardized, but that doesn't mean people follow + // the standards, so this is more of an approximation + [BTN_DPAD_UP] = GAMEPAD_BUTTON_LEFT_FACE_UP, + [BTN_DPAD_RIGHT] = GAMEPAD_BUTTON_LEFT_FACE_RIGHT, + [BTN_DPAD_DOWN] = GAMEPAD_BUTTON_LEFT_FACE_DOWN, + [BTN_DPAD_LEFT] = GAMEPAD_BUTTON_LEFT_FACE_LEFT, + [BTN_Y] = GAMEPAD_BUTTON_RIGHT_FACE_UP, + [BTN_B] = GAMEPAD_BUTTON_RIGHT_FACE_RIGHT, + [BTN_A] = GAMEPAD_BUTTON_RIGHT_FACE_DOWN, + [BTN_X] = GAMEPAD_BUTTON_RIGHT_FACE_LEFT, + [BTN_TL] = GAMEPAD_BUTTON_LEFT_TRIGGER_1, + [BTN_TL2] = GAMEPAD_BUTTON_LEFT_TRIGGER_2, + [BTN_TR] = GAMEPAD_BUTTON_RIGHT_TRIGGER_1, + [BTN_TR2] GAMEPAD_BUTTON_RIGHT_TRIGGER_2, + [BTN_SELECT] = GAMEPAD_BUTTON_MIDDLE_LEFT, + [BTN_MODE] = GAMEPAD_BUTTON_MIDDLE, + [BTN_START] = GAMEPAD_BUTTON_MIDDLE_RIGHT, + [BTN_THUMBL] = GAMEPAD_BUTTON_LEFT_THUMB, + [BTN_THUMBR] = GAMEPAD_BUTTON_RIGHT_THUMB, +}; + //---------------------------------------------------------------------------------- // Module Internal Functions Declaration //---------------------------------------------------------------------------------- int InitPlatform(void); // Initialize platform (graphics, inputs and more) void ClosePlatform(void); // Close platform +#if defined(SUPPORT_SSH_KEYBOARD_RPI) static void InitKeyboard(void); // Initialize raw keyboard system static void RestoreKeyboard(void); // Restore keyboard system -#if defined(SUPPORT_SSH_KEYBOARD_RPI) static void ProcessKeyboard(void); // Process keyboard events #endif static void InitEvdevInput(void); // Initialize evdev inputs static void ConfigureEvdevDevice(char *device); // Identifies a input device and configures it for use if appropriate static void PollKeyboardEvents(void); // Process evdev keyboard events -static void *EventThread(void *arg); // Input device events reading thread - -static void InitGamepad(void); // Initialize raw gamepad input -static void *GamepadThread(void *arg); // Mouse reading thread +static void PollGamepadEvents(void); // Process evdev gamepad events +static void PollMouseEvents(void); // Process evdev mouse events static int FindMatchingConnectorMode(const drmModeConnector *connector, const drmModeModeInfo *mode); // Search matching DRM mode in connector's mode list static int FindExactConnectorMode(const drmModeConnector *connector, uint width, uint height, uint fps, bool allowInterlaced); // Search exactly matching DRM connector mode in connector's list @@ -349,29 +388,69 @@ Vector2 GetMonitorPosition(int monitor) // Get selected monitor width (currently used by monitor) int GetMonitorWidth(int monitor) { - TRACELOG(LOG_WARNING, "GetMonitorWidth() not implemented on target platform"); - return 0; + int width = 0; + + if (monitor != 0) + { + TRACELOG(LOG_WARNING, "GetMonitorWidth() implemented for first monitor only"); + } + else if ((platform.connector) && (platform.modeIndex >= 0)) + { + width = platform.connector->modes[platform.modeIndex].hdisplay; + } + + return width; } // Get selected monitor height (currently used by monitor) int GetMonitorHeight(int monitor) { - TRACELOG(LOG_WARNING, "GetMonitorHeight() not implemented on target platform"); - return 0; + int height = 0; + + if (monitor != 0) + { + TRACELOG(LOG_WARNING, "GetMonitorHeight() implemented for first monitor only"); + } + else if ((platform.connector) && (platform.modeIndex >= 0)) + { + height = platform.connector->modes[platform.modeIndex].vdisplay; + } + + return height; } // Get selected monitor physical width in millimetres int GetMonitorPhysicalWidth(int monitor) { - TRACELOG(LOG_WARNING, "GetMonitorPhysicalWidth() not implemented on target platform"); - return 0; + int physicalWidth = 0; + + if (monitor != 0) + { + TRACELOG(LOG_WARNING, "GetMonitorPhysicalWidth() implemented for first monitor only"); + } + else if ((platform.connector) && (platform.modeIndex >= 0)) + { + physicalWidth = platform.connector->mmWidth; + } + + return physicalWidth; } // Get selected monitor physical height in millimetres int GetMonitorPhysicalHeight(int monitor) { - TRACELOG(LOG_WARNING, "GetMonitorPhysicalHeight() not implemented on target platform"); - return 0; + int physicalHeight = 0; + + if (monitor != 0) + { + TRACELOG(LOG_WARNING, "GetMonitorPhysicalHeight() implemented for first monitor only"); + } + else if ((platform.connector) && (platform.modeIndex >= 0)) + { + physicalHeight = platform.connector->mmHeight; + } + + return physicalHeight; } // Get selected monitor refresh rate @@ -390,8 +469,18 @@ int GetMonitorRefreshRate(int monitor) // Get the human-readable, UTF-8 encoded name of the selected monitor const char *GetMonitorName(int monitor) { - TRACELOG(LOG_WARNING, "GetMonitorName() not implemented on target platform"); - return ""; + const char *name = ""; + + if (monitor != 0) + { + TRACELOG(LOG_WARNING, "GetMonitorName() implemented for first monitor only"); + } + else if ((platform.connector) && (platform.modeIndex >= 0)) + { + name = platform.connector->modes[platform.modeIndex].name; + } + + return name; } // Get window position XY on monitor @@ -520,6 +609,12 @@ int SetGamepadMappings(const char *mappings) return 0; } +// Set gamepad vibration +void SetGamepadVibration(int gamepad, float leftMotor, float rightMotor) +{ + TRACELOG(LOG_WARNING, "GamepadSetVibration() not implemented on target platform"); +} + // Set mouse position XY void SetMousePosition(int x, int y) { @@ -546,9 +641,6 @@ void PollInputEvents(void) CORE.Input.Keyboard.keyPressedQueueCount = 0; CORE.Input.Keyboard.charPressedQueueCount = 0; - // Reset key repeats - for (int i = 0; i < MAX_KEYBOARD_KEYS; i++) CORE.Input.Keyboard.keyRepeatInFrame[i] = 0; - // Reset last gamepad button/axis registered state CORE.Input.Gamepad.lastButtonPressed = 0; // GAMEPAD_BUTTON_UNKNOWN //CORE.Input.Gamepad.axisCount = 0; @@ -562,6 +654,15 @@ void PollInputEvents(void) PollKeyboardEvents(); +#if defined(SUPPORT_SSH_KEYBOARD_RPI) + // NOTE: Keyboard reading could be done using input_event(s) or just read from stdin, both methods are used here. + // stdin reading is still used for legacy purposes, it allows keyboard input trough SSH console + if (!platform.eventKeyboardMode) ProcessKeyboard(); +#endif + + // Check exit key + if (CORE.Input.Keyboard.currentKeyState[CORE.Input.Keyboard.exitKey] == 1) CORE.Window.shouldClose = true; + // Register previous mouse position if (platform.cursorRelative) CORE.Input.Mouse.currentPosition = (Vector2){ 0.0f, 0.0f }; else CORE.Input.Mouse.previousPosition = CORE.Input.Mouse.currentPosition; @@ -570,21 +671,16 @@ void PollInputEvents(void) CORE.Input.Mouse.previousWheelMove = CORE.Input.Mouse.currentWheelMove; CORE.Input.Mouse.currentWheelMove = platform.eventWheelMove; platform.eventWheelMove = (Vector2){ 0.0f, 0.0f }; + for (int i = 0; i < MAX_MOUSE_BUTTONS; i++) { CORE.Input.Mouse.previousButtonState[i] = CORE.Input.Mouse.currentButtonState[i]; CORE.Input.Mouse.currentButtonState[i] = platform.currentButtonStateEvdev[i]; + CORE.Input.Touch.currentTouchState[i] = platform.currentButtonStateEvdev[i]; } // Register gamepads buttons events - for (int i = 0; i < MAX_GAMEPADS; i++) - { - if (CORE.Input.Gamepad.ready[i]) - { - // Register previous gamepad states - for (int k = 0; k < MAX_GAMEPAD_BUTTONS; k++) CORE.Input.Gamepad.previousButtonState[i][k] = CORE.Input.Gamepad.currentButtonState[i][k]; - } - } + PollGamepadEvents(); // Register previous touch states for (int i = 0; i < MAX_TOUCH_POINTS; i++) CORE.Input.Touch.previousTouchState[i] = CORE.Input.Touch.currentTouchState[i]; @@ -595,192 +691,8 @@ void PollInputEvents(void) // Map touch position to mouse position for convenience CORE.Input.Touch.position[0] = CORE.Input.Mouse.currentPosition; -#if defined(SUPPORT_SSH_KEYBOARD_RPI) - // NOTE: Keyboard reading could be done using input_event(s) or just read from stdin, both methods are used here. - // stdin reading is still used for legacy purposes, it allows keyboard input trough SSH console - - if (!platform.eventKeyboardMode) ProcessKeyboard(); - - // NOTE: Mouse input events polling is done asynchronously in another pthread - EventThread() - // NOTE: Gamepad (Joystick) input events polling is done asynchonously in another pthread - GamepadThread() -#endif - // Handle the mouse/touch/gestures events: - // NOTE: Replaces the EventThread handling that is now commented. - { - int fd = platform.mouseFd; - if (fd == -1) return; - - struct input_event event = { 0 }; - - int touchAction = -1; // 0-TOUCH_ACTION_UP, 1-TOUCH_ACTION_DOWN, 2-TOUCH_ACTION_MOVE - bool gestureUpdate = false; // Flag to note gestures require to update - - // Try to read data from the mouse/touch/gesture and only continue if successful - while (read(fd, &event, sizeof(event)) == (int)sizeof(event)) - { - // Relative movement parsing - if (event.type == EV_REL) - { - if (event.code == REL_X) - { - if (platform.cursorRelative) - { - CORE.Input.Mouse.currentPosition.x = event.value; - CORE.Input.Mouse.previousPosition.x = 0.0f; - } - else CORE.Input.Mouse.currentPosition.x += event.value; - CORE.Input.Touch.position[0].x = CORE.Input.Mouse.currentPosition.x; - - touchAction = 2; // TOUCH_ACTION_MOVE - gestureUpdate = true; - } - - if (event.code == REL_Y) - { - if (platform.cursorRelative) - { - CORE.Input.Mouse.currentPosition.y = event.value; - CORE.Input.Mouse.previousPosition.y = 0.0f; - } - else CORE.Input.Mouse.currentPosition.y += event.value; - CORE.Input.Touch.position[0].y = CORE.Input.Mouse.currentPosition.y; - - touchAction = 2; // TOUCH_ACTION_MOVE - gestureUpdate = true; - } - - if (event.code == REL_WHEEL) platform.eventWheelMove.y += event.value; - } - - // Absolute movement parsing - if (event.type == EV_ABS) - { - // Basic movement - if (event.code == ABS_X) - { - CORE.Input.Mouse.currentPosition.x = (event.value - platform.absRange.x)*CORE.Window.screen.width/platform.absRange.width; // Scale according to absRange - CORE.Input.Touch.position[0].x = (event.value - platform.absRange.x)*CORE.Window.screen.width/platform.absRange.width; // Scale according to absRange - - touchAction = 2; // TOUCH_ACTION_MOVE - gestureUpdate = true; - } - - if (event.code == ABS_Y) - { - CORE.Input.Mouse.currentPosition.y = (event.value - platform.absRange.y)*CORE.Window.screen.height/platform.absRange.height; // Scale according to absRange - CORE.Input.Touch.position[0].y = (event.value - platform.absRange.y)*CORE.Window.screen.height/platform.absRange.height; // Scale according to absRange - - touchAction = 2; // TOUCH_ACTION_MOVE - gestureUpdate = true; - } - - // Multitouch movement - if (event.code == ABS_MT_SLOT) platform.touchSlot = event.value; // Remember the slot number for the folowing events - - if (event.code == ABS_MT_POSITION_X) - { - if (platform.touchSlot < MAX_TOUCH_POINTS) CORE.Input.Touch.position[platform.touchSlot].x = (event.value - platform.absRange.x)*CORE.Window.screen.width/platform.absRange.width; // Scale according to absRange - } - - if (event.code == ABS_MT_POSITION_Y) - { - if (platform.touchSlot < MAX_TOUCH_POINTS) CORE.Input.Touch.position[platform.touchSlot].y = (event.value - platform.absRange.y)*CORE.Window.screen.height/platform.absRange.height; // Scale according to absRange - } - - if (event.code == ABS_MT_TRACKING_ID) - { - if ((event.value < 0) && (platform.touchSlot < MAX_TOUCH_POINTS)) - { - // Touch has ended for this point - CORE.Input.Touch.position[platform.touchSlot].x = -1; - CORE.Input.Touch.position[platform.touchSlot].y = -1; - } - } - - // Touchscreen tap - if (event.code == ABS_PRESSURE) - { - int previousMouseLeftButtonState = platform.currentButtonStateEvdev[MOUSE_BUTTON_LEFT]; - - if (!event.value && previousMouseLeftButtonState) - { - platform.currentButtonStateEvdev[MOUSE_BUTTON_LEFT] = 0; - - touchAction = 0; // TOUCH_ACTION_UP - gestureUpdate = true; - } - - if (event.value && !previousMouseLeftButtonState) - { - platform.currentButtonStateEvdev[MOUSE_BUTTON_LEFT] = 1; - - touchAction = 1; // TOUCH_ACTION_DOWN - gestureUpdate = true; - } - } - - } - - // Button parsing - if (event.type == EV_KEY) - { - // Mouse button parsing - if ((event.code == BTN_TOUCH) || (event.code == BTN_LEFT)) - { - platform.currentButtonStateEvdev[MOUSE_BUTTON_LEFT] = event.value; - - if (event.value > 0) touchAction = 1; // TOUCH_ACTION_DOWN - else touchAction = 0; // TOUCH_ACTION_UP - gestureUpdate = true; - } - - if (event.code == BTN_RIGHT) platform.currentButtonStateEvdev[MOUSE_BUTTON_RIGHT] = event.value; - if (event.code == BTN_MIDDLE) platform.currentButtonStateEvdev[MOUSE_BUTTON_MIDDLE] = event.value; - if (event.code == BTN_SIDE) platform.currentButtonStateEvdev[MOUSE_BUTTON_SIDE] = event.value; - if (event.code == BTN_EXTRA) platform.currentButtonStateEvdev[MOUSE_BUTTON_EXTRA] = event.value; - if (event.code == BTN_FORWARD) platform.currentButtonStateEvdev[MOUSE_BUTTON_FORWARD] = event.value; - if (event.code == BTN_BACK) platform.currentButtonStateEvdev[MOUSE_BUTTON_BACK] = event.value; - } - - // Screen confinement - if (!CORE.Input.Mouse.cursorHidden) - { - if (CORE.Input.Mouse.currentPosition.x < 0) CORE.Input.Mouse.currentPosition.x = 0; - if (CORE.Input.Mouse.currentPosition.x > CORE.Window.screen.width/CORE.Input.Mouse.scale.x) CORE.Input.Mouse.currentPosition.x = CORE.Window.screen.width/CORE.Input.Mouse.scale.x; - - if (CORE.Input.Mouse.currentPosition.y < 0) CORE.Input.Mouse.currentPosition.y = 0; - if (CORE.Input.Mouse.currentPosition.y > CORE.Window.screen.height/CORE.Input.Mouse.scale.y) CORE.Input.Mouse.currentPosition.y = CORE.Window.screen.height/CORE.Input.Mouse.scale.y; - } - - // Update touch point count - CORE.Input.Touch.pointCount = 0; - for (int i = 0; i < MAX_TOUCH_POINTS; i++) - { - if (CORE.Input.Touch.position[i].x >= 0) CORE.Input.Touch.pointCount++; - } - -#if defined(SUPPORT_GESTURES_SYSTEM) - if (gestureUpdate) - { - GestureEvent gestureEvent = { 0 }; - - gestureEvent.touchAction = touchAction; - gestureEvent.pointCount = CORE.Input.Touch.pointCount; - - for (int i = 0; i < MAX_TOUCH_POINTS; i++) - { - gestureEvent.pointId[i] = i; - gestureEvent.position[i] = CORE.Input.Touch.position[i]; - } - - ProcessGestureEvent(gestureEvent); - - gestureUpdate = false; - } -#endif - } - } + PollMouseEvents(); } //---------------------------------------------------------------------------------- @@ -1138,8 +1050,10 @@ int InitPlatform(void) // Initialize input events system //---------------------------------------------------------------------------- InitEvdevInput(); // Evdev inputs initialization - InitGamepad(); // Gamepad init + +#if defined(SUPPORT_SSH_KEYBOARD_RPI) InitKeyboard(); // Keyboard init (stdin) +#endif //---------------------------------------------------------------------------- // Initialize storage system @@ -1218,30 +1132,29 @@ void ClosePlatform(void) platform.device = EGL_NO_DISPLAY; } - // Wait for mouse and gamepad threads to finish before closing - // NOTE: Those threads should already have finished at this point - // because they are controlled by CORE.Window.shouldClose variable - CORE.Window.shouldClose = true; // Added to force threads to exit when the close window is called - // Close the evdev keyboard + // Close the evdev devices + + if (platform.mouseFd != -1) { + close(platform.mouseFd); + platform.mouseFd = -1; + } + + for (int i = 0; i < platform.gamepadCount; i++) + { + close(platform.gamepadStreamFd[i]); + platform.gamepadStreamFd[i] = -1; + } + if (platform.keyboardFd != -1) { close(platform.keyboardFd); platform.keyboardFd = -1; } - - for (int i = 0; i < sizeof(platform.eventWorker)/sizeof(InputEventWorker); ++i) - { - if (platform.eventWorker[i].threadId) - { - pthread_join(platform.eventWorker[i].threadId, NULL); - } - } - - if (platform.gamepadThreadId) pthread_join(platform.gamepadThreadId, NULL); } +#if defined(SUPPORT_SSH_KEYBOARD_RPI) // Initialize Keyboard system (using standard input) static void InitKeyboard(void) { @@ -1273,7 +1186,7 @@ static void InitKeyboard(void) int result = ioctl(STDIN_FILENO, KDGKBMODE, &platform.defaultKeyboardMode); // In case of failure, it could mean a remote keyboard is used (SSH) - if (result < 0) TRACELOG(LOG_WARNING, "RPI: Failed to change keyboard mode, an SSH keyboard is probably used"); + if (result < 0) TRACELOG(LOG_WARNING, "DRM: Failed to change keyboard mode, an SSH keyboard is probably used"); else { // Reconfigure keyboard mode to get: @@ -1299,7 +1212,6 @@ static void RestoreKeyboard(void) ioctl(STDIN_FILENO, KDSKBMODE, platform.defaultKeyboardMode); } -#if defined(SUPPORT_SSH_KEYBOARD_RPI) // Process keyboard inputs static void ProcessKeyboard(void) { @@ -1400,18 +1312,6 @@ static void ProcessKeyboard(void) CORE.Input.Keyboard.keyPressedQueueCount++; } } - - // Check exit key (same functionality as GLFW3 KeyCallback()) - if (CORE.Input.Keyboard.currentKeyState[CORE.Input.Keyboard.exitKey] == 1) CORE.Window.shouldClose = true; - -#if defined(SUPPORT_SCREEN_CAPTURE) - // Check screen capture key (raylib key: KEY_F12) - if (CORE.Input.Keyboard.currentKeyState[301] == 1) - { - TakeScreenshot(TextFormat("screenshot%03i.png", screenshotCounter)); - screenshotCounter++; - } -#endif } #endif // SUPPORT_SSH_KEYBOARD_RPI @@ -1425,6 +1325,7 @@ static void InitEvdevInput(void) // Initialise keyboard file descriptor platform.keyboardFd = -1; + platform.mouseFd = -1; // Reset variables for (int i = 0; i < MAX_TOUCH_POINTS; ++i) @@ -1457,7 +1358,7 @@ static void InitEvdevInput(void) closedir(directory); } - else TRACELOG(LOG_WARNING, "RPI: Failed to open linux event directory: %s", DEFAULT_EVDEV_PATH); + else TRACELOG(LOG_WARNING, "INPUT: Failed to open linux event directory: %s", DEFAULT_EVDEV_PATH); } // Identifies a input device and configures it for use if appropriate @@ -1470,62 +1371,18 @@ static void ConfigureEvdevDevice(char *device) #define LONG(x) ((x)/BITS_PER_LONG) #define TEST_BIT(array, bit) ((array[LONG(bit)] >> OFF(bit)) & 1) - struct input_absinfo absinfo = { 0 }; unsigned long evBits[NBITS(EV_MAX)] = { 0 }; unsigned long absBits[NBITS(ABS_MAX)] = { 0 }; unsigned long relBits[NBITS(REL_MAX)] = { 0 }; unsigned long keyBits[NBITS(KEY_MAX)] = { 0 }; - bool hasAbs = false; - bool hasRel = false; - bool hasAbsMulti = false; - int freeWorkerId = -1; - int fd = -1; - - InputEventWorker *worker = NULL; - - // Open the device and allocate worker - //------------------------------------------------------------------------------------------------------- - // Find a free spot in the workers array - for (int i = 0; i < sizeof(platform.eventWorker)/sizeof(InputEventWorker); ++i) - { - if (platform.eventWorker[i].threadId == 0) - { - freeWorkerId = i; - break; - } - } - - // Select the free worker from array - if (freeWorkerId >= 0) - { - worker = &(platform.eventWorker[freeWorkerId]); // Grab a pointer to the worker - memset(worker, 0, sizeof(InputEventWorker)); // Clear the worker - } - else - { - TRACELOG(LOG_WARNING, "RPI: Failed to create input device thread for %s, out of worker slots", device); - return; - } // Open the device - fd = open(device, O_RDONLY | O_NONBLOCK); + int fd = open(device, O_RDONLY | O_NONBLOCK); if (fd < 0) { - TRACELOG(LOG_WARNING, "RPI: Failed to open input device: %s", device); + TRACELOG(LOG_WARNING, "DRM: Failed to open input device: %s", device); return; } - worker->fd = fd; - - // Grab number on the end of the devices name "event" - int devNum = 0; - char *ptrDevName = strrchr(device, 't'); - worker->eventNum = -1; - - if (ptrDevName != NULL) - { - if (sscanf(ptrDevName, "t%d", &devNum) == 1) worker->eventNum = devNum; - } - else worker->eventNum = 0; // TODO: HACK: Grab number for mouse0 device! // At this point we have a connection to the device, but we don't yet know what the device is. // It could be many things, even as simple as a power button... @@ -1533,149 +1390,173 @@ static void ConfigureEvdevDevice(char *device) // Identify the device //------------------------------------------------------------------------------------------------------- - ioctl(fd, EVIOCGBIT(0, sizeof(evBits)), evBits); // Read a bitfield of the available device properties + struct { + bool exist; + struct input_absinfo info; + } absinfo[ABS_CNT] = { 0 }; + + // These flags aren't really a one of + // Some devices could have properties we assosciate with keyboards as well as properties + // we assosciate with mice + bool isKeyboard = false; + bool isMouse = false; + bool isTouch = false; + bool isGamepad = false; + + int absAxisCount = 0; + + ioctl(fd, EVIOCGBIT(0, sizeof(evBits)), evBits); + ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keyBits)), keyBits); - // Check for absolute input devices if (TEST_BIT(evBits, EV_ABS)) { ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absBits)), absBits); - // Check for absolute movement support (usually touchscreens, but also joysticks) - if (TEST_BIT(absBits, ABS_X) && TEST_BIT(absBits, ABS_Y)) + // If the device has an X an Y axis it's either a touch device, a special mouse or a gamepad + bool hasAbsXY = TEST_BIT(absBits, ABS_X) && TEST_BIT(absBits, ABS_Y); + + if (hasAbsXY) { - hasAbs = true; + absAxisCount += 2; - // Get the scaling values - ioctl(fd, EVIOCGABS(ABS_X), &absinfo); - worker->absRange.x = absinfo.minimum; - worker->absRange.width = absinfo.maximum - absinfo.minimum; - platform.absRange.x = absinfo.minimum; - platform.absRange.width = absinfo.maximum - absinfo.minimum; + absinfo[ABS_X].exist = true; + absinfo[ABS_Y].exist = true; - ioctl(fd, EVIOCGABS(ABS_Y), &absinfo); - worker->absRange.y = absinfo.minimum; - worker->absRange.height = absinfo.maximum - absinfo.minimum; - platform.absRange.y = absinfo.minimum; - platform.absRange.height = absinfo.maximum - absinfo.minimum; + ioctl(fd, EVIOCGABS(ABS_X), &absinfo[ABS_X].info); + ioctl(fd, EVIOCGABS(ABS_Y), &absinfo[ABS_Y].info); } - // Check for multiple absolute movement support (usually multitouch touchscreens) - if (TEST_BIT(absBits, ABS_MT_POSITION_X) && TEST_BIT(absBits, ABS_MT_POSITION_Y)) + // If it has any of these buttons it's a touch device + if (hasAbsXY && + (TEST_BIT(keyBits, BTN_STYLUS) || + TEST_BIT(keyBits, BTN_TOOL_PEN) || + TEST_BIT(keyBits, BTN_TOOL_FINGER) || + TEST_BIT(keyBits, BTN_TOUCH))) isTouch = true; + + // Absolute mice should really only exist with VMWare, but it shouldn't + // matter if we support them + else if (hasAbsXY && TEST_BIT(keyBits, BTN_MOUSE)) isMouse = true; + + // If any of the common joystick axis is present, we assume it's a gamepad + else { - hasAbsMulti = true; + for (int axis = (hasAbsXY? ABS_Z : ABS_X); axis < ABS_PRESSURE; axis++) + { + if (TEST_BIT(absBits, axis)) + { + absinfo[axis].exist = true; + isGamepad = true; + absAxisCount++; - // Get the scaling values - ioctl(fd, EVIOCGABS(ABS_X), &absinfo); - worker->absRange.x = absinfo.minimum; - worker->absRange.width = absinfo.maximum - absinfo.minimum; - platform.absRange.x = absinfo.minimum; - platform.absRange.width = absinfo.maximum - absinfo.minimum; - - ioctl(fd, EVIOCGABS(ABS_Y), &absinfo); - worker->absRange.y = absinfo.minimum; - worker->absRange.height = absinfo.maximum - absinfo.minimum; - platform.absRange.y = absinfo.minimum; - platform.absRange.height = absinfo.maximum - absinfo.minimum; + ioctl(fd, EVIOCGABS(axis), &absinfo[axis].info); + } + } } + + // If the device has multitouch axes, it's a touch device + if (TEST_BIT(absBits, ABS_MT_POSITION_X) && + TEST_BIT(absBits, ABS_MT_POSITION_Y)) isTouch = true; } - // Check for relative movement support (usually mouse) if (TEST_BIT(evBits, EV_REL)) { ioctl(fd, EVIOCGBIT(EV_REL, sizeof(relBits)), relBits); - if (TEST_BIT(relBits, REL_X) && TEST_BIT(relBits, REL_Y)) hasRel = true; + // If it has any of the gamepad or touch features we tested so far, it's not a mouse + if (!isTouch && + !isGamepad && + TEST_BIT(relBits, REL_X) && + TEST_BIT(relBits, REL_Y) && + TEST_BIT(keyBits, BTN_MOUSE)) isMouse = true; } - // Check for button support to determine the device type(usually on all input devices) + if (TEST_BIT(evBits, EV_KEY)) { - ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keyBits)), keyBits); + // The first 32 keys as defined in input-event-codes.h are pretty much + // exclusive to keyboards, so we can test them using a mask + // Leave out the first bit to not test KEY_RESERVED + const unsigned long mask = 0xFFFFFFFE; + if ((keyBits[0] & mask) == mask) isKeyboard = true; - if (hasAbs || hasAbsMulti) + // If we find any of the common gamepad buttons we assume it's a gamepad + else { - if (TEST_BIT(keyBits, BTN_TOUCH)) worker->isTouch = true; // This is a touchscreen - if (TEST_BIT(keyBits, BTN_TOOL_FINGER)) worker->isTouch = true; // This is a drawing tablet - if (TEST_BIT(keyBits, BTN_TOOL_PEN)) worker->isTouch = true; // This is a drawing tablet - if (TEST_BIT(keyBits, BTN_STYLUS)) worker->isTouch = true; // This is a drawing tablet - if (worker->isTouch || hasAbsMulti) worker->isMultitouch = true; // This is a multitouch capable device - } - - if (hasRel) - { - if (TEST_BIT(keyBits, BTN_LEFT)) worker->isMouse = true; // This is a mouse - if (TEST_BIT(keyBits, BTN_RIGHT)) worker->isMouse = true; // This is a mouse - } - - if (TEST_BIT(keyBits, BTN_A)) worker->isGamepad = true; // This is a gamepad - if (TEST_BIT(keyBits, BTN_TRIGGER)) worker->isGamepad = true; // This is a gamepad - if (TEST_BIT(keyBits, BTN_START)) worker->isGamepad = true; // This is a gamepad - if (TEST_BIT(keyBits, BTN_TL)) worker->isGamepad = true; // This is a gamepad - if (TEST_BIT(keyBits, BTN_TL)) worker->isGamepad = true; // This is a gamepad - - if (TEST_BIT(keyBits, KEY_SPACE)) worker->isKeyboard = true; // This is a keyboard - } - //------------------------------------------------------------------------------------------------------- - - // Decide what to do with the device - //------------------------------------------------------------------------------------------------------- - if (worker->isKeyboard && (platform.keyboardFd == -1)) - { - // Use the first keyboard encountered. This assumes that a device that says it's a keyboard is just a - // keyboard. The keyboard is polled synchronously, whereas other input devices are polled in separate - // threads so that they don't drop events when the frame rate is slow. - TRACELOG(LOG_INFO, "RPI: Opening keyboard device: %s", device); - platform.keyboardFd = worker->fd; - } - else if (worker->isTouch || worker->isMouse) - { - // Looks like an interesting device - TRACELOG(LOG_INFO, "RPI: Opening input device: %s (%s%s%s%s)", device, - worker->isMouse? "mouse " : "", - worker->isMultitouch? "multitouch " : "", - worker->isTouch? "touchscreen " : "", - worker->isGamepad? "gamepad " : ""); - platform.mouseFd = worker->fd; - - // NOTE: moved the mouse/touch/gesture input to PollInputEvents()/ - // so added the "platform.mouseFd = worker->fd;" line above - // and commented the thread code below: - - // Create a thread for this device - //int error = pthread_create(&worker->threadId, NULL, &EventThread, (void *)worker); - //if (error != 0) - //{ - // TRACELOG(LOG_WARNING, "RPI: Failed to create input device thread: %s (error: %d)", device, error); - // worker->threadId = 0; - // close(fd); - //} - -#if defined(USE_LAST_TOUCH_DEVICE) - // Find touchscreen with the highest index - int maxTouchNumber = -1; - - for (int i = 0; i < sizeof(platform.eventWorker)/sizeof(InputEventWorker); ++i) - { - if (platform.eventWorker[i].isTouch && (platform.eventWorker[i].eventNum > maxTouchNumber)) maxTouchNumber = platform.eventWorker[i].eventNum; - } - - // Find touchscreens with lower indexes - for (int i = 0; i < sizeof(platform.eventWorker)/sizeof(InputEventWorker); ++i) - { - if (platform.eventWorker[i].isTouch && (platform.eventWorker[i].eventNum < maxTouchNumber)) + for (int button = BTN_JOYSTICK; button < BTN_DIGI; ++button) { - if (platform.eventWorker[i].threadId != 0) + if (TEST_BIT(keyBits, button)) isGamepad = true; + } + + for (int button = BTN_TRIGGER_HAPPY1; button <= BTN_TRIGGER_HAPPY40; button++) + { + if (TEST_BIT(keyBits, button)) isGamepad = true; + } + } + } + + const char *deviceKindStr = "unknown"; + if (isMouse || isTouch) + { + deviceKindStr = "mouse"; + if (platform.mouseFd != -1) close(platform.mouseFd); + platform.mouseFd = fd; + + if (absAxisCount > 0) + { + platform.absRange.x = absinfo[ABS_X].info.minimum; + platform.absRange.width = absinfo[ABS_X].info.maximum - absinfo[ABS_X].info.minimum; + + platform.absRange.y = absinfo[ABS_Y].info.minimum; + platform.absRange.height = absinfo[ABS_Y].info.maximum - absinfo[ABS_Y].info.minimum; + } + } + else if (isGamepad && !isMouse && !isKeyboard && platform.gamepadCount < MAX_GAMEPADS) + { + deviceKindStr = "gamepad"; + int index = platform.gamepadCount++; + + platform.gamepadStreamFd[index] = fd; + CORE.Input.Gamepad.ready[index] = true; + + ioctl(platform.gamepadStreamFd[index], EVIOCGNAME(64), &CORE.Input.Gamepad.name[index]); + CORE.Input.Gamepad.axisCount[index] = absAxisCount; + + if (absAxisCount > 0) + { + // TODO / NOTE + // So gamepad axis (as in the actual linux joydev.c) are just simply enumerated + // and (at least for some input drivers like xpat) it's convention to use + // ABS_X, ABX_Y for one joystick ABS_RX, ABS_RY for the other and the Z axes for the + // shoulder buttons + // If these are now enumerated you get LJOY_X, LJOY_Y, LEFT_SHOULDERB, RJOY_X, ... + // That means they don't match the GamepadAxis enum + // This could be fixed + int axisIndex = 0; + for (int axis = ABS_X; axis < ABS_PRESSURE; axis++) + { + if (absinfo[axis].exist) { - TRACELOG(LOG_WARNING, "RPI: Found duplicate touchscreen, killing touchscreen on event: %d", i); - pthread_cancel(platform.eventWorker[i].threadId); - close(platform.eventWorker[i].fd); + platform.gamepadAbsAxisRange[index][axisIndex][0] = absinfo[axisIndex].info.minimum; + platform.gamepadAbsAxisRange[index][axisIndex][1] = absinfo[axisIndex].info.maximum - absinfo[axisIndex].info.minimum; + + platform.gamepadAbsAxisMap[index][axis] = axisIndex; + axisIndex++; } } } -#endif } - else close(fd); // We are not interested in this device - //------------------------------------------------------------------------------------------------------- + else if (isKeyboard && (platform.keyboardFd == -1)) + { + deviceKindStr = "keyboard"; + platform.keyboardFd = fd; + } + else + { + close(fd); + return; + } + + TRACELOG(LOG_INFO, "INPUT: Initialized input device %s as %s", device, deviceKindStr); } // Poll and process evdev keyboard events @@ -1690,338 +1571,272 @@ static void PollKeyboardEvents(void) // Try to read data from the keyboard and only continue if successful while (read(fd, &event, sizeof(event)) == (int)sizeof(event)) { - // Button parsing - if (event.type == EV_KEY) - { -#if defined(SUPPORT_SSH_KEYBOARD_RPI) - // Change keyboard mode to events - platform.eventKeyboardMode = true; -#endif - // Keyboard button parsing - if ((event.code >= 1) && (event.code <= 255)) //Keyboard keys appear for codes 1 to 255 - { - keycode = keymapUS[event.code & 0xFF]; // The code we get is a scancode so we look up the appropriate keycode + // Check if the event is a key event + if (event.type != EV_KEY) continue; - // Make sure we got a valid keycode - if ((keycode > 0) && (keycode < sizeof(CORE.Input.Keyboard.currentKeyState))) +#if defined(SUPPORT_SSH_KEYBOARD_RPI) + // If the event was a key, we know a working keyboard is connected, so disable the SSH keyboard + platform.eventKeyboardMode = true; +#endif + + // Keyboard keys appear for codes 1 to 255, ignore everthing else + if ((event.code >= 1) && (event.code <= 255)) + { + + // Lookup the scancode in the keymap to get a keycode + keycode = linuxToRaylibMap[event.code]; + + // Make sure we got a valid keycode + if ((keycode > 0) && (keycode < MAX_KEYBOARD_KEYS)) + { + + // WARNING: https://www.kernel.org/doc/Documentation/input/input.txt + // Event interface: 'value' is the value the event carries. Either a relative change for EV_REL, + // absolute new value for EV_ABS (joysticks ...), or 0 for EV_KEY for release, 1 for keypress and 2 for autorepeat + CORE.Input.Keyboard.currentKeyState[keycode] = (event.value >= 1); + CORE.Input.Keyboard.keyRepeatInFrame[keycode] = (event.value == 2); + + // If the key is pressed add it to the queues + if (event.value == 1) { - // WARNING: https://www.kernel.org/doc/Documentation/input/input.txt - // Event interface: 'value' is the value the event carries. Either a relative change for EV_REL, - // absolute new value for EV_ABS (joysticks ...), or 0 for EV_KEY for release, 1 for keypress and 2 for autorepeat - CORE.Input.Keyboard.currentKeyState[keycode] = (event.value >= 1)? 1 : 0; - if (event.value >= 1) + if (CORE.Input.Keyboard.keyPressedQueueCount < MAX_CHAR_PRESSED_QUEUE) { - CORE.Input.Keyboard.keyPressedQueue[CORE.Input.Keyboard.keyPressedQueueCount] = keycode; // Register last key pressed + CORE.Input.Keyboard.keyPressedQueue[CORE.Input.Keyboard.keyPressedQueueCount] = keycode; CORE.Input.Keyboard.keyPressedQueueCount++; } - #if defined(SUPPORT_SCREEN_CAPTURE) - // Check screen capture key (raylib key: KEY_F12) - if (CORE.Input.Keyboard.currentKeyState[301] == 1) + if (CORE.Input.Keyboard.charPressedQueueCount < MAX_CHAR_PRESSED_QUEUE) { - TakeScreenshot(TextFormat("screenshot%03i.png", screenshotCounter)); - screenshotCounter++; + // TODO/FIXME: This is not actually converting to unicode properly because it's not taking things like shift into account + CORE.Input.Keyboard.charPressedQueue[CORE.Input.Keyboard.charPressedQueueCount] = evkeyToUnicodeLUT[event.code]; + CORE.Input.Keyboard.charPressedQueueCount++; } - #endif - - // Detect char presses (unicode) - if (event.value == 1) - { - // Check if there is space available in the queue - if (CORE.Input.Keyboard.charPressedQueueCount < MAX_CHAR_PRESSED_QUEUE) - { - // Add character to the queue - CORE.Input.Keyboard.charPressedQueue[CORE.Input.Keyboard.charPressedQueueCount] = EvkeyToUnicodeLUT[event.code]; - CORE.Input.Keyboard.charPressedQueueCount++; - } - } - - if (CORE.Input.Keyboard.currentKeyState[CORE.Input.Keyboard.exitKey] == 1) CORE.Window.shouldClose = true; - - TRACELOGD("RPI: KEY_%s ScanCode: %4i KeyCode: %4i", (event.value == 0)? "UP" : "DOWN", event.code, keycode); } + + TRACELOG(LOG_DEBUG, "INPUT: KEY_%s Keycode(linux): %4i KeyCode(raylib): %4i", (event.value == 0) ? "UP " : "DOWN", event.code, keycode); } } } } -// Input device events reading thread -static void *EventThread(void *arg) +// Poll gamepad input events +static void PollGamepadEvents(void) { -/* + // Read gamepad event struct input_event event = { 0 }; - InputEventWorker *worker = (InputEventWorker *)arg; - int touchAction = -1; // 0-TOUCH_ACTION_UP, 1-TOUCH_ACTION_DOWN, 2-TOUCH_ACTION_MOVE - bool gestureUpdate = false; // Flag to note gestures require to update - - while (!CORE.Window.shouldClose) + for (int i = 0; i < platform.gamepadCount; i++) { - // Try to read data from the device and only continue if successful - while (read(worker->fd, &event, sizeof(event)) == (int)sizeof(event)) + if (!CORE.Input.Gamepad.ready[i]) continue; + + // Register previous gamepad states + for (int k = 0; k < MAX_GAMEPAD_BUTTONS; k++) CORE.Input.Gamepad.previousButtonState[i][k] = CORE.Input.Gamepad.currentButtonState[i][k]; + + while (read(platform.gamepadStreamFd[i], &event, sizeof(event)) == (int)sizeof(event)) { - // Relative movement parsing - if (event.type == EV_REL) - { - if (event.code == REL_X) - { - if (platform.cursorRelative) - { - CORE.Input.Mouse.currentPosition.x -= event.value; - CORE.Input.Touch.position[0].x = CORE.Input.Mouse.currentPosition.x; - } - else - { - CORE.Input.Mouse.currentPosition.x += event.value; - CORE.Input.Touch.position[0].x = CORE.Input.Mouse.currentPosition.x; - } - - touchAction = 2; // TOUCH_ACTION_MOVE - gestureUpdate = true; - } - - if (event.code == REL_Y) - { - if (platform.cursorRelative) - { - CORE.Input.Mouse.currentPosition.y -= event.value; - CORE.Input.Touch.position[0].y = CORE.Input.Mouse.currentPosition.y; - } - else - { - CORE.Input.Mouse.currentPosition.y += event.value; - CORE.Input.Touch.position[0].y = CORE.Input.Mouse.currentPosition.y; - } - - touchAction = 2; // TOUCH_ACTION_MOVE - gestureUpdate = true; - } - - if (event.code == REL_WHEEL) platform.eventWheelMove.y += event.value; - } - - // Absolute movement parsing - if (event.type == EV_ABS) - { - // Basic movement - if (event.code == ABS_X) - { - CORE.Input.Mouse.currentPosition.x = (event.value - worker->absRange.x)*CORE.Window.screen.width/worker->absRange.width; // Scale according to absRange - CORE.Input.Touch.position[0].x = (event.value - worker->absRange.x)*CORE.Window.screen.width/worker->absRange.width; // Scale according to absRange - - touchAction = 2; // TOUCH_ACTION_MOVE - gestureUpdate = true; - } - - if (event.code == ABS_Y) - { - CORE.Input.Mouse.currentPosition.y = (event.value - worker->absRange.y)*CORE.Window.screen.height/worker->absRange.height; // Scale according to absRange - CORE.Input.Touch.position[0].y = (event.value - worker->absRange.y)*CORE.Window.screen.height/worker->absRange.height; // Scale according to absRange - - touchAction = 2; // TOUCH_ACTION_MOVE - gestureUpdate = true; - } - - // Multitouch movement - if (event.code == ABS_MT_SLOT) worker->touchSlot = event.value; // Remember the slot number for the folowing events - - if (event.code == ABS_MT_POSITION_X) - { - if (worker->touchSlot < MAX_TOUCH_POINTS) CORE.Input.Touch.position[worker->touchSlot].x = (event.value - worker->absRange.x)*CORE.Window.screen.width/worker->absRange.width; // Scale according to absRange - } - - if (event.code == ABS_MT_POSITION_Y) - { - if (worker->touchSlot < MAX_TOUCH_POINTS) CORE.Input.Touch.position[worker->touchSlot].y = (event.value - worker->absRange.y)*CORE.Window.screen.height/worker->absRange.height; // Scale according to absRange - } - - if (event.code == ABS_MT_TRACKING_ID) - { - if ((event.value < 0) && (worker->touchSlot < MAX_TOUCH_POINTS)) - { - // Touch has ended for this point - CORE.Input.Touch.position[worker->touchSlot].x = -1; - CORE.Input.Touch.position[worker->touchSlot].y = -1; - } - } - - // Touchscreen tap - if (event.code == ABS_PRESSURE) - { - int previousMouseLeftButtonState = platform.currentButtonStateEvdev[MOUSE_BUTTON_LEFT]; - - if (!event.value && previousMouseLeftButtonState) - { - platform.currentButtonStateEvdev[MOUSE_BUTTON_LEFT] = 0; - - touchAction = 0; // TOUCH_ACTION_UP - gestureUpdate = true; - } - - if (event.value && !previousMouseLeftButtonState) - { - platform.currentButtonStateEvdev[MOUSE_BUTTON_LEFT] = 1; - - touchAction = 1; // TOUCH_ACTION_DOWN - gestureUpdate = true; - } - } - - } - - // Button parsing if (event.type == EV_KEY) { - // Mouse button parsing - if ((event.code == BTN_TOUCH) || (event.code == BTN_LEFT)) + if (event.code < KEYMAP_SIZE) { - platform.currentButtonStateEvdev[MOUSE_BUTTON_LEFT] = event.value; + short keycodeRaylib = linuxToRaylibMap[event.code]; - if (event.value > 0) touchAction = 1; // TOUCH_ACTION_DOWN - else touchAction = 0; // TOUCH_ACTION_UP - gestureUpdate = true; - } + TRACELOG(LOG_DEBUG, "INPUT: Gamepad %2i: KEY_%s Keycode(linux): %4i Keycode(raylib): %4i", i, (event.value == 0) ? "UP " : "DOWN", event.code, keycodeRaylib); - if (event.code == BTN_RIGHT) platform.currentButtonStateEvdev[MOUSE_BUTTON_RIGHT] = event.value; - if (event.code == BTN_MIDDLE) platform.currentButtonStateEvdev[MOUSE_BUTTON_MIDDLE] = event.value; - if (event.code == BTN_SIDE) platform.currentButtonStateEvdev[MOUSE_BUTTON_SIDE] = event.value; - if (event.code == BTN_EXTRA) platform.currentButtonStateEvdev[MOUSE_BUTTON_EXTRA] = event.value; - if (event.code == BTN_FORWARD) platform.currentButtonStateEvdev[MOUSE_BUTTON_FORWARD] = event.value; - if (event.code == BTN_BACK) platform.currentButtonStateEvdev[MOUSE_BUTTON_BACK] = event.value; - } - - // Screen confinement - if (!CORE.Input.Mouse.cursorHidden) - { - if (CORE.Input.Mouse.currentPosition.x < 0) CORE.Input.Mouse.currentPosition.x = 0; - if (CORE.Input.Mouse.currentPosition.x > CORE.Window.screen.width/CORE.Input.Mouse.scale.x) CORE.Input.Mouse.currentPosition.x = CORE.Window.screen.width/CORE.Input.Mouse.scale.x; - - if (CORE.Input.Mouse.currentPosition.y < 0) CORE.Input.Mouse.currentPosition.y = 0; - if (CORE.Input.Mouse.currentPosition.y > CORE.Window.screen.height/CORE.Input.Mouse.scale.y) CORE.Input.Mouse.currentPosition.y = CORE.Window.screen.height/CORE.Input.Mouse.scale.y; - } - - // Update touch point count - CORE.Input.Touch.pointCount = 0; - for (int i = 0; i < MAX_TOUCH_POINTS; i++) - { - if (CORE.Input.Touch.position[i].x >= 0) CORE.Input.Touch.pointCount++; - } - -#if defined(SUPPORT_GESTURES_SYSTEM) - if (gestureUpdate) - { - GestureEvent gestureEvent = { 0 }; - - gestureEvent.touchAction = touchAction; - gestureEvent.pointCount = CORE.Input.Touch.pointCount; - - for (int i = 0; i < MAX_TOUCH_POINTS; i++) - { - gestureEvent.pointId[i] = i; - gestureEvent.position[i] = CORE.Input.Touch.position[i]; - } - - ProcessGestureEvent(gestureEvent); - } -#endif - } - - WaitTime(0.005); // Sleep for 5ms to avoid hogging CPU time - } - - close(worker->fd); -*/ - return NULL; -} - -// Initialize gamepad system -static void InitGamepad(void) -{ - char gamepadDev[128] = { 0 }; - - for (int i = 0; i < MAX_GAMEPADS; i++) - { - sprintf(gamepadDev, "%s%i", DEFAULT_GAMEPAD_DEV, i); - - if ((platform.gamepadStreamFd[i] = open(gamepadDev, O_RDONLY | O_NONBLOCK)) < 0) - { - // NOTE: Only show message for first gamepad - if (i == 0) TRACELOG(LOG_WARNING, "RPI: Failed to open Gamepad device, no gamepad available"); - } - else - { - CORE.Input.Gamepad.ready[i] = true; - - // NOTE: Only create one thread - if (i == 0) - { - int error = pthread_create(&platform.gamepadThreadId, NULL, &GamepadThread, NULL); - - if (error != 0) TRACELOG(LOG_WARNING, "RPI: Failed to create gamepad input event thread"); - else TRACELOG(LOG_INFO, "RPI: Gamepad device initialized successfully"); - } - - ioctl(platform.gamepadStreamFd[i], JSIOCGNAME(64), &CORE.Input.Gamepad.name[i]); - ioctl(platform.gamepadStreamFd[i], JSIOCGAXES, &CORE.Input.Gamepad.axisCount[i]); - } - } -} - -// Process Gamepad (/dev/input/js0) -static void *GamepadThread(void *arg) -{ - #define JS_EVENT_BUTTON 0x01 // Button pressed/released - #define JS_EVENT_AXIS 0x02 // Joystick axis moved - #define JS_EVENT_INIT 0x80 // Initial state of device - - struct js_event { - unsigned int time; // event timestamp in milliseconds - short value; // event value - unsigned char type; // event type - unsigned char number; // event axis/button number - }; - - // Read gamepad event - struct js_event gamepadEvent = { 0 }; - - while (!CORE.Window.shouldClose) - { - for (int i = 0; i < MAX_GAMEPADS; i++) - { - if (read(platform.gamepadStreamFd[i], &gamepadEvent, sizeof(struct js_event)) == (int)sizeof(struct js_event)) - { - gamepadEvent.type &= ~JS_EVENT_INIT; // Ignore synthetic events - - // Process gamepad events by type - if (gamepadEvent.type == JS_EVENT_BUTTON) - { - //TRACELOG(LOG_WARNING, "RPI: Gamepad button: %i, value: %i", gamepadEvent.number, gamepadEvent.value); - - if (gamepadEvent.number < MAX_GAMEPAD_BUTTONS) + if ((keycodeRaylib != 0) && (keycodeRaylib < MAX_GAMEPAD_BUTTONS)) { // 1 - button pressed, 0 - button released - CORE.Input.Gamepad.currentButtonState[i][gamepadEvent.number] = (int)gamepadEvent.value; + CORE.Input.Gamepad.currentButtonState[i][keycodeRaylib] = event.value; - if ((int)gamepadEvent.value == 1) CORE.Input.Gamepad.lastButtonPressed = gamepadEvent.number; - else CORE.Input.Gamepad.lastButtonPressed = 0; // GAMEPAD_BUTTON_UNKNOWN - } - } - else if (gamepadEvent.type == JS_EVENT_AXIS) - { - //TRACELOG(LOG_WARNING, "RPI: Gamepad axis: %i, value: %i", gamepadEvent.number, gamepadEvent.value); - - if (gamepadEvent.number < MAX_GAMEPAD_AXIS) - { - // NOTE: Scaling of gamepadEvent.value to get values between -1..1 - CORE.Input.Gamepad.axisState[i][gamepadEvent.number] = (float)gamepadEvent.value/32768; + CORE.Input.Gamepad.lastButtonPressed = (event.value == 1)? keycodeRaylib : GAMEPAD_BUTTON_UNKNOWN; + } + } + } + else if (event.type == EV_ABS) + { + if (event.code < ABS_CNT) + { + int axisRaylib = platform.gamepadAbsAxisMap[i][event.code]; + + TRACELOG(LOG_DEBUG, "INPUT: Gamepad %2i: Axis: %2i Value: %i", i, axisRaylib, event.value); + + if (axisRaylib < MAX_GAMEPAD_AXIS) + { + int min = platform.gamepadAbsAxisRange[i][event.code][0]; + int range = platform.gamepadAbsAxisRange[i][event.code][1]; + + // NOTE: Scaling of event.value to get values between -1..1 + CORE.Input.Gamepad.axisState[i][axisRaylib] = (2 * (float)(event.value - min) / range) - 1; } } } - else WaitTime(0.001); // Sleep for 1 ms to avoid hogging CPU time } } +} - return NULL; +// Poll mouse input events +static void PollMouseEvents(void) +{ + int fd = platform.mouseFd; + if (fd == -1) return; + + struct input_event event = { 0 }; + int touchAction = -1; // 0-TOUCH_ACTION_UP, 1-TOUCH_ACTION_DOWN, 2-TOUCH_ACTION_MOVE + + // Try to read data from the mouse/touch/gesture and only continue if successful + while (read(fd, &event, sizeof(event)) == (int)sizeof(event)) + { + // Relative movement parsing + if (event.type == EV_REL) + { + if (event.code == REL_X) + { + if (platform.cursorRelative) + { + CORE.Input.Mouse.currentPosition.x = event.value; + CORE.Input.Mouse.previousPosition.x = 0.0f; + } + else CORE.Input.Mouse.currentPosition.x += event.value; + + CORE.Input.Touch.position[0].x = CORE.Input.Mouse.currentPosition.x; + touchAction = 2; // TOUCH_ACTION_MOVE + } + + if (event.code == REL_Y) + { + if (platform.cursorRelative) + { + CORE.Input.Mouse.currentPosition.y = event.value; + CORE.Input.Mouse.previousPosition.y = 0.0f; + } + else CORE.Input.Mouse.currentPosition.y += event.value; + + CORE.Input.Touch.position[0].y = CORE.Input.Mouse.currentPosition.y; + touchAction = 2; // TOUCH_ACTION_MOVE + } + + if (event.code == REL_WHEEL) platform.eventWheelMove.y += event.value; + } + + // Absolute movement parsing + if (event.type == EV_ABS) + { + // Basic movement + if (event.code == ABS_X) + { + CORE.Input.Mouse.currentPosition.x = (event.value - platform.absRange.x)*CORE.Window.screen.width/platform.absRange.width; // Scale according to absRange + CORE.Input.Touch.position[0].x = (event.value - platform.absRange.x)*CORE.Window.screen.width/platform.absRange.width; // Scale according to absRange + + touchAction = 2; // TOUCH_ACTION_MOVE + } + + if (event.code == ABS_Y) + { + CORE.Input.Mouse.currentPosition.y = (event.value - platform.absRange.y)*CORE.Window.screen.height/platform.absRange.height; // Scale according to absRange + CORE.Input.Touch.position[0].y = (event.value - platform.absRange.y)*CORE.Window.screen.height/platform.absRange.height; // Scale according to absRange + + touchAction = 2; // TOUCH_ACTION_MOVE + } + + // Multitouch movement + if (event.code == ABS_MT_SLOT) platform.touchSlot = event.value; // Remember the slot number for the folowing events + + if (event.code == ABS_MT_POSITION_X) + { + if (platform.touchSlot < MAX_TOUCH_POINTS) CORE.Input.Touch.position[platform.touchSlot].x = (event.value - platform.absRange.x)*CORE.Window.screen.width/platform.absRange.width; // Scale according to absRange + } + + if (event.code == ABS_MT_POSITION_Y) + { + if (platform.touchSlot < MAX_TOUCH_POINTS) CORE.Input.Touch.position[platform.touchSlot].y = (event.value - platform.absRange.y)*CORE.Window.screen.height/platform.absRange.height; // Scale according to absRange + } + + if (event.code == ABS_MT_TRACKING_ID) + { + if ((event.value < 0) && (platform.touchSlot < MAX_TOUCH_POINTS)) + { + // Touch has ended for this point + CORE.Input.Touch.position[platform.touchSlot].x = -1; + CORE.Input.Touch.position[platform.touchSlot].y = -1; + } + } + + // Touchscreen tap + if (event.code == ABS_PRESSURE) + { + int previousMouseLeftButtonState = platform.currentButtonStateEvdev[MOUSE_BUTTON_LEFT]; + + if (!event.value && previousMouseLeftButtonState) + { + platform.currentButtonStateEvdev[MOUSE_BUTTON_LEFT] = 0; + touchAction = 0; // TOUCH_ACTION_UP + } + + if (event.value && !previousMouseLeftButtonState) + { + platform.currentButtonStateEvdev[MOUSE_BUTTON_LEFT] = 1; + touchAction = 1; // TOUCH_ACTION_DOWN + } + } + + } + + // Button parsing + if (event.type == EV_KEY) + { + // Mouse button parsing + if ((event.code == BTN_TOUCH) || (event.code == BTN_LEFT)) + { + platform.currentButtonStateEvdev[MOUSE_BUTTON_LEFT] = event.value; + + if (event.value > 0) touchAction = 1; // TOUCH_ACTION_DOWN + else touchAction = 0; // TOUCH_ACTION_UP + } + + if (event.code == BTN_RIGHT) platform.currentButtonStateEvdev[MOUSE_BUTTON_RIGHT] = event.value; + if (event.code == BTN_MIDDLE) platform.currentButtonStateEvdev[MOUSE_BUTTON_MIDDLE] = event.value; + if (event.code == BTN_SIDE) platform.currentButtonStateEvdev[MOUSE_BUTTON_SIDE] = event.value; + if (event.code == BTN_EXTRA) platform.currentButtonStateEvdev[MOUSE_BUTTON_EXTRA] = event.value; + if (event.code == BTN_FORWARD) platform.currentButtonStateEvdev[MOUSE_BUTTON_FORWARD] = event.value; + if (event.code == BTN_BACK) platform.currentButtonStateEvdev[MOUSE_BUTTON_BACK] = event.value; + } + + // Screen confinement + if (!CORE.Input.Mouse.cursorHidden) + { + if (CORE.Input.Mouse.currentPosition.x < 0) CORE.Input.Mouse.currentPosition.x = 0; + if (CORE.Input.Mouse.currentPosition.x > CORE.Window.screen.width/CORE.Input.Mouse.scale.x) CORE.Input.Mouse.currentPosition.x = CORE.Window.screen.width/CORE.Input.Mouse.scale.x; + + if (CORE.Input.Mouse.currentPosition.y < 0) CORE.Input.Mouse.currentPosition.y = 0; + if (CORE.Input.Mouse.currentPosition.y > CORE.Window.screen.height/CORE.Input.Mouse.scale.y) CORE.Input.Mouse.currentPosition.y = CORE.Window.screen.height/CORE.Input.Mouse.scale.y; + } + + // Update touch point count + CORE.Input.Touch.pointCount = 0; + for (int i = 0; i < MAX_TOUCH_POINTS; i++) + { + if (CORE.Input.Touch.position[i].x >= 0) CORE.Input.Touch.pointCount++; + } + +#if defined(SUPPORT_GESTURES_SYSTEM) + if (touchAction > -1) + { + GestureEvent gestureEvent = { 0 }; + + gestureEvent.touchAction = touchAction; + gestureEvent.pointCount = CORE.Input.Touch.pointCount; + + for (int i = 0; i < MAX_TOUCH_POINTS; i++) + { + gestureEvent.pointId[i] = i; + gestureEvent.position[i] = CORE.Input.Touch.position[i]; + } + + ProcessGestureEvent(gestureEvent); + + touchAction = -1; + } +#endif + } } // Search matching DRM mode in connector's mode list diff --git a/raylib/raudio.c b/raylib/raudio.c index 101b72e..4a140c5 100644 --- a/raylib/raudio.c +++ b/raylib/raudio.c @@ -53,7 +53,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2013-2023 Ramon Santamaria (@raysan5) +* Copyright (c) 2013-2024 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. @@ -170,6 +170,10 @@ typedef struct tagBITMAPINFOHEADER { #define MA_NO_WAV #define MA_NO_FLAC #define MA_NO_MP3 +#define MA_NO_RESOURCE_MANAGER +#define MA_NO_NODE_GRAPH +#define MA_NO_ENGINE +#define MA_NO_GENERATION // Threading model: Default: [0] COINIT_MULTITHREADED: COM calls objects on any thread (free threading) #define MA_COINIT_VALUE 2 // [2] COINIT_APARTMENTTHREADED: Each object has its own thread (apartment model) @@ -409,12 +413,23 @@ static AudioData AUDIO = { // Global AUDIO context // Module specific Functions Declaration //---------------------------------------------------------------------------------- static void OnLog(void *pUserData, ma_uint32 level, const char *pMessage); + +// Reads audio data from an AudioBuffer object in internal/device formats +static ma_uint32 ReadAudioBufferFramesInInternalFormat(AudioBuffer *audioBuffer, void *framesOut, ma_uint32 frameCount); +static ma_uint32 ReadAudioBufferFramesInMixingFormat(AudioBuffer *audioBuffer, float *framesOut, ma_uint32 frameCount); + static void OnSendAudioDataToDevice(ma_device *pDevice, void *pFramesOut, const void *pFramesInput, ma_uint32 frameCount); static void MixAudioFrames(float *framesOut, const float *framesIn, ma_uint32 frameCount, AudioBuffer *buffer); +static bool IsAudioBufferPlayingInLockedState(AudioBuffer *buffer); +static void StopAudioBufferInLockedState(AudioBuffer *buffer); +static void UpdateAudioStreamInLockedState(AudioStream stream, const void *data, int frameCount); + #if defined(RAUDIO_STANDALONE) static bool IsFileExtension(const char *fileName, const char *ext); // Check file extension static const char *GetFileExtension(const char *fileName); // Get pointer to extension for a filename string (includes the dot: .png) +static const char *GetFileName(const char *filePath); // Get pointer to filename for a path string +static const char *GetFileNameWithoutExt(const char *filePath); // Get filename string without extension (uses static string) static unsigned char *LoadFileData(const char *fileName, int *dataSize); // Load file data as byte array (read) static bool SaveFileData(const char *fileName, void *data, int dataSize); // Save data to file from byte array (write) @@ -439,6 +454,7 @@ void SetAudioBufferPan(AudioBuffer *buffer, float pan); void TrackAudioBuffer(AudioBuffer *buffer); void UntrackAudioBuffer(AudioBuffer *buffer); + //---------------------------------------------------------------------------------- // Module Functions Definition - Audio Device initialization and Closing //---------------------------------------------------------------------------------- @@ -457,12 +473,12 @@ void InitAudioDevice(void) } // Init audio device - // NOTE: Using the default device. Format is floating point because it simplifies mixing. + // NOTE: Using the default device. Format is floating point because it simplifies mixing ma_device_config config = ma_device_config_init(ma_device_type_playback); - config.playback.pDeviceID = NULL; // NULL for the default playback AUDIO.System.device. + config.playback.pDeviceID = NULL; // NULL for the default playback AUDIO.System.device config.playback.format = AUDIO_DEVICE_FORMAT; config.playback.channels = AUDIO_DEVICE_CHANNELS; - config.capture.pDeviceID = NULL; // NULL for the default capture AUDIO.System.device. + config.capture.pDeviceID = NULL; // NULL for the default capture AUDIO.System.device config.capture.format = ma_format_s16; config.capture.channels = 1; config.sampleRate = AUDIO_DEVICE_SAMPLE_RATE; @@ -478,7 +494,7 @@ void InitAudioDevice(void) } // Mixing happens on a separate thread which means we need to synchronize. I'm using a mutex here to make things simple, but may - // want to look at something a bit smarter later on to keep everything real-time, if that's necessary. + // want to look at something a bit smarter later on to keep everything real-time, if that's necessary if (ma_mutex_init(&AUDIO.System.lock) != MA_SUCCESS) { TRACELOG(LOG_WARNING, "AUDIO: Failed to create mutex for mixing"); @@ -488,7 +504,7 @@ void InitAudioDevice(void) } // Keep the device running the whole time. May want to consider doing something a bit smarter and only have the device running - // while there's at least one sound being played. + // while there's at least one sound being played result = ma_device_start(&AUDIO.System.device); if (result != MA_SUCCESS) { @@ -499,7 +515,7 @@ void InitAudioDevice(void) } TRACELOG(LOG_INFO, "AUDIO: Device initialized successfully"); - TRACELOG(LOG_INFO, " > Backend: miniaudio / %s", ma_get_backend_name(AUDIO.System.context.backend)); + TRACELOG(LOG_INFO, " > Backend: miniaudio | %s", ma_get_backend_name(AUDIO.System.context.backend)); TRACELOG(LOG_INFO, " > Format: %s -> %s", ma_get_format_name(AUDIO.System.device.playback.format), ma_get_format_name(AUDIO.System.device.playback.internalFormat)); TRACELOG(LOG_INFO, " > Channels: %d -> %d", AUDIO.System.device.playback.channels, AUDIO.System.device.playback.internalChannels); TRACELOG(LOG_INFO, " > Sample rate: %d -> %d", AUDIO.System.device.sampleRate, AUDIO.System.device.playback.internalSampleRate); @@ -609,69 +625,77 @@ void UnloadAudioBuffer(AudioBuffer *buffer) { if (buffer != NULL) { - ma_data_converter_uninit(&buffer->converter, NULL); UntrackAudioBuffer(buffer); + ma_data_converter_uninit(&buffer->converter, NULL); RL_FREE(buffer->data); RL_FREE(buffer); } } -// Check if an audio buffer is playing +// Check if an audio buffer is playing from a program state without lock bool IsAudioBufferPlaying(AudioBuffer *buffer) { bool result = false; - - if (buffer != NULL) result = (buffer->playing && !buffer->paused); - + ma_mutex_lock(&AUDIO.System.lock); + result = IsAudioBufferPlayingInLockedState(buffer); + ma_mutex_unlock(&AUDIO.System.lock); return result; } // Play an audio buffer -// NOTE: Buffer is restarted to the start. -// Use PauseAudioBuffer() and ResumeAudioBuffer() if the playback position should be maintained. +// NOTE: Buffer is restarted to the start +// Use PauseAudioBuffer() and ResumeAudioBuffer() if the playback position should be maintained void PlayAudioBuffer(AudioBuffer *buffer) { if (buffer != NULL) { + ma_mutex_lock(&AUDIO.System.lock); buffer->playing = true; buffer->paused = false; buffer->frameCursorPos = 0; + ma_mutex_unlock(&AUDIO.System.lock); } } -// Stop an audio buffer +// Stop an audio buffer from a program state without lock void StopAudioBuffer(AudioBuffer *buffer) { - if (buffer != NULL) - { - if (IsAudioBufferPlaying(buffer)) - { - buffer->playing = false; - buffer->paused = false; - buffer->frameCursorPos = 0; - buffer->framesProcessed = 0; - buffer->isSubBufferProcessed[0] = true; - buffer->isSubBufferProcessed[1] = true; - } - } + ma_mutex_lock(&AUDIO.System.lock); + StopAudioBufferInLockedState(buffer); + ma_mutex_unlock(&AUDIO.System.lock); } // Pause an audio buffer void PauseAudioBuffer(AudioBuffer *buffer) { - if (buffer != NULL) buffer->paused = true; + if (buffer != NULL) + { + ma_mutex_lock(&AUDIO.System.lock); + buffer->paused = true; + ma_mutex_unlock(&AUDIO.System.lock); + } } // Resume an audio buffer void ResumeAudioBuffer(AudioBuffer *buffer) { - if (buffer != NULL) buffer->paused = false; + if (buffer != NULL) + { + ma_mutex_lock(&AUDIO.System.lock); + buffer->paused = false; + ma_mutex_unlock(&AUDIO.System.lock); + } } // Set volume for an audio buffer void SetAudioBufferVolume(AudioBuffer *buffer, float volume) { - if (buffer != NULL) buffer->volume = volume; + if (buffer != NULL) + { + ma_mutex_lock(&AUDIO.System.lock); + buffer->volume = volume; + ma_mutex_unlock(&AUDIO.System.lock); + } } // Set pitch for an audio buffer @@ -679,7 +703,8 @@ void SetAudioBufferPitch(AudioBuffer *buffer, float pitch) { if ((buffer != NULL) && (pitch > 0.0f)) { - // Pitching is just an adjustment of the sample rate. + ma_mutex_lock(&AUDIO.System.lock); + // Pitching is just an adjustment of the sample rate // Note that this changes the duration of the sound: // - higher pitches will make the sound faster // - lower pitches make it slower @@ -687,6 +712,7 @@ void SetAudioBufferPitch(AudioBuffer *buffer, float pitch) ma_data_converter_set_rate(&buffer->converter, buffer->converter.sampleRateIn, outputSampleRate); buffer->pitch = pitch; + ma_mutex_unlock(&AUDIO.System.lock); } } @@ -696,7 +722,12 @@ void SetAudioBufferPan(AudioBuffer *buffer, float pan) if (pan < 0.0f) pan = 0.0f; else if (pan > 1.0f) pan = 1.0f; - if (buffer != NULL) buffer->pan = pan; + if (buffer != NULL) + { + ma_mutex_lock(&AUDIO.System.lock); + buffer->pan = pan; + ma_mutex_unlock(&AUDIO.System.lock); + } } // Track audio buffer to linked list next position @@ -749,7 +780,7 @@ Wave LoadWave(const char *fileName) // Loading wave from memory data if (fileData != NULL) wave = LoadWaveFromMemory(GetFileExtension(fileName), fileData, dataSize); - RL_FREE(fileData); + UnloadFileData(fileData); return wave; } @@ -867,11 +898,15 @@ Wave LoadWaveFromMemory(const char *fileType, const unsigned char *fileData, int // Checks if wave data is ready bool IsWaveReady(Wave wave) { - return ((wave.data != NULL) && // Validate wave data available - (wave.frameCount > 0) && // Validate frame count - (wave.sampleRate > 0) && // Validate sample rate is supported - (wave.sampleSize > 0) && // Validate sample size is supported - (wave.channels > 0)); // Validate number of channels supported + bool result = false; + + if ((wave.data != NULL) && // Validate wave data available + (wave.frameCount > 0) && // Validate frame count + (wave.sampleRate > 0) && // Validate sample rate is supported + (wave.sampleSize > 0) && // Validate sample size is supported + (wave.channels > 0)) result = true; // Validate number of channels supported + + return result; } // Load sound from file @@ -895,15 +930,15 @@ Sound LoadSoundFromWave(Wave wave) if (wave.data != NULL) { - // When using miniaudio we need to do our own mixing. + // When using miniaudio we need to do our own mixing // To simplify this we need convert the format of each sound to be consistent with // the format used to open the playback AUDIO.System.device. We can do this two ways: // - // 1) Convert the whole sound in one go at load time (here). - // 2) Convert the audio data in chunks at mixing time. + // 1) Convert the whole sound in one go at load time (here) + // 2) Convert the audio data in chunks at mixing time // - // First option has been selected, format conversion is done on the loading stage. - // The downside is that it uses more memory if the original sound is u8 or s16. + // First option has been selected, format conversion is done on the loading stage + // The downside is that it uses more memory if the original sound is u8 or s16 ma_format formatIn = ((wave.sampleSize == 8)? ma_format_u8 : ((wave.sampleSize == 16)? ma_format_s16 : ma_format_f32)); ma_uint32 frameCountIn = wave.frameCount; @@ -938,12 +973,14 @@ Sound LoadSoundAlias(Sound source) if (source.stream.buffer->data != NULL) { - AudioBuffer* audioBuffer = LoadAudioBuffer(AUDIO_DEVICE_FORMAT, AUDIO_DEVICE_CHANNELS, AUDIO.System.device.sampleRate, 0, AUDIO_BUFFER_USAGE_STATIC); + AudioBuffer *audioBuffer = LoadAudioBuffer(AUDIO_DEVICE_FORMAT, AUDIO_DEVICE_CHANNELS, AUDIO.System.device.sampleRate, 0, AUDIO_BUFFER_USAGE_STATIC); + if (audioBuffer == NULL) { TRACELOG(LOG_WARNING, "SOUND: Failed to create buffer"); - return sound; // early return to avoid dereferencing the audioBuffer null pointer + return sound; // Early return to avoid dereferencing the audioBuffer null pointer } + audioBuffer->sizeInFrames = source.stream.buffer->sizeInFrames; audioBuffer->volume = source.stream.buffer->volume; audioBuffer->data = source.stream.buffer->data; @@ -962,11 +999,15 @@ Sound LoadSoundAlias(Sound source) // Checks if a sound is ready bool IsSoundReady(Sound sound) { - return ((sound.frameCount > 0) && // Validate frame count - (sound.stream.buffer != NULL) && // Validate stream buffer - (sound.stream.sampleRate > 0) && // Validate sample rate is supported - (sound.stream.sampleSize > 0) && // Validate sample size is supported - (sound.stream.channels > 0)); // Validate number of channels supported + bool result = false; + + if ((sound.frameCount > 0) && // Validate frame count + (sound.stream.buffer != NULL) && // Validate stream buffer + (sound.stream.sampleRate > 0) && // Validate sample rate is supported + (sound.stream.sampleSize > 0) && // Validate sample size is supported + (sound.stream.channels > 0)) result = true; // Validate number of channels supported + + return result; } // Unload wave data @@ -985,11 +1026,11 @@ void UnloadSound(Sound sound) void UnloadSoundAlias(Sound alias) { - // untrack and unload just the sound buffer, not the sample data, it is shared with the source for the alias + // Untrack and unload just the sound buffer, not the sample data, it is shared with the source for the alias if (alias.stream.buffer != NULL) { - ma_data_converter_uninit(&alias.stream.buffer->converter, NULL); UntrackAudioBuffer(alias.stream.buffer); + ma_data_converter_uninit(&alias.stream.buffer->converter, NULL); RL_FREE(alias.stream.buffer); } } @@ -1001,7 +1042,6 @@ void UpdateSound(Sound sound, const void *data, int frameCount) { StopAudioBuffer(sound.stream.buffer); - // TODO: May want to lock/unlock this since this data buffer is read at mixing time memcpy(sound.stream.buffer->data, data, frameCount*ma_get_bytes_per_frame(sound.stream.buffer->converter.formatIn, sound.stream.buffer->converter.channelsIn)); } } @@ -1076,8 +1116,9 @@ bool ExportWaveAsCode(Wave wave, const char *fileName) int waveDataSize = wave.frameCount*wave.channels*wave.sampleSize/8; // NOTE: Text data buffer size is estimated considering wave data size in bytes - // and requiring 6 char bytes for every byte: "0x00, " - char *txtData = (char *)RL_CALLOC(waveDataSize*6 + 2000, sizeof(char)); + // and requiring 12 char bytes for every byte; the actual size varies, but + // the longest possible char being appended is "%.4ff,\n ", which is 12 bytes. + char *txtData = (char *)RL_CALLOC(waveDataSize*12 + 2000, sizeof(char)); int byteCount = 0; byteCount += sprintf(txtData + byteCount, "\n//////////////////////////////////////////////////////////////////////////////////\n"); @@ -1087,7 +1128,7 @@ bool ExportWaveAsCode(Wave wave, const char *fileName) byteCount += sprintf(txtData + byteCount, "// more info and bugs-report: github.com/raysan5/raylib //\n"); byteCount += sprintf(txtData + byteCount, "// feedback and support: ray[at]raylib.com //\n"); byteCount += sprintf(txtData + byteCount, "// //\n"); - byteCount += sprintf(txtData + byteCount, "// Copyright (c) 2018-2023 Ramon Santamaria (@raysan5) //\n"); + byteCount += sprintf(txtData + byteCount, "// Copyright (c) 2018-2024 Ramon Santamaria (@raysan5) //\n"); byteCount += sprintf(txtData + byteCount, "// //\n"); byteCount += sprintf(txtData + byteCount, "//////////////////////////////////////////////////////////////////////////////////\n\n"); @@ -1096,7 +1137,7 @@ bool ExportWaveAsCode(Wave wave, const char *fileName) strcpy(varFileName, GetFileNameWithoutExt(fileName)); for (int i = 0; varFileName[i] != '\0'; i++) if (varFileName[i] >= 'a' && varFileName[i] <= 'z') { varFileName[i] = varFileName[i] - 32; } - //Add wave information + // Add wave information byteCount += sprintf(txtData + byteCount, "// Wave data information\n"); byteCount += sprintf(txtData + byteCount, "#define %s_FRAME_COUNT %u\n", varFileName, wave.frameCount); byteCount += sprintf(txtData + byteCount, "#define %s_SAMPLE_RATE %u\n", varFileName, wave.sampleRate); @@ -1157,7 +1198,11 @@ void StopSound(Sound sound) // Check if a sound is playing bool IsSoundPlaying(Sound sound) { - return IsAudioBufferPlaying(sound.stream.buffer); + bool result = false; + + if (IsAudioBufferPlaying(sound.stream.buffer)) result = true; + + return result; } // Set volume for a sound @@ -1292,11 +1337,10 @@ Music LoadMusicStream(const char *fileName) drwav *ctxWav = RL_CALLOC(1, sizeof(drwav)); bool success = drwav_init_file(ctxWav, fileName, NULL); - music.ctxType = MUSIC_AUDIO_WAV; - music.ctxData = ctxWav; - if (success) { + music.ctxType = MUSIC_AUDIO_WAV; + music.ctxData = ctxWav; int sampleSize = ctxWav->bitsPerSample; if (ctxWav->bitsPerSample == 24) sampleSize = 16; // Forcing conversion to s16 on UpdateMusicStream() @@ -1305,17 +1349,23 @@ Music LoadMusicStream(const char *fileName) music.looping = true; // Looping enabled by default musicLoaded = true; } + else + { + drwav_uninit(ctxWav); + RL_FREE(ctxWav); + } } #endif #if defined(SUPPORT_FILEFORMAT_OGG) else if (IsFileExtension(fileName, ".ogg")) { // Open ogg audio stream - music.ctxType = MUSIC_AUDIO_OGG; - music.ctxData = stb_vorbis_open_filename(fileName, NULL, NULL); + stb_vorbis *ctxOgg = stb_vorbis_open_filename(fileName, NULL, NULL); - if (music.ctxData != NULL) + if (ctxOgg != NULL) { + music.ctxType = MUSIC_AUDIO_OGG; + music.ctxData = ctxOgg; stb_vorbis_info info = stb_vorbis_get_info((stb_vorbis *)music.ctxData); // Get Ogg file info // OGG bit rate defaults to 16 bit, it's enough for compressed format @@ -1326,6 +1376,10 @@ Music LoadMusicStream(const char *fileName) music.looping = true; // Looping enabled by default musicLoaded = true; } + else + { + stb_vorbis_close(ctxOgg); + } } #endif #if defined(SUPPORT_FILEFORMAT_MP3) @@ -1334,27 +1388,30 @@ Music LoadMusicStream(const char *fileName) drmp3 *ctxMp3 = RL_CALLOC(1, sizeof(drmp3)); int result = drmp3_init_file(ctxMp3, fileName, NULL); - music.ctxType = MUSIC_AUDIO_MP3; - music.ctxData = ctxMp3; - if (result > 0) { + music.ctxType = MUSIC_AUDIO_MP3; + music.ctxData = ctxMp3; music.stream = LoadAudioStream(ctxMp3->sampleRate, 32, ctxMp3->channels); music.frameCount = (unsigned int)drmp3_get_pcm_frame_count(ctxMp3); music.looping = true; // Looping enabled by default musicLoaded = true; } + else + { + RL_FREE(ctxMp3); + } } #endif #if defined(SUPPORT_FILEFORMAT_QOA) else if (IsFileExtension(fileName, ".qoa")) { qoaplay_desc *ctxQoa = qoaplay_open(fileName); - music.ctxType = MUSIC_AUDIO_QOA; - music.ctxData = ctxQoa; - if (ctxQoa->file != NULL) + if (ctxQoa != NULL) { + music.ctxType = MUSIC_AUDIO_QOA; + music.ctxData = ctxQoa; // NOTE: We are loading samples are 32bit float normalized data, so, // we configure the output audio stream to also use float 32bit music.stream = LoadAudioStream(ctxQoa->info.samplerate, 32, ctxQoa->info.channels); @@ -1362,23 +1419,27 @@ Music LoadMusicStream(const char *fileName) music.looping = true; // Looping enabled by default musicLoaded = true; } + else{} //No uninit required } #endif #if defined(SUPPORT_FILEFORMAT_FLAC) else if (IsFileExtension(fileName, ".flac")) { - music.ctxType = MUSIC_AUDIO_FLAC; - music.ctxData = drflac_open_file(fileName, NULL); + drflac *ctxFlac = drflac_open_file(fileName, NULL); - if (music.ctxData != NULL) + if (ctxFlac != NULL) { - drflac *ctxFlac = (drflac *)music.ctxData; - + music.ctxType = MUSIC_AUDIO_FLAC; + music.ctxData = ctxFlac; music.stream = LoadAudioStream(ctxFlac->sampleRate, ctxFlac->bitsPerSample, ctxFlac->channels); music.frameCount = (unsigned int)ctxFlac->totalPCMFrameCount; music.looping = true; // Looping enabled by default musicLoaded = true; } + else + { + drflac_free(ctxFlac, NULL); + } } #endif #if defined(SUPPORT_FILEFORMAT_XM) @@ -1387,11 +1448,10 @@ Music LoadMusicStream(const char *fileName) jar_xm_context_t *ctxXm = NULL; int result = jar_xm_create_context_from_file(&ctxXm, AUDIO.System.device.sampleRate, fileName); - music.ctxType = MUSIC_MODULE_XM; - music.ctxData = ctxXm; - if (result == 0) // XM AUDIO.System.context created successfully { + music.ctxType = MUSIC_MODULE_XM; + music.ctxData = ctxXm; jar_xm_set_max_loop_count(ctxXm, 0); // Set infinite number of loops unsigned int bits = 32; @@ -1402,9 +1462,13 @@ Music LoadMusicStream(const char *fileName) music.stream = LoadAudioStream(AUDIO.System.device.sampleRate, bits, AUDIO_DEVICE_CHANNELS); music.frameCount = (unsigned int)jar_xm_get_remaining_samples(ctxXm); // NOTE: Always 2 channels (stereo) music.looping = true; // Looping enabled by default - jar_xm_reset(ctxXm); // make sure we start at the beginning of the song + jar_xm_reset(ctxXm); // Make sure we start at the beginning of the song musicLoaded = true; } + else + { + jar_xm_free_context(ctxXm); + } } #endif #if defined(SUPPORT_FILEFORMAT_MOD) @@ -1414,47 +1478,27 @@ Music LoadMusicStream(const char *fileName) jar_mod_init(ctxMod); int result = jar_mod_load_file(ctxMod, fileName); - music.ctxType = MUSIC_MODULE_MOD; - music.ctxData = ctxMod; - if (result > 0) { + music.ctxType = MUSIC_MODULE_MOD; + music.ctxData = ctxMod; // NOTE: Only stereo is supported for MOD music.stream = LoadAudioStream(AUDIO.System.device.sampleRate, 16, AUDIO_DEVICE_CHANNELS); music.frameCount = (unsigned int)jar_mod_max_samples(ctxMod); // NOTE: Always 2 channels (stereo) music.looping = true; // Looping enabled by default musicLoaded = true; } + else + { + jar_mod_unload(ctxMod); + RL_FREE(ctxMod); + } } #endif else TRACELOG(LOG_WARNING, "STREAM: [%s] File format not supported", fileName); if (!musicLoaded) { - if (false) { } - #if defined(SUPPORT_FILEFORMAT_WAV) - else if (music.ctxType == MUSIC_AUDIO_WAV) drwav_uninit((drwav *)music.ctxData); - #endif - #if defined(SUPPORT_FILEFORMAT_OGG) - else if (music.ctxType == MUSIC_AUDIO_OGG) stb_vorbis_close((stb_vorbis *)music.ctxData); - #endif - #if defined(SUPPORT_FILEFORMAT_MP3) - else if (music.ctxType == MUSIC_AUDIO_MP3) { drmp3_uninit((drmp3 *)music.ctxData); RL_FREE(music.ctxData); } - #endif - #if defined(SUPPORT_FILEFORMAT_QOA) - else if (music.ctxType == MUSIC_AUDIO_QOA) qoaplay_close((qoaplay_desc *)music.ctxData); - #endif - #if defined(SUPPORT_FILEFORMAT_FLAC) - else if (music.ctxType == MUSIC_AUDIO_FLAC) drflac_free((drflac *)music.ctxData, NULL); - #endif - #if defined(SUPPORT_FILEFORMAT_XM) - else if (music.ctxType == MUSIC_MODULE_XM) jar_xm_free_context((jar_xm_context_t *)music.ctxData); - #endif - #if defined(SUPPORT_FILEFORMAT_MOD) - else if (music.ctxType == MUSIC_MODULE_MOD) { jar_mod_unload((jar_mod_context_t *)music.ctxData); RL_FREE(music.ctxData); } - #endif - - music.ctxData = NULL; TRACELOG(LOG_WARNING, "FILEIO: [%s] Music file could not be opened", fileName); } else @@ -1485,11 +1529,10 @@ Music LoadMusicStreamFromMemory(const char *fileType, const unsigned char *data, bool success = drwav_init_memory(ctxWav, (const void *)data, dataSize, NULL); - music.ctxType = MUSIC_AUDIO_WAV; - music.ctxData = ctxWav; - if (success) { + music.ctxType = MUSIC_AUDIO_WAV; + music.ctxData = ctxWav; int sampleSize = ctxWav->bitsPerSample; if (ctxWav->bitsPerSample == 24) sampleSize = 16; // Forcing conversion to s16 on UpdateMusicStream() @@ -1498,18 +1541,22 @@ Music LoadMusicStreamFromMemory(const char *fileType, const unsigned char *data, music.looping = true; // Looping enabled by default musicLoaded = true; } + else { + drwav_uninit(ctxWav); + RL_FREE(ctxWav); + } } #endif #if defined(SUPPORT_FILEFORMAT_OGG) else if ((strcmp(fileType, ".ogg") == 0) || (strcmp(fileType, ".OGG") == 0)) { // Open ogg audio stream - music.ctxType = MUSIC_AUDIO_OGG; - //music.ctxData = stb_vorbis_open_filename(fileName, NULL, NULL); - music.ctxData = stb_vorbis_open_memory((const unsigned char *)data, dataSize, NULL, NULL); + stb_vorbis* ctxOgg = stb_vorbis_open_memory((const unsigned char*)data, dataSize, NULL, NULL); - if (music.ctxData != NULL) + if (ctxOgg != NULL) { + music.ctxType = MUSIC_AUDIO_OGG; + music.ctxData = ctxOgg; stb_vorbis_info info = stb_vorbis_get_info((stb_vorbis *)music.ctxData); // Get Ogg file info // OGG bit rate defaults to 16 bit, it's enough for compressed format @@ -1520,6 +1567,10 @@ Music LoadMusicStreamFromMemory(const char *fileType, const unsigned char *data, music.looping = true; // Looping enabled by default musicLoaded = true; } + else + { + stb_vorbis_close(ctxOgg); + } } #endif #if defined(SUPPORT_FILEFORMAT_MP3) @@ -1528,27 +1579,35 @@ Music LoadMusicStreamFromMemory(const char *fileType, const unsigned char *data, drmp3 *ctxMp3 = RL_CALLOC(1, sizeof(drmp3)); int success = drmp3_init_memory(ctxMp3, (const void*)data, dataSize, NULL); - music.ctxType = MUSIC_AUDIO_MP3; - music.ctxData = ctxMp3; - if (success) { + music.ctxType = MUSIC_AUDIO_MP3; + music.ctxData = ctxMp3; music.stream = LoadAudioStream(ctxMp3->sampleRate, 32, ctxMp3->channels); music.frameCount = (unsigned int)drmp3_get_pcm_frame_count(ctxMp3); music.looping = true; // Looping enabled by default musicLoaded = true; } + else + { + drmp3_uninit(ctxMp3); + RL_FREE(ctxMp3); + } } #endif #if defined(SUPPORT_FILEFORMAT_QOA) else if ((strcmp(fileType, ".qoa") == 0) || (strcmp(fileType, ".QOA") == 0)) { - qoaplay_desc *ctxQoa = qoaplay_open_memory(data, dataSize); - music.ctxType = MUSIC_AUDIO_QOA; - music.ctxData = ctxQoa; - - if ((ctxQoa->file_data != NULL) && (ctxQoa->file_data_size != 0)) + qoaplay_desc *ctxQoa = NULL; + if ((data != NULL) && (dataSize > 0)) { + ctxQoa = qoaplay_open_memory(data, dataSize); + } + + if (ctxQoa != NULL) + { + music.ctxType = MUSIC_AUDIO_QOA; + music.ctxData = ctxQoa; // NOTE: We are loading samples are 32bit float normalized data, so, // we configure the output audio stream to also use float 32bit music.stream = LoadAudioStream(ctxQoa->info.samplerate, 32, ctxQoa->info.channels); @@ -1556,23 +1615,27 @@ Music LoadMusicStreamFromMemory(const char *fileType, const unsigned char *data, music.looping = true; // Looping enabled by default musicLoaded = true; } + else{} //No uninit required } #endif #if defined(SUPPORT_FILEFORMAT_FLAC) else if ((strcmp(fileType, ".flac") == 0) || (strcmp(fileType, ".FLAC") == 0)) { - music.ctxType = MUSIC_AUDIO_FLAC; - music.ctxData = drflac_open_memory((const void*)data, dataSize, NULL); + drflac *ctxFlac = drflac_open_memory((const void*)data, dataSize, NULL); - if (music.ctxData != NULL) + if (ctxFlac != NULL) { - drflac *ctxFlac = (drflac *)music.ctxData; - + music.ctxType = MUSIC_AUDIO_FLAC; + music.ctxData = ctxFlac; music.stream = LoadAudioStream(ctxFlac->sampleRate, ctxFlac->bitsPerSample, ctxFlac->channels); music.frameCount = (unsigned int)ctxFlac->totalPCMFrameCount; music.looping = true; // Looping enabled by default musicLoaded = true; } + else + { + drflac_free(ctxFlac, NULL); + } } #endif #if defined(SUPPORT_FILEFORMAT_XM) @@ -1583,6 +1646,7 @@ Music LoadMusicStreamFromMemory(const char *fileType, const unsigned char *data, if (result == 0) // XM AUDIO.System.context created successfully { music.ctxType = MUSIC_MODULE_XM; + music.ctxData = ctxXm; jar_xm_set_max_loop_count(ctxXm, 0); // Set infinite number of loops unsigned int bits = 32; @@ -1593,11 +1657,14 @@ Music LoadMusicStreamFromMemory(const char *fileType, const unsigned char *data, music.stream = LoadAudioStream(AUDIO.System.device.sampleRate, bits, 2); music.frameCount = (unsigned int)jar_xm_get_remaining_samples(ctxXm); // NOTE: Always 2 channels (stereo) music.looping = true; // Looping enabled by default - jar_xm_reset(ctxXm); // make sure we start at the beginning of the song + jar_xm_reset(ctxXm); // Make sure we start at the beginning of the song - music.ctxData = ctxXm; musicLoaded = true; } + else + { + jar_xm_free_context(ctxXm); + } } #endif #if defined(SUPPORT_FILEFORMAT_MOD) @@ -1624,15 +1691,18 @@ Music LoadMusicStreamFromMemory(const char *fileType, const unsigned char *data, if (result > 0) { music.ctxType = MUSIC_MODULE_MOD; + music.ctxData = ctxMod; // NOTE: Only stereo is supported for MOD music.stream = LoadAudioStream(AUDIO.System.device.sampleRate, 16, 2); music.frameCount = (unsigned int)jar_mod_max_samples(ctxMod); // NOTE: Always 2 channels (stereo) music.looping = true; // Looping enabled by default musicLoaded = true; - - music.ctxData = ctxMod; - musicLoaded = true; + } + else + { + jar_mod_unload(ctxMod); + RL_FREE(ctxMod); } } #endif @@ -1640,30 +1710,6 @@ Music LoadMusicStreamFromMemory(const char *fileType, const unsigned char *data, if (!musicLoaded) { - if (false) { } -#if defined(SUPPORT_FILEFORMAT_WAV) - else if (music.ctxType == MUSIC_AUDIO_WAV) drwav_uninit((drwav *)music.ctxData); -#endif -#if defined(SUPPORT_FILEFORMAT_OGG) - else if (music.ctxType == MUSIC_AUDIO_OGG) stb_vorbis_close((stb_vorbis *)music.ctxData); -#endif -#if defined(SUPPORT_FILEFORMAT_MP3) - else if (music.ctxType == MUSIC_AUDIO_MP3) { drmp3_uninit((drmp3 *)music.ctxData); RL_FREE(music.ctxData); } -#endif -#if defined(SUPPORT_FILEFORMAT_QOA) - else if (music.ctxType == MUSIC_AUDIO_QOA) qoaplay_close((qoaplay_desc *)music.ctxData); -#endif -#if defined(SUPPORT_FILEFORMAT_FLAC) - else if (music.ctxType == MUSIC_AUDIO_FLAC) drflac_free((drflac *)music.ctxData, NULL); -#endif -#if defined(SUPPORT_FILEFORMAT_XM) - else if (music.ctxType == MUSIC_MODULE_XM) jar_xm_free_context((jar_xm_context_t *)music.ctxData); -#endif -#if defined(SUPPORT_FILEFORMAT_MOD) - else if (music.ctxType == MUSIC_MODULE_MOD) { jar_mod_unload((jar_mod_context_t *)music.ctxData); RL_FREE(music.ctxData); } -#endif - - music.ctxData = NULL; TRACELOG(LOG_WARNING, "FILEIO: Music data could not be loaded"); } else @@ -1721,19 +1767,10 @@ void UnloadMusicStream(Music music) } } -// Start music playing (open stream) +// Start music playing (open stream) from beginning void PlayMusicStream(Music music) { - if (music.stream.buffer != NULL) - { - // For music streams, we need to make sure we maintain the frame cursor position - // This is a hack for this section of code in UpdateMusicStream() - // NOTE: In case window is minimized, music stream is stopped, just make sure to - // play again on window restore: if (IsMusicStreamPlaying(music)) PlayMusicStream(music); - ma_uint32 frameCursorPos = music.stream.buffer->frameCursorPos; - PlayAudioStream(music.stream); // WARNING: This resets the cursor position. - music.stream.buffer->frameCursorPos = frameCursorPos; - } + PlayAudioStream(music.stream); } // Pause music playing @@ -1815,7 +1852,9 @@ void SeekMusicStream(Music music, float position) default: break; } + ma_mutex_lock(&AUDIO.System.lock); music.stream.buffer->framesProcessed = positionInFrames; + ma_mutex_unlock(&AUDIO.System.lock); } // Update (re-fill) music buffers if data already processed @@ -1823,6 +1862,8 @@ void UpdateMusicStream(Music music) { if (music.stream.buffer == NULL) return; + ma_mutex_lock(&AUDIO.System.lock); + unsigned int subBufferSizeInFrames = music.stream.buffer->sizeInFrames/2; // On first call of this function we lazily pre-allocated a temp buffer to read audio files/memory data in @@ -1839,7 +1880,7 @@ void UpdateMusicStream(Music music) // Check both sub-buffers to check if they require refilling for (int i = 0; i < 2; i++) { - if ((music.stream.buffer != NULL) && !music.stream.buffer->isSubBufferProcessed[i]) continue; // No refilling required, move to next sub-buffer + if (!music.stream.buffer->isSubBufferProcessed[i]) continue; // No refilling required, move to next sub-buffer unsigned int framesLeft = music.frameCount - music.stream.buffer->framesProcessed; // Frames left to be processed unsigned int framesToStream = 0; // Total frames to be streamed @@ -1958,7 +1999,7 @@ void UpdateMusicStream(Music music) default: break; } - UpdateAudioStream(music.stream, AUDIO.System.pcmBuffer, framesToStream); + UpdateAudioStreamInLockedState(music.stream, AUDIO.System.pcmBuffer, framesToStream); music.stream.buffer->framesProcessed = music.stream.buffer->framesProcessed%music.frameCount; @@ -1966,6 +2007,7 @@ void UpdateMusicStream(Music music) { if (!music.looping) { + ma_mutex_unlock(&AUDIO.System.lock); // Streaming is ending, we filled latest frames from input StopMusicStream(music); return; @@ -1973,9 +2015,7 @@ void UpdateMusicStream(Music music) } } - // NOTE: In case window is minimized, music stream is stopped, - // just make sure to play again on window restore - if (IsMusicStreamPlaying(music)) PlayMusicStream(music); + ma_mutex_unlock(&AUDIO.System.lock); } // Check if any music is playing @@ -2029,6 +2069,7 @@ float GetMusicTimePlayed(Music music) else #endif { + ma_mutex_lock(&AUDIO.System.lock); //ma_uint32 frameSizeInBytes = ma_get_bytes_per_sample(music.stream.buffer->dsp.formatConverterIn.config.formatIn)*music.stream.buffer->dsp.formatConverterIn.config.channels; int framesProcessed = (int)music.stream.buffer->framesProcessed; int subBufferSize = (int)music.stream.buffer->sizeInFrames/2; @@ -2038,6 +2079,7 @@ float GetMusicTimePlayed(Music music) int framesPlayed = (framesProcessed - framesInFirstBuffer - framesInSecondBuffer + framesSentToMix)%(int)music.frameCount; if (framesPlayed < 0) framesPlayed += music.frameCount; secondsPlayed = (float)framesPlayed/music.stream.sampleRate; + ma_mutex_unlock(&AUDIO.System.lock); } } @@ -2098,51 +2140,9 @@ void UnloadAudioStream(AudioStream stream) // NOTE 2: To dequeue a buffer it needs to be processed: IsAudioStreamProcessed() void UpdateAudioStream(AudioStream stream, const void *data, int frameCount) { - if (stream.buffer != NULL) - { - if (stream.buffer->isSubBufferProcessed[0] || stream.buffer->isSubBufferProcessed[1]) - { - ma_uint32 subBufferToUpdate = 0; - - if (stream.buffer->isSubBufferProcessed[0] && stream.buffer->isSubBufferProcessed[1]) - { - // Both buffers are available for updating. - // Update the first one and make sure the cursor is moved back to the front. - subBufferToUpdate = 0; - stream.buffer->frameCursorPos = 0; - } - else - { - // Just update whichever sub-buffer is processed. - subBufferToUpdate = (stream.buffer->isSubBufferProcessed[0])? 0 : 1; - } - - ma_uint32 subBufferSizeInFrames = stream.buffer->sizeInFrames/2; - unsigned char *subBuffer = stream.buffer->data + ((subBufferSizeInFrames*stream.channels*(stream.sampleSize/8))*subBufferToUpdate); - - // Total frames processed in buffer is always the complete size, filled with 0 if required - stream.buffer->framesProcessed += subBufferSizeInFrames; - - // Does this API expect a whole buffer to be updated in one go? - // Assuming so, but if not will need to change this logic. - if (subBufferSizeInFrames >= (ma_uint32)frameCount) - { - ma_uint32 framesToWrite = (ma_uint32)frameCount; - - ma_uint32 bytesToWrite = framesToWrite*stream.channels*(stream.sampleSize/8); - memcpy(subBuffer, data, bytesToWrite); - - // Any leftover frames should be filled with zeros. - ma_uint32 leftoverFrameCount = subBufferSizeInFrames - framesToWrite; - - if (leftoverFrameCount > 0) memset(subBuffer + bytesToWrite, 0, leftoverFrameCount*stream.channels*(stream.sampleSize/8)); - - stream.buffer->isSubBufferProcessed[subBufferToUpdate] = false; - } - else TRACELOG(LOG_WARNING, "STREAM: Attempting to write too many frames to buffer"); - } - else TRACELOG(LOG_WARNING, "STREAM: Buffer not available for updating"); - } + ma_mutex_lock(&AUDIO.System.lock); + UpdateAudioStreamInLockedState(stream, data, frameCount); + ma_mutex_unlock(&AUDIO.System.lock); } // Check if any audio stream buffers requires refill @@ -2150,7 +2150,11 @@ bool IsAudioStreamProcessed(AudioStream stream) { if (stream.buffer == NULL) return false; - return (stream.buffer->isSubBufferProcessed[0] || stream.buffer->isSubBufferProcessed[1]); + bool result = false; + ma_mutex_lock(&AUDIO.System.lock); + result = stream.buffer->isSubBufferProcessed[0] || stream.buffer->isSubBufferProcessed[1]; + ma_mutex_unlock(&AUDIO.System.lock); + return result; } // Play audio stream @@ -2171,7 +2175,7 @@ void ResumeAudioStream(AudioStream stream) ResumeAudioBuffer(stream.buffer); } -// Check if audio stream is playing. +// Check if audio stream is playing bool IsAudioStreamPlaying(AudioStream stream) { return IsAudioBufferPlaying(stream.buffer); @@ -2210,12 +2214,17 @@ void SetAudioStreamBufferSizeDefault(int size) // Audio thread callback to request new data void SetAudioStreamCallback(AudioStream stream, AudioCallback callback) { - if (stream.buffer != NULL) stream.buffer->callback = callback; + if (stream.buffer != NULL) + { + ma_mutex_lock(&AUDIO.System.lock); + stream.buffer->callback = callback; + ma_mutex_unlock(&AUDIO.System.lock); + } } -// Add processor to audio stream. Contrary to buffers, the order of processors is important. +// Add processor to audio stream. Contrary to buffers, the order of processors is important // The new processor must be added at the end. As there aren't supposed to be a lot of processors attached to -// a given stream, we iterate through the list to find the end. That way we don't need a pointer to the last element. +// a given stream, we iterate through the list to find the end. That way we don't need a pointer to the last element void AttachAudioStreamProcessor(AudioStream stream, AudioCallback process) { ma_mutex_lock(&AUDIO.System.lock); @@ -2330,7 +2339,7 @@ static void OnLog(void *pUserData, ma_uint32 level, const char *pMessage) TRACELOG(LOG_WARNING, "miniaudio: %s", pMessage); // All log messages from miniaudio are errors } -// Reads audio data from an AudioBuffer object in internal format. +// Reads audio data from an AudioBuffer object in internal format static ma_uint32 ReadAudioBufferFramesInInternalFormat(AudioBuffer *audioBuffer, void *framesOut, ma_uint32 frameCount) { // Using audio buffer callback @@ -2404,7 +2413,7 @@ static ma_uint32 ReadAudioBufferFramesInInternalFormat(AudioBuffer *audioBuffer, // We need to break from this loop if we're not looping if (!audioBuffer->looping) { - StopAudioBuffer(audioBuffer); + StopAudioBufferInLockedState(audioBuffer); break; } } @@ -2418,20 +2427,20 @@ static ma_uint32 ReadAudioBufferFramesInInternalFormat(AudioBuffer *audioBuffer, // For static buffers we can fill the remaining frames with silence for safety, but we don't want // to report those frames as "read". The reason for this is that the caller uses the return value - // to know whether a non-looping sound has finished playback. + // to know whether a non-looping sound has finished playback if (audioBuffer->usage != AUDIO_BUFFER_USAGE_STATIC) framesRead += totalFramesRemaining; } return framesRead; } -// Reads audio data from an AudioBuffer object in device format. Returned data will be in a format appropriate for mixing. +// Reads audio data from an AudioBuffer object in device format, returned data will be in a format appropriate for mixing static ma_uint32 ReadAudioBufferFramesInMixingFormat(AudioBuffer *audioBuffer, float *framesOut, ma_uint32 frameCount) { // What's going on here is that we're continuously converting data from the AudioBuffer's internal format to the mixing format, which // should be defined by the output format of the data converter. We do this until frameCount frames have been output. The important // detail to remember here is that we never, ever attempt to read more input data than is required for the specified number of output - // frames. This can be achieved with ma_data_converter_get_required_input_frame_count(). + // frames. This can be achieved with ma_data_converter_get_required_input_frame_count() ma_uint8 inputBuffer[4096] = { 0 }; ma_uint32 inputBufferFrameCap = sizeof(inputBuffer)/ma_get_bytes_per_frame(audioBuffer->converter.formatIn, audioBuffer->converter.channelsIn); @@ -2540,7 +2549,7 @@ static void OnSendAudioDataToDevice(ma_device *pDevice, void *pFramesOut, const { if (!audioBuffer->looping) { - StopAudioBuffer(audioBuffer); + StopAudioBufferInLockedState(audioBuffer); break; } else @@ -2613,6 +2622,83 @@ static void MixAudioFrames(float *framesOut, const float *framesIn, ma_uint32 fr } } +// Check if an audio buffer is playing, assuming the audio system mutex has been locked +static bool IsAudioBufferPlayingInLockedState(AudioBuffer *buffer) +{ + bool result = false; + + if (buffer != NULL) result = (buffer->playing && !buffer->paused); + + return result; +} + +// Stop an audio buffer, assuming the audio system mutex has been locked +static void StopAudioBufferInLockedState(AudioBuffer *buffer) +{ + if (buffer != NULL) + { + if (IsAudioBufferPlayingInLockedState(buffer)) + { + buffer->playing = false; + buffer->paused = false; + buffer->frameCursorPos = 0; + buffer->framesProcessed = 0; + buffer->isSubBufferProcessed[0] = true; + buffer->isSubBufferProcessed[1] = true; + } + } +} + +// Update audio stream, assuming the audio system mutex has been locked +static void UpdateAudioStreamInLockedState(AudioStream stream, const void *data, int frameCount) +{ + if (stream.buffer != NULL) + { + if (stream.buffer->isSubBufferProcessed[0] || stream.buffer->isSubBufferProcessed[1]) + { + ma_uint32 subBufferToUpdate = 0; + + if (stream.buffer->isSubBufferProcessed[0] && stream.buffer->isSubBufferProcessed[1]) + { + // Both buffers are available for updating + // Update the first one and make sure the cursor is moved back to the front + subBufferToUpdate = 0; + stream.buffer->frameCursorPos = 0; + } + else + { + // Just update whichever sub-buffer is processed + subBufferToUpdate = (stream.buffer->isSubBufferProcessed[0])? 0 : 1; + } + + ma_uint32 subBufferSizeInFrames = stream.buffer->sizeInFrames/2; + unsigned char *subBuffer = stream.buffer->data + ((subBufferSizeInFrames*stream.channels*(stream.sampleSize/8))*subBufferToUpdate); + + // Total frames processed in buffer is always the complete size, filled with 0 if required + stream.buffer->framesProcessed += subBufferSizeInFrames; + + // Does this API expect a whole buffer to be updated in one go? + // Assuming so, but if not will need to change this logic + if (subBufferSizeInFrames >= (ma_uint32)frameCount) + { + ma_uint32 framesToWrite = (ma_uint32)frameCount; + + ma_uint32 bytesToWrite = framesToWrite*stream.channels*(stream.sampleSize/8); + memcpy(subBuffer, data, bytesToWrite); + + // Any leftover frames should be filled with zeros + ma_uint32 leftoverFrameCount = subBufferSizeInFrames - framesToWrite; + + if (leftoverFrameCount > 0) memset(subBuffer + bytesToWrite, 0, leftoverFrameCount*stream.channels*(stream.sampleSize/8)); + + stream.buffer->isSubBufferProcessed[subBufferToUpdate] = false; + } + else TRACELOG(LOG_WARNING, "STREAM: Attempting to write too many frames to buffer"); + } + else TRACELOG(LOG_WARNING, "STREAM: Buffer not available for updating"); + } +} + // Some required functions for audio standalone module version #if defined(RAUDIO_STANDALONE) // Check file extension @@ -2639,6 +2725,50 @@ static const char *GetFileExtension(const char *fileName) return dot; } +// String pointer reverse break: returns right-most occurrence of charset in s +static const char *strprbrk(const char *s, const char *charset) +{ + const char *latestMatch = NULL; + for (; s = strpbrk(s, charset), s != NULL; latestMatch = s++) { } + return latestMatch; +} + +// Get pointer to filename for a path string +static const char *GetFileName(const char *filePath) +{ + const char *fileName = NULL; + if (filePath != NULL) fileName = strprbrk(filePath, "\\/"); + + if (!fileName) return filePath; + + return fileName + 1; +} + +// Get filename string without extension (uses static string) +static const char *GetFileNameWithoutExt(const char *filePath) +{ + #define MAX_FILENAMEWITHOUTEXT_LENGTH 256 + + static char fileName[MAX_FILENAMEWITHOUTEXT_LENGTH] = { 0 }; + memset(fileName, 0, MAX_FILENAMEWITHOUTEXT_LENGTH); + + if (filePath != NULL) strcpy(fileName, GetFileName(filePath)); // Get filename with extension + + int size = (int)strlen(fileName); // Get size in bytes + + for (int i = 0; (i < size) && (i < MAX_FILENAMEWITHOUTEXT_LENGTH); i++) + { + if (fileName[i] == '.') + { + // NOTE: We break on first '.' found + fileName[i] = '\0'; + break; + } + } + + return fileName; +} + // Load data from file into a buffer static unsigned char *LoadFileData(const char *fileName, int *dataSize) { @@ -2696,9 +2826,19 @@ static bool SaveFileData(const char *fileName, void *data, int dataSize) fclose(file); } - else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to open file", fileName); + else + { + TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to open file", fileName); + return false; + } } - else TRACELOG(LOG_WARNING, "FILEIO: File name provided is not valid"); + else + { + TRACELOG(LOG_WARNING, "FILEIO: File name provided is not valid"); + return false; + } + + return true; } // Save text data to file (write), string must be '\0' terminated @@ -2717,9 +2857,19 @@ static bool SaveFileText(const char *fileName, char *text) fclose(file); } - else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to open text file", fileName); + else + { + TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to open text file", fileName); + return false; + } } - else TRACELOG(LOG_WARNING, "FILEIO: File name provided is not valid"); + else + { + TRACELOG(LOG_WARNING, "FILEIO: File name provided is not valid"); + return false; + } + + return true; } #endif diff --git a/raylib/raylib.h b/raylib/raylib.h index 1c4c4a0..035f6f2 100644 --- a/raylib/raylib.h +++ b/raylib/raylib.h @@ -1,6 +1,6 @@ /********************************************************************************************** * -* raylib v5.0 - A simple and easy-to-use library to enjoy videogames programming (www.raylib.com) +* raylib v5.1-dev - A simple and easy-to-use library to enjoy videogames programming (www.raylib.com) * * FEATURES: * - NO external dependencies, all required libraries included with raylib @@ -57,7 +57,7 @@ * raylib is licensed under an unmodified zlib/libpng license, which is an OSI-certified, * BSD-like license that allows static linking with closed source software: * -* Copyright (c) 2013-2023 Ramon Santamaria (@raysan5) +* Copyright (c) 2013-2024 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. @@ -82,21 +82,26 @@ #include // Required for: va_list - Only used by TraceLogCallback #define RAYLIB_VERSION_MAJOR 5 -#define RAYLIB_VERSION_MINOR 0 +#define RAYLIB_VERSION_MINOR 1 #define RAYLIB_VERSION_PATCH 0 -#define RAYLIB_VERSION "5.0" +#define RAYLIB_VERSION "5.1-dev" -// Function specifiers in case library is build/used as a shared library (Windows) +// Function specifiers in case library is build/used as a shared library // NOTE: Microsoft specifiers to tell compiler that symbols are imported/exported from a .dll +// NOTE: visibility("default") attribute makes symbols "visible" when compiled with -fvisibility=hidden #if defined(_WIN32) + #if defined(__TINYC__) + #define __declspec(x) __attribute__((x)) + #endif #if defined(BUILD_LIBTYPE_SHARED) - #if defined(__TINYC__) - #define __declspec(x) __attribute__((x)) - #endif #define RLAPI __declspec(dllexport) // We are building the library as a Win32 shared library (.dll) #elif defined(USE_LIBTYPE_SHARED) #define RLAPI __declspec(dllimport) // We are using the library as a Win32 shared library (.dll) #endif +#else + #if defined(BUILD_LIBTYPE_SHARED) + #define RLAPI __attribute__((visibility("default"))) // We are building as a Unix shared library (.so/.dylib) + #endif #endif #ifndef RLAPI @@ -479,7 +484,6 @@ typedef struct VrDeviceInfo { int vResolution; // Vertical resolution in pixels float hScreenSize; // Horizontal size in meters float vScreenSize; // Vertical size in meters - float vScreenCenter; // Screen center in meters float eyeToScreenDistance; // Distance between eye and display in meters float lensSeparationDistance; // Lens separation distance in meters float interpupillaryDistance; // IPD (distance between pupils) in meters @@ -673,7 +677,7 @@ typedef enum { KEY_KP_EQUAL = 336, // Key: Keypad = // Android key buttons KEY_BACK = 4, // Key: Android back button - KEY_MENU = 82, // Key: Android menu button + KEY_MENU = 5, // Key: Android menu button KEY_VOLUME_UP = 24, // Key: Android volume up button KEY_VOLUME_DOWN = 25 // Key: Android volume down button } KeyboardKey; @@ -717,12 +721,12 @@ typedef enum { GAMEPAD_BUTTON_LEFT_FACE_DOWN, // Gamepad left DPAD down button GAMEPAD_BUTTON_LEFT_FACE_LEFT, // Gamepad left DPAD left button GAMEPAD_BUTTON_RIGHT_FACE_UP, // Gamepad right button up (i.e. PS3: Triangle, Xbox: Y) - GAMEPAD_BUTTON_RIGHT_FACE_RIGHT, // Gamepad right button right (i.e. PS3: Square, Xbox: X) + GAMEPAD_BUTTON_RIGHT_FACE_RIGHT, // Gamepad right button right (i.e. PS3: Circle, Xbox: B) GAMEPAD_BUTTON_RIGHT_FACE_DOWN, // Gamepad right button down (i.e. PS3: Cross, Xbox: A) - GAMEPAD_BUTTON_RIGHT_FACE_LEFT, // Gamepad right button left (i.e. PS3: Circle, Xbox: B) + GAMEPAD_BUTTON_RIGHT_FACE_LEFT, // Gamepad right button left (i.e. PS3: Square, Xbox: X) GAMEPAD_BUTTON_LEFT_TRIGGER_1, // Gamepad top/back trigger left (first), it could be a trailing button GAMEPAD_BUTTON_LEFT_TRIGGER_2, // Gamepad top/back trigger left (second), it could be a trailing button - GAMEPAD_BUTTON_RIGHT_TRIGGER_1, // Gamepad top/back trigger right (one), it could be a trailing button + GAMEPAD_BUTTON_RIGHT_TRIGGER_1, // Gamepad top/back trigger right (first), it could be a trailing button GAMEPAD_BUTTON_RIGHT_TRIGGER_2, // Gamepad top/back trigger right (second), it could be a trailing button GAMEPAD_BUTTON_MIDDLE_LEFT, // Gamepad center buttons, left one (i.e. PS3: Select) GAMEPAD_BUTTON_MIDDLE, // Gamepad center buttons, middle one (i.e. PS3: PS, Xbox: XBOX) @@ -909,11 +913,11 @@ typedef enum { // Camera system modes typedef enum { - CAMERA_CUSTOM = 0, // Custom camera - CAMERA_FREE, // Free camera - CAMERA_ORBITAL, // Orbital camera - CAMERA_FIRST_PERSON, // First person camera - CAMERA_THIRD_PERSON // Third person camera + CAMERA_CUSTOM = 0, // Camera custom, controlled by user (UpdateCamera() does nothing) + CAMERA_FREE, // Camera free mode + CAMERA_ORBITAL, // Camera orbital, around target, zoom supported + CAMERA_FIRST_PERSON, // Camera first person + CAMERA_THIRD_PERSON // Camera third person } CameraMode; // Camera projection @@ -1045,13 +1049,15 @@ RLAPI void SetShaderValueTexture(Shader shader, int locIndex, Texture2D texture) RLAPI void UnloadShader(Shader shader); // Unload shader from GPU memory (VRAM) // Screen-space-related functions -RLAPI Ray GetMouseRay(Vector2 mousePosition, Camera camera); // Get a ray trace from mouse position -RLAPI Matrix GetCameraMatrix(Camera camera); // Get camera transform matrix (view matrix) -RLAPI Matrix GetCameraMatrix2D(Camera2D camera); // Get camera 2d transform matrix -RLAPI Vector2 GetWorldToScreen(Vector3 position, Camera camera); // Get the screen space position for a 3d world space position -RLAPI Vector2 GetScreenToWorld2D(Vector2 position, Camera2D camera); // Get the world space position for a 2d camera screen space position +#define GetMouseRay GetScreenToWorldRay // Compatibility hack for previous raylib versions +RLAPI Ray GetScreenToWorldRay(Vector2 position, Camera camera); // Get a ray trace from screen position (i.e mouse) +RLAPI Ray GetScreenToWorldRayEx(Vector2 position, Camera camera, int width, int height); // Get a ray trace from screen position (i.e mouse) in a viewport +RLAPI Vector2 GetWorldToScreen(Vector3 position, Camera camera); // Get the screen space position for a 3d world space position RLAPI Vector2 GetWorldToScreenEx(Vector3 position, Camera camera, int width, int height); // Get size position for a 3d world space position -RLAPI Vector2 GetWorldToScreen2D(Vector2 position, Camera2D camera); // Get the screen space position for a 2d camera world space position +RLAPI Vector2 GetWorldToScreen2D(Vector2 position, Camera2D camera); // Get the screen space position for a 2d camera world space position +RLAPI Vector2 GetScreenToWorld2D(Vector2 position, Camera2D camera); // Get the world space position for a 2d camera screen space position +RLAPI Matrix GetCameraMatrix(Camera camera); // Get camera transform matrix (view matrix) +RLAPI Matrix GetCameraMatrix2D(Camera2D camera); // Get camera 2d transform matrix // Timing-related functions RLAPI void SetTargetFPS(int fps); // Set target FPS (maximum) @@ -1134,7 +1140,7 @@ RLAPI unsigned char *DecodeDataBase64(const unsigned char *data, int *outputSize // Automation events functionality RLAPI AutomationEventList LoadAutomationEventList(const char *fileName); // Load automation events list from file, NULL for empty list, capacity = MAX_AUTOMATION_EVENTS -RLAPI void UnloadAutomationEventList(AutomationEventList *list); // Unload automation events list from file +RLAPI void UnloadAutomationEventList(AutomationEventList list); // Unload automation events list from file RLAPI bool ExportAutomationEventList(AutomationEventList list, const char *fileName); // Export automation events list as text file RLAPI void SetAutomationEventList(AutomationEventList *list); // Set automation event list to record to RLAPI void SetAutomationEventBaseFrame(int frame); // Set automation event internal base frame to start recording @@ -1157,16 +1163,17 @@ RLAPI int GetCharPressed(void); // Get char presse RLAPI void SetExitKey(int key); // Set a custom key to exit program (default is ESC) // Input-related functions: gamepads -RLAPI bool IsGamepadAvailable(int gamepad); // Check if a gamepad is available -RLAPI const char *GetGamepadName(int gamepad); // Get gamepad internal name id -RLAPI bool IsGamepadButtonPressed(int gamepad, int button); // Check if a gamepad button has been pressed once -RLAPI bool IsGamepadButtonDown(int gamepad, int button); // Check if a gamepad button is being pressed -RLAPI bool IsGamepadButtonReleased(int gamepad, int button); // Check if a gamepad button has been released once -RLAPI bool IsGamepadButtonUp(int gamepad, int button); // Check if a gamepad button is NOT being pressed -RLAPI int GetGamepadButtonPressed(void); // Get the last gamepad button pressed -RLAPI int GetGamepadAxisCount(int gamepad); // Get gamepad axis count for a gamepad -RLAPI float GetGamepadAxisMovement(int gamepad, int axis); // Get axis movement value for a gamepad axis -RLAPI int SetGamepadMappings(const char *mappings); // Set internal gamepad mappings (SDL_GameControllerDB) +RLAPI bool IsGamepadAvailable(int gamepad); // Check if a gamepad is available +RLAPI const char *GetGamepadName(int gamepad); // Get gamepad internal name id +RLAPI bool IsGamepadButtonPressed(int gamepad, int button); // Check if a gamepad button has been pressed once +RLAPI bool IsGamepadButtonDown(int gamepad, int button); // Check if a gamepad button is being pressed +RLAPI bool IsGamepadButtonReleased(int gamepad, int button); // Check if a gamepad button has been released once +RLAPI bool IsGamepadButtonUp(int gamepad, int button); // Check if a gamepad button is NOT being pressed +RLAPI int GetGamepadButtonPressed(void); // Get the last gamepad button pressed +RLAPI int GetGamepadAxisCount(int gamepad); // Get gamepad axis count for a gamepad +RLAPI float GetGamepadAxisMovement(int gamepad, int axis); // Get axis movement value for a gamepad axis +RLAPI int SetGamepadMappings(const char *mappings); // Set internal gamepad mappings (SDL_GameControllerDB) +RLAPI void SetGamepadVibration(int gamepad, float leftMotor, float rightMotor); // Set gamepad vibration for both motors // Input-related functions: mouse RLAPI bool IsMouseButtonPressed(int button); // Check if a mouse button has been pressed once @@ -1216,6 +1223,8 @@ RLAPI void UpdateCameraPro(Camera *camera, Vector3 movement, Vector3 rotation, f // NOTE: It can be useful when using basic shapes and one single font, // defining a font char white rectangle would allow drawing everything in a single draw call RLAPI void SetShapesTexture(Texture2D texture, Rectangle source); // Set texture and rectangle to be used on shapes drawing +RLAPI Texture2D GetShapesTexture(void); // Get texture that is used for shapes drawing +RLAPI Rectangle GetShapesTextureRectangle(void); // Get texture source rectangle that is used for shapes drawing // Basic shapes drawing functions RLAPI void DrawPixel(int posX, int posY, Color color); // Draw a pixel @@ -1246,7 +1255,8 @@ RLAPI void DrawRectangleGradientEx(Rectangle rec, Color col1, Color col2, Color RLAPI void DrawRectangleLines(int posX, int posY, int width, int height, Color color); // Draw rectangle outline RLAPI void DrawRectangleLinesEx(Rectangle rec, float lineThick, Color color); // Draw rectangle outline with extended parameters RLAPI void DrawRectangleRounded(Rectangle rec, float roundness, int segments, Color color); // Draw rectangle with rounded edges -RLAPI void DrawRectangleRoundedLines(Rectangle rec, float roundness, int segments, float lineThick, Color color); // Draw rectangle with rounded edges outline +RLAPI void DrawRectangleRoundedLines(Rectangle rec, float roundness, int segments, Color color); // Draw rectangle lines with rounded edges +RLAPI void DrawRectangleRoundedLinesEx(Rectangle rec, float roundness, int segments, float lineThick, Color color); // Draw rectangle with rounded edges outline RLAPI void DrawTriangle(Vector2 v1, Vector2 v2, Vector2 v3, Color color); // Draw a color-filled triangle (vertex in counter-clockwise order!) RLAPI void DrawTriangleLines(Vector2 v1, Vector2 v2, Vector2 v3, Color color); // Draw triangle outline (vertex in counter-clockwise order!) RLAPI void DrawTriangleFan(Vector2 *points, int pointCount, Color color); // Draw a triangle fan defined by points (first vertex is the center) @@ -1296,6 +1306,7 @@ RLAPI Image LoadImage(const char *fileName); RLAPI Image LoadImageRaw(const char *fileName, int width, int height, int format, int headerSize); // Load image from RAW file data RLAPI Image LoadImageSvg(const char *fileNameOrString, int width, int height); // Load image from SVG file data or string with specified size RLAPI Image LoadImageAnim(const char *fileName, int *frames); // Load image sequence from file (frames appended to image.data) +RLAPI Image LoadImageAnimFromMemory(const char *fileType, const unsigned char *fileData, int dataSize, int *frames); // Load image sequence from memory buffer RLAPI Image LoadImageFromMemory(const char *fileType, const unsigned char *fileData, int dataSize); // Load image from memory buffer, fileType refers to extension: i.e. '.png' RLAPI Image LoadImageFromTexture(Texture2D texture); // Load image from GPU texture data RLAPI Image LoadImageFromScreen(void); // Load image from screen buffer and (screenshot) @@ -1329,6 +1340,7 @@ RLAPI void ImageAlphaClear(Image *image, Color color, float threshold); RLAPI void ImageAlphaMask(Image *image, Image alphaMask); // Apply alpha mask to image RLAPI void ImageAlphaPremultiply(Image *image); // Premultiply alpha channel RLAPI void ImageBlurGaussian(Image *image, int blurSize); // Apply Gaussian blur using a box blur approximation +RLAPI void ImageKernelConvolution(Image *image, float* kernel, int kernelSize); // Apply Custom Square image convolution kernel RLAPI void ImageResize(Image *image, int newWidth, int newHeight); // Resize image (Bicubic scaling algorithm) RLAPI void ImageResizeNN(Image *image, int newWidth,int newHeight); // Resize image (Nearest-Neighbor scaling algorithm) RLAPI void ImageResizeCanvas(Image *image, int newWidth, int newHeight, int offsetX, int offsetY, Color fill); // Resize canvas and fill with color @@ -1398,8 +1410,9 @@ RLAPI void DrawTexturePro(Texture2D texture, Rectangle source, Rectangle dest, V RLAPI void DrawTextureNPatch(Texture2D texture, NPatchInfo nPatchInfo, Rectangle dest, Vector2 origin, float rotation, Color tint); // Draws a texture (or part of it) that stretches or shrinks nicely // Color/pixel related functions +RLAPI bool ColorIsEqual(Color col1, Color col2); // Check if two colors are equal RLAPI Color Fade(Color color, float alpha); // Get color with alpha applied, alpha goes from 0.0f to 1.0f -RLAPI int ColorToInt(Color color); // Get hexadecimal value for a Color +RLAPI int ColorToInt(Color color); // Get hexadecimal value for a Color (0xRRGGBBAA) RLAPI Vector4 ColorNormalize(Color color); // Get Color normalized as float [0..1] RLAPI Color ColorFromNormalized(Vector4 normalized); // Get Color from normalized values [0..1] RLAPI Vector3 ColorToHSV(Color color); // Get HSV values for a Color, hue [0..360], saturation/value [0..1] @@ -1465,7 +1478,7 @@ RLAPI bool TextIsEqual(const char *text1, const char *text2); RLAPI unsigned int TextLength(const char *text); // Get text length, checks for '\0' ending RLAPI const char *TextFormat(const char *text, ...); // Text formatting with variables (sprintf() style) RLAPI const char *TextSubtext(const char *text, int position, int length); // Get a piece of a text string -RLAPI char *TextReplace(char *text, const char *replace, const char *by); // Replace text string (WARNING: memory must be freed!) +RLAPI char *TextReplace(const char *text, const char *replace, const char *by); // Replace text string (WARNING: memory must be freed!) RLAPI char *TextInsert(const char *text, const char *insert, int position); // Insert text in a position (WARNING: memory must be freed!) RLAPI const char *TextJoin(const char **textList, int count, const char *delimiter); // Join text strings with delimiter RLAPI const char **TextSplit(const char *text, char delimiter, int *count); // Split text into multiple strings @@ -1475,6 +1488,7 @@ RLAPI const char *TextToUpper(const char *text); // Get upp RLAPI const char *TextToLower(const char *text); // Get lower case version of provided string RLAPI const char *TextToPascal(const char *text); // Get Pascal case notation version of provided string RLAPI int TextToInteger(const char *text); // Get integer value from text (negative values not supported) +RLAPI float TextToFloat(const char *text); // Get float value from text (negative values not supported) //------------------------------------------------------------------------------------ // Basic 3d Shapes Drawing Functions (Module: models) @@ -1530,9 +1544,10 @@ RLAPI void UpdateMeshBuffer(Mesh mesh, int index, const void *data, int dataSize RLAPI void UnloadMesh(Mesh mesh); // Unload mesh data from CPU and GPU RLAPI void DrawMesh(Mesh mesh, Material material, Matrix transform); // Draw a 3d mesh with material and transform RLAPI void DrawMeshInstanced(Mesh mesh, Material material, const Matrix *transforms, int instances); // Draw multiple mesh instances with material and different transforms -RLAPI bool ExportMesh(Mesh mesh, const char *fileName); // Export mesh data to file, returns true on success RLAPI BoundingBox GetMeshBoundingBox(Mesh mesh); // Compute mesh bounding box limits RLAPI void GenMeshTangents(Mesh *mesh); // Compute mesh tangents +RLAPI bool ExportMesh(Mesh mesh, const char *fileName); // Export mesh data to file, returns true on success +RLAPI bool ExportMeshAsCode(Mesh mesh, const char *fileName); // Export mesh as code file (.h) defining multiple arrays of vertex attributes // Mesh generation functions RLAPI Mesh GenMeshPoly(int sides, float radius); // Generate polygonal mesh @@ -1649,10 +1664,10 @@ RLAPI void SetAudioStreamPan(AudioStream stream, float pan); // Set pan RLAPI void SetAudioStreamBufferSizeDefault(int size); // Default size for new audio streams RLAPI void SetAudioStreamCallback(AudioStream stream, AudioCallback callback); // Audio thread callback to request new data -RLAPI void AttachAudioStreamProcessor(AudioStream stream, AudioCallback processor); // Attach audio stream processor to stream, receives the samples as s +RLAPI void AttachAudioStreamProcessor(AudioStream stream, AudioCallback processor); // Attach audio stream processor to stream, receives the samples as 'float' RLAPI void DetachAudioStreamProcessor(AudioStream stream, AudioCallback processor); // Detach audio stream processor from stream -RLAPI void AttachAudioMixedProcessor(AudioCallback processor); // Attach audio stream processor to the entire audio pipeline, receives the samples as s +RLAPI void AttachAudioMixedProcessor(AudioCallback processor); // Attach audio stream processor to the entire audio pipeline, receives the samples as 'float' RLAPI void DetachAudioMixedProcessor(AudioCallback processor); // Detach audio stream processor from the entire audio pipeline #if defined(__cplusplus) diff --git a/raylib/raymath.h b/raylib/raymath.h index ff60170..19625f1 100644 --- a/raylib/raymath.h +++ b/raylib/raymath.h @@ -30,7 +30,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2015-2023 Ramon Santamaria (@raysan5) +* Copyright (c) 2015-2024 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. @@ -59,7 +59,9 @@ // Function specifiers definition #if defined(RAYMATH_IMPLEMENTATION) #if defined(_WIN32) && defined(BUILD_LIBTYPE_SHARED) - #define RMAPI __declspec(dllexport) extern inline // We are building raylib as a Win32 shared library (.dll). + #define RMAPI __declspec(dllexport) extern inline // We are building raylib as a Win32 shared library (.dll) + #elif defined(BUILD_LIBTYPE_SHARED) + #define RMAPI __attribute__((visibility("default"))) // We are building raylib as a Unix shared library (.so/.dylib) #elif defined(_WIN32) && defined(USE_LIBTYPE_SHARED) #define RMAPI __declspec(dllimport) // We are using raylib as a Win32 shared library (.dll) #else @@ -163,7 +165,7 @@ typedef struct float16 { float v[16]; } float16; -#include // Required for: sinf(), cosf(), tan(), atan2f(), sqrtf(), floor(), fminf(), fmaxf(), fabs() +#include // Required for: sinf(), cosf(), tan(), atan2f(), sqrtf(), floor(), fminf(), fmaxf(), fabsf() //---------------------------------------------------------------------------------- // Module Functions Definition - Utils math @@ -172,7 +174,7 @@ typedef struct float16 { // Clamp float value RMAPI float Clamp(float value, float min, float max) { - float result = (value < min)? min : value; + float result = (value < min) ? min : value; if (result > max) result = max; @@ -429,6 +431,28 @@ RMAPI Vector2 Vector2Reflect(Vector2 v, Vector2 normal) return result; } +// Get min value for each pair of components +RMAPI Vector2 Vector2Min(Vector2 v1, Vector2 v2) +{ + Vector2 result = { 0 }; + + result.x = fminf(v1.x, v2.x); + result.y = fminf(v1.y, v2.y); + + return result; +} + +// Get max value for each pair of components +RMAPI Vector2 Vector2Max(Vector2 v1, Vector2 v2) +{ + Vector2 result = { 0 }; + + result.x = fmaxf(v1.x, v2.x); + result.y = fmaxf(v1.y, v2.y); + + return result; +} + // Rotate vector by angle RMAPI Vector2 Vector2Rotate(Vector2 v, float angle) { @@ -492,18 +516,18 @@ RMAPI Vector2 Vector2ClampValue(Vector2 v, float min, float max) { length = sqrtf(length); + float scale = 1; // By default, 1 as the neutral element. if (length < min) { - float scale = min/length; - result.x = v.x*scale; - result.y = v.y*scale; + scale = min/length; } else if (length > max) { - float scale = max/length; - result.x = v.x*scale; - result.y = v.y*scale; + scale = max/length; } + + result.x = v.x*scale; + result.y = v.y*scale; } return result; @@ -522,6 +546,31 @@ RMAPI int Vector2Equals(Vector2 p, Vector2 q) return result; } +// Compute the direction of a refracted ray +// v: normalized direction of the incoming ray +// n: normalized normal vector of the interface of two optical media +// r: ratio of the refractive index of the medium from where the ray comes +// to the refractive index of the medium on the other side of the surface +RMAPI Vector2 Vector2Refract(Vector2 v, Vector2 n, float r) +{ + Vector2 result = { 0 }; + + float dot = v.x*n.x + v.y*n.y; + float d = 1.0f - r*r*(1.0f - dot*dot); + + if (d >= 0.0f) + { + d = sqrtf(d); + v.x = r*v.x - (r*dot + d)*n.x; + v.y = r*v.y - (r*dot + d)*n.y; + + result = v; + } + + return result; +} + + //---------------------------------------------------------------------------------- // Module Functions Definition - Vector3 math //---------------------------------------------------------------------------------- @@ -603,12 +652,12 @@ RMAPI Vector3 Vector3Perpendicular(Vector3 v) { Vector3 result = { 0 }; - float min = (float) fabs(v.x); + float min = fabsf(v.x); Vector3 cardinalAxis = {1.0f, 0.0f, 0.0f}; if (fabsf(v.y) < min) { - min = (float) fabs(v.y); + min = fabsf(v.y); Vector3 tmp = {0.0f, 1.0f, 0.0f}; cardinalAxis = tmp; } @@ -728,7 +777,7 @@ RMAPI Vector3 Vector3Normalize(Vector3 v) RMAPI Vector3 Vector3Project(Vector3 v1, Vector3 v2) { Vector3 result = { 0 }; - + float v1dv2 = (v1.x*v2.x + v1.y*v2.y + v1.z*v2.z); float v2dv2 = (v2.x*v2.x + v2.y*v2.y + v2.z*v2.z); @@ -745,7 +794,7 @@ RMAPI Vector3 Vector3Project(Vector3 v1, Vector3 v2) RMAPI Vector3 Vector3Reject(Vector3 v1, Vector3 v2) { Vector3 result = { 0 }; - + float v1dv2 = (v1.x*v2.x + v1.y*v2.y + v1.z*v2.z); float v2dv2 = (v2.x*v2.x + v2.y*v2.y + v2.z*v2.z); @@ -832,7 +881,7 @@ RMAPI Vector3 Vector3RotateByAxisAngle(Vector3 v, Vector3 axis, float angle) // Vector3Normalize(axis); float length = sqrtf(axis.x*axis.x + axis.y*axis.y + axis.z*axis.z); if (length == 0.0f) length = 1.0f; - float ilength = 1.0f / length; + float ilength = 1.0f/length; axis.x *= ilength; axis.y *= ilength; axis.z *= ilength; @@ -873,6 +922,27 @@ RMAPI Vector3 Vector3RotateByAxisAngle(Vector3 v, Vector3 axis, float angle) return result; } +// Move Vector towards target +RMAPI Vector3 Vector3MoveTowards(Vector3 v, Vector3 target, float maxDistance) +{ + Vector3 result = { 0 }; + + float dx = target.x - v.x; + float dy = target.y - v.y; + float dz = target.z - v.z; + float value = (dx*dx) + (dy*dy) + (dz*dz); + + if ((value == 0) || ((maxDistance >= 0) && (value <= maxDistance*maxDistance))) return target; + + float dist = sqrtf(value); + + result.x = v.x + dx/dist*maxDistance; + result.y = v.y + dy/dist*maxDistance; + result.z = v.z + dz/dist*maxDistance; + + return result; +} + // Calculate linear interpolation between two vectors RMAPI Vector3 Vector3Lerp(Vector3 v1, Vector3 v2, float amount) { @@ -885,6 +955,22 @@ RMAPI Vector3 Vector3Lerp(Vector3 v1, Vector3 v2, float amount) return result; } +// Calculate cubic hermite interpolation between two vectors and their tangents +// as described in the GLTF 2.0 specification: https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#interpolation-cubic +RMAPI Vector3 Vector3CubicHermite(Vector3 v1, Vector3 tangent1, Vector3 v2, Vector3 tangent2, float amount) +{ + Vector3 result = { 0 }; + + float amountPow2 = amount * amount; + float amountPow3 = amount * amount * amount; + + result.x = (2 * amountPow3 - 3 * amountPow2 + 1) * v1.x + (amountPow3 - 2 * amountPow2 + amount) * tangent1.x + (-2 * amountPow3 + 3 * amountPow2) * v2.x + (amountPow3 - amountPow2) * tangent2.x; + result.y = (2 * amountPow3 - 3 * amountPow2 + 1) * v1.y + (amountPow3 - 2 * amountPow2 + amount) * tangent1.y + (-2 * amountPow3 + 3 * amountPow2) * v2.y + (amountPow3 - amountPow2) * tangent2.y; + result.z = (2 * amountPow3 - 3 * amountPow2 + 1) * v1.z + (amountPow3 - 2 * amountPow2 + amount) * tangent1.z + (-2 * amountPow3 + 3 * amountPow2) * v2.z + (amountPow3 - amountPow2) * tangent2.z; + + return result; +} + // Calculate reflected vector to normal RMAPI Vector3 Vector3Reflect(Vector3 v, Vector3 normal) { @@ -1078,20 +1164,19 @@ RMAPI Vector3 Vector3ClampValue(Vector3 v, float min, float max) { length = sqrtf(length); + float scale = 1; // By default, 1 as the neutral element. if (length < min) { - float scale = min/length; - result.x = v.x*scale; - result.y = v.y*scale; - result.z = v.z*scale; + scale = min/length; } else if (length > max) { - float scale = max/length; - result.x = v.x*scale; - result.y = v.y*scale; - result.z = v.z*scale; + scale = max/length; } + + result.x = v.x*scale; + result.y = v.y*scale; + result.z = v.z*scale; } return result; @@ -1136,6 +1221,233 @@ RMAPI Vector3 Vector3Refract(Vector3 v, Vector3 n, float r) return result; } + +//---------------------------------------------------------------------------------- +// Module Functions Definition - Vector4 math +//---------------------------------------------------------------------------------- + +RMAPI Vector4 Vector4Zero(void) +{ + Vector4 result = { 0.0f, 0.0f, 0.0f, 0.0f }; + return result; +} + +RMAPI Vector4 Vector4One(void) +{ + Vector4 result = { 1.0f, 1.0f, 1.0f, 1.0f }; + return result; +} + +RMAPI Vector4 Vector4Add(Vector4 v1, Vector4 v2) +{ + Vector4 result = { + v1.x + v2.x, + v1.y + v2.y, + v1.z + v2.z, + v1.w + v2.w + }; + return result; +} + +RMAPI Vector4 Vector4AddValue(Vector4 v, float add) +{ + Vector4 result = { + v.x + add, + v.y + add, + v.z + add, + v.w + add + }; + return result; +} + +RMAPI Vector4 Vector4Subtract(Vector4 v1, Vector4 v2) +{ + Vector4 result = { + v1.x - v2.x, + v1.y - v2.y, + v1.z - v2.z, + v1.w - v2.w + }; + return result; +} + +RMAPI Vector4 Vector4SubtractValue(Vector4 v, float add) +{ + Vector4 result = { + v.x - add, + v.y - add, + v.z - add, + v.w - add + }; + return result; +} + +RMAPI float Vector4Length(Vector4 v) +{ + float result = sqrtf((v.x*v.x) + (v.y*v.y) + (v.z*v.z) + (v.w*v.w)); + return result; +} + +RMAPI float Vector4LengthSqr(Vector4 v) +{ + float result = (v.x*v.x) + (v.y*v.y) + (v.z*v.z) + (v.w*v.w); + return result; +} + +RMAPI float Vector4DotProduct(Vector4 v1, Vector4 v2) +{ + float result = (v1.x*v2.x + v1.y*v2.y + v1.z*v2.z + v1.w*v2.w); + return result; +} + +// Calculate distance between two vectors +RMAPI float Vector4Distance(Vector4 v1, Vector4 v2) +{ + float result = sqrtf( + (v1.x - v2.x)*(v1.x - v2.x) + (v1.y - v2.y)*(v1.y - v2.y) + + (v1.z - v2.z)*(v1.z - v2.z) + (v1.w - v2.w)*(v1.w - v2.w)); + return result; +} + +// Calculate square distance between two vectors +RMAPI float Vector4DistanceSqr(Vector4 v1, Vector4 v2) +{ + float result = + (v1.x - v2.x)*(v1.x - v2.x) + (v1.y - v2.y)*(v1.y - v2.y) + + (v1.z - v2.z)*(v1.z - v2.z) + (v1.w - v2.w)*(v1.w - v2.w); + + return result; +} + +RMAPI Vector4 Vector4Scale(Vector4 v, float scale) +{ + Vector4 result = { v.x*scale, v.y*scale, v.z*scale, v.w*scale }; + return result; +} + +// Multiply vector by vector +RMAPI Vector4 Vector4Multiply(Vector4 v1, Vector4 v2) +{ + Vector4 result = { v1.x*v2.x, v1.y*v2.y, v1.z*v2.z, v1.w*v2.w }; + return result; +} + +// Negate vector +RMAPI Vector4 Vector4Negate(Vector4 v) +{ + Vector4 result = { -v.x, -v.y, -v.z, -v.w }; + return result; +} + +// Divide vector by vector +RMAPI Vector4 Vector4Divide(Vector4 v1, Vector4 v2) +{ + Vector4 result = { v1.x/v2.x, v1.y/v2.y, v1.z/v2.z, v1.w/v2.w }; + return result; +} + +// Normalize provided vector +RMAPI Vector4 Vector4Normalize(Vector4 v) +{ + Vector4 result = { 0 }; + float length = sqrtf((v.x*v.x) + (v.y*v.y) + (v.z*v.z) + (v.w*v.w)); + + if (length > 0) + { + float ilength = 1.0f/length; + result.x = v.x*ilength; + result.y = v.y*ilength; + result.z = v.z*ilength; + result.w = v.w*ilength; + } + + return result; +} + +// Get min value for each pair of components +RMAPI Vector4 Vector4Min(Vector4 v1, Vector4 v2) +{ + Vector4 result = { 0 }; + + result.x = fminf(v1.x, v2.x); + result.y = fminf(v1.y, v2.y); + result.z = fminf(v1.z, v2.z); + result.w = fminf(v1.w, v2.w); + + return result; +} + +// Get max value for each pair of components +RMAPI Vector4 Vector4Max(Vector4 v1, Vector4 v2) +{ + Vector4 result = { 0 }; + + result.x = fmaxf(v1.x, v2.x); + result.y = fmaxf(v1.y, v2.y); + result.z = fmaxf(v1.z, v2.z); + result.w = fmaxf(v1.w, v2.w); + + return result; +} + +// Calculate linear interpolation between two vectors +RMAPI Vector4 Vector4Lerp(Vector4 v1, Vector4 v2, float amount) +{ + Vector4 result = { 0 }; + + result.x = v1.x + amount*(v2.x - v1.x); + result.y = v1.y + amount*(v2.y - v1.y); + result.z = v1.z + amount*(v2.z - v1.z); + result.w = v1.w + amount*(v2.w - v1.w); + + return result; +} + +// Move Vector towards target +RMAPI Vector4 Vector4MoveTowards(Vector4 v, Vector4 target, float maxDistance) +{ + Vector4 result = { 0 }; + + float dx = target.x - v.x; + float dy = target.y - v.y; + float dz = target.z - v.z; + float dw = target.w - v.w; + float value = (dx*dx) + (dy*dy) + (dz*dz) + (dw*dw); + + if ((value == 0) || ((maxDistance >= 0) && (value <= maxDistance*maxDistance))) return target; + + float dist = sqrtf(value); + + result.x = v.x + dx/dist*maxDistance; + result.y = v.y + dy/dist*maxDistance; + result.z = v.z + dz/dist*maxDistance; + result.w = v.w + dw/dist*maxDistance; + + return result; +} + +// Invert the given vector +RMAPI Vector4 Vector4Invert(Vector4 v) +{ + Vector4 result = { 1.0f/v.x, 1.0f/v.y, 1.0f/v.z, 1.0f/v.w }; + return result; +} + +// Check whether two given vectors are almost equal +RMAPI int Vector4Equals(Vector4 p, Vector4 q) +{ +#if !defined(EPSILON) + #define EPSILON 0.000001f +#endif + + int result = ((fabsf(p.x - q.x)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.x), fabsf(q.x))))) && + ((fabsf(p.y - q.y)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.y), fabsf(q.y))))) && + ((fabsf(p.z - q.z)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.z), fabsf(q.z))))) && + ((fabsf(p.w - q.w)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.w), fabsf(q.w))))); + return result; +} + + //---------------------------------------------------------------------------------- // Module Functions Definition - Matrix math //---------------------------------------------------------------------------------- @@ -1901,6 +2213,32 @@ RMAPI Quaternion QuaternionSlerp(Quaternion q1, Quaternion q2, float amount) return result; } +// Calculate quaternion cubic spline interpolation using Cubic Hermite Spline algorithm +// as described in the GLTF 2.0 specification: https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#interpolation-cubic +RMAPI Quaternion QuaternionCubicHermiteSpline(Quaternion q1, Quaternion outTangent1, Quaternion q2, Quaternion inTangent2, float t) +{ + float t2 = t * t; + float t3 = t2 * t; + float h00 = 2 * t3 - 3 * t2 + 1; + float h10 = t3 - 2 * t2 + t; + float h01 = -2 * t3 + 3 * t2; + float h11 = t3 - t2; + + Quaternion p0 = QuaternionScale(q1, h00); + Quaternion m0 = QuaternionScale(outTangent1, h10); + Quaternion p1 = QuaternionScale(q2, h01); + Quaternion m1 = QuaternionScale(inTangent2, h11); + + Quaternion result = { 0 }; + + result = QuaternionAdd(p0, m0); + result = QuaternionAdd(result, p1); + result = QuaternionAdd(result, m1); + result = QuaternionNormalize(result); + + return result; +} + // Calculate quaternion based on the rotation from one vector to another RMAPI Quaternion QuaternionFromVector3ToVector3(Vector3 from, Vector3 to) { @@ -1960,7 +2298,7 @@ RMAPI Quaternion QuaternionFromMatrix(Matrix mat) } float biggestVal = sqrtf(fourBiggestSquaredMinus1 + 1.0f)*0.5f; - float mult = 0.25f / biggestVal; + float mult = 0.25f/biggestVal; switch (biggestIndex) { @@ -2042,8 +2380,7 @@ RMAPI Quaternion QuaternionFromAxisAngle(Vector3 axis, float angle) float ilength = 0.0f; // Vector3Normalize(axis) - Vector3 v = axis; - length = sqrtf(v.x*v.x + v.y*v.y + v.z*v.z); + length = axisLength; if (length == 0.0f) length = 1.0f; ilength = 1.0f/length; axis.x *= ilength; diff --git a/raylib/rcamera.h b/raylib/rcamera.h index c999370..9c19556 100644 --- a/raylib/rcamera.h +++ b/raylib/rcamera.h @@ -20,7 +20,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2022-2023 Christoph Wagner (@Crydsch) & Ramon Santamaria (@raysan5) +* Copyright (c) 2022-2024 Christoph Wagner (@Crydsch) & Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. @@ -202,18 +202,10 @@ RLAPI Matrix GetCameraProjectionMatrix(Camera* camera, float aspect); // Camera mouse movement sensitivity #define CAMERA_MOUSE_MOVE_SENSITIVITY 0.003f // TODO: it should be independant of framerate -#define CAMERA_MOUSE_SCROLL_SENSITIVITY 1.5f +// Camera orbital speed in CAMERA_ORBITAL mode #define CAMERA_ORBITAL_SPEED 0.5f // Radians per second - -#define CAMERA_FIRST_PERSON_STEP_TRIGONOMETRIC_DIVIDER 8.0f -#define CAMERA_FIRST_PERSON_STEP_DIVIDER 30.0f -#define CAMERA_FIRST_PERSON_WAVING_DIVIDER 200.0f - -// PLAYER (used by camera) -#define PLAYER_MOVEMENT_SENSITIVITY 20.0f - //---------------------------------------------------------------------------------- // Types and Structures Definition //---------------------------------------------------------------------------------- @@ -251,7 +243,7 @@ Vector3 GetCameraRight(Camera *camera) Vector3 forward = GetCameraForward(camera); Vector3 up = GetCameraUp(camera); - return Vector3CrossProduct(forward, up); + return Vector3Normalize(Vector3CrossProduct(forward, up)); } // Moves the camera in its forward direction @@ -449,10 +441,11 @@ void UpdateCamera(Camera *camera, int mode) bool moveInWorldPlane = ((mode == CAMERA_FIRST_PERSON) || (mode == CAMERA_THIRD_PERSON)); bool rotateAroundTarget = ((mode == CAMERA_THIRD_PERSON) || (mode == CAMERA_ORBITAL)); - bool lockView = ((mode == CAMERA_FIRST_PERSON) || (mode == CAMERA_THIRD_PERSON) || (mode == CAMERA_ORBITAL)); + bool lockView = ((mode == CAMERA_FREE) || (mode == CAMERA_FIRST_PERSON) || (mode == CAMERA_THIRD_PERSON) || (mode == CAMERA_ORBITAL)); bool rotateUp = false; - if (mode == CAMERA_ORBITAL) + if (mode == CAMERA_CUSTOM) {} + else if (mode == CAMERA_ORBITAL) { // Orbital can just orbit Matrix rotation = MatrixRotate(GetCameraUp(camera), CAMERA_ORBITAL_SPEED*GetFrameTime()); @@ -471,31 +464,30 @@ void UpdateCamera(Camera *camera, int mode) if (IsKeyDown(KEY_E)) CameraRoll(camera, CAMERA_ROTATION_SPEED); // Camera movement - if (!IsGamepadAvailable(0)) + // Camera pan (for CAMERA_FREE) + if ((mode == CAMERA_FREE) && (IsMouseButtonDown(MOUSE_BUTTON_MIDDLE))) { - // Camera pan (for CAMERA_FREE) - if ((mode == CAMERA_FREE) && (IsMouseButtonDown(MOUSE_BUTTON_MIDDLE))) - { - const Vector2 mouseDelta = GetMouseDelta(); - if (mouseDelta.x > 0.0f) CameraMoveRight(camera, CAMERA_PAN_SPEED, moveInWorldPlane); - if (mouseDelta.x < 0.0f) CameraMoveRight(camera, -CAMERA_PAN_SPEED, moveInWorldPlane); - if (mouseDelta.y > 0.0f) CameraMoveUp(camera, -CAMERA_PAN_SPEED); - if (mouseDelta.y < 0.0f) CameraMoveUp(camera, CAMERA_PAN_SPEED); - } - else - { - // Mouse support - CameraYaw(camera, -mousePositionDelta.x*CAMERA_MOUSE_MOVE_SENSITIVITY, rotateAroundTarget); - CameraPitch(camera, -mousePositionDelta.y*CAMERA_MOUSE_MOVE_SENSITIVITY, lockView, rotateAroundTarget, rotateUp); - } - - // Keyboard support - if (IsKeyDown(KEY_W)) CameraMoveForward(camera, CAMERA_MOVE_SPEED, moveInWorldPlane); - if (IsKeyDown(KEY_A)) CameraMoveRight(camera, -CAMERA_MOVE_SPEED, moveInWorldPlane); - if (IsKeyDown(KEY_S)) CameraMoveForward(camera, -CAMERA_MOVE_SPEED, moveInWorldPlane); - if (IsKeyDown(KEY_D)) CameraMoveRight(camera, CAMERA_MOVE_SPEED, moveInWorldPlane); + const Vector2 mouseDelta = GetMouseDelta(); + if (mouseDelta.x > 0.0f) CameraMoveRight(camera, CAMERA_PAN_SPEED, moveInWorldPlane); + if (mouseDelta.x < 0.0f) CameraMoveRight(camera, -CAMERA_PAN_SPEED, moveInWorldPlane); + if (mouseDelta.y > 0.0f) CameraMoveUp(camera, -CAMERA_PAN_SPEED); + if (mouseDelta.y < 0.0f) CameraMoveUp(camera, CAMERA_PAN_SPEED); } else + { + // Mouse support + CameraYaw(camera, -mousePositionDelta.x*CAMERA_MOUSE_MOVE_SENSITIVITY, rotateAroundTarget); + CameraPitch(camera, -mousePositionDelta.y*CAMERA_MOUSE_MOVE_SENSITIVITY, lockView, rotateAroundTarget, rotateUp); + } + + // Keyboard support + if (IsKeyDown(KEY_W)) CameraMoveForward(camera, CAMERA_MOVE_SPEED, moveInWorldPlane); + if (IsKeyDown(KEY_A)) CameraMoveRight(camera, -CAMERA_MOVE_SPEED, moveInWorldPlane); + if (IsKeyDown(KEY_S)) CameraMoveForward(camera, -CAMERA_MOVE_SPEED, moveInWorldPlane); + if (IsKeyDown(KEY_D)) CameraMoveRight(camera, CAMERA_MOVE_SPEED, moveInWorldPlane); + + // Gamepad movement + if (IsGamepadAvailable(0)) { // Gamepad controller support CameraYaw(camera, -(GetGamepadAxisMovement(0, GAMEPAD_AXIS_RIGHT_X) * 2)*CAMERA_MOUSE_MOVE_SENSITIVITY, rotateAroundTarget); diff --git a/raylib/rcore.c b/raylib/rcore.c index 4539889..1db8651 100644 --- a/raylib/rcore.c +++ b/raylib/rcore.c @@ -63,7 +63,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2013-2023 Ramon Santamaria (@raysan5) and contributors +* Copyright (c) 2013-2024 Ramon Santamaria (@raysan5) and contributors * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. @@ -82,6 +82,19 @@ * **********************************************************************************************/ +//---------------------------------------------------------------------------------- +// Feature Test Macros required for this module +//---------------------------------------------------------------------------------- +#if (defined(__linux__) || defined(PLATFORM_WEB)) && (_XOPEN_SOURCE < 500) + #undef _XOPEN_SOURCE + #define _XOPEN_SOURCE 500 // Required for: readlink if compiled with c99 without gnu ext. +#endif + +#if (defined(__linux__) || defined(PLATFORM_WEB)) && (_POSIX_C_SOURCE < 199309L) + #undef _POSIX_C_SOURCE + #define _POSIX_C_SOURCE 199309L // Required for: CLOCK_MONOTONIC if compiled with c99 without gnu ext. +#endif + #include "raylib.h" // Declares module functions // Check if config flags have been externally provided on compilation line @@ -105,12 +118,12 @@ #if defined(SUPPORT_GESTURES_SYSTEM) #define RGESTURES_IMPLEMENTATION - #include "rgestures.h" // Gestures detection functionality + #include "rgestures.h" // Gestures detection functionality #endif #if defined(SUPPORT_CAMERA_SYSTEM) #define RCAMERA_IMPLEMENTATION - #include "rcamera.h" // Camera system functionality + #include "rcamera.h" // Camera system functionality #endif #if defined(SUPPORT_GIF_RECORDING) @@ -141,13 +154,15 @@ #endif // Platform specific defines to handle GetApplicationDirectory() -#if defined(_WIN32) +#if (defined(_WIN32) && !defined(PLATFORM_DESKTOP_RGFW)) || (defined(_MSC_VER) && defined(PLATFORM_DESKTOP_RGFW)) #ifndef MAX_PATH #define MAX_PATH 1025 #endif __declspec(dllimport) unsigned long __stdcall GetModuleFileNameA(void *hModule, void *lpFilename, unsigned long nSize); __declspec(dllimport) unsigned long __stdcall GetModuleFileNameW(void *hModule, void *lpFilename, unsigned long nSize); __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigned long flags, void *widestr, int cchwide, void *str, int cbmb, void *defchar, int *used_default); +unsigned int __stdcall timeBeginPeriod(unsigned int uPeriod); +unsigned int __stdcall timeEndPeriod(unsigned int uPeriod); #elif defined(__linux__) #include #elif defined(__APPLE__) @@ -211,6 +226,9 @@ __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigne #ifndef MAX_GAMEPAD_BUTTONS #define MAX_GAMEPAD_BUTTONS 32 // Maximum number of buttons supported (per gamepad) #endif +#ifndef MAX_GAMEPAD_VIBRATION_TIME + #define MAX_GAMEPAD_VIBRATION_TIME 2.0f // Maximum vibration time in seconds +#endif #ifndef MAX_TOUCH_POINTS #define MAX_TOUCH_POINTS 8 // Maximum number of touch points supported #endif @@ -235,11 +253,6 @@ __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigne #define FLAG_TOGGLE(n, f) ((n) ^= (f)) #define FLAG_CHECK(n, f) ((n) & (f)) -#if (defined(__linux__) || defined(PLATFORM_WEB)) && (_POSIX_C_SOURCE < 199309L) - #undef _POSIX_C_SOURCE - #define _POSIX_C_SOURCE 199309L // Required for: CLOCK_MONOTONIC if compiled with c99 without gnu ext. -#endif - //---------------------------------------------------------------------------------- // Types and Structures Definition //---------------------------------------------------------------------------------- @@ -281,16 +294,16 @@ typedef struct CoreData { struct { struct { int exitKey; // Default exit key - char currentKeyState[MAX_KEYBOARD_KEYS]; // Registers current frame key state - char previousKeyState[MAX_KEYBOARD_KEYS]; // Registers previous frame key state + char currentKeyState[MAX_KEYBOARD_KEYS]; // Registers current frame key state + char previousKeyState[MAX_KEYBOARD_KEYS]; // Registers previous frame key state // NOTE: Since key press logic involves comparing prev vs cur key state, we need to handle key repeats specially - char keyRepeatInFrame[MAX_KEYBOARD_KEYS]; // Registers key repeats for current frame. + char keyRepeatInFrame[MAX_KEYBOARD_KEYS]; // Registers key repeats for current frame - int keyPressedQueue[MAX_KEY_PRESSED_QUEUE]; // Input keys queue + int keyPressedQueue[MAX_KEY_PRESSED_QUEUE]; // Input keys queue int keyPressedQueueCount; // Input keys queue count - int charPressedQueue[MAX_CHAR_PRESSED_QUEUE]; // Input characters queue (unicode) + int charPressedQueue[MAX_CHAR_PRESSED_QUEUE]; // Input characters queue (unicode) int charPressedQueueCount; // Input characters queue count } Keyboard; @@ -320,7 +333,7 @@ typedef struct CoreData { } Touch; struct { int lastButtonPressed; // Register last gamepad button pressed - int axisCount[MAX_GAMEPADS]; // Register number of available gamepad axis + int axisCount[MAX_GAMEPADS]; // Register number of available gamepad axis bool ready[MAX_GAMEPADS]; // Flag to know if gamepad is ready char name[MAX_GAMEPADS][64]; // Gamepad name holder char currentButtonState[MAX_GAMEPADS][MAX_GAMEPAD_BUTTONS]; // Current gamepad buttons state @@ -354,7 +367,7 @@ static int screenshotCounter = 0; // Screenshots counter #endif #if defined(SUPPORT_GIF_RECORDING) -int gifFrameCounter = 0; // GIF frames counter +unsigned int gifFrameCounter = 0; // GIF frames counter bool gifRecording = false; // GIF recording state MsfGifState gifState = { 0 }; // MSGIF context state #endif @@ -471,7 +484,7 @@ static void ScanDirectoryFilesRecursively(const char *basePath, FilePathList *li static void RecordAutomationEvent(void); // Record frame events (to internal events array) #endif -#if defined(_WIN32) +#if defined(_WIN32) && !defined(PLATFORM_DESKTOP_RGFW) // NOTE: We declare Sleep() function symbol to avoid including windows.h (kernel32.lib linkage required) void __stdcall Sleep(unsigned long msTimeout); // Required for: WaitTime() #endif @@ -485,6 +498,8 @@ const char *TextFormat(const char *text, ...); // Formatting of tex #include "platforms/rcore_desktop.c" #elif defined(PLATFORM_DESKTOP_SDL) #include "platforms/rcore_desktop_sdl.c" +#elif defined(PLATFORM_DESKTOP_RGFW) + #include "platforms/rcore_desktop_rgfw.c" #elif defined(PLATFORM_WEB) #include "platforms/rcore_web.c" #elif defined(PLATFORM_DRM) @@ -795,7 +810,7 @@ bool IsCursorHidden(void) return CORE.Input.Mouse.cursorHidden; } -// Check if cursor is on the current screen. +// Check if cursor is on the current screen bool IsCursorOnScreen(void) { return CORE.Input.Mouse.cursorOnScreen; @@ -838,23 +853,33 @@ void EndDrawing(void) // Draw record indicator if (gifRecording) { + #ifndef GIF_RECORD_FRAMERATE #define GIF_RECORD_FRAMERATE 10 - gifFrameCounter++; + #endif + gifFrameCounter += GetFrameTime()*1000; - // NOTE: We record one gif frame every 10 game frames - if ((gifFrameCounter%GIF_RECORD_FRAMERATE) == 0) + // NOTE: We record one gif frame depending on the desired gif framerate + if (gifFrameCounter > 1000/GIF_RECORD_FRAMERATE) { // Get image data for the current frame (from backbuffer) // NOTE: This process is quite slow... :( Vector2 scale = GetWindowScaleDPI(); unsigned char *screenData = rlReadScreenPixels((int)((float)CORE.Window.render.width*scale.x), (int)((float)CORE.Window.render.height*scale.y)); - msf_gif_frame(&gifState, screenData, 10, 16, (int)((float)CORE.Window.render.width*scale.x)*4); + + #ifndef GIF_RECORD_BITRATE + #define GIF_RECORD_BITRATE 16 + #endif + + // Add the frame to the gif recording, given how many frames have passed in centiseconds + msf_gif_frame(&gifState, screenData, gifFrameCounter/10, GIF_RECORD_BITRATE, (int)((float)CORE.Window.render.width*scale.x)*4); + gifFrameCounter -= 1000/GIF_RECORD_FRAMERATE; RL_FREE(screenData); // Free image data } #if defined(SUPPORT_MODULE_RSHAPES) && defined(SUPPORT_MODULE_RTEXT) - if (((gifFrameCounter/15)%2) == 1) + // Display the recording indicator every half-second + if ((int)(GetTime()/0.5)%2 == 1) { DrawCircle(30, CORE.Window.screen.height - 20, 10, MAROON); // WARNING: Module required: rshapes DrawText("GIF RECORDING", 50, CORE.Window.screen.height - 25, 10, RED); // WARNING: Module required: rtext @@ -944,9 +969,6 @@ void BeginMode2D(Camera2D camera) // Apply 2d camera transformation to modelview rlMultMatrixf(MatrixToFloat(GetCameraMatrix2D(camera))); - - // Apply screen scaling if required - rlMultMatrixf(MatrixToFloat(CORE.Window.screenScale)); } // Ends 2D mode with custom camera @@ -955,7 +977,8 @@ void EndMode2D(void) rlDrawRenderBatchActive(); // Update and draw internal render batch rlLoadIdentity(); // Reset current matrix (modelview) - rlMultMatrixf(MatrixToFloat(CORE.Window.screenScale)); // Apply screen scaling if required + + if (rlGetActiveFramebuffer() == 0) rlMultMatrixf(MatrixToFloat(CORE.Window.screenScale)); // Apply screen scaling if required } // Initializes 3D mode with custom camera (3D) @@ -973,10 +996,10 @@ void BeginMode3D(Camera camera) if (camera.projection == CAMERA_PERSPECTIVE) { // Setup perspective projection - double top = RL_CULL_DISTANCE_NEAR*tan(camera.fovy*0.5*DEG2RAD); + double top = rlGetCullDistanceNear()*tan(camera.fovy*0.5*DEG2RAD); double right = top*aspect; - rlFrustum(-right, right, -top, top, RL_CULL_DISTANCE_NEAR, RL_CULL_DISTANCE_FAR); + rlFrustum(-right, right, -top, top, rlGetCullDistanceNear(), rlGetCullDistanceFar()); } else if (camera.projection == CAMERA_ORTHOGRAPHIC) { @@ -984,7 +1007,7 @@ void BeginMode3D(Camera camera) double top = camera.fovy/2.0; double right = top*aspect; - rlOrtho(-right, right, -top,top, RL_CULL_DISTANCE_NEAR, RL_CULL_DISTANCE_FAR); + rlOrtho(-right, right, -top,top, rlGetCullDistanceNear(), rlGetCullDistanceFar()); } rlMatrixMode(RL_MODELVIEW); // Switch back to modelview matrix @@ -1008,7 +1031,7 @@ void EndMode3D(void) rlMatrixMode(RL_MODELVIEW); // Switch back to modelview matrix rlLoadIdentity(); // Reset current matrix (modelview) - rlMultMatrixf(MatrixToFloat(CORE.Window.screenScale)); // Apply screen scaling if required + if (rlGetActiveFramebuffer() == 0) rlMultMatrixf(MatrixToFloat(CORE.Window.screenScale)); // Apply screen scaling if required rlDisableDepthTest(); // Disable DEPTH_TEST for 2D } @@ -1054,6 +1077,11 @@ void EndTextureMode(void) // Set viewport to default framebuffer size SetupViewport(CORE.Window.render.width, CORE.Window.render.height); + // Go back to the modelview state from BeginDrawing since we are back to the default FBO + rlMatrixMode(RL_MODELVIEW); // Switch back to modelview matrix + rlLoadIdentity(); // Reset current matrix (modelview) + rlMultMatrixf(MatrixToFloat(CORE.Window.screenScale)); // Apply screen scaling if required + // Reset current fbo to screen size CORE.Window.currentFbo.width = CORE.Window.render.width; CORE.Window.currentFbo.height = CORE.Window.render.height; @@ -1183,17 +1211,17 @@ VrStereoConfig LoadVrStereoConfig(VrDeviceInfo device) // Compute camera projection matrices float projOffset = 4.0f*lensShift; // Scaled to projection space coordinates [-1..1] - Matrix proj = MatrixPerspective(fovy, aspect, RL_CULL_DISTANCE_NEAR, RL_CULL_DISTANCE_FAR); + Matrix proj = MatrixPerspective(fovy, aspect, rlGetCullDistanceNear(), rlGetCullDistanceFar()); config.projection[0] = MatrixMultiply(proj, MatrixTranslate(projOffset, 0.0f, 0.0f)); config.projection[1] = MatrixMultiply(proj, MatrixTranslate(-projOffset, 0.0f, 0.0f)); // Compute camera transformation matrices - // NOTE: Camera movement might seem more natural if we model the head. + // NOTE: Camera movement might seem more natural if we model the head // Our axis of rotation is the base of our head, so we might want to add - // some y (base of head to eye level) and -z (center of head to eye protrusion) to the camera positions. - config.viewOffset[0] = MatrixTranslate(-device.interpupillaryDistance*0.5f, 0.075f, 0.045f); - config.viewOffset[1] = MatrixTranslate(device.interpupillaryDistance*0.5f, 0.075f, 0.045f); + // some y (base of head to eye level) and -z (center of head to eye protrusion) to the camera positions + config.viewOffset[0] = MatrixTranslate(device.interpupillaryDistance*0.5f, 0.075f, 0.045f); + config.viewOffset[1] = MatrixTranslate(-device.interpupillaryDistance*0.5f, 0.075f, 0.045f); // Compute eyes Viewports /* @@ -1392,15 +1420,23 @@ void SetShaderValueTexture(Shader shader, int locIndex, Texture2D texture) // Module Functions Definition: Screen-space Queries //---------------------------------------------------------------------------------- -// Get a ray trace from mouse position -Ray GetMouseRay(Vector2 mouse, Camera camera) +// Get a ray trace from screen position (i.e mouse) +Ray GetScreenToWorldRay(Vector2 position, Camera camera) +{ + Ray ray = GetScreenToWorldRayEx(position, camera, GetScreenWidth(), GetScreenHeight()); + + return ray; +} + +// Get a ray trace from the screen position (i.e mouse) within a specific section of the screen +Ray GetScreenToWorldRayEx(Vector2 position, Camera camera, int width, int height) { Ray ray = { 0 }; // Calculate normalized device coordinates // NOTE: y value is negative - float x = (2.0f*mouse.x)/(float)GetScreenWidth() - 1.0f; - float y = 1.0f - (2.0f*mouse.y)/(float)GetScreenHeight(); + float x = (2.0f*position.x)/(float)width - 1.0f; + float y = 1.0f - (2.0f*position.y)/(float)height; float z = 1.0f; // Store values in a vector @@ -1414,11 +1450,11 @@ Ray GetMouseRay(Vector2 mouse, Camera camera) if (camera.projection == CAMERA_PERSPECTIVE) { // Calculate projection matrix from perspective - matProj = MatrixPerspective(camera.fovy*DEG2RAD, ((double)GetScreenWidth()/(double)GetScreenHeight()), RL_CULL_DISTANCE_NEAR, RL_CULL_DISTANCE_FAR); + matProj = MatrixPerspective(camera.fovy*DEG2RAD, ((double)width/(double)height), rlGetCullDistanceNear(), rlGetCullDistanceFar()); } else if (camera.projection == CAMERA_ORTHOGRAPHIC) { - double aspect = (double)CORE.Window.screen.width/(double)CORE.Window.screen.height; + double aspect = (double)width/(double)height; double top = camera.fovy/2.0; double right = top*aspect; @@ -1430,9 +1466,10 @@ Ray GetMouseRay(Vector2 mouse, Camera camera) Vector3 nearPoint = Vector3Unproject((Vector3){ deviceCoords.x, deviceCoords.y, 0.0f }, matProj, matView); Vector3 farPoint = Vector3Unproject((Vector3){ deviceCoords.x, deviceCoords.y, 1.0f }, matProj, matView); - // Unproject the mouse cursor in the near plane. - // We need this as the source position because orthographic projects, compared to perspective doesn't have a - // convergence point, meaning that the "eye" of the camera is more like a plane than a point. + // Unproject the mouse cursor in the near plane + // We need this as the source position because orthographic projects, + // compared to perspective doesn't have a convergence point, + // meaning that the "eye" of the camera is more like a plane than a point Vector3 cameraPlanePointerPos = Vector3Unproject((Vector3){ deviceCoords.x, deviceCoords.y, -1.0f }, matProj, matView); // Calculate normalized direction vector @@ -1450,7 +1487,9 @@ Ray GetMouseRay(Vector2 mouse, Camera camera) // Get transform matrix for camera Matrix GetCameraMatrix(Camera camera) { - return MatrixLookAt(camera.position, camera.target, camera.up); + Matrix mat = MatrixLookAt(camera.position, camera.target, camera.up); + + return mat; } // Get camera 2d transform matrix @@ -1461,12 +1500,12 @@ Matrix GetCameraMatrix2D(Camera2D camera) // 1. Move it to target // 2. Rotate by -rotation and scale by (1/zoom) // When setting higher scale, it's more intuitive for the world to become bigger (= camera become smaller), - // not for the camera getting bigger, hence the invert. Same deal with rotation. + // not for the camera getting bigger, hence the invert. Same deal with rotation // 3. Move it by (-offset); // Offset defines target transform relative to screen, but since we're effectively "moving" screen (camera) // we need to do it into opposite direction (inverse transform) - // Having camera transform in world-space, inverse of it gives the modelview transform. + // Having camera transform in world-space, inverse of it gives the modelview transform // Since (A*B*C)' = C'*B'*A', the modelview is // 1. Move to offset // 2. Rotate and Scale @@ -1498,7 +1537,7 @@ Vector2 GetWorldToScreenEx(Vector3 position, Camera camera, int width, int heigh if (camera.projection == CAMERA_PERSPECTIVE) { // Calculate projection matrix from perspective - matProj = MatrixPerspective(camera.fovy*DEG2RAD, ((double)width/(double)height), RL_CULL_DISTANCE_NEAR, RL_CULL_DISTANCE_FAR); + matProj = MatrixPerspective(camera.fovy*DEG2RAD, ((double)width/(double)height), rlGetCullDistanceNear(), rlGetCullDistanceFar()); } else if (camera.projection == CAMERA_ORTHOGRAPHIC) { @@ -1507,7 +1546,7 @@ Vector2 GetWorldToScreenEx(Vector3 position, Camera camera, int width, int heigh double right = top*aspect; // Calculate projection matrix from orthographic - matProj = MatrixOrtho(-right, right, -top, top, RL_CULL_DISTANCE_NEAR, RL_CULL_DISTANCE_FAR); + matProj = MatrixOrtho(-right, right, -top, top, rlGetCullDistanceNear(), rlGetCullDistanceFar()); } // Calculate view matrix from camera look at (and transpose it) @@ -1631,7 +1670,7 @@ float GetFrameTime(void) // Ref: http://www.geisswerks.com/ryan/FAQS/timing.html --> All about timing on Win32! void WaitTime(double seconds) { - if (seconds < 0) return; + if (seconds < 0) return; // Security check #if defined(SUPPORT_BUSY_WAIT_LOOP) || defined(SUPPORT_PARTIALBUSY_WAIT_LOOP) double destinationTime = GetTime() + seconds; @@ -1657,7 +1696,7 @@ void WaitTime(double seconds) req.tv_sec = sec; req.tv_nsec = nsec; - // NOTE: Use nanosleep() on Unix platforms... usleep() it's deprecated. + // NOTE: Use nanosleep() on Unix platforms... usleep() it's deprecated while (nanosleep(&req, &req) == -1) continue; #endif #if defined(__APPLE__) @@ -1677,7 +1716,6 @@ void WaitTime(double seconds) // NOTE: Functions with a platform-specific implementation on rcore_.c //void OpenURL(const char *url) - // Set the seed for the random number generator void SetRandomSeed(unsigned int seed) { @@ -1725,7 +1763,7 @@ int *LoadRandomSequence(unsigned int count, int min, int max) #if defined(SUPPORT_RPRAND_GENERATOR) values = rprand_load_sequence(count, min, max); #else - if (count > ((unsigned int)abs(max - min) + 1)) return values; + if (count > ((unsigned int)abs(max - min) + 1)) return values; // Security check values = (int *)RL_CALLOC(count, sizeof(int)); @@ -1780,7 +1818,7 @@ void TakeScreenshot(const char *fileName) char path[512] = { 0 }; strcpy(path, TextFormat("%s/%s", CORE.Storage.basePath, GetFileName(fileName))); - + ExportImage(image, path); // WARNING: Module required: rtextures RL_FREE(imgData); @@ -1793,7 +1831,7 @@ void TakeScreenshot(const char *fileName) // Setup window configuration flags (view FLAGS) // NOTE: This function is expected to be called before window creation, -// because it sets up some flags for the window creation process. +// because it sets up some flags for the window creation process // To configure window states after creation, just use SetWindowState() void SetConfigFlags(unsigned int flags) { @@ -1829,7 +1867,7 @@ bool FileExists(const char *fileName) // NOTE: Extensions checking is not case-sensitive bool IsFileExtension(const char *fileName, const char *ext) { - #define MAX_FILE_EXTENSION_SIZE 16 + #define MAX_FILE_EXTENSION_LENGTH 16 bool result = false; const char *fileExt = GetFileExtension(fileName); @@ -1840,8 +1878,8 @@ bool IsFileExtension(const char *fileName, const char *ext) int extCount = 0; const char **checkExts = TextSplit(ext, ';', &extCount); // WARNING: Module required: rtext - char fileExtLower[MAX_FILE_EXTENSION_SIZE + 1] = { 0 }; - strncpy(fileExtLower, TextToLower(fileExt), MAX_FILE_EXTENSION_SIZE); // WARNING: Module required: rtext + char fileExtLower[MAX_FILE_EXTENSION_LENGTH + 1] = { 0 }; + strncpy(fileExtLower, TextToLower(fileExt), MAX_FILE_EXTENSION_LENGTH); // WARNING: Module required: rtext for (int i = 0; i < extCount; i++) { @@ -1917,7 +1955,9 @@ const char *GetFileExtension(const char *fileName) static const char *strprbrk(const char *s, const char *charset) { const char *latestMatch = NULL; + for (; s = strpbrk(s, charset), s != NULL; latestMatch = s++) { } + return latestMatch; } @@ -1925,9 +1965,10 @@ static const char *strprbrk(const char *s, const char *charset) const char *GetFileName(const char *filePath) { const char *fileName = NULL; + if (filePath != NULL) fileName = strprbrk(filePath, "\\/"); - if (!fileName) return filePath; + if (fileName == NULL) return filePath; return fileName + 1; } @@ -1935,22 +1976,24 @@ const char *GetFileName(const char *filePath) // Get filename string without extension (uses static string) const char *GetFileNameWithoutExt(const char *filePath) { - #define MAX_FILENAMEWITHOUTEXT_LENGTH 256 + #define MAX_FILENAME_LENGTH 256 - static char fileName[MAX_FILENAMEWITHOUTEXT_LENGTH] = { 0 }; - memset(fileName, 0, MAX_FILENAMEWITHOUTEXT_LENGTH); + static char fileName[MAX_FILENAME_LENGTH] = { 0 }; + memset(fileName, 0, MAX_FILENAME_LENGTH); - if (filePath != NULL) strcpy(fileName, GetFileName(filePath)); // Get filename with extension - - int size = (int)strlen(fileName); // Get size in bytes - - for (int i = 0; (i < size) && (i < MAX_FILENAMEWITHOUTEXT_LENGTH); i++) + if (filePath != NULL) { - if (fileName[i] == '.') + strcpy(fileName, GetFileName(filePath)); // Get filename.ext without path + int size = (int)strlen(fileName); // Get size in bytes + + for (int i = size; i > 0; i--) // Reverse search '.' { - // NOTE: We break on first '.' found - fileName[i] = '\0'; - break; + if (fileName[i] == '.') + { + // NOTE: We break on first '.' found + fileName[i] = '\0'; + break; + } } } @@ -2204,8 +2247,11 @@ bool IsPathFile(const char *path) // Check if a file has been dropped into window bool IsFileDropped(void) { - if (CORE.Window.dropFileCount > 0) return true; - else return false; + bool result = false; + + if (CORE.Window.dropFileCount > 0) result = true; + + return result; } // Load dropped filepaths @@ -2239,15 +2285,16 @@ void UnloadDroppedFiles(FilePathList files) long GetFileModTime(const char *fileName) { struct stat result = { 0 }; + long modTime = 0; if (stat(fileName, &result) == 0) { time_t mod = result.st_mtime; - return (long)mod; + modTime = (long)mod; } - return 0; + return modTime; } //---------------------------------------------------------------------------------- @@ -2316,7 +2363,7 @@ char *EncodeDataBase64(const unsigned char *data, int dataSize, int *outputSize) char *encodedData = (char *)RL_MALLOC(*outputSize); - if (encodedData == NULL) return NULL; + if (encodedData == NULL) return NULL; // Security check for (int i = 0, j = 0; i < dataSize;) { @@ -2480,13 +2527,10 @@ AutomationEventList LoadAutomationEventList(const char *fileName) } // Unload automation events list from file -void UnloadAutomationEventList(AutomationEventList *list) +void UnloadAutomationEventList(AutomationEventList list) { #if defined(SUPPORT_AUTOMATION_EVENTS) - RL_FREE(list->events); - list->events = NULL; - list->count = 0; - list->capacity = 0; + RL_FREE(list.events); #endif } @@ -2623,8 +2667,9 @@ void PlayAutomationEvent(AutomationEvent event) { CORE.Input.Gamepad.axisState[event.params[0]][event.params[1]] = ((float)event.params[2]/32768.0f); } break; + #if defined(SUPPORT_GESTURES_SYSTEM) case INPUT_GESTURE: GESTURES.current = event.params[0]; break; // param[0]: gesture (enum Gesture) -> rgestures.h: GESTURES.current - + #endif // Window event case WINDOW_CLOSE: CORE.Window.shouldClose = true; break; case WINDOW_MAXIMIZE: MaximizeWindow(); break; @@ -2632,11 +2677,13 @@ void PlayAutomationEvent(AutomationEvent event) case WINDOW_RESIZE: SetWindowSize(event.params[0], event.params[1]); break; // Custom event + #if defined(SUPPORT_SCREEN_CAPTURE) case ACTION_TAKE_SCREENSHOT: { TakeScreenshot(TextFormat("screenshot%03i.png", screenshotCounter)); screenshotCounter++; } break; + #endif case ACTION_SETTARGETFPS: SetTargetFPS(event.params[0]); break; default: break; } @@ -2918,13 +2965,15 @@ bool IsMouseButtonUp(int button) // Get mouse position X int GetMouseX(void) { - return (int)((CORE.Input.Mouse.currentPosition.x + CORE.Input.Mouse.offset.x)*CORE.Input.Mouse.scale.x); + int mouseX = (int)((CORE.Input.Mouse.currentPosition.x + CORE.Input.Mouse.offset.x)*CORE.Input.Mouse.scale.x); + return mouseX; } // Get mouse position Y int GetMouseY(void) { - return (int)((CORE.Input.Mouse.currentPosition.y + CORE.Input.Mouse.offset.y)*CORE.Input.Mouse.scale.y); + int mouseY = (int)((CORE.Input.Mouse.currentPosition.y + CORE.Input.Mouse.offset.y)*CORE.Input.Mouse.scale.y); + return mouseY; } // Get mouse position XY @@ -2991,13 +3040,15 @@ Vector2 GetMouseWheelMoveV(void) // Get touch position X for touch point 0 (relative to screen size) int GetTouchX(void) { - return (int)CORE.Input.Touch.position[0].x; + int touchX = (int)CORE.Input.Touch.position[0].x; + return touchX; } // Get touch position Y for touch point 0 (relative to screen size) int GetTouchY(void) { - return (int)CORE.Input.Touch.position[0].y; + int touchY = (int)CORE.Input.Touch.position[0].y; + return touchY; } // Get touch position XY for a touch point index (relative to screen size) @@ -3039,10 +3090,10 @@ int GetTouchPointCount(void) // Initialize hi-resolution timer void InitTimer(void) { - // Setting a higher resolution can improve the accuracy of time-out intervals in wait functions. - // However, it can also reduce overall system performance, because the thread scheduler switches tasks more often. - // High resolutions can also prevent the CPU power management system from entering power-saving modes. - // Setting a higher resolution does not improve the accuracy of the high-resolution performance counter. + // Setting a higher resolution can improve the accuracy of time-out intervals in wait functions + // However, it can also reduce overall system performance, because the thread scheduler switches tasks more often + // High resolutions can also prevent the CPU power management system from entering power-saving modes + // Setting a higher resolution does not improve the accuracy of the high-resolution performance counter #if defined(_WIN32) && defined(SUPPORT_WINMM_HIGHRES_TIMER) && !defined(SUPPORT_BUSY_WAIT_LOOP) && !defined(PLATFORM_DESKTOP_SDL) timeBeginPeriod(1); // Setup high-resolution timer to 1ms (granularity of 1-2 ms) #endif @@ -3265,7 +3316,7 @@ static void ScanDirectoryFilesRecursively(const char *basePath, FilePathList *fi #if defined(SUPPORT_AUTOMATION_EVENTS) // Automation event recording -// NOTE: Recording is by default done at EndDrawing(), after PollInputEvents() +// NOTE: Recording is by default done at EndDrawing(), before PollInputEvents() static void RecordAutomationEvent(void) { // Checking events in current frame and save them into currentEventList @@ -3507,6 +3558,7 @@ static void RecordAutomationEvent(void) } //------------------------------------------------------------------------------------- +#if defined(SUPPORT_GESTURES_SYSTEM) // Gestures input currentEventList->events recording //------------------------------------------------------------------------------------- if (GESTURES.current != GESTURE_NONE) @@ -3524,16 +3576,7 @@ static void RecordAutomationEvent(void) if (currentEventList->count == currentEventList->capacity) return; // Security check } //------------------------------------------------------------------------------------- - - // Window events recording - //------------------------------------------------------------------------------------- - // TODO. - //------------------------------------------------------------------------------------- - - // Custom actions events recording - //------------------------------------------------------------------------------------- - // TODO. - //------------------------------------------------------------------------------------- +#endif } #endif diff --git a/raylib/rcore.go b/raylib/rcore.go index cad113d..7dfd092 100644 --- a/raylib/rcore.go +++ b/raylib/rcore.go @@ -920,7 +920,7 @@ func LoadAutomationEventList(fileName string) AutomationEventList { // UnloadAutomationEventList - Unload automation events list from file func UnloadAutomationEventList(list *AutomationEventList) { - C.UnloadAutomationEventList(list.cptr()) + C.UnloadAutomationEventList(*list.cptr()) } // ExportAutomationEventList - Export automation events list as text file diff --git a/raylib/rgestures.h b/raylib/rgestures.h index 9161b74..664a6e1 100644 --- a/raylib/rgestures.h +++ b/raylib/rgestures.h @@ -21,7 +21,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2023 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2024 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/raylib/rlgl.h b/raylib/rlgl.h index 6cf9c7e..513dd3e 100644 --- a/raylib/rlgl.h +++ b/raylib/rlgl.h @@ -1,6 +1,6 @@ /********************************************************************************************** * -* rlgl v4.5 - A multi-OpenGL abstraction layer with an immediate-mode style API +* rlgl v5.0 - A multi-OpenGL abstraction layer with an immediate-mode style API * * DESCRIPTION: * An abstraction layer for multiple OpenGL versions (1.1, 2.1, 3.3 Core, 4.3 Core, ES 2.0) @@ -62,17 +62,17 @@ * When loading a shader, the following vertex attributes and uniform * location names are tried to be set automatically: * -* #define RL_DEFAULT_SHADER_ATTRIB_NAME_POSITION "vertexPosition" // Bound by default to shader location: 0 -* #define RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD "vertexTexCoord" // Bound by default to shader location: 1 -* #define RL_DEFAULT_SHADER_ATTRIB_NAME_NORMAL "vertexNormal" // Bound by default to shader location: 2 -* #define RL_DEFAULT_SHADER_ATTRIB_NAME_COLOR "vertexColor" // Bound by default to shader location: 3 -* #define RL_DEFAULT_SHADER_ATTRIB_NAME_TANGENT "vertexTangent" // Bound by default to shader location: 4 -* #define RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD2 "vertexTexCoord2" // Bound by default to shader location: 5 +* #define RL_DEFAULT_SHADER_ATTRIB_NAME_POSITION "vertexPosition" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION +* #define RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD "vertexTexCoord" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD +* #define RL_DEFAULT_SHADER_ATTRIB_NAME_NORMAL "vertexNormal" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL +* #define RL_DEFAULT_SHADER_ATTRIB_NAME_COLOR "vertexColor" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_LOCATION_COLOR +* #define RL_DEFAULT_SHADER_ATTRIB_NAME_TANGENT "vertexTangent" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_LOCATION_TANGENT +* #define RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD2 "vertexTexCoord2" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD2 * #define RL_DEFAULT_SHADER_UNIFORM_NAME_MVP "mvp" // model-view-projection matrix * #define RL_DEFAULT_SHADER_UNIFORM_NAME_VIEW "matView" // view matrix * #define RL_DEFAULT_SHADER_UNIFORM_NAME_PROJECTION "matProjection" // projection matrix * #define RL_DEFAULT_SHADER_UNIFORM_NAME_MODEL "matModel" // model matrix -* #define RL_DEFAULT_SHADER_UNIFORM_NAME_NORMAL "matNormal" // normal matrix (transpose(inverse(matModelView)) +* #define RL_DEFAULT_SHADER_UNIFORM_NAME_NORMAL "matNormal" // normal matrix (transpose(inverse(matModelView))) * #define RL_DEFAULT_SHADER_UNIFORM_NAME_COLOR "colDiffuse" // color diffuse (base tint color, multiplied by texture color) * #define RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE0 "texture0" // texture0 (texture slot active 0) * #define RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE1 "texture1" // texture1 (texture slot active 1) @@ -85,7 +85,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2023 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2024 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. @@ -107,16 +107,17 @@ #ifndef RLGL_H #define RLGL_H -#define RLGL_VERSION "4.5" +#define RLGL_VERSION "5.0" -// Function specifiers in case library is build/used as a shared library (Windows) +// Function specifiers in case library is build/used as a shared library // NOTE: Microsoft specifiers to tell compiler that symbols are imported/exported from a .dll -#if defined(_WIN32) - #if defined(BUILD_LIBTYPE_SHARED) - #define RLAPI __declspec(dllexport) // We are building the library as a Win32 shared library (.dll) - #elif defined(USE_LIBTYPE_SHARED) - #define RLAPI __declspec(dllimport) // We are using the library as a Win32 shared library (.dll) - #endif +// NOTE: visibility(default) attribute makes symbols "visible" when compiled with -fvisibility=hidden +#if defined(_WIN32) && defined(BUILD_LIBTYPE_SHARED) + #define RLAPI __declspec(dllexport) // We are building the library as a Win32 shared library (.dll) +#elif defined(BUILD_LIBTYPE_SHARED) + #define RLAPI __attribute__((visibility("default"))) // We are building the library as a Unix shared library (.so/.dylib) +#elif defined(_WIN32) && defined(USE_LIBTYPE_SHARED) + #define RLAPI __declspec(dllimport) // We are using the library as a Win32 shared library (.dll) #endif // Function specifiers definition @@ -318,6 +319,28 @@ #define RL_BLEND_SRC_ALPHA 0x80CB // GL_BLEND_SRC_ALPHA #define RL_BLEND_COLOR 0x8005 // GL_BLEND_COLOR +#define RL_READ_FRAMEBUFFER 0x8CA8 // GL_READ_FRAMEBUFFER +#define RL_DRAW_FRAMEBUFFER 0x8CA9 // GL_DRAW_FRAMEBUFFER + +// Default shader vertex attribute locations +#ifndef RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION + #define RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION 0 +#endif +#ifndef RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD + #define RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD 1 +#endif +#ifndef RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL + #define RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL 2 +#endif +#ifndef RL_DEFAULT_SHADER_ATTRIB_LOCATION_COLOR + #define RL_DEFAULT_SHADER_ATTRIB_LOCATION_COLOR 3 +#endif + #ifndef RL_DEFAULT_SHADER_ATTRIB_LOCATION_TANGENT +#define RL_DEFAULT_SHADER_ATTRIB_LOCATION_TANGENT 4 +#endif +#ifndef RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD2 + #define RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD2 5 +#endif //---------------------------------------------------------------------------------- // Types and Structures Definition @@ -346,6 +369,7 @@ typedef struct rlVertexBuffer { float *vertices; // Vertex position (XYZ - 3 components per vertex) (shader-location = 0) float *texcoords; // Vertex texture coordinates (UV - 2 components per vertex) (shader-location = 1) + float *normals; // Vertex normal (XYZ - 3 components per vertex) (shader-location = 2) unsigned char *colors; // Vertex colors (RGBA - 4 components per vertex) (shader-location = 3) #if defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_33) unsigned int *indices; // Vertex indices (in case vertex data comes indexed) (6 indices per quad) @@ -354,7 +378,7 @@ typedef struct rlVertexBuffer { unsigned short *indices; // Vertex indices (in case vertex data comes indexed) (6 indices per quad) #endif unsigned int vaoId; // OpenGL Vertex Array Object id - unsigned int vboId[4]; // OpenGL Vertex Buffer Objects id (4 types of vertex data) + unsigned int vboId[5]; // OpenGL Vertex Buffer Objects id (5 types of vertex data) } rlVertexBuffer; // Draw call type @@ -555,30 +579,33 @@ typedef enum { extern "C" { // Prevents name mangling of functions #endif -RLAPI void rlMatrixMode(int mode); // Choose the current matrix to be transformed -RLAPI void rlPushMatrix(void); // Push the current matrix to stack -RLAPI void rlPopMatrix(void); // Pop latest inserted matrix from stack -RLAPI void rlLoadIdentity(void); // Reset current matrix to identity matrix -RLAPI void rlTranslatef(float x, float y, float z); // Multiply the current matrix by a translation matrix -RLAPI void rlRotatef(float angle, float x, float y, float z); // Multiply the current matrix by a rotation matrix -RLAPI void rlScalef(float x, float y, float z); // Multiply the current matrix by a scaling matrix -RLAPI void rlMultMatrixf(const float *matf); // Multiply the current matrix by another matrix +RLAPI void rlMatrixMode(int mode); // Choose the current matrix to be transformed +RLAPI void rlPushMatrix(void); // Push the current matrix to stack +RLAPI void rlPopMatrix(void); // Pop latest inserted matrix from stack +RLAPI void rlLoadIdentity(void); // Reset current matrix to identity matrix +RLAPI void rlTranslatef(float x, float y, float z); // Multiply the current matrix by a translation matrix +RLAPI void rlRotatef(float angle, float x, float y, float z); // Multiply the current matrix by a rotation matrix +RLAPI void rlScalef(float x, float y, float z); // Multiply the current matrix by a scaling matrix +RLAPI void rlMultMatrixf(const float *matf); // Multiply the current matrix by another matrix RLAPI void rlFrustum(double left, double right, double bottom, double top, double znear, double zfar); RLAPI void rlOrtho(double left, double right, double bottom, double top, double znear, double zfar); RLAPI void rlViewport(int x, int y, int width, int height); // Set the viewport area +RLAPI void rlSetClipPlanes(double near, double far); // Set clip planes distances +RLAPI double rlGetCullDistanceNear(); // Get cull plane distance near +RLAPI double rlGetCullDistanceFar(); // Get cull plane distance far //------------------------------------------------------------------------------------ // Functions Declaration - Vertex level operations //------------------------------------------------------------------------------------ -RLAPI void rlBegin(int mode); // Initialize drawing mode (how to organize vertex) -RLAPI void rlEnd(void); // Finish vertex providing -RLAPI void rlVertex2i(int x, int y); // Define one vertex (position) - 2 int -RLAPI void rlVertex2f(float x, float y); // Define one vertex (position) - 2 float -RLAPI void rlVertex3f(float x, float y, float z); // Define one vertex (position) - 3 float -RLAPI void rlTexCoord2f(float x, float y); // Define one vertex (texture coordinate) - 2 float -RLAPI void rlNormal3f(float x, float y, float z); // Define one vertex (normal) - 3 float -RLAPI void rlColor4ub(unsigned char r, unsigned char g, unsigned char b, unsigned char a); // Define one vertex (color) - 4 byte -RLAPI void rlColor3f(float x, float y, float z); // Define one vertex (color) - 3 float +RLAPI void rlBegin(int mode); // Initialize drawing mode (how to organize vertex) +RLAPI void rlEnd(void); // Finish vertex providing +RLAPI void rlVertex2i(int x, int y); // Define one vertex (position) - 2 int +RLAPI void rlVertex2f(float x, float y); // Define one vertex (position) - 2 float +RLAPI void rlVertex3f(float x, float y, float z); // Define one vertex (position) - 3 float +RLAPI void rlTexCoord2f(float x, float y); // Define one vertex (texture coordinate) - 2 float +RLAPI void rlNormal3f(float x, float y, float z); // Define one vertex (normal) - 3 float +RLAPI void rlColor4ub(unsigned char r, unsigned char g, unsigned char b, unsigned char a); // Define one vertex (color) - 4 byte +RLAPI void rlColor3f(float x, float y, float z); // Define one vertex (color) - 3 float RLAPI void rlColor4f(float x, float y, float z, float w); // Define one vertex (color) - 4 float //------------------------------------------------------------------------------------ @@ -592,13 +619,13 @@ RLAPI bool rlEnableVertexArray(unsigned int vaoId); // Enable vertex array ( RLAPI void rlDisableVertexArray(void); // Disable vertex array (VAO, if supported) RLAPI void rlEnableVertexBuffer(unsigned int id); // Enable vertex buffer (VBO) RLAPI void rlDisableVertexBuffer(void); // Disable vertex buffer (VBO) -RLAPI void rlEnableVertexBufferElement(unsigned int id);// Enable vertex buffer element (VBO element) +RLAPI void rlEnableVertexBufferElement(unsigned int id); // Enable vertex buffer element (VBO element) RLAPI void rlDisableVertexBufferElement(void); // Disable vertex buffer element (VBO element) RLAPI void rlEnableVertexAttribute(unsigned int index); // Enable vertex attribute index -RLAPI void rlDisableVertexAttribute(unsigned int index);// Disable vertex attribute index +RLAPI void rlDisableVertexAttribute(unsigned int index); // Disable vertex attribute index #if defined(GRAPHICS_API_OPENGL_11) -RLAPI void rlEnableStatePointer(int vertexAttribType, void *buffer); // Enable attribute state pointer -RLAPI void rlDisableStatePointer(int vertexAttribType); // Disable attribute state pointer +RLAPI void rlEnableStatePointer(int vertexAttribType, void *buffer); // Enable attribute state pointer +RLAPI void rlDisableStatePointer(int vertexAttribType); // Disable attribute state pointer #endif // Textures state @@ -617,11 +644,13 @@ RLAPI void rlDisableShader(void); // Disable shader progra // Framebuffer state RLAPI void rlEnableFramebuffer(unsigned int id); // Enable render texture (fbo) RLAPI void rlDisableFramebuffer(void); // Disable render texture (fbo), return to default framebuffer +RLAPI unsigned int rlGetActiveFramebuffer(void); // Get the currently active render texture (fbo), 0 for default framebuffer RLAPI void rlActiveDrawBuffers(int count); // Activate multiple draw color buffers RLAPI void rlBlitFramebuffer(int srcX, int srcY, int srcWidth, int srcHeight, int dstX, int dstY, int dstWidth, int dstHeight, int bufferMask); // Blit active framebuffer to main framebuffer +RLAPI void rlBindFramebuffer(unsigned int target, unsigned int framebuffer); // Bind framebuffer (FBO) // General render state -RLAPI void rlEnableColorBlend(void); // Enable color blending +RLAPI void rlEnableColorBlend(void); // Enable color blending RLAPI void rlDisableColorBlend(void); // Disable color blending RLAPI void rlEnableDepthTest(void); // Enable depth test RLAPI void rlDisableDepthTest(void); // Disable depth test @@ -629,12 +658,13 @@ RLAPI void rlEnableDepthMask(void); // Enable depth write RLAPI void rlDisableDepthMask(void); // Disable depth write RLAPI void rlEnableBackfaceCulling(void); // Enable backface culling RLAPI void rlDisableBackfaceCulling(void); // Disable backface culling +RLAPI void rlColorMask(bool r, bool g, bool b, bool a); // Color mask control RLAPI void rlSetCullFace(int mode); // Set face culling mode RLAPI void rlEnableScissorTest(void); // Enable scissor test RLAPI void rlDisableScissorTest(void); // Disable scissor test RLAPI void rlScissor(int x, int y, int width, int height); // Scissor test RLAPI void rlEnableWireMode(void); // Enable wire mode -RLAPI void rlEnablePointMode(void); // Enable point mode +RLAPI void rlEnablePointMode(void); // Enable point mode RLAPI void rlDisableWireMode(void); // Disable wire mode ( and point ) maybe rename RLAPI void rlSetLineWidth(float width); // Set the line drawing width RLAPI float rlGetLineWidth(void); // Get the line drawing width @@ -671,48 +701,48 @@ RLAPI int *rlGetShaderLocsDefault(void); // Get default shader lo // Render batch management // NOTE: rlgl provides a default render batch to behave like OpenGL 1.1 immediate mode // but this render batch API is exposed in case of custom batches are required -RLAPI rlRenderBatch rlLoadRenderBatch(int numBuffers, int bufferElements); // Load a render batch system -RLAPI void rlUnloadRenderBatch(rlRenderBatch batch); // Unload render batch system -RLAPI void rlDrawRenderBatch(rlRenderBatch *batch); // Draw render batch data (Update->Draw->Reset) -RLAPI void rlSetRenderBatchActive(rlRenderBatch *batch); // Set the active render batch for rlgl (NULL for default internal) -RLAPI void rlDrawRenderBatchActive(void); // Update and draw internal render batch -RLAPI bool rlCheckRenderBatchLimit(int vCount); // Check internal buffer overflow for a given number of vertex +RLAPI rlRenderBatch rlLoadRenderBatch(int numBuffers, int bufferElements); // Load a render batch system +RLAPI void rlUnloadRenderBatch(rlRenderBatch batch); // Unload render batch system +RLAPI void rlDrawRenderBatch(rlRenderBatch *batch); // Draw render batch data (Update->Draw->Reset) +RLAPI void rlSetRenderBatchActive(rlRenderBatch *batch); // Set the active render batch for rlgl (NULL for default internal) +RLAPI void rlDrawRenderBatchActive(void); // Update and draw internal render batch +RLAPI bool rlCheckRenderBatchLimit(int vCount); // Check internal buffer overflow for a given number of vertex RLAPI void rlSetTexture(unsigned int id); // Set current texture for render batch and check buffers limits //------------------------------------------------------------------------------------------------------------------------ // Vertex buffers management -RLAPI unsigned int rlLoadVertexArray(void); // Load vertex array (vao) if supported -RLAPI unsigned int rlLoadVertexBuffer(const void *buffer, int size, bool dynamic); // Load a vertex buffer attribute -RLAPI unsigned int rlLoadVertexBufferElement(const void *buffer, int size, bool dynamic); // Load a new attributes element buffer -RLAPI void rlUpdateVertexBuffer(unsigned int bufferId, const void *data, int dataSize, int offset); // Update GPU buffer with new data -RLAPI void rlUpdateVertexBufferElements(unsigned int id, const void *data, int dataSize, int offset); // Update vertex buffer elements with new data -RLAPI void rlUnloadVertexArray(unsigned int vaoId); -RLAPI void rlUnloadVertexBuffer(unsigned int vboId); -RLAPI void rlSetVertexAttribute(unsigned int index, int compSize, int type, bool normalized, int stride, const void *pointer); -RLAPI void rlSetVertexAttributeDivisor(unsigned int index, int divisor); -RLAPI void rlSetVertexAttributeDefault(int locIndex, const void *value, int attribType, int count); // Set vertex attribute default value -RLAPI void rlDrawVertexArray(int offset, int count); -RLAPI void rlDrawVertexArrayElements(int offset, int count, const void *buffer); -RLAPI void rlDrawVertexArrayInstanced(int offset, int count, int instances); -RLAPI void rlDrawVertexArrayElementsInstanced(int offset, int count, const void *buffer, int instances); +RLAPI unsigned int rlLoadVertexArray(void); // Load vertex array (vao) if supported +RLAPI unsigned int rlLoadVertexBuffer(const void *buffer, int size, bool dynamic); // Load a vertex buffer object +RLAPI unsigned int rlLoadVertexBufferElement(const void *buffer, int size, bool dynamic); // Load vertex buffer elements object +RLAPI void rlUpdateVertexBuffer(unsigned int bufferId, const void *data, int dataSize, int offset); // Update vertex buffer object data on GPU buffer +RLAPI void rlUpdateVertexBufferElements(unsigned int id, const void *data, int dataSize, int offset); // Update vertex buffer elements data on GPU buffer +RLAPI void rlUnloadVertexArray(unsigned int vaoId); // Unload vertex array (vao) +RLAPI void rlUnloadVertexBuffer(unsigned int vboId); // Unload vertex buffer object +RLAPI void rlSetVertexAttribute(unsigned int index, int compSize, int type, bool normalized, int stride, int offset); // Set vertex attribute data configuration +RLAPI void rlSetVertexAttributeDivisor(unsigned int index, int divisor); // Set vertex attribute data divisor +RLAPI void rlSetVertexAttributeDefault(int locIndex, const void *value, int attribType, int count); // Set vertex attribute default value, when attribute to provided +RLAPI void rlDrawVertexArray(int offset, int count); // Draw vertex array (currently active vao) +RLAPI void rlDrawVertexArrayElements(int offset, int count, const void *buffer); // Draw vertex array elements +RLAPI void rlDrawVertexArrayInstanced(int offset, int count, int instances); // Draw vertex array (currently active vao) with instancing +RLAPI void rlDrawVertexArrayElementsInstanced(int offset, int count, const void *buffer, int instances); // Draw vertex array elements with instancing // Textures management -RLAPI unsigned int rlLoadTexture(const void *data, int width, int height, int format, int mipmapCount); // Load texture in GPU -RLAPI unsigned int rlLoadTextureDepth(int width, int height, bool useRenderBuffer); // Load depth texture/renderbuffer (to be attached to fbo) -RLAPI unsigned int rlLoadTextureCubemap(const void *data, int size, int format); // Load texture cubemap -RLAPI void rlUpdateTexture(unsigned int id, int offsetX, int offsetY, int width, int height, int format, const void *data); // Update GPU texture with new data -RLAPI void rlGetGlTextureFormats(int format, unsigned int *glInternalFormat, unsigned int *glFormat, unsigned int *glType); // Get OpenGL internal formats +RLAPI unsigned int rlLoadTexture(const void *data, int width, int height, int format, int mipmapCount); // Load texture data +RLAPI unsigned int rlLoadTextureDepth(int width, int height, bool useRenderBuffer); // Load depth texture/renderbuffer (to be attached to fbo) +RLAPI unsigned int rlLoadTextureCubemap(const void *data, int size, int format); // Load texture cubemap data +RLAPI void rlUpdateTexture(unsigned int id, int offsetX, int offsetY, int width, int height, int format, const void *data); // Update texture with new data on GPU +RLAPI void rlGetGlTextureFormats(int format, unsigned int *glInternalFormat, unsigned int *glFormat, unsigned int *glType); // Get OpenGL internal formats RLAPI const char *rlGetPixelFormatName(unsigned int format); // Get name string for pixel format RLAPI void rlUnloadTexture(unsigned int id); // Unload texture from GPU memory RLAPI void rlGenTextureMipmaps(unsigned int id, int width, int height, int format, int *mipmaps); // Generate mipmap data for selected texture -RLAPI void *rlReadTexturePixels(unsigned int id, int width, int height, int format); // Read texture pixel data +RLAPI void *rlReadTexturePixels(unsigned int id, int width, int height, int format); // Read texture pixel data RLAPI unsigned char *rlReadScreenPixels(int width, int height); // Read screen pixel data (color buffer) // Framebuffer management (fbo) -RLAPI unsigned int rlLoadFramebuffer(int width, int height); // Load an empty framebuffer -RLAPI void rlFramebufferAttach(unsigned int fboId, unsigned int texId, int attachType, int texType, int mipLevel); // Attach texture/renderbuffer to a framebuffer +RLAPI unsigned int rlLoadFramebuffer(void); // Load an empty framebuffer +RLAPI void rlFramebufferAttach(unsigned int fboId, unsigned int texId, int attachType, int texType, int mipLevel); // Attach texture/renderbuffer to a framebuffer RLAPI bool rlFramebufferComplete(unsigned int id); // Verify framebuffer is complete RLAPI void rlUnloadFramebuffer(unsigned int id); // Delete framebuffer from GPU @@ -723,14 +753,14 @@ RLAPI unsigned int rlLoadShaderProgram(unsigned int vShaderId, unsigned int fSha RLAPI void rlUnloadShaderProgram(unsigned int id); // Unload shader program RLAPI int rlGetLocationUniform(unsigned int shaderId, const char *uniformName); // Get shader location uniform RLAPI int rlGetLocationAttrib(unsigned int shaderId, const char *attribName); // Get shader location attribute -RLAPI void rlSetUniform(int locIndex, const void *value, int uniformType, int count); // Set shader value uniform +RLAPI void rlSetUniform(int locIndex, const void *value, int uniformType, int count); // Set shader value uniform RLAPI void rlSetUniformMatrix(int locIndex, Matrix mat); // Set shader value matrix RLAPI void rlSetUniformSampler(int locIndex, unsigned int textureId); // Set shader value sampler RLAPI void rlSetShader(unsigned int id, int *locs); // Set shader currently active (id and locations) // Compute shader management RLAPI unsigned int rlLoadComputeShaderProgram(unsigned int shaderId); // Load compute shader program -RLAPI void rlComputeShaderDispatch(unsigned int groupX, unsigned int groupY, unsigned int groupZ); // Dispatch compute shader (equivalent to *draw* for graphics pipeline) +RLAPI void rlComputeShaderDispatch(unsigned int groupX, unsigned int groupY, unsigned int groupZ); // Dispatch compute shader (equivalent to *draw* for graphics pipeline) // Shader buffer storage object management (ssbo) RLAPI unsigned int rlLoadShaderBuffer(unsigned int size, const void *data, int usageHint); // Load shader storage buffer object (SSBO) @@ -773,6 +803,12 @@ RLAPI void rlLoadDrawQuad(void); // Load and draw a quad #if defined(RLGL_IMPLEMENTATION) +// Expose OpenGL functions from glad in raylib +#if defined(BUILD_LIBTYPE_SHARED) + #define GLAD_API_CALL_EXPORT + #define GLAD_API_CALL_EXPORT_BUILD +#endif + #if defined(GRAPHICS_API_OPENGL_11) #if defined(__APPLE__) #include // OpenGL 1.1 library for OSX @@ -891,6 +927,14 @@ RLAPI void rlLoadDrawQuad(void); // Load and draw a quad #define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE #endif +#ifndef GL_PROGRAM_POINT_SIZE + #define GL_PROGRAM_POINT_SIZE 0x8642 +#endif + +#ifndef GL_LINE_WIDTH + #define GL_LINE_WIDTH 0x0B21 +#endif + #if defined(GRAPHICS_API_OPENGL_11) #define GL_UNSIGNED_SHORT_5_6_5 0x8363 #define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 @@ -912,22 +956,22 @@ RLAPI void rlLoadDrawQuad(void); // Load and draw a quad // Default shader vertex attribute names to set location points #ifndef RL_DEFAULT_SHADER_ATTRIB_NAME_POSITION - #define RL_DEFAULT_SHADER_ATTRIB_NAME_POSITION "vertexPosition" // Bound by default to shader location: 0 + #define RL_DEFAULT_SHADER_ATTRIB_NAME_POSITION "vertexPosition" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_NAME_POSITION #endif #ifndef RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD - #define RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD "vertexTexCoord" // Bound by default to shader location: 1 + #define RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD "vertexTexCoord" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD #endif #ifndef RL_DEFAULT_SHADER_ATTRIB_NAME_NORMAL - #define RL_DEFAULT_SHADER_ATTRIB_NAME_NORMAL "vertexNormal" // Bound by default to shader location: 2 + #define RL_DEFAULT_SHADER_ATTRIB_NAME_NORMAL "vertexNormal" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_NAME_NORMAL #endif #ifndef RL_DEFAULT_SHADER_ATTRIB_NAME_COLOR - #define RL_DEFAULT_SHADER_ATTRIB_NAME_COLOR "vertexColor" // Bound by default to shader location: 3 + #define RL_DEFAULT_SHADER_ATTRIB_NAME_COLOR "vertexColor" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_NAME_COLOR #endif #ifndef RL_DEFAULT_SHADER_ATTRIB_NAME_TANGENT - #define RL_DEFAULT_SHADER_ATTRIB_NAME_TANGENT "vertexTangent" // Bound by default to shader location: 4 + #define RL_DEFAULT_SHADER_ATTRIB_NAME_TANGENT "vertexTangent" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_NAME_TANGENT #endif #ifndef RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD2 - #define RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD2 "vertexTexCoord2" // Bound by default to shader location: 5 + #define RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD2 "vertexTexCoord2" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD2 #endif #ifndef RL_DEFAULT_SHADER_UNIFORM_NAME_MVP @@ -1042,6 +1086,9 @@ typedef void *(*rlglLoadProc)(const char *name); // OpenGL extension functions //---------------------------------------------------------------------------------- // Global Variables Definition //---------------------------------------------------------------------------------- +static double rlCullDistanceNear = RL_CULL_DISTANCE_NEAR; +static double rlCullDistanceFar = RL_CULL_DISTANCE_FAR; + #if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) static rlglData RLGL = { 0 }; #endif // GRAPHICS_API_OPENGL_33 || GRAPHICS_API_OPENGL_ES2 @@ -1072,8 +1119,15 @@ static const char *rlGetCompressedFormatName(int format); // Get compressed form static int rlGetPixelDataSize(int width, int height, int format); // Get pixel data size in bytes (image or texture) // Auxiliar matrix math functions +typedef struct rl_float16 { + float v[16]; +} rl_float16; +static rl_float16 rlMatrixToFloatV(Matrix mat); // Get float array of matrix data +#define rlMatrixToFloat(mat) (rlMatrixToFloatV(mat).v) // Get float vector for Matrix static Matrix rlMatrixIdentity(void); // Get identity matrix static Matrix rlMatrixMultiply(Matrix left, Matrix right); // Multiply two matrices +static Matrix rlMatrixTranspose(Matrix mat); // Transposes provided matrix +static Matrix rlMatrixInvert(Matrix mat); // Invert provided matrix //---------------------------------------------------------------------------------- // Module Functions Definition - Matrix operations @@ -1242,7 +1296,7 @@ void rlMultMatrixf(const float *matf) matf[2], matf[6], matf[10], matf[14], matf[3], matf[7], matf[11], matf[15] }; - *RLGL.State.currentMatrix = rlMatrixMultiply(*RLGL.State.currentMatrix, mat); + *RLGL.State.currentMatrix = rlMatrixMultiply(mat, *RLGL.State.currentMatrix); } // Multiply the current matrix by a perspective matrix generated by parameters @@ -1316,6 +1370,25 @@ void rlViewport(int x, int y, int width, int height) glViewport(x, y, width, height); } +// Set clip planes distances +void rlSetClipPlanes(double near, double far) +{ + rlCullDistanceNear = near; + rlCullDistanceFar = far; +} + +// Get cull plane distance near +double rlGetCullDistanceNear(void) +{ + return rlCullDistanceNear; +} + +// Get cull plane distance far +double rlGetCullDistanceFar(void) +{ + return rlCullDistanceFar; +} + //---------------------------------------------------------------------------------- // Module Functions Definition - Vertex level operations //---------------------------------------------------------------------------------- @@ -1436,7 +1509,10 @@ void rlVertex3f(float x, float y, float z) RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].texcoords[2*RLGL.State.vertexCounter] = RLGL.State.texcoordx; RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].texcoords[2*RLGL.State.vertexCounter + 1] = RLGL.State.texcoordy; - // WARNING: By default rlVertexBuffer struct does not store normals + // Add current normal + RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].normals[3*RLGL.State.vertexCounter] = RLGL.State.normalx; + RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].normals[3*RLGL.State.vertexCounter + 1] = RLGL.State.normaly; + RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].normals[3*RLGL.State.vertexCounter + 2] = RLGL.State.normalz; // Add current color RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].colors[4*RLGL.State.vertexCounter] = RLGL.State.colorr; @@ -1472,9 +1548,26 @@ void rlTexCoord2f(float x, float y) // NOTE: Normals limited to TRIANGLES only? void rlNormal3f(float x, float y, float z) { - RLGL.State.normalx = x; - RLGL.State.normaly = y; - RLGL.State.normalz = z; + float normalx = x; + float normaly = y; + float normalz = z; + if (RLGL.State.transformRequired) + { + normalx = RLGL.State.transform.m0*x + RLGL.State.transform.m4*y + RLGL.State.transform.m8*z; + normaly = RLGL.State.transform.m1*x + RLGL.State.transform.m5*y + RLGL.State.transform.m9*z; + normalz = RLGL.State.transform.m2*x + RLGL.State.transform.m6*y + RLGL.State.transform.m10*z; + } + float length = sqrtf(normalx*normalx + normaly*normaly + normalz*normalz); + if (length != 0.0f) + { + float ilength = 1.0f / length; + normalx *= ilength; + normaly *= ilength; + normalz *= ilength; + } + RLGL.State.normalx = normalx; + RLGL.State.normaly = normaly; + RLGL.State.normalz = normalz; } // Define one vertex (color) @@ -1713,6 +1806,16 @@ void rlEnableFramebuffer(unsigned int id) #endif } +// return the active render texture (fbo) +unsigned int rlGetActiveFramebuffer(void) +{ + GLint fboId = 0; +#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES3)) && defined(RLGL_RENDER_TEXTURES_HINT) + glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &fboId); +#endif + return fboId; +} + // Disable rendering to texture void rlDisableFramebuffer(void) { @@ -1729,6 +1832,14 @@ void rlBlitFramebuffer(int srcX, int srcY, int srcWidth, int srcHeight, int dstX #endif } +// Bind framebuffer object (fbo) +void rlBindFramebuffer(unsigned int target, unsigned int framebuffer) +{ +#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) && defined(RLGL_RENDER_TEXTURES_HINT) + glBindFramebuffer(target, framebuffer); +#endif +} + // Activate multiple draw color buffers // NOTE: One color buffer is always active by default void rlActiveDrawBuffers(int count) @@ -1805,6 +1916,9 @@ void rlEnableBackfaceCulling(void) { glEnable(GL_CULL_FACE); } // Disable backface culling void rlDisableBackfaceCulling(void) { glDisable(GL_CULL_FACE); } +// Set color mask active for screen read/draw +void rlColorMask(bool r, bool g, bool b, bool a) { glColorMask(r, g, b, a); } + // Set face culling mode void rlSetCullFace(int mode) { @@ -2122,7 +2236,10 @@ void rlglInit(int width, int height) RLGL.State.currentShaderLocs = RLGL.State.defaultShaderLocs; // Init default vertex arrays buffers + // Simulate that the default shader has the location RL_SHADER_LOC_VERTEX_NORMAL to bind the normal buffer for the default render batch + RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_NORMAL] = RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL; RLGL.defaultBatch = rlLoadRenderBatch(RL_DEFAULT_BATCH_BUFFERS, RL_DEFAULT_BATCH_BUFFER_ELEMENTS); + RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_NORMAL] = -1; RLGL.currentBatch = &RLGL.defaultBatch; // Init stack matrices (emulating OpenGL 1.1) @@ -2567,6 +2684,7 @@ rlRenderBatch rlLoadRenderBatch(int numBuffers, int bufferElements) batch.vertexBuffer[i].vertices = (float *)RL_MALLOC(bufferElements*3*4*sizeof(float)); // 3 float by vertex, 4 vertex by quad batch.vertexBuffer[i].texcoords = (float *)RL_MALLOC(bufferElements*2*4*sizeof(float)); // 2 float by texcoord, 4 texcoord by quad + batch.vertexBuffer[i].normals = (float *)RL_MALLOC(bufferElements*3*4*sizeof(float)); // 3 float by vertex, 4 vertex by quad batch.vertexBuffer[i].colors = (unsigned char *)RL_MALLOC(bufferElements*4*4*sizeof(unsigned char)); // 4 float by color, 4 colors by quad #if defined(GRAPHICS_API_OPENGL_33) batch.vertexBuffer[i].indices = (unsigned int *)RL_MALLOC(bufferElements*6*sizeof(unsigned int)); // 6 int by quad (indices) @@ -2577,6 +2695,7 @@ rlRenderBatch rlLoadRenderBatch(int numBuffers, int bufferElements) for (int j = 0; j < (3*4*bufferElements); j++) batch.vertexBuffer[i].vertices[j] = 0.0f; for (int j = 0; j < (2*4*bufferElements); j++) batch.vertexBuffer[i].texcoords[j] = 0.0f; + for (int j = 0; j < (3*4*bufferElements); j++) batch.vertexBuffer[i].normals[j] = 0.0f; for (int j = 0; j < (4*4*bufferElements); j++) batch.vertexBuffer[i].colors[j] = 0; int k = 0; @@ -2626,16 +2745,23 @@ rlRenderBatch rlLoadRenderBatch(int numBuffers, int bufferElements) glEnableVertexAttribArray(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_TEXCOORD01]); glVertexAttribPointer(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_TEXCOORD01], 2, GL_FLOAT, 0, 0, 0); - // Vertex color buffer (shader-location = 3) + // Vertex normal buffer (shader-location = 2) glGenBuffers(1, &batch.vertexBuffer[i].vboId[2]); glBindBuffer(GL_ARRAY_BUFFER, batch.vertexBuffer[i].vboId[2]); + glBufferData(GL_ARRAY_BUFFER, bufferElements*3*4*sizeof(float), batch.vertexBuffer[i].normals, GL_DYNAMIC_DRAW); + glEnableVertexAttribArray(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_NORMAL]); + glVertexAttribPointer(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_NORMAL], 3, GL_FLOAT, 0, 0, 0); + + // Vertex color buffer (shader-location = 3) + glGenBuffers(1, &batch.vertexBuffer[i].vboId[3]); + glBindBuffer(GL_ARRAY_BUFFER, batch.vertexBuffer[i].vboId[3]); glBufferData(GL_ARRAY_BUFFER, bufferElements*4*4*sizeof(unsigned char), batch.vertexBuffer[i].colors, GL_DYNAMIC_DRAW); glEnableVertexAttribArray(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_COLOR]); glVertexAttribPointer(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_COLOR], 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, 0); // Fill index buffer - glGenBuffers(1, &batch.vertexBuffer[i].vboId[3]); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, batch.vertexBuffer[i].vboId[3]); + glGenBuffers(1, &batch.vertexBuffer[i].vboId[4]); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, batch.vertexBuffer[i].vboId[4]); #if defined(GRAPHICS_API_OPENGL_33) glBufferData(GL_ELEMENT_ARRAY_BUFFER, bufferElements*6*sizeof(int), batch.vertexBuffer[i].indices, GL_STATIC_DRAW); #endif @@ -2690,10 +2816,10 @@ void rlUnloadRenderBatch(rlRenderBatch batch) if (RLGL.ExtSupported.vao) { glBindVertexArray(batch.vertexBuffer[i].vaoId); - glDisableVertexAttribArray(0); - glDisableVertexAttribArray(1); - glDisableVertexAttribArray(2); - glDisableVertexAttribArray(3); + glDisableVertexAttribArray(RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION); + glDisableVertexAttribArray(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD); + glDisableVertexAttribArray(RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL); + glDisableVertexAttribArray(RL_DEFAULT_SHADER_ATTRIB_LOCATION_COLOR); glBindVertexArray(0); } @@ -2702,6 +2828,7 @@ void rlUnloadRenderBatch(rlRenderBatch batch) glDeleteBuffers(1, &batch.vertexBuffer[i].vboId[1]); glDeleteBuffers(1, &batch.vertexBuffer[i].vboId[2]); glDeleteBuffers(1, &batch.vertexBuffer[i].vboId[3]); + glDeleteBuffers(1, &batch.vertexBuffer[i].vboId[4]); // Delete VAOs from GPU (VRAM) if (RLGL.ExtSupported.vao) glDeleteVertexArrays(1, &batch.vertexBuffer[i].vaoId); @@ -2709,6 +2836,7 @@ void rlUnloadRenderBatch(rlRenderBatch batch) // Free vertex arrays memory from CPU (RAM) RL_FREE(batch.vertexBuffer[i].vertices); RL_FREE(batch.vertexBuffer[i].texcoords); + RL_FREE(batch.vertexBuffer[i].normals); RL_FREE(batch.vertexBuffer[i].colors); RL_FREE(batch.vertexBuffer[i].indices); } @@ -2743,8 +2871,13 @@ void rlDrawRenderBatch(rlRenderBatch *batch) glBufferSubData(GL_ARRAY_BUFFER, 0, RLGL.State.vertexCounter*2*sizeof(float), batch->vertexBuffer[batch->currentBuffer].texcoords); //glBufferData(GL_ARRAY_BUFFER, sizeof(float)*2*4*batch->vertexBuffer[batch->currentBuffer].elementCount, batch->vertexBuffer[batch->currentBuffer].texcoords, GL_DYNAMIC_DRAW); // Update all buffer - // Colors buffer + // Normals buffer glBindBuffer(GL_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[2]); + glBufferSubData(GL_ARRAY_BUFFER, 0, RLGL.State.vertexCounter*3*sizeof(float), batch->vertexBuffer[batch->currentBuffer].normals); + //glBufferData(GL_ARRAY_BUFFER, sizeof(float)*3*4*batch->vertexBuffer[batch->currentBuffer].elementCount, batch->vertexBuffer[batch->currentBuffer].normals, GL_DYNAMIC_DRAW); // Update all buffer + + // Colors buffer + glBindBuffer(GL_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[3]); glBufferSubData(GL_ARRAY_BUFFER, 0, RLGL.State.vertexCounter*4*sizeof(unsigned char), batch->vertexBuffer[batch->currentBuffer].colors); //glBufferData(GL_ARRAY_BUFFER, sizeof(float)*4*4*batch->vertexBuffer[batch->currentBuffer].elementCount, batch->vertexBuffer[batch->currentBuffer].colors, GL_DYNAMIC_DRAW); // Update all buffer @@ -2797,13 +2930,30 @@ void rlDrawRenderBatch(rlRenderBatch *batch) // Create modelview-projection matrix and upload to shader Matrix matMVP = rlMatrixMultiply(RLGL.State.modelview, RLGL.State.projection); - float matMVPfloat[16] = { - matMVP.m0, matMVP.m1, matMVP.m2, matMVP.m3, - matMVP.m4, matMVP.m5, matMVP.m6, matMVP.m7, - matMVP.m8, matMVP.m9, matMVP.m10, matMVP.m11, - matMVP.m12, matMVP.m13, matMVP.m14, matMVP.m15 - }; - glUniformMatrix4fv(RLGL.State.currentShaderLocs[RL_SHADER_LOC_MATRIX_MVP], 1, false, matMVPfloat); + glUniformMatrix4fv(RLGL.State.currentShaderLocs[RL_SHADER_LOC_MATRIX_MVP], 1, false, rlMatrixToFloat(matMVP)); + + if (RLGL.State.currentShaderLocs[RL_SHADER_LOC_MATRIX_PROJECTION] != -1) + { + glUniformMatrix4fv(RLGL.State.currentShaderLocs[RL_SHADER_LOC_MATRIX_PROJECTION], 1, false, rlMatrixToFloat(RLGL.State.projection)); + } + + // WARNING: For the following setup of the view, model, and normal matrices, it is expected that + // transformations and rendering occur between rlPushMatrix and rlPopMatrix. + + if (RLGL.State.currentShaderLocs[RL_SHADER_LOC_MATRIX_VIEW] != -1) + { + glUniformMatrix4fv(RLGL.State.currentShaderLocs[RL_SHADER_LOC_MATRIX_VIEW], 1, false, rlMatrixToFloat(RLGL.State.modelview)); + } + + if (RLGL.State.currentShaderLocs[RL_SHADER_LOC_MATRIX_MODEL] != -1) + { + glUniformMatrix4fv(RLGL.State.currentShaderLocs[RL_SHADER_LOC_MATRIX_MODEL], 1, false, rlMatrixToFloat(RLGL.State.transform)); + } + + if (RLGL.State.currentShaderLocs[RL_SHADER_LOC_MATRIX_NORMAL] != -1) + { + glUniformMatrix4fv(RLGL.State.currentShaderLocs[RL_SHADER_LOC_MATRIX_NORMAL], 1, false, rlMatrixToFloat(rlMatrixTranspose(rlMatrixInvert(RLGL.State.transform)))); + } if (RLGL.ExtSupported.vao) glBindVertexArray(batch->vertexBuffer[batch->currentBuffer].vaoId); else @@ -2818,12 +2968,17 @@ void rlDrawRenderBatch(rlRenderBatch *batch) glVertexAttribPointer(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_TEXCOORD01], 2, GL_FLOAT, 0, 0, 0); glEnableVertexAttribArray(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_TEXCOORD01]); - // Bind vertex attrib: color (shader-location = 3) + // Bind vertex attrib: normal (shader-location = 2) glBindBuffer(GL_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[2]); + glVertexAttribPointer(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_NORMAL], 3, GL_FLOAT, 0, 0, 0); + glEnableVertexAttribArray(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_NORMAL]); + + // Bind vertex attrib: color (shader-location = 3) + glBindBuffer(GL_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[3]); glVertexAttribPointer(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_COLOR], 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, 0); glEnableVertexAttribArray(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_COLOR]); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[3]); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[4]); } // Setup some default shader values @@ -3378,7 +3533,6 @@ void rlGenTextureMipmaps(unsigned int id, int width, int height, int format, int #endif } - // Read texture pixel data void *rlReadTexturePixels(unsigned int id, int width, int height, int format) { @@ -3422,7 +3576,7 @@ void *rlReadTexturePixels(unsigned int id, int width, int height, int format) // 2 - Create an fbo, activate it, render quad with texture, glReadPixels() // We are using Option 1, just need to care for texture format on retrieval // NOTE: This behaviour could be conditioned by graphic driver... - unsigned int fboId = rlLoadFramebuffer(width, height); + unsigned int fboId = rlLoadFramebuffer(); glBindFramebuffer(GL_FRAMEBUFFER, fboId); glBindTexture(GL_TEXTURE_2D, 0); @@ -3476,7 +3630,7 @@ unsigned char *rlReadScreenPixels(int width, int height) //----------------------------------------------------------------------------------------- // Load a framebuffer to be used for rendering // NOTE: No textures attached -unsigned int rlLoadFramebuffer(int width, int height) +unsigned int rlLoadFramebuffer(void) { unsigned int fboId = 0; @@ -3784,10 +3938,14 @@ unsigned int rlLoadVertexArray(void) } // Set vertex attribute -void rlSetVertexAttribute(unsigned int index, int compSize, int type, bool normalized, int stride, const void *pointer) +void rlSetVertexAttribute(unsigned int index, int compSize, int type, bool normalized, int stride, int offset) { #if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glVertexAttribPointer(index, compSize, type, normalized, stride, pointer); + // NOTE: Data type could be: GL_BYTE, GL_UNSIGNED_BYTE, GL_SHORT, GL_UNSIGNED_SHORT, GL_INT, GL_UNSIGNED_INT + // Additional types (depends on OpenGL version or extensions): + // - GL_HALF_FLOAT, GL_FLOAT, GL_DOUBLE, GL_FIXED, + // - GL_INT_2_10_10_10_REV, GL_UNSIGNED_INT_2_10_10_10_REV, GL_UNSIGNED_INT_10F_11F_11F_REV + glVertexAttribPointer(index, compSize, type, normalized, stride, (void *)offset); #endif } @@ -3970,12 +4128,12 @@ unsigned int rlLoadShaderProgram(unsigned int vShaderId, unsigned int fShaderId) glAttachShader(program, fShaderId); // NOTE: Default attribute shader locations must be Bound before linking - glBindAttribLocation(program, 0, RL_DEFAULT_SHADER_ATTRIB_NAME_POSITION); - glBindAttribLocation(program, 1, RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD); - glBindAttribLocation(program, 2, RL_DEFAULT_SHADER_ATTRIB_NAME_NORMAL); - glBindAttribLocation(program, 3, RL_DEFAULT_SHADER_ATTRIB_NAME_COLOR); - glBindAttribLocation(program, 4, RL_DEFAULT_SHADER_ATTRIB_NAME_TANGENT); - glBindAttribLocation(program, 5, RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD2); + glBindAttribLocation(program, RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION, RL_DEFAULT_SHADER_ATTRIB_NAME_POSITION); + glBindAttribLocation(program, RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD, RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD); + glBindAttribLocation(program, RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL, RL_DEFAULT_SHADER_ATTRIB_NAME_NORMAL); + glBindAttribLocation(program, RL_DEFAULT_SHADER_ATTRIB_LOCATION_COLOR, RL_DEFAULT_SHADER_ATTRIB_NAME_COLOR); + glBindAttribLocation(program, RL_DEFAULT_SHADER_ATTRIB_LOCATION_TANGENT, RL_DEFAULT_SHADER_ATTRIB_NAME_TANGENT); + glBindAttribLocation(program, RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD2, RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD2); // NOTE: If some attrib name is no found on the shader, it locations becomes -1 @@ -4108,7 +4266,14 @@ void rlSetUniformSampler(int locIndex, unsigned int textureId) { #if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) // Check if texture is already active - for (int i = 0; i < RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS; i++) if (RLGL.State.activeTextureId[i] == textureId) return; + for (int i = 0; i < RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS; i++) + { + if (RLGL.State.activeTextureId[i] == textureId) + { + glUniform1i(locIndex, 1 + i); + return; + } + } // Register a new active texture for the internal batch system // NOTE: Default texture is always activated as GL_TEXTURE0 @@ -4431,10 +4596,10 @@ void rlLoadDrawQuad(void) glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), &vertices, GL_STATIC_DRAW); // Bind vertex attributes (position, texcoords) - glEnableVertexAttribArray(0); - glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5*sizeof(float), (void *)0); // Positions - glEnableVertexAttribArray(1); - glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5*sizeof(float), (void *)(3*sizeof(float))); // Texcoords + glEnableVertexAttribArray(RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION); + glVertexAttribPointer(RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION, 3, GL_FLOAT, GL_FALSE, 5*sizeof(float), (void *)0); // Positions + glEnableVertexAttribArray(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD); + glVertexAttribPointer(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD, 2, GL_FLOAT, GL_FALSE, 5*sizeof(float), (void *)(3*sizeof(float))); // Texcoords // Draw quad glBindVertexArray(quadVAO); @@ -4505,12 +4670,12 @@ void rlLoadDrawCube(void) // Bind vertex attributes (position, normals, texcoords) glBindVertexArray(cubeVAO); - glEnableVertexAttribArray(0); - glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8*sizeof(float), (void *)0); // Positions - glEnableVertexAttribArray(1); - glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8*sizeof(float), (void *)(3*sizeof(float))); // Normals - glEnableVertexAttribArray(2); - glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8*sizeof(float), (void *)(6*sizeof(float))); // Texcoords + glEnableVertexAttribArray(RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION); + glVertexAttribPointer(RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION, 3, GL_FLOAT, GL_FALSE, 8*sizeof(float), (void *)0); // Positions + glEnableVertexAttribArray(RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL); + glVertexAttribPointer(RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL, 3, GL_FLOAT, GL_FALSE, 8*sizeof(float), (void *)(3*sizeof(float))); // Normals + glEnableVertexAttribArray(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD); + glVertexAttribPointer(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD, 2, GL_FLOAT, GL_FALSE, 8*sizeof(float), (void *)(6*sizeof(float))); // Texcoords glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); @@ -4658,14 +4823,14 @@ static void rlLoadShaderDefault(void) TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Default shader loaded successfully", RLGL.State.defaultShaderId); // Set default shader locations: attributes locations - RLGL.State.defaultShaderLocs[RL_SHADER_LOC_VERTEX_POSITION] = glGetAttribLocation(RLGL.State.defaultShaderId, "vertexPosition"); - RLGL.State.defaultShaderLocs[RL_SHADER_LOC_VERTEX_TEXCOORD01] = glGetAttribLocation(RLGL.State.defaultShaderId, "vertexTexCoord"); - RLGL.State.defaultShaderLocs[RL_SHADER_LOC_VERTEX_COLOR] = glGetAttribLocation(RLGL.State.defaultShaderId, "vertexColor"); + RLGL.State.defaultShaderLocs[RL_SHADER_LOC_VERTEX_POSITION] = glGetAttribLocation(RLGL.State.defaultShaderId, RL_DEFAULT_SHADER_ATTRIB_NAME_POSITION); + RLGL.State.defaultShaderLocs[RL_SHADER_LOC_VERTEX_TEXCOORD01] = glGetAttribLocation(RLGL.State.defaultShaderId, RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD); + RLGL.State.defaultShaderLocs[RL_SHADER_LOC_VERTEX_COLOR] = glGetAttribLocation(RLGL.State.defaultShaderId, RL_DEFAULT_SHADER_ATTRIB_NAME_COLOR); // Set default shader locations: uniform locations - RLGL.State.defaultShaderLocs[RL_SHADER_LOC_MATRIX_MVP] = glGetUniformLocation(RLGL.State.defaultShaderId, "mvp"); - RLGL.State.defaultShaderLocs[RL_SHADER_LOC_COLOR_DIFFUSE] = glGetUniformLocation(RLGL.State.defaultShaderId, "colDiffuse"); - RLGL.State.defaultShaderLocs[RL_SHADER_LOC_MAP_DIFFUSE] = glGetUniformLocation(RLGL.State.defaultShaderId, "texture0"); + RLGL.State.defaultShaderLocs[RL_SHADER_LOC_MATRIX_MVP] = glGetUniformLocation(RLGL.State.defaultShaderId, RL_DEFAULT_SHADER_UNIFORM_NAME_MVP); + RLGL.State.defaultShaderLocs[RL_SHADER_LOC_COLOR_DIFFUSE] = glGetUniformLocation(RLGL.State.defaultShaderId, RL_DEFAULT_SHADER_UNIFORM_NAME_COLOR); + RLGL.State.defaultShaderLocs[RL_SHADER_LOC_MAP_DIFFUSE] = glGetUniformLocation(RLGL.State.defaultShaderId, RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE0); } else TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Failed to load default shader", RLGL.State.defaultShaderId); } @@ -4817,6 +4982,31 @@ static int rlGetPixelDataSize(int width, int height, int format) // Auxiliar math functions +// Get float array of matrix data +static rl_float16 rlMatrixToFloatV(Matrix mat) +{ + rl_float16 result = { 0 }; + + result.v[0] = mat.m0; + result.v[1] = mat.m1; + result.v[2] = mat.m2; + result.v[3] = mat.m3; + result.v[4] = mat.m4; + result.v[5] = mat.m5; + result.v[6] = mat.m6; + result.v[7] = mat.m7; + result.v[8] = mat.m8; + result.v[9] = mat.m9; + result.v[10] = mat.m10; + result.v[11] = mat.m11; + result.v[12] = mat.m12; + result.v[13] = mat.m13; + result.v[14] = mat.m14; + result.v[15] = mat.m15; + + return result; +} + // Get identity matrix static Matrix rlMatrixIdentity(void) { @@ -4856,4 +5046,76 @@ static Matrix rlMatrixMultiply(Matrix left, Matrix right) return result; } +// Transposes provided matrix +static Matrix rlMatrixTranspose(Matrix mat) +{ + Matrix result = { 0 }; + + result.m0 = mat.m0; + result.m1 = mat.m4; + result.m2 = mat.m8; + result.m3 = mat.m12; + result.m4 = mat.m1; + result.m5 = mat.m5; + result.m6 = mat.m9; + result.m7 = mat.m13; + result.m8 = mat.m2; + result.m9 = mat.m6; + result.m10 = mat.m10; + result.m11 = mat.m14; + result.m12 = mat.m3; + result.m13 = mat.m7; + result.m14 = mat.m11; + result.m15 = mat.m15; + + return result; +} + +// Invert provided matrix +static Matrix rlMatrixInvert(Matrix mat) +{ + Matrix result = { 0 }; + + // Cache the matrix values (speed optimization) + float a00 = mat.m0, a01 = mat.m1, a02 = mat.m2, a03 = mat.m3; + float a10 = mat.m4, a11 = mat.m5, a12 = mat.m6, a13 = mat.m7; + float a20 = mat.m8, a21 = mat.m9, a22 = mat.m10, a23 = mat.m11; + float a30 = mat.m12, a31 = mat.m13, a32 = mat.m14, a33 = mat.m15; + + float b00 = a00*a11 - a01*a10; + float b01 = a00*a12 - a02*a10; + float b02 = a00*a13 - a03*a10; + float b03 = a01*a12 - a02*a11; + float b04 = a01*a13 - a03*a11; + float b05 = a02*a13 - a03*a12; + float b06 = a20*a31 - a21*a30; + float b07 = a20*a32 - a22*a30; + float b08 = a20*a33 - a23*a30; + float b09 = a21*a32 - a22*a31; + float b10 = a21*a33 - a23*a31; + float b11 = a22*a33 - a23*a32; + + // Calculate the invert determinant (inlined to avoid double-caching) + float invDet = 1.0f/(b00*b11 - b01*b10 + b02*b09 + b03*b08 - b04*b07 + b05*b06); + + result.m0 = (a11*b11 - a12*b10 + a13*b09)*invDet; + result.m1 = (-a01*b11 + a02*b10 - a03*b09)*invDet; + result.m2 = (a31*b05 - a32*b04 + a33*b03)*invDet; + result.m3 = (-a21*b05 + a22*b04 - a23*b03)*invDet; + result.m4 = (-a10*b11 + a12*b08 - a13*b07)*invDet; + result.m5 = (a00*b11 - a02*b08 + a03*b07)*invDet; + result.m6 = (-a30*b05 + a32*b02 - a33*b01)*invDet; + result.m7 = (a20*b05 - a22*b02 + a23*b01)*invDet; + result.m8 = (a10*b10 - a11*b08 + a13*b06)*invDet; + result.m9 = (-a00*b10 + a01*b08 - a03*b06)*invDet; + result.m10 = (a30*b04 - a31*b02 + a33*b00)*invDet; + result.m11 = (-a20*b04 + a21*b02 - a23*b00)*invDet; + result.m12 = (-a10*b09 + a11*b07 - a12*b06)*invDet; + result.m13 = (a00*b09 - a01*b07 + a02*b06)*invDet; + result.m14 = (-a30*b03 + a31*b01 - a32*b00)*invDet; + result.m15 = (a20*b03 - a21*b01 + a22*b00)*invDet; + + return result; +} + #endif // RLGL_IMPLEMENTATION diff --git a/raylib/rlgl_cgo.go b/raylib/rlgl_cgo.go index 15f0067..0136791 100644 --- a/raylib/rlgl_cgo.go +++ b/raylib/rlgl_cgo.go @@ -587,9 +587,7 @@ func LoadTextureDepth(width, height int32, useRenderBuffer bool) { // LoadFramebuffer - Load an empty framebuffer func LoadFramebuffer(width int32, height int32) uint32 { - cwidth := C.int(width) - cheight := C.int(height) - return uint32(C.rlLoadFramebuffer(cwidth, cheight)) + return uint32(C.rlLoadFramebuffer()) } // FramebufferAttach - Attach texture/renderbuffer to a framebuffer diff --git a/raylib/rmodels.c b/raylib/rmodels.c index 229d373..27c19a3 100644 --- a/raylib/rmodels.c +++ b/raylib/rmodels.c @@ -21,7 +21,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2013-2023 Ramon Santamaria (@raysan5) +* Copyright (c) 2013-2024 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. @@ -54,8 +54,8 @@ #include "raymath.h" // Required for: Vector3, Quaternion and Matrix functionality #include // Required for: sprintf() -#include // Required for: malloc(), free() -#include // Required for: memcmp(), strlen() +#include // Required for: malloc(), calloc(), free() +#include // Required for: memcmp(), strlen(), strncpy() #include // Required for: sinf(), cosf(), sqrtf(), fabsf() #if defined(SUPPORT_FILEFORMAT_OBJ) || defined(SUPPORT_FILEFORMAT_MTL) @@ -228,7 +228,7 @@ void DrawTriangle3D(Vector3 v1, Vector3 v2, Vector3 v3, Color color) // Draw a triangle strip defined by points void DrawTriangleStrip3D(Vector3 *points, int pointCount, Color color) { - if (pointCount < 3) return; + if (pointCount < 3) return; // Security check rlBegin(RL_TRIANGLES); rlColor4ub(color.r, color.g, color.b, color.a); @@ -269,6 +269,7 @@ void DrawCube(Vector3 position, float width, float height, float length, Color c rlColor4ub(color.r, color.g, color.b, color.a); // Front face + rlNormal3f(0.0f, 0.0f, 1.0f); rlVertex3f(x - width/2, y - height/2, z + length/2); // Bottom Left rlVertex3f(x + width/2, y - height/2, z + length/2); // Bottom Right rlVertex3f(x - width/2, y + height/2, z + length/2); // Top Left @@ -278,6 +279,7 @@ void DrawCube(Vector3 position, float width, float height, float length, Color c rlVertex3f(x + width/2, y - height/2, z + length/2); // Bottom Right // Back face + rlNormal3f(0.0f, 0.0f, -1.0f); rlVertex3f(x - width/2, y - height/2, z - length/2); // Bottom Left rlVertex3f(x - width/2, y + height/2, z - length/2); // Top Left rlVertex3f(x + width/2, y - height/2, z - length/2); // Bottom Right @@ -287,6 +289,7 @@ void DrawCube(Vector3 position, float width, float height, float length, Color c rlVertex3f(x - width/2, y + height/2, z - length/2); // Top Left // Top face + rlNormal3f(0.0f, 1.0f, 0.0f); rlVertex3f(x - width/2, y + height/2, z - length/2); // Top Left rlVertex3f(x - width/2, y + height/2, z + length/2); // Bottom Left rlVertex3f(x + width/2, y + height/2, z + length/2); // Bottom Right @@ -296,6 +299,7 @@ void DrawCube(Vector3 position, float width, float height, float length, Color c rlVertex3f(x + width/2, y + height/2, z + length/2); // Bottom Right // Bottom face + rlNormal3f(0.0f, -1.0f, 0.0f); rlVertex3f(x - width/2, y - height/2, z - length/2); // Top Left rlVertex3f(x + width/2, y - height/2, z + length/2); // Bottom Right rlVertex3f(x - width/2, y - height/2, z + length/2); // Bottom Left @@ -305,6 +309,7 @@ void DrawCube(Vector3 position, float width, float height, float length, Color c rlVertex3f(x - width/2, y - height/2, z - length/2); // Top Left // Right face + rlNormal3f(1.0f, 0.0f, 0.0f); rlVertex3f(x + width/2, y - height/2, z - length/2); // Bottom Right rlVertex3f(x + width/2, y + height/2, z - length/2); // Top Right rlVertex3f(x + width/2, y + height/2, z + length/2); // Top Left @@ -314,6 +319,7 @@ void DrawCube(Vector3 position, float width, float height, float length, Color c rlVertex3f(x + width/2, y + height/2, z + length/2); // Top Left // Left face + rlNormal3f(-1.0f, 0.0f, 0.0f); rlVertex3f(x - width/2, y - height/2, z - length/2); // Bottom Right rlVertex3f(x - width/2, y + height/2, z + length/2); // Top Left rlVertex3f(x - width/2, y + height/2, z - length/2); // Top Right @@ -559,7 +565,7 @@ void DrawCylinderEx(Vector3 startPos, Vector3 endPos, float startRadius, float e if (sides < 3) sides = 3; Vector3 direction = { endPos.x - startPos.x, endPos.y - startPos.y, endPos.z - startPos.z }; - if ((direction.x == 0) && (direction.y == 0) && (direction.z == 0)) return; + if ((direction.x == 0) && (direction.y == 0) && (direction.z == 0)) return; // Security check // Construct a basis of the base and the top face: Vector3 b1 = Vector3Normalize(Vector3Perpendicular(direction)); @@ -570,8 +576,9 @@ void DrawCylinderEx(Vector3 startPos, Vector3 endPos, float startRadius, float e rlBegin(RL_TRIANGLES); rlColor4ub(color.r, color.g, color.b, color.a); - for (int i = 0; i < sides; i++) { - // compute the four vertices + for (int i = 0; i < sides; i++) + { + // Compute the four vertices float s1 = sinf(baseAngle*(i + 0))*startRadius; float c1 = cosf(baseAngle*(i + 0))*startRadius; Vector3 w1 = { startPos.x + s1*b1.x + c1*b2.x, startPos.y + s1*b1.y + c1*b2.y, startPos.z + s1*b1.z + c1*b2.z }; @@ -585,11 +592,12 @@ void DrawCylinderEx(Vector3 startPos, Vector3 endPos, float startRadius, float e float c4 = cosf(baseAngle*(i + 1))*endRadius; Vector3 w4 = { endPos.x + s4*b1.x + c4*b2.x, endPos.y + s4*b1.y + c4*b2.y, endPos.z + s4*b1.z + c4*b2.z }; - if (startRadius > 0) { // + if (startRadius > 0) + { rlVertex3f(startPos.x, startPos.y, startPos.z); // | rlVertex3f(w2.x, w2.y, w2.z); // T0 rlVertex3f(w1.x, w1.y, w1.z); // | - } // + } // w2 x.-----------x startPos rlVertex3f(w1.x, w1.y, w1.z); // | |\'. T0 / rlVertex3f(w2.x, w2.y, w2.z); // T1 | \ '. / @@ -599,7 +607,8 @@ void DrawCylinderEx(Vector3 startPos, Vector3 endPos, float startRadius, float e rlVertex3f(w4.x, w4.y, w4.z); // T2 '. \ |T3/ rlVertex3f(w3.x, w3.y, w3.z); // | '. \ | / // '.\|/ - if (endRadius > 0) { // 'x w3 + if (endRadius > 0) // 'x w3 + { rlVertex3f(endPos.x, endPos.y, endPos.z); // | rlVertex3f(w3.x, w3.y, w3.z); // T3 rlVertex3f(w4.x, w4.y, w4.z); // | @@ -646,7 +655,7 @@ void DrawCylinderWiresEx(Vector3 startPos, Vector3 endPos, float startRadius, fl if (sides < 3) sides = 3; Vector3 direction = { endPos.x - startPos.x, endPos.y - startPos.y, endPos.z - startPos.z }; - if ((direction.x == 0) && (direction.y == 0) && (direction.z == 0))return; + if ((direction.x == 0) && (direction.y == 0) && (direction.z == 0)) return; // Security check // Construct a basis of the base and the top face: Vector3 b1 = Vector3Normalize(Vector3Perpendicular(direction)); @@ -657,8 +666,9 @@ void DrawCylinderWiresEx(Vector3 startPos, Vector3 endPos, float startRadius, fl rlBegin(RL_LINES); rlColor4ub(color.r, color.g, color.b, color.a); - for (int i = 0; i < sides; i++) { - // compute the four vertices + for (int i = 0; i < sides; i++) + { + // Compute the four vertices float s1 = sinf(baseAngle*(i + 0))*startRadius; float c1 = cosf(baseAngle*(i + 0))*startRadius; Vector3 w1 = { startPos.x + s1*b1.x + c1*b2.x, startPos.y + s1*b1.y + c1*b2.y, startPos.z + s1*b1.z + c1*b2.z }; @@ -702,7 +712,7 @@ void DrawCapsule(Vector3 startPos, Vector3 endPos, float radius, int slices, int Vector3 capCenter = endPos; float baseSliceAngle = (2.0f*PI)/slices; - float baseRingAngle = PI * 0.5f / rings; + float baseRingAngle = PI*0.5f/rings; rlBegin(RL_TRIANGLES); rlColor4ub(color.r, color.g, color.b, color.a); @@ -721,38 +731,38 @@ void DrawCapsule(Vector3 startPos, Vector3 endPos, float radius, int slices, int // as we iterate through the rings they must get smaller by the cos(angle(i)) // compute the four vertices - float ringSin1 = sinf(baseSliceAngle*(j + 0))*cosf(baseRingAngle * ( i + 0 )); - float ringCos1 = cosf(baseSliceAngle*(j + 0))*cosf(baseRingAngle * ( i + 0 )); + float ringSin1 = sinf(baseSliceAngle*(j + 0))*cosf(baseRingAngle*( i + 0 )); + float ringCos1 = cosf(baseSliceAngle*(j + 0))*cosf(baseRingAngle*( i + 0 )); Vector3 w1 = (Vector3){ - capCenter.x + (sinf(baseRingAngle * ( i + 0 ))*b0.x + ringSin1*b1.x + ringCos1*b2.x) * radius, - capCenter.y + (sinf(baseRingAngle * ( i + 0 ))*b0.y + ringSin1*b1.y + ringCos1*b2.y) * radius, - capCenter.z + (sinf(baseRingAngle * ( i + 0 ))*b0.z + ringSin1*b1.z + ringCos1*b2.z) * radius + capCenter.x + (sinf(baseRingAngle*( i + 0 ))*b0.x + ringSin1*b1.x + ringCos1*b2.x)*radius, + capCenter.y + (sinf(baseRingAngle*( i + 0 ))*b0.y + ringSin1*b1.y + ringCos1*b2.y)*radius, + capCenter.z + (sinf(baseRingAngle*( i + 0 ))*b0.z + ringSin1*b1.z + ringCos1*b2.z)*radius }; - float ringSin2 = sinf(baseSliceAngle*(j + 1))*cosf(baseRingAngle * ( i + 0 )); - float ringCos2 = cosf(baseSliceAngle*(j + 1))*cosf(baseRingAngle * ( i + 0 )); + float ringSin2 = sinf(baseSliceAngle*(j + 1))*cosf(baseRingAngle*( i + 0 )); + float ringCos2 = cosf(baseSliceAngle*(j + 1))*cosf(baseRingAngle*( i + 0 )); Vector3 w2 = (Vector3){ - capCenter.x + (sinf(baseRingAngle * ( i + 0 ))*b0.x + ringSin2*b1.x + ringCos2*b2.x) * radius, - capCenter.y + (sinf(baseRingAngle * ( i + 0 ))*b0.y + ringSin2*b1.y + ringCos2*b2.y) * radius, - capCenter.z + (sinf(baseRingAngle * ( i + 0 ))*b0.z + ringSin2*b1.z + ringCos2*b2.z) * radius + capCenter.x + (sinf(baseRingAngle*( i + 0 ))*b0.x + ringSin2*b1.x + ringCos2*b2.x)*radius, + capCenter.y + (sinf(baseRingAngle*( i + 0 ))*b0.y + ringSin2*b1.y + ringCos2*b2.y)*radius, + capCenter.z + (sinf(baseRingAngle*( i + 0 ))*b0.z + ringSin2*b1.z + ringCos2*b2.z)*radius }; - float ringSin3 = sinf(baseSliceAngle*(j + 0))*cosf(baseRingAngle * ( i + 1 )); - float ringCos3 = cosf(baseSliceAngle*(j + 0))*cosf(baseRingAngle * ( i + 1 )); + float ringSin3 = sinf(baseSliceAngle*(j + 0))*cosf(baseRingAngle*( i + 1 )); + float ringCos3 = cosf(baseSliceAngle*(j + 0))*cosf(baseRingAngle*( i + 1 )); Vector3 w3 = (Vector3){ - capCenter.x + (sinf(baseRingAngle * ( i + 1 ))*b0.x + ringSin3*b1.x + ringCos3*b2.x) * radius, - capCenter.y + (sinf(baseRingAngle * ( i + 1 ))*b0.y + ringSin3*b1.y + ringCos3*b2.y) * radius, - capCenter.z + (sinf(baseRingAngle * ( i + 1 ))*b0.z + ringSin3*b1.z + ringCos3*b2.z) * radius + capCenter.x + (sinf(baseRingAngle*( i + 1 ))*b0.x + ringSin3*b1.x + ringCos3*b2.x)*radius, + capCenter.y + (sinf(baseRingAngle*( i + 1 ))*b0.y + ringSin3*b1.y + ringCos3*b2.y)*radius, + capCenter.z + (sinf(baseRingAngle*( i + 1 ))*b0.z + ringSin3*b1.z + ringCos3*b2.z)*radius }; - float ringSin4 = sinf(baseSliceAngle*(j + 1))*cosf(baseRingAngle * ( i + 1 )); - float ringCos4 = cosf(baseSliceAngle*(j + 1))*cosf(baseRingAngle * ( i + 1 )); + float ringSin4 = sinf(baseSliceAngle*(j + 1))*cosf(baseRingAngle*( i + 1 )); + float ringCos4 = cosf(baseSliceAngle*(j + 1))*cosf(baseRingAngle*( i + 1 )); Vector3 w4 = (Vector3){ - capCenter.x + (sinf(baseRingAngle * ( i + 1 ))*b0.x + ringSin4*b1.x + ringCos4*b2.x) * radius, - capCenter.y + (sinf(baseRingAngle * ( i + 1 ))*b0.y + ringSin4*b1.y + ringCos4*b2.y) * radius, - capCenter.z + (sinf(baseRingAngle * ( i + 1 ))*b0.z + ringSin4*b1.z + ringCos4*b2.z) * radius + capCenter.x + (sinf(baseRingAngle*( i + 1 ))*b0.x + ringSin4*b1.x + ringCos4*b2.x)*radius, + capCenter.y + (sinf(baseRingAngle*( i + 1 ))*b0.y + ringSin4*b1.y + ringCos4*b2.y)*radius, + capCenter.z + (sinf(baseRingAngle*( i + 1 ))*b0.z + ringSin4*b1.z + ringCos4*b2.z)*radius }; - // make sure cap triangle normals are facing outwards - if(c == 0) + // Make sure cap triangle normals are facing outwards + if (c == 0) { rlVertex3f(w1.x, w1.y, w1.z); rlVertex3f(w2.x, w2.y, w2.z); @@ -845,7 +855,7 @@ void DrawCapsuleWires(Vector3 startPos, Vector3 endPos, float radius, int slices Vector3 capCenter = endPos; float baseSliceAngle = (2.0f*PI)/slices; - float baseRingAngle = PI * 0.5f / rings; + float baseRingAngle = PI*0.5f/rings; rlBegin(RL_LINES); rlColor4ub(color.r, color.g, color.b, color.a); @@ -864,34 +874,34 @@ void DrawCapsuleWires(Vector3 startPos, Vector3 endPos, float radius, int slices // as we iterate through the rings they must get smaller by the cos(angle(i)) // compute the four vertices - float ringSin1 = sinf(baseSliceAngle*(j + 0))*cosf(baseRingAngle * ( i + 0 )); - float ringCos1 = cosf(baseSliceAngle*(j + 0))*cosf(baseRingAngle * ( i + 0 )); + float ringSin1 = sinf(baseSliceAngle*(j + 0))*cosf(baseRingAngle*( i + 0 )); + float ringCos1 = cosf(baseSliceAngle*(j + 0))*cosf(baseRingAngle*( i + 0 )); Vector3 w1 = (Vector3){ - capCenter.x + (sinf(baseRingAngle * ( i + 0 ))*b0.x + ringSin1*b1.x + ringCos1*b2.x) * radius, - capCenter.y + (sinf(baseRingAngle * ( i + 0 ))*b0.y + ringSin1*b1.y + ringCos1*b2.y) * radius, - capCenter.z + (sinf(baseRingAngle * ( i + 0 ))*b0.z + ringSin1*b1.z + ringCos1*b2.z) * radius + capCenter.x + (sinf(baseRingAngle*( i + 0 ))*b0.x + ringSin1*b1.x + ringCos1*b2.x)*radius, + capCenter.y + (sinf(baseRingAngle*( i + 0 ))*b0.y + ringSin1*b1.y + ringCos1*b2.y)*radius, + capCenter.z + (sinf(baseRingAngle*( i + 0 ))*b0.z + ringSin1*b1.z + ringCos1*b2.z)*radius }; - float ringSin2 = sinf(baseSliceAngle*(j + 1))*cosf(baseRingAngle * ( i + 0 )); - float ringCos2 = cosf(baseSliceAngle*(j + 1))*cosf(baseRingAngle * ( i + 0 )); + float ringSin2 = sinf(baseSliceAngle*(j + 1))*cosf(baseRingAngle*( i + 0 )); + float ringCos2 = cosf(baseSliceAngle*(j + 1))*cosf(baseRingAngle*( i + 0 )); Vector3 w2 = (Vector3){ - capCenter.x + (sinf(baseRingAngle * ( i + 0 ))*b0.x + ringSin2*b1.x + ringCos2*b2.x) * radius, - capCenter.y + (sinf(baseRingAngle * ( i + 0 ))*b0.y + ringSin2*b1.y + ringCos2*b2.y) * radius, - capCenter.z + (sinf(baseRingAngle * ( i + 0 ))*b0.z + ringSin2*b1.z + ringCos2*b2.z) * radius + capCenter.x + (sinf(baseRingAngle*( i + 0 ))*b0.x + ringSin2*b1.x + ringCos2*b2.x)*radius, + capCenter.y + (sinf(baseRingAngle*( i + 0 ))*b0.y + ringSin2*b1.y + ringCos2*b2.y)*radius, + capCenter.z + (sinf(baseRingAngle*( i + 0 ))*b0.z + ringSin2*b1.z + ringCos2*b2.z)*radius }; - float ringSin3 = sinf(baseSliceAngle*(j + 0))*cosf(baseRingAngle * ( i + 1 )); - float ringCos3 = cosf(baseSliceAngle*(j + 0))*cosf(baseRingAngle * ( i + 1 )); + float ringSin3 = sinf(baseSliceAngle*(j + 0))*cosf(baseRingAngle*( i + 1 )); + float ringCos3 = cosf(baseSliceAngle*(j + 0))*cosf(baseRingAngle*( i + 1 )); Vector3 w3 = (Vector3){ - capCenter.x + (sinf(baseRingAngle * ( i + 1 ))*b0.x + ringSin3*b1.x + ringCos3*b2.x) * radius, - capCenter.y + (sinf(baseRingAngle * ( i + 1 ))*b0.y + ringSin3*b1.y + ringCos3*b2.y) * radius, - capCenter.z + (sinf(baseRingAngle * ( i + 1 ))*b0.z + ringSin3*b1.z + ringCos3*b2.z) * radius + capCenter.x + (sinf(baseRingAngle*( i + 1 ))*b0.x + ringSin3*b1.x + ringCos3*b2.x)*radius, + capCenter.y + (sinf(baseRingAngle*( i + 1 ))*b0.y + ringSin3*b1.y + ringCos3*b2.y)*radius, + capCenter.z + (sinf(baseRingAngle*( i + 1 ))*b0.z + ringSin3*b1.z + ringCos3*b2.z)*radius }; - float ringSin4 = sinf(baseSliceAngle*(j + 1))*cosf(baseRingAngle * ( i + 1 )); - float ringCos4 = cosf(baseSliceAngle*(j + 1))*cosf(baseRingAngle * ( i + 1 )); + float ringSin4 = sinf(baseSliceAngle*(j + 1))*cosf(baseRingAngle*( i + 1 )); + float ringCos4 = cosf(baseSliceAngle*(j + 1))*cosf(baseRingAngle*( i + 1 )); Vector3 w4 = (Vector3){ - capCenter.x + (sinf(baseRingAngle * ( i + 1 ))*b0.x + ringSin4*b1.x + ringCos4*b2.x) * radius, - capCenter.y + (sinf(baseRingAngle * ( i + 1 ))*b0.y + ringSin4*b1.y + ringCos4*b2.y) * radius, - capCenter.z + (sinf(baseRingAngle * ( i + 1 ))*b0.z + ringSin4*b1.z + ringCos4*b2.z) * radius + capCenter.x + (sinf(baseRingAngle*( i + 1 ))*b0.x + ringSin4*b1.x + ringCos4*b2.x)*radius, + capCenter.y + (sinf(baseRingAngle*( i + 1 ))*b0.y + ringSin4*b1.y + ringCos4*b2.y)*radius, + capCenter.z + (sinf(baseRingAngle*( i + 1 ))*b0.z + ringSin4*b1.z + ringCos4*b2.z)*radius }; rlVertex3f(w1.x, w1.y, w1.z); @@ -1100,13 +1110,17 @@ Model LoadModelFromMesh(Mesh mesh) // Check if a model is ready bool IsModelReady(Model model) { - return ((model.meshes != NULL) && // Validate model contains some mesh - (model.materials != NULL) && // Validate model contains some material (at least default one) - (model.meshMaterial != NULL) && // Validate mesh-material linkage - (model.meshCount > 0) && // Validate mesh count - (model.materialCount > 0)); // Validate material count + bool result = false; + + if ((model.meshes != NULL) && // Validate model contains some mesh + (model.materials != NULL) && // Validate model contains some material (at least default one) + (model.meshMaterial != NULL) && // Validate mesh-material linkage + (model.meshCount > 0) && // Validate mesh count + (model.materialCount > 0)) result = true; // Validate material count // NOTE: This is a very general model validation, many elements could be validated from a model... + + return result; } // Unload model (meshes/materials) from memory (RAM and/or VRAM) @@ -1200,13 +1214,13 @@ void UploadMesh(Mesh *mesh, bool dynamic) // Enable vertex attributes: position (shader-location = 0) void *vertices = (mesh->animVertices != NULL)? mesh->animVertices : mesh->vertices; mesh->vboId[0] = rlLoadVertexBuffer(vertices, mesh->vertexCount*3*sizeof(float), dynamic); - rlSetVertexAttribute(0, 3, RL_FLOAT, 0, 0, 0); - rlEnableVertexAttribute(0); + rlSetVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION, 3, RL_FLOAT, 0, 0, 0); + rlEnableVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION); // Enable vertex attributes: texcoords (shader-location = 1) mesh->vboId[1] = rlLoadVertexBuffer(mesh->texcoords, mesh->vertexCount*2*sizeof(float), dynamic); - rlSetVertexAttribute(1, 2, RL_FLOAT, 0, 0, 0); - rlEnableVertexAttribute(1); + rlSetVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD, 2, RL_FLOAT, 0, 0, 0); + rlEnableVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD); // WARNING: When setting default vertex attribute values, the values for each generic vertex attribute // is part of current state, and it is maintained even if a different program object is used @@ -1216,64 +1230,64 @@ void UploadMesh(Mesh *mesh, bool dynamic) // Enable vertex attributes: normals (shader-location = 2) void *normals = (mesh->animNormals != NULL)? mesh->animNormals : mesh->normals; mesh->vboId[2] = rlLoadVertexBuffer(normals, mesh->vertexCount*3*sizeof(float), dynamic); - rlSetVertexAttribute(2, 3, RL_FLOAT, 0, 0, 0); - rlEnableVertexAttribute(2); + rlSetVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL, 3, RL_FLOAT, 0, 0, 0); + rlEnableVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL); } else { // Default vertex attribute: normal // WARNING: Default value provided to shader if location available float value[3] = { 1.0f, 1.0f, 1.0f }; - rlSetVertexAttributeDefault(2, value, SHADER_ATTRIB_VEC3, 3); - rlDisableVertexAttribute(2); + rlSetVertexAttributeDefault(RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL, value, SHADER_ATTRIB_VEC3, 3); + rlDisableVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL); } if (mesh->colors != NULL) { // Enable vertex attribute: color (shader-location = 3) mesh->vboId[3] = rlLoadVertexBuffer(mesh->colors, mesh->vertexCount*4*sizeof(unsigned char), dynamic); - rlSetVertexAttribute(3, 4, RL_UNSIGNED_BYTE, 1, 0, 0); - rlEnableVertexAttribute(3); + rlSetVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_COLOR, 4, RL_UNSIGNED_BYTE, 1, 0, 0); + rlEnableVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_COLOR); } else { // Default vertex attribute: color // WARNING: Default value provided to shader if location available float value[4] = { 1.0f, 1.0f, 1.0f, 1.0f }; // WHITE - rlSetVertexAttributeDefault(3, value, SHADER_ATTRIB_VEC4, 4); - rlDisableVertexAttribute(3); + rlSetVertexAttributeDefault(RL_DEFAULT_SHADER_ATTRIB_LOCATION_COLOR, value, SHADER_ATTRIB_VEC4, 4); + rlDisableVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_COLOR); } if (mesh->tangents != NULL) { // Enable vertex attribute: tangent (shader-location = 4) mesh->vboId[4] = rlLoadVertexBuffer(mesh->tangents, mesh->vertexCount*4*sizeof(float), dynamic); - rlSetVertexAttribute(4, 4, RL_FLOAT, 0, 0, 0); - rlEnableVertexAttribute(4); + rlSetVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TANGENT, 4, RL_FLOAT, 0, 0, 0); + rlEnableVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TANGENT); } else { // Default vertex attribute: tangent // WARNING: Default value provided to shader if location available float value[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; - rlSetVertexAttributeDefault(4, value, SHADER_ATTRIB_VEC4, 4); - rlDisableVertexAttribute(4); + rlSetVertexAttributeDefault(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TANGENT, value, SHADER_ATTRIB_VEC4, 4); + rlDisableVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TANGENT); } if (mesh->texcoords2 != NULL) { // Enable vertex attribute: texcoord2 (shader-location = 5) mesh->vboId[5] = rlLoadVertexBuffer(mesh->texcoords2, mesh->vertexCount*2*sizeof(float), dynamic); - rlSetVertexAttribute(5, 2, RL_FLOAT, 0, 0, 0); - rlEnableVertexAttribute(5); + rlSetVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD2, 2, RL_FLOAT, 0, 0, 0); + rlEnableVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD2); } else { // Default vertex attribute: texcoord2 // WARNING: Default value provided to shader if location available float value[2] = { 0.0f, 0.0f }; - rlSetVertexAttributeDefault(5, value, SHADER_ATTRIB_VEC2, 2); - rlDisableVertexAttribute(5); + rlSetVertexAttributeDefault(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD2, value, SHADER_ATTRIB_VEC2, 2); + rlDisableVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD2); } if (mesh->indices != NULL) @@ -1352,10 +1366,10 @@ void DrawMesh(Mesh mesh, Material material, Matrix transform) if (material.shader.locs[SHADER_LOC_COLOR_SPECULAR] != -1) { float values[4] = { - (float)material.maps[SHADER_LOC_COLOR_SPECULAR].color.r/255.0f, - (float)material.maps[SHADER_LOC_COLOR_SPECULAR].color.g/255.0f, - (float)material.maps[SHADER_LOC_COLOR_SPECULAR].color.b/255.0f, - (float)material.maps[SHADER_LOC_COLOR_SPECULAR].color.a/255.0f + (float)material.maps[MATERIAL_MAP_SPECULAR].color.r/255.0f, + (float)material.maps[MATERIAL_MAP_SPECULAR].color.g/255.0f, + (float)material.maps[MATERIAL_MAP_SPECULAR].color.b/255.0f, + (float)material.maps[MATERIAL_MAP_SPECULAR].color.a/255.0f }; rlSetUniform(material.shader.locs[SHADER_LOC_COLOR_SPECULAR], values, SHADER_UNIFORM_VEC4, 1); @@ -1470,9 +1484,6 @@ void DrawMesh(Mesh mesh, Material material, Matrix transform) if (mesh.indices != NULL) rlEnableVertexBufferElement(mesh.vboId[6]); } - // WARNING: Disable vertex attribute color input if mesh can not provide that data (despite location being enabled in shader) - if (mesh.vboId[3] == 0) rlDisableVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_COLOR]); - int eyeCount = 1; if (rlIsStereoRenderEnabled()) eyeCount = 2; @@ -1588,7 +1599,7 @@ void DrawMeshInstanced(Mesh mesh, Material material, const Matrix *transforms, i // Enable mesh VAO to attach new buffer rlEnableVertexArray(mesh.vaoId); - // This could alternatively use a static VBO and either glMapBuffer() or glBufferSubData(). + // This could alternatively use a static VBO and either glMapBuffer() or glBufferSubData() // It isn't clear which would be reliably faster in all cases and on all platforms, // anecdotally glMapBuffer() seems very slow (syncs) while glBufferSubData() seems // no faster, since we're transferring all the transform matrices anyway @@ -1598,7 +1609,7 @@ void DrawMeshInstanced(Mesh mesh, Material material, const Matrix *transforms, i for (unsigned int i = 0; i < 4; i++) { rlEnableVertexAttribute(material.shader.locs[SHADER_LOC_MATRIX_MODEL] + i); - rlSetVertexAttribute(material.shader.locs[SHADER_LOC_MATRIX_MODEL] + i, 4, RL_FLOAT, 0, sizeof(Matrix), (void *)(i*sizeof(Vector4))); + rlSetVertexAttribute(material.shader.locs[SHADER_LOC_MATRIX_MODEL] + i, 4, RL_FLOAT, 0, sizeof(Matrix), i*sizeof(Vector4)); rlSetVertexAttributeDivisor(material.shader.locs[SHADER_LOC_MATRIX_MODEL] + i, 1); } @@ -1691,9 +1702,6 @@ void DrawMeshInstanced(Mesh mesh, Material material, const Matrix *transforms, i if (mesh.indices != NULL) rlEnableVertexBufferElement(mesh.vboId[6]); } - // WARNING: Disable vertex attribute color input if mesh can not provide that data (despite location being enabled in shader) - if (mesh.vboId[3] == 0) rlDisableVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_COLOR]); - int eyeCount = 1; if (rlIsStereoRenderEnabled()) eyeCount = 2; @@ -1794,7 +1802,7 @@ bool ExportMesh(Mesh mesh, const char *fileName) byteCount += sprintf(txtData + byteCount, "# // more info and bugs-report: github.com/raysan5/raylib //\n"); byteCount += sprintf(txtData + byteCount, "# // feedback and support: ray[at]raylib.com //\n"); byteCount += sprintf(txtData + byteCount, "# // //\n"); - byteCount += sprintf(txtData + byteCount, "# // Copyright (c) 2018-2023 Ramon Santamaria (@raysan5) //\n"); + byteCount += sprintf(txtData + byteCount, "# // Copyright (c) 2018-2024 Ramon Santamaria (@raysan5) //\n"); byteCount += sprintf(txtData + byteCount, "# // //\n"); byteCount += sprintf(txtData + byteCount, "# //////////////////////////////////////////////////////////////////////////////////\n\n"); byteCount += sprintf(txtData + byteCount, "# Vertex Count: %i\n", mesh.vertexCount); @@ -1850,6 +1858,104 @@ bool ExportMesh(Mesh mesh, const char *fileName) return success; } +// Export mesh as code file (.h) defining multiple arrays of vertex attributes +bool ExportMeshAsCode(Mesh mesh, const char *fileName) +{ + bool success = false; + +#ifndef TEXT_BYTES_PER_LINE + #define TEXT_BYTES_PER_LINE 20 +#endif + + // NOTE: Text data buffer size is fixed to 64MB + char *txtData = (char *)RL_CALLOC(64*1024*1024, sizeof(char)); // 64 MB + + int byteCount = 0; + byteCount += sprintf(txtData + byteCount, "////////////////////////////////////////////////////////////////////////////////////////\n"); + byteCount += sprintf(txtData + byteCount, "// //\n"); + byteCount += sprintf(txtData + byteCount, "// MeshAsCode exporter v1.0 - Mesh vertex data exported as arrays //\n"); + byteCount += sprintf(txtData + byteCount, "// //\n"); + byteCount += sprintf(txtData + byteCount, "// more info and bugs-report: github.com/raysan5/raylib //\n"); + byteCount += sprintf(txtData + byteCount, "// feedback and support: ray[at]raylib.com //\n"); + byteCount += sprintf(txtData + byteCount, "// //\n"); + byteCount += sprintf(txtData + byteCount, "// Copyright (c) 2023 Ramon Santamaria (@raysan5) //\n"); + byteCount += sprintf(txtData + byteCount, "// //\n"); + byteCount += sprintf(txtData + byteCount, "////////////////////////////////////////////////////////////////////////////////////////\n\n"); + + // Get file name from path and convert variable name to uppercase + char varFileName[256] = { 0 }; + strcpy(varFileName, GetFileNameWithoutExt(fileName)); + for (int i = 0; varFileName[i] != '\0'; i++) if ((varFileName[i] >= 'a') && (varFileName[i] <= 'z')) { varFileName[i] = varFileName[i] - 32; } + + // Add image information + byteCount += sprintf(txtData + byteCount, "// Mesh basic information\n"); + byteCount += sprintf(txtData + byteCount, "#define %s_VERTEX_COUNT %i\n", varFileName, mesh.vertexCount); + byteCount += sprintf(txtData + byteCount, "#define %s_TRIANGLE_COUNT %i\n\n", varFileName, mesh.triangleCount); + + // Define vertex attributes data as separate arrays + //----------------------------------------------------------------------------------------- + if (mesh.vertices != NULL) // Vertex position (XYZ - 3 components per vertex - float) + { + byteCount += sprintf(txtData + byteCount, "static float %s_VERTEX_DATA[%i] = { ", varFileName, mesh.vertexCount*3); + for (int i = 0; i < mesh.vertexCount*3 - 1; i++) byteCount += sprintf(txtData + byteCount, ((i%TEXT_BYTES_PER_LINE == 0)? "%.3ff,\n" : "%.3ff, "), mesh.vertices[i]); + byteCount += sprintf(txtData + byteCount, "%.3ff };\n\n", mesh.vertices[mesh.vertexCount*3 - 1]); + } + + if (mesh.texcoords != NULL) // Vertex texture coordinates (UV - 2 components per vertex - float) + { + byteCount += sprintf(txtData + byteCount, "static float %s_TEXCOORD_DATA[%i] = { ", varFileName, mesh.vertexCount*2); + for (int i = 0; i < mesh.vertexCount*2 - 1; i++) byteCount += sprintf(txtData + byteCount, ((i%TEXT_BYTES_PER_LINE == 0)? "%.3ff,\n" : "%.3ff, "), mesh.texcoords[i]); + byteCount += sprintf(txtData + byteCount, "%.3ff };\n\n", mesh.texcoords[mesh.vertexCount*2 - 1]); + } + + if (mesh.texcoords2 != NULL) // Vertex texture coordinates (UV - 2 components per vertex - float) + { + byteCount += sprintf(txtData + byteCount, "static float %s_TEXCOORD2_DATA[%i] = { ", varFileName, mesh.vertexCount*2); + for (int i = 0; i < mesh.vertexCount*2 - 1; i++) byteCount += sprintf(txtData + byteCount, ((i%TEXT_BYTES_PER_LINE == 0)? "%.3ff,\n" : "%.3ff, "), mesh.texcoords2[i]); + byteCount += sprintf(txtData + byteCount, "%.3ff };\n\n", mesh.texcoords2[mesh.vertexCount*2 - 1]); + } + + if (mesh.normals != NULL) // Vertex normals (XYZ - 3 components per vertex - float) + { + byteCount += sprintf(txtData + byteCount, "static float %s_NORMAL_DATA[%i] = { ", varFileName, mesh.vertexCount*3); + for (int i = 0; i < mesh.vertexCount*3 - 1; i++) byteCount += sprintf(txtData + byteCount, ((i%TEXT_BYTES_PER_LINE == 0)? "%.3ff,\n" : "%.3ff, "), mesh.normals[i]); + byteCount += sprintf(txtData + byteCount, "%.3ff };\n\n", mesh.normals[mesh.vertexCount*3 - 1]); + } + + if (mesh.tangents != NULL) // Vertex tangents (XYZW - 4 components per vertex - float) + { + byteCount += sprintf(txtData + byteCount, "static float %s_TANGENT_DATA[%i] = { ", varFileName, mesh.vertexCount*4); + for (int i = 0; i < mesh.vertexCount*4 - 1; i++) byteCount += sprintf(txtData + byteCount, ((i%TEXT_BYTES_PER_LINE == 0)? "%.3ff,\n" : "%.3ff, "), mesh.tangents[i]); + byteCount += sprintf(txtData + byteCount, "%.3ff };\n\n", mesh.tangents[mesh.vertexCount*4 - 1]); + } + + if (mesh.colors != NULL) // Vertex colors (RGBA - 4 components per vertex - unsigned char) + { + byteCount += sprintf(txtData + byteCount, "static unsigned char %s_COLOR_DATA[%i] = { ", varFileName, mesh.vertexCount*4); + for (int i = 0; i < mesh.vertexCount*4 - 1; i++) byteCount += sprintf(txtData + byteCount, ((i%TEXT_BYTES_PER_LINE == 0)? "0x%x,\n" : "0x%x, "), mesh.colors[i]); + byteCount += sprintf(txtData + byteCount, "0x%x };\n\n", mesh.colors[mesh.vertexCount*4 - 1]); + } + + if (mesh.indices != NULL) // Vertex indices (3 index per triangle - unsigned short) + { + byteCount += sprintf(txtData + byteCount, "static unsigned short %s_INDEX_DATA[%i] = { ", varFileName, mesh.triangleCount*3); + for (int i = 0; i < mesh.triangleCount*3 - 1; i++) byteCount += sprintf(txtData + byteCount, ((i%TEXT_BYTES_PER_LINE == 0)? "%i,\n" : "%i, "), mesh.indices[i]); + byteCount += sprintf(txtData + byteCount, "%i };\n", mesh.indices[mesh.triangleCount*3 - 1]); + } + //----------------------------------------------------------------------------------------- + + // NOTE: Text data size exported is determined by '\0' (NULL) character + success = SaveFileText(fileName, txtData); + + RL_FREE(txtData); + + //if (success != 0) TRACELOG(LOG_INFO, "FILEIO: [%s] Image as code exported successfully", fileName); + //else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to export image as code", fileName); + + return success; +} + + #if defined(SUPPORT_FILEFORMAT_OBJ) || defined(SUPPORT_FILEFORMAT_MTL) // Process obj materials static void ProcessMaterialsOBJ(Material *materials, tinyobj_material_t *mats, int materialCount) @@ -1866,18 +1972,18 @@ static void ProcessMaterialsOBJ(Material *materials, tinyobj_material_t *mats, i materials[m].maps[MATERIAL_MAP_DIFFUSE].texture = (Texture2D){ rlGetTextureIdDefault(), 1, 1, 1, PIXELFORMAT_UNCOMPRESSED_R8G8B8A8 }; if (mats[m].diffuse_texname != NULL) materials[m].maps[MATERIAL_MAP_DIFFUSE].texture = LoadTexture(mats[m].diffuse_texname); //char *diffuse_texname; // map_Kd - else materials[m].maps[MATERIAL_MAP_DIFFUSE].color = (Color){ (unsigned char)(mats[m].diffuse[0]*255.0f), (unsigned char)(mats[m].diffuse[1]*255.0f), (unsigned char)(mats[m].diffuse[2] * 255.0f), 255 }; //float diffuse[3]; + else materials[m].maps[MATERIAL_MAP_DIFFUSE].color = (Color){ (unsigned char)(mats[m].diffuse[0]*255.0f), (unsigned char)(mats[m].diffuse[1]*255.0f), (unsigned char)(mats[m].diffuse[2]*255.0f), 255 }; //float diffuse[3]; materials[m].maps[MATERIAL_MAP_DIFFUSE].value = 0.0f; if (mats[m].specular_texname != NULL) materials[m].maps[MATERIAL_MAP_SPECULAR].texture = LoadTexture(mats[m].specular_texname); //char *specular_texname; // map_Ks - materials[m].maps[MATERIAL_MAP_SPECULAR].color = (Color){ (unsigned char)(mats[m].specular[0]*255.0f), (unsigned char)(mats[m].specular[1]*255.0f), (unsigned char)(mats[m].specular[2] * 255.0f), 255 }; //float specular[3]; + materials[m].maps[MATERIAL_MAP_SPECULAR].color = (Color){ (unsigned char)(mats[m].specular[0]*255.0f), (unsigned char)(mats[m].specular[1]*255.0f), (unsigned char)(mats[m].specular[2]*255.0f), 255 }; //float specular[3]; materials[m].maps[MATERIAL_MAP_SPECULAR].value = 0.0f; if (mats[m].bump_texname != NULL) materials[m].maps[MATERIAL_MAP_NORMAL].texture = LoadTexture(mats[m].bump_texname); //char *bump_texname; // map_bump, bump materials[m].maps[MATERIAL_MAP_NORMAL].color = WHITE; materials[m].maps[MATERIAL_MAP_NORMAL].value = mats[m].shininess; - materials[m].maps[MATERIAL_MAP_EMISSION].color = (Color){ (unsigned char)(mats[m].emission[0]*255.0f), (unsigned char)(mats[m].emission[1]*255.0f), (unsigned char)(mats[m].emission[2] * 255.0f), 255 }; //float emission[3]; + materials[m].maps[MATERIAL_MAP_EMISSION].color = (Color){ (unsigned char)(mats[m].emission[0]*255.0f), (unsigned char)(mats[m].emission[1]*255.0f), (unsigned char)(mats[m].emission[2]*255.0f), 255 }; //float emission[3]; if (mats[m].displacement_texname != NULL) materials[m].maps[MATERIAL_MAP_HEIGHT].texture = LoadTexture(mats[m].displacement_texname); //char *displacement_texname; // disp } @@ -1937,8 +2043,12 @@ Material LoadMaterialDefault(void) // Check if a material is ready bool IsMaterialReady(Material material) { - return ((material.maps != NULL) && // Validate material contain some map - (material.shader.id > 0)); // Validate material shader is valid + bool result = false; + + if ((material.maps != NULL) && // Validate material contain some map + (material.shader.id > 0)) result = true; // Validate material shader is valid + + return result; } // Unload material from memory @@ -2134,7 +2244,7 @@ Mesh GenMeshPoly(int sides, float radius) { Mesh mesh = { 0 }; - if (sides < 3) return mesh; + if (sides < 3) return mesh; // Security check int vertexCount = sides*3; @@ -2245,7 +2355,7 @@ Mesh GenMeshPlane(float width, float length, int resX, int resZ) for (int face = 0; face < numFaces; face++) { // Retrieve lower left corner from face ind - int i = face + face / (resX - 1); + int i = face + face/(resX - 1); triangles[t++] = i + resX; triangles[t++] = i + 1; @@ -2591,7 +2701,7 @@ Mesh GenMeshCylinder(float radius, float height, int slices) { // Instance a cylinder that sits on the Z=0 plane using the given tessellation // levels across the UV domain. Think of "slices" like a number of pizza - // slices, and "stacks" like a number of stacked rings. + // slices, and "stacks" like a number of stacked rings // Height and radius are both 1.0, but they can easily be changed with par_shapes_scale par_shapes_mesh *cylinder = par_shapes_create_cylinder(slices, 8); par_shapes_scale(cylinder, radius, radius, height); @@ -2655,7 +2765,7 @@ Mesh GenMeshCone(float radius, float height, int slices) { // Instance a cone that sits on the Z=0 plane using the given tessellation // levels across the UV domain. Think of "slices" like a number of pizza - // slices, and "stacks" like a number of stacked rings. + // slices, and "stacks" like a number of stacked rings // Height and radius are both 1.0, but they can easily be changed with par_shapes_scale par_shapes_mesh *cone = par_shapes_create_cone(slices, 8); par_shapes_scale(cone, radius, radius, height); @@ -2934,7 +3044,7 @@ Mesh GenMeshCubicmap(Image cubicmap, Vector3 cubeSize) Color *pixels = LoadImageColors(cubicmap); // NOTE: Max possible number of triangles numCubes*(12 triangles by cube) - int maxTriangles = cubicmap.width * cubicmap.height * 12; + int maxTriangles = cubicmap.width*cubicmap.height*12; int vCounter = 0; // Used to count vertices int tcCounter = 0; // Used to count texcoords @@ -3400,8 +3510,8 @@ void GenMeshTangents(Mesh *mesh) } rlEnableVertexArray(mesh->vaoId); - rlSetVertexAttribute(4, 4, RL_FLOAT, 0, 0, 0); - rlEnableVertexAttribute(4); + rlSetVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TANGENT, 4, RL_FLOAT, 0, 0, 0); + rlEnableVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TANGENT); rlDisableVertexArray(); } @@ -3484,6 +3594,8 @@ void DrawBillboardRec(Camera camera, Texture2D texture, Rectangle source, Vector DrawBillboardPro(camera, texture, source, position, up, size, Vector2Zero(), 0.0f, tint); } +// Draw a billboard with additional parameters +// NOTE: Size defines the destination rectangle size, stretching the source texture as required void DrawBillboardPro(Camera camera, Texture2D texture, Rectangle source, Vector3 position, Vector3 up, Vector2 size, Vector2 origin, float rotation, Color tint) { // NOTE: Billboard size will maintain source rectangle aspect ratio, size will represent billboard width @@ -3553,7 +3665,7 @@ void DrawBillboardPro(Camera camera, Texture2D texture, Rectangle source, Vector rlBegin(RL_QUADS); rlColor4ub(tint.r, tint.g, tint.b, tint.a); - if (sizeRatio.x * sizeRatio.y >= 0.0f) + if (sizeRatio.x*sizeRatio.y >= 0.0f) { // Bottom-left corner for texture and quad rlTexCoord2f((float)source.x/texture.width, (float)source.y/texture.height); @@ -3709,7 +3821,7 @@ RayCollision GetRayCollisionBox(Ray ray, BoundingBox box) RayCollision collision = { 0 }; // Note: If ray.position is inside the box, the distance is negative (as if the ray was reversed) - // Reversing ray.direction will give use the correct result. + // Reversing ray.direction will give use the correct result bool insideBox = (ray.position.x > box.min.x) && (ray.position.x < box.max.x) && (ray.position.y > box.min.y) && (ray.position.y < box.max.y) && (ray.position.z > box.min.z) && (ray.position.z < box.max.z); @@ -3952,7 +4064,7 @@ static Model LoadOBJ(const char *fileName) model.meshCount = meshCount; // Set number of materials available - // NOTE: There could be more materials available than meshes but it will be resolved at + // NOTE: There could be more materials available than meshes but it will be resolved at // model.meshMaterial, just assigning the right material to corresponding mesh model.materialCount = materialCount; if (model.materialCount == 0) @@ -3970,7 +4082,7 @@ static Model LoadOBJ(const char *fileName) for (int i = 0; i < model.meshCount; i++) { // WARNING: We need to calculate the mesh triangles manually using meshes[i].face_offset - // because in case of triangulated quads, meshes[i].length actually report quads, + // because in case of triangulated quads, meshes[i].length actually report quads, // despite the triangulation that is efectively considered on attrib.num_faces unsigned int tris = 0; if (i == model.meshCount - 1) tris = attrib.num_faces - meshes[i].face_offset; @@ -4397,7 +4509,7 @@ static Model LoadIQM(const char *fileName) BuildPoseFromParentJoints(model.bones, model.boneCount, model.bindPose); - RL_FREE(fileData); + UnloadFileData(fileData); RL_FREE(imesh); RL_FREE(tri); @@ -4629,7 +4741,7 @@ static ModelAnimation *LoadModelAnimationsIQM(const char *fileName, int *animCou } } - RL_FREE(fileData); + UnloadFileData(fileData); RL_FREE(joints); RL_FREE(framedata); @@ -4642,6 +4754,26 @@ static ModelAnimation *LoadModelAnimationsIQM(const char *fileName, int *animCou #endif #if defined(SUPPORT_FILEFORMAT_GLTF) +// Load file data callback for cgltf +static cgltf_result LoadFileGLTFCallback(const struct cgltf_memory_options *memoryOptions, const struct cgltf_file_options *fileOptions, const char *path, cgltf_size *size, void **data) +{ + int filesize; + unsigned char *filedata = LoadFileData(path, &filesize); + + if (filedata == NULL) return cgltf_result_io_error; + + *size = filesize; + *data = filedata; + + return cgltf_result_success; +} + +// Release file data callback for cgltf +static void ReleaseFileGLTFCallback(const struct cgltf_memory_options *memoryOptions, const struct cgltf_file_options *fileOptions, void *data) +{ + UnloadFileData(data); +} + // Load image from different glTF provided methods (uri, path, buffer_view) static Image LoadImageFromCgltfImage(cgltf_image *cgltfImage, const char *texPath) { @@ -4670,6 +4802,8 @@ static Image LoadImageFromCgltfImage(cgltf_image *cgltfImage, const char *texPat void *data = NULL; cgltf_options options = { 0 }; + options.file.read = LoadFileGLTFCallback; + options.file.release = ReleaseFileGLTFCallback; cgltf_result result = cgltf_load_buffer_base64(&options, outSize, cgltfImage->uri + i + 1, &data); if (result == cgltf_result_success) @@ -4793,6 +4927,8 @@ static Model LoadGLTF(const char *fileName) // glTF data loading cgltf_options options = { 0 }; + options.file.read = LoadFileGLTFCallback; + options.file.release = ReleaseFileGLTFCallback; cgltf_data *data = NULL; cgltf_result result = cgltf_parse(&options, fileData, dataSize, &data); @@ -4936,13 +5072,13 @@ static Model LoadGLTF(const char *fileName) for (unsigned int j = 0; j < data->meshes[i].primitives[p].attributes_count; j++) { // Check the different attributes for every primitive - if (data->meshes[i].primitives[p].attributes[j].type == cgltf_attribute_type_position) // POSITION + if (data->meshes[i].primitives[p].attributes[j].type == cgltf_attribute_type_position) // POSITION, vec3, float { cgltf_accessor *attribute = data->meshes[i].primitives[p].attributes[j].data; - // WARNING: SPECS: POSITION accessor MUST have its min and max properties defined. + // WARNING: SPECS: POSITION accessor MUST have its min and max properties defined - if ((attribute->component_type == cgltf_component_type_r_32f) && (attribute->type == cgltf_type_vec3)) + if ((attribute->type == cgltf_type_vec3) && (attribute->component_type == cgltf_component_type_r_32f)) { // Init raylib mesh vertices to copy glTF attribute data model.meshes[meshIndex].vertexCount = (int)attribute->count; @@ -4953,11 +5089,11 @@ static Model LoadGLTF(const char *fileName) } else TRACELOG(LOG_WARNING, "MODEL: [%s] Vertices attribute data format not supported, use vec3 float", fileName); } - else if (data->meshes[i].primitives[p].attributes[j].type == cgltf_attribute_type_normal) // NORMAL + else if (data->meshes[i].primitives[p].attributes[j].type == cgltf_attribute_type_normal) // NORMAL, vec3, float { cgltf_accessor *attribute = data->meshes[i].primitives[p].attributes[j].data; - if ((attribute->component_type == cgltf_component_type_r_32f) && (attribute->type == cgltf_type_vec3)) + if ((attribute->type == cgltf_type_vec3) && (attribute->component_type == cgltf_component_type_r_32f)) { // Init raylib mesh normals to copy glTF attribute data model.meshes[meshIndex].normals = RL_MALLOC(attribute->count*3*sizeof(float)); @@ -4967,11 +5103,11 @@ static Model LoadGLTF(const char *fileName) } else TRACELOG(LOG_WARNING, "MODEL: [%s] Normal attribute data format not supported, use vec3 float", fileName); } - else if (data->meshes[i].primitives[p].attributes[j].type == cgltf_attribute_type_tangent) // TANGENT + else if (data->meshes[i].primitives[p].attributes[j].type == cgltf_attribute_type_tangent) // TANGENT, vec3, float { cgltf_accessor *attribute = data->meshes[i].primitives[p].attributes[j].data; - if ((attribute->component_type == cgltf_component_type_r_32f) && (attribute->type == cgltf_type_vec4)) + if ((attribute->type == cgltf_type_vec4) && (attribute->component_type == cgltf_component_type_r_32f)) { // Init raylib mesh tangent to copy glTF attribute data model.meshes[meshIndex].tangents = RL_MALLOC(attribute->count*4*sizeof(float)); @@ -4981,65 +5117,177 @@ static Model LoadGLTF(const char *fileName) } else TRACELOG(LOG_WARNING, "MODEL: [%s] Tangent attribute data format not supported, use vec4 float", fileName); } - else if (data->meshes[i].primitives[p].attributes[j].type == cgltf_attribute_type_texcoord) // TEXCOORD_0 + else if (data->meshes[i].primitives[p].attributes[j].type == cgltf_attribute_type_texcoord) // TEXCOORD_n, vec2, float/u8n/u16n { - // TODO: Support additional texture coordinates: TEXCOORD_1 -> mesh.texcoords2 + // Support up to 2 texture coordinates attributes + float *texcoordPtr = NULL; cgltf_accessor *attribute = data->meshes[i].primitives[p].attributes[j].data; - if ((attribute->component_type == cgltf_component_type_r_32f) && (attribute->type == cgltf_type_vec2)) + if (attribute->type == cgltf_type_vec2) { - // Init raylib mesh texcoords to copy glTF attribute data - model.meshes[meshIndex].texcoords = RL_MALLOC(attribute->count*2*sizeof(float)); + if (attribute->component_type == cgltf_component_type_r_32f) // vec2, float + { + // Init raylib mesh texcoords to copy glTF attribute data + texcoordPtr = (float *)RL_MALLOC(attribute->count*2*sizeof(float)); - // Load 3 components of float data type into mesh.texcoords - LOAD_ATTRIBUTE(attribute, 2, float, model.meshes[meshIndex].texcoords) + // Load 3 components of float data type into mesh.texcoords + LOAD_ATTRIBUTE(attribute, 2, float, texcoordPtr) + } + else if (attribute->component_type == cgltf_component_type_r_8u) // vec2, u8n + { + // Init raylib mesh texcoords to copy glTF attribute data + texcoordPtr = (float *)RL_MALLOC(attribute->count*2*sizeof(float)); + + // Load data into a temp buffer to be converted to raylib data type + unsigned char *temp = (unsigned char *)RL_MALLOC(attribute->count*2*sizeof(unsigned char)); + LOAD_ATTRIBUTE(attribute, 2, unsigned char, temp); + + // Convert data to raylib texcoord data type (float) + for (unsigned int t = 0; t < attribute->count*2; t++) texcoordPtr[t] = (float)temp[t]/255.0f; + + RL_FREE(temp); + } + else if (attribute->component_type == cgltf_component_type_r_16u) // vec2, u16n + { + // Init raylib mesh texcoords to copy glTF attribute data + texcoordPtr = (float *)RL_MALLOC(attribute->count*2*sizeof(float)); + + // Load data into a temp buffer to be converted to raylib data type + unsigned short *temp = (unsigned short *)RL_MALLOC(attribute->count*2*sizeof(unsigned short)); + LOAD_ATTRIBUTE(attribute, 2, unsigned short, temp); + + // Convert data to raylib texcoord data type (float) + for (unsigned int t = 0; t < attribute->count*2; t++) texcoordPtr[t] = (float)temp[t]/65535.0f; + + RL_FREE(temp); + } + else TRACELOG(LOG_WARNING, "MODEL: [%s] Texcoords attribute data format not supported", fileName); } else TRACELOG(LOG_WARNING, "MODEL: [%s] Texcoords attribute data format not supported, use vec2 float", fileName); + + int index = data->meshes[i].primitives[p].attributes[j].index; + if (index == 0) model.meshes[meshIndex].texcoords = texcoordPtr; + else if (index == 1) model.meshes[meshIndex].texcoords2 = texcoordPtr; + else + { + TRACELOG(LOG_WARNING, "MODEL: [%s] No more than 2 texture coordinates attributes supported", fileName); + if (texcoordPtr != NULL) RL_FREE(texcoordPtr); + } } - else if (data->meshes[i].primitives[p].attributes[j].type == cgltf_attribute_type_color) // COLOR_0 + else if (data->meshes[i].primitives[p].attributes[j].type == cgltf_attribute_type_color) // COLOR_n, vec3/vec4, float/u8n/u16n { cgltf_accessor *attribute = data->meshes[i].primitives[p].attributes[j].data; - // WARNING: SPECS: All components of each COLOR_n accessor element MUST be clamped to [0.0, 1.0] range. + // WARNING: SPECS: All components of each COLOR_n accessor element MUST be clamped to [0.0, 1.0] range - if ((attribute->component_type == cgltf_component_type_r_8u) && (attribute->type == cgltf_type_vec4)) + if (attribute->type == cgltf_type_vec3) // RGB { - // Init raylib mesh color to copy glTF attribute data - model.meshes[meshIndex].colors = RL_MALLOC(attribute->count*4*sizeof(unsigned char)); + if (attribute->component_type == cgltf_component_type_r_8u) + { + // Init raylib mesh color to copy glTF attribute data + model.meshes[meshIndex].colors = RL_MALLOC(attribute->count*4*sizeof(unsigned char)); - // Load 4 components of unsigned char data type into mesh.colors - LOAD_ATTRIBUTE(attribute, 4, unsigned char, model.meshes[meshIndex].colors) + // Load data into a temp buffer to be converted to raylib data type + unsigned char *temp = RL_MALLOC(attribute->count*3*sizeof(unsigned char)); + LOAD_ATTRIBUTE(attribute, 3, unsigned char, temp); + + // Convert data to raylib color data type (4 bytes) + for (unsigned int c = 0, k = 0; c < (attribute->count*4 - 3); c += 4, k += 3) + { + model.meshes[meshIndex].colors[c] = temp[k]; + model.meshes[meshIndex].colors[c + 1] = temp[k + 1]; + model.meshes[meshIndex].colors[c + 2] = temp[k + 2]; + model.meshes[meshIndex].colors[c + 3] = 255; + } + + RL_FREE(temp); + } + else if (attribute->component_type == cgltf_component_type_r_16u) + { + // Init raylib mesh color to copy glTF attribute data + model.meshes[meshIndex].colors = RL_MALLOC(attribute->count*4*sizeof(unsigned char)); + + // Load data into a temp buffer to be converted to raylib data type + unsigned short *temp = RL_MALLOC(attribute->count*3*sizeof(unsigned short)); + LOAD_ATTRIBUTE(attribute, 3, unsigned short, temp); + + // Convert data to raylib color data type (4 bytes) + for (unsigned int c = 0, k = 0; c < (attribute->count*4 - 3); c += 4, k += 3) + { + model.meshes[meshIndex].colors[c] = (unsigned char)(((float)temp[k]/65535.0f)*255.0f); + model.meshes[meshIndex].colors[c + 1] = (unsigned char)(((float)temp[k + 1]/65535.0f)*255.0f); + model.meshes[meshIndex].colors[c + 2] = (unsigned char)(((float)temp[k + 2]/65535.0f)*255.0f); + model.meshes[meshIndex].colors[c + 3] = 255; + } + + RL_FREE(temp); + } + else if (attribute->component_type == cgltf_component_type_r_32f) + { + // Init raylib mesh color to copy glTF attribute data + model.meshes[meshIndex].colors = RL_MALLOC(attribute->count*4*sizeof(unsigned char)); + + // Load data into a temp buffer to be converted to raylib data type + float *temp = RL_MALLOC(attribute->count*3*sizeof(float)); + LOAD_ATTRIBUTE(attribute, 3, float, temp); + + // Convert data to raylib color data type (4 bytes) + for (unsigned int c = 0, k = 0; c < (attribute->count*4 - 3); c += 4, k += 3) + { + model.meshes[meshIndex].colors[c] = (unsigned char)(temp[k]*255.0f); + model.meshes[meshIndex].colors[c + 1] = (unsigned char)(temp[k + 1]*255.0f); + model.meshes[meshIndex].colors[c + 2] = (unsigned char)(temp[k + 2]*255.0f); + model.meshes[meshIndex].colors[c + 3] = 255; + } + + RL_FREE(temp); + } + else TRACELOG(LOG_WARNING, "MODEL: [%s] Color attribute data format not supported", fileName); } - else if ((attribute->component_type == cgltf_component_type_r_16u) && (attribute->type == cgltf_type_vec4)) + else if (attribute->type == cgltf_type_vec4) // RGBA { - // Init raylib mesh color to copy glTF attribute data - model.meshes[meshIndex].colors = RL_MALLOC(attribute->count*4*sizeof(unsigned char)); + if (attribute->component_type == cgltf_component_type_r_8u) + { + // Init raylib mesh color to copy glTF attribute data + model.meshes[meshIndex].colors = RL_MALLOC(attribute->count*4*sizeof(unsigned char)); - // Load data into a temp buffer to be converted to raylib data type - unsigned short *temp = RL_MALLOC(attribute->count*4*sizeof(unsigned short)); - LOAD_ATTRIBUTE(attribute, 4, unsigned short, temp); + // Load 4 components of unsigned char data type into mesh.colors + LOAD_ATTRIBUTE(attribute, 4, unsigned char, model.meshes[meshIndex].colors) + } + else if (attribute->component_type == cgltf_component_type_r_16u) + { + // Init raylib mesh color to copy glTF attribute data + model.meshes[meshIndex].colors = RL_MALLOC(attribute->count*4*sizeof(unsigned char)); - // Convert data to raylib color data type (4 bytes) - for (unsigned int c = 0; c < attribute->count*4; c++) model.meshes[meshIndex].colors[c] = (unsigned char)(((float)temp[c]/65535.0f)*255.0f); + // Load data into a temp buffer to be converted to raylib data type + unsigned short *temp = RL_MALLOC(attribute->count*4*sizeof(unsigned short)); + LOAD_ATTRIBUTE(attribute, 4, unsigned short, temp); - RL_FREE(temp); - } - else if ((attribute->component_type == cgltf_component_type_r_32f) && (attribute->type == cgltf_type_vec4)) - { - // Init raylib mesh color to copy glTF attribute data - model.meshes[meshIndex].colors = RL_MALLOC(attribute->count*4*sizeof(unsigned char)); + // Convert data to raylib color data type (4 bytes) + for (unsigned int c = 0; c < attribute->count*4; c++) model.meshes[meshIndex].colors[c] = (unsigned char)(((float)temp[c]/65535.0f)*255.0f); - // Load data into a temp buffer to be converted to raylib data type - float *temp = RL_MALLOC(attribute->count*4*sizeof(float)); - LOAD_ATTRIBUTE(attribute, 4, float, temp); + RL_FREE(temp); + } + else if (attribute->component_type == cgltf_component_type_r_32f) + { + // Init raylib mesh color to copy glTF attribute data + model.meshes[meshIndex].colors = RL_MALLOC(attribute->count*4*sizeof(unsigned char)); - // Convert data to raylib color data type (4 bytes), we expect the color data normalized - for (unsigned int c = 0; c < attribute->count*4; c++) model.meshes[meshIndex].colors[c] = (unsigned char)(temp[c]*255.0f); + // Load data into a temp buffer to be converted to raylib data type + float *temp = RL_MALLOC(attribute->count*4*sizeof(float)); + LOAD_ATTRIBUTE(attribute, 4, float, temp); - RL_FREE(temp); + // Convert data to raylib color data type (4 bytes), we expect the color data normalized + for (unsigned int c = 0; c < attribute->count*4; c++) model.meshes[meshIndex].colors[c] = (unsigned char)(temp[c]*255.0f); + + RL_FREE(temp); + } + else TRACELOG(LOG_WARNING, "MODEL: [%s] Color attribute data format not supported", fileName); } else TRACELOG(LOG_WARNING, "MODEL: [%s] Color attribute data format not supported", fileName); + + } // NOTE: Attributes related to animations are processed separately @@ -5149,37 +5397,103 @@ static Model LoadGLTF(const char *fileName) { // NOTE: JOINTS_1 + WEIGHT_1 will be used for +4 joints influencing a vertex -> Not supported by raylib - if (data->meshes[i].primitives[p].attributes[j].type == cgltf_attribute_type_joints) // JOINTS_n (vec4: 4 bones max per vertex / u8, u16) + if (data->meshes[i].primitives[p].attributes[j].type == cgltf_attribute_type_joints) // JOINTS_n (vec4: 4 bones max per vertex / u8, u16) { cgltf_accessor *attribute = data->meshes[i].primitives[p].attributes[j].data; - if ((attribute->component_type == cgltf_component_type_r_8u) && (attribute->type == cgltf_type_vec4)) - { - // Init raylib mesh bone ids to copy glTF attribute data - model.meshes[meshIndex].boneIds = RL_CALLOC(model.meshes[meshIndex].vertexCount*4, sizeof(unsigned char)); + // NOTE: JOINTS_n can only be vec4 and u8/u16 + // SPECS: https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#meshes-overview - // Load 4 components of unsigned char data type into mesh.boneIds - // for cgltf_attribute_type_joints we have: - // - data.meshes[0] (256 vertices) - // - 256 values, provided as cgltf_type_vec4 of bytes (4 byte per joint, stride 4) - LOAD_ATTRIBUTE(attribute, 4, unsigned char, model.meshes[meshIndex].boneIds) + // WARNING: raylib only supports model.meshes[].boneIds as u8 (unsigned char), + // if data is provided in any other format, it is converted to supported format but + // it could imply data loss (a warning message is issued in that case) + + if (attribute->type == cgltf_type_vec4) + { + if (attribute->component_type == cgltf_component_type_r_8u) + { + // Init raylib mesh boneIds to copy glTF attribute data + model.meshes[meshIndex].boneIds = RL_CALLOC(model.meshes[meshIndex].vertexCount*4, sizeof(unsigned char)); + + // Load attribute: vec4, u8 (unsigned char) + LOAD_ATTRIBUTE(attribute, 4, unsigned char, model.meshes[meshIndex].boneIds) + } + else if (attribute->component_type == cgltf_component_type_r_16u) + { + // Init raylib mesh boneIds to copy glTF attribute data + model.meshes[meshIndex].boneIds = RL_CALLOC(model.meshes[meshIndex].vertexCount*4, sizeof(unsigned char)); + + // Load data into a temp buffer to be converted to raylib data type + unsigned short *temp = RL_CALLOC(model.meshes[meshIndex].vertexCount*4, sizeof(unsigned short)); + LOAD_ATTRIBUTE(attribute, 4, unsigned short, temp); + + // Convert data to raylib color data type (4 bytes) + bool boneIdOverflowWarning = false; + for (int b = 0; b < model.meshes[meshIndex].vertexCount*4; b++) + { + if ((temp[b] > 255) && !boneIdOverflowWarning) + { + TRACELOG(LOG_WARNING, "MODEL: [%s] Joint attribute data format (u16) overflow", fileName); + boneIdOverflowWarning = true; + } + + // Despite the possible overflow, we convert data to unsigned char + model.meshes[meshIndex].boneIds[b] = (unsigned char)temp[b]; + } + + RL_FREE(temp); + } + else TRACELOG(LOG_WARNING, "MODEL: [%s] Joint attribute data format not supported", fileName); } - else TRACELOG(LOG_WARNING, "MODEL: [%s] Joint attribute data format not supported, use vec4 u8", fileName); + else TRACELOG(LOG_WARNING, "MODEL: [%s] Joint attribute data format not supported", fileName); } - else if (data->meshes[i].primitives[p].attributes[j].type == cgltf_attribute_type_weights) // WEIGHTS_n (vec4 / u8, u16, f32) + else if (data->meshes[i].primitives[p].attributes[j].type == cgltf_attribute_type_weights) // WEIGHTS_n (vec4, u8n/u16n/f32) { cgltf_accessor *attribute = data->meshes[i].primitives[p].attributes[j].data; - if ((attribute->component_type == cgltf_component_type_r_32f) && (attribute->type == cgltf_type_vec4)) + if (attribute->type == cgltf_type_vec4) { - // Init raylib mesh bone weight to copy glTF attribute data - model.meshes[meshIndex].boneWeights = RL_CALLOC(model.meshes[meshIndex].vertexCount*4, sizeof(float)); + // TODO: Support component types: u8, u16? + if (attribute->component_type == cgltf_component_type_r_8u) + { + // Init raylib mesh bone weight to copy glTF attribute data + model.meshes[meshIndex].boneWeights = RL_CALLOC(model.meshes[meshIndex].vertexCount*4, sizeof(float)); - // Load 4 components of float data type into mesh.boneWeights - // for cgltf_attribute_type_weights we have: - // - data.meshes[0] (256 vertices) - // - 256 values, provided as cgltf_type_vec4 of float (4 byte per joint, stride 16) - LOAD_ATTRIBUTE(attribute, 4, float, model.meshes[meshIndex].boneWeights) + // Load data into a temp buffer to be converted to raylib data type + unsigned char *temp = RL_MALLOC(attribute->count*4*sizeof(unsigned char)); + LOAD_ATTRIBUTE(attribute, 4, unsigned char, temp); + + // Convert data to raylib bone weight data type (4 bytes) + for (unsigned int b = 0; b < attribute->count*4; b++) model.meshes[meshIndex].boneWeights[b] = (float)temp[b]/255.0f; + + RL_FREE(temp); + } + else if (attribute->component_type == cgltf_component_type_r_16u) + { + // Init raylib mesh bone weight to copy glTF attribute data + model.meshes[meshIndex].boneWeights = RL_CALLOC(model.meshes[meshIndex].vertexCount*4, sizeof(float)); + + // Load data into a temp buffer to be converted to raylib data type + unsigned short *temp = RL_MALLOC(attribute->count*4*sizeof(unsigned short)); + LOAD_ATTRIBUTE(attribute, 4, unsigned short, temp); + + // Convert data to raylib bone weight data type + for (unsigned int b = 0; b < attribute->count*4; b++) model.meshes[meshIndex].boneWeights[b] = (float)temp[b]/65535.0f; + + RL_FREE(temp); + } + else if (attribute->component_type == cgltf_component_type_r_32f) + { + // Init raylib mesh bone weight to copy glTF attribute data + model.meshes[meshIndex].boneWeights = RL_CALLOC(model.meshes[meshIndex].vertexCount*4, sizeof(float)); + + // Load 4 components of float data type into mesh.boneWeights + // for cgltf_attribute_type_weights we have: + // - data.meshes[0] (256 vertices) + // - 256 values, provided as cgltf_type_vec4 of float (4 byte per joint, stride 16) + LOAD_ATTRIBUTE(attribute, 4, float, model.meshes[meshIndex].boneWeights) + } + else TRACELOG(LOG_WARNING, "MODEL: [%s] Joint weight attribute data format not supported, use vec4 float", fileName); } else TRACELOG(LOG_WARNING, "MODEL: [%s] Joint weight attribute data format not supported, use vec4 float", fileName); } @@ -5189,7 +5503,8 @@ static Model LoadGLTF(const char *fileName) model.meshes[meshIndex].animVertices = RL_CALLOC(model.meshes[meshIndex].vertexCount*3, sizeof(float)); memcpy(model.meshes[meshIndex].animVertices, model.meshes[meshIndex].vertices, model.meshes[meshIndex].vertexCount*3*sizeof(float)); model.meshes[meshIndex].animNormals = RL_CALLOC(model.meshes[meshIndex].vertexCount*3, sizeof(float)); - if (model.meshes[meshIndex].normals != NULL) { + if (model.meshes[meshIndex].normals != NULL) + { memcpy(model.meshes[meshIndex].animNormals, model.meshes[meshIndex].normals, model.meshes[meshIndex].vertexCount*3*sizeof(float)); } @@ -5209,9 +5524,11 @@ static Model LoadGLTF(const char *fileName) return model; } -// Get interpolated pose for bone sampler at a specific time. Returns true on success. -static bool GetPoseAtTimeGLTF(cgltf_accessor *input, cgltf_accessor *output, float time, void *data) +// Get interpolated pose for bone sampler at a specific time. Returns true on success +static bool GetPoseAtTimeGLTF(cgltf_interpolation_type interpolationType, cgltf_accessor *input, cgltf_accessor *output, float time, void *data) { + if (interpolationType >= cgltf_interpolation_type_max_enum) return false; + // Input and output should have the same count float tstart = 0.0f; float tend = 0.0f; @@ -5232,7 +5549,8 @@ static bool GetPoseAtTimeGLTF(cgltf_accessor *input, cgltf_accessor *output, flo } } - float t = (time - tstart)/(tend - tstart); + float duration = fmaxf((tend - tstart), EPSILON); + float t = (time - tstart)/duration; t = (t < 0.0f)? 0.0f : t; t = (t > 1.0f)? 1.0f : t; @@ -5240,25 +5558,99 @@ static bool GetPoseAtTimeGLTF(cgltf_accessor *input, cgltf_accessor *output, flo if (output->type == cgltf_type_vec3) { - float tmp[3] = { 0.0f }; - cgltf_accessor_read_float(output, keyframe, tmp, 3); - Vector3 v1 = {tmp[0], tmp[1], tmp[2]}; - cgltf_accessor_read_float(output, keyframe+1, tmp, 3); - Vector3 v2 = {tmp[0], tmp[1], tmp[2]}; - Vector3 *r = data; - *r = Vector3Lerp(v1, v2, t); + switch (interpolationType) + { + case cgltf_interpolation_type_step: + { + float tmp[3] = { 0.0f }; + cgltf_accessor_read_float(output, keyframe, tmp, 3); + Vector3 v1 = {tmp[0], tmp[1], tmp[2]}; + Vector3 *r = data; + + *r = v1; + } break; + case cgltf_interpolation_type_linear: + { + float tmp[3] = { 0.0f }; + cgltf_accessor_read_float(output, keyframe, tmp, 3); + Vector3 v1 = {tmp[0], tmp[1], tmp[2]}; + cgltf_accessor_read_float(output, keyframe+1, tmp, 3); + Vector3 v2 = {tmp[0], tmp[1], tmp[2]}; + Vector3 *r = data; + + *r = Vector3Lerp(v1, v2, t); + } break; + case cgltf_interpolation_type_cubic_spline: + { + float tmp[3] = { 0.0f }; + cgltf_accessor_read_float(output, 3*keyframe+1, tmp, 3); + Vector3 v1 = {tmp[0], tmp[1], tmp[2]}; + cgltf_accessor_read_float(output, 3*keyframe+2, tmp, 3); + Vector3 tangent1 = {tmp[0], tmp[1], tmp[2]}; + cgltf_accessor_read_float(output, 3*(keyframe+1)+1, tmp, 3); + Vector3 v2 = {tmp[0], tmp[1], tmp[2]}; + cgltf_accessor_read_float(output, 3*(keyframe+1), tmp, 3); + Vector3 tangent2 = {tmp[0], tmp[1], tmp[2]}; + Vector3 *r = data; + + *r = Vector3CubicHermite(v1, tangent1, v2, tangent2, t); + } break; + default: break; + } } else if (output->type == cgltf_type_vec4) { - float tmp[4] = { 0.0f }; - cgltf_accessor_read_float(output, keyframe, tmp, 4); - Vector4 v1 = {tmp[0], tmp[1], tmp[2], tmp[3]}; - cgltf_accessor_read_float(output, keyframe+1, tmp, 4); - Vector4 v2 = {tmp[0], tmp[1], tmp[2], tmp[3]}; - Vector4 *r = data; - // Only v4 is for rotations, so we know it's a quaternion - *r = QuaternionSlerp(v1, v2, t); + switch (interpolationType) + { + case cgltf_interpolation_type_step: + { + float tmp[4] = { 0.0f }; + cgltf_accessor_read_float(output, keyframe, tmp, 4); + Vector4 v1 = {tmp[0], tmp[1], tmp[2], tmp[3]}; + Vector4 *r = data; + + *r = v1; + } break; + case cgltf_interpolation_type_linear: + { + float tmp[4] = { 0.0f }; + cgltf_accessor_read_float(output, keyframe, tmp, 4); + Vector4 v1 = {tmp[0], tmp[1], tmp[2], tmp[3]}; + cgltf_accessor_read_float(output, keyframe+1, tmp, 4); + Vector4 v2 = {tmp[0], tmp[1], tmp[2], tmp[3]}; + Vector4 *r = data; + + *r = QuaternionSlerp(v1, v2, t); + } break; + case cgltf_interpolation_type_cubic_spline: + { + float tmp[4] = { 0.0f }; + cgltf_accessor_read_float(output, 3*keyframe+1, tmp, 4); + Vector4 v1 = {tmp[0], tmp[1], tmp[2], tmp[3]}; + cgltf_accessor_read_float(output, 3*keyframe+2, tmp, 4); + Vector4 outTangent1 = {tmp[0], tmp[1], tmp[2]}; + cgltf_accessor_read_float(output, 3*(keyframe+1)+1, tmp, 4); + Vector4 v2 = {tmp[0], tmp[1], tmp[2], tmp[3]}; + cgltf_accessor_read_float(output, 3*(keyframe+1), tmp, 4); + Vector4 inTangent2 = {tmp[0], tmp[1], tmp[2]}; + Vector4 *r = data; + + v1 = QuaternionNormalize(v1); + v2 = QuaternionNormalize(v2); + + if (Vector4DotProduct(v1, v2) < 0.0f) + { + v2 = Vector4Negate(v2); + } + + outTangent1 = Vector4Scale(outTangent1, duration); + inTangent2 = Vector4Scale(inTangent2, duration); + + *r = QuaternionCubicHermiteSpline(v1, outTangent1, v2, inTangent2, t); + } break; + default: break; + } } return true; @@ -5276,6 +5668,8 @@ static ModelAnimation *LoadModelAnimationsGLTF(const char *fileName, int *animCo // glTF data loading cgltf_options options = { 0 }; + options.file.read = LoadFileGLTFCallback; + options.file.release = ReleaseFileGLTFCallback; cgltf_data *data = NULL; cgltf_result result = cgltf_parse(&options, fileData, dataSize, &data); @@ -5307,6 +5701,7 @@ static ModelAnimation *LoadModelAnimationsGLTF(const char *fileName, int *animCo cgltf_animation_channel *translate; cgltf_animation_channel *rotate; cgltf_animation_channel *scale; + cgltf_interpolation_type interpolationType; }; struct Channels *boneChannels = RL_CALLOC(animations[i].boneCount, sizeof(struct Channels)); @@ -5332,7 +5727,9 @@ static ModelAnimation *LoadModelAnimationsGLTF(const char *fileName, int *animCo continue; } - if (animData.channels[j].sampler->interpolation == cgltf_interpolation_type_linear) + boneChannels[boneIndex].interpolationType = animData.channels[j].sampler->interpolation; + + if (animData.channels[j].sampler->interpolation != cgltf_interpolation_type_max_enum) { if (channel.target_path == cgltf_animation_path_type_translation) { @@ -5351,7 +5748,7 @@ static ModelAnimation *LoadModelAnimationsGLTF(const char *fileName, int *animCo TRACELOG(LOG_WARNING, "MODEL: [%s] Unsupported target_path on channel %d's sampler for animation %d. Skipping.", fileName, j, i); } } - else TRACELOG(LOG_WARNING, "MODEL: [%s] Only linear interpolation curves are supported for GLTF animation.", fileName); + else TRACELOG(LOG_WARNING, "MODEL: [%s] Invalid interpolation curve encountered for GLTF animation.", fileName); float t = 0.0f; cgltf_bool r = cgltf_accessor_read_float(channel.sampler->input, channel.sampler->input->count - 1, &t, 1); @@ -5368,7 +5765,7 @@ static ModelAnimation *LoadModelAnimationsGLTF(const char *fileName, int *animCo strncpy(animations[i].name, animData.name, sizeof(animations[i].name)); animations[i].name[sizeof(animations[i].name) - 1] = '\0'; - animations[i].frameCount = (int)(animDuration*1000.0f/GLTF_ANIMDELAY); + animations[i].frameCount = (int)(animDuration*1000.0f/GLTF_ANIMDELAY) + 1; animations[i].framePoses = RL_MALLOC(animations[i].frameCount*sizeof(Transform *)); for (int j = 0; j < animations[i].frameCount; j++) @@ -5384,7 +5781,7 @@ static ModelAnimation *LoadModelAnimationsGLTF(const char *fileName, int *animCo if (boneChannels[k].translate) { - if (!GetPoseAtTimeGLTF(boneChannels[k].translate->sampler->input, boneChannels[k].translate->sampler->output, time, &translation)) + if (!GetPoseAtTimeGLTF(boneChannels[k].interpolationType, boneChannels[k].translate->sampler->input, boneChannels[k].translate->sampler->output, time, &translation)) { TRACELOG(LOG_INFO, "MODEL: [%s] Failed to load translate pose data for bone %s", fileName, animations[i].bones[k].name); } @@ -5392,7 +5789,7 @@ static ModelAnimation *LoadModelAnimationsGLTF(const char *fileName, int *animCo if (boneChannels[k].rotate) { - if (!GetPoseAtTimeGLTF(boneChannels[k].rotate->sampler->input, boneChannels[k].rotate->sampler->output, time, &rotation)) + if (!GetPoseAtTimeGLTF(boneChannels[k].interpolationType, boneChannels[k].rotate->sampler->input, boneChannels[k].rotate->sampler->output, time, &rotation)) { TRACELOG(LOG_INFO, "MODEL: [%s] Failed to load rotate pose data for bone %s", fileName, animations[i].bones[k].name); } @@ -5400,7 +5797,7 @@ static ModelAnimation *LoadModelAnimationsGLTF(const char *fileName, int *animCo if (boneChannels[k].scale) { - if (!GetPoseAtTimeGLTF(boneChannels[k].scale->sampler->input, boneChannels[k].scale->sampler->output, time, &scale)) + if (!GetPoseAtTimeGLTF(boneChannels[k].interpolationType, boneChannels[k].scale->sampler->input, boneChannels[k].scale->sampler->output, time, &scale)) { TRACELOG(LOG_INFO, "MODEL: [%s] Failed to load scale pose data for bone %s", fileName, animations[i].bones[k].name); } @@ -5487,6 +5884,7 @@ static Model LoadVOX(const char *fileName) // 6*4 = 12 vertices per voxel Vector3 *pvertices = (Vector3 *)voxarray.vertices.array; + Vector3 *pnormals = (Vector3 *)voxarray.normals.array; Color *pcolors = (Color *)voxarray.colors.array; unsigned short *pindices = voxarray.indices.array; // 5461*6*6 = 196596 indices max per mesh @@ -5502,12 +5900,16 @@ static Model LoadVOX(const char *fileName) pmesh->vertexCount = (int)fmin(verticesMax, verticesRemain); size = pmesh->vertexCount*sizeof(float)*3; - pmesh->vertices = RL_MALLOC(size); + pmesh->vertices = (float *)RL_MALLOC(size); memcpy(pmesh->vertices, pvertices, size); + // Copy normals + pmesh->normals = (float *)RL_MALLOC(size); + memcpy(pmesh->normals, pnormals, size); + // Copy indices size = voxarray.indices.used*sizeof(unsigned short); - pmesh->indices = RL_MALLOC(size); + pmesh->indices = (unsigned short *)RL_MALLOC(size); memcpy(pmesh->indices, pindices, size); pmesh->triangleCount = (pmesh->vertexCount/4)*2; @@ -5522,6 +5924,7 @@ static Model LoadVOX(const char *fileName) verticesRemain -= verticesMax; pvertices += verticesMax; + pnormals += verticesMax; pcolors += verticesMax; } @@ -5585,7 +5988,7 @@ static Model LoadM3D(const char *fileName) // We always need a default material, so we add +1 model.materialCount++; - // Faces must be in non-decreasing materialid order. Verify that quickly, sorting them otherwise. + // Faces must be in non-decreasing materialid order. Verify that quickly, sorting them otherwise // WARNING: Sorting is not needed, valid M3D model files should already be sorted // Just keeping the sorting function for reference (Check PR #3363 #3385) /* @@ -5593,12 +5996,12 @@ static Model LoadM3D(const char *fileName) { if (m3d->face[i-1].materialid <= m3d->face[i].materialid) continue; - // face[i-1] > face[i]. slide face[i] lower. + // face[i-1] > face[i]. slide face[i] lower m3df_t slider = m3d->face[i]; j = i-1; do - { // face[j] > slider, face[j+1] is svailable vacant gap. + { // face[j] > slider, face[j+1] is svailable vacant gap m3d->face[j+1] = m3d->face[j]; j = j-1; } @@ -5651,6 +6054,12 @@ static Model LoadM3D(const char *fileName) // M3D specs only consider vertex colors if no material is provided, however raylib uses both and mixes the colors if ((mi == M3D_UNDEF) || vcolor) model.meshes[k].colors = RL_CALLOC(model.meshes[k].vertexCount*4, sizeof(unsigned char)); + // If no map is provided and we allocated vertex colors, set them to white + if ((mi == M3D_UNDEF) && (model.meshes[k].colors != NULL)) + { + for (int c = 0; c < model.meshes[k].vertexCount*4; c++) model.meshes[k].colors[c] = 255; + } + if (m3d->numbone && m3d->numskin) { model.meshes[k].boneIds = (unsigned char *)RL_CALLOC(model.meshes[k].vertexCount*4, sizeof(unsigned char)); @@ -5853,10 +6262,10 @@ static Model LoadM3D(const char *fileName) } // Load bone-pose default mesh into animation vertices. These will be updated when UpdateModelAnimation gets - // called, but not before, however DrawMesh uses these if they exist (so not good if they are left empty). + // called, but not before, however DrawMesh uses these if they exist (so not good if they are left empty) if (m3d->numbone && m3d->numskin) { - for(i = 0; i < model.meshCount; i++) + for (i = 0; i < model.meshCount; i++) { memcpy(model.meshes[i].animVertices, model.meshes[i].vertices, model.meshes[i].vertexCount*3*sizeof(float)); memcpy(model.meshes[i].animNormals, model.meshes[i].normals, model.meshes[i].vertexCount*3*sizeof(float)); @@ -5910,11 +6319,13 @@ static ModelAnimation *LoadModelAnimationsM3D(const char *fileName, int *animCou for (unsigned int a = 0; a < m3d->numaction; a++) { - animations[a].frameCount = m3d->action[a].durationmsec / M3D_ANIMDELAY; + animations[a].frameCount = m3d->action[a].durationmsec/M3D_ANIMDELAY; animations[a].boneCount = m3d->numbone + 1; animations[a].bones = RL_MALLOC((m3d->numbone + 1)*sizeof(BoneInfo)); animations[a].framePoses = RL_MALLOC(animations[a].frameCount*sizeof(Transform *)); - // strncpy(animations[a].name, m3d->action[a].name, sizeof(animations[a].name)); + strncpy(animations[a].name, m3d->action[a].name, sizeof(animations[a].name)); + animations[a].name[sizeof(animations[a].name) - 1] = '\0'; + TRACELOG(LOG_INFO, "MODEL: [%s] animation #%i: %i msec, %i frames", fileName, a, m3d->action[a].durationmsec, animations[a].frameCount); for (i = 0; i < (int)m3d->numbone; i++) diff --git a/raylib/rshapes.c b/raylib/rshapes.c index bababf8..80df64e 100644 --- a/raylib/rshapes.c +++ b/raylib/rshapes.c @@ -25,7 +25,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2013-2023 Ramon Santamaria (@raysan5) +* Copyright (c) 2013-2024 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. @@ -71,7 +71,6 @@ #define SPLINE_SEGMENT_DIVISIONS 24 // Spline segment divisions #endif - //---------------------------------------------------------------------------------- // Types and Structures Definition //---------------------------------------------------------------------------------- @@ -112,6 +111,18 @@ void SetShapesTexture(Texture2D texture, Rectangle source) } } +// Get texture that is used for shapes drawing +Texture2D GetShapesTexture(void) +{ + return texShapes; +} + +// Get texture source rectangle that is used for shapes drawing +Rectangle GetShapesTextureRectangle(void) +{ + return texShapesRec; +} + // Draw a pixel void DrawPixel(int posX, int posY, Color color) { @@ -122,23 +133,24 @@ void DrawPixel(int posX, int posY, Color color) void DrawPixelV(Vector2 position, Color color) { #if defined(SUPPORT_QUADS_DRAW_MODE) - rlSetTexture(texShapes.id); + rlSetTexture(GetShapesTexture().id); + Rectangle shapeRect = GetShapesTextureRectangle(); rlBegin(RL_QUADS); rlNormal3f(0.0f, 0.0f, 1.0f); rlColor4ub(color.r, color.g, color.b, color.a); - rlTexCoord2f(texShapesRec.x/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(position.x, position.y); - rlTexCoord2f(texShapesRec.x/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(position.x, position.y + 1); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(position.x + 1, position.y + 1); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(position.x + 1, position.y); rlEnd(); @@ -166,8 +178,9 @@ void DrawLine(int startPosX, int startPosY, int endPosX, int endPosY, Color colo { rlBegin(RL_LINES); rlColor4ub(color.r, color.g, color.b, color.a); - rlVertex2f((float)startPosX, (float)startPosY); - rlVertex2f((float)endPosX, (float)endPosY); + // WARNING: Adding 0.5f offset to "center" point on selected pixel + rlVertex2f((float)startPosX + 0.5f, (float)startPosY + 0.5f); + rlVertex2f((float)endPosX + 0.5f, (float)endPosY + 0.5f); rlEnd(); } @@ -176,26 +189,26 @@ void DrawLineV(Vector2 startPos, Vector2 endPos, Color color) { rlBegin(RL_LINES); rlColor4ub(color.r, color.g, color.b, color.a); - rlVertex2f(startPos.x, startPos.y); - rlVertex2f(endPos.x, endPos.y); + // WARNING: Adding 0.5f offset to "center" point on selected pixel + rlVertex2f(startPos.x + 0.5f, startPos.y + 0.5f); + rlVertex2f(endPos.x + 0.5f, endPos.y + 0.5f); rlEnd(); } // Draw lines sequuence (using gl lines) void DrawLineStrip(Vector2 *points, int pointCount, Color color) { - if (pointCount >= 2) - { - rlBegin(RL_LINES); - rlColor4ub(color.r, color.g, color.b, color.a); + if (pointCount < 2) return; // Security check - for (int i = 0; i < pointCount - 1; i++) - { - rlVertex2f(points[i].x, points[i].y); - rlVertex2f(points[i + 1].x, points[i + 1].y); - } - rlEnd(); - } + rlBegin(RL_LINES); + rlColor4ub(color.r, color.g, color.b, color.a); + + for (int i = 0; i < pointCount - 1; i++) + { + rlVertex2f(points[i].x, points[i].y); + rlVertex2f(points[i + 1].x, points[i + 1].y); + } + rlEnd(); } // Draw line using cubic-bezier spline, in-out interpolation, no control points @@ -300,7 +313,8 @@ void DrawCircleSector(Vector2 center, float radius, float startAngle, float endA float angle = startAngle; #if defined(SUPPORT_QUADS_DRAW_MODE) - rlSetTexture(texShapes.id); + rlSetTexture(GetShapesTexture().id); + Rectangle shapeRect = GetShapesTextureRectangle(); rlBegin(RL_QUADS); @@ -309,36 +323,36 @@ void DrawCircleSector(Vector2 center, float radius, float startAngle, float endA { rlColor4ub(color.r, color.g, color.b, color.a); - rlTexCoord2f(texShapesRec.x/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(center.x, center.y); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(center.x + cosf(DEG2RAD*(angle + stepLength*2.0f))*radius, center.y + sinf(DEG2RAD*(angle + stepLength*2.0f))*radius); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(center.x + cosf(DEG2RAD*(angle + stepLength))*radius, center.y + sinf(DEG2RAD*(angle + stepLength))*radius); - rlTexCoord2f(texShapesRec.x/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(center.x + cosf(DEG2RAD*angle)*radius, center.y + sinf(DEG2RAD*angle)*radius); angle += (stepLength*2.0f); } // NOTE: In case number of segments is odd, we add one last piece to the cake - if ((segments%2) == 1) + if (((unsigned int)segments%2) == 1) { rlColor4ub(color.r, color.g, color.b, color.a); - rlTexCoord2f(texShapesRec.x/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(center.x, center.y); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(center.x + cosf(DEG2RAD*(angle + stepLength))*radius, center.y + sinf(DEG2RAD*(angle + stepLength))*radius); - rlTexCoord2f(texShapesRec.x/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(center.x + cosf(DEG2RAD*angle)*radius, center.y + sinf(DEG2RAD*angle)*radius); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(center.x, center.y); } @@ -528,23 +542,24 @@ void DrawRing(Vector2 center, float innerRadius, float outerRadius, float startA float angle = startAngle; #if defined(SUPPORT_QUADS_DRAW_MODE) - rlSetTexture(texShapes.id); + rlSetTexture(GetShapesTexture().id); + Rectangle shapeRect = GetShapesTextureRectangle(); rlBegin(RL_QUADS); for (int i = 0; i < segments; i++) { rlColor4ub(color.r, color.g, color.b, color.a); - rlTexCoord2f(texShapesRec.x/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(center.x + cosf(DEG2RAD*angle)*outerRadius, center.y + sinf(DEG2RAD*angle)*outerRadius); - rlTexCoord2f(texShapesRec.x/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(center.x + cosf(DEG2RAD*angle)*innerRadius, center.y + sinf(DEG2RAD*angle)*innerRadius); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(center.x + cosf(DEG2RAD*(angle + stepLength))*innerRadius, center.y + sinf(DEG2RAD*(angle + stepLength))*innerRadius); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(center.x + cosf(DEG2RAD*(angle + stepLength))*outerRadius, center.y + sinf(DEG2RAD*(angle + stepLength))*outerRadius); angle += stepLength; @@ -707,23 +722,24 @@ void DrawRectanglePro(Rectangle rec, Vector2 origin, float rotation, Color color } #if defined(SUPPORT_QUADS_DRAW_MODE) - rlSetTexture(texShapes.id); + rlSetTexture(GetShapesTexture().id); + Rectangle shapeRect = GetShapesTextureRectangle(); rlBegin(RL_QUADS); rlNormal3f(0.0f, 0.0f, 1.0f); rlColor4ub(color.r, color.g, color.b, color.a); - rlTexCoord2f(texShapesRec.x/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(topLeft.x, topLeft.y); - rlTexCoord2f(texShapesRec.x/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(bottomLeft.x, bottomLeft.y); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(bottomRight.x, bottomRight.y); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(topRight.x, topRight.y); rlEnd(); @@ -764,26 +780,27 @@ void DrawRectangleGradientH(int posX, int posY, int width, int height, Color col // NOTE: Colors refer to corners, starting at top-lef corner and counter-clockwise void DrawRectangleGradientEx(Rectangle rec, Color col1, Color col2, Color col3, Color col4) { - rlSetTexture(texShapes.id); + rlSetTexture(GetShapesTexture().id); + Rectangle shapeRect = GetShapesTextureRectangle(); rlBegin(RL_QUADS); rlNormal3f(0.0f, 0.0f, 1.0f); // NOTE: Default raylib font character 95 is a white square rlColor4ub(col1.r, col1.g, col1.b, col1.a); - rlTexCoord2f(texShapesRec.x/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(rec.x, rec.y); rlColor4ub(col2.r, col2.g, col2.b, col2.a); - rlTexCoord2f(texShapesRec.x/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(rec.x, rec.y + rec.height); rlColor4ub(col3.r, col3.g, col3.b, col3.a); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(rec.x + rec.width, rec.y + rec.height); rlColor4ub(col4.r, col4.g, col4.b, col4.a); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(rec.x + rec.width, rec.y); rlEnd(); @@ -791,30 +808,25 @@ void DrawRectangleGradientEx(Rectangle rec, Color col1, Color col2, Color col3, } // Draw rectangle outline -// NOTE: On OpenGL 3.3 and ES2 we use QUADS to avoid drawing order issues +// WARNING: All Draw*Lines() functions use RL_LINES for drawing, +// it implies flushing the current batch and changing draw mode to RL_LINES +// but it solves another issue: https://github.com/raysan5/raylib/issues/3884 void DrawRectangleLines(int posX, int posY, int width, int height, Color color) { -#if defined(SUPPORT_QUADS_DRAW_MODE) - DrawRectangle(posX, posY, width, 1, color); - DrawRectangle(posX + width - 1, posY + 1, 1, height - 2, color); - DrawRectangle(posX, posY + height - 1, width, 1, color); - DrawRectangle(posX, posY + 1, 1, height - 2, color); -#else rlBegin(RL_LINES); rlColor4ub(color.r, color.g, color.b, color.a); - rlVertex2f(posX + 1, posY + 1); - rlVertex2f(posX + width, posY + 1); + rlVertex2f((float)posX, (float)posY); + rlVertex2f((float)posX + (float)width, (float)posY + 1); - rlVertex2f(posX + width, posY + 1); - rlVertex2f(posX + width, posY + height); + rlVertex2f((float)posX + (float)width, (float)posY + 1); + rlVertex2f((float)posX + (float)width, (float)posY + (float)height); - rlVertex2f(posX + width, posY + height); - rlVertex2f(posX + 1, posY + height); + rlVertex2f((float)posX + (float)width, (float)posY + (float)height); + rlVertex2f((float)posX + 1, (float)posY + (float)height); - rlVertex2f(posX + 1, posY + height); - rlVertex2f(posX + 1, posY + 1); + rlVertex2f((float)posX + 1, (float)posY + (float)height); + rlVertex2f((float)posX + 1, (float)posY + 1); rlEnd(); -#endif } // Draw rectangle outline with extended parameters @@ -904,7 +916,8 @@ void DrawRectangleRounded(Rectangle rec, float roundness, int segments, Color co const float angles[4] = { 180.0f, 270.0f, 0.0f, 90.0f }; #if defined(SUPPORT_QUADS_DRAW_MODE) - rlSetTexture(texShapes.id); + rlSetTexture(GetShapesTexture().id); + Rectangle shapeRect = GetShapesTextureRectangle(); rlBegin(RL_QUADS); // Draw all the 4 corners: [1] Upper Left Corner, [3] Upper Right Corner, [5] Lower Right Corner, [7] Lower Left Corner @@ -917,16 +930,16 @@ void DrawRectangleRounded(Rectangle rec, float roundness, int segments, Color co for (int i = 0; i < segments/2; i++) { rlColor4ub(color.r, color.g, color.b, color.a); - rlTexCoord2f(texShapesRec.x/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(center.x, center.y); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(center.x + cosf(DEG2RAD*(angle + stepLength*2))*radius, center.y + sinf(DEG2RAD*(angle + stepLength*2))*radius); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(center.x + cosf(DEG2RAD*(angle + stepLength))*radius, center.y + sinf(DEG2RAD*(angle + stepLength))*radius); - rlTexCoord2f(texShapesRec.x/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(center.x + cosf(DEG2RAD*angle)*radius, center.y + sinf(DEG2RAD*angle)*radius); angle += (stepLength*2); @@ -936,73 +949,73 @@ void DrawRectangleRounded(Rectangle rec, float roundness, int segments, Color co if (segments%2) { rlColor4ub(color.r, color.g, color.b, color.a); - rlTexCoord2f(texShapesRec.x/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(center.x, center.y); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(center.x + cosf(DEG2RAD*(angle + stepLength))*radius, center.y + sinf(DEG2RAD*(angle + stepLength))*radius); - rlTexCoord2f(texShapesRec.x/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(center.x + cosf(DEG2RAD*angle)*radius, center.y + sinf(DEG2RAD*angle)*radius); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(center.x, center.y); } } // [2] Upper Rectangle rlColor4ub(color.r, color.g, color.b, color.a); - rlTexCoord2f(texShapesRec.x/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(point[0].x, point[0].y); - rlTexCoord2f(texShapesRec.x/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(point[8].x, point[8].y); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(point[9].x, point[9].y); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(point[1].x, point[1].y); // [4] Right Rectangle rlColor4ub(color.r, color.g, color.b, color.a); - rlTexCoord2f(texShapesRec.x/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(point[2].x, point[2].y); - rlTexCoord2f(texShapesRec.x/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(point[9].x, point[9].y); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(point[10].x, point[10].y); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(point[3].x, point[3].y); // [6] Bottom Rectangle rlColor4ub(color.r, color.g, color.b, color.a); - rlTexCoord2f(texShapesRec.x/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(point[11].x, point[11].y); - rlTexCoord2f(texShapesRec.x/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(point[5].x, point[5].y); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(point[4].x, point[4].y); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(point[10].x, point[10].y); // [8] Left Rectangle rlColor4ub(color.r, color.g, color.b, color.a); - rlTexCoord2f(texShapesRec.x/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(point[7].x, point[7].y); - rlTexCoord2f(texShapesRec.x/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(point[6].x, point[6].y); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(point[11].x, point[11].y); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(point[8].x, point[8].y); // [9] Middle Rectangle rlColor4ub(color.r, color.g, color.b, color.a); - rlTexCoord2f(texShapesRec.x/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(point[8].x, point[8].y); - rlTexCoord2f(texShapesRec.x/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(point[11].x, point[11].y); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(point[10].x, point[10].y); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(point[9].x, point[9].y); rlEnd(); @@ -1073,8 +1086,15 @@ void DrawRectangleRounded(Rectangle rec, float roundness, int segments, Color co #endif } +// Draw rectangle with rounded edges +// TODO: This function should be refactored to use RL_LINES, for consistency with other Draw*Lines() +void DrawRectangleRoundedLines(Rectangle rec, float roundness, int segments, Color color) +{ + DrawRectangleRoundedLinesEx(rec, roundness, segments, 1.0f, color); +} + // Draw rectangle with rounded edges outline -void DrawRectangleRoundedLines(Rectangle rec, float roundness, int segments, float lineThick, Color color) +void DrawRectangleRoundedLinesEx(Rectangle rec, float roundness, int segments, float lineThick, Color color) { if (lineThick < 0) lineThick = 0; @@ -1139,7 +1159,8 @@ void DrawRectangleRoundedLines(Rectangle rec, float roundness, int segments, flo if (lineThick > 1) { #if defined(SUPPORT_QUADS_DRAW_MODE) - rlSetTexture(texShapes.id); + rlSetTexture(GetShapesTexture().id); + Rectangle shapeRect = GetShapesTextureRectangle(); rlBegin(RL_QUADS); @@ -1152,16 +1173,16 @@ void DrawRectangleRoundedLines(Rectangle rec, float roundness, int segments, flo { rlColor4ub(color.r, color.g, color.b, color.a); - rlTexCoord2f(texShapesRec.x/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(center.x + cosf(DEG2RAD*angle)*innerRadius, center.y + sinf(DEG2RAD*angle)*innerRadius); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(center.x + cosf(DEG2RAD*(angle + stepLength))*innerRadius, center.y + sinf(DEG2RAD*(angle + stepLength))*innerRadius); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(center.x + cosf(DEG2RAD*(angle + stepLength))*outerRadius, center.y + sinf(DEG2RAD*(angle + stepLength))*outerRadius); - rlTexCoord2f(texShapesRec.x/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(center.x + cosf(DEG2RAD*angle)*outerRadius, center.y + sinf(DEG2RAD*angle)*outerRadius); angle += stepLength; @@ -1170,46 +1191,46 @@ void DrawRectangleRoundedLines(Rectangle rec, float roundness, int segments, flo // Upper rectangle rlColor4ub(color.r, color.g, color.b, color.a); - rlTexCoord2f(texShapesRec.x/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(point[0].x, point[0].y); - rlTexCoord2f(texShapesRec.x/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(point[8].x, point[8].y); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(point[9].x, point[9].y); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(point[1].x, point[1].y); // Right rectangle rlColor4ub(color.r, color.g, color.b, color.a); - rlTexCoord2f(texShapesRec.x/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(point[2].x, point[2].y); - rlTexCoord2f(texShapesRec.x/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(point[10].x, point[10].y); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(point[11].x, point[11].y); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(point[3].x, point[3].y); // Lower rectangle rlColor4ub(color.r, color.g, color.b, color.a); - rlTexCoord2f(texShapesRec.x/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(point[13].x, point[13].y); - rlTexCoord2f(texShapesRec.x/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(point[5].x, point[5].y); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(point[4].x, point[4].y); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(point[12].x, point[12].y); // Left rectangle rlColor4ub(color.r, color.g, color.b, color.a); - rlTexCoord2f(texShapesRec.x/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(point[15].x, point[15].y); - rlTexCoord2f(texShapesRec.x/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(point[7].x, point[7].y); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(point[6].x, point[6].y); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(point[14].x, point[14].y); rlEnd(); @@ -1314,21 +1335,22 @@ void DrawRectangleRoundedLines(Rectangle rec, float roundness, int segments, flo void DrawTriangle(Vector2 v1, Vector2 v2, Vector2 v3, Color color) { #if defined(SUPPORT_QUADS_DRAW_MODE) - rlSetTexture(texShapes.id); + rlSetTexture(GetShapesTexture().id); + Rectangle shapeRect = GetShapesTextureRectangle(); rlBegin(RL_QUADS); rlColor4ub(color.r, color.g, color.b, color.a); - rlTexCoord2f(texShapesRec.x/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(v1.x, v1.y); - rlTexCoord2f(texShapesRec.x/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(v2.x, v2.y); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(v2.x, v2.y); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(v3.x, v3.y); rlEnd(); @@ -1367,22 +1389,24 @@ void DrawTriangleFan(Vector2 *points, int pointCount, Color color) { if (pointCount >= 3) { - rlSetTexture(texShapes.id); + rlSetTexture(GetShapesTexture().id); + Rectangle shapeRect = GetShapesTextureRectangle(); + rlBegin(RL_QUADS); rlColor4ub(color.r, color.g, color.b, color.a); for (int i = 1; i < pointCount - 1; i++) { - rlTexCoord2f(texShapesRec.x/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(points[0].x, points[0].y); - rlTexCoord2f(texShapesRec.x/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(points[i].x, points[i].y); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(points[i + 1].x, points[i + 1].y); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(points[i + 1].x, points[i + 1].y); } rlEnd(); @@ -1426,7 +1450,8 @@ void DrawPoly(Vector2 center, int sides, float radius, float rotation, Color col float angleStep = 360.0f/(float)sides*DEG2RAD; #if defined(SUPPORT_QUADS_DRAW_MODE) - rlSetTexture(texShapes.id); + rlSetTexture(GetShapesTexture().id); + Rectangle shapeRect = GetShapesTextureRectangle(); rlBegin(RL_QUADS); for (int i = 0; i < sides; i++) @@ -1434,16 +1459,16 @@ void DrawPoly(Vector2 center, int sides, float radius, float rotation, Color col rlColor4ub(color.r, color.g, color.b, color.a); float nextAngle = centralAngle + angleStep; - rlTexCoord2f(texShapesRec.x/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(center.x, center.y); - rlTexCoord2f(texShapesRec.x/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(center.x + cosf(centralAngle)*radius, center.y + sinf(centralAngle)*radius); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(center.x + cosf(nextAngle)*radius, center.y + sinf(nextAngle)*radius); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(center.x + cosf(centralAngle)*radius, center.y + sinf(centralAngle)*radius); centralAngle = nextAngle; @@ -1494,7 +1519,8 @@ void DrawPolyLinesEx(Vector2 center, int sides, float radius, float rotation, fl float innerRadius = radius - (lineThick*cosf(DEG2RAD*exteriorAngle/2.0f)); #if defined(SUPPORT_QUADS_DRAW_MODE) - rlSetTexture(texShapes.id); + rlSetTexture(GetShapesTexture().id); + Rectangle shapeRect = GetShapesTextureRectangle(); rlBegin(RL_QUADS); for (int i = 0; i < sides; i++) @@ -1502,16 +1528,16 @@ void DrawPolyLinesEx(Vector2 center, int sides, float radius, float rotation, fl rlColor4ub(color.r, color.g, color.b, color.a); float nextAngle = centralAngle + exteriorAngle; - rlTexCoord2f(texShapesRec.x/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(center.x + cosf(centralAngle)*radius, center.y + sinf(centralAngle)*radius); - rlTexCoord2f(texShapesRec.x/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f(shapeRect.x/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(center.x + cosf(centralAngle)*innerRadius, center.y + sinf(centralAngle)*innerRadius); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, (texShapesRec.y + texShapesRec.height)/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, (shapeRect.y + shapeRect.height)/texShapes.height); rlVertex2f(center.x + cosf(nextAngle)*innerRadius, center.y + sinf(nextAngle)*innerRadius); - rlTexCoord2f((texShapesRec.x + texShapesRec.width)/texShapes.width, texShapesRec.y/texShapes.height); + rlTexCoord2f((shapeRect.x + shapeRect.width)/texShapes.width, shapeRect.y/texShapes.height); rlVertex2f(center.x + cosf(nextAngle)*radius, center.y + sinf(nextAngle)*radius); centralAngle = nextAngle; @@ -1546,10 +1572,96 @@ void DrawPolyLinesEx(Vector2 center, int sides, float radius, float rotation, fl // Draw spline: linear, minimum 2 points void DrawSplineLinear(Vector2 *points, int pointCount, float thick, Color color) { + if (pointCount < 2) return; + +#if defined(SUPPORT_SPLINE_MITERS) + Vector2 prevNormal = (Vector2){-(points[1].y - points[0].y), (points[1].x - points[0].x)}; + float prevLength = sqrtf(prevNormal.x*prevNormal.x + prevNormal.y*prevNormal.y); + + if (prevLength > 0.0f) + { + prevNormal.x /= prevLength; + prevNormal.y /= prevLength; + } + else + { + prevNormal.x = 0.0f; + prevNormal.y = 0.0f; + } + + Vector2 prevRadius = { 0.5f*thick*prevNormal.x, 0.5f*thick*prevNormal.y }; + + for (int i = 0; i < pointCount - 1; i++) + { + Vector2 normal = { 0 }; + + if (i < pointCount - 2) + { + normal = (Vector2){-(points[i + 2].y - points[i + 1].y), (points[i + 2].x - points[i + 1].x)}; + float normalLength = sqrtf(normal.x*normal.x + normal.y*normal.y); + + if (normalLength > 0.0f) + { + normal.x /= normalLength; + normal.y /= normalLength; + } + else + { + normal.x = 0.0f; + normal.y = 0.0f; + } + } + else + { + normal = prevNormal; + } + + Vector2 radius = { prevNormal.x + normal.x, prevNormal.y + normal.y }; + float radiusLength = sqrtf(radius.x*radius.x + radius.y*radius.y); + + if (radiusLength > 0.0f) + { + radius.x /= radiusLength; + radius.y /= radiusLength; + } + else + { + radius.x = 0.0f; + radius.y = 0.0f; + } + + float cosTheta = radius.x*normal.x + radius.y*normal.y; + + if (cosTheta != 0.0f) + { + radius.x *= (thick*0.5f/cosTheta); + radius.y *= (thick*0.5f/cosTheta); + } + else + { + radius.x = 0.0f; + radius.y = 0.0f; + } + + Vector2 strip[4] = { + { points[i].x - prevRadius.x, points[i].y - prevRadius.y }, + { points[i].x + prevRadius.x, points[i].y + prevRadius.y }, + { points[i + 1].x - radius.x, points[i + 1].y - radius.y }, + { points[i + 1].x + radius.x, points[i + 1].y + radius.y } + }; + + DrawTriangleStrip(strip, 4, color); + + prevRadius = radius; + prevNormal = normal; + } + +#else // !SUPPORT_SPLINE_MITTERS + Vector2 delta = { 0 }; float length = 0.0f; float scale = 0.0f; - + for (int i = 0; i < pointCount - 1; i++) { delta = (Vector2){ points[i + 1].x - points[i].x, points[i + 1].y - points[i].y }; @@ -1567,8 +1679,10 @@ void DrawSplineLinear(Vector2 *points, int pointCount, float thick, Color color) DrawTriangleStrip(strip, 4, color); } +#endif + #if defined(SUPPORT_SPLINE_SEGMENT_CAPS) - + // TODO: Add spline segment rounded caps at the begin/end of the spline #endif } @@ -1718,7 +1832,7 @@ void DrawSplineCatmullRom(Vector2 *points, int pointCount, float thick, Color co void DrawSplineBezierQuadratic(Vector2 *points, int pointCount, float thick, Color color) { if (pointCount < 3) return; - + for (int i = 0; i < pointCount - 2; i++) { DrawSplineSegmentBezierQuadratic(points[i], points[i + 1], points[i + 2], thick, color); @@ -1729,7 +1843,7 @@ void DrawSplineBezierQuadratic(Vector2 *points, int pointCount, float thick, Col void DrawSplineBezierCubic(Vector2 *points, int pointCount, float thick, Color color) { if (pointCount < 4) return; - + for (int i = 0; i < pointCount - 3; i++) { DrawSplineSegmentBezierCubic(points[i], points[i + 1], points[i + 2], points[i + 3], thick, color); @@ -1740,7 +1854,7 @@ void DrawSplineBezierCubic(Vector2 *points, int pointCount, float thick, Color c void DrawSplineSegmentLinear(Vector2 p1, Vector2 p2, float thick, Color color) { // NOTE: For the linear spline we don't use subdivisions, just a single quad - + Vector2 delta = { p2.x - p1.x, p2.y - p1.y }; float length = sqrtf(delta.x*delta.x + delta.y*delta.y); @@ -1768,9 +1882,9 @@ void DrawSplineSegmentBasis(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4, floa Vector2 currentPoint = { 0 }; Vector2 nextPoint = { 0 }; float t = 0.0f; - + Vector2 points[2*SPLINE_SEGMENT_DIVISIONS + 2] = { 0 }; - + float a[4] = { 0 }; float b[4] = { 0 }; @@ -1825,7 +1939,7 @@ void DrawSplineSegmentCatmullRom(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4, Vector2 currentPoint = p1; Vector2 nextPoint = { 0 }; float t = 0.0f; - + Vector2 points[2*SPLINE_SEGMENT_DIVISIONS + 2] = { 0 }; for (int i = 0; i <= SPLINE_SEGMENT_DIVISIONS; i++) @@ -2083,21 +2197,21 @@ bool CheckCollisionPointTriangle(Vector2 point, Vector2 p1, Vector2 p2, Vector2 // NOTE: Based on http://jeffreythompson.org/collision-detection/poly-point.php bool CheckCollisionPointPoly(Vector2 point, Vector2 *points, int pointCount) { - bool collision = false; + bool inside = false; if (pointCount > 2) { - for (int i = 0; i < pointCount - 1; i++) + for (int i = 0, j = pointCount - 1; i < pointCount; j = i++) { - Vector2 vc = points[i]; - Vector2 vn = points[i + 1]; - - if ((((vc.y >= point.y) && (vn.y < point.y)) || ((vc.y < point.y) && (vn.y >= point.y))) && - (point.x < ((vn.x - vc.x)*(point.y - vc.y)/(vn.y - vc.y) + vc.x))) collision = !collision; + if ((points[i].y > point.y) != (points[j].y > point.y) && + (point.x < (points[j].x - points[i].x)*(point.y - points[i].y)/(points[j].y - points[i].y) + points[i].x)) + { + inside = !inside; + } } } - return collision; + return inside; } // Check collision between two rectangles @@ -2132,11 +2246,11 @@ bool CheckCollisionCircleRec(Vector2 center, float radius, Rectangle rec) { bool collision = false; - int recCenterX = (int)(rec.x + rec.width/2.0f); - int recCenterY = (int)(rec.y + rec.height/2.0f); + float recCenterX = rec.x + rec.width/2.0f; + float recCenterY = rec.y + rec.height/2.0f; - float dx = fabsf(center.x - (float)recCenterX); - float dy = fabsf(center.y - (float)recCenterY); + float dx = fabsf(center.x - recCenterX); + float dy = fabsf(center.y - recCenterY); if (dx > (rec.width/2.0f + radius)) { return false; } if (dy > (rec.height/2.0f + radius)) { return false; } @@ -2234,11 +2348,16 @@ Rectangle GetCollisionRec(Rectangle rec1, Rectangle rec2) // NOTE: Used by DrawLineBezier() only static float EaseCubicInOut(float t, float b, float c, float d) { - if ((t /= 0.5f*d) < 1) return 0.5f*c*t*t*t + b; + float result = 0.0f; - t -= 2; + if ((t /= 0.5f*d) < 1) result = 0.5f*c*t*t*t + b; + else + { + t -= 2; + result = 0.5f*c*(t*t*t + 2.0f) + b; + } - return 0.5f*c*(t*t*t + 2.0f) + b; + return result; } #endif // SUPPORT_MODULE_RSHAPES diff --git a/raylib/rshapes.go b/raylib/rshapes.go index 25fb1b7..2e2e18f 100644 --- a/raylib/rshapes.go +++ b/raylib/rshapes.go @@ -276,9 +276,8 @@ func DrawRectangleRoundedLines(rec Rectangle, roundness float32, segments, lineT crec := rec.cptr() croundness := (C.float)(roundness) csegments := (C.int)(segments) - clineThick := (C.float)(lineThick) ccolor := colorCptr(col) - C.DrawRectangleRoundedLines(*crec, croundness, csegments, clineThick, *ccolor) + C.DrawRectangleRoundedLines(*crec, croundness, csegments, *ccolor) } // DrawTriangle - Draw a color-filled triangle diff --git a/raylib/rtext.c b/raylib/rtext.c index dd7c83f..b5ba17e 100644 --- a/raylib/rtext.c +++ b/raylib/rtext.c @@ -12,6 +12,7 @@ * * #define SUPPORT_FILEFORMAT_FNT * #define SUPPORT_FILEFORMAT_TTF +* #define SUPPORT_FILEFORMAT_BDF * Selected desired fileformats to be supported for loading. Some of those formats are * supported by default, to remove support, just comment unrequired #define in this module * @@ -33,7 +34,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2013-2023 Ramon Santamaria (@raysan5) +* Copyright (c) 2013-2024 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. @@ -70,14 +71,27 @@ #include // Required for: va_list, va_start(), vsprintf(), va_end() [Used in TextFormat()] #include // Required for: toupper(), tolower() [Used in TextToUpper(), TextToLower()] -#if defined(SUPPORT_FILEFORMAT_TTF) +#if defined(SUPPORT_FILEFORMAT_TTF) || defined(SUPPORT_FILEFORMAT_BDF) #if defined(__GNUC__) // GCC and Clang #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-function" #endif #define STB_RECT_PACK_IMPLEMENTATION - #include "external/stb_rect_pack.h" // Required for: ttf font rectangles packaging + #include "external/stb_rect_pack.h" // Required for: ttf/bdf font rectangles packaging + + #include // Required for: ttf/bdf font rectangles packaging + + #if defined(__GNUC__) // GCC and Clang + #pragma GCC diagnostic pop + #endif +#endif + +#if defined(SUPPORT_FILEFORMAT_TTF) + #if defined(__GNUC__) // GCC and Clang + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wunused-function" + #endif #define STBTT_STATIC #define STB_TRUETYPE_IMPLEMENTATION @@ -105,7 +119,7 @@ //---------------------------------------------------------------------------------- // Types and Structures Definition //---------------------------------------------------------------------------------- -// ... +//... //---------------------------------------------------------------------------------- // Global variables @@ -127,7 +141,10 @@ static Font defaultFont = { 0 }; #if defined(SUPPORT_FILEFORMAT_FNT) static Font LoadBMFont(const char *fileName); // Load a BMFont file (AngelCode font file) #endif -static int textLineSpacing = 15; // Text vertical line spacing in pixels +#if defined(SUPPORT_FILEFORMAT_BDF) +static GlyphInfo *LoadFontDataBDF(const unsigned char *fileData, int dataSize, int *codepoints, int codepointCount, int *outFontSize); +#endif +static int textLineSpacing = 2; // Text vertical line spacing in pixels (between lines) #if defined(SUPPORT_DEFAULT_FONT) extern void LoadFontDefault(void); @@ -334,6 +351,10 @@ Font LoadFont(const char *fileName) #if defined(SUPPORT_FILEFORMAT_FNT) if (IsFileExtension(fileName, ".fnt")) font = LoadBMFont(fileName); else +#endif +#if defined(SUPPORT_FILEFORMAT_BDF) + if (IsFileExtension(fileName, ".bdf")) font = LoadFontEx(fileName, FONT_TTF_DEFAULT_SIZE, NULL, FONT_TTF_DEFAULT_NUMCHARS); + else #endif { Image image = LoadImage(fileName); @@ -355,7 +376,7 @@ Font LoadFont(const char *fileName) return font; } -// Load Font from TTF font file with generation parameters +// Load Font from TTF or BDF font file with generation parameters // NOTE: You can pass an array with desired characters, those characters should be available in the font // if array is NULL, default char set is selected 32..126 Font LoadFontEx(const char *fileName, int fontSize, int *codepoints, int codepointCount) @@ -413,7 +434,7 @@ Font LoadFontFromImage(Image image, Color key, int firstChar) if (!COLOR_EQUAL(pixels[y*image.width + x], key)) break; } - if ((x == 0) || (y == 0)) return font; + if ((x == 0) || (y == 0)) return font; // Security check charSpacing = x; lineSpacing = y; @@ -509,37 +530,51 @@ Font LoadFontFromMemory(const char *fileType, const unsigned char *fileData, int Font font = { 0 }; char fileExtLower[16] = { 0 }; - strcpy(fileExtLower, TextToLower(fileType)); + strncpy(fileExtLower, TextToLower(fileType), 16 - 1); + + font.baseSize = fontSize; + font.glyphCount = (codepointCount > 0)? codepointCount : 95; + font.glyphPadding = 0; #if defined(SUPPORT_FILEFORMAT_TTF) if (TextIsEqual(fileExtLower, ".ttf") || TextIsEqual(fileExtLower, ".otf")) { - font.baseSize = fontSize; - font.glyphCount = (codepointCount > 0)? codepointCount : 95; - font.glyphPadding = 0; font.glyphs = LoadFontData(fileData, dataSize, font.baseSize, codepoints, font.glyphCount, FONT_DEFAULT); - - if (font.glyphs != NULL) - { - font.glyphPadding = FONT_TTF_DEFAULT_CHARS_PADDING; - - Image atlas = GenImageFontAtlas(font.glyphs, &font.recs, font.glyphCount, font.baseSize, font.glyphPadding, 0); - font.texture = LoadTextureFromImage(atlas); - - // Update glyphs[i].image to use alpha, required to be used on ImageDrawText() - for (int i = 0; i < font.glyphCount; i++) - { - UnloadImage(font.glyphs[i].image); - font.glyphs[i].image = ImageFromImage(atlas, font.recs[i]); - } - - UnloadImage(atlas); - - TRACELOG(LOG_INFO, "FONT: Data loaded successfully (%i pixel size | %i glyphs)", font.baseSize, font.glyphCount); - } - else font = GetFontDefault(); } + else +#endif +#if defined(SUPPORT_FILEFORMAT_BDF) + if (TextIsEqual(fileExtLower, ".bdf")) + { + font.glyphs = LoadFontDataBDF(fileData, dataSize, codepoints, font.glyphCount, &font.baseSize); + } + else +#endif + { + font.glyphs = NULL; + } + +#if defined(SUPPORT_FILEFORMAT_TTF) || defined(SUPPORT_FILEFORMAT_BDF) + if (font.glyphs != NULL) + { + font.glyphPadding = FONT_TTF_DEFAULT_CHARS_PADDING; + + Image atlas = GenImageFontAtlas(font.glyphs, &font.recs, font.glyphCount, font.baseSize, font.glyphPadding, 0); + font.texture = LoadTextureFromImage(atlas); + + // Update glyphs[i].image to use alpha, required to be used on ImageDrawText() + for (int i = 0; i < font.glyphCount; i++) + { + UnloadImage(font.glyphs[i].image); + font.glyphs[i].image = ImageFromImage(atlas, font.recs[i]); + } + + UnloadImage(atlas); + + TRACELOG(LOG_INFO, "FONT: Data loaded successfully (%i pixel size | %i glyphs)", font.baseSize, font.glyphCount); + } + else font = GetFontDefault(); #else font = GetFontDefault(); #endif @@ -604,7 +639,6 @@ GlyphInfo *LoadFontData(const unsigned char *fileData, int dataSize, int fontSiz // Fill fontChars in case not provided externally // NOTE: By default we fill glyphCount consecutively, starting at 32 (Space) - if (codepoints == NULL) { codepoints = (int *)RL_MALLOC(codepointCount*sizeof(int)); @@ -612,7 +646,7 @@ GlyphInfo *LoadFontData(const unsigned char *fileData, int dataSize, int fontSiz genFontChars = true; } - chars = (GlyphInfo *)RL_MALLOC(codepointCount*sizeof(GlyphInfo)); + chars = (GlyphInfo *)RL_CALLOC(codepointCount, sizeof(GlyphInfo)); // NOTE: Using simple packaging, one char after another for (int i = 0; i < codepointCount; i++) @@ -626,54 +660,67 @@ GlyphInfo *LoadFontData(const unsigned char *fileData, int dataSize, int fontSiz // stbtt_GetCodepointBitmapBox() -- how big the bitmap must be // stbtt_MakeCodepointBitmap() -- renders into bitmap you provide - if (type != FONT_SDF) chars[i].image.data = stbtt_GetCodepointBitmap(&fontInfo, scaleFactor, scaleFactor, ch, &chw, &chh, &chars[i].offsetX, &chars[i].offsetY); - else if (ch != 32) chars[i].image.data = stbtt_GetCodepointSDF(&fontInfo, scaleFactor, ch, FONT_SDF_CHAR_PADDING, FONT_SDF_ON_EDGE_VALUE, FONT_SDF_PIXEL_DIST_SCALE, &chw, &chh, &chars[i].offsetX, &chars[i].offsetY); - else chars[i].image.data = NULL; + // Check if a glyph is available in the font + // WARNING: if (index == 0), glyph not found, it could fallback to default .notdef glyph (if defined in font) + int index = stbtt_FindGlyphIndex(&fontInfo, ch); - stbtt_GetCodepointHMetrics(&fontInfo, ch, &chars[i].advanceX, NULL); - chars[i].advanceX = (int)((float)chars[i].advanceX*scaleFactor); - - // Load characters images - chars[i].image.width = chw; - chars[i].image.height = chh; - chars[i].image.mipmaps = 1; - chars[i].image.format = PIXELFORMAT_UNCOMPRESSED_GRAYSCALE; - - chars[i].offsetY += (int)((float)ascent*scaleFactor); - - // NOTE: We create an empty image for space character, it could be further required for atlas packing - if (ch == 32) + if (index > 0) { - Image imSpace = { - .data = RL_CALLOC(chars[i].advanceX*fontSize, 2), - .width = chars[i].advanceX, - .height = fontSize, - .mipmaps = 1, - .format = PIXELFORMAT_UNCOMPRESSED_GRAYSCALE - }; - - chars[i].image = imSpace; - } - - if (type == FONT_BITMAP) - { - // Aliased bitmap (black & white) font generation, avoiding anti-aliasing - // NOTE: For optimum results, bitmap font should be generated at base pixel size - for (int p = 0; p < chw*chh; p++) + switch (type) { - if (((unsigned char *)chars[i].image.data)[p] < FONT_BITMAP_ALPHA_THRESHOLD) ((unsigned char *)chars[i].image.data)[p] = 0; - else ((unsigned char *)chars[i].image.data)[p] = 255; + case FONT_DEFAULT: + case FONT_BITMAP: chars[i].image.data = stbtt_GetCodepointBitmap(&fontInfo, scaleFactor, scaleFactor, ch, &chw, &chh, &chars[i].offsetX, &chars[i].offsetY); break; + case FONT_SDF: if (ch != 32) chars[i].image.data = stbtt_GetCodepointSDF(&fontInfo, scaleFactor, ch, FONT_SDF_CHAR_PADDING, FONT_SDF_ON_EDGE_VALUE, FONT_SDF_PIXEL_DIST_SCALE, &chw, &chh, &chars[i].offsetX, &chars[i].offsetY); break; + default: break; + } + + if (chars[i].image.data != NULL) // Glyph data has been found in the font + { + stbtt_GetCodepointHMetrics(&fontInfo, ch, &chars[i].advanceX, NULL); + chars[i].advanceX = (int)((float)chars[i].advanceX*scaleFactor); + + // Load characters images + chars[i].image.width = chw; + chars[i].image.height = chh; + chars[i].image.mipmaps = 1; + chars[i].image.format = PIXELFORMAT_UNCOMPRESSED_GRAYSCALE; + + chars[i].offsetY += (int)((float)ascent*scaleFactor); + } + + // NOTE: We create an empty image for space character, + // it could be further required for atlas packing + if (ch == 32) + { + stbtt_GetCodepointHMetrics(&fontInfo, ch, &chars[i].advanceX, NULL); + chars[i].advanceX = (int)((float)chars[i].advanceX*scaleFactor); + + Image imSpace = { + .data = RL_CALLOC(chars[i].advanceX*fontSize, 2), + .width = chars[i].advanceX, + .height = fontSize, + .mipmaps = 1, + .format = PIXELFORMAT_UNCOMPRESSED_GRAYSCALE + }; + + chars[i].image = imSpace; + } + + if (type == FONT_BITMAP) + { + // Aliased bitmap (black & white) font generation, avoiding anti-aliasing + // NOTE: For optimum results, bitmap font should be generated at base pixel size + for (int p = 0; p < chw*chh; p++) + { + if (((unsigned char *)chars[i].image.data)[p] < FONT_BITMAP_ALPHA_THRESHOLD) ((unsigned char *)chars[i].image.data)[p] = 0; + else ((unsigned char *)chars[i].image.data)[p] = 255; + } } } - - // Get bounding box for character (maybe offset to account for chars that dip above or below the line) - /* - int chX1, chY1, chX2, chY2; - stbtt_GetCodepointBitmapBox(&fontInfo, ch, scaleFactor, scaleFactor, &chX1, &chY1, &chX2, &chY2); - - TRACELOGD("FONT: Character box measures: %i, %i, %i, %i", chX1, chY1, chX2 - chX1, chY2 - chY1); - TRACELOGD("FONT: Character offsetY: %i", (int)((float)ascent*scaleFactor) + chY1); - */ + else + { + // TODO: Use some fallback glyph for codepoints not found in the font + } } } else TRACELOG(LOG_WARNING, "FONT: Failed to process TTF font data"); @@ -687,7 +734,7 @@ GlyphInfo *LoadFontData(const unsigned char *fileData, int dataSize, int fontSiz // Generate image font atlas using chars info // NOTE: Packing method: 0-Default, 1-Skyline -#if defined(SUPPORT_FILEFORMAT_TTF) +#if defined(SUPPORT_FILEFORMAT_TTF) || defined(SUPPORT_FILEFORMAT_BDF) Image GenImageFontAtlas(const GlyphInfo *glyphs, Rectangle **glyphRecs, int glyphCount, int fontSize, int padding, int packMethod) { Image atlas = { 0 }; @@ -713,7 +760,7 @@ Image GenImageFontAtlas(const GlyphInfo *glyphs, Rectangle **glyphRecs, int glyp for (int i = 0; i < glyphCount; i++) { if (glyphs[i].image.width > maxGlyphWidth) maxGlyphWidth = glyphs[i].image.width; - totalWidth += glyphs[i].image.width + 4*padding; + totalWidth += glyphs[i].image.width + 2*padding; } //#define SUPPORT_FONT_ATLAS_SIZE_CONSERVATIVE @@ -731,8 +778,9 @@ Image GenImageFontAtlas(const GlyphInfo *glyphs, Rectangle **glyphRecs, int glyp atlas.width = imageSize; // Atlas bitmap width atlas.height = imageSize; // Atlas bitmap height #else + int paddedFontSize = fontSize + 2*padding; // No need for a so-conservative atlas generation - float totalArea = totalWidth*fontSize*1.2f; + float totalArea = totalWidth*paddedFontSize*1.2f; float imageMinSize = sqrtf(totalArea); int imageSize = (int)powf(2, ceilf(logf(imageMinSize)/logf(2))); @@ -775,10 +823,10 @@ Image GenImageFontAtlas(const GlyphInfo *glyphs, Rectangle **glyphRecs, int glyp if (offsetY > (atlas.height - fontSize - padding)) { - for(int j = i + 1; j < glyphCount; j++) + for (int j = i + 1; j < glyphCount; j++) { TRACELOG(LOG_WARNING, "FONT: Failed to package character (%i)", j); - // make sure remaining recs contain valid data + // Make sure remaining recs contain valid data recs[j].x = 0; recs[j].y = 0; recs[j].width = 0; @@ -923,7 +971,7 @@ bool ExportFontAsCode(Font font, const char *fileName) // Get file name from path char fileNamePascal[256] = { 0 }; - strcpy(fileNamePascal, TextToPascal(GetFileNameWithoutExt(fileName))); + strncpy(fileNamePascal, TextToPascal(GetFileNameWithoutExt(fileName)), 256 - 1); // NOTE: Text data buffer size is estimated considering image data size in bytes // and requiring 6 char bytes for every byte: "0x00, " @@ -937,7 +985,7 @@ bool ExportFontAsCode(Font font, const char *fileName) byteCount += sprintf(txtData + byteCount, "// more info and bugs-report: github.com/raysan5/raylib //\n"); byteCount += sprintf(txtData + byteCount, "// feedback and support: ray[at]raylib.com //\n"); byteCount += sprintf(txtData + byteCount, "// //\n"); - byteCount += sprintf(txtData + byteCount, "// Copyright (c) 2018-2023 Ramon Santamaria (@raysan5) //\n"); + byteCount += sprintf(txtData + byteCount, "// Copyright (c) 2018-2024 Ramon Santamaria (@raysan5) //\n"); byteCount += sprintf(txtData + byteCount, "// //\n"); byteCount += sprintf(txtData + byteCount, "// ---------------------------------------------------------------------------------- //\n"); byteCount += sprintf(txtData + byteCount, "// //\n"); @@ -1029,7 +1077,7 @@ bool ExportFontAsCode(Font font, const char *fileName) #endif // We have two possible mechanisms to assign font.recs and font.glyphs data, // that data is already available as global arrays, we two options to assign that data: - // - 1. Data copy. This option consumes more memory and Font MUST be unloaded by user, requiring additional code. + // - 1. Data copy. This option consumes more memory and Font MUST be unloaded by user, requiring additional code // - 2. Data assignment. This option consumes less memory and Font MUST NOT be unloaded by user because data is on protected DATA segment //#define SUPPORT_FONT_DATA_COPY #if defined(SUPPORT_FONT_DATA_COPY) @@ -1064,7 +1112,6 @@ bool ExportFontAsCode(Font font, const char *fileName) return success; } - // Draw current FPS // NOTE: Uses default font void DrawFPS(int posX, int posY) @@ -1104,7 +1151,7 @@ void DrawTextEx(Font font, const char *text, Vector2 position, float fontSize, f int size = TextLength(text); // Total size in bytes of the text, scanned by codepoints in loop - int textOffsetY = 0; // Offset between lines (on linebreak '\n') + float textOffsetY = 0; // Offset between lines (on linebreak '\n') float textOffsetX = 0.0f; // Offset X to next character to draw float scaleFactor = fontSize/font.baseSize; // Character quad scaling factor @@ -1119,7 +1166,7 @@ void DrawTextEx(Font font, const char *text, Vector2 position, float fontSize, f if (codepoint == '\n') { // NOTE: Line spacing is a global variable, use SetTextLineSpacing() to setup - textOffsetY += textLineSpacing; + textOffsetY += (fontSize + textLineSpacing); textOffsetX = 0.0f; } else @@ -1178,7 +1225,7 @@ void DrawTextCodepoint(Font font, int codepoint, Vector2 position, float fontSiz // Draw multiple character (codepoints) void DrawTextCodepoints(Font font, const int *codepoints, int codepointCount, Vector2 position, float fontSize, float spacing, Color tint) { - int textOffsetY = 0; // Offset between lines (on linebreak '\n') + float textOffsetY = 0; // Offset between lines (on linebreak '\n') float textOffsetX = 0.0f; // Offset X to next character to draw float scaleFactor = fontSize/font.baseSize; // Character quad scaling factor @@ -1190,7 +1237,7 @@ void DrawTextCodepoints(Font font, const int *codepoints, int codepointCount, Ve if (codepoints[i] == '\n') { // NOTE: Line spacing is a global variable, use SetTextLineSpacing() to setup - textOffsetY += textLineSpacing; + textOffsetY += (fontSize + textLineSpacing); textOffsetX = 0.0f; } else @@ -1235,7 +1282,7 @@ Vector2 MeasureTextEx(Font font, const char *text, float fontSize, float spacing { Vector2 textSize = { 0 }; - if ((font.texture.id == 0) || (text == NULL)) return textSize; + if ((font.texture.id == 0) || (text == NULL)) return textSize; // Security check int size = TextLength(text); // Get size in bytes of text int tempByteCounter = 0; // Used to count longer text line num chars @@ -1244,7 +1291,7 @@ Vector2 MeasureTextEx(Font font, const char *text, float fontSize, float spacing float textWidth = 0.0f; float tempTextWidth = 0.0f; // Used to count longer text line width - float textHeight = (float)font.baseSize; + float textHeight = fontSize; float scaleFactor = fontSize/(float)font.baseSize; int letter = 0; // Current character @@ -1272,7 +1319,7 @@ Vector2 MeasureTextEx(Font font, const char *text, float fontSize, float spacing textWidth = 0; // NOTE: Line spacing is a global variable, use SetTextLineSpacing() to setup - textHeight += (float)textLineSpacing; + textHeight += (fontSize + textLineSpacing); } if (tempByteCounter < byteCounter) tempByteCounter = byteCounter; @@ -1281,7 +1328,7 @@ Vector2 MeasureTextEx(Font font, const char *text, float fontSize, float spacing if (tempTextWidth < textWidth) tempTextWidth = textWidth; textSize.x = tempTextWidth*scaleFactor + (float)((tempByteCounter - 1)*spacing); - textSize.y = textHeight*scaleFactor; + textSize.y = textHeight; return textSize; } @@ -1390,7 +1437,6 @@ const char *TextFormat(const char *text, ...) return currentBuffer; } - // Get integer value from text // NOTE: This function replaces atoi() [stdlib.h] int TextToInteger(const char *text) @@ -1409,6 +1455,37 @@ int TextToInteger(const char *text) return value*sign; } +// Get float value from text +// NOTE: This function replaces atof() [stdlib.h] +// WARNING: Only '.' character is understood as decimal point +float TextToFloat(const char *text) +{ + float value = 0.0f; + float sign = 1.0f; + + if ((text[0] == '+') || (text[0] == '-')) + { + if (text[0] == '-') sign = -1.0f; + text++; + } + + int i = 0; + for (; ((text[i] >= '0') && (text[i] <= '9')); i++) value = value*10.0f + (float)(text[i] - '0'); + + if (text[i++] != '.') value *= sign; + else + { + float divisor = 10.0f; + for (; ((text[i] >= '0') && (text[i] <= '9')); i++) + { + value += ((float)(text[i] - '0'))/divisor; + divisor = divisor*10.0f; + } + } + + return value; +} + #if defined(SUPPORT_TEXT_MANIPULATION) // Copy one string to another, returns bytes copied int TextCopy(char *dst, const char *src) @@ -1480,7 +1557,7 @@ const char *TextSubtext(const char *text, int position, int length) // Replace text string // REQUIRES: strlen(), strstr(), strncpy(), strcpy() // WARNING: Allocated memory must be manually freed -char *TextReplace(char *text, const char *replace, const char *by) +char *TextReplace(const char *text, const char *replace, const char *by) { // Sanity checks and initialization if (!text || !replace || !by) return NULL; @@ -1500,7 +1577,7 @@ char *TextReplace(char *text, const char *replace, const char *by) byLen = TextLength(by); // Count the number of replacements needed - insertPoint = text; + insertPoint = (char*)text; for (count = 0; (temp = strstr(insertPoint, replace)); count++) insertPoint = temp + replaceLen; // Allocate returning string and point temp to it @@ -1620,7 +1697,8 @@ const char **TextSplit(const char *text, char delimiter, int *count) return result; } -// Append text at specific position and move cursor! +// Append text at specific position and move cursor +// WARNING: It's up to the user to make sure appended text does not overflow the buffer! // REQUIRES: strcpy() void TextAppend(char *text, const char *append, int *position) { @@ -1951,21 +2029,21 @@ int GetCodepointNext(const char *text, int *codepointSize) if (0xf0 == (0xf8 & ptr[0])) { // 4 byte UTF-8 codepoint - if(((ptr[1] & 0xC0) ^ 0x80) || ((ptr[2] & 0xC0) ^ 0x80) || ((ptr[3] & 0xC0) ^ 0x80)) { return codepoint; } //10xxxxxx checks + if (((ptr[1] & 0xC0) ^ 0x80) || ((ptr[2] & 0xC0) ^ 0x80) || ((ptr[3] & 0xC0) ^ 0x80)) { return codepoint; } // 10xxxxxx checks codepoint = ((0x07 & ptr[0]) << 18) | ((0x3f & ptr[1]) << 12) | ((0x3f & ptr[2]) << 6) | (0x3f & ptr[3]); *codepointSize = 4; } else if (0xe0 == (0xf0 & ptr[0])) { // 3 byte UTF-8 codepoint */ - if(((ptr[1] & 0xC0) ^ 0x80) || ((ptr[2] & 0xC0) ^ 0x80)) { return codepoint; } //10xxxxxx checks + if (((ptr[1] & 0xC0) ^ 0x80) || ((ptr[2] & 0xC0) ^ 0x80)) { return codepoint; } // 10xxxxxx checks codepoint = ((0x0f & ptr[0]) << 12) | ((0x3f & ptr[1]) << 6) | (0x3f & ptr[2]); *codepointSize = 3; } else if (0xc0 == (0xe0 & ptr[0])) { // 2 byte UTF-8 codepoint - if((ptr[1] & 0xC0) ^ 0x80) { return codepoint; } //10xxxxxx checks + if ((ptr[1] & 0xC0) ^ 0x80) { return codepoint; } // 10xxxxxx checks codepoint = ((0x1f & ptr[0]) << 6) | (0x3f & ptr[1]); *codepointSize = 2; } @@ -2001,23 +2079,27 @@ int GetCodepointPrevious(const char *text, int *codepointSize) //---------------------------------------------------------------------------------- // Module specific Functions Definition //---------------------------------------------------------------------------------- -#if defined(SUPPORT_FILEFORMAT_FNT) +#if defined(SUPPORT_FILEFORMAT_FNT) || defined(SUPPORT_FILEFORMAT_BDF) // Read a line from memory // REQUIRES: memcpy() // NOTE: Returns the number of bytes read static int GetLine(const char *origin, char *buffer, int maxLength) { int count = 0; - for (; count < maxLength; count++) if (origin[count] == '\n') break; + for (; count < maxLength - 1; count++) if (origin[count] == '\n') break; memcpy(buffer, origin, count); + buffer[count] = '\0'; return count; } +#endif +#if defined(SUPPORT_FILEFORMAT_FNT) // Load a BMFont file (AngelCode font file) // REQUIRES: strstr(), sscanf(), strrchr(), memcpy() static Font LoadBMFont(const char *fileName) { - #define MAX_BUFFER_SIZE 256 + #define MAX_BUFFER_SIZE 256 + #define MAX_FONT_IMAGE_PAGES 8 Font font = { 0 }; @@ -2029,7 +2111,8 @@ static Font LoadBMFont(const char *fileName) int imWidth = 0; int imHeight = 0; - char imFileName[129] = { 0 }; + int pageCount = 1; + char imFileName[MAX_FONT_IMAGE_PAGES][129] = { 0 }; int base = 0; // Useless data int readBytes = 0; // Data bytes read @@ -2048,17 +2131,26 @@ static Font LoadBMFont(const char *fileName) // Read line data readBytes = GetLine(fileTextPtr, buffer, MAX_BUFFER_SIZE); searchPoint = strstr(buffer, "lineHeight"); - readVars = sscanf(searchPoint, "lineHeight=%i base=%i scaleW=%i scaleH=%i", &fontSize, &base, &imWidth, &imHeight); + readVars = sscanf(searchPoint, "lineHeight=%i base=%i scaleW=%i scaleH=%i pages=%i", &fontSize, &base, &imWidth, &imHeight, &pageCount); fileTextPtr += (readBytes + 1); - + if (readVars < 4) { UnloadFileText(fileText); return font; } // Some data not available, file malformed - readBytes = GetLine(fileTextPtr, buffer, MAX_BUFFER_SIZE); - searchPoint = strstr(buffer, "file"); - readVars = sscanf(searchPoint, "file=\"%128[^\"]\"", imFileName); - fileTextPtr += (readBytes + 1); + if (pageCount > MAX_FONT_IMAGE_PAGES) + { + TRACELOG(LOG_WARNING, "FONT: [%s] Font defines more pages than supported: %i/%i", fileName, pageCount, MAX_FONT_IMAGE_PAGES); + pageCount = MAX_FONT_IMAGE_PAGES; + } - if (readVars < 1) { UnloadFileText(fileText); return font; } // No fileName read + for (int i = 0; i < pageCount; i++) + { + readBytes = GetLine(fileTextPtr, buffer, MAX_BUFFER_SIZE); + searchPoint = strstr(buffer, "file"); + readVars = sscanf(searchPoint, "file=\"%128[^\"]\"", imFileName[i]); + fileTextPtr += (readBytes + 1); + + if (readVars < 1) { UnloadFileText(fileText); return font; } // No fileName read + } readBytes = GetLine(fileTextPtr, buffer, MAX_BUFFER_SIZE); searchPoint = strstr(buffer, "count"); @@ -2067,50 +2159,56 @@ static Font LoadBMFont(const char *fileName) if (readVars < 1) { UnloadFileText(fileText); return font; } // No glyphCount read - // Compose correct path using route of .fnt file (fileName) and imFileName - char *imPath = NULL; - char *lastSlash = NULL; + // Load all required images for further compose + Image *imFonts = (Image *)RL_CALLOC(pageCount, sizeof(Image)); // Font atlases, multiple images - lastSlash = strrchr(fileName, '/'); - if (lastSlash == NULL) lastSlash = strrchr(fileName, '\\'); - - if (lastSlash != NULL) + for (int i = 0; i < pageCount; i++) { - // NOTE: We need some extra space to avoid memory corruption on next allocations! - imPath = (char *)RL_CALLOC(TextLength(fileName) - TextLength(lastSlash) + TextLength(imFileName) + 4, 1); - memcpy(imPath, fileName, TextLength(fileName) - TextLength(lastSlash) + 1); - memcpy(imPath + TextLength(fileName) - TextLength(lastSlash) + 1, imFileName, TextLength(imFileName)); - } - else imPath = imFileName; + imFonts[i] = LoadImage(TextFormat("%s/%s", GetDirectoryPath(fileName), imFileName[i])); - TRACELOGD(" > Image loading path: %s", imPath); - - Image imFont = LoadImage(imPath); - - if (imFont.format == PIXELFORMAT_UNCOMPRESSED_GRAYSCALE) - { - // Convert image to GRAYSCALE + ALPHA, using the mask as the alpha channel - Image imFontAlpha = { - .data = RL_CALLOC(imFont.width*imFont.height, 2), - .width = imFont.width, - .height = imFont.height, - .mipmaps = 1, - .format = PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA - }; - - for (int p = 0, i = 0; p < (imFont.width*imFont.height*2); p += 2, i++) + if (imFonts[i].format == PIXELFORMAT_UNCOMPRESSED_GRAYSCALE) { - ((unsigned char *)(imFontAlpha.data))[p] = 0xff; - ((unsigned char *)(imFontAlpha.data))[p + 1] = ((unsigned char *)imFont.data)[i]; - } + // Convert image to GRAYSCALE + ALPHA, using the mask as the alpha channel + Image imFontAlpha = { + .data = RL_CALLOC(imFonts[i].width*imFonts[i].height, 2), + .width = imFonts[i].width, + .height = imFonts[i].height, + .mipmaps = 1, + .format = PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA + }; - UnloadImage(imFont); - imFont = imFontAlpha; + for (int p = 0, pi = 0; p < (imFonts[i].width*imFonts[i].height*2); p += 2, pi++) + { + ((unsigned char *)(imFontAlpha.data))[p] = 0xff; + ((unsigned char *)(imFontAlpha.data))[p + 1] = ((unsigned char *)imFonts[i].data)[pi]; + } + + UnloadImage(imFonts[i]); + imFonts[i] = imFontAlpha; + } } - font.texture = LoadTextureFromImage(imFont); + Image fullFont = imFonts[0]; + for (int i = 1; i < pageCount; i++) UnloadImage(imFonts[i]); - if (lastSlash != NULL) RL_FREE(imPath); + // If multiple atlas, then merge atlas + // NOTE: WARNING: This process could be really slow! + if (pageCount > 1) + { + // Resize font atlas to draw additional images + ImageResizeCanvas(&fullFont, imWidth, imHeight*pageCount, 0, 0, BLACK); + + for (int i = 1; i < pageCount; i++) + { + Rectangle srcRec = { 0.0f, 0.0f, (float)imWidth, (float)imHeight }; + Rectangle destRec = { 0.0f, (float)imHeight*(float)i, (float)imWidth, (float)imHeight }; + ImageDraw(&fullFont, imFonts[i], srcRec, destRec, WHITE); + } + } + + RL_FREE(imFonts); + + font.texture = LoadTextureFromImage(fullFont); // Fill font characters info data font.baseSize = fontSize; @@ -2119,19 +2217,19 @@ static Font LoadBMFont(const char *fileName) font.glyphs = (GlyphInfo *)RL_MALLOC(glyphCount*sizeof(GlyphInfo)); font.recs = (Rectangle *)RL_MALLOC(glyphCount*sizeof(Rectangle)); - int charId, charX, charY, charWidth, charHeight, charOffsetX, charOffsetY, charAdvanceX; + int charId, charX, charY, charWidth, charHeight, charOffsetX, charOffsetY, charAdvanceX, pageID; for (int i = 0; i < glyphCount; i++) { readBytes = GetLine(fileTextPtr, buffer, MAX_BUFFER_SIZE); - readVars = sscanf(buffer, "char id=%i x=%i y=%i width=%i height=%i xoffset=%i yoffset=%i xadvance=%i", - &charId, &charX, &charY, &charWidth, &charHeight, &charOffsetX, &charOffsetY, &charAdvanceX); + readVars = sscanf(buffer, "char id=%i x=%i y=%i width=%i height=%i xoffset=%i yoffset=%i xadvance=%i page=%i", + &charId, &charX, &charY, &charWidth, &charHeight, &charOffsetX, &charOffsetY, &charAdvanceX, &pageID); fileTextPtr += (readBytes + 1); - - if (readVars == 8) // Make sure all char data has been properly read + + if (readVars == 9) // Make sure all char data has been properly read { // Get character rectangle in the font atlas texture - font.recs[i] = (Rectangle){ (float)charX, (float)charY, (float)charWidth, (float)charHeight }; + font.recs[i] = (Rectangle){ (float)charX, (float)charY + (float)imHeight*pageID, (float)charWidth, (float)charHeight }; // Save data properly in sprite font font.glyphs[i].value = charId; @@ -2139,13 +2237,13 @@ static Font LoadBMFont(const char *fileName) font.glyphs[i].offsetY = charOffsetY; font.glyphs[i].advanceX = charAdvanceX; - // Fill character image data from imFont data - font.glyphs[i].image = ImageFromImage(imFont, font.recs[i]); + // Fill character image data from full font data + font.glyphs[i].image = ImageFromImage(fullFont, font.recs[i]); } else TRACELOG(LOG_WARNING, "FONT: [%s] Some characters data not correctly provided", fileName); } - UnloadImage(imFont); + UnloadImage(fullFont); UnloadFileText(fileText); if (font.texture.id == 0) @@ -2158,6 +2256,258 @@ static Font LoadBMFont(const char *fileName) return font; } + #endif +#if defined(SUPPORT_FILEFORMAT_BDF) + +// Convert hexadecimal to decimal (single digit) +static unsigned char HexToInt(char hex) +{ + if (hex >= '0' && hex <= '9') return hex - '0'; + else if (hex >= 'a' && hex <= 'f') return hex - 'a' + 10; + else if (hex >= 'A' && hex <= 'F') return hex - 'A' + 10; + else return 0; +} + +// Load font data for further use +// NOTE: Requires BDF font memory data +static GlyphInfo *LoadFontDataBDF(const unsigned char *fileData, int dataSize, int *codepoints, int codepointCount, int *outFontSize) +{ + #define MAX_BUFFER_SIZE 256 + + char buffer[MAX_BUFFER_SIZE] = { 0 }; + + GlyphInfo *glyphs = NULL; + bool genFontChars = false; + + int totalReadBytes = 0; // Data bytes read (total) + int readBytes = 0; // Data bytes read (line) + int readVars = 0; // Variables filled by sscanf() + + const char *fileText = (const char*)fileData; + const char *fileTextPtr = fileText; + + bool fontMalformed = false; // Is the font malformed + bool fontStarted = false; // Has font started (STARTFONT) + int fontBBw = 0; // Font base character bounding box width + int fontBBh = 0; // Font base character bounding box height + int fontBBxoff0 = 0; // Font base character bounding box X0 offset + int fontBByoff0 = 0; // Font base character bounding box Y0 offset + int fontAscent = 0; // Font ascent + + bool charStarted = false; // Has character started (STARTCHAR) + bool charBitmapStarted = false; // Has bitmap data started (BITMAP) + int charBitmapNextRow = 0; // Y position for the next row of bitmap data + int charEncoding = -1; // The unicode value of the character (-1 if not set) + int charBBw = 0; // Character bounding box width + int charBBh = 0; // Character bounding box height + int charBBxoff0 = 0; // Character bounding box X0 offset + int charBByoff0 = 0; // Character bounding box Y0 offset + int charDWidthX = 0; // Character advance X + int charDWidthY = 0; // Character advance Y (unused) + GlyphInfo *charGlyphInfo = NULL; // Pointer to output glyph info (NULL if not set) + + if (fileData == NULL) return glyphs; + + // In case no chars count provided, default to 95 + codepointCount = (codepointCount > 0)? codepointCount : 95; + + // Fill fontChars in case not provided externally + // NOTE: By default we fill glyphCount consecutively, starting at 32 (Space) + if (codepoints == NULL) + { + codepoints = (int *)RL_MALLOC(codepointCount*sizeof(int)); + for (int i = 0; i < codepointCount; i++) codepoints[i] = i + 32; + genFontChars = true; + } + + glyphs = (GlyphInfo *)RL_CALLOC(codepointCount, sizeof(GlyphInfo)); + + while (totalReadBytes <= dataSize) + { + readBytes = GetLine(fileTextPtr, buffer, MAX_BUFFER_SIZE); + totalReadBytes += (readBytes + 1); + fileTextPtr += (readBytes + 1); + + // Line: COMMENT + if (strstr(buffer, "COMMENT") != NULL) continue; // Ignore line + + if (charStarted) + { + // Line: ENDCHAR + if (strstr(buffer, "ENDCHAR") != NULL) + { + charStarted = false; + continue; + } + + if (charBitmapStarted) + { + if (charGlyphInfo != NULL) + { + int pixelY = charBitmapNextRow++; + + if (pixelY >= charGlyphInfo->image.height) break; + + for (int x = 0; x < readBytes; x++) + { + unsigned char byte = HexToInt(buffer[x]); + + for (int bitX = 0; bitX < 4; bitX++) + { + int pixelX = ((x*4) + bitX); + + if (pixelX >= charGlyphInfo->image.width) break; + + if ((byte & (8 >> bitX)) > 0) ((unsigned char *)charGlyphInfo->image.data)[(pixelY*charGlyphInfo->image.width) + pixelX] = 255; + } + } + } + continue; + } + + // Line: ENCODING + if (strstr(buffer, "ENCODING") != NULL) + { + readVars = sscanf(buffer, "ENCODING %i", &charEncoding); + continue; + } + + // Line: BBX + if (strstr(buffer, "BBX") != NULL) + { + readVars = sscanf(buffer, "BBX %i %i %i %i", &charBBw, &charBBh, &charBBxoff0, &charBByoff0); + continue; + } + + // Line: DWIDTH + if (strstr(buffer, "DWIDTH") != NULL) + { + readVars = sscanf(buffer, "DWIDTH %i %i", &charDWidthX, &charDWidthY); + continue; + } + + // Line: BITMAP + if (strstr(buffer, "BITMAP") != NULL) + { + // Search for glyph index in codepoints + charGlyphInfo = NULL; + + for (int codepointIndex = 0; codepointIndex < codepointCount; codepointIndex++) + { + if (codepoints[codepointIndex] == charEncoding) + { + charGlyphInfo = &glyphs[codepointIndex]; + break; + } + } + + // Init glyph info + if (charGlyphInfo != NULL) + { + charGlyphInfo->value = charEncoding; + charGlyphInfo->offsetX = charBBxoff0 + fontBByoff0; + charGlyphInfo->offsetY = fontBBh - (charBBh + charBByoff0 + fontBByoff0 + fontAscent); + charGlyphInfo->advanceX = charDWidthX; + + charGlyphInfo->image.data = RL_CALLOC(charBBw*charBBh, 1); + charGlyphInfo->image.width = charBBw; + charGlyphInfo->image.height = charBBh; + charGlyphInfo->image.mipmaps = 1; + charGlyphInfo->image.format = PIXELFORMAT_UNCOMPRESSED_GRAYSCALE; + } + + charBitmapStarted = true; + charBitmapNextRow = 0; + + continue; + } + } + else if (fontStarted) + { + // Line: ENDFONT + if (strstr(buffer, "ENDFONT") != NULL) + { + fontStarted = false; + break; + } + + // Line: SIZE + if (strstr(buffer, "SIZE") != NULL) + { + if (outFontSize != NULL) readVars = sscanf(buffer, "SIZE %i", outFontSize); + continue; + } + + // PIXEL_SIZE + if (strstr(buffer, "PIXEL_SIZE") != NULL) + { + if (outFontSize != NULL) readVars = sscanf(buffer, "PIXEL_SIZE %i", outFontSize); + continue; + } + + // FONTBOUNDINGBOX + if (strstr(buffer, "FONTBOUNDINGBOX") != NULL) + { + readVars = sscanf(buffer, "FONTBOUNDINGBOX %i %i %i %i", &fontBBw, &fontBBh, &fontBBxoff0, &fontBByoff0); + continue; + } + + // FONT_ASCENT + if (strstr(buffer, "FONT_ASCENT") != NULL) + { + readVars = sscanf(buffer, "FONT_ASCENT %i", &fontAscent); + continue; + } + + // STARTCHAR + if (strstr(buffer, "STARTCHAR") != NULL) + { + charStarted = true; + charEncoding = -1; + charGlyphInfo = NULL; + charBBw = 0; + charBBh = 0; + charBBxoff0 = 0; + charBByoff0 = 0; + charDWidthX = 0; + charDWidthY = 0; + charGlyphInfo = NULL; + charBitmapStarted = false; + charBitmapNextRow = 0; + continue; + } + } + else + { + // STARTFONT + if (strstr(buffer, "STARTFONT") != NULL) + { + if (fontStarted) + { + fontMalformed = true; + break; + } + else + { + fontStarted = true; + continue; + } + } + } + } + + if (genFontChars) RL_FREE(codepoints); + + if (fontMalformed) + { + RL_FREE(glyphs); + glyphs = NULL; + } + + return glyphs; +} +#endif // SUPPORT_FILEFORMAT_BDF + #endif // SUPPORT_MODULE_RTEXT diff --git a/raylib/rtextures.c b/raylib/rtextures.c index 98586db..47ff83f 100644 --- a/raylib/rtextures.c +++ b/raylib/rtextures.c @@ -42,7 +42,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2013-2023 Ramon Santamaria (@raysan5) +* Copyright (c) 2013-2024 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. @@ -71,10 +71,10 @@ #if defined(SUPPORT_MODULE_RTEXTURES) #include "utils.h" // Required for: TRACELOG() -#include "rlgl.h" // OpenGL abstraction layer to OpenGL 1.1, 3.3 or ES2 +#include "rlgl.h" // OpenGL abstraction layer to multiple versions -#include // Required for: malloc(), free() -#include // Required for: strlen() [Used in ImageTextEx()], strcmp() [Used in LoadImageFromMemory()] +#include // Required for: malloc(), calloc(), free() +#include // Required for: strlen() [Used in ImageTextEx()], strcmp() [Used in LoadImageFromMemory()/LoadImageAnimFromMemory()/ExportImageToMemory()] #include // Required for: fabsf() [Used in DrawTextureRec()] #include // Required for: sprintf() [Used in ExportImageAsCode()] @@ -212,15 +212,25 @@ #define STBIR_MALLOC(size,c) ((void)(c), RL_MALLOC(size)) #define STBIR_FREE(ptr,c) ((void)(c), RL_FREE(ptr)) + +#if defined(__GNUC__) // GCC and Clang + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wunused-function" +#endif + #define STB_IMAGE_RESIZE_IMPLEMENTATION -#include "external/stb_image_resize2.h" // Required for: stbir_resize_uint8_linear() [ImageResize()] +#include "external/stb_image_resize2.h" // Required for: stbir_resize_uint8_linear() [ImageResize()] + +#if defined(__GNUC__) // GCC and Clang + #pragma GCC diagnostic pop +#endif #if defined(SUPPORT_FILEFORMAT_SVG) - #define NANOSVG_IMPLEMENTATION // Expands implementation - #include "external/nanosvg.h" + #define NANOSVG_IMPLEMENTATION // Expands implementation + #include "external/nanosvg.h" - #define NANOSVGRAST_IMPLEMENTATION - #include "external/nanosvgrast.h" + #define NANOSVGRAST_IMPLEMENTATION + #include "external/nanosvgrast.h" #endif //---------------------------------------------------------------------------------- @@ -283,9 +293,12 @@ Image LoadImage(const char *fileName) unsigned char *fileData = LoadFileData(fileName, &dataSize); // Loading image from memory data - if (fileData != NULL) image = LoadImageFromMemory(GetFileExtension(fileName), fileData, dataSize); + if (fileData != NULL) + { + image = LoadImageFromMemory(GetFileExtension(fileName), fileData, dataSize); - RL_FREE(fileData); + UnloadFileData(fileData); + } return image; } @@ -301,18 +314,22 @@ Image LoadImageRaw(const char *fileName, int width, int height, int format, int if (fileData != NULL) { unsigned char *dataPtr = fileData; - unsigned int size = GetPixelDataSize(width, height, format); + int size = GetPixelDataSize(width, height, format); - if (headerSize > 0) dataPtr += headerSize; + if (size <= dataSize) // Security check + { + // Offset file data to expected raw image by header size + if ((headerSize > 0) && ((headerSize + size) <= dataSize)) dataPtr += headerSize; - image.data = RL_MALLOC(size); // Allocate required memory in bytes - memcpy(image.data, dataPtr, size); // Copy required data to image - image.width = width; - image.height = height; - image.mipmaps = 1; - image.format = format; + image.data = RL_MALLOC(size); // Allocate required memory in bytes + memcpy(image.data, dataPtr, size); // Copy required data to image + image.width = width; + image.height = height; + image.mipmaps = 1; + image.format = format; + } - RL_FREE(fileData); + UnloadFileData(fileData); } return image; @@ -368,8 +385,8 @@ Image LoadImageSvg(const char *fileNameOrString, int width, int height) int offsetX = 0; int offsetY = 0; - if (scaleHeight > scaleWidth) offsetY = (height - svgImage->height*scale) / 2; - else offsetX = (width - svgImage->width*scale) / 2; + if (scaleHeight > scaleWidth) offsetY = (height - svgImage->height*scale)/2; + else offsetX = (width - svgImage->width*scale)/2; // Rasterize struct NSVGrasterizer *rast = nsvgCreateRasterizer(); @@ -421,7 +438,7 @@ Image LoadImageAnim(const char *fileName, int *frames) image.mipmaps = 1; image.format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8; - RL_FREE(fileData); + UnloadFileData(fileData); RL_FREE(delays); // NOTE: Frames delays are discarded } } @@ -438,12 +455,56 @@ Image LoadImageAnim(const char *fileName, int *frames) return image; } +// Load animated image data +// - Image.data buffer includes all frames: [image#0][image#1][image#2][...] +// - Number of frames is returned through 'frames' parameter +// - All frames are returned in RGBA format +// - Frames delay data is discarded +Image LoadImageAnimFromMemory(const char *fileType, const unsigned char *fileData, int dataSize, int *frames) +{ + Image image = { 0 }; + int frameCount = 0; + + // Security check for input data + if ((fileType == NULL) || (fileData == NULL) || (dataSize == 0)) return image; + +#if defined(SUPPORT_FILEFORMAT_GIF) + if ((strcmp(fileType, ".gif") == 0) || (strcmp(fileType, ".GIF") == 0)) + { + if (fileData != NULL) + { + int comp = 0; + int *delays = NULL; + image.data = stbi_load_gif_from_memory(fileData, dataSize, &delays, &image.width, &image.height, &frameCount, &comp, 4); + + image.mipmaps = 1; + image.format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8; + + RL_FREE(delays); // NOTE: Frames delays are discarded + } + } +#else + if (false) { } +#endif + else + { + image = LoadImageFromMemory(fileType, fileData, dataSize); + frameCount = 1; + } + + *frames = frameCount; + return image; +} + // Load image from memory buffer, fileType refers to extension: i.e. ".png" // WARNING: File extension must be provided in lower-case Image LoadImageFromMemory(const char *fileType, const unsigned char *fileData, int dataSize) { Image image = { 0 }; + // Security check for input data + if ((fileType == NULL) || (fileData == NULL) || (dataSize == 0)) return image; + if ((false) #if defined(SUPPORT_FILEFORMAT_PNG) || (strcmp(fileType, ".png") == 0) || (strcmp(fileType, ".PNG") == 0) @@ -633,10 +694,11 @@ Image LoadImageFromTexture(Texture2D texture) // Load image from screen buffer and (screenshot) Image LoadImageFromScreen(void) { + Vector2 scale = GetWindowScaleDPI(); Image image = { 0 }; - image.width = GetScreenWidth(); - image.height = GetScreenHeight(); + image.width = (int)(GetScreenWidth()*scale.x); + image.height = (int)(GetScreenHeight()*scale.y); image.mipmaps = 1; image.format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8; image.data = rlReadScreenPixels(image.width, image.height); @@ -647,11 +709,15 @@ Image LoadImageFromScreen(void) // Check if an image is ready bool IsImageReady(Image image) { - return ((image.data != NULL) && // Validate pixel data available - (image.width > 0) && - (image.height > 0) && // Validate image size - (image.format > 0) && // Validate image format - (image.mipmaps > 0)); // Validate image mipmaps (at least 1 for basic mipmap level) + bool result = false; + + if ((image.data != NULL) && // Validate pixel data available + (image.width > 0) && + (image.height > 0) && // Validate image size + (image.format > 0) && // Validate image format + (image.mipmaps > 0)) result = true; // Validate image mipmaps (at least 1 for basic mipmap level) + + return result; } // Unload image from CPU memory (RAM) @@ -666,6 +732,7 @@ bool ExportImage(Image image, const char *fileName) { int result = 0; + // Security check for input data if ((image.width == 0) || (image.height == 0) || (image.data == NULL)) return result; #if defined(SUPPORT_IMAGE_EXPORT) @@ -753,6 +820,7 @@ unsigned char *ExportImageToMemory(Image image, const char *fileType, int *dataS unsigned char *fileData = NULL; *dataSize = 0; + // Security check for input data if ((image.width == 0) || (image.height == 0) || (image.data == NULL)) return NULL; #if defined(SUPPORT_IMAGE_EXPORT) @@ -800,7 +868,7 @@ bool ExportImageAsCode(Image image, const char *fileName) byteCount += sprintf(txtData + byteCount, "// more info and bugs-report: github.com/raysan5/raylib //\n"); byteCount += sprintf(txtData + byteCount, "// feedback and support: ray[at]raylib.com //\n"); byteCount += sprintf(txtData + byteCount, "// //\n"); - byteCount += sprintf(txtData + byteCount, "// Copyright (c) 2018-2023 Ramon Santamaria (@raysan5) //\n"); + byteCount += sprintf(txtData + byteCount, "// Copyright (c) 2018-2024 Ramon Santamaria (@raysan5) //\n"); byteCount += sprintf(txtData + byteCount, "// //\n"); byteCount += sprintf(txtData + byteCount, "////////////////////////////////////////////////////////////////////////////////////////\n\n"); @@ -856,8 +924,8 @@ Image GenImageColor(int width, int height, Color color) #if defined(SUPPORT_IMAGE_GENERATION) // Generate image: linear gradient // The direction value specifies the direction of the gradient (in degrees) -// with 0 being vertical (from top to bottom), 90 being horizontal (from left to right). -// The gradient effectively rotates counter-clockwise by the specified amount. +// with 0 being vertical (from top to bottom), 90 being horizontal (from left to right) +// The gradient effectively rotates counter-clockwise by the specified amount Image GenImageGradientLinear(int width, int height, int direction, Color start, Color end) { Color *pixels = (Color *)RL_MALLOC(width*height*sizeof(Color)); @@ -950,8 +1018,8 @@ Image GenImageGradientSquare(int width, int height, float density, Color inner, float distY = fabsf(y - centerY); // Normalize the distances by the dimensions of the gradient rectangle - float normalizedDistX = distX / centerX; - float normalizedDistY = distY / centerY; + float normalizedDistX = distX/centerX; + float normalizedDistY = distY/centerY; // Calculate the total normalized Manhattan distance float manhattanDist = fmaxf(normalizedDistX, normalizedDistY); @@ -1008,6 +1076,7 @@ Image GenImageChecked(int width, int height, int checksX, int checksY, Color col } // Generate image: white noise +// NOTE: It requires GetRandomValue(), defined in [rcore] Image GenImageWhiteNoise(int width, int height, float factor) { Color *pixels = (Color *)RL_MALLOC(width*height*sizeof(Color)); @@ -1546,7 +1615,7 @@ Image ImageTextEx(Font font, const char *text, float fontSize, float spacing, Co // Scale image depending on text size if (textSize.y != imSize.y) { - float scaleFactor = textSize.y / imSize.y; + float scaleFactor = textSize.y/imSize.y; TRACELOG(LOG_INFO, "IMAGE: Text scaled by factor: %f", scaleFactor); // Using nearest-neighbor scaling algorithm for default font @@ -1600,7 +1669,6 @@ void ImageResizeNN(Image *image,int newWidth,int newHeight) UnloadImageColors(pixels); } - // Resize and image to new size // NOTE: Uses stb default scaling filters (both bicubic): // STBIR_DEFAULT_FILTER_UPSAMPLE STBIR_FILTER_CATMULLROM @@ -1693,8 +1761,22 @@ void ImageResizeCanvas(Image *image, int newWidth, int newHeight, int offsetX, i int bytesPerPixel = GetPixelDataSize(1, 1, image->format); unsigned char *resizedData = (unsigned char *)RL_CALLOC(newWidth*newHeight*bytesPerPixel, 1); - // TODO: Fill resized canvas with fill color (must be formatted to image->format) + // Fill resized canvas with fill color + // Set first pixel with image->format + SetPixelColor(resizedData, fill, image->format); + // Fill remaining bytes of first row + for (int x = 1; x < newWidth; x++) + { + memcpy(resizedData + x*bytesPerPixel, resizedData, bytesPerPixel); + } + // Copy the first row into the other rows + for (int y = 1; y < newHeight; y++) + { + memcpy(resizedData + y*newWidth*bytesPerPixel, resizedData, newWidth*bytesPerPixel); + } + + // Copy old image to resized canvas int dstOffsetSize = ((int)dstPos.y*newWidth + (int)dstPos.x)*bytesPerPixel; for (int y = 0; y < (int)srcRec.height; y++) @@ -1930,8 +2012,9 @@ void ImageAlphaPremultiply(Image *image) ImageFormat(image, format); } -// Apply box blur -void ImageBlurGaussian(Image *image, int blurSize) { +// Apply box blur to image +void ImageBlurGaussian(Image *image, int blurSize) +{ // Security check to avoid program crash if ((image->data == NULL) || (image->width == 0) || (image->height == 0)) return; @@ -1943,7 +2026,8 @@ void ImageBlurGaussian(Image *image, int blurSize) { Vector4 *pixelsCopy1 = RL_MALLOC((image->height)*(image->width)*sizeof(Vector4)); Vector4 *pixelsCopy2 = RL_MALLOC((image->height)*(image->width)*sizeof(Vector4)); - for (int i = 0; i < (image->height)*(image->width); i++) { + for (int i = 0; i < (image->height*image->width); i++) + { pixelsCopy1[i].x = pixels[i].r; pixelsCopy1[i].y = pixels[i].g; pixelsCopy1[i].z = pixels[i].b; @@ -1951,7 +2035,8 @@ void ImageBlurGaussian(Image *image, int blurSize) { } // Repeated convolution of rectangular window signal by itself converges to a gaussian distribution - for (int j = 0; j < GAUSSIAN_BLUR_ITERATIONS; j++) { + for (int j = 0; j < GAUSSIAN_BLUR_ITERATIONS; j++) + { // Horizontal motion blur for (int row = 0; row < image->height; row++) { @@ -1959,9 +2044,9 @@ void ImageBlurGaussian(Image *image, int blurSize) { float avgG = 0.0f; float avgB = 0.0f; float avgAlpha = 0.0f; - int convolutionSize = blurSize+1; + int convolutionSize = blurSize; - for (int i = 0; i < blurSize+1; i++) + for (int i = 0; i < blurSize; i++) { avgR += pixelsCopy1[row*image->width + i].x; avgG += pixelsCopy1[row*image->width + i].y; @@ -1969,19 +2054,14 @@ void ImageBlurGaussian(Image *image, int blurSize) { avgAlpha += pixelsCopy1[row*image->width + i].w; } - pixelsCopy2[row*image->width].x = avgR/convolutionSize; - pixelsCopy2[row*image->width].y = avgG/convolutionSize; - pixelsCopy2[row*image->width].z = avgB/convolutionSize; - pixelsCopy2[row*image->width].w = avgAlpha/convolutionSize; - - for (int x = 1; x < image->width; x++) + for (int x = 0; x < image->width; x++) { - if (x-blurSize >= 0) + if (x-blurSize-1 >= 0) { - avgR -= pixelsCopy1[row*image->width + x-blurSize].x; - avgG -= pixelsCopy1[row*image->width + x-blurSize].y; - avgB -= pixelsCopy1[row*image->width + x-blurSize].z; - avgAlpha -= pixelsCopy1[row*image->width + x-blurSize].w; + avgR -= pixelsCopy1[row*image->width + x-blurSize-1].x; + avgG -= pixelsCopy1[row*image->width + x-blurSize-1].y; + avgB -= pixelsCopy1[row*image->width + x-blurSize-1].z; + avgAlpha -= pixelsCopy1[row*image->width + x-blurSize-1].w; convolutionSize--; } @@ -1999,7 +2079,7 @@ void ImageBlurGaussian(Image *image, int blurSize) { pixelsCopy2[row*image->width + x].z = avgB/convolutionSize; pixelsCopy2[row*image->width + x].w = avgAlpha/convolutionSize; } - } + } // Vertical motion blur for (int col = 0; col < image->width; col++) @@ -2008,9 +2088,9 @@ void ImageBlurGaussian(Image *image, int blurSize) { float avgG = 0.0f; float avgB = 0.0f; float avgAlpha = 0.0f; - int convolutionSize = blurSize+1; + int convolutionSize = blurSize; - for (int i = 0; i < blurSize+1; i++) + for (int i = 0; i < blurSize; i++) { avgR += pixelsCopy2[i*image->width + col].x; avgG += pixelsCopy2[i*image->width + col].y; @@ -2018,19 +2098,14 @@ void ImageBlurGaussian(Image *image, int blurSize) { avgAlpha += pixelsCopy2[i*image->width + col].w; } - pixelsCopy1[col].x = (unsigned char) (avgR/convolutionSize); - pixelsCopy1[col].y = (unsigned char) (avgG/convolutionSize); - pixelsCopy1[col].z = (unsigned char) (avgB/convolutionSize); - pixelsCopy1[col].w = (unsigned char) (avgAlpha/convolutionSize); - - for (int y = 1; y < image->height; y++) + for (int y = 0; y < image->height; y++) { - if (y-blurSize >= 0) + if (y-blurSize-1 >= 0) { - avgR -= pixelsCopy2[(y-blurSize)*image->width + col].x; - avgG -= pixelsCopy2[(y-blurSize)*image->width + col].y; - avgB -= pixelsCopy2[(y-blurSize)*image->width + col].z; - avgAlpha -= pixelsCopy2[(y-blurSize)*image->width + col].w; + avgR -= pixelsCopy2[(y-blurSize-1)*image->width + col].x; + avgG -= pixelsCopy2[(y-blurSize-1)*image->width + col].y; + avgB -= pixelsCopy2[(y-blurSize-1)*image->width + col].z; + avgAlpha -= pixelsCopy2[(y-blurSize-1)*image->width + col].w; convolutionSize--; } if (y+blurSize < image->height) @@ -2050,7 +2125,6 @@ void ImageBlurGaussian(Image *image, int blurSize) { } } - // Reverse premultiply for (int i = 0; i < (image->width)*(image->height); i++) { @@ -2082,6 +2156,135 @@ void ImageBlurGaussian(Image *image, int blurSize) { ImageFormat(image, format); } +// The kernel matrix is assumed to be square. Only supply the width of the kernel +void ImageKernelConvolution(Image *image, float* kernel, int kernelSize) +{ + if ((image->data == NULL) || (image->width == 0) || (image->height == 0) || kernel == NULL) return; + + int kernelWidth = (int)sqrtf((float)kernelSize); + + if (kernelWidth*kernelWidth != kernelSize) + { + TRACELOG(LOG_WARNING, "IMAGE: Convolution kernel must be square to be applied"); + return; + } + + Color *pixels = LoadImageColors(*image); + + Vector4 *imageCopy2 = RL_MALLOC((image->height)*(image->width)*sizeof(Vector4)); + Vector4 *temp = RL_MALLOC(kernelSize*sizeof(Vector4)); + + for (int i = 0; i < kernelSize; i++) + { + temp[i].x = 0.0f; + temp[i].y = 0.0f; + temp[i].z = 0.0f; + temp[i].w = 0.0f; + } + + float rRes = 0.0f; + float gRes = 0.0f; + float bRes = 0.0f; + float aRes = 0.0f; + + int startRange = 0, endRange = 0; + + if (kernelWidth%2 == 0) + { + startRange = -kernelWidth/2; + endRange = kernelWidth/2; + } + else + { + startRange = -kernelWidth/2; + endRange = kernelWidth/2 + 1; + } + + for (int x = 0; x < image->height; x++) + { + for (int y = 0; y < image->width; y++) + { + for (int xk = startRange; xk < endRange; xk++) + { + for (int yk = startRange; yk < endRange; yk++) + { + int xkabs = xk + kernelWidth/2; + int ykabs = yk + kernelWidth/2; + unsigned int imgindex = image->width*(x + xk) + (y + yk); + + if (imgindex >= (unsigned int)(image->width*image->height)) + { + temp[kernelWidth*xkabs + ykabs].x = 0.0f; + temp[kernelWidth*xkabs + ykabs].y = 0.0f; + temp[kernelWidth*xkabs + ykabs].z = 0.0f; + temp[kernelWidth*xkabs + ykabs].w = 0.0f; + } + else + { + temp[kernelWidth*xkabs + ykabs].x = ((float)pixels[imgindex].r)/255.0f*kernel[kernelWidth*xkabs + ykabs]; + temp[kernelWidth*xkabs + ykabs].y = ((float)pixels[imgindex].g)/255.0f*kernel[kernelWidth*xkabs + ykabs]; + temp[kernelWidth*xkabs + ykabs].z = ((float)pixels[imgindex].b)/255.0f*kernel[kernelWidth*xkabs + ykabs]; + temp[kernelWidth*xkabs + ykabs].w = ((float)pixels[imgindex].a)/255.0f*kernel[kernelWidth*xkabs + ykabs]; + } + } + } + + for (int i = 0; i < kernelSize; i++) + { + rRes += temp[i].x; + gRes += temp[i].y; + bRes += temp[i].z; + aRes += temp[i].w; + } + + if (rRes < 0.0f) rRes = 0.0f; + if (gRes < 0.0f) gRes = 0.0f; + if (bRes < 0.0f) bRes = 0.0f; + + if (rRes > 1.0f) rRes = 1.0f; + if (gRes > 1.0f) gRes = 1.0f; + if (bRes > 1.0f) bRes = 1.0f; + + imageCopy2[image->width*x + y].x = rRes; + imageCopy2[image->width*x + y].y = gRes; + imageCopy2[image->width*x + y].z = bRes; + imageCopy2[image->width*x + y].w = aRes; + + rRes = 0.0f; + gRes = 0.0f; + bRes = 0.0f; + aRes = 0.0f; + + for (int i = 0; i < kernelSize; i++) + { + temp[i].x = 0.0f; + temp[i].y = 0.0f; + temp[i].z = 0.0f; + temp[i].w = 0.0f; + } + } + } + + for (int i = 0; i < (image->width*image->height); i++) + { + float alpha = (float)imageCopy2[i].w; + + pixels[i].r = (unsigned char)((imageCopy2[i].x)*255.0f); + pixels[i].g = (unsigned char)((imageCopy2[i].y)*255.0f); + pixels[i].b = (unsigned char)((imageCopy2[i].z)*255.0f); + pixels[i].a = (unsigned char)((alpha)*255.0f); + } + + int format = image->format; + RL_FREE(image->data); + RL_FREE(imageCopy2); + RL_FREE(temp); + + image->data = pixels; + image->format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8; + ImageFormat(image, format); +} + // Generate all mipmap levels for a provided image // NOTE 1: Supports POT and NPOT images // NOTE 2: image.data is scaled to include mipmap levels @@ -2469,21 +2672,17 @@ void ImageColorTint(Image *image, Color color) float cB = (float)color.b/255; float cA = (float)color.a/255; - for (int y = 0; y < image->height; y++) + for (int i = 0; i < image->width*image->height; i++) { - for (int x = 0; x < image->width; x++) - { - int index = y*image->width + x; - unsigned char r = (unsigned char)(((float)pixels[index].r/255*cR)*255.0f); - unsigned char g = (unsigned char)(((float)pixels[index].g/255*cG)*255.0f); - unsigned char b = (unsigned char)(((float)pixels[index].b/255*cB)*255.0f); - unsigned char a = (unsigned char)(((float)pixels[index].a/255*cA)*255.0f); + unsigned char r = (unsigned char)(((float)pixels[i].r/255*cR)*255.0f); + unsigned char g = (unsigned char)(((float)pixels[i].g/255*cG)*255.0f); + unsigned char b = (unsigned char)(((float)pixels[i].b/255*cB)*255.0f); + unsigned char a = (unsigned char)(((float)pixels[i].a/255*cA)*255.0f); - pixels[index].r = r; - pixels[index].g = g; - pixels[index].b = b; - pixels[index].a = a; - } + pixels[i].r = r; + pixels[i].g = g; + pixels[i].b = b; + pixels[i].a = a; } int format = image->format; @@ -2503,14 +2702,11 @@ void ImageColorInvert(Image *image) Color *pixels = LoadImageColors(*image); - for (int y = 0; y < image->height; y++) + for (int i = 0; i < image->width*image->height; i++) { - for (int x = 0; x < image->width; x++) - { - pixels[y*image->width + x].r = 255 - pixels[y*image->width + x].r; - pixels[y*image->width + x].g = 255 - pixels[y*image->width + x].g; - pixels[y*image->width + x].b = 255 - pixels[y*image->width + x].b; - } + pixels[i].r = 255 - pixels[i].r; + pixels[i].g = 255 - pixels[i].g; + pixels[i].b = 255 - pixels[i].b; } int format = image->format; @@ -2543,38 +2739,35 @@ void ImageColorContrast(Image *image, float contrast) Color *pixels = LoadImageColors(*image); - for (int y = 0; y < image->height; y++) + for (int i = 0; i < image->width*image->height; i++) { - for (int x = 0; x < image->width; x++) - { - float pR = (float)pixels[y*image->width + x].r/255.0f; - pR -= 0.5f; - pR *= contrast; - pR += 0.5f; - pR *= 255; - if (pR < 0) pR = 0; - if (pR > 255) pR = 255; + float pR = (float)pixels[i].r/255.0f; + pR -= 0.5f; + pR *= contrast; + pR += 0.5f; + pR *= 255; + if (pR < 0) pR = 0; + if (pR > 255) pR = 255; - float pG = (float)pixels[y*image->width + x].g/255.0f; - pG -= 0.5f; - pG *= contrast; - pG += 0.5f; - pG *= 255; - if (pG < 0) pG = 0; - if (pG > 255) pG = 255; + float pG = (float)pixels[i].g/255.0f; + pG -= 0.5f; + pG *= contrast; + pG += 0.5f; + pG *= 255; + if (pG < 0) pG = 0; + if (pG > 255) pG = 255; - float pB = (float)pixels[y*image->width + x].b/255.0f; - pB -= 0.5f; - pB *= contrast; - pB += 0.5f; - pB *= 255; - if (pB < 0) pB = 0; - if (pB > 255) pB = 255; + float pB = (float)pixels[i].b/255.0f; + pB -= 0.5f; + pB *= contrast; + pB += 0.5f; + pB *= 255; + if (pB < 0) pB = 0; + if (pB > 255) pB = 255; - pixels[y*image->width + x].r = (unsigned char)pR; - pixels[y*image->width + x].g = (unsigned char)pG; - pixels[y*image->width + x].b = (unsigned char)pB; - } + pixels[i].r = (unsigned char)pR; + pixels[i].g = (unsigned char)pG; + pixels[i].b = (unsigned char)pB; } int format = image->format; @@ -2598,27 +2791,24 @@ void ImageColorBrightness(Image *image, int brightness) Color *pixels = LoadImageColors(*image); - for (int y = 0; y < image->height; y++) + for (int i = 0; i < image->width*image->height; i++) { - for (int x = 0; x < image->width; x++) - { - int cR = pixels[y*image->width + x].r + brightness; - int cG = pixels[y*image->width + x].g + brightness; - int cB = pixels[y*image->width + x].b + brightness; + int cR = pixels[i].r + brightness; + int cG = pixels[i].g + brightness; + int cB = pixels[i].b + brightness; - if (cR < 0) cR = 1; - if (cR > 255) cR = 255; + if (cR < 0) cR = 1; + if (cR > 255) cR = 255; - if (cG < 0) cG = 1; - if (cG > 255) cG = 255; + if (cG < 0) cG = 1; + if (cG > 255) cG = 255; - if (cB < 0) cB = 1; - if (cB > 255) cB = 255; + if (cB < 0) cB = 1; + if (cB > 255) cB = 255; - pixels[y*image->width + x].r = (unsigned char)cR; - pixels[y*image->width + x].g = (unsigned char)cG; - pixels[y*image->width + x].b = (unsigned char)cB; - } + pixels[i].r = (unsigned char)cR; + pixels[i].g = (unsigned char)cG; + pixels[i].b = (unsigned char)cB; } int format = image->format; @@ -2638,20 +2828,17 @@ void ImageColorReplace(Image *image, Color color, Color replace) Color *pixels = LoadImageColors(*image); - for (int y = 0; y < image->height; y++) + for (int i = 0; i < image->width*image->height; i++) { - for (int x = 0; x < image->width; x++) + if ((pixels[i].r == color.r) && + (pixels[i].g == color.g) && + (pixels[i].b == color.b) && + (pixels[i].a == color.a)) { - if ((pixels[y*image->width + x].r == color.r) && - (pixels[y*image->width + x].g == color.g) && - (pixels[y*image->width + x].b == color.b) && - (pixels[y*image->width + x].a == color.a)) - { - pixels[y*image->width + x].r = replace.r; - pixels[y*image->width + x].g = replace.g; - pixels[y*image->width + x].b = replace.b; - pixels[y*image->width + x].a = replace.a; - } + pixels[i].r = replace.r; + pixels[i].g = replace.g; + pixels[i].b = replace.b; + pixels[i].a = replace.a; } } @@ -3398,8 +3585,8 @@ void ImageDrawRectangleRec(Image *dst, Rectangle rec, Color color) if ((dst->data == NULL) || (dst->width == 0) || (dst->height == 0)) return; // Security check to avoid drawing out of bounds in case of bad user data - if (rec.x < 0) { rec.width -= rec.x; rec.x = 0; } - if (rec.y < 0) { rec.height -= rec.y; rec.y = 0; } + if (rec.x < 0) { rec.width += rec.x; rec.x = 0; } + if (rec.y < 0) { rec.height += rec.y; rec.y = 0; } if (rec.width < 0) rec.width = 0; if (rec.height < 0) rec.height = 0; @@ -3408,8 +3595,8 @@ void ImageDrawRectangleRec(Image *dst, Rectangle rec, Color color) if ((rec.y + rec.height) >= dst->height) rec.height = dst->height - rec.y; // Check if the rect is even inside the image - if ((rec.x > dst->width) || (rec.y > dst->height)) return; - if (((rec.x + rec.width) < 0) || (rec.y + rec.height < 0)) return; + if ((rec.x >= dst->width) || (rec.y >= dst->height)) return; + if (((rec.x + rec.width) <= 0) || (rec.y + rec.height <= 0)) return; int sy = (int)rec.y; int sx = (int)rec.x; @@ -3429,7 +3616,7 @@ void ImageDrawRectangleRec(Image *dst, Rectangle rec, Color color) } // Repeat the first row data for all other rows - int bytesPerRow = bytesPerPixel * (int)rec.width; + int bytesPerRow = bytesPerPixel*(int)rec.width; for (int y = 1; y < (int)rec.height; y++) { memcpy(pSrcPixel + (y*dst->width)*bytesPerPixel, pSrcPixel, bytesPerRow); @@ -3564,7 +3751,7 @@ void ImageDraw(Image *dst, Image src, Rectangle srcRec, Rectangle dstRec, Color // Draw text (default font) within an image (destination) void ImageDrawText(Image *dst, const char *text, int posX, int posY, int fontSize, Color color) { -#if defined(SUPPORT_MODULE_RTEXT) +#if defined(SUPPORT_MODULE_RTEXT) && defined(SUPPORT_DEFAULT_FONT) // Make sure default font is loaded to be used on image text drawing if (GetFontDefault().texture.id == 0) LoadFontDefault(); @@ -3646,7 +3833,9 @@ TextureCubemap LoadTextureCubemap(Image image, int layout) if ((image.height/6) == image.width) { layout = CUBEMAP_LAYOUT_LINE_VERTICAL; cubemap.width = image.height/6; } else if ((image.width/3) == (image.height/4)) { layout = CUBEMAP_LAYOUT_CROSS_THREE_BY_FOUR; cubemap.width = image.width/3; } } - } else { + } + else + { if (layout == CUBEMAP_LAYOUT_LINE_VERTICAL) cubemap.width = image.height/6; if (layout == CUBEMAP_LAYOUT_LINE_HORIZONTAL) cubemap.width = image.width/6; if (layout == CUBEMAP_LAYOUT_CROSS_THREE_BY_FOUR) cubemap.width = image.width/3; @@ -3663,6 +3852,7 @@ TextureCubemap LoadTextureCubemap(Image image, int layout) Image faces = { 0 }; // Vertical column image Rectangle faceRecs[6] = { 0 }; // Face source rectangles + for (int i = 0; i < 6; i++) faceRecs[i] = (Rectangle){ 0, 0, (float)size, (float)size }; if (layout == CUBEMAP_LAYOUT_LINE_VERTICAL) @@ -3708,7 +3898,13 @@ TextureCubemap LoadTextureCubemap(Image image, int layout) // NOTE: Cubemap data is expected to be provided as 6 images in a single data array, // one after the other (that's a vertical image), following convention: +X, -X, +Y, -Y, +Z, -Z cubemap.id = rlLoadTextureCubemap(faces.data, size, faces.format); - if (cubemap.id == 0) TRACELOG(LOG_WARNING, "IMAGE: Failed to load cubemap image"); + + if (cubemap.id != 0) + { + cubemap.format = faces.format; + cubemap.mipmaps = 1; + } + else TRACELOG(LOG_WARNING, "IMAGE: Failed to load cubemap image"); UnloadImage(faces); } @@ -3723,7 +3919,7 @@ RenderTexture2D LoadRenderTexture(int width, int height) { RenderTexture2D target = { 0 }; - target.id = rlLoadFramebuffer(width, height); // Load an empty framebuffer + target.id = rlLoadFramebuffer(); // Load an empty framebuffer if (target.id > 0) { @@ -3760,13 +3956,17 @@ RenderTexture2D LoadRenderTexture(int width, int height) // Check if a texture is ready bool IsTextureReady(Texture2D texture) { + bool result = false; + // TODO: Validate maximum texture size supported by GPU? - return ((texture.id > 0) && // Validate OpenGL id - (texture.width > 0) && - (texture.height > 0) && // Validate texture size - (texture.format > 0) && // Validate texture pixel format - (texture.mipmaps > 0)); // Validate texture mipmaps (at least 1 for basic mipmap level) + if ((texture.id > 0) && // Validate OpenGL id + (texture.width > 0) && + (texture.height > 0) && // Validate texture size + (texture.format > 0) && // Validate texture pixel format + (texture.mipmaps > 0)) result = true; // Validate texture mipmaps (at least 1 for basic mipmap level) + + return result; } // Unload texture from GPU memory (VRAM) @@ -3783,9 +3983,13 @@ void UnloadTexture(Texture2D texture) // Check if a render texture is ready bool IsRenderTextureReady(RenderTexture2D target) { - return ((target.id > 0) && // Validate OpenGL id - IsTextureReady(target.depth) && // Validate FBO depth texture/renderbuffer - IsTextureReady(target.texture)); // Validate FBO texture + bool result = false; + + if ((target.id > 0) && // Validate OpenGL id + IsTextureReady(target.depth) && // Validate FBO depth texture/renderbuffer + IsTextureReady(target.texture)) result = true; // Validate FBO texture + + return result; } // Unload render texture from GPU memory (VRAM) @@ -4043,7 +4247,7 @@ void DrawTexturePro(Texture2D texture, Rectangle source, Rectangle dest, Vector2 // NOTE: Vertex position can be transformed using matrices // but the process is way more costly than just calculating - // the vertex positions manually, like done above. + // the vertex positions manually, like done above // I leave here the old implementation for educational purposes, // just in case someone wants to do some performance test /* @@ -4280,19 +4484,35 @@ void DrawTextureNPatch(Texture2D texture, NPatchInfo nPatchInfo, Rectangle dest, } } +// Check if two colors are equal +bool ColorIsEqual(Color col1, Color col2) +{ + bool result = false; + + if ((col1.r == col2.r) && (col1.g == col2.g) && (col1.b == col2.b) && (col1.a == col2.a)) result = true; + + return result; +} + // Get color with alpha applied, alpha goes from 0.0f to 1.0f Color Fade(Color color, float alpha) { + Color result = color; + if (alpha < 0.0f) alpha = 0.0f; else if (alpha > 1.0f) alpha = 1.0f; - return (Color){ color.r, color.g, color.b, (unsigned char)(255.0f*alpha) }; + result.a = (unsigned char)(255.0f*alpha); + + return result; } // Get hexadecimal value for a Color int ColorToInt(Color color) { - return (((int)color.r << 24) | ((int)color.g << 16) | ((int)color.b << 8) | (int)color.a); + int result = (((int)color.r << 24) | ((int)color.g << 16) | ((int)color.b << 8) | (int)color.a); + + return result; } // Get color normalized as float [0..1] @@ -4511,10 +4731,14 @@ Color ColorContrast(Color color, float contrast) // Get color with alpha applied, alpha goes from 0.0f to 1.0f Color ColorAlpha(Color color, float alpha) { + Color result = color; + if (alpha < 0.0f) alpha = 0.0f; else if (alpha > 1.0f) alpha = 1.0f; - return (Color){color.r, color.g, color.b, (unsigned char)(255.0f*alpha)}; + result.a = (unsigned char)(255.0f*alpha); + + return result; } // Get src alpha-blended into dst color with tint @@ -4813,22 +5037,35 @@ int GetPixelDataSize(int width, int height, int format) //---------------------------------------------------------------------------------- // Module specific Functions Definition //---------------------------------------------------------------------------------- -// From https://stackoverflow.com/questions/1659440/32-bit-to-16-bit-floating-point-conversion/60047308#60047308 +// Convert half-float (stored as unsigned short) to float +// REF: https://stackoverflow.com/questions/1659440/32-bit-to-16-bit-floating-point-conversion/60047308#60047308 +static float HalfToFloat(unsigned short x) +{ + float result = 0.0f; -static float HalfToFloat(unsigned short x) { - const unsigned int e = (x&0x7C00)>>10; // exponent - const unsigned int m = (x&0x03FF)<<13; // mantissa + const unsigned int e = (x & 0x7C00) >> 10; // Exponent + const unsigned int m = (x & 0x03FF) << 13; // Mantissa const float fm = (float)m; - const unsigned int v = (*(unsigned int*)&fm)>>23; // evil log2 bit hack to count leading zeros in denormalized format - const unsigned int r = (x&0x8000)<<16 | (e!=0)*((e+112)<<23|m) | ((e==0)&(m!=0))*((v-37)<<23|((m<<(150-v))&0x007FE000)); // sign : normalized : denormalized - return *(float*)&r; + const unsigned int v = (*(unsigned int*)&fm) >> 23; // Evil log2 bit hack to count leading zeros in denormalized format + const unsigned int r = (x & 0x8000) << 16 | (e != 0)*((e + 112) << 23 | m) | ((e == 0)&(m != 0))*((v - 37) << 23 | ((m << (150 - v)) & 0x007FE000)); // sign : normalized : denormalized + + result = *(float *)&r; + + return result; } -static unsigned short FloatToHalf(float x) { - const unsigned int b = (*(unsigned int*)&x)+0x00001000; // round-to-nearest-even: add last bit after truncated mantissa - const unsigned int e = (b&0x7F800000)>>23; // exponent - const unsigned int m = b&0x007FFFFF; // mantissa; in line below: 0x007FF000 = 0x00800000-0x00001000 = decimal indicator flag - initial rounding - return (b&0x80000000)>>16 | (e>112)*((((e-112)<<10)&0x7C00)|m>>13) | ((e<113)&(e>101))*((((0x007FF000+m)>>(125-e))+1)>>1) | (e>143)*0x7FFF; // sign : normalized : denormalized : saturate +// Convert float to half-float (stored as unsigned short) +static unsigned short FloatToHalf(float x) +{ + unsigned short result = 0; + + const unsigned int b = (*(unsigned int*) & x) + 0x00001000; // Round-to-nearest-even: add last bit after truncated mantissa + const unsigned int e = (b & 0x7F800000) >> 23; // Exponent + const unsigned int m = b & 0x007FFFFF; // Mantissa; in line below: 0x007FF000 = 0x00800000-0x00001000 = decimal indicator flag - initial rounding + + result = (b & 0x80000000) >> 16 | (e > 112)*((((e - 112) << 10) & 0x7C00) | m >> 13) | ((e < 113) & (e > 101))*((((0x007FF000 + m) >> (125 - e)) + 1) >> 1) | (e > 143)*0x7FFF; // sign : normalized : denormalized : saturate + + return result; } // Get pixel data from image as Vector4 array (float normalized) diff --git a/raylib/utils.c b/raylib/utils.c index 51d84cf..fcbdba0 100644 --- a/raylib/utils.c +++ b/raylib/utils.c @@ -10,7 +10,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2023 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2024 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. @@ -41,7 +41,7 @@ #if defined(PLATFORM_ANDROID) #include // Required for: Android error types #include // Required for: Android log system: __android_log_vprint() - #include // Required for: Android assets manager: AAsset, AAssetManager_open(), ... + #include // Required for: Android assets manager: AAsset, AAssetManager_open()... #endif #include // Required for: exit() @@ -211,13 +211,13 @@ unsigned char *LoadFileData(const char *fileName, int *dataSize) { // NOTE: fread() returns number of read elements instead of bytes, so we read [1 byte, size elements] size_t count = fread(data, sizeof(unsigned char), size, file); - + // WARNING: fread() returns a size_t value, usually 'unsigned int' (32bit compilation) and 'unsigned long long' (64bit compilation) // dataSize is unified along raylib as a 'int' type, so, for file-sizes > INT_MAX (2147483647 bytes) we have a limitation if (count > 2147483647) { TRACELOG(LOG_WARNING, "FILEIO: [%s] File is bigger than 2147483647 bytes, avoid using LoadFileData()", fileName); - + RL_FREE(data); data = NULL; } @@ -309,14 +309,20 @@ bool ExportDataAsCode(const unsigned char *data, int dataSize, const char *fileN byteCount += sprintf(txtData + byteCount, "// more info and bugs-report: github.com/raysan5/raylib //\n"); byteCount += sprintf(txtData + byteCount, "// feedback and support: ray[at]raylib.com //\n"); byteCount += sprintf(txtData + byteCount, "// //\n"); - byteCount += sprintf(txtData + byteCount, "// Copyright (c) 2022-2023 Ramon Santamaria (@raysan5) //\n"); + byteCount += sprintf(txtData + byteCount, "// Copyright (c) 2022-2024 Ramon Santamaria (@raysan5) //\n"); byteCount += sprintf(txtData + byteCount, "// //\n"); byteCount += sprintf(txtData + byteCount, "////////////////////////////////////////////////////////////////////////////////////////\n\n"); - // Get file name from path and convert variable name to uppercase + // Get file name from path char varFileName[256] = { 0 }; strcpy(varFileName, GetFileNameWithoutExt(fileName)); - for (int i = 0; varFileName[i] != '\0'; i++) if ((varFileName[i] >= 'a') && (varFileName[i] <= 'z')) { varFileName[i] = varFileName[i] - 32; } + for (int i = 0; varFileName[i] != '\0'; i++) + { + // Convert variable name to uppercase + if ((varFileName[i] >= 'a') && (varFileName[i] <= 'z')) { varFileName[i] = varFileName[i] - 32; } + // Replace non valid character for C identifier with '_' + else if (varFileName[i] == '.' || varFileName[i] == '-' || varFileName[i] == '?' || varFileName[i] == '!' || varFileName[i] == '+') { varFileName[i] = '_'; } + } byteCount += sprintf(txtData + byteCount, "#define %s_DATA_SIZE %i\n\n", varFileName, dataSize); diff --git a/raylib/utils.h b/raylib/utils.h index ff8246a..23eca8e 100644 --- a/raylib/utils.h +++ b/raylib/utils.h @@ -5,7 +5,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2023 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2024 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software.