Debian Codegraph @

src/rtextures.c

raw symbols SCIP
1 /**********************************************************************************************
2 *
3 * rtextures - Basic functions to load and draw textures
4 *
5 * CONFIGURATION:
6 * #define SUPPORT_MODULE_RTEXTURES 1
7 * rtextures module is included in the build
8 *
9 * #define SUPPORT_FILEFORMAT_BMP 1
10 * #define SUPPORT_FILEFORMAT_PNG 1
11 * #define SUPPORT_FILEFORMAT_TGA 0
12 * #define SUPPORT_FILEFORMAT_JPG 0
13 * #define SUPPORT_FILEFORMAT_GIF 1
14 * #define SUPPORT_FILEFORMAT_QOI 1
15 * #define SUPPORT_FILEFORMAT_PSD 0
16 * #define SUPPORT_FILEFORMAT_HDR 0
17 * #define SUPPORT_FILEFORMAT_PIC 0
18 * #define SUPPORT_FILEFORMAT_PNM 0
19 * #define SUPPORT_FILEFORMAT_DDS 1
20 * #define SUPPORT_FILEFORMAT_PKM 0
21 * #define SUPPORT_FILEFORMAT_KTX 0
22 * #define SUPPORT_FILEFORMAT_PVR 0
23 * #define SUPPORT_FILEFORMAT_ASTC 0
24 * Selected desired fileformats to be supported for image data loading. Some of those formats are
25 * supported by default, to remove support, #define as 0 in this module or your build system
26 *
27 * #define SUPPORT_IMAGE_EXPORT 1
28 * Support image export in multiple file formats
29 *
30 * #define SUPPORT_IMAGE_GENERATION 1
31 * Support procedural image generation functionality (gradient, spot, perlin-noise, cellular)
32 *
33 * DEPENDENCIES:
34 * stb_image - Multiple image formats loading (JPEG, PNG, BMP, TGA, PSD, GIF, PIC)
35 * NOTE: stb_image has been slightly modified to support Android platform
36 * stb_image_resize - Multiple image resize algorithms
37 *
38 *
39 * LICENSE: zlib/libpng
40 *
41 * Copyright (c) 2013-2026 Ramon Santamaria (@raysan5)
42 *
43 * This software is provided "as-is", without any express or implied warranty. In no event
44 * will the authors be held liable for any damages arising from the use of this software.
45 *
46 * Permission is granted to anyone to use this software for any purpose, including commercial
47 * applications, and to alter it and redistribute it freely, subject to the following restrictions:
48 *
49 * 1. The origin of this software must not be misrepresented; you must not claim that you
50 * wrote the original software. If you use this software in a product, an acknowledgment
51 * in the product documentation would be appreciated but is not required.
52 *
53 * 2. Altered source versions must be plainly marked as such, and must not be misrepresented
54 * as being the original software.
55 *
56 * 3. This notice may not be removed or altered from any source distribution.
57 *
58 **********************************************************************************************/
59
60 #include "raylib.h" // Declares module functions
61
62 #include "config.h" // Defines module configuration flags
63
64 #if SUPPORT_MODULE_RTEXTURES
65
66 #include "rlgl.h" // OpenGL abstraction layer to multiple versions
67
68 #include <stdlib.h> // Required for: malloc(), calloc(), free()
69 #include <string.h> // Required for: strlen() [Used in ImageTextEx()], strcmp() [Used in LoadImageFromMemory()/LoadImageAnimFromMemory()/ExportImageToMemory()]
70 #include <math.h> // Required for: fabsf() [Used in DrawTextureRec()]
71 #include <stdio.h> // Required for: sprintf() [Used in ExportImageAsCode()]
72
73 // Support only desired texture formats on stb_image
74 #if !SUPPORT_FILEFORMAT_BMP
75 #define STBI_NO_BMP
76 #endif
77 #if !SUPPORT_FILEFORMAT_PNG
78 #define STBI_NO_PNG
79 #endif
80 #if !SUPPORT_FILEFORMAT_TGA
81 #define STBI_NO_TGA
82 #endif
83 #if !SUPPORT_FILEFORMAT_JPG
84 #define STBI_NO_JPEG // Image format .jpg and .jpeg
85 #endif
86 #if !SUPPORT_FILEFORMAT_PSD
87 #define STBI_NO_PSD
88 #endif
89 #if !SUPPORT_FILEFORMAT_GIF
90 #define STBI_NO_GIF
91 #endif
92 #if !SUPPORT_FILEFORMAT_PIC
93 #define STBI_NO_PIC
94 #endif
95 #if !SUPPORT_FILEFORMAT_HDR
96 #define STBI_NO_HDR
97 #endif
98 #if !SUPPORT_FILEFORMAT_PNM
99 #define STBI_NO_PNM
100 #endif
101
102 #if SUPPORT_FILEFORMAT_DDS
103 #define RLTEXGPU_SUPPORT_DDS
104 #endif
105 #if SUPPORT_FILEFORMAT_PKM
106 #define RLTEXGPU_SUPPORT_PKM
107 #endif
108 #if SUPPORT_FILEFORMAT_KTX
109 #define RLTEXGPU_SUPPORT_KTX
110 #endif
111 #if SUPPORT_FILEFORMAT_PVR
112 #define RLTEXGPU_SUPPORT_PVR
113 #endif
114 #if SUPPORT_FILEFORMAT_ASTC
115 #define RLTEXGPU_SUPPORT_ASTC
116 #endif
117
118 // Image fileformats not supported by default
119 #if (SUPPORT_FILEFORMAT_BMP || \
120 SUPPORT_FILEFORMAT_PNG || \
121 SUPPORT_FILEFORMAT_TGA || \
122 SUPPORT_FILEFORMAT_JPG || \
123 SUPPORT_FILEFORMAT_PSD || \
124 SUPPORT_FILEFORMAT_GIF || \
125 SUPPORT_FILEFORMAT_HDR || \
126 SUPPORT_FILEFORMAT_PIC || \
127 SUPPORT_FILEFORMAT_PNM)
128
129 #if defined(__GNUC__) // GCC and Clang
130 #pragma GCC diagnostic push
131 #pragma GCC diagnostic ignored "-Wunused-function"
132 #endif
133
134 #define STBI_MALLOC RL_MALLOC
135 #define STBI_FREE RL_FREE
136 #define STBI_REALLOC RL_REALLOC
137
138 #define STBI_NO_THREAD_LOCALS
139
140 #if defined(__TINYC__)
141 #define STBI_NO_SIMD
142 #endif
143
144 #define STB_IMAGE_IMPLEMENTATION
145 #include "external/stb_image.h" // Required for: stbi_load_from_file()
146 // NOTE: Used to read image data (multiple formats support)
147
148 #if defined(__GNUC__) // GCC and Clang
149 #pragma GCC diagnostic pop
150 #endif
151 #endif
152
153 #if (SUPPORT_FILEFORMAT_DDS || \
154 SUPPORT_FILEFORMAT_PKM || \
155 SUPPORT_FILEFORMAT_KTX || \
156 SUPPORT_FILEFORMAT_PVR || \
157 SUPPORT_FILEFORMAT_ASTC)
158
159 #if defined(__GNUC__) // GCC and Clang
160 #pragma GCC diagnostic push
161 #pragma GCC diagnostic ignored "-Wunused-function"
162 #endif
163
164 #define RLTEXGPU_MALLOC RL_MALLOC
165 #define RLTEXGPU_FREE RL_FREE
166 #define RLTEXGPU_LOG(...) TRACELOG(LOG_WARNING, "IMAGE: " __VA_ARGS__)
167 #define RLTEXGPU_SHOW_LOG_INFO
168 #define RLTEXGPU_IMPLEMENTATION
169 #include "external/rltexgpu.h" // Required for: rl_load_xxx_from_memory()
170 // NOTE: Used to read compressed textures data (multiple formats support)
171 #if defined(__GNUC__) // GCC and Clang
172 #pragma GCC diagnostic pop
173 #endif
174 #endif
175
176 #if SUPPORT_FILEFORMAT_QOI
177 #define QOI_MALLOC RL_MALLOC
178 #define QOI_FREE RL_FREE
179
180 #if defined(_MSC_VER) // Disable some MSVC warning
181 #pragma warning(push)
182 #pragma warning(disable : 4267)
183 #endif
184
185 #define QOI_IMPLEMENTATION
186 #include "external/qoi.h"
187
188 #if defined(_MSC_VER)
189 #pragma warning(pop) // Disable MSVC warning suppression
190 #endif
191
192 #endif
193
194 #if SUPPORT_IMAGE_EXPORT
195 #define STBIW_MALLOC RL_MALLOC
196 #define STBIW_FREE RL_FREE
197 #define STBIW_REALLOC RL_REALLOC
198
199 #define STB_IMAGE_WRITE_IMPLEMENTATION
200 #include "external/stb_image_write.h" // Required for: stbi_write_*()
201 #endif
202
203 #if SUPPORT_IMAGE_GENERATION
204 #define STB_PERLIN_IMPLEMENTATION
205 #include "external/stb_perlin.h" // Required for: stb_perlin_fbm_noise3
206 #endif
207
208 #define STBIR_MALLOC(size,c) ((void)(c), RL_MALLOC(size))
209 #define STBIR_FREE(ptr,c) ((void)(c), RL_FREE(ptr))
210
211 #if defined(__GNUC__) // GCC and Clang
212 #pragma GCC diagnostic push
213 #pragma GCC diagnostic ignored "-Wunused-function"
214 #endif
215
216 #if defined(__TINYC__)
217 #define STBIR_NO_SIMD
218 #endif
219 #define STB_IMAGE_RESIZE_IMPLEMENTATION
220 #include "external/stb_image_resize2.h" // Required for: stbir_resize_uint8_linear() [ImageResize()]
221
222 #if defined(__GNUC__) // GCC and Clang
223 #pragma GCC diagnostic pop
224 #endif
225
226 //----------------------------------------------------------------------------------
227 // Defines and Macros
228 //----------------------------------------------------------------------------------
229 #ifndef PIXELFORMAT_UNCOMPRESSED_R5G5B5A1_ALPHA_THRESHOLD
230 #define PIXELFORMAT_UNCOMPRESSED_R5G5B5A1_ALPHA_THRESHOLD 50 // Threshold over 255 to set alpha as 0
231 #endif
232
233 #ifndef GAUSSIAN_BLUR_ITERATIONS
234 #define GAUSSIAN_BLUR_ITERATIONS 4 // Number of box blur iterations to approximate gaussian blur
235 #endif
236
237 //----------------------------------------------------------------------------------
238 // Types and Structures Definition
239 //----------------------------------------------------------------------------------
240 // ...
241
242 //----------------------------------------------------------------------------------
243 // Global Variables Definition
244 //----------------------------------------------------------------------------------
245 // It's lonely here...
246
247 //----------------------------------------------------------------------------------
248 // Other Modules Functions Declaration (required by text)
249 //----------------------------------------------------------------------------------
250 extern void LoadFontDefault(void); // [Module: text] Loads default font, required by ImageDrawText()
251
252 //----------------------------------------------------------------------------------
253 // Module Internal Functions Declaration
254 //----------------------------------------------------------------------------------
255 static float HalfToFloat(unsigned short x);
256 static unsigned short FloatToHalf(float x);
257 static Vector4 *LoadImageDataNormalized(Image image); // Load pixel data from image as Vector4 array (float normalized)
258
259 //----------------------------------------------------------------------------------
260 // Module Functions Definition
261 //----------------------------------------------------------------------------------
262 // Load image from file into CPU memory (RAM)
263 Image LoadImage(const char *fileName)
264 {
265 Image image = { 0 };
266
267 #if SUPPORT_FILEFORMAT_PNG || \
268 SUPPORT_FILEFORMAT_BMP || \
269 SUPPORT_FILEFORMAT_TGA || \
270 SUPPORT_FILEFORMAT_JPG || \
271 SUPPORT_FILEFORMAT_GIF || \
272 SUPPORT_FILEFORMAT_PIC || \
273 SUPPORT_FILEFORMAT_HDR || \
274 SUPPORT_FILEFORMAT_PNM || \
275 SUPPORT_FILEFORMAT_PSD
276
277 #define STBI_REQUIRED
278 #endif
279
280 // Loading file to memory
281 int dataSize = 0;
282 unsigned char *fileData = LoadFileData(fileName, &dataSize);
283
284 // Loading image from memory data
285 if (fileData != NULL)
286 {
287 image = LoadImageFromMemory(GetFileExtension(fileName), fileData, dataSize);
288
289 UnloadFileData(fileData);
290 }
291
292 return image;
293 }
294
295 // Load an image from RAW file data
296 Image LoadImageRaw(const char *fileName, int width, int height, int format, int headerSize)
297 {
298 Image image = { 0 };
299
300 int dataSize = 0;
301 unsigned char *fileData = LoadFileData(fileName, &dataSize);
302
303 if (fileData != NULL)
304 {
305 unsigned char *dataPtr = fileData;
306 int size = GetPixelDataSize(width, height, format);
307
308 if (size <= dataSize) // Security check
309 {
310 // Offset file data to expected raw image by header size
311 if ((headerSize > 0) && ((headerSize + size) <= dataSize)) dataPtr += headerSize;
312
313 image.data = RL_MALLOC(size); // Allocate required memory in bytes
314 memcpy(image.data, dataPtr, size); // Copy required data to image
315 image.width = width;
316 image.height = height;
317 image.mipmaps = 1;
318 image.format = format;
319 }
320
321 UnloadFileData(fileData);
322 }
323
324 return image;
325 }
326
327 // Load animated image data
328 // - Image.data buffer includes all frames: [image#0][image#1][image#2][...]
329 // - Number of frames is returned through 'frames' parameter
330 // - All frames are returned in RGBA format
331 // - Frames delay data is discarded
332 Image LoadImageAnim(const char *fileName, int *frames)
333 {
334 Image image = { 0 };
335 int frameCount = 0;
336
337 #if SUPPORT_FILEFORMAT_GIF
338 if (IsFileExtension(fileName, ".gif"))
339 {
340 int dataSize = 0;
341 unsigned char *fileData = LoadFileData(fileName, &dataSize);
342
343 if (fileData != NULL)
344 {
345 int comp = 0;
346 int *delays = NULL;
347 image.data = stbi_load_gif_from_memory(fileData, dataSize, &delays, &image.width, &image.height, &frameCount, &comp, 4);
348
349 image.mipmaps = 1;
350 image.format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8;
351
352 UnloadFileData(fileData);
353 RL_FREE(delays); // NOTE: Frames delays are discarded
354 }
355 }
356 #else
357 if (false) { }
358 #endif
359 else
360 {
361 image = LoadImage(fileName);
362 frameCount = 1;
363 }
364
365 *frames = frameCount;
366 return image;
367 }
368
369 // Load animated image data from memory
370 // - Image.data buffer includes all frames: [image#0][image#1][image#2][...]
371 // - Number of frames is returned through 'frames' parameter
372 // - All frames are returned in RGBA format
373 // - Frames delay data is discarded
374 Image LoadImageAnimFromMemory(const char *fileType, const unsigned char *fileData, int dataSize, int *frames)
375 {
376 Image image = { 0 };
377 int frameCount = 0;
378
379 if ((fileType == NULL) || (fileData == NULL) || (dataSize == 0)) return image; // Security check
380
381 #if SUPPORT_FILEFORMAT_GIF
382 if ((strcmp(fileType, ".gif") == 0) || (strcmp(fileType, ".GIF") == 0))
383 {
384 if (fileData != NULL)
385 {
386 int comp = 0;
387 int *delays = NULL;
388 image.data = stbi_load_gif_from_memory(fileData, dataSize, &delays, &image.width, &image.height, &frameCount, &comp, 4);
389
390 image.mipmaps = 1;
391 image.format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8;
392
393 RL_FREE(delays); // NOTE: Frames delays are discarded
394 }
395 }
396 #else
397 if (false) { }
398 #endif
399 else
400 {
401 image = LoadImageFromMemory(fileType, fileData, dataSize);
402 frameCount = 1;
403 }
404
405 *frames = frameCount;
406 return image;
407 }
408
409 // Load image from memory buffer, fileType refers to extension: i.e. ".png"
410 // WARNING: File extension must be provided in lower-case
411 Image LoadImageFromMemory(const char *fileType, const unsigned char *fileData, int dataSize)
412 {
413 Image image = { 0 };
414
415 // Security checks for input data
416 if ((fileData == NULL) || (dataSize == 0))
417 {
418 TRACELOG(LOG_WARNING, "IMAGE: Invalid file data");
419 return image;
420 }
421 if (fileType == NULL)
422 {
423 TRACELOG(LOG_WARNING, "IMAGE: Missing file extension");
424 return image;
425 }
426
427 if ((false)
428 #if SUPPORT_FILEFORMAT_PNG
429 || (strcmp(fileType, ".png") == 0) || (strcmp(fileType, ".PNG") == 0)
430 #endif
431 #if SUPPORT_FILEFORMAT_BMP
432 || (strcmp(fileType, ".bmp") == 0) || (strcmp(fileType, ".BMP") == 0)
433 #endif
434 #if SUPPORT_FILEFORMAT_TGA
435 || (strcmp(fileType, ".tga") == 0) || (strcmp(fileType, ".TGA") == 0)
436 #endif
437 #if SUPPORT_FILEFORMAT_JPG
438 || (strcmp(fileType, ".jpg") == 0) || (strcmp(fileType, ".jpeg") == 0)
439 || (strcmp(fileType, ".JPG") == 0) || (strcmp(fileType, ".JPEG") == 0)
440 #endif
441 #if SUPPORT_FILEFORMAT_GIF
442 || (strcmp(fileType, ".gif") == 0) || (strcmp(fileType, ".GIF") == 0)
443 #endif
444 #if SUPPORT_FILEFORMAT_PIC
445 || (strcmp(fileType, ".pic") == 0) || (strcmp(fileType, ".PIC") == 0)
446 #endif
447 #if SUPPORT_FILEFORMAT_PNM
448 || (strcmp(fileType, ".ppm") == 0) || (strcmp(fileType, ".pgm") == 0)
449 || (strcmp(fileType, ".PPM") == 0) || (strcmp(fileType, ".PGM") == 0)
450 #endif
451 #if SUPPORT_FILEFORMAT_PSD
452 || (strcmp(fileType, ".psd") == 0) || (strcmp(fileType, ".PSD") == 0)
453 #endif
454 )
455 {
456 #if defined(STBI_REQUIRED)
457 // NOTE: Using stb_image to load images (Supports multiple image formats)
458
459 if (fileData != NULL)
460 {
461 int comp = 0;
462 image.data = stbi_load_from_memory(fileData, dataSize, &image.width, &image.height, &comp, 0);
463
464 if (image.data != NULL)
465 {
466 image.mipmaps = 1;
467
468 if (comp == 1) image.format = PIXELFORMAT_UNCOMPRESSED_GRAYSCALE;
469 else if (comp == 2) image.format = PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA;
470 else if (comp == 3) image.format = PIXELFORMAT_UNCOMPRESSED_R8G8B8;
471 else if (comp == 4) image.format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8;
472 }
473 }
474 #endif
475 }
476 #if SUPPORT_FILEFORMAT_HDR
477 else if ((strcmp(fileType, ".hdr") == 0) || (strcmp(fileType, ".HDR") == 0))
478 {
479 #if defined(STBI_REQUIRED)
480 if (fileData != NULL)
481 {
482 int comp = 0;
483 image.data = stbi_loadf_from_memory(fileData, dataSize, &image.width, &image.height, &comp, 0);
484
485 image.mipmaps = 1;
486
487 if (comp == 1) image.format = PIXELFORMAT_UNCOMPRESSED_R32;
488 else if (comp == 3) image.format = PIXELFORMAT_UNCOMPRESSED_R32G32B32;
489 else if (comp == 4) image.format = PIXELFORMAT_UNCOMPRESSED_R32G32B32A32;
490 else
491 {
492 TRACELOG(LOG_WARNING, "IMAGE: HDR file format not supported");
493 UnloadImage(image);
494 }
495 }
496 #endif
497 }
498 #endif
499 #if SUPPORT_FILEFORMAT_QOI
500 else if ((strcmp(fileType, ".qoi") == 0) || (strcmp(fileType, ".QOI") == 0))
501 {
502 if (fileData != NULL)
503 {
504 qoi_desc desc = { 0 };
505 image.data = qoi_decode(fileData, dataSize, &desc, (int) fileData[12]);
506 image.width = desc.width;
507 image.height = desc.height;
508 image.format = (desc.channels == 4)? PIXELFORMAT_UNCOMPRESSED_R8G8B8A8 : PIXELFORMAT_UNCOMPRESSED_R8G8B8;
509 image.mipmaps = 1;
510 }
511 }
512 #endif
513 #if SUPPORT_FILEFORMAT_DDS
514 else if ((strcmp(fileType, ".dds") == 0) || (strcmp(fileType, ".DDS") == 0))
515 {
516 image.data = rl_load_dds_from_memory(fileData, dataSize, &image.width, &image.height, &image.format, &image.mipmaps);
517 }
518 #endif
519 #if SUPPORT_FILEFORMAT_PKM
520 else if ((strcmp(fileType, ".pkm") == 0) || (strcmp(fileType, ".PKM") == 0))
521 {
522 image.data = rl_load_pkm_from_memory(fileData, dataSize, &image.width, &image.height, &image.format, &image.mipmaps);
523 }
524 #endif
525 #if SUPPORT_FILEFORMAT_KTX
526 else if ((strcmp(fileType, ".ktx") == 0) || (strcmp(fileType, ".KTX") == 0))
527 {
528 image.data = rl_load_ktx_from_memory(fileData, dataSize, &image.width, &image.height, &image.format, &image.mipmaps);
529 }
530 #endif
531 #if SUPPORT_FILEFORMAT_PVR
532 else if ((strcmp(fileType, ".pvr") == 0) || (strcmp(fileType, ".PVR") == 0))
533 {
534 image.data = rl_load_pvr_from_memory(fileData, dataSize, &image.width, &image.height, &image.format, &image.mipmaps);
535 }
536 #endif
537 #if SUPPORT_FILEFORMAT_ASTC
538 else if ((strcmp(fileType, ".astc") == 0) || (strcmp(fileType, ".ASTC") == 0))
539 {
540 image.data = rl_load_astc_from_memory(fileData, dataSize, &image.width, &image.height, &image.format, &image.mipmaps);
541 }
542 #endif
543 else TRACELOG(LOG_WARNING, "IMAGE: Data format not supported");
544
545 if (image.data != NULL) TRACELOG(LOG_INFO, "IMAGE: Data loaded successfully (%ix%i | %s | %i mipmaps)", image.width, image.height, rlGetPixelFormatName(image.format), image.mipmaps);
546 else TRACELOG(LOG_WARNING, "IMAGE: Failed to load image data");
547
548 return image;
549 }
550
551 // Load image from GPU texture data
552 // NOTE: Compressed texture formats not supported
553 Image LoadImageFromTexture(Texture2D texture)
554 {
555 Image image = { 0 };
556
557 if (texture.format < PIXELFORMAT_COMPRESSED_DXT1_RGB)
558 {
559 image.data = rlReadTexturePixels(texture.id, texture.width, texture.height, texture.format);
560
561 if (image.data != NULL)
562 {
563 image.width = texture.width;
564 image.height = texture.height;
565 image.format = texture.format;
566 image.mipmaps = 1;
567
568 #if defined(GRAPHICS_API_OPENGL_ES2)
569 // NOTE: Data retrieved on OpenGL ES 2.0 should be RGBA,
570 // coming from FBO color buffer attachment, but it seems
571 // original texture format is retrieved on RPI...
572 image.format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8;
573 #endif
574 TRACELOG(LOG_INFO, "TEXTURE: [ID %i] Pixel data retrieved successfully", texture.id);
575 }
576 else TRACELOG(LOG_WARNING, "TEXTURE: [ID %i] Failed to retrieve pixel data", texture.id);
577 }
578 else TRACELOG(LOG_WARNING, "TEXTURE: [ID %i] Failed to retrieve compressed pixel data", texture.id);
579
580 return image;
581 }
582
583 // Load image from screen buffer and (screenshot)
584 Image LoadImageFromScreen(void)
585 {
586 Image image = { 0 };
587
588 image.width = (int)(GetRenderWidth());
589 image.height = (int)(GetRenderHeight());
590 image.mipmaps = 1;
591 image.format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8;
592 image.data = rlReadScreenPixels(image.width, image.height);
593
594 return image;
595 }
596
597 // Check if an image is ready
598 bool IsImageValid(Image image)
599 {
600 bool result = false;
601
602 if ((image.data != NULL) && // Validate pixel data available
603 (image.width > 0) && // Validate image width
604 (image.height > 0) && // Validate image height
605 (image.format > 0) && // Validate image format
606 (image.mipmaps > 0)) result = true; // Validate image mipmaps (at least 1 for basic mipmap level)
607
608 return result;
609 }
610
611 // Unload image from CPU memory (RAM)
612 void UnloadImage(Image image)
613 {
614 RL_FREE(image.data);
615 }
616
617 // Export image data to file
618 // NOTE: File format depends on fileName extension
619 bool ExportImage(Image image, const char *fileName)
620 {
621 int result = 0;
622
623 if ((image.width == 0) || (image.height == 0) || (image.data == NULL)) return result; // Security check
624
625 #if SUPPORT_IMAGE_EXPORT
626 int channels = 4;
627 bool allocatedData = false;
628 unsigned char *imgData = (unsigned char *)image.data;
629
630 if (image.format == PIXELFORMAT_UNCOMPRESSED_GRAYSCALE) channels = 1;
631 else if (image.format == PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA) channels = 2;
632 else if (image.format == PIXELFORMAT_UNCOMPRESSED_R8G8B8) channels = 3;
633 else if (image.format == PIXELFORMAT_UNCOMPRESSED_R8G8B8A8) channels = 4;
634 else
635 {
636 // NOTE: Getting Color array as RGBA unsigned char values
637 imgData = (unsigned char *)LoadImageColors(image);
638 allocatedData = true;
639 }
640
641 if (false) { } // Required to attach following 'else' cases
642 #if SUPPORT_FILEFORMAT_PNG
643 else if (IsFileExtension(fileName, ".png"))
644 {
645 int dataSize = 0;
646 unsigned char *fileData = stbi_write_png_to_mem((const unsigned char *)imgData, image.width*channels, image.width, image.height, channels, &dataSize);
647 result = SaveFileData(fileName, fileData, dataSize);
648 RL_FREE(fileData);
649 }
650 #endif
651 #if SUPPORT_FILEFORMAT_BMP
652 else if (IsFileExtension(fileName, ".bmp")) result = stbi_write_bmp(fileName, image.width, image.height, channels, imgData);
653 #endif
654 #if SUPPORT_FILEFORMAT_TGA
655 else if (IsFileExtension(fileName, ".tga")) result = stbi_write_tga(fileName, image.width, image.height, channels, imgData);
656 #endif
657 #if SUPPORT_FILEFORMAT_JPG
658 else if (IsFileExtension(fileName, ".jpg") ||
659 IsFileExtension(fileName, ".jpeg")) result = stbi_write_jpg(fileName, image.width, image.height, channels, imgData, 90); // JPG quality: between 1 and 100
660 #endif
661 #if SUPPORT_FILEFORMAT_QOI
662 else if (IsFileExtension(fileName, ".qoi"))
663 {
664 channels = 0;
665 if (image.format == PIXELFORMAT_UNCOMPRESSED_R8G8B8) channels = 3;
666 else if (image.format == PIXELFORMAT_UNCOMPRESSED_R8G8B8A8) channels = 4;
667 else TRACELOG(LOG_WARNING, "IMAGE: Image pixel format must be R8G8B8 or R8G8B8A8");
668
669 if ((channels == 3) || (channels == 4))
670 {
671 qoi_desc desc = { 0 };
672 desc.width = image.width;
673 desc.height = image.height;
674 desc.channels = channels;
675 desc.colorspace = QOI_SRGB;
676
677 result = qoi_write(fileName, imgData, &desc);
678 }
679 }
680 #endif
681 #if SUPPORT_FILEFORMAT_KTX
682 else if (IsFileExtension(fileName, ".ktx"))
683 {
684 result = rl_save_ktx(fileName, image.data, image.width, image.height, image.format, image.mipmaps);
685 }
686 #endif
687 else if (IsFileExtension(fileName, ".raw"))
688 {
689 // Export raw pixel data (without header)
690 // NOTE: It's up to the user to track image parameters
691 result = SaveFileData(fileName, image.data, GetPixelDataSize(image.width, image.height, image.format));
692 }
693 else TRACELOG(LOG_WARNING, "IMAGE: Export image format requested not supported");
694
695 if (allocatedData) RL_FREE(imgData);
696 #endif // SUPPORT_IMAGE_EXPORT
697
698 if (result != 0) TRACELOG(LOG_INFO, "FILEIO: [%s] Image exported successfully", fileName);
699 else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to export image", fileName);
700
701 return result;
702 }
703
704 // Export image to memory buffer
705 unsigned char *ExportImageToMemory(Image image, const char *fileType, int *dataSize)
706 {
707 unsigned char *fileData = NULL;
708 *dataSize = 0;
709
710 if ((image.width == 0) || (image.height == 0) || (image.data == NULL)) return fileData; // Security check
711
712 int channels = 4;
713
714 if (image.format == PIXELFORMAT_UNCOMPRESSED_GRAYSCALE) channels = 1;
715 else if (image.format == PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA) channels = 2;
716 else if (image.format == PIXELFORMAT_UNCOMPRESSED_R8G8B8) channels = 3;
717 else if (image.format == PIXELFORMAT_UNCOMPRESSED_R8G8B8A8) channels = 4;
718
719 #if SUPPORT_IMAGE_EXPORT
720 if ((strcmp(fileType, ".png") == 0) || (strcmp(fileType, ".PNG") == 0))
721 {
722 fileData = stbi_write_png_to_mem((const unsigned char *)image.data, image.width*channels, image.width, image.height, channels, dataSize);
723 }
724 #else
725 TRACELOG(LOG_WARNING, "IMAGE: To export image, enable flag SUPPORT_IMAGE_EXPORT");
726 #endif
727
728 return fileData;
729 }
730
731 // Export image as code file (.h) defining an array of bytes
732 bool ExportImageAsCode(Image image, const char *fileName)
733 {
734 bool result = false;
735
736 #ifndef TEXT_BYTES_PER_LINE
737 #define TEXT_BYTES_PER_LINE 20
738 #endif
739
740 int dataSize = GetPixelDataSize(image.width, image.height, image.format);
741
742 // NOTE: Text data buffer size is estimated considering image data size in bytes
743 // and requiring 6 char bytes for every byte: "0x00, "
744 char *txtData = (char *)RL_CALLOC(dataSize*6 + 2000, sizeof(char));
745
746 int byteCount = 0;
747 byteCount += sprintf(txtData + byteCount, "////////////////////////////////////////////////////////////////////////////////////////\n");
748 byteCount += sprintf(txtData + byteCount, "// //\n");
749 byteCount += sprintf(txtData + byteCount, "// ImageAsCode exporter v1.0 - Image pixel data exported as an array of bytes //\n");
750 byteCount += sprintf(txtData + byteCount, "// //\n");
751 byteCount += sprintf(txtData + byteCount, "// more info and bugs-report: github.com/raysan5/raylib //\n");
752 byteCount += sprintf(txtData + byteCount, "// feedback and support: ray[at]raylib.com //\n");
753 byteCount += sprintf(txtData + byteCount, "// //\n");
754 byteCount += sprintf(txtData + byteCount, "// Copyright (c) 2018-2026 Ramon Santamaria (@raysan5) //\n");
755 byteCount += sprintf(txtData + byteCount, "// //\n");
756 byteCount += sprintf(txtData + byteCount, "////////////////////////////////////////////////////////////////////////////////////////\n\n");
757
758 // Get file name from path and convert variable name to uppercase
759 char varFileName[256] = { 0 };
760 strncpy(varFileName, GetFileNameWithoutExt(fileName), 256 - 1); // NOTE: Using function provided by [rcore] module
761 for (int i = 0; varFileName[i] != '\0'; i++) if ((varFileName[i] >= 'a') && (varFileName[i] <= 'z')) { varFileName[i] = varFileName[i] - 32; }
762
763 // Add image information
764 byteCount += sprintf(txtData + byteCount, "// Image data information\n");
765 byteCount += sprintf(txtData + byteCount, "#define %s_WIDTH %i\n", varFileName, image.width);
766 byteCount += sprintf(txtData + byteCount, "#define %s_HEIGHT %i\n", varFileName, image.height);
767 byteCount += sprintf(txtData + byteCount, "#define %s_FORMAT %i // raylib internal pixel format\n\n", varFileName, image.format);
768
769 byteCount += sprintf(txtData + byteCount, "static unsigned char %s_DATA[%i] = { ", varFileName, dataSize);
770 for (int i = 0; i < dataSize - 1; i++) byteCount += sprintf(txtData + byteCount, ((i%TEXT_BYTES_PER_LINE == 0)? "0x%x,\n" : "0x%x, "), ((unsigned char *)image.data)[i]);
771 byteCount += sprintf(txtData + byteCount, "0x%x };\n", ((unsigned char *)image.data)[dataSize - 1]);
772
773 // NOTE: Text data size exported is determined by '\0' (NULL) character
774 result = SaveFileText(fileName, txtData);
775
776 RL_FREE(txtData);
777
778 if (result != 0) TRACELOG(LOG_INFO, "FILEIO: [%s] Image as code exported successfully", fileName);
779 else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to export image as code", fileName);
780
781 return result;
782 }
783
784 //------------------------------------------------------------------------------------
785 // Image generation functions
786 //------------------------------------------------------------------------------------
787 // Generate image: plain color
788 Image GenImageColor(int width, int height, Color color)
789 {
790 Color *pixels = (Color *)RL_CALLOC(width*height, sizeof(Color));
791
792 for (int i = 0; i < width*height; i++) pixels[i] = color;
793
794 Image image = {
795 .data = pixels,
796 .width = width,
797 .height = height,
798 .mipmaps = 1,
799 .format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8
800 };
801
802 return image;
803 }
804
805 #if SUPPORT_IMAGE_GENERATION
806 // Generate image: linear gradient
807 // The direction value specifies the direction of the gradient (in degrees)
808 // with 0 being vertical (from top to bottom), 90 being horizontal (from left to right)
809 // The gradient effectively rotates counter-clockwise by the specified amount
810 Image GenImageGradientLinear(int width, int height, int direction, Color start, Color end)
811 {
812 Color *pixels = (Color *)RL_MALLOC(width*height*sizeof(Color));
813
814 float radianDirection = (float)(90 - direction)/180.f*3.14159f;
815 float cosDir = cosf(radianDirection);
816 float sinDir = sinf(radianDirection);
817
818 // Calculate how far the top-left pixel is along the gradient direction from the center of said gradient
819 float startingPos = 0.5f - (cosDir*width/2) - (sinDir*height/2);
820
821 // With directions that lie in the first or third quadrant (i.e. from top-left to
822 // bottom-right or vice-versa), pixel (0, 0) is the farthest point on the gradient
823 // (i.e. the pixel which should become one of the gradient's ends color); while for
824 // directions that lie in the second or fourth quadrant, that point is pixel (width, 0)
825 float maxPosValue = ((signbit(sinDir) != 0) == (signbit(cosDir) != 0))? fabsf(startingPos) : fabsf(startingPos + width*cosDir);
826 for (int i = 0; i < width; i++)
827 {
828 for (int j = 0; j < height; j++)
829 {
830 // Calculate the relative position of the pixel along the gradient direction
831 float pos = (startingPos + (i*cosDir + j*sinDir))/maxPosValue;
832
833 float factor = pos;
834 factor = (factor > 1.0f)? 1.0f : factor; // Clamp to [-1,1]
835 factor = (factor < -1.0f)? -1.0f : factor; // Clamp to [-1,1]
836 factor = factor/2.0f + 0.5f;
837
838 // Generate the color for this pixel
839 pixels[j*width + i].r = (int)((float)end.r*factor + (float)start.r*(1.0f - factor));
840 pixels[j*width + i].g = (int)((float)end.g*factor + (float)start.g*(1.0f - factor));
841 pixels[j*width + i].b = (int)((float)end.b*factor + (float)start.b*(1.0f - factor));
842 pixels[j*width + i].a = (int)((float)end.a*factor + (float)start.a*(1.0f - factor));
843 }
844 }
845
846 Image image = {
847 .data = pixels,
848 .width = width,
849 .height = height,
850 .mipmaps = 1,
851 .format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8
852 };
853
854 return image;
855 }
856
857 // Generate image: radial gradient
858 Image GenImageGradientRadial(int width, int height, float density, Color inner, Color outer)
859 {
860 Color *pixels = (Color *)RL_MALLOC(width*height*sizeof(Color));
861 float radius = (width < height)? (float)width/2.0f : (float)height/2.0f;
862
863 float centerX = (float)width/2.0f;
864 float centerY = (float)height/2.0f;
865
866 for (int y = 0; y < height; y++)
867 {
868 for (int x = 0; x < width; x++)
869 {
870 float dist = hypotf((float)x - centerX, (float)y - centerY);
871 float factor = (dist - radius*density)/(radius*(1.0f - density));
872
873 factor = (float)fmax(factor, 0.0f);
874 factor = (float)fmin(factor, 1.f); // Distance can be bigger than radius, so it needs to be checked
875
876 pixels[y*width + x].r = (int)((float)outer.r*factor + (float)inner.r*(1.0f - factor));
877 pixels[y*width + x].g = (int)((float)outer.g*factor + (float)inner.g*(1.0f - factor));
878 pixels[y*width + x].b = (int)((float)outer.b*factor + (float)inner.b*(1.0f - factor));
879 pixels[y*width + x].a = (int)((float)outer.a*factor + (float)inner.a*(1.0f - factor));
880 }
881 }
882
883 Image image = {
884 .data = pixels,
885 .width = width,
886 .height = height,
887 .mipmaps = 1,
888 .format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8
889 };
890
891 return image;
892 }
893
894 // Generate image: square gradient
895 Image GenImageGradientSquare(int width, int height, float density, Color inner, Color outer)
896 {
897 Color *pixels = (Color *)RL_MALLOC(width*height*sizeof(Color));
898
899 float centerX = (float)width/2.0f;
900 float centerY = (float)height/2.0f;
901
902 for (int y = 0; y < height; y++)
903 {
904 for (int x = 0; x < width; x++)
905 {
906 // Calculate the Manhattan distance from the center
907 float distX = fabsf(x - centerX);
908 float distY = fabsf(y - centerY);
909
910 // Normalize the distances by the dimensions of the gradient rectangle
911 float normalizedDistX = distX/centerX;
912 float normalizedDistY = distY/centerY;
913
914 // Calculate the total normalized Manhattan distance
915 float manhattanDist = fmaxf(normalizedDistX, normalizedDistY);
916
917 // Subtract the density from the manhattanDist, then divide by (1 - density)
918 // This makes the gradient start from the center when density is 0, and from the edge when density is 1
919 float factor = (manhattanDist - density)/(1.0f - density);
920
921 // Clamp the factor between 0 and 1
922 factor = fminf(fmaxf(factor, 0.0f), 1.0f);
923
924 // Blend the colors based on the calculated factor
925 pixels[y*width + x].r = (int)((float)outer.r*factor + (float)inner.r*(1.0f - factor));
926 pixels[y*width + x].g = (int)((float)outer.g*factor + (float)inner.g*(1.0f - factor));
927 pixels[y*width + x].b = (int)((float)outer.b*factor + (float)inner.b*(1.0f - factor));
928 pixels[y*width + x].a = (int)((float)outer.a*factor + (float)inner.a*(1.0f - factor));
929 }
930 }
931
932 Image image = {
933 .data = pixels,
934 .width = width,
935 .height = height,
936 .mipmaps = 1,
937 .format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8
938 };
939
940 return image;
941 }
942
943 // Generate image: checked
944 Image GenImageChecked(int width, int height, int checksX, int checksY, Color col1, Color col2)
945 {
946 Color *pixels = (Color *)RL_MALLOC(width*height*sizeof(Color));
947
948 for (int y = 0; y < height; y++)
949 {
950 for (int x = 0; x < width; x++)
951 {
952 if ((x/checksX + y/checksY)%2 == 0) pixels[y*width + x] = col1;
953 else pixels[y*width + x] = col2;
954 }
955 }
956
957 Image image = {
958 .data = pixels,
959 .width = width,
960 .height = height,
961 .mipmaps = 1,
962 .format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8
963 };
964
965 return image;
966 }
967
968 // Generate image: white noise
969 // NOTE: It requires GetRandomValue(), defined in [rcore]
970 Image GenImageWhiteNoise(int width, int height, float factor)
971 {
972 Color *pixels = (Color *)RL_MALLOC(width*height*sizeof(Color));
973
974 for (int i = 0; i < width*height; i++)
975 {
976 if (GetRandomValue(0, 99) < (int)(factor*100.0f)) pixels[i] = WHITE;
977 else pixels[i] = BLACK;
978 }
979
980 Image image = {
981 .data = pixels,
982 .width = width,
983 .height = height,
984 .mipmaps = 1,
985 .format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8
986 };
987
988 return image;
989 }
990
991 // Generate image: perlin noise
992 Image GenImagePerlinNoise(int width, int height, int offsetX, int offsetY, float scale)
993 {
994 Color *pixels = (Color *)RL_MALLOC(width*height*sizeof(Color));
995
996 float aspectRatio = (float)width/(float)height;
997
998 for (int y = 0; y < height; y++)
999 {
1000 for (int x = 0; x < width; x++)
1001 {
1002 float nx = (float)(x + offsetX)*(scale/(float)width);
1003 float ny = (float)(y + offsetY)*(scale/(float)height);
1004
1005 // Apply aspect ratio compensation to wider side
1006 if (width > height) nx *= aspectRatio;
1007 else ny /= aspectRatio;
1008
1009 // Basic perlin noise implementation (not used)
1010 //float p = (stb_perlin_noise3(nx, ny, 0.0f, 0, 0, 0);
1011
1012 // Calculate a better perlin noise using fbm (fractal brownian motion)
1013 // Typical values to start playing with:
1014 // lacunarity = ~2.0 -- spacing between successive octaves (use exactly 2.0 for wrapping output)
1015 // gain = 0.5 -- relative weighting applied to each successive octave
1016 // octaves = 6 -- number of "octaves" of noise3() to sum
1017 float p = stb_perlin_fbm_noise3(nx, ny, 1.0f, 2.0f, 0.5f, 6);
1018
1019 // Clamp between -1.0f and 1.0f
1020 if (p < -1.0f) p = -1.0f;
1021 if (p > 1.0f) p = 1.0f;
1022
1023 // Data needs to be normalized from [-1..1] to [0..1]
1024 float np = (p + 1.0f)/2.0f;
1025
1026 unsigned char intensity = (unsigned char)(np*255.0f);
1027 pixels[y*width + x] = (Color){ intensity, intensity, intensity, 255 };
1028 }
1029 }
1030
1031 Image image = {
1032 .data = pixels,
1033 .width = width,
1034 .height = height,
1035 .mipmaps = 1,
1036 .format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8
1037 };
1038
1039 return image;
1040 }
1041
1042 // Generate image: cellular algorithm. Bigger tileSize means bigger cells
1043 Image GenImageCellular(int width, int height, int tileSize)
1044 {
1045 Color *pixels = (Color *)RL_MALLOC(width*height*sizeof(Color));
1046
1047 int seedsPerRow = width/tileSize;
1048 int seedsPerCol = height/tileSize;
1049 int seedCount = seedsPerRow*seedsPerCol;
1050
1051 Vector2 *seeds = (Vector2 *)RL_MALLOC(seedCount*sizeof(Vector2));
1052
1053 for (int i = 0; i < seedCount; i++)
1054 {
1055 int y = (i/seedsPerRow)*tileSize + GetRandomValue(0, tileSize - 1);
1056 int x = (i%seedsPerRow)*tileSize + GetRandomValue(0, tileSize - 1);
1057 seeds[i] = (Vector2){ (float)x, (float)y };
1058 }
1059
1060 for (int y = 0; y < height; y++)
1061 {
1062 int tileY = y/tileSize;
1063
1064 for (int x = 0; x < width; x++)
1065 {
1066 int tileX = x/tileSize;
1067
1068 float minDistance = 65536.0f; //(float)strtod("Inf", NULL);
1069
1070 // Check all adjacent tiles
1071 for (int i = -1; i < 2; i++)
1072 {
1073 if ((tileX + i < 0) || (tileX + i >= seedsPerRow)) continue;
1074
1075 for (int j = -1; j < 2; j++)
1076 {
1077 if ((tileY + j < 0) || (tileY + j >= seedsPerCol)) continue;
1078
1079 Vector2 neighborSeed = seeds[(tileY + j)*seedsPerRow + tileX + i];
1080
1081 float dist = (float)hypot(x - (int)neighborSeed.x, y - (int)neighborSeed.y);
1082 minDistance = (float)fmin(minDistance, dist);
1083 }
1084 }
1085
1086 // This approach seems to give good results at all tile sizes
1087 int intensity = (int)(minDistance*256.0f/tileSize);
1088 if (intensity > 255) intensity = 255;
1089
1090 unsigned char intensityUC = (unsigned char)intensity;
1091 pixels[y*width + x] = (Color){ intensityUC, intensityUC, intensityUC, 255 };
1092 }
1093 }
1094
1095 RL_FREE(seeds);
1096
1097 Image image = {
1098 .data = pixels,
1099 .width = width,
1100 .height = height,
1101 .mipmaps = 1,
1102 .format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8
1103 };
1104
1105 return image;
1106 }
1107
1108 // Generate image: grayscale image from text data
1109 Image GenImageText(int width, int height, const char *text)
1110 {
1111 Image image = { 0 };
1112
1113 int imageSize = width*height;
1114 image.width = width;
1115 image.height = height;
1116 image.format = PIXELFORMAT_UNCOMPRESSED_GRAYSCALE;
1117 image.data = RL_CALLOC(imageSize, 1);
1118 image.mipmaps = 1;
1119
1120 if (text != NULL)
1121 {
1122 int textLength = (int)strlen(text);
1123 memcpy(image.data, text, (textLength > imageSize)? imageSize : textLength);
1124 }
1125
1126 return image;
1127 }
1128 #endif // SUPPORT_IMAGE_GENERATION
1129
1130 //------------------------------------------------------------------------------------
1131 // Image manipulation functions
1132 //------------------------------------------------------------------------------------
1133 // Copy an image to a new image
1134 Image ImageCopy(Image image)
1135 {
1136 Image newImage = { 0 };
1137
1138 int width = image.width;
1139 int height = image.height;
1140 int size = 0;
1141
1142 for (int i = 0; i < image.mipmaps; i++)
1143 {
1144 size += GetPixelDataSize(width, height, image.format);
1145
1146 width /= 2;
1147 height /= 2;
1148
1149 // Security check for NPOT textures
1150 if (width < 1) width = 1;
1151 if (height < 1) height = 1;
1152 }
1153
1154 newImage.data = RL_CALLOC(size, 1);
1155
1156 if (newImage.data != NULL)
1157 {
1158 // NOTE: Size must be provided in bytes
1159 memcpy(newImage.data, image.data, size);
1160
1161 newImage.width = image.width;
1162 newImage.height = image.height;
1163 newImage.mipmaps = image.mipmaps;
1164 newImage.format = image.format;
1165 }
1166
1167 return newImage;
1168 }
1169
1170 // Create an image from another image piece
1171 Image ImageFromImage(Image image, Rectangle rec)
1172 {
1173 Image result = { 0 };
1174
1175 int bytesPerPixel = GetPixelDataSize(1, 1, image.format);
1176
1177 result.width = (int)rec.width;
1178 result.height = (int)rec.height;
1179 result.data = RL_CALLOC((int)rec.width*(int)rec.height*bytesPerPixel, 1);
1180 result.format = image.format;
1181 result.mipmaps = 1;
1182
1183 for (int y = 0; y < (int)rec.height; y++)
1184 {
1185 memcpy(((unsigned char *)result.data) + y*(int)rec.width*bytesPerPixel, ((unsigned char *)image.data) + ((y + (int)rec.y)*image.width + (int)rec.x)*bytesPerPixel, (int)rec.width*bytesPerPixel);
1186 }
1187
1188 return result;
1189 }
1190
1191 // Crop an image to area defined by a rectangle
1192 // NOTE: Security checks are performed in case rectangle goes out of bounds
1193 void ImageCrop(Image *image, Rectangle crop)
1194 {
1195 // Security check to avoid program crash
1196 if ((image->data == NULL) || (image->width == 0) || (image->height == 0)) return;
1197
1198 // Security checks to validate crop rectangle
1199 if (crop.x < 0) { crop.width += crop.x; crop.x = 0; }
1200 if (crop.y < 0) { crop.height += crop.y; crop.y = 0; }
1201 if ((crop.x + crop.width) > image->width) crop.width = image->width - crop.x;
1202 if ((crop.y + crop.height) > image->height) crop.height = image->height - crop.y;
1203 if ((crop.x > image->width) || (crop.y > image->height))
1204 {
1205 TRACELOG(LOG_WARNING, "IMAGE: Failed to crop, rectangle out of bounds");
1206 return;
1207 }
1208
1209 if (image->mipmaps > 1) TRACELOG(LOG_WARNING, "Image manipulation only applied to base mipmap level");
1210 if (image->format >= PIXELFORMAT_COMPRESSED_DXT1_RGB) TRACELOG(LOG_WARNING, "Image manipulation not supported for compressed formats");
1211 else
1212 {
1213 int bytesPerPixel = GetPixelDataSize(1, 1, image->format);
1214
1215 unsigned char *croppedData = (unsigned char *)RL_MALLOC((int)(crop.width*crop.height)*bytesPerPixel);
1216
1217 // OPTION 1: Move cropped data line-by-line
1218 for (int y = (int)crop.y, offsetSize = 0; y < (int)(crop.y + crop.height); y++)
1219 {
1220 memcpy(croppedData + offsetSize, ((unsigned char *)image->data) + (y*image->width + (int)crop.x)*bytesPerPixel, (int)crop.width*bytesPerPixel);
1221 offsetSize += ((int)crop.width*bytesPerPixel);
1222 }
1223
1224 /*
1225 // OPTION 2: Move cropped data pixel-by-pixel or byte-by-byte
1226 for (int y = (int)crop.y; y < (int)(crop.y + crop.height); y++)
1227 {
1228 for (int x = (int)crop.x; x < (int)(crop.x + crop.width); x++)
1229 {
1230 //memcpy(croppedData + ((y - (int)crop.y)*(int)crop.width + (x - (int)crop.x))*bytesPerPixel, ((unsigned char *)image->data) + (y*image->width + x)*bytesPerPixel, bytesPerPixel);
1231 for (int i = 0; i < bytesPerPixel; i++) croppedData[((y - (int)crop.y)*(int)crop.width + (x - (int)crop.x))*bytesPerPixel + i] = ((unsigned char *)image->data)[(y*image->width + x)*bytesPerPixel + i];
1232 }
1233 }
1234 */
1235
1236 RL_FREE(image->data);
1237 image->data = croppedData;
1238 image->width = (int)crop.width;
1239 image->height = (int)crop.height;
1240 }
1241 }
1242
1243 // Convert image data to desired format
1244 void ImageFormat(Image *image, int newFormat)
1245 {
1246 // Security check to avoid program crash
1247 if ((image->data == NULL) || (image->width == 0) || (image->height == 0)) return;
1248
1249 if ((newFormat != 0) && (image->format != newFormat))
1250 {
1251 if ((image->format < PIXELFORMAT_COMPRESSED_DXT1_RGB) && (newFormat < PIXELFORMAT_COMPRESSED_DXT1_RGB))
1252 {
1253 Vector4 *pixels = LoadImageDataNormalized(*image); // Supports 8 to 32 bit per channel
1254
1255 RL_FREE(image->data); // WARNING! Loosing mipmaps data --> Regenerated at the end
1256 image->data = NULL;
1257 image->format = newFormat;
1258
1259 switch (image->format)
1260 {
1261 case PIXELFORMAT_UNCOMPRESSED_GRAYSCALE:
1262 {
1263 image->data = (unsigned char *)RL_MALLOC(image->width*image->height*sizeof(unsigned char));
1264
1265 for (int i = 0; i < image->width*image->height; i++)
1266 {
1267 ((unsigned char *)image->data)[i] = (unsigned char)((pixels[i].x*0.299f + pixels[i].y*0.587f + pixels[i].z*0.114f)*255.0f);
1268 }
1269
1270 } break;
1271 case PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA:
1272 {
1273 image->data = (unsigned char *)RL_MALLOC(image->width*image->height*2*sizeof(unsigned char));
1274
1275 for (int i = 0, k = 0; i < image->width*image->height*2; i += 2, k++)
1276 {
1277 ((unsigned char *)image->data)[i] = (unsigned char)((pixels[k].x*0.299f + (float)pixels[k].y*0.587f + (float)pixels[k].z*0.114f)*255.0f);
1278 ((unsigned char *)image->data)[i + 1] = (unsigned char)(pixels[k].w*255.0f);
1279 }
1280
1281 } break;
1282 case PIXELFORMAT_UNCOMPRESSED_R5G6B5:
1283 {
1284 image->data = (unsigned short *)RL_MALLOC(image->width*image->height*sizeof(unsigned short));
1285
1286 unsigned char r = 0;
1287 unsigned char g = 0;
1288 unsigned char b = 0;
1289
1290 for (int i = 0; i < image->width*image->height; i++)
1291 {
1292 r = (unsigned char)(round(pixels[i].x*31.0f));
1293 g = (unsigned char)(round(pixels[i].y*63.0f));
1294 b = (unsigned char)(round(pixels[i].z*31.0f));
1295
1296 ((unsigned short *)image->data)[i] = (unsigned short)r << 11 | (unsigned short)g << 5 | (unsigned short)b;
1297 }
1298
1299 } break;
1300 case PIXELFORMAT_UNCOMPRESSED_R8G8B8:
1301 {
1302 image->data = (unsigned char *)RL_MALLOC(image->width*image->height*3*sizeof(unsigned char));
1303
1304 for (int i = 0, k = 0; i < image->width*image->height*3; i += 3, k++)
1305 {
1306 ((unsigned char *)image->data)[i] = (unsigned char)(pixels[k].x*255.0f);
1307 ((unsigned char *)image->data)[i + 1] = (unsigned char)(pixels[k].y*255.0f);
1308 ((unsigned char *)image->data)[i + 2] = (unsigned char)(pixels[k].z*255.0f);
1309 }
1310 } break;
1311 case PIXELFORMAT_UNCOMPRESSED_R5G5B5A1:
1312 {
1313 image->data = (unsigned short *)RL_MALLOC(image->width*image->height*sizeof(unsigned short));
1314
1315 unsigned char r = 0;
1316 unsigned char g = 0;
1317 unsigned char b = 0;
1318 unsigned char a = 0;
1319
1320 for (int i = 0; i < image->width*image->height; i++)
1321 {
1322 r = (unsigned char)(round(pixels[i].x*31.0f));
1323 g = (unsigned char)(round(pixels[i].y*31.0f));
1324 b = (unsigned char)(round(pixels[i].z*31.0f));
1325 a = (pixels[i].w > ((float)PIXELFORMAT_UNCOMPRESSED_R5G5B5A1_ALPHA_THRESHOLD/255.0f))? 1 : 0;
1326
1327 ((unsigned short *)image->data)[i] = (unsigned short)r << 11 | (unsigned short)g << 6 | (unsigned short)b << 1 | (unsigned short)a;
1328 }
1329
1330 } break;
1331 case PIXELFORMAT_UNCOMPRESSED_R4G4B4A4:
1332 {
1333 image->data = (unsigned short *)RL_MALLOC(image->width*image->height*sizeof(unsigned short));
1334
1335 unsigned char r = 0;
1336 unsigned char g = 0;
1337 unsigned char b = 0;
1338 unsigned char a = 0;
1339
1340 for (int i = 0; i < image->width*image->height; i++)
1341 {
1342 r = (unsigned char)(round(pixels[i].x*15.0f));
1343 g = (unsigned char)(round(pixels[i].y*15.0f));
1344 b = (unsigned char)(round(pixels[i].z*15.0f));
1345 a = (unsigned char)(round(pixels[i].w*15.0f));
1346
1347 ((unsigned short *)image->data)[i] = (unsigned short)r << 12 | (unsigned short)g << 8 | (unsigned short)b << 4 | (unsigned short)a;
1348 }
1349
1350 } break;
1351 case PIXELFORMAT_UNCOMPRESSED_R8G8B8A8:
1352 {
1353 image->data = (unsigned char *)RL_MALLOC(image->width*image->height*4*sizeof(unsigned char));
1354
1355 for (int i = 0, k = 0; i < image->width*image->height*4; i += 4, k++)
1356 {
1357 ((unsigned char *)image->data)[i] = (unsigned char)(pixels[k].x*255.0f);
1358 ((unsigned char *)image->data)[i + 1] = (unsigned char)(pixels[k].y*255.0f);
1359 ((unsigned char *)image->data)[i + 2] = (unsigned char)(pixels[k].z*255.0f);
1360 ((unsigned char *)image->data)[i + 3] = (unsigned char)(pixels[k].w*255.0f);
1361 }
1362 } break;
1363 case PIXELFORMAT_UNCOMPRESSED_R32:
1364 {
1365 // WARNING: Image is converted to GRAYSCALE equivalent 32bit
1366
1367 image->data = (float *)RL_MALLOC(image->width*image->height*sizeof(float));
1368
1369 for (int i = 0; i < image->width*image->height; i++)
1370 {
1371 ((float *)image->data)[i] = (float)(pixels[i].x*0.299f + pixels[i].y*0.587f + pixels[i].z*0.114f);
1372 }
1373 } break;
1374 case PIXELFORMAT_UNCOMPRESSED_R32G32B32:
1375 {
1376 image->data = (float *)RL_MALLOC(image->width*image->height*3*sizeof(float));
1377
1378 for (int i = 0, k = 0; i < image->width*image->height*3; i += 3, k++)
1379 {
1380 ((float *)image->data)[i] = pixels[k].x;
1381 ((float *)image->data)[i + 1] = pixels[k].y;
1382 ((float *)image->data)[i + 2] = pixels[k].z;
1383 }
1384 } break;
1385 case PIXELFORMAT_UNCOMPRESSED_R32G32B32A32:
1386 {
1387 image->data = (float *)RL_MALLOC(image->width*image->height*4*sizeof(float));
1388
1389 for (int i = 0, k = 0; i < image->width*image->height*4; i += 4, k++)
1390 {
1391 ((float *)image->data)[i] = pixels[k].x;
1392 ((float *)image->data)[i + 1] = pixels[k].y;
1393 ((float *)image->data)[i + 2] = pixels[k].z;
1394 ((float *)image->data)[i + 3] = pixels[k].w;
1395 }
1396 } break;
1397 case PIXELFORMAT_UNCOMPRESSED_R16:
1398 {
1399 // WARNING: Image is converted to GRAYSCALE equivalent 16bit
1400
1401 image->data = (unsigned short *)RL_MALLOC(image->width*image->height*sizeof(unsigned short));
1402
1403 for (int i = 0; i < image->width*image->height; i++)
1404 {
1405 ((unsigned short *)image->data)[i] = FloatToHalf((float)(pixels[i].x*0.299f + pixels[i].y*0.587f + pixels[i].z*0.114f));
1406 }
1407 } break;
1408 case PIXELFORMAT_UNCOMPRESSED_R16G16B16:
1409 {
1410 image->data = (unsigned short *)RL_MALLOC(image->width*image->height*3*sizeof(unsigned short));
1411
1412 for (int i = 0, k = 0; i < image->width*image->height*3; i += 3, k++)
1413 {
1414 ((unsigned short *)image->data)[i] = FloatToHalf(pixels[k].x);
1415 ((unsigned short *)image->data)[i + 1] = FloatToHalf(pixels[k].y);
1416 ((unsigned short *)image->data)[i + 2] = FloatToHalf(pixels[k].z);
1417 }
1418 } break;
1419 case PIXELFORMAT_UNCOMPRESSED_R16G16B16A16:
1420 {
1421 image->data = (unsigned short *)RL_MALLOC(image->width*image->height*4*sizeof(unsigned short));
1422
1423 for (int i = 0, k = 0; i < image->width*image->height*4; i += 4, k++)
1424 {
1425 ((unsigned short *)image->data)[i] = FloatToHalf(pixels[k].x);
1426 ((unsigned short *)image->data)[i + 1] = FloatToHalf(pixels[k].y);
1427 ((unsigned short *)image->data)[i + 2] = FloatToHalf(pixels[k].z);
1428 ((unsigned short *)image->data)[i + 3] = FloatToHalf(pixels[k].w);
1429 }
1430 } break;
1431 default: break;
1432 }
1433
1434 RL_FREE(pixels);
1435 pixels = NULL;
1436
1437 // In case original image had mipmaps, generate mipmaps for formatted image
1438 // NOTE: Original mipmaps are replaced by new ones, if custom mipmaps were used, they are lost
1439 if (image->mipmaps > 1)
1440 {
1441 image->mipmaps = 1;
1442 if (image->data != NULL) ImageMipmaps(image);
1443 }
1444 }
1445 else TRACELOG(LOG_WARNING, "IMAGE: Data format is compressed, can not be converted");
1446 }
1447 }
1448
1449 // Create an image from text (default font)
1450 Image ImageText(const char *text, int fontSize, Color color)
1451 {
1452 Image imText = { 0 };
1453 #if SUPPORT_MODULE_RTEXT
1454 int defaultFontSize = 10; // Default Font chars height in pixel
1455 if (fontSize < defaultFontSize) fontSize = defaultFontSize;
1456 int spacing = fontSize/defaultFontSize;
1457 imText = ImageTextEx(GetFontDefault(), text, (float)fontSize, (float)spacing, color); // WARNING: Module required: rtext
1458 #else
1459 imText = GenImageColor(200, 60, BLACK); // Generating placeholder black image rectangle
1460 TRACELOG(LOG_WARNING, "IMAGE: ImageTextEx() requires module: rtext");
1461 #endif
1462 return imText;
1463 }
1464
1465 // Create an image from text (custom sprite font)
1466 // WARNING: Module required: rtext
1467 Image ImageTextEx(Font font, const char *text, float fontSize, float spacing, Color tint)
1468 {
1469 Image imText = { 0 };
1470 #if SUPPORT_MODULE_RTEXT
1471 if (text == NULL) return imText;
1472
1473 int textLength = (int)strlen(text); // Get length of text in bytes
1474 int textOffsetX = 0; // Image drawing position X
1475 int textOffsetY = 0; // Offset between lines (on linebreak '\n')
1476
1477 // NOTE: Text image is generated at font base size, later scaled to desired font size
1478 Vector2 imSize = MeasureTextEx(font, text, (float)font.baseSize, spacing); // WARNING: Module required: rtext
1479 Vector2 textSize = MeasureTextEx(font, text, fontSize, spacing);
1480
1481 // Create image to store text
1482 imText = GenImageColor((int)imSize.x, (int)imSize.y, BLANK);
1483
1484 for (int i = 0; i < textLength;)
1485 {
1486 // Get next codepoint from byte string and glyph index in font
1487 int codepointByteCount = 0;
1488 int codepoint = GetCodepointNext(&text[i], &codepointByteCount); // WARNING: Module required: rtext
1489 int index = GetGlyphIndex(font, codepoint); // WARNING: Module required: rtext
1490
1491 if (codepoint == '\n')
1492 {
1493 // NOTE: Fixed line spacing of 1.5 line-height
1494 // TODO: Support custom line spacing defined by user
1495 textOffsetY += (font.baseSize + font.baseSize/2);
1496 textOffsetX = 0;
1497 }
1498 else
1499 {
1500 if ((codepoint != ' ') && (codepoint != '\t'))
1501 {
1502 Rectangle rec = { (float)(textOffsetX + font.glyphs[index].offsetX), (float)(textOffsetY + font.glyphs[index].offsetY), (float)font.recs[index].width, (float)font.recs[index].height };
1503 ImageDraw(&imText, font.glyphs[index].image, (Rectangle){ 0, 0, (float)font.glyphs[index].image.width, (float)font.glyphs[index].image.height }, rec, tint);
1504 }
1505
1506 if (font.glyphs[index].advanceX == 0) textOffsetX += (int)(font.recs[index].width + spacing);
1507 else textOffsetX += font.glyphs[index].advanceX + (int)spacing;
1508 }
1509
1510 i += codepointByteCount; // Move text bytes counter to next codepoint
1511 }
1512
1513 // Scale image depending on text size
1514 if (textSize.y != imSize.y)
1515 {
1516 float scaleFactor = textSize.y/imSize.y;
1517 TRACELOG(LOG_INFO, "IMAGE: Text scaled by factor: %f", scaleFactor);
1518
1519 // Using nearest-neighbor scaling algorithm for default font
1520 // TODO: Allow defining the preferred scaling mechanism externally
1521 if (font.texture.id == GetFontDefault().texture.id) ImageResizeNN(&imText, (int)(imSize.x*scaleFactor), (int)(imSize.y*scaleFactor));
1522 else ImageResize(&imText, (int)(imSize.x*scaleFactor), (int)(imSize.y*scaleFactor));
1523 }
1524 #else
1525 imText = GenImageColor(200, 60, BLACK); // Generating placeholder black image rectangle
1526 TRACELOG(LOG_WARNING, "IMAGE: ImageTextEx() requires module: rtext");
1527 #endif
1528 return imText;
1529 }
1530
1531 // Create an image from a selected channel of another image
1532 Image ImageFromChannel(Image image, int selectedChannel)
1533 {
1534 Image result = { 0 };
1535
1536 if ((image.data == NULL) || (image.width == 0) || (image.height == 0)) return result; // Security check
1537
1538 // Check selected channel is valid
1539 if (selectedChannel < 0)
1540 {
1541 TRACELOG(LOG_WARNING, "Channel cannot be negative. Setting channel to 0.");
1542 selectedChannel = 0;
1543 }
1544
1545 if (image.format == PIXELFORMAT_UNCOMPRESSED_GRAYSCALE ||
1546 image.format == PIXELFORMAT_UNCOMPRESSED_R32 ||
1547 image.format == PIXELFORMAT_UNCOMPRESSED_R16)
1548 {
1549 if (selectedChannel > 0)
1550 {
1551 TRACELOG(LOG_WARNING, "This image has only 1 channel. Setting channel to it.");
1552 selectedChannel = 0;
1553 }
1554 }
1555 else if (image.format == PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA)
1556 {
1557 if (selectedChannel > 1)
1558 {
1559 TRACELOG(LOG_WARNING, "This image has only 2 channels. Setting channel to alpha.");
1560 selectedChannel = 1;
1561 }
1562 }
1563 else if (image.format == PIXELFORMAT_UNCOMPRESSED_R5G6B5 ||
1564 image.format == PIXELFORMAT_UNCOMPRESSED_R8G8B8 ||
1565 image.format == PIXELFORMAT_UNCOMPRESSED_R32G32B32 ||
1566 image.format == PIXELFORMAT_UNCOMPRESSED_R16G16B16)
1567 {
1568 if (selectedChannel > 2)
1569 {
1570 TRACELOG(LOG_WARNING, "This image has only 3 channels. Setting channel to red.");
1571 selectedChannel = 0;
1572 }
1573 }
1574
1575 // Check for RGBA formats
1576 if (selectedChannel > 3)
1577 {
1578 TRACELOG(LOG_WARNING, "ImageFromChannel supports channels 0 to 3 (RGBA). Setting channel to alpha.");
1579 selectedChannel = 3;
1580 }
1581
1582 // TODO: Consider other one-channel formats: R16, R32
1583 result.format = PIXELFORMAT_UNCOMPRESSED_GRAYSCALE;
1584 result.height = image.height;
1585 result.width = image.width;
1586 result.mipmaps = 1;
1587
1588 unsigned char *pixels = (unsigned char *)RL_CALLOC(image.width*image.height, sizeof(unsigned char)); // Values from 0 to 255
1589
1590 if (image.format >= PIXELFORMAT_COMPRESSED_DXT1_RGB) TRACELOG(LOG_WARNING, "IMAGE: Pixel data retrieval not supported for compressed image formats");
1591 else
1592 {
1593 for (int i = 0, k = 0; i < image.width*image.height; i++)
1594 {
1595 float pixelValue = -1;
1596 switch (image.format)
1597 {
1598 case PIXELFORMAT_UNCOMPRESSED_GRAYSCALE:
1599 {
1600 pixelValue = (float)((unsigned char *)image.data)[i + selectedChannel]/255.0f;
1601
1602 } break;
1603 case PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA:
1604 {
1605 pixelValue = (float)((unsigned char *)image.data)[k + selectedChannel]/255.0f;
1606 k += 2;
1607
1608 } break;
1609 case PIXELFORMAT_UNCOMPRESSED_R5G5B5A1:
1610 {
1611 unsigned short pixel = ((unsigned short *)image.data)[i];
1612
1613 if (selectedChannel == 0) pixelValue = (float)((pixel & 0b1111100000000000) >> 11)*(1.0f/31);
1614 else if (selectedChannel == 1) pixelValue = (float)((pixel & 0b0000011111000000) >> 6)*(1.0f/31);
1615 else if (selectedChannel == 2) pixelValue = (float)((pixel & 0b0000000000111110) >> 1)*(1.0f/31);
1616 else if (selectedChannel == 3) pixelValue = ((pixel & 0b0000000000000001) == 0)? 0.0f : 1.0f;
1617
1618 } break;
1619 case PIXELFORMAT_UNCOMPRESSED_R5G6B5:
1620 {
1621 unsigned short pixel = ((unsigned short *)image.data)[i];
1622
1623 if (selectedChannel == 0) pixelValue = (float)((pixel & 0b1111100000000000) >> 11)*(1.0f/31);
1624 else if (selectedChannel == 1) pixelValue = (float)((pixel & 0b0000011111100000) >> 5)*(1.0f/63);
1625 else if (selectedChannel == 2) pixelValue = (float)(pixel & 0b0000000000011111)*(1.0f/31);
1626
1627 } break;
1628 case PIXELFORMAT_UNCOMPRESSED_R4G4B4A4:
1629 {
1630 unsigned short pixel = ((unsigned short *)image.data)[i];
1631
1632 if (selectedChannel == 0) pixelValue = (float)((pixel & 0b1111000000000000) >> 12)*(1.0f/15);
1633 else if (selectedChannel == 1) pixelValue = (float)((pixel & 0b0000111100000000) >> 8)*(1.0f/15);
1634 else if (selectedChannel == 2) pixelValue = (float)((pixel & 0b0000000011110000) >> 4)*(1.0f/15);
1635 else if (selectedChannel == 3) pixelValue = (float)(pixel & 0b0000000000001111)*(1.0f/15);
1636
1637 } break;
1638 case PIXELFORMAT_UNCOMPRESSED_R8G8B8A8:
1639 {
1640 pixelValue = (float)((unsigned char *)image.data)[k + selectedChannel]/255.0f;
1641 k += 4;
1642
1643 } break;
1644 case PIXELFORMAT_UNCOMPRESSED_R8G8B8:
1645 {
1646 pixelValue = (float)((unsigned char *)image.data)[k + selectedChannel]/255.0f;
1647 k += 3;
1648
1649 } break;
1650 case PIXELFORMAT_UNCOMPRESSED_R32:
1651 {
1652 pixelValue = ((float *)image.data)[k];
1653 k += 1;
1654
1655 } break;
1656 case PIXELFORMAT_UNCOMPRESSED_R32G32B32:
1657 {
1658 pixelValue = ((float *)image.data)[k + selectedChannel];
1659 k += 3;
1660
1661 } break;
1662 case PIXELFORMAT_UNCOMPRESSED_R32G32B32A32:
1663 {
1664 pixelValue = ((float *)image.data)[k + selectedChannel];
1665 k += 4;
1666
1667 } break;
1668 case PIXELFORMAT_UNCOMPRESSED_R16:
1669 {
1670 pixelValue = HalfToFloat(((unsigned short *)image.data)[k]);
1671 k += 1;
1672
1673 } break;
1674 case PIXELFORMAT_UNCOMPRESSED_R16G16B16:
1675 {
1676 pixelValue = HalfToFloat(((unsigned short *)image.data)[k+selectedChannel]);
1677 k += 3;
1678
1679 } break;
1680 case PIXELFORMAT_UNCOMPRESSED_R16G16B16A16:
1681 {
1682 pixelValue = HalfToFloat(((unsigned short *)image.data)[k + selectedChannel]);
1683 k += 4;
1684
1685 } break;
1686 default: break;
1687 }
1688
1689 pixels[i] = (unsigned char)(pixelValue*255);
1690 }
1691 }
1692
1693 result.data = pixels;
1694
1695 return result;
1696 }
1697
1698 // Resize and image to new size using Nearest-Neighbor scaling algorithm
1699 void ImageResizeNN(Image *image, int newWidth, int newHeight)
1700 {
1701 // Security check to avoid program crash
1702 if ((image->data == NULL) || (image->width == 0) || (image->height == 0)) return;
1703
1704 Color *pixels = LoadImageColors(*image);
1705 Color *output = (Color *)RL_MALLOC(newWidth*newHeight*sizeof(Color));
1706
1707 // EDIT: added +1 to account for an early rounding problem
1708 int xRatio = (int)((image->width << 16)/newWidth) + 1;
1709 int yRatio = (int)((image->height << 16)/newHeight) + 1;
1710
1711 int x2 = 0;
1712 int y2 = 0;
1713 for (int y = 0; y < newHeight; y++)
1714 {
1715 for (int x = 0; x < newWidth; x++)
1716 {
1717 x2 = ((x*xRatio) >> 16);
1718 y2 = ((y*yRatio) >> 16);
1719
1720 output[(y*newWidth) + x] = pixels[(y2*image->width) + x2] ;
1721 }
1722 }
1723
1724 int format = image->format;
1725
1726 RL_FREE(image->data);
1727
1728 image->data = output;
1729 image->width = newWidth;
1730 image->height = newHeight;
1731 image->format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8;
1732
1733 ImageFormat(image, format); // Reformat 32bit RGBA image to original format
1734
1735 UnloadImageColors(pixels);
1736 }
1737
1738 // Resize and image to new size
1739 // NOTE: Uses stb default scaling filters (both bicubic):
1740 // STBIR_DEFAULT_FILTER_UPSAMPLE STBIR_FILTER_CATMULLROM
1741 // STBIR_DEFAULT_FILTER_DOWNSAMPLE STBIR_FILTER_MITCHELL (high-quality Catmull-Rom)
1742 void ImageResize(Image *image, int newWidth, int newHeight)
1743 {
1744 // Security check to avoid program crash
1745 if ((image->data == NULL) || (image->width == 0) || (image->height == 0)) return;
1746
1747 // Check if a fast path can be used on image scaling
1748 // It can be for 8 bit per channel images with 1 to 4 channels per pixel
1749 if ((image->format == PIXELFORMAT_UNCOMPRESSED_GRAYSCALE) ||
1750 (image->format == PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA) ||
1751 (image->format == PIXELFORMAT_UNCOMPRESSED_R8G8B8) ||
1752 (image->format == PIXELFORMAT_UNCOMPRESSED_R8G8B8A8))
1753 {
1754 int bytesPerPixel = GetPixelDataSize(1, 1, image->format);
1755 unsigned char *output = (unsigned char *)RL_MALLOC(newWidth*newHeight*bytesPerPixel);
1756
1757 switch (image->format)
1758 {
1759 case PIXELFORMAT_UNCOMPRESSED_GRAYSCALE: stbir_resize_uint8_linear((unsigned char *)image->data, image->width, image->height, 0, output, newWidth, newHeight, 0, (stbir_pixel_layout)1); break;
1760 case PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA: stbir_resize_uint8_linear((unsigned char *)image->data, image->width, image->height, 0, output, newWidth, newHeight, 0, (stbir_pixel_layout)2); break;
1761 case PIXELFORMAT_UNCOMPRESSED_R8G8B8: stbir_resize_uint8_linear((unsigned char *)image->data, image->width, image->height, 0, output, newWidth, newHeight, 0, (stbir_pixel_layout)3); break;
1762 case PIXELFORMAT_UNCOMPRESSED_R8G8B8A8: stbir_resize_uint8_linear((unsigned char *)image->data, image->width, image->height, 0, output, newWidth, newHeight, 0, (stbir_pixel_layout)4); break;
1763 default: break;
1764 }
1765
1766 RL_FREE(image->data);
1767 image->data = output;
1768 image->width = newWidth;
1769 image->height = newHeight;
1770 }
1771 else
1772 {
1773 // Get data as Color pixels array to work with it
1774 Color *pixels = LoadImageColors(*image);
1775 Color *output = (Color *)RL_MALLOC(newWidth*newHeight*sizeof(Color));
1776
1777 // NOTE: Color data is cast to (unsigned char *), there shouldn't been any problem...
1778 stbir_resize_uint8_linear((unsigned char *)pixels, image->width, image->height, 0, (unsigned char *)output, newWidth, newHeight, 0, (stbir_pixel_layout)4);
1779
1780 int format = image->format;
1781
1782 UnloadImageColors(pixels);
1783 RL_FREE(image->data);
1784
1785 image->data = output;
1786 image->width = newWidth;
1787 image->height = newHeight;
1788 image->format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8;
1789
1790 ImageFormat(image, format); // Reformat 32bit RGBA image to original format
1791 }
1792 }
1793
1794 // Resize canvas and fill with color
1795 // NOTE: Resize offset is relative to the top-left corner of the original image
1796 void ImageResizeCanvas(Image *image, int newWidth, int newHeight, int offsetX, int offsetY, Color fill)
1797 {
1798 // Security check to avoid program crash
1799 if ((image->data == NULL) || (image->width == 0) || (image->height == 0)) return;
1800
1801 if (image->mipmaps > 1) TRACELOG(LOG_WARNING, "Image manipulation only applied to base mipmap level");
1802 if (image->format >= PIXELFORMAT_COMPRESSED_DXT1_RGB) TRACELOG(LOG_WARNING, "Image manipulation not supported for compressed formats");
1803 else if ((newWidth != image->width) || (newHeight != image->height))
1804 {
1805 Rectangle srcRec = { 0, 0, (float)image->width, (float)image->height };
1806 Vector2 dstPos = { (float)offsetX, (float)offsetY };
1807
1808 if (offsetX < 0)
1809 {
1810 srcRec.x = (float)-offsetX;
1811 srcRec.width += (float)offsetX;
1812 dstPos.x = 0;
1813 }
1814 else if ((offsetX + image->width) > newWidth) srcRec.width = (float)(newWidth - offsetX);
1815
1816 if (offsetY < 0)
1817 {
1818 srcRec.y = (float)-offsetY;
1819 srcRec.height += (float)offsetY;
1820 dstPos.y = 0;
1821 }
1822 else if ((offsetY + image->height) > newHeight) srcRec.height = (float)(newHeight - offsetY);
1823
1824 if (newWidth < srcRec.width) srcRec.width = (float)newWidth;
1825 if (newHeight < srcRec.height) srcRec.height = (float)newHeight;
1826
1827 int bytesPerPixel = GetPixelDataSize(1, 1, image->format);
1828 unsigned char *resizedData = (unsigned char *)RL_CALLOC(newWidth*newHeight*bytesPerPixel, 1);
1829
1830 // Fill resized canvas with fill color
1831 // Set first pixel with image->format
1832 SetPixelColor(resizedData, fill, image->format);
1833
1834 // Fill remaining bytes of first row
1835 for (int x = 1; x < newWidth; x++)
1836 {
1837 memcpy(resizedData + x*bytesPerPixel, resizedData, bytesPerPixel);
1838 }
1839 // Copy the first row into the other rows
1840 for (int y = 1; y < newHeight; y++)
1841 {
1842 memcpy(resizedData + y*newWidth*bytesPerPixel, resizedData, newWidth*bytesPerPixel);
1843 }
1844
1845 // Copy old image to resized canvas
1846 int dstOffsetSize = ((int)dstPos.y*newWidth + (int)dstPos.x)*bytesPerPixel;
1847
1848 for (int y = 0; y < (int)srcRec.height; y++)
1849 {
1850 memcpy(resizedData + dstOffsetSize, ((unsigned char *)image->data) + ((y + (int)srcRec.y)*image->width + (int)srcRec.x)*bytesPerPixel, (int)srcRec.width*bytesPerPixel);
1851 dstOffsetSize += (newWidth*bytesPerPixel);
1852 }
1853
1854 RL_FREE(image->data);
1855 image->data = resizedData;
1856 image->width = newWidth;
1857 image->height = newHeight;
1858 }
1859 }
1860
1861 // Convert image to POT (power-of-two)
1862 // NOTE: It could be useful on OpenGL ES 2.0 (RPI, HTML5)
1863 void ImageToPOT(Image *image, Color fill)
1864 {
1865 // Security check to avoid program crash
1866 if ((image->data == NULL) || (image->width == 0) || (image->height == 0)) return;
1867
1868 // Calculate next power-of-two values
1869 // NOTE: Add the required amount of pixels at the right and bottom sides of image...
1870 int potWidth = (int)powf(2, ceilf(logf((float)image->width)/logf(2)));
1871 int potHeight = (int)powf(2, ceilf(logf((float)image->height)/logf(2)));
1872
1873 // Check if POT texture generation is required (if texture is not already POT)
1874 if ((potWidth != image->width) || (potHeight != image->height)) ImageResizeCanvas(image, potWidth, potHeight, 0, 0, fill);
1875 }
1876
1877 // Crop image depending on alpha value
1878 // NOTE: Threshold is defined as a percentage: 0.0f -> 1.0f
1879 void ImageAlphaCrop(Image *image, float threshold)
1880 {
1881 // Security check to avoid program crash
1882 if ((image->data == NULL) || (image->width == 0) || (image->height == 0)) return;
1883
1884 Rectangle crop = GetImageAlphaBorder(*image, threshold);
1885
1886 // Crop if rectangle is valid
1887 if (((int)crop.width != 0) && ((int)crop.height != 0)) ImageCrop(image, crop);
1888 }
1889
1890 // Clear alpha channel to desired color
1891 // NOTE: Threshold defines the alpha limit, 0.0f to 1.0f
1892 void ImageAlphaClear(Image *image, Color color, float threshold)
1893 {
1894 // Security check to avoid program crash
1895 if ((image->data == NULL) || (image->width == 0) || (image->height == 0)) return;
1896
1897 if (image->mipmaps > 1) TRACELOG(LOG_WARNING, "Image manipulation only applied to base mipmap level");
1898 if (image->format >= PIXELFORMAT_COMPRESSED_DXT1_RGB) TRACELOG(LOG_WARNING, "Image manipulation not supported for compressed formats");
1899 else
1900 {
1901 switch (image->format)
1902 {
1903 case PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA:
1904 {
1905 unsigned char thresholdValue = (unsigned char)(threshold*255.0f);
1906 for (int i = 1; i < image->width*image->height*2; i += 2)
1907 {
1908 if (((unsigned char *)image->data)[i] <= thresholdValue)
1909 {
1910 ((unsigned char *)image->data)[i - 1] = color.r;
1911 ((unsigned char *)image->data)[i] = color.a;
1912 }
1913 }
1914 } break;
1915 case PIXELFORMAT_UNCOMPRESSED_R5G5B5A1:
1916 {
1917 unsigned char thresholdValue = ((threshold < 0.5f)? 0 : 1);
1918
1919 unsigned char r = (unsigned char)(round((float)color.r*31.0f));
1920 unsigned char g = (unsigned char)(round((float)color.g*31.0f));
1921 unsigned char b = (unsigned char)(round((float)color.b*31.0f));
1922 unsigned char a = (color.a < 128)? 0 : 1;
1923
1924 for (int i = 0; i < image->width*image->height; i++)
1925 {
1926 if ((((unsigned short *)image->data)[i] & 0b0000000000000001) <= thresholdValue)
1927 {
1928 ((unsigned short *)image->data)[i] = (unsigned short)r << 11 | (unsigned short)g << 6 | (unsigned short)b << 1 | (unsigned short)a;
1929 }
1930 }
1931 } break;
1932 case PIXELFORMAT_UNCOMPRESSED_R4G4B4A4:
1933 {
1934 unsigned char thresholdValue = (unsigned char)(threshold*15.0f);
1935
1936 unsigned char r = (unsigned char)(round((float)color.r*15.0f));
1937 unsigned char g = (unsigned char)(round((float)color.g*15.0f));
1938 unsigned char b = (unsigned char)(round((float)color.b*15.0f));
1939 unsigned char a = (unsigned char)(round((float)color.a*15.0f));
1940
1941 for (int i = 0; i < image->width*image->height; i++)
1942 {
1943 if ((((unsigned short *)image->data)[i] & 0x000f) <= thresholdValue)
1944 {
1945 ((unsigned short *)image->data)[i] = (unsigned short)r << 12 | (unsigned short)g << 8 | (unsigned short)b << 4 | (unsigned short)a;
1946 }
1947 }
1948 } break;
1949 case PIXELFORMAT_UNCOMPRESSED_R8G8B8A8:
1950 {
1951 unsigned char thresholdValue = (unsigned char)(threshold*255.0f);
1952 for (int i = 3; i < image->width*image->height*4; i += 4)
1953 {
1954 if (((unsigned char *)image->data)[i] <= thresholdValue)
1955 {
1956 ((unsigned char *)image->data)[i - 3] = color.r;
1957 ((unsigned char *)image->data)[i - 2] = color.g;
1958 ((unsigned char *)image->data)[i - 1] = color.b;
1959 ((unsigned char *)image->data)[i] = color.a;
1960 }
1961 }
1962 } break;
1963 case PIXELFORMAT_UNCOMPRESSED_R32G32B32A32:
1964 {
1965 for (int i = 3; i < image->width*image->height*4; i += 4)
1966 {
1967 if (((float *)image->data)[i] <= threshold)
1968 {
1969 ((float *)image->data)[i - 3] = (float)color.r/255.0f;
1970 ((float *)image->data)[i - 2] = (float)color.g/255.0f;
1971 ((float *)image->data)[i - 1] = (float)color.b/255.0f;
1972 ((float *)image->data)[i] = (float)color.a/255.0f;
1973 }
1974 }
1975 } break;
1976 case PIXELFORMAT_UNCOMPRESSED_R16G16B16A16:
1977 {
1978 for (int i = 3; i < image->width*image->height*4; i += 4)
1979 {
1980 if (HalfToFloat(((unsigned short *)image->data)[i]) <= threshold)
1981 {
1982 ((unsigned short *)image->data)[i - 3] = FloatToHalf((float)color.r/255.0f);
1983 ((unsigned short *)image->data)[i - 2] = FloatToHalf((float)color.g/255.0f);
1984 ((unsigned short *)image->data)[i - 1] = FloatToHalf((float)color.b/255.0f);
1985 ((unsigned short *)image->data)[i] = FloatToHalf((float)color.a/255.0f);
1986 }
1987 }
1988 } break;
1989 default: break;
1990 }
1991 }
1992 }
1993
1994 // Apply alpha mask to image
1995 // NOTE 1: Returned image is GRAY_ALPHA (16bit) or RGBA (32bit)
1996 // NOTE 2: alphaMask should be same size as image
1997 void ImageAlphaMask(Image *image, Image alphaMask)
1998 {
1999 if ((image->width != alphaMask.width) || (image->height != alphaMask.height))
2000 {
2001 TRACELOG(LOG_WARNING, "IMAGE: Alpha mask must be same size as image");
2002 }
2003 else if (image->format >= PIXELFORMAT_COMPRESSED_DXT1_RGB)
2004 {
2005 TRACELOG(LOG_WARNING, "IMAGE: Alpha mask can not be applied to compressed data formats");
2006 }
2007 else
2008 {
2009 // Force mask to be Grayscale
2010 Image mask = ImageCopy(alphaMask);
2011 if (mask.format != PIXELFORMAT_UNCOMPRESSED_GRAYSCALE) ImageFormat(&mask, PIXELFORMAT_UNCOMPRESSED_GRAYSCALE);
2012
2013 // In case image is only grayscale, add alpha channel
2014 if (image->format == PIXELFORMAT_UNCOMPRESSED_GRAYSCALE)
2015 {
2016 unsigned char *data = (unsigned char *)RL_MALLOC(image->width*image->height*2);
2017
2018 // Apply alpha mask to alpha channel
2019 for (int i = 0, k = 0; (i < mask.width*mask.height) || (i < image->width*image->height); i++, k += 2)
2020 {
2021 data[k] = ((unsigned char *)image->data)[i];
2022 data[k + 1] = ((unsigned char *)mask.data)[i];
2023 }
2024
2025 RL_FREE(image->data);
2026 image->data = data;
2027 image->format = PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA;
2028 }
2029 else
2030 {
2031 // Convert image to RGBA
2032 if (image->format != PIXELFORMAT_UNCOMPRESSED_R8G8B8A8) ImageFormat(image, PIXELFORMAT_UNCOMPRESSED_R8G8B8A8);
2033
2034 // Apply alpha mask to alpha channel
2035 for (int i = 0, k = 3; (i < mask.width*mask.height) || (i < image->width*image->height); i++, k += 4)
2036 {
2037 ((unsigned char *)image->data)[k] = ((unsigned char *)mask.data)[i];
2038 }
2039 }
2040
2041 UnloadImage(mask);
2042 }
2043 }
2044
2045 // Premultiply alpha channel
2046 void ImageAlphaPremultiply(Image *image)
2047 {
2048 // Security check to avoid program crash
2049 if ((image->data == NULL) || (image->width == 0) || (image->height == 0)) return;
2050
2051 float alpha = 0.0f;
2052 Color *pixels = LoadImageColors(*image);
2053
2054 for (int i = 0; i < image->width*image->height; i++)
2055 {
2056 if (pixels[i].a == 0)
2057 {
2058 pixels[i].r = 0;
2059 pixels[i].g = 0;
2060 pixels[i].b = 0;
2061 }
2062 else if (pixels[i].a < 255)
2063 {
2064 alpha = (float)pixels[i].a/255.0f;
2065 pixels[i].r = (unsigned char)((float)pixels[i].r*alpha);
2066 pixels[i].g = (unsigned char)((float)pixels[i].g*alpha);
2067 pixels[i].b = (unsigned char)((float)pixels[i].b*alpha);
2068 }
2069 }
2070
2071 RL_FREE(image->data);
2072
2073 int format = image->format;
2074 image->data = pixels;
2075 image->format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8;
2076
2077 ImageFormat(image, format);
2078 }
2079
2080 // Apply box blur to image
2081 void ImageBlurGaussian(Image *image, int blurSize)
2082 {
2083 // Security check to avoid program crash
2084 if ((image->data == NULL) || (image->width == 0) || (image->height == 0)) return;
2085
2086 ImageAlphaPremultiply(image);
2087
2088 Color *pixels = LoadImageColors(*image);
2089
2090 // Loop switches between pixelsCopy1 and pixelsCopy2
2091 Vector4 *pixelsCopy1 = (Vector4 *)RL_MALLOC((image->height)*(image->width)*sizeof(Vector4));
2092 Vector4 *pixelsCopy2 = (Vector4 *)RL_MALLOC((image->height)*(image->width)*sizeof(Vector4));
2093
2094 for (int i = 0; i < (image->height*image->width); i++)
2095 {
2096 pixelsCopy1[i].x = pixels[i].r;
2097 pixelsCopy1[i].y = pixels[i].g;
2098 pixelsCopy1[i].z = pixels[i].b;
2099 pixelsCopy1[i].w = pixels[i].a;
2100 }
2101
2102 // Repeated convolution of rectangular window signal by itself converges to a gaussian distribution
2103 for (int j = 0; j < GAUSSIAN_BLUR_ITERATIONS; j++)
2104 {
2105 // Horizontal motion blur
2106 for (int row = 0; row < image->height; row++)
2107 {
2108 float avgR = 0.0f;
2109 float avgG = 0.0f;
2110 float avgB = 0.0f;
2111 float avgAlpha = 0.0f;
2112 int convolutionSize = blurSize;
2113
2114 for (int i = 0; i < blurSize; i++)
2115 {
2116 avgR += pixelsCopy1[row*image->width + i].x;
2117 avgG += pixelsCopy1[row*image->width + i].y;
2118 avgB += pixelsCopy1[row*image->width + i].z;
2119 avgAlpha += pixelsCopy1[row*image->width + i].w;
2120 }
2121
2122 for (int x = 0; x < image->width; x++)
2123 {
2124 if (x-blurSize-1 >= 0)
2125 {
2126 avgR -= pixelsCopy1[row*image->width + x-blurSize-1].x;
2127 avgG -= pixelsCopy1[row*image->width + x-blurSize-1].y;
2128 avgB -= pixelsCopy1[row*image->width + x-blurSize-1].z;
2129 avgAlpha -= pixelsCopy1[row*image->width + x-blurSize-1].w;
2130 convolutionSize--;
2131 }
2132
2133 if (x+blurSize < image->width)
2134 {
2135 avgR += pixelsCopy1[row*image->width + x+blurSize].x;
2136 avgG += pixelsCopy1[row*image->width + x+blurSize].y;
2137 avgB += pixelsCopy1[row*image->width + x+blurSize].z;
2138 avgAlpha += pixelsCopy1[row*image->width + x+blurSize].w;
2139 convolutionSize++;
2140 }
2141
2142 pixelsCopy2[row*image->width + x].x = avgR/convolutionSize;
2143 pixelsCopy2[row*image->width + x].y = avgG/convolutionSize;
2144 pixelsCopy2[row*image->width + x].z = avgB/convolutionSize;
2145 pixelsCopy2[row*image->width + x].w = avgAlpha/convolutionSize;
2146 }
2147 }
2148
2149 // Vertical motion blur
2150 for (int col = 0; col < image->width; col++)
2151 {
2152 float avgR = 0.0f;
2153 float avgG = 0.0f;
2154 float avgB = 0.0f;
2155 float avgAlpha = 0.0f;
2156 int convolutionSize = blurSize;
2157
2158 for (int i = 0; i < blurSize; i++)
2159 {
2160 avgR += pixelsCopy2[i*image->width + col].x;
2161 avgG += pixelsCopy2[i*image->width + col].y;
2162 avgB += pixelsCopy2[i*image->width + col].z;
2163 avgAlpha += pixelsCopy2[i*image->width + col].w;
2164 }
2165
2166 for (int y = 0; y < image->height; y++)
2167 {
2168 if (y-blurSize-1 >= 0)
2169 {
2170 avgR -= pixelsCopy2[(y-blurSize-1)*image->width + col].x;
2171 avgG -= pixelsCopy2[(y-blurSize-1)*image->width + col].y;
2172 avgB -= pixelsCopy2[(y-blurSize-1)*image->width + col].z;
2173 avgAlpha -= pixelsCopy2[(y-blurSize-1)*image->width + col].w;
2174 convolutionSize--;
2175 }
2176 if (y+blurSize < image->height)
2177 {
2178 avgR += pixelsCopy2[(y+blurSize)*image->width + col].x;
2179 avgG += pixelsCopy2[(y+blurSize)*image->width + col].y;
2180 avgB += pixelsCopy2[(y+blurSize)*image->width + col].z;
2181 avgAlpha += pixelsCopy2[(y+blurSize)*image->width + col].w;
2182 convolutionSize++;
2183 }
2184
2185 pixelsCopy1[y*image->width + col].x = (unsigned char) (avgR/convolutionSize);
2186 pixelsCopy1[y*image->width + col].y = (unsigned char) (avgG/convolutionSize);
2187 pixelsCopy1[y*image->width + col].z = (unsigned char) (avgB/convolutionSize);
2188 pixelsCopy1[y*image->width + col].w = (unsigned char) (avgAlpha/convolutionSize);
2189 }
2190 }
2191 }
2192
2193 // Reverse premultiply
2194 for (int i = 0; i < (image->width)*(image->height); i++)
2195 {
2196 if (pixelsCopy1[i].w == 0.0f)
2197 {
2198 pixels[i].r = 0;
2199 pixels[i].g = 0;
2200 pixels[i].b = 0;
2201 pixels[i].a = 0;
2202 }
2203 else if (pixelsCopy1[i].w <= 255.0f)
2204 {
2205 float alpha = (float)pixelsCopy1[i].w/255.0f;
2206 pixels[i].r = (unsigned char)fminf((float)pixelsCopy1[i].x/alpha, 255.0);
2207 pixels[i].g = (unsigned char)fminf((float)pixelsCopy1[i].y/alpha, 255.0);
2208 pixels[i].b = (unsigned char)fminf((float)pixelsCopy1[i].z/alpha, 255.0);
2209 pixels[i].a = (unsigned char) pixelsCopy1[i].w;
2210 }
2211 }
2212
2213 int format = image->format;
2214 RL_FREE(image->data);
2215 RL_FREE(pixelsCopy1);
2216 RL_FREE(pixelsCopy2);
2217
2218 image->data = pixels;
2219 image->format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8;
2220
2221 ImageFormat(image, format);
2222 }
2223
2224 // Apply custom square convolution kernel to image
2225 // NOTE: The convolution kernel matrix is expected to be square
2226 void ImageKernelConvolution(Image *image, const float *kernel, int kernelSize)
2227 {
2228 if ((image->data == NULL) || (image->width == 0) || (image->height == 0) || kernel == NULL) return;
2229
2230 int kernelWidth = (int)sqrtf((float)kernelSize);
2231
2232 if (kernelWidth*kernelWidth != kernelSize)
2233 {
2234 TRACELOG(LOG_WARNING, "IMAGE: Convolution kernel must be square to be applied");
2235 return;
2236 }
2237
2238 Color *pixels = LoadImageColors(*image);
2239
2240 Vector4 *imageCopy2 = (Vector4 *)RL_MALLOC((image->height)*(image->width)*sizeof(Vector4));
2241 Vector4 *temp = (Vector4 *)RL_MALLOC(kernelSize*sizeof(Vector4));
2242
2243 for (int i = 0; i < kernelSize; i++)
2244 {
2245 temp[i].x = 0.0f;
2246 temp[i].y = 0.0f;
2247 temp[i].z = 0.0f;
2248 temp[i].w = 0.0f;
2249 }
2250
2251 float rRes = 0.0f;
2252 float gRes = 0.0f;
2253 float bRes = 0.0f;
2254 float aRes = 0.0f;
2255
2256 int startRange = 0, endRange = 0;
2257
2258 if (kernelWidth%2 == 0)
2259 {
2260 startRange = -kernelWidth/2;
2261 endRange = kernelWidth/2;
2262 }
2263 else
2264 {
2265 startRange = -kernelWidth/2;
2266 endRange = kernelWidth/2 + 1;
2267 }
2268
2269 for (int x = 0; x < image->height; x++)
2270 {
2271 for (int y = 0; y < image->width; y++)
2272 {
2273 for (int xk = startRange; xk < endRange; xk++)
2274 {
2275 for (int yk = startRange; yk < endRange; yk++)
2276 {
2277 int xkabs = xk + kernelWidth/2;
2278 int ykabs = yk + kernelWidth/2;
2279 unsigned int imgindex = image->width*(x + xk) + (y + yk);
2280
2281 if (imgindex >= (unsigned int)(image->width*image->height))
2282 {
2283 temp[kernelWidth*xkabs + ykabs].x = 0.0f;
2284 temp[kernelWidth*xkabs + ykabs].y = 0.0f;
2285 temp[kernelWidth*xkabs + ykabs].z = 0.0f;
2286 temp[kernelWidth*xkabs + ykabs].w = 0.0f;
2287 }
2288 else
2289 {
2290 temp[kernelWidth*xkabs + ykabs].x = ((float)pixels[imgindex].r)/255.0f*kernel[kernelWidth*xkabs + ykabs];
2291 temp[kernelWidth*xkabs + ykabs].y = ((float)pixels[imgindex].g)/255.0f*kernel[kernelWidth*xkabs + ykabs];
2292 temp[kernelWidth*xkabs + ykabs].z = ((float)pixels[imgindex].b)/255.0f*kernel[kernelWidth*xkabs + ykabs];
2293 temp[kernelWidth*xkabs + ykabs].w = ((float)pixels[imgindex].a)/255.0f*kernel[kernelWidth*xkabs + ykabs];
2294 }
2295 }
2296 }
2297
2298 for (int i = 0; i < kernelSize; i++)
2299 {
2300 rRes += temp[i].x;
2301 gRes += temp[i].y;
2302 bRes += temp[i].z;
2303 aRes += temp[i].w;
2304 }
2305
2306 if (rRes < 0.0f) rRes = 0.0f;
2307 if (gRes < 0.0f) gRes = 0.0f;
2308 if (bRes < 0.0f) bRes = 0.0f;
2309
2310 if (rRes > 1.0f) rRes = 1.0f;
2311 if (gRes > 1.0f) gRes = 1.0f;
2312 if (bRes > 1.0f) bRes = 1.0f;
2313
2314 imageCopy2[image->width*x + y].x = rRes;
2315 imageCopy2[image->width*x + y].y = gRes;
2316 imageCopy2[image->width*x + y].z = bRes;
2317 imageCopy2[image->width*x + y].w = aRes;
2318
2319 rRes = 0.0f;
2320 gRes = 0.0f;
2321 bRes = 0.0f;
2322 aRes = 0.0f;
2323
2324 for (int i = 0; i < kernelSize; i++)
2325 {
2326 temp[i].x = 0.0f;
2327 temp[i].y = 0.0f;
2328 temp[i].z = 0.0f;
2329 temp[i].w = 0.0f;
2330 }
2331 }
2332 }
2333
2334 for (int i = 0; i < (image->width*image->height); i++)
2335 {
2336 float alpha = (float)imageCopy2[i].w;
2337
2338 pixels[i].r = (unsigned char)((imageCopy2[i].x)*255.0f);
2339 pixels[i].g = (unsigned char)((imageCopy2[i].y)*255.0f);
2340 pixels[i].b = (unsigned char)((imageCopy2[i].z)*255.0f);
2341 pixels[i].a = (unsigned char)((alpha)*255.0f);
2342 }
2343
2344 int format = image->format;
2345 RL_FREE(image->data);
2346 RL_FREE(imageCopy2);
2347 RL_FREE(temp);
2348
2349 image->data = pixels;
2350 image->format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8;
2351 ImageFormat(image, format);
2352 }
2353
2354 // Generate all mipmap levels for a provided image
2355 // NOTE 1: Supports POT and NPOT images
2356 // NOTE 2: image.data is scaled to include mipmap levels
2357 // NOTE 3: Mipmaps format is the same as base image
2358 void ImageMipmaps(Image *image)
2359 {
2360 // Security check to avoid program crash
2361 if ((image->data == NULL) || (image->width == 0) || (image->height == 0)) return;
2362
2363 int mipCount = 1; // Required mipmap levels count (including base level)
2364 int mipWidth = image->width; // Base image width
2365 int mipHeight = image->height; // Base image height
2366 int mipSize = GetPixelDataSize(mipWidth, mipHeight, image->format); // Image data size (in bytes)
2367
2368 // Count mipmap levels required
2369 while ((mipWidth != 1) || (mipHeight != 1))
2370 {
2371 if (mipWidth != 1) mipWidth /= 2;
2372 if (mipHeight != 1) mipHeight /= 2;
2373
2374 // Security check for NPOT textures
2375 if (mipWidth < 1) mipWidth = 1;
2376 if (mipHeight < 1) mipHeight = 1;
2377
2378 TRACELOG(LOG_DEBUG, "IMAGE: Next mipmap level: %i x %i - current size %i", mipWidth, mipHeight, mipSize);
2379
2380 mipCount++;
2381 mipSize += GetPixelDataSize(mipWidth, mipHeight, image->format); // Add mipmap size (in bytes)
2382 }
2383
2384 if (image->mipmaps < mipCount)
2385 {
2386 // Create second buffer and copy data manually to it
2387 void *temp = RL_CALLOC(mipSize, 1);
2388 memcpy(temp, image->data, GetPixelDataSize(image->width, image->height, image->format));
2389 RL_FREE(image->data);
2390 image->data = temp;
2391
2392 // Pointer to allocated memory point where store next mipmap level data
2393 unsigned char *nextmip = (unsigned char *)image->data;
2394
2395 mipWidth = image->width;
2396 mipHeight = image->height;
2397 mipSize = GetPixelDataSize(mipWidth, mipHeight, image->format);
2398 Image imCopy = ImageCopy(*image);
2399
2400 for (int i = 1; i < mipCount; i++)
2401 {
2402 nextmip += mipSize;
2403
2404 mipWidth /= 2;
2405 mipHeight /= 2;
2406
2407 // Security check for NPOT textures
2408 if (mipWidth < 1) mipWidth = 1;
2409 if (mipHeight < 1) mipHeight = 1;
2410
2411 mipSize = GetPixelDataSize(mipWidth, mipHeight, image->format);
2412
2413 if (i < image->mipmaps) continue;
2414
2415 TRACELOG(LOG_DEBUG, "IMAGE: Generating mipmap level: %i (%i x %i) - size: %i - offset: 0x%x", i, mipWidth, mipHeight, mipSize, nextmip);
2416 ImageResize(&imCopy, mipWidth, mipHeight); // Uses internally Mitchell cubic downscale filter
2417 memcpy(nextmip, imCopy.data, mipSize);
2418 }
2419
2420 UnloadImage(imCopy);
2421
2422 image->mipmaps = mipCount;
2423 }
2424 else TRACELOG(LOG_WARNING, "IMAGE: Mipmaps already available");
2425 }
2426
2427 // Dither image data to 16bpp or lower (Floyd-Steinberg dithering)
2428 // NOTE: In case selected bpp do not represent a known 16bit format,
2429 // dithered data is stored in the LSB part of the unsigned short
2430 void ImageDither(Image *image, int rBpp, int gBpp, int bBpp, int aBpp)
2431 {
2432 // Security check to avoid program crash
2433 if ((image->data == NULL) || (image->width == 0) || (image->height == 0)) return;
2434
2435 if (image->format >= PIXELFORMAT_COMPRESSED_DXT1_RGB)
2436 {
2437 TRACELOG(LOG_WARNING, "IMAGE: Compressed data formats can not be dithered");
2438 return;
2439 }
2440
2441 if ((rBpp + gBpp + bBpp + aBpp) > 16)
2442 {
2443 TRACELOG(LOG_WARNING, "IMAGE: Unsupported dithering bpps (%ibpp), only 16bpp or lower modes supported", (rBpp+gBpp+bBpp+aBpp));
2444 }
2445 else
2446 {
2447 Color *pixels = LoadImageColors(*image);
2448
2449 RL_FREE(image->data); // free old image data
2450
2451 if ((image->format != PIXELFORMAT_UNCOMPRESSED_R8G8B8) && (image->format != PIXELFORMAT_UNCOMPRESSED_R8G8B8A8))
2452 {
2453 TRACELOG(LOG_WARNING, "IMAGE: Format is already 16bpp or lower, dithering could have no effect");
2454 }
2455
2456 // Define new image format, check if desired bpp match internal known format
2457 if ((rBpp == 5) && (gBpp == 6) && (bBpp == 5) && (aBpp == 0)) image->format = PIXELFORMAT_UNCOMPRESSED_R5G6B5;
2458 else if ((rBpp == 5) && (gBpp == 5) && (bBpp == 5) && (aBpp == 1)) image->format = PIXELFORMAT_UNCOMPRESSED_R5G5B5A1;
2459 else if ((rBpp == 4) && (gBpp == 4) && (bBpp == 4) && (aBpp == 4)) image->format = PIXELFORMAT_UNCOMPRESSED_R4G4B4A4;
2460 else
2461 {
2462 image->format = 0;
2463 TRACELOG(LOG_WARNING, "IMAGE: Unsupported dithered OpenGL internal format: %ibpp (R%iG%iB%iA%i)", (rBpp+gBpp+bBpp+aBpp), rBpp, gBpp, bBpp, aBpp);
2464 }
2465
2466 // NOTE: Storing the dithered data as unsigned short (16bpp)
2467 image->data = (unsigned short *)RL_MALLOC(image->width*image->height*sizeof(unsigned short));
2468
2469 Color oldPixel = WHITE;
2470 Color newPixel = WHITE;
2471
2472 int rError = 0;
2473 int gError = 0;
2474 int bError = 0;
2475 unsigned short rPixel = 0; // Used for 16bit pixel composition
2476 unsigned short gPixel = 0;
2477 unsigned short bPixel = 0;
2478 unsigned short aPixel = 0;
2479
2480 #define MIN(a,b) (((a)<(b))?(a):(b))
2481
2482 for (int y = 0; y < image->height; y++)
2483 {
2484 for (int x = 0; x < image->width; x++)
2485 {
2486 oldPixel = pixels[y*image->width + x];
2487
2488 // NOTE: New pixel obtained by bits truncate, it would be better to round values (check ImageFormat())
2489 newPixel.r = oldPixel.r >> (8 - rBpp); // R bits
2490 newPixel.g = oldPixel.g >> (8 - gBpp); // G bits
2491 newPixel.b = oldPixel.b >> (8 - bBpp); // B bits
2492 newPixel.a = oldPixel.a >> (8 - aBpp); // A bits (not used on dithering)
2493
2494 // NOTE: Error must be computed between new and old pixel but using same number of bits,
2495 // to know how much color precision has been lost
2496 rError = (int)oldPixel.r - (int)(newPixel.r << (8 - rBpp));
2497 gError = (int)oldPixel.g - (int)(newPixel.g << (8 - gBpp));
2498 bError = (int)oldPixel.b - (int)(newPixel.b << (8 - bBpp));
2499
2500 pixels[y*image->width + x] = newPixel;
2501
2502 // NOTE: Some cases are out of the array and should be ignored
2503 if (x < (image->width - 1))
2504 {
2505 pixels[y*image->width + x+1].r = MIN((int)pixels[y*image->width + x+1].r + (int)((float)rError*7.0f/16), 0xff);
2506 pixels[y*image->width + x+1].g = MIN((int)pixels[y*image->width + x+1].g + (int)((float)gError*7.0f/16), 0xff);
2507 pixels[y*image->width + x+1].b = MIN((int)pixels[y*image->width + x+1].b + (int)((float)bError*7.0f/16), 0xff);
2508 }
2509
2510 if ((x > 0) && (y < (image->height - 1)))
2511 {
2512 pixels[(y+1)*image->width + x-1].r = MIN((int)pixels[(y+1)*image->width + x-1].r + (int)((float)rError*3.0f/16), 0xff);
2513 pixels[(y+1)*image->width + x-1].g = MIN((int)pixels[(y+1)*image->width + x-1].g + (int)((float)gError*3.0f/16), 0xff);
2514 pixels[(y+1)*image->width + x-1].b = MIN((int)pixels[(y+1)*image->width + x-1].b + (int)((float)bError*3.0f/16), 0xff);
2515 }
2516
2517 if (y < (image->height - 1))
2518 {
2519 pixels[(y+1)*image->width + x].r = MIN((int)pixels[(y+1)*image->width + x].r + (int)((float)rError*5.0f/16), 0xff);
2520 pixels[(y+1)*image->width + x].g = MIN((int)pixels[(y+1)*image->width + x].g + (int)((float)gError*5.0f/16), 0xff);
2521 pixels[(y+1)*image->width + x].b = MIN((int)pixels[(y+1)*image->width + x].b + (int)((float)bError*5.0f/16), 0xff);
2522 }
2523
2524 if ((x < (image->width - 1)) && (y < (image->height - 1)))
2525 {
2526 pixels[(y+1)*image->width + x+1].r = MIN((int)pixels[(y+1)*image->width + x+1].r + (int)((float)rError*1.0f/16), 0xff);
2527 pixels[(y+1)*image->width + x+1].g = MIN((int)pixels[(y+1)*image->width + x+1].g + (int)((float)gError*1.0f/16), 0xff);
2528 pixels[(y+1)*image->width + x+1].b = MIN((int)pixels[(y+1)*image->width + x+1].b + (int)((float)bError*1.0f/16), 0xff);
2529 }
2530
2531 rPixel = (unsigned short)newPixel.r;
2532 gPixel = (unsigned short)newPixel.g;
2533 bPixel = (unsigned short)newPixel.b;
2534 aPixel = (unsigned short)newPixel.a;
2535
2536 ((unsigned short *)image->data)[y*image->width + x] = (rPixel << (gBpp + bBpp + aBpp)) | (gPixel << (bBpp + aBpp)) | (bPixel << aBpp) | aPixel;
2537 }
2538 }
2539
2540 UnloadImageColors(pixels);
2541 }
2542 }
2543
2544 // Flip image vertically
2545 void ImageFlipVertical(Image *image)
2546 {
2547 // Security check to avoid program crash
2548 if ((image->data == NULL) || (image->width == 0) || (image->height == 0)) return;
2549
2550 if (image->mipmaps > 1) TRACELOG(LOG_WARNING, "Image manipulation only applied to base mipmap level");
2551 if (image->format >= PIXELFORMAT_COMPRESSED_DXT1_RGB) TRACELOG(LOG_WARNING, "Image manipulation not supported for compressed formats");
2552 else
2553 {
2554 int bytesPerPixel = GetPixelDataSize(1, 1, image->format);
2555 unsigned char *flippedData = (unsigned char *)RL_MALLOC(image->width*image->height*bytesPerPixel);
2556
2557 for (int i = (image->height - 1), offsetSize = 0; i >= 0; i--)
2558 {
2559 memcpy(flippedData + offsetSize, ((unsigned char *)image->data) + i*image->width*bytesPerPixel, image->width*bytesPerPixel);
2560 offsetSize += image->width*bytesPerPixel;
2561 }
2562
2563 RL_FREE(image->data);
2564 image->data = flippedData;
2565 }
2566 }
2567
2568 // Flip image horizontally
2569 void ImageFlipHorizontal(Image *image)
2570 {
2571 // Security check to avoid program crash
2572 if ((image->data == NULL) || (image->width == 0) || (image->height == 0)) return;
2573
2574 if (image->mipmaps > 1) TRACELOG(LOG_WARNING, "Image manipulation only applied to base mipmap level");
2575 if (image->format >= PIXELFORMAT_COMPRESSED_DXT1_RGB) TRACELOG(LOG_WARNING, "Image manipulation not supported for compressed formats");
2576 else
2577 {
2578 int bytesPerPixel = GetPixelDataSize(1, 1, image->format);
2579 unsigned char *flippedData = (unsigned char *)RL_MALLOC(image->width*image->height*bytesPerPixel);
2580
2581 for (int y = 0; y < image->height; y++)
2582 {
2583 for (int x = 0; x < image->width; x++)
2584 {
2585 // OPTION 1: Move pixels with memcpy()
2586 //memcpy(flippedData + (y*image->width + x)*bytesPerPixel, ((unsigned char *)image->data) + (y*image->width + (image->width - 1 - x))*bytesPerPixel, bytesPerPixel);
2587
2588 // OPTION 2: Copy data pixel by pixel
2589 for (int i = 0; i < bytesPerPixel; i++) flippedData[(y*image->width + x)*bytesPerPixel + i] = ((unsigned char *)image->data)[(y*image->width + (image->width - 1 - x))*bytesPerPixel + i];
2590 }
2591 }
2592
2593 RL_FREE(image->data);
2594 image->data = flippedData;
2595
2596 /*
2597 // OPTION 3: Faster implementation (specific for 32bit pixels)
2598 // NOTE: It does not require additional allocations
2599 uint32_t *ptr = (uint32_t *)image->data;
2600 for (int y = 0; y < image->height; y++)
2601 {
2602 for (int x = 0; x < image->width/2; x++)
2603 {
2604 uint32_t backup = ptr[y*image->width + x];
2605 ptr[y*image->width + x] = ptr[y*image->width + (image->width - 1 - x)];
2606 ptr[y*image->width + (image->width - 1 - x)] = backup;
2607 }
2608 }
2609 */
2610 }
2611 }
2612
2613 // Rotate image in degrees
2614 void ImageRotate(Image *image, int degrees)
2615 {
2616 // Security check to avoid program crash
2617 if ((image->data == NULL) || (image->width == 0) || (image->height == 0)) return;
2618
2619 if (image->mipmaps > 1) TRACELOG(LOG_WARNING, "Image manipulation only applied to base mipmap level");
2620 if (image->format >= PIXELFORMAT_COMPRESSED_DXT1_RGB) TRACELOG(LOG_WARNING, "Image manipulation not supported for compressed formats");
2621 else
2622 {
2623 float rad = degrees*PI/180.0f;
2624 float sinRadius = sinf(rad);
2625 float cosRadius = cosf(rad);
2626
2627 int width = (int)(fabsf(image->width*cosRadius) + fabsf(image->height*sinRadius));
2628 int height = (int)(fabsf(image->height*cosRadius) + fabsf(image->width*sinRadius));
2629
2630 int bytesPerPixel = GetPixelDataSize(1, 1, image->format);
2631 unsigned char *rotatedData = (unsigned char *)RL_CALLOC(width*height, bytesPerPixel);
2632
2633 for (int y = 0; y < height; y++)
2634 {
2635 for (int x = 0; x < width; x++)
2636 {
2637 float oldX = ((x - width/2.0f)*cosRadius + (y - height/2.0f)*sinRadius) + image->width/2.0f;
2638 float oldY = ((y - height/2.0f)*cosRadius - (x - width/2.0f)*sinRadius) + image->height/2.0f;
2639
2640 if ((oldX >= 0) && (oldX < image->width) && (oldY >= 0) && (oldY < image->height))
2641 {
2642 int x1 = (int)floorf(oldX);
2643 int y1 = (int)floorf(oldY);
2644 int x2 = MIN(x1 + 1, image->width - 1);
2645 int y2 = MIN(y1 + 1, image->height - 1);
2646
2647 float px = oldX - x1;
2648 float py = oldY - y1;
2649
2650 for (int i = 0; i < bytesPerPixel; i++)
2651 {
2652 float f1 = ((unsigned char *)image->data)[(y1*image->width + x1)*bytesPerPixel + i];
2653 float f2 = ((unsigned char *)image->data)[(y1*image->width + x2)*bytesPerPixel + i];
2654 float f3 = ((unsigned char *)image->data)[(y2*image->width + x1)*bytesPerPixel + i];
2655 float f4 = ((unsigned char *)image->data)[(y2*image->width + x2)*bytesPerPixel + i];
2656
2657 float val = f1*(1 - px)*(1 - py) + f2*px*(1 - py) + f3*(1 - px)*py + f4*px*py;
2658
2659 rotatedData[(y*width + x)*bytesPerPixel + i] = (unsigned char)val;
2660 }
2661 }
2662 }
2663 }
2664
2665 RL_FREE(image->data);
2666 image->data = rotatedData;
2667 image->width = width;
2668 image->height = height;
2669 }
2670 }
2671
2672 // Rotate image clockwise 90deg
2673 void ImageRotateCW(Image *image)
2674 {
2675 // Security check to avoid program crash
2676 if ((image->data == NULL) || (image->width == 0) || (image->height == 0)) return;
2677
2678 if (image->mipmaps > 1) TRACELOG(LOG_WARNING, "Image manipulation only applied to base mipmap level");
2679 if (image->format >= PIXELFORMAT_COMPRESSED_DXT1_RGB) TRACELOG(LOG_WARNING, "Image manipulation not supported for compressed formats");
2680 else
2681 {
2682 int bytesPerPixel = GetPixelDataSize(1, 1, image->format);
2683 unsigned char *rotatedData = (unsigned char *)RL_MALLOC(image->width*image->height*bytesPerPixel);
2684
2685 for (int y = 0; y < image->height; y++)
2686 {
2687 for (int x = 0; x < image->width; x++)
2688 {
2689 //memcpy(rotatedData + (x*image->height + (image->height - y - 1))*bytesPerPixel, ((unsigned char *)image->data) + (y*image->width + x)*bytesPerPixel, bytesPerPixel);
2690 for (int i = 0; i < bytesPerPixel; i++) rotatedData[(x*image->height + (image->height - y - 1))*bytesPerPixel + i] = ((unsigned char *)image->data)[(y*image->width + x)*bytesPerPixel + i];
2691 }
2692 }
2693
2694 RL_FREE(image->data);
2695 image->data = rotatedData;
2696 int width = image->width;
2697 int height = image-> height;
2698
2699 image->width = height;
2700 image->height = width;
2701 }
2702 }
2703
2704 // Rotate image counter-clockwise 90deg
2705 void ImageRotateCCW(Image *image)
2706 {
2707 // Security check to avoid program crash
2708 if ((image->data == NULL) || (image->width == 0) || (image->height == 0)) return;
2709
2710 if (image->mipmaps > 1) TRACELOG(LOG_WARNING, "Image manipulation only applied to base mipmap level");
2711 if (image->format >= PIXELFORMAT_COMPRESSED_DXT1_RGB) TRACELOG(LOG_WARNING, "Image manipulation not supported for compressed formats");
2712 else
2713 {
2714 int bytesPerPixel = GetPixelDataSize(1, 1, image->format);
2715 unsigned char *rotatedData = (unsigned char *)RL_MALLOC(image->width*image->height*bytesPerPixel);
2716
2717 for (int y = 0; y < image->height; y++)
2718 {
2719 for (int x = 0; x < image->width; x++)
2720 {
2721 //memcpy(rotatedData + (x*image->height + y))*bytesPerPixel, ((unsigned char *)image->data) + (y*image->width + (image->width - x - 1))*bytesPerPixel, bytesPerPixel);
2722 for (int i = 0; i < bytesPerPixel; i++) rotatedData[(x*image->height + y)*bytesPerPixel + i] = ((unsigned char *)image->data)[(y*image->width + (image->width - x - 1))*bytesPerPixel + i];
2723 }
2724 }
2725
2726 RL_FREE(image->data);
2727 image->data = rotatedData;
2728 int width = image->width;
2729 int height = image-> height;
2730
2731 image->width = height;
2732 image->height = width;
2733 }
2734 }
2735
2736 // Modify image color: tint
2737 void ImageColorTint(Image *image, Color color)
2738 {
2739 // Security check to avoid program crash
2740 if ((image->data == NULL) || (image->width == 0) || (image->height == 0)) return;
2741
2742 Color *pixels = LoadImageColors(*image);
2743
2744 for (int i = 0; i < image->width*image->height; i++)
2745 {
2746 unsigned char r = (unsigned char)(((int)pixels[i].r*(int)color.r)/255);
2747 unsigned char g = (unsigned char)(((int)pixels[i].g*(int)color.g)/255);
2748 unsigned char b = (unsigned char)(((int)pixels[i].b*(int)color.b)/255);
2749 unsigned char a = (unsigned char)(((int)pixels[i].a*(int)color.a)/255);
2750
2751 pixels[i].r = r;
2752 pixels[i].g = g;
2753 pixels[i].b = b;
2754 pixels[i].a = a;
2755 }
2756
2757 int format = image->format;
2758 RL_FREE(image->data);
2759
2760 image->data = pixels;
2761 image->format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8;
2762
2763 ImageFormat(image, format);
2764 }
2765
2766 // Modify image color: invert
2767 void ImageColorInvert(Image *image)
2768 {
2769 // Security check to avoid program crash
2770 if ((image->data == NULL) || (image->width == 0) || (image->height == 0)) return;
2771
2772 Color *pixels = LoadImageColors(*image);
2773
2774 for (int i = 0; i < image->width*image->height; i++)
2775 {
2776 pixels[i].r = 255 - pixels[i].r;
2777 pixels[i].g = 255 - pixels[i].g;
2778 pixels[i].b = 255 - pixels[i].b;
2779 }
2780
2781 int format = image->format;
2782 RL_FREE(image->data);
2783
2784 image->data = pixels;
2785 image->format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8;
2786
2787 ImageFormat(image, format);
2788 }
2789
2790 // Modify image color: grayscale
2791 void ImageColorGrayscale(Image *image)
2792 {
2793 ImageFormat(image, PIXELFORMAT_UNCOMPRESSED_GRAYSCALE);
2794 }
2795
2796 // Modify image color: contrast
2797 // NOTE: Contrast values between -100 and 100
2798 void ImageColorContrast(Image *image, float contrast)
2799 {
2800 // Security check to avoid program crash
2801 if ((image->data == NULL) || (image->width == 0) || (image->height == 0)) return;
2802
2803 if (contrast < -100) contrast = -100;
2804 if (contrast > 100) contrast = 100;
2805
2806 contrast = (100.0f + contrast)/100.0f;
2807 contrast *= contrast;
2808
2809 Color *pixels = LoadImageColors(*image);
2810
2811 for (int i = 0; i < image->width*image->height; i++)
2812 {
2813 float pR = (float)pixels[i].r/255.0f;
2814 pR -= 0.5f;
2815 pR *= contrast;
2816 pR += 0.5f;
2817 pR *= 255;
2818 if (pR < 0) pR = 0;
2819 if (pR > 255) pR = 255;
2820
2821 float pG = (float)pixels[i].g/255.0f;
2822 pG -= 0.5f;
2823 pG *= contrast;
2824 pG += 0.5f;
2825 pG *= 255;
2826 if (pG < 0) pG = 0;
2827 if (pG > 255) pG = 255;
2828
2829 float pB = (float)pixels[i].b/255.0f;
2830 pB -= 0.5f;
2831 pB *= contrast;
2832 pB += 0.5f;
2833 pB *= 255;
2834 if (pB < 0) pB = 0;
2835 if (pB > 255) pB = 255;
2836
2837 pixels[i].r = (unsigned char)pR;
2838 pixels[i].g = (unsigned char)pG;
2839 pixels[i].b = (unsigned char)pB;
2840 }
2841
2842 int format = image->format;
2843 RL_FREE(image->data);
2844
2845 image->data = pixels;
2846 image->format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8;
2847
2848 ImageFormat(image, format);
2849 }
2850
2851 // Modify image color: brightness
2852 // NOTE: Brightness values between -255 and 255
2853 void ImageColorBrightness(Image *image, int brightness)
2854 {
2855 // Security check to avoid program crash
2856 if ((image->data == NULL) || (image->width == 0) || (image->height == 0)) return;
2857
2858 if (brightness < -255) brightness = -255;
2859 if (brightness > 255) brightness = 255;
2860
2861 Color *pixels = LoadImageColors(*image);
2862
2863 for (int i = 0; i < image->width*image->height; i++)
2864 {
2865 int cR = pixels[i].r + brightness;
2866 int cG = pixels[i].g + brightness;
2867 int cB = pixels[i].b + brightness;
2868
2869 if (cR < 0) cR = 1;
2870 if (cR > 255) cR = 255;
2871
2872 if (cG < 0) cG = 1;
2873 if (cG > 255) cG = 255;
2874
2875 if (cB < 0) cB = 1;
2876 if (cB > 255) cB = 255;
2877
2878 pixels[i].r = (unsigned char)cR;
2879 pixels[i].g = (unsigned char)cG;
2880 pixels[i].b = (unsigned char)cB;
2881 }
2882
2883 int format = image->format;
2884 RL_FREE(image->data);
2885
2886 image->data = pixels;
2887 image->format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8;
2888
2889 ImageFormat(image, format);
2890 }
2891
2892 // Modify image color: replace color
2893 void ImageColorReplace(Image *image, Color color, Color replace)
2894 {
2895 // Security check to avoid program crash
2896 if ((image->data == NULL) || (image->width == 0) || (image->height == 0)) return;
2897
2898 Color *pixels = LoadImageColors(*image);
2899
2900 for (int i = 0; i < image->width*image->height; i++)
2901 {
2902 if ((pixels[i].r == color.r) &&
2903 (pixels[i].g == color.g) &&
2904 (pixels[i].b == color.b) &&
2905 (pixels[i].a == color.a))
2906 {
2907 pixels[i].r = replace.r;
2908 pixels[i].g = replace.g;
2909 pixels[i].b = replace.b;
2910 pixels[i].a = replace.a;
2911 }
2912 }
2913
2914 int format = image->format;
2915 RL_FREE(image->data);
2916
2917 image->data = pixels;
2918 image->format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8;
2919
2920 // Only convert back to original format if it supported alpha
2921 if ((format == PIXELFORMAT_UNCOMPRESSED_R8G8B8) ||
2922 (format == PIXELFORMAT_UNCOMPRESSED_R5G6B5) ||
2923 (format == PIXELFORMAT_UNCOMPRESSED_GRAYSCALE) ||
2924 (format == PIXELFORMAT_UNCOMPRESSED_R32G32B32) ||
2925 (format == PIXELFORMAT_UNCOMPRESSED_R16G16B16) ||
2926 (format == PIXELFORMAT_COMPRESSED_DXT1_RGB) ||
2927 (format == PIXELFORMAT_COMPRESSED_ETC1_RGB) ||
2928 (format == PIXELFORMAT_COMPRESSED_ETC2_RGB) ||
2929 (format == PIXELFORMAT_COMPRESSED_PVRT_RGB)) ImageFormat(image, format);
2930 }
2931
2932 // Load color data from image as a Color array (RGBA - 32bit)
2933 // NOTE: Memory allocated should be freed using UnloadImageColors();
2934 Color *LoadImageColors(Image image)
2935 {
2936 if ((image.width == 0) || (image.height == 0)) return NULL; // Security check
2937
2938 Color *pixels = (Color *)RL_MALLOC(image.width*image.height*sizeof(Color));
2939
2940 if (image.format >= PIXELFORMAT_COMPRESSED_DXT1_RGB) TRACELOG(LOG_WARNING, "IMAGE: Pixel data retrieval not supported for compressed image formats");
2941 else
2942 {
2943 if ((image.format == PIXELFORMAT_UNCOMPRESSED_R32) ||
2944 (image.format == PIXELFORMAT_UNCOMPRESSED_R32G32B32) ||
2945 (image.format == PIXELFORMAT_UNCOMPRESSED_R32G32B32A32)) TRACELOG(LOG_WARNING, "IMAGE: Pixel format converted from 32bit to 8bit per channel");
2946
2947 if ((image.format == PIXELFORMAT_UNCOMPRESSED_R16) ||
2948 (image.format == PIXELFORMAT_UNCOMPRESSED_R16G16B16) ||
2949 (image.format == PIXELFORMAT_UNCOMPRESSED_R16G16B16A16)) TRACELOG(LOG_WARNING, "IMAGE: Pixel format converted from 16bit to 8bit per channel");
2950
2951 for (int i = 0, k = 0; i < image.width*image.height; i++)
2952 {
2953 switch (image.format)
2954 {
2955 case PIXELFORMAT_UNCOMPRESSED_GRAYSCALE:
2956 {
2957 pixels[i].r = ((unsigned char *)image.data)[i];
2958 pixels[i].g = ((unsigned char *)image.data)[i];
2959 pixels[i].b = ((unsigned char *)image.data)[i];
2960 pixels[i].a = 255;
2961
2962 } break;
2963 case PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA:
2964 {
2965 pixels[i].r = ((unsigned char *)image.data)[k];
2966 pixels[i].g = ((unsigned char *)image.data)[k];
2967 pixels[i].b = ((unsigned char *)image.data)[k];
2968 pixels[i].a = ((unsigned char *)image.data)[k + 1];
2969
2970 k += 2;
2971 } break;
2972 case PIXELFORMAT_UNCOMPRESSED_R5G5B5A1:
2973 {
2974 unsigned short pixel = ((unsigned short *)image.data)[i];
2975
2976 pixels[i].r = (unsigned char)((float)((pixel & 0b1111100000000000) >> 11)*(255/31));
2977 pixels[i].g = (unsigned char)((float)((pixel & 0b0000011111000000) >> 6)*(255/31));
2978 pixels[i].b = (unsigned char)((float)((pixel & 0b0000000000111110) >> 1)*(255/31));
2979 pixels[i].a = (unsigned char)((pixel & 0b0000000000000001)*255);
2980
2981 } break;
2982 case PIXELFORMAT_UNCOMPRESSED_R5G6B5:
2983 {
2984 unsigned short pixel = ((unsigned short *)image.data)[i];
2985
2986 pixels[i].r = (unsigned char)((float)((pixel & 0b1111100000000000) >> 11)*(255/31));
2987 pixels[i].g = (unsigned char)((float)((pixel & 0b0000011111100000) >> 5)*(255/63));
2988 pixels[i].b = (unsigned char)((float)(pixel & 0b0000000000011111)*(255/31));
2989 pixels[i].a = 255;
2990
2991 } break;
2992 case PIXELFORMAT_UNCOMPRESSED_R4G4B4A4:
2993 {
2994 unsigned short pixel = ((unsigned short *)image.data)[i];
2995
2996 pixels[i].r = (unsigned char)((float)((pixel & 0b1111000000000000) >> 12)*(255/15));
2997 pixels[i].g = (unsigned char)((float)((pixel & 0b0000111100000000) >> 8)*(255/15));
2998 pixels[i].b = (unsigned char)((float)((pixel & 0b0000000011110000) >> 4)*(255/15));
2999 pixels[i].a = (unsigned char)((float)(pixel & 0b0000000000001111)*(255/15));
3000
3001 } break;
3002 case PIXELFORMAT_UNCOMPRESSED_R8G8B8A8:
3003 {
3004 pixels[i].r = ((unsigned char *)image.data)[k];
3005 pixels[i].g = ((unsigned char *)image.data)[k + 1];
3006 pixels[i].b = ((unsigned char *)image.data)[k + 2];
3007 pixels[i].a = ((unsigned char *)image.data)[k + 3];
3008
3009 k += 4;
3010 } break;
3011 case PIXELFORMAT_UNCOMPRESSED_R8G8B8:
3012 {
3013 pixels[i].r = (unsigned char)((unsigned char *)image.data)[k];
3014 pixels[i].g = (unsigned char)((unsigned char *)image.data)[k + 1];
3015 pixels[i].b = (unsigned char)((unsigned char *)image.data)[k + 2];
3016 pixels[i].a = 255;
3017
3018 k += 3;
3019 } break;
3020 case PIXELFORMAT_UNCOMPRESSED_R32:
3021 {
3022 pixels[i].r = (unsigned char)(((float *)image.data)[k]*255.0f);
3023 pixels[i].g = 0;
3024 pixels[i].b = 0;
3025 pixels[i].a = 255;
3026
3027 k += 1;
3028 } break;
3029 case PIXELFORMAT_UNCOMPRESSED_R32G32B32:
3030 {
3031 pixels[i].r = (unsigned char)(((float *)image.data)[k]*255.0f);
3032 pixels[i].g = (unsigned char)(((float *)image.data)[k + 1]*255.0f);
3033 pixels[i].b = (unsigned char)(((float *)image.data)[k + 2]*255.0f);
3034 pixels[i].a = 255;
3035
3036 k += 3;
3037 } break;
3038 case PIXELFORMAT_UNCOMPRESSED_R32G32B32A32:
3039 {
3040 pixels[i].r = (unsigned char)(((float *)image.data)[k]*255.0f);
3041 pixels[i].g = (unsigned char)(((float *)image.data)[k + 1]*255.0f);
3042 pixels[i].b = (unsigned char)(((float *)image.data)[k + 2]*255.0f);
3043 pixels[i].a = (unsigned char)(((float *)image.data)[k + 3]*255.0f);
3044
3045 k += 4;
3046 } break;
3047 case PIXELFORMAT_UNCOMPRESSED_R16:
3048 {
3049 pixels[i].r = (unsigned char)(HalfToFloat(((unsigned short *)image.data)[k])*255.0f);
3050 pixels[i].g = 0;
3051 pixels[i].b = 0;
3052 pixels[i].a = 255;
3053
3054 k += 1;
3055 } break;
3056 case PIXELFORMAT_UNCOMPRESSED_R16G16B16:
3057 {
3058 pixels[i].r = (unsigned char)(HalfToFloat(((unsigned short *)image.data)[k])*255.0f);
3059 pixels[i].g = (unsigned char)(HalfToFloat(((unsigned short *)image.data)[k + 1])*255.0f);
3060 pixels[i].b = (unsigned char)(HalfToFloat(((unsigned short *)image.data)[k + 2])*255.0f);
3061 pixels[i].a = 255;
3062
3063 k += 3;
3064 } break;
3065 case PIXELFORMAT_UNCOMPRESSED_R16G16B16A16:
3066 {
3067 pixels[i].r = (unsigned char)(HalfToFloat(((unsigned short *)image.data)[k])*255.0f);
3068 pixels[i].g = (unsigned char)(HalfToFloat(((unsigned short *)image.data)[k + 1])*255.0f);
3069 pixels[i].b = (unsigned char)(HalfToFloat(((unsigned short *)image.data)[k + 2])*255.0f);
3070 pixels[i].a = (unsigned char)(HalfToFloat(((unsigned short *)image.data)[k + 3])*255.0f);
3071
3072 k += 4;
3073 } break;
3074 default: break;
3075 }
3076 }
3077 }
3078
3079 return pixels;
3080 }
3081
3082 // Load colors palette from image as a Color array (RGBA - 32bit)
3083 // NOTE: Memory allocated should be freed using UnloadImagePalette()
3084 Color *LoadImagePalette(Image image, int maxPaletteSize, int *colorCount)
3085 {
3086 #define COLOR_EQUAL(col1, col2) ((col1.r == col2.r)&&(col1.g == col2.g)&&(col1.b == col2.b)&&(col1.a == col2.a))
3087
3088 int palCount = 0;
3089 Color *palette = NULL;
3090 Color *pixels = LoadImageColors(image);
3091
3092 if (pixels != NULL)
3093 {
3094 palette = (Color *)RL_MALLOC(maxPaletteSize*sizeof(Color));
3095
3096 for (int i = 0; i < maxPaletteSize; i++) palette[i] = BLANK; // Set all colors to BLANK
3097
3098 for (int i = 0; i < image.width*image.height; i++)
3099 {
3100 if (pixels[i].a > 0)
3101 {
3102 bool colorInPalette = false;
3103
3104 // Check if the color is already on palette
3105 for (int j = 0; j < maxPaletteSize; j++)
3106 {
3107 if (COLOR_EQUAL(pixels[i], palette[j]))
3108 {
3109 colorInPalette = true;
3110 break;
3111 }
3112 }
3113
3114 // Store color if not on the palette
3115 if (!colorInPalette)
3116 {
3117 palette[palCount] = pixels[i]; // Add pixels[i] to palette
3118 palCount++;
3119
3120 // Reached the limit of colors supported by palette
3121 if (palCount >= maxPaletteSize)
3122 {
3123 i = image.width*image.height; // Finish palette get
3124 TRACELOG(LOG_WARNING, "IMAGE: Palette is greater than %i colors", maxPaletteSize);
3125 }
3126 }
3127 }
3128 }
3129
3130 UnloadImageColors(pixels);
3131 }
3132
3133 *colorCount = palCount;
3134
3135 return palette;
3136 }
3137
3138 // Unload color data loaded with LoadImageColors()
3139 void UnloadImageColors(Color *colors)
3140 {
3141 RL_FREE(colors);
3142 }
3143
3144 // Unload colors palette loaded with LoadImagePalette()
3145 void UnloadImagePalette(Color *colors)
3146 {
3147 RL_FREE(colors);
3148 }
3149
3150 // Get image alpha border rectangle
3151 // NOTE: Threshold is defined as a percentage: 0.0f -> 1.0f
3152 Rectangle GetImageAlphaBorder(Image image, float threshold)
3153 {
3154 Rectangle crop = { 0 };
3155
3156 Color *pixels = LoadImageColors(image);
3157
3158 if (pixels != NULL)
3159 {
3160 int xMin = 65536; // Define a big enough number
3161 int xMax = 0;
3162 int yMin = 65536;
3163 int yMax = 0;
3164
3165 for (int y = 0; y < image.height; y++)
3166 {
3167 for (int x = 0; x < image.width; x++)
3168 {
3169 if (pixels[y*image.width + x].a > (unsigned char)(threshold*255.0f))
3170 {
3171 if (x < xMin) xMin = x;
3172 if (x > xMax) xMax = x;
3173 if (y < yMin) yMin = y;
3174 if (y > yMax) yMax = y;
3175 }
3176 }
3177 }
3178
3179 // Check for empty blank image
3180 if ((xMin != 65536) && (xMax != 65536))
3181 {
3182 crop = (Rectangle){ (float)xMin, (float)yMin, (float)((xMax + 1) - xMin), (float)((yMax + 1) - yMin) };
3183 }
3184
3185 UnloadImageColors(pixels);
3186 }
3187
3188 return crop;
3189 }
3190
3191 // Get image pixel color at (x, y) position
3192 Color GetImageColor(Image image, int x, int y)
3193 {
3194 Color color = { 0 };
3195
3196 if ((x >=0) && (x < image.width) && (y >= 0) && (y < image.height))
3197 {
3198 switch (image.format)
3199 {
3200 case PIXELFORMAT_UNCOMPRESSED_GRAYSCALE:
3201 {
3202 color.r = ((unsigned char *)image.data)[y*image.width + x];
3203 color.g = ((unsigned char *)image.data)[y*image.width + x];
3204 color.b = ((unsigned char *)image.data)[y*image.width + x];
3205 color.a = 255;
3206
3207 } break;
3208 case PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA:
3209 {
3210 color.r = ((unsigned char *)image.data)[(y*image.width + x)*2];
3211 color.g = ((unsigned char *)image.data)[(y*image.width + x)*2];
3212 color.b = ((unsigned char *)image.data)[(y*image.width + x)*2];
3213 color.a = ((unsigned char *)image.data)[(y*image.width + x)*2 + 1];
3214
3215 } break;
3216 case PIXELFORMAT_UNCOMPRESSED_R5G5B5A1:
3217 {
3218 unsigned short pixel = ((unsigned short *)image.data)[y*image.width + x];
3219
3220 color.r = (unsigned char)((float)((pixel & 0b1111100000000000) >> 11)*(255/31));
3221 color.g = (unsigned char)((float)((pixel & 0b0000011111000000) >> 6)*(255/31));
3222 color.b = (unsigned char)((float)((pixel & 0b0000000000111110) >> 1)*(255/31));
3223 color.a = (unsigned char)((pixel & 0b0000000000000001)*255);
3224
3225 } break;
3226 case PIXELFORMAT_UNCOMPRESSED_R5G6B5:
3227 {
3228 unsigned short pixel = ((unsigned short *)image.data)[y*image.width + x];
3229
3230 color.r = (unsigned char)((float)((pixel & 0b1111100000000000) >> 11)*(255/31));
3231 color.g = (unsigned char)((float)((pixel & 0b0000011111100000) >> 5)*(255/63));
3232 color.b = (unsigned char)((float)(pixel & 0b0000000000011111)*(255/31));
3233 color.a = 255;
3234
3235 } break;
3236 case PIXELFORMAT_UNCOMPRESSED_R4G4B4A4:
3237 {
3238 unsigned short pixel = ((unsigned short *)image.data)[y*image.width + x];
3239
3240 color.r = (unsigned char)((float)((pixel & 0b1111000000000000) >> 12)*(255/15));
3241 color.g = (unsigned char)((float)((pixel & 0b0000111100000000) >> 8)*(255/15));
3242 color.b = (unsigned char)((float)((pixel & 0b0000000011110000) >> 4)*(255/15));
3243 color.a = (unsigned char)((float)(pixel & 0b0000000000001111)*(255/15));
3244
3245 } break;
3246 case PIXELFORMAT_UNCOMPRESSED_R8G8B8A8:
3247 {
3248 color.r = ((unsigned char *)image.data)[(y*image.width + x)*4];
3249 color.g = ((unsigned char *)image.data)[(y*image.width + x)*4 + 1];
3250 color.b = ((unsigned char *)image.data)[(y*image.width + x)*4 + 2];
3251 color.a = ((unsigned char *)image.data)[(y*image.width + x)*4 + 3];
3252
3253 } break;
3254 case PIXELFORMAT_UNCOMPRESSED_R8G8B8:
3255 {
3256 color.r = (unsigned char)((unsigned char *)image.data)[(y*image.width + x)*3];
3257 color.g = (unsigned char)((unsigned char *)image.data)[(y*image.width + x)*3 + 1];
3258 color.b = (unsigned char)((unsigned char *)image.data)[(y*image.width + x)*3 + 2];
3259 color.a = 255;
3260
3261 } break;
3262 case PIXELFORMAT_UNCOMPRESSED_R32:
3263 {
3264 color.r = (unsigned char)(((float *)image.data)[y*image.width + x]*255.0f);
3265 color.g = 0;
3266 color.b = 0;
3267 color.a = 255;
3268
3269 } break;
3270 case PIXELFORMAT_UNCOMPRESSED_R32G32B32:
3271 {
3272 color.r = (unsigned char)(((float *)image.data)[(y*image.width + x)*3]*255.0f);
3273 color.g = (unsigned char)(((float *)image.data)[(y*image.width + x)*3 + 1]*255.0f);
3274 color.b = (unsigned char)(((float *)image.data)[(y*image.width + x)*3 + 2]*255.0f);
3275 color.a = 255;
3276
3277 } break;
3278 case PIXELFORMAT_UNCOMPRESSED_R32G32B32A32:
3279 {
3280 color.r = (unsigned char)(((float *)image.data)[(y*image.width + x)*4]*255.0f);
3281 color.g = (unsigned char)(((float *)image.data)[(y*image.width + x)*4 + 1]*255.0f);
3282 color.b = (unsigned char)(((float *)image.data)[(y*image.width + x)*4 + 2]*255.0f);
3283 color.a = (unsigned char)(((float *)image.data)[(y*image.width + x)*4 + 3]*255.0f);
3284
3285 } break;
3286 case PIXELFORMAT_UNCOMPRESSED_R16:
3287 {
3288 color.r = (unsigned char)(HalfToFloat(((unsigned short *)image.data)[y*image.width + x])*255.0f);
3289 color.g = 0;
3290 color.b = 0;
3291 color.a = 255;
3292
3293 } break;
3294 case PIXELFORMAT_UNCOMPRESSED_R16G16B16:
3295 {
3296 color.r = (unsigned char)(HalfToFloat(((unsigned short *)image.data)[(y*image.width + x)*3])*255.0f);
3297 color.g = (unsigned char)(HalfToFloat(((unsigned short *)image.data)[(y*image.width + x)*3 + 1])*255.0f);
3298 color.b = (unsigned char)(HalfToFloat(((unsigned short *)image.data)[(y*image.width + x)*3 + 2])*255.0f);
3299 color.a = 255;
3300
3301 } break;
3302 case PIXELFORMAT_UNCOMPRESSED_R16G16B16A16:
3303 {
3304 color.r = (unsigned char)(HalfToFloat(((unsigned short *)image.data)[(y*image.width + x)*4])*255.0f);
3305 color.g = (unsigned char)(HalfToFloat(((unsigned short *)image.data)[(y*image.width + x)*4 + 1])*255.0f);
3306 color.b = (unsigned char)(HalfToFloat(((unsigned short *)image.data)[(y*image.width + x)*4 + 2])*255.0f);
3307 color.a = (unsigned char)(HalfToFloat(((unsigned short *)image.data)[(y*image.width + x)*4 + 3])*255.0f);
3308
3309 } break;
3310 default: TRACELOG(LOG_WARNING, "Compressed image format does not support color reading"); break;
3311 }
3312 }
3313 else TRACELOG(LOG_WARNING, "Requested image pixel (%i, %i) out of bounds", x, y);
3314
3315 return color;
3316 }
3317
3318 //------------------------------------------------------------------------------------
3319 // Image drawing functions
3320 //------------------------------------------------------------------------------------
3321 // Clear image background with given color
3322 void ImageClearBackground(Image *dst, Color color)
3323 {
3324 // Security check to avoid program crash
3325 if ((dst->data == NULL) || (dst->width == 0) || (dst->height == 0)) return;
3326
3327 // Fill in first pixel based on image format
3328 ImageDrawPixel(dst, 0, 0, color);
3329
3330 unsigned char *pSrcPixel = (unsigned char *)dst->data;
3331 int bytesPerPixel = GetPixelDataSize(1, 1, dst->format);
3332 int totalPixels = dst->width*dst->height;
3333
3334 // Repeat the first pixel data throughout the image,
3335 // doubling the pixels copied on each iteration
3336 for (int i = 1; i < totalPixels; i *= 2)
3337 {
3338 int pixelsToCopy = MIN(i, totalPixels - i);
3339 memcpy(pSrcPixel + i*bytesPerPixel, pSrcPixel, pixelsToCopy*bytesPerPixel);
3340 }
3341 }
3342
3343 // Draw pixel within an image
3344 // NOTE: Compressed image formats not supported
3345 void ImageDrawPixel(Image *dst, int x, int y, Color color)
3346 {
3347 // Security check to avoid program crash
3348 if ((dst->data == NULL) || (x < 0) || (x >= dst->width) || (y < 0) || (y >= dst->height)) return;
3349
3350 switch (dst->format)
3351 {
3352 case PIXELFORMAT_UNCOMPRESSED_GRAYSCALE:
3353 {
3354 // NOTE: Calculate grayscale equivalent color
3355 Vector3 coln = { (float)color.r/255.0f, (float)color.g/255.0f, (float)color.b/255.0f };
3356 unsigned char gray = (unsigned char)((coln.x*0.299f + coln.y*0.587f + coln.z*0.114f)*255.0f);
3357
3358 ((unsigned char *)dst->data)[y*dst->width + x] = gray;
3359
3360 } break;
3361 case PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA:
3362 {
3363 // NOTE: Calculate grayscale equivalent color
3364 Vector3 coln = { (float)color.r/255.0f, (float)color.g/255.0f, (float)color.b/255.0f };
3365 unsigned char gray = (unsigned char)((coln.x*0.299f + coln.y*0.587f + coln.z*0.114f)*255.0f);
3366
3367 ((unsigned char *)dst->data)[(y*dst->width + x)*2] = gray;
3368 ((unsigned char *)dst->data)[(y*dst->width + x)*2 + 1] = color.a;
3369
3370 } break;
3371 case PIXELFORMAT_UNCOMPRESSED_R5G6B5:
3372 {
3373 // NOTE: Calculate R5G6B5 equivalent color
3374 Vector3 coln = { (float)color.r/255.0f, (float)color.g/255.0f, (float)color.b/255.0f };
3375
3376 unsigned char r = (unsigned char)(round(coln.x*31.0f));
3377 unsigned char g = (unsigned char)(round(coln.y*63.0f));
3378 unsigned char b = (unsigned char)(round(coln.z*31.0f));
3379
3380 ((unsigned short *)dst->data)[y*dst->width + x] = (unsigned short)r << 11 | (unsigned short)g << 5 | (unsigned short)b;
3381
3382 } break;
3383 case PIXELFORMAT_UNCOMPRESSED_R5G5B5A1:
3384 {
3385 // NOTE: Calculate R5G5B5A1 equivalent color
3386 Vector4 coln = { (float)color.r/255.0f, (float)color.g/255.0f, (float)color.b/255.0f, (float)color.a/255.0f };
3387
3388 unsigned char r = (unsigned char)(round(coln.x*31.0f));
3389 unsigned char g = (unsigned char)(round(coln.y*31.0f));
3390 unsigned char b = (unsigned char)(round(coln.z*31.0f));
3391 unsigned char a = (coln.w > ((float)PIXELFORMAT_UNCOMPRESSED_R5G5B5A1_ALPHA_THRESHOLD/255.0f))? 1 : 0;
3392
3393 ((unsigned short *)dst->data)[y*dst->width + x] = (unsigned short)r << 11 | (unsigned short)g << 6 | (unsigned short)b << 1 | (unsigned short)a;
3394
3395 } break;
3396 case PIXELFORMAT_UNCOMPRESSED_R4G4B4A4:
3397 {
3398 // NOTE: Calculate R5G5B5A1 equivalent color
3399 Vector4 coln = { (float)color.r/255.0f, (float)color.g/255.0f, (float)color.b/255.0f, (float)color.a/255.0f };
3400
3401 unsigned char r = (unsigned char)(round(coln.x*15.0f));
3402 unsigned char g = (unsigned char)(round(coln.y*15.0f));
3403 unsigned char b = (unsigned char)(round(coln.z*15.0f));
3404 unsigned char a = (unsigned char)(round(coln.w*15.0f));
3405
3406 ((unsigned short *)dst->data)[y*dst->width + x] = (unsigned short)r << 12 | (unsigned short)g << 8 | (unsigned short)b << 4 | (unsigned short)a;
3407
3408 } break;
3409 case PIXELFORMAT_UNCOMPRESSED_R8G8B8:
3410 {
3411 ((unsigned char *)dst->data)[(y*dst->width + x)*3] = color.r;
3412 ((unsigned char *)dst->data)[(y*dst->width + x)*3 + 1] = color.g;
3413 ((unsigned char *)dst->data)[(y*dst->width + x)*3 + 2] = color.b;
3414
3415 } break;
3416 case PIXELFORMAT_UNCOMPRESSED_R8G8B8A8:
3417 {
3418 ((unsigned char *)dst->data)[(y*dst->width + x)*4] = color.r;
3419 ((unsigned char *)dst->data)[(y*dst->width + x)*4 + 1] = color.g;
3420 ((unsigned char *)dst->data)[(y*dst->width + x)*4 + 2] = color.b;
3421 ((unsigned char *)dst->data)[(y*dst->width + x)*4 + 3] = color.a;
3422
3423 } break;
3424 case PIXELFORMAT_UNCOMPRESSED_R32:
3425 {
3426 // NOTE: Calculate grayscale equivalent color (normalized to 32bit)
3427 Vector3 coln = { (float)color.r/255.0f, (float)color.g/255.0f, (float)color.b/255.0f };
3428
3429 ((float *)dst->data)[y*dst->width + x] = coln.x*0.299f + coln.y*0.587f + coln.z*0.114f;
3430
3431 } break;
3432 case PIXELFORMAT_UNCOMPRESSED_R32G32B32:
3433 {
3434 // NOTE: Calculate R32G32B32 equivalent color (normalized to 32bit)
3435 Vector3 coln = { (float)color.r/255.0f, (float)color.g/255.0f, (float)color.b/255.0f };
3436
3437 ((float *)dst->data)[(y*dst->width + x)*3] = coln.x;
3438 ((float *)dst->data)[(y*dst->width + x)*3 + 1] = coln.y;
3439 ((float *)dst->data)[(y*dst->width + x)*3 + 2] = coln.z;
3440 } break;
3441 case PIXELFORMAT_UNCOMPRESSED_R32G32B32A32:
3442 {
3443 // NOTE: Calculate R32G32B32A32 equivalent color (normalized to 32bit)
3444 Vector4 coln = { (float)color.r/255.0f, (float)color.g/255.0f, (float)color.b/255.0f, (float)color.a/255.0f };
3445
3446 ((float *)dst->data)[(y*dst->width + x)*4] = coln.x;
3447 ((float *)dst->data)[(y*dst->width + x)*4 + 1] = coln.y;
3448 ((float *)dst->data)[(y*dst->width + x)*4 + 2] = coln.z;
3449 ((float *)dst->data)[(y*dst->width + x)*4 + 3] = coln.w;
3450
3451 } break;
3452 case PIXELFORMAT_UNCOMPRESSED_R16:
3453 {
3454 // NOTE: Calculate grayscale equivalent color (normalized to 32bit)
3455 Vector3 coln = { (float)color.r/255.0f, (float)color.g/255.0f, (float)color.b/255.0f };
3456
3457 ((unsigned short*)dst->data)[y*dst->width + x] = FloatToHalf(coln.x*0.299f + coln.y*0.587f + coln.z*0.114f);
3458
3459 } break;
3460 case PIXELFORMAT_UNCOMPRESSED_R16G16B16:
3461 {
3462 // NOTE: Calculate R32G32B32 equivalent color (normalized to 32bit)
3463 Vector3 coln = { (float)color.r/255.0f, (float)color.g/255.0f, (float)color.b/255.0f };
3464
3465 ((unsigned short *)dst->data)[(y*dst->width + x)*3] = FloatToHalf(coln.x);
3466 ((unsigned short *)dst->data)[(y*dst->width + x)*3 + 1] = FloatToHalf(coln.y);
3467 ((unsigned short *)dst->data)[(y*dst->width + x)*3 + 2] = FloatToHalf(coln.z);
3468 } break;
3469 case PIXELFORMAT_UNCOMPRESSED_R16G16B16A16:
3470 {
3471 // NOTE: Calculate R32G32B32A32 equivalent color (normalized to 32bit)
3472 Vector4 coln = { (float)color.r/255.0f, (float)color.g/255.0f, (float)color.b/255.0f, (float)color.a/255.0f };
3473
3474 ((unsigned short *)dst->data)[(y*dst->width + x)*4] = FloatToHalf(coln.x);
3475 ((unsigned short *)dst->data)[(y*dst->width + x)*4 + 1] = FloatToHalf(coln.y);
3476 ((unsigned short *)dst->data)[(y*dst->width + x)*4 + 2] = FloatToHalf(coln.z);
3477 ((unsigned short *)dst->data)[(y*dst->width + x)*4 + 3] = FloatToHalf(coln.w);
3478
3479 } break;
3480 default: break;
3481 }
3482 }
3483
3484 // Draw pixel within an image (Vector version)
3485 void ImageDrawPixelV(Image *dst, Vector2 position, Color color)
3486 {
3487 ImageDrawPixel(dst, (int)position.x, (int)position.y, color);
3488 }
3489
3490 // Draw line within an image
3491 void ImageDrawLine(Image *dst, int startPosX, int startPosY, int endPosX, int endPosY, Color color)
3492 {
3493 // Calculate differences in coordinates
3494 int shortLen = endPosY - startPosY;
3495 int longLen = endPosX - startPosX;
3496 bool yLonger = false;
3497
3498 // Determine if the line is more vertical than horizontal
3499 if (abs(shortLen) > abs(longLen))
3500 {
3501 // Swap the lengths if the line is more vertical
3502 int temp = shortLen;
3503 shortLen = longLen;
3504 longLen = temp;
3505 yLonger = true;
3506 }
3507
3508 // Initialize variables for drawing loop
3509 int endVal = longLen;
3510 int sgnInc = 1;
3511
3512 // Adjust direction increment based on longLen sign
3513 if (longLen < 0)
3514 {
3515 longLen = -longLen;
3516 sgnInc = -1;
3517 }
3518
3519 // Calculate fixed-point increment for shorter length
3520 int decInc = (longLen == 0)? 0 : (shortLen << 16)/longLen;
3521
3522 // Draw the line pixel by pixel
3523 if (yLonger)
3524 {
3525 // If line is more vertical, iterate over y-axis
3526 for (int i = 0, j = 0; i != endVal; i += sgnInc, j += decInc)
3527 {
3528 // Calculate pixel position and draw it
3529 ImageDrawPixel(dst, startPosX + (j >> 16), startPosY + i, color);
3530 }
3531 }
3532 else
3533 {
3534 // If line is more horizontal, iterate over x-axis
3535 for (int i = 0, j = 0; i != endVal; i += sgnInc, j += decInc)
3536 {
3537 // Calculate pixel position and draw it
3538 ImageDrawPixel(dst, startPosX + i, startPosY + (j >> 16), color);
3539 }
3540 }
3541 }
3542
3543 // Draw line within an image (Vector version)
3544 void ImageDrawLineV(Image *dst, Vector2 start, Vector2 end, Color color)
3545 {
3546 // Round start and end positions to nearest integer coordinates
3547 int x1 = (int)(start.x + 0.5f);
3548 int y1 = (int)(start.y + 0.5f);
3549 int x2 = (int)(end.x + 0.5f);
3550 int y2 = (int)(end.y + 0.5f);
3551
3552 // Draw a vertical line using ImageDrawLine function
3553 ImageDrawLine(dst, x1, y1, x2, y2, color);
3554 }
3555
3556 // Draw a line defining thickness within an image
3557 void ImageDrawLineEx(Image *dst, Vector2 start, Vector2 end, int thick, Color color)
3558 {
3559 // Round start and end positions to nearest integer coordinates
3560 int x1 = (int)(start.x + 0.5f);
3561 int y1 = (int)(start.y + 0.5f);
3562 int x2 = (int)(end.x + 0.5f);
3563 int y2 = (int)(end.y + 0.5f);
3564
3565 // Calculate differences in x and y coordinates
3566 int dx = x2 - x1;
3567 int dy = y2 - y1;
3568
3569 // Determine if the line is more horizontal or vertical
3570 if ((dx != 0) && (abs(dy/dx) < 1))
3571 {
3572 // Line is more horizontal
3573
3574 // How many additional lines to draw
3575 int wy = thick - 1;
3576
3577 // Draw the main line and lower half
3578 for (int i = 0; i <= ((wy+1)/2); i++)
3579 {
3580 ImageDrawLine(dst, x1, y1 + i, x2, y2 + i, color);
3581 }
3582
3583 // Draw the upper half
3584 for (int i = 1; i <= (wy/2); i++)
3585 {
3586 ImageDrawLine(dst, x1, y1 - i, x2, y2 - i, color);
3587 }
3588 }
3589 else if (dy != 0)
3590 {
3591 // Line is more vertical or perfectly horizontal
3592
3593 // How many additional lines to draw
3594 int wx = thick - 1;
3595
3596 //Draw the main line and right half
3597 for (int i = 0; i <= ((wx+1)/2); i++)
3598 {
3599 ImageDrawLine(dst, x1 + i, y1, x2 + i, y2, color);
3600 }
3601
3602 // Draw the left half
3603 for (int i = 1; i <= (wx/2); i++)
3604 {
3605 ImageDrawLine(dst, x1 - i, y1, x2 - i, y2, color);
3606 }
3607 }
3608 }
3609
3610 // Draw circle within an image
3611 void ImageDrawCircle(Image *dst, int centerX, int centerY, int radius, Color color)
3612 {
3613 int x = 0;
3614 int y = radius;
3615 int decesionParameter = 3 - 2*radius;
3616
3617 while (y >= x)
3618 {
3619 ImageDrawRectangle(dst, centerX - x, centerY + y, x*2, 1, color);
3620 ImageDrawRectangle(dst, centerX - x, centerY - y, x*2, 1, color);
3621 ImageDrawRectangle(dst, centerX - y, centerY + x, y*2, 1, color);
3622 ImageDrawRectangle(dst, centerX - y, centerY - x, y*2, 1, color);
3623 x++;
3624
3625 if (decesionParameter > 0)
3626 {
3627 y--;
3628 decesionParameter = decesionParameter + 4*(x - y) + 10;
3629 }
3630 else decesionParameter = decesionParameter + 4*x + 6;
3631 }
3632 }
3633
3634 // Draw circle within an image (Vector version)
3635 void ImageDrawCircleV(Image *dst, Vector2 center, int radius, Color color)
3636 {
3637 ImageDrawCircle(dst, (int)center.x, (int)center.y, radius, color);
3638 }
3639
3640 // Draw circle outline within an image
3641 void ImageDrawCircleLines(Image *dst, int centerX, int centerY, int radius, Color color)
3642 {
3643 int x = 0;
3644 int y = radius;
3645 int decesionParameter = 3 - 2*radius;
3646
3647 while (y >= x)
3648 {
3649 ImageDrawPixel(dst, centerX + x, centerY + y, color);
3650 ImageDrawPixel(dst, centerX - x, centerY + y, color);
3651 ImageDrawPixel(dst, centerX + x, centerY - y, color);
3652 ImageDrawPixel(dst, centerX - x, centerY - y, color);
3653 ImageDrawPixel(dst, centerX + y, centerY + x, color);
3654 ImageDrawPixel(dst, centerX - y, centerY + x, color);
3655 ImageDrawPixel(dst, centerX + y, centerY - x, color);
3656 ImageDrawPixel(dst, centerX - y, centerY - x, color);
3657 x++;
3658
3659 if (decesionParameter > 0)
3660 {
3661 y--;
3662 decesionParameter = decesionParameter + 4*(x - y) + 10;
3663 }
3664 else decesionParameter = decesionParameter + 4*x + 6;
3665 }
3666 }
3667
3668 // Draw circle outline within an image (Vector version)
3669 void ImageDrawCircleLinesV(Image *dst, Vector2 center, int radius, Color color)
3670 {
3671 ImageDrawCircleLines(dst, (int)center.x, (int)center.y, radius, color);
3672 }
3673
3674 // Draw rectangle within an image
3675 void ImageDrawRectangle(Image *dst, int posX, int posY, int width, int height, Color color)
3676 {
3677 ImageDrawRectangleRec(dst, (Rectangle){ (float)posX, (float)posY, (float)width, (float)height }, color);
3678 }
3679
3680 // Draw rectangle within an image (Vector version)
3681 void ImageDrawRectangleV(Image *dst, Vector2 position, Vector2 size, Color color)
3682 {
3683 ImageDrawRectangle(dst, (int)position.x, (int)position.y, (int)size.x, (int)size.y, color);
3684 }
3685
3686 // Draw rectangle within an image
3687 void ImageDrawRectangleRec(Image *dst, Rectangle rec, Color color)
3688 {
3689 // Security check to avoid program crash
3690 if ((dst->data == NULL) || (dst->width == 0) || (dst->height == 0)) return;
3691
3692 // Security check to avoid drawing out of bounds in case of bad user data
3693 if (rec.x < 0) { rec.width += rec.x; rec.x = 0; }
3694 if (rec.y < 0) { rec.height += rec.y; rec.y = 0; }
3695 if (rec.width < 0) rec.width = 0;
3696 if (rec.height < 0) rec.height = 0;
3697
3698 // Clamp the size the the image bounds
3699 if ((rec.x + rec.width) >= dst->width) rec.width = dst->width - rec.x;
3700 if ((rec.y + rec.height) >= dst->height) rec.height = dst->height - rec.y;
3701
3702 // Check if the rect is even inside the image
3703 if ((rec.x >= dst->width) || (rec.y >= dst->height)) return;
3704 if (((rec.x + rec.width) <= 0) || (rec.y + rec.height <= 0)) return;
3705
3706 int sy = (int)rec.y;
3707 int sx = (int)rec.x;
3708
3709 int bytesPerPixel = GetPixelDataSize(1, 1, dst->format);
3710
3711 // Fill in the first pixel of the first row based on image format
3712 ImageDrawPixel(dst, sx, sy, color);
3713
3714 int bytesOffset = ((sy*dst->width) + sx)*bytesPerPixel;
3715 unsigned char *pSrcPixel = (unsigned char *)dst->data + bytesOffset;
3716
3717 // Repeat the first pixel data throughout the row
3718 for (int x = 1; x < (int)rec.width; x *= 2)
3719 {
3720 int pixelsToCopy = MIN(x, (int)rec.width - x);
3721 memcpy(pSrcPixel + x*bytesPerPixel, pSrcPixel, pixelsToCopy*bytesPerPixel);
3722 }
3723
3724 // Repeat the first row data for all other rows
3725 int bytesPerRow = bytesPerPixel*(int)rec.width;
3726 for (int y = 1; y < (int)rec.height; y++)
3727 {
3728 memcpy(pSrcPixel + (y*dst->width)*bytesPerPixel, pSrcPixel, bytesPerRow);
3729 }
3730 }
3731
3732 // Draw rectangle lines within an image
3733 void ImageDrawRectangleLines(Image *dst, Rectangle rec, int thick, Color color)
3734 {
3735 ImageDrawRectangle(dst, (int)rec.x, (int)rec.y, (int)rec.width, thick, color);
3736 ImageDrawRectangle(dst, (int)rec.x, (int)(rec.y + thick), thick, (int)(rec.height - thick*2), color);
3737 ImageDrawRectangle(dst, (int)(rec.x + rec.width - thick), (int)(rec.y + thick), thick, (int)(rec.height - thick*2), color);
3738 ImageDrawRectangle(dst, (int)rec.x, (int)(rec.y + rec.height - thick), (int)rec.width, thick, color);
3739 }
3740
3741 // Draw triangle within an image
3742 void ImageDrawTriangle(Image *dst, Vector2 v1, Vector2 v2, Vector2 v3, Color color)
3743 {
3744 // Calculate the 2D bounding box of the triangle
3745 // Determine the minimum and maximum x and y coordinates of the triangle vertices
3746 int xMin = (int)((v1.x < v2.x)? ((v1.x < v3.x)? v1.x : v3.x) : ((v2.x < v3.x)? v2.x : v3.x));
3747 int yMin = (int)((v1.y < v2.y)? ((v1.y < v3.y)? v1.y : v3.y) : ((v2.y < v3.y)? v2.y : v3.y));
3748 int xMax = (int)((v1.x > v2.x)? ((v1.x > v3.x)? v1.x : v3.x) : ((v2.x > v3.x)? v2.x : v3.x));
3749 int yMax = (int)((v1.y > v2.y)? ((v1.y > v3.y)? v1.y : v3.y) : ((v2.y > v3.y)? v2.y : v3.y));
3750
3751 // Clamp the bounding box to the image dimensions
3752 if (xMin < 0) xMin = 0;
3753 if (yMin < 0) yMin = 0;
3754 if (xMax > dst->width) xMax = dst->width;
3755 if (yMax > dst->height) yMax = dst->height;
3756
3757 // Check the order of the vertices to determine if it's a front or back face
3758 // NOTE: if signedArea is equal to 0, the face is degenerate
3759 float signedArea = (v2.x - v1.x)*(v3.y - v1.y) - (v3.x - v1.x)*(v2.y - v1.y);
3760 bool isBackFace = (signedArea > 0);
3761
3762 // Barycentric interpolation setup
3763 // Calculate the step increments for the barycentric coordinates
3764 int w1XStep = (int)(v3.y - v2.y), w1YStep = (int)(v2.x - v3.x);
3765 int w2XStep = (int)(v1.y - v3.y), w2YStep = (int)(v3.x - v1.x);
3766 int w3XStep = (int)(v2.y - v1.y), w3YStep = (int)(v1.x - v2.x);
3767
3768 // If the triangle is a back face, invert the steps
3769 if (isBackFace)
3770 {
3771 w1XStep = -w1XStep, w1YStep = -w1YStep;
3772 w2XStep = -w2XStep, w2YStep = -w2YStep;
3773 w3XStep = -w3XStep, w3YStep = -w3YStep;
3774 }
3775
3776 // Calculate the initial barycentric coordinates for the top-left point of the bounding box
3777 int w1Row = (int)((xMin - v2.x)*w1XStep + w1YStep*(yMin - v2.y));
3778 int w2Row = (int)((xMin - v3.x)*w2XStep + w2YStep*(yMin - v3.y));
3779 int w3Row = (int)((xMin - v1.x)*w3XStep + w3YStep*(yMin - v1.y));
3780
3781 // Rasterization loop
3782 // Iterate through each pixel in the bounding box
3783 for (int y = yMin; y <= yMax; y++)
3784 {
3785 int w1 = w1Row;
3786 int w2 = w2Row;
3787 int w3 = w3Row;
3788
3789 for (int x = xMin; x <= xMax; x++)
3790 {
3791 // Check if the pixel is inside the triangle using barycentric coordinates
3792 // If it is, the pixel can be drawn with the given color
3793 if ((w1 | w2 | w3) >= 0) ImageDrawPixel(dst, x, y, color);
3794
3795 // Increment the barycentric coordinates for the next pixel
3796 w1 += w1XStep;
3797 w2 += w2XStep;
3798 w3 += w3XStep;
3799 }
3800
3801 // Move to the next row in the bounding box
3802 w1Row += w1YStep;
3803 w2Row += w2YStep;
3804 w3Row += w3YStep;
3805 }
3806 }
3807
3808 // Draw triangle with interpolated colors within an image
3809 void ImageDrawTriangleEx(Image *dst, Vector2 v1, Vector2 v2, Vector2 v3, Color c1, Color c2, Color c3)
3810 {
3811 // Calculate the 2D bounding box of the triangle
3812 // Determine the minimum and maximum x and y coordinates of the triangle vertices
3813 int xMin = (int)((v1.x < v2.x)? ((v1.x < v3.x)? v1.x : v3.x) : ((v2.x < v3.x)? v2.x : v3.x));
3814 int yMin = (int)((v1.y < v2.y)? ((v1.y < v3.y)? v1.y : v3.y) : ((v2.y < v3.y)? v2.y : v3.y));
3815 int xMax = (int)((v1.x > v2.x)? ((v1.x > v3.x)? v1.x : v3.x) : ((v2.x > v3.x)? v2.x : v3.x));
3816 int yMax = (int)((v1.y > v2.y)? ((v1.y > v3.y)? v1.y : v3.y) : ((v2.y > v3.y)? v2.y : v3.y));
3817
3818 // Clamp the bounding box to the image dimensions
3819 if (xMin < 0) xMin = 0;
3820 if (yMin < 0) yMin = 0;
3821 if (xMax > dst->width) xMax = dst->width;
3822 if (yMax > dst->height) yMax = dst->height;
3823
3824 // Check the order of the vertices to determine if it's a front or back face
3825 // NOTE: if signedArea is equal to 0, the face is degenerate
3826 float signedArea = (v2.x - v1.x)*(v3.y - v1.y) - (v3.x - v1.x)*(v2.y - v1.y);
3827 bool isBackFace = (signedArea > 0);
3828
3829 // Barycentric interpolation setup
3830 // Calculate the step increments for the barycentric coordinates
3831 int w1XStep = (int)(v3.y - v2.y), w1YStep = (int)(v2.x - v3.x);
3832 int w2XStep = (int)(v1.y - v3.y), w2YStep = (int)(v3.x - v1.x);
3833 int w3XStep = (int)(v2.y - v1.y), w3YStep = (int)(v1.x - v2.x);
3834
3835 // If the triangle is a back face, invert the steps
3836 if (isBackFace)
3837 {
3838 w1XStep = -w1XStep, w1YStep = -w1YStep;
3839 w2XStep = -w2XStep, w2YStep = -w2YStep;
3840 w3XStep = -w3XStep, w3YStep = -w3YStep;
3841 }
3842
3843 // Calculate the initial barycentric coordinates for the top-left point of the bounding box
3844 int w1Row = (int)((xMin - v2.x)*w1XStep + w1YStep*(yMin - v2.y));
3845 int w2Row = (int)((xMin - v3.x)*w2XStep + w2YStep*(yMin - v3.y));
3846 int w3Row = (int)((xMin - v1.x)*w3XStep + w3YStep*(yMin - v1.y));
3847
3848 // Calculate the inverse of the sum of the barycentric coordinates for normalization
3849 float wInvSum = 255.0f/(w1Row + w2Row + w3Row);
3850
3851 // Rasterization loop
3852 // Iterate through each pixel in the bounding box
3853 for (int y = yMin; y <= yMax; y++)
3854 {
3855 int w1 = w1Row;
3856 int w2 = w2Row;
3857 int w3 = w3Row;
3858
3859 for (int x = xMin; x <= xMax; x++)
3860 {
3861 // Check if the pixel is inside the triangle using barycentric coordinates
3862 if ((w1 | w2 | w3) >= 0)
3863 {
3864 // Compute the normalized barycentric coordinates
3865 unsigned char aW1 = (unsigned char)((float)w1*wInvSum);
3866 unsigned char aW2 = (unsigned char)((float)w2*wInvSum);
3867 unsigned char aW3 = (unsigned char)((float)w3*wInvSum);
3868
3869 // Interpolate the color using the barycentric coordinates
3870 Color finalColor = { 0 };
3871 finalColor.r = (c1.r*aW1 + c2.r*aW2 + c3.r*aW3)/255;
3872 finalColor.g = (c1.g*aW1 + c2.g*aW2 + c3.g*aW3)/255;
3873 finalColor.b = (c1.b*aW1 + c2.b*aW2 + c3.b*aW3)/255;
3874 finalColor.a = (c1.a*aW1 + c2.a*aW2 + c3.a*aW3)/255;
3875
3876 // Draw the pixel with the interpolated color
3877 ImageDrawPixel(dst, x, y, finalColor);
3878 }
3879
3880 // Increment the barycentric coordinates for the next pixel
3881 w1 += w1XStep;
3882 w2 += w2XStep;
3883 w3 += w3XStep;
3884 }
3885
3886 // Move to the next row in the bounding box
3887 w1Row += w1YStep;
3888 w2Row += w2YStep;
3889 w3Row += w3YStep;
3890 }
3891 }
3892
3893 // Draw triangle outline within an image
3894 void ImageDrawTriangleLines(Image *dst, Vector2 v1, Vector2 v2, Vector2 v3, Color color)
3895 {
3896 ImageDrawLine(dst, (int)v1.x, (int)v1.y, (int)v2.x, (int)v2.y, color);
3897 ImageDrawLine(dst, (int)v2.x, (int)v2.y, (int)v3.x, (int)v3.y, color);
3898 ImageDrawLine(dst, (int)v3.x, (int)v3.y, (int)v1.x, (int)v1.y, color);
3899 }
3900
3901 // Draw a triangle fan defined by points within an image (first vertex is the center)
3902 void ImageDrawTriangleFan(Image *dst, const Vector2 *points, int pointCount, Color color)
3903 {
3904 if (pointCount >= 3)
3905 {
3906 for (int i = 1; i < pointCount - 1; i++)
3907 {
3908 ImageDrawTriangle(dst, points[0], points[i], points[i + 1], color);
3909 }
3910 }
3911 }
3912
3913 // Draw a triangle strip defined by points within an image
3914 void ImageDrawTriangleStrip(Image *dst, const Vector2 *points, int pointCount, Color color)
3915 {
3916 if (pointCount >= 3)
3917 {
3918 for (int i = 2; i < pointCount; i++)
3919 {
3920 if ((i%2) == 0) ImageDrawTriangle(dst, points[i], points[i - 2], points[i - 1], color);
3921 else ImageDrawTriangle(dst, points[i], points[i - 1], points[i - 2], color);
3922 }
3923 }
3924 }
3925
3926 // Draw an image (source) within an image (destination)
3927 // NOTE: Color tint is applied to source image
3928 void ImageDraw(Image *dst, Image src, Rectangle srcRec, Rectangle dstRec, Color tint)
3929 {
3930 // Security check to avoid program crash
3931 if ((dst->data == NULL) || (dst->width == 0) || (dst->height == 0) ||
3932 (src.data == NULL) || (src.width == 0) || (src.height == 0)) return;
3933
3934 if (dst->format >= PIXELFORMAT_COMPRESSED_DXT1_RGB) TRACELOG(LOG_WARNING, "Image drawing not supported for compressed formats");
3935 else
3936 {
3937 Image srcMod = { 0 }; // Source copy (in case it was required)
3938 Image *srcPtr = &src; // Pointer to source image
3939 bool useSrcMod = false; // Track source copy required
3940
3941 // Source rectangle out-of-bounds security checks
3942 if (srcRec.x < 0) { srcRec.width += srcRec.x; srcRec.x = 0; }
3943 if (srcRec.y < 0) { srcRec.height += srcRec.y; srcRec.y = 0; }
3944 if ((srcRec.x + srcRec.width) > src.width) srcRec.width = src.width - srcRec.x;
3945 if ((srcRec.y + srcRec.height) > src.height) srcRec.height = src.height - srcRec.y;
3946
3947 // Check if source rectangle needs to be resized to destination rectangle
3948 // In that case, make a copy of source, and apply all required transform
3949 if (((int)srcRec.width != (int)dstRec.width) || ((int)srcRec.height != (int)dstRec.height))
3950 {
3951 srcMod = ImageFromImage(src, srcRec); // Create image from another image
3952 ImageResize(&srcMod, (int)dstRec.width, (int)dstRec.height); // Resize to destination rectangle
3953 srcRec = (Rectangle){ 0, 0, (float)srcMod.width, (float)srcMod.height };
3954
3955 srcPtr = &srcMod;
3956 useSrcMod = true;
3957 }
3958
3959 // Destination rectangle out-of-bounds security checks
3960 if (dstRec.x < 0)
3961 {
3962 srcRec.x -= dstRec.x;
3963 srcRec.width += dstRec.x;
3964 dstRec.x = 0;
3965 }
3966 else if ((dstRec.x + srcRec.width) > dst->width) srcRec.width = dst->width - dstRec.x;
3967
3968 if (dstRec.y < 0)
3969 {
3970 srcRec.y -= dstRec.y;
3971 srcRec.height += dstRec.y;
3972 dstRec.y = 0;
3973 }
3974 else if ((dstRec.y + srcRec.height) > dst->height) srcRec.height = dst->height - dstRec.y;
3975
3976 if (dst->width < srcRec.width) srcRec.width = (float)dst->width;
3977 if (dst->height < srcRec.height) srcRec.height = (float)dst->height;
3978
3979 // This blitting method is quite fast! The process followed is:
3980 // for every pixel -> [get_src_format/get_dst_format -> blend -> format_to_dst]
3981 // Some optimization ideas:
3982 // [x] Avoid creating source copy if not required (no resize required)
3983 // [x] Optimize ImageResize() for pixel format (alternative: ImageResizeNN())
3984 // [x] Optimize ColorAlphaBlend() to avoid processing (alpha = 0) and (alpha = 1)
3985 // [x] Optimize ColorAlphaBlend() for faster operations (maybe avoiding divs?)
3986 // [x] Consider fast path: no alpha blending required cases (src has no alpha)
3987 // [x] Consider fast path: same src/dst format with no alpha -> direct line copy
3988 // [-] GetPixelColor(): Get Vector4 instead of Color, easier for ColorAlphaBlend()
3989 // [ ] TODO: Support 16bit and 32bit (float) channels drawing
3990
3991 Color colSrc = { 0 };
3992 Color colDst = { 0 };
3993 Color blend = { 0 };
3994 bool blendRequired = true;
3995
3996 // Fast path: Avoid blend if source has no alpha to blend
3997 if ((tint.a == 255) &&
3998 ((srcPtr->format == PIXELFORMAT_UNCOMPRESSED_GRAYSCALE) ||
3999 (srcPtr->format == PIXELFORMAT_UNCOMPRESSED_R5G6B5) ||
4000 (srcPtr->format == PIXELFORMAT_UNCOMPRESSED_R8G8B8) ||
4001 (srcPtr->format == PIXELFORMAT_UNCOMPRESSED_R32) ||
4002 (srcPtr->format == PIXELFORMAT_UNCOMPRESSED_R32G32B32) ||
4003 (srcPtr->format == PIXELFORMAT_UNCOMPRESSED_R16) ||
4004 (srcPtr->format == PIXELFORMAT_UNCOMPRESSED_R16G16B16)))
4005 blendRequired = false;
4006
4007 int strideDst = GetPixelDataSize(dst->width, 1, dst->format);
4008 int bytesPerPixelDst = strideDst/(dst->width);
4009
4010 int strideSrc = GetPixelDataSize(srcPtr->width, 1, srcPtr->format);
4011 int bytesPerPixelSrc = strideSrc/(srcPtr->width);
4012
4013 unsigned char *pSrcBase = (unsigned char *)srcPtr->data + ((int)srcRec.y*srcPtr->width + (int)srcRec.x)*bytesPerPixelSrc;
4014 unsigned char *pDstBase = (unsigned char *)dst->data + ((int)dstRec.y*dst->width + (int)dstRec.x)*bytesPerPixelDst;
4015
4016 for (int y = 0; y < (int)srcRec.height; y++)
4017 {
4018 unsigned char *pSrc = pSrcBase;
4019 unsigned char *pDst = pDstBase;
4020
4021 // Fast path: Avoid moving pixel by pixel if no blend required and same format
4022 if (!blendRequired && (srcPtr->format == dst->format)) memcpy(pDst, pSrc, (int)(srcRec.width)*bytesPerPixelSrc);
4023 else
4024 {
4025 for (int x = 0; x < (int)srcRec.width; x++)
4026 {
4027 colSrc = GetPixelColor(pSrc, srcPtr->format);
4028 colDst = GetPixelColor(pDst, dst->format);
4029
4030 // Fast path: Avoid blend if source has no alpha to blend
4031 if (blendRequired) blend = ColorAlphaBlend(colDst, colSrc, tint);
4032 else blend = colSrc;
4033
4034 SetPixelColor(pDst, blend, dst->format);
4035
4036 pDst += bytesPerPixelDst;
4037 pSrc += bytesPerPixelSrc;
4038 }
4039 }
4040
4041 pSrcBase += strideSrc;
4042 pDstBase += strideDst;
4043 }
4044
4045 if (useSrcMod) UnloadImage(srcMod); // Unload source modified image
4046
4047 if ((dst->mipmaps > 1) && (src.mipmaps > 1))
4048 {
4049 Image mipmapDst = *dst;
4050 mipmapDst.data = (char *)mipmapDst.data + GetPixelDataSize(mipmapDst.width, mipmapDst.height, mipmapDst.format);
4051 mipmapDst.width /= 2;
4052 mipmapDst.height /= 2;
4053 mipmapDst.mipmaps--;
4054
4055 Image mipmapSrc = src;
4056 mipmapSrc.data = (char *)mipmapSrc.data + GetPixelDataSize(mipmapSrc.width, mipmapSrc.height, mipmapSrc.format);
4057 mipmapSrc.width /= 2;
4058 mipmapSrc.height /= 2;
4059 mipmapSrc.mipmaps--;
4060
4061 Rectangle mipmapSrcRec = srcRec;
4062 mipmapSrcRec.width /= 2;
4063 mipmapSrcRec.height /= 2;
4064 mipmapSrcRec.x /= 2;
4065 mipmapSrcRec.y /= 2;
4066
4067 Rectangle mipmapDstRec = dstRec;
4068 mipmapDstRec.width /= 2;
4069 mipmapDstRec.height /= 2;
4070 mipmapDstRec.x /= 2;
4071 mipmapDstRec.y /= 2;
4072
4073 ImageDraw(&mipmapDst, mipmapSrc, mipmapSrcRec, mipmapDstRec, tint);
4074 }
4075 }
4076 }
4077
4078 // Draw text (default font) within an image (destination)
4079 void ImageDrawText(Image *dst, const char *text, int posX, int posY, int fontSize, Color color)
4080 {
4081 #if SUPPORT_MODULE_RTEXT
4082 // Make sure default font is loaded to be used on image text drawing
4083 if (GetFontDefault().texture.id == 0) LoadFontDefault();
4084
4085 Vector2 position = { (float)posX, (float)posY };
4086 ImageDrawTextEx(dst, GetFontDefault(), text, position, (float)fontSize, 1.0f, color); // WARNING: Module required: rtext
4087 #else
4088 TRACELOG(LOG_WARNING, "IMAGE: ImageDrawText() requires module: rtext");
4089 #endif
4090 }
4091
4092 // Draw text (custom sprite font) within an image (destination)
4093 void ImageDrawTextEx(Image *dst, Font font, const char *text, Vector2 position, float fontSize, float spacing, Color tint)
4094 {
4095 Image imText = ImageTextEx(font, text, fontSize, spacing, tint);
4096
4097 Rectangle srcRec = { 0.0f, 0.0f, (float)imText.width, (float)imText.height };
4098 Rectangle dstRec = { position.x, position.y, (float)imText.width, (float)imText.height };
4099
4100 ImageDraw(dst, imText, srcRec, dstRec, WHITE);
4101
4102 UnloadImage(imText);
4103 }
4104
4105 //------------------------------------------------------------------------------------
4106 // Texture loading functions
4107 //------------------------------------------------------------------------------------
4108 // Load texture from file into GPU memory (VRAM)
4109 Texture2D LoadTexture(const char *fileName)
4110 {
4111 Texture2D texture = { 0 };
4112
4113 Image image = LoadImage(fileName);
4114
4115 if (image.data != NULL)
4116 {
4117 texture = LoadTextureFromImage(image);
4118 UnloadImage(image);
4119 }
4120
4121 return texture;
4122 }
4123
4124 // Load a texture from image data
4125 // NOTE: image is not unloaded, it must be done manually
4126 Texture2D LoadTextureFromImage(Image image)
4127 {
4128 Texture2D texture = { 0 };
4129
4130 if ((image.width != 0) && (image.height != 0))
4131 {
4132 texture.id = rlLoadTexture(image.data, image.width, image.height, image.format, image.mipmaps);
4133 }
4134 else TRACELOG(LOG_WARNING, "IMAGE: Data is not valid to load texture");
4135
4136 texture.width = image.width;
4137 texture.height = image.height;
4138 texture.mipmaps = image.mipmaps;
4139 texture.format = image.format;
4140
4141 return texture;
4142 }
4143
4144 // Load cubemap from image, multiple image cubemap layouts supported
4145 TextureCubemap LoadTextureCubemap(Image image, int layout)
4146 {
4147 TextureCubemap cubemap = { 0 };
4148
4149 if (layout == CUBEMAP_LAYOUT_AUTO_DETECT) // Try to automatically guess layout type
4150 {
4151 // Check image width/height to determine the type of cubemap provided
4152 if (image.width > image.height)
4153 {
4154 if ((image.width/6) == image.height) { layout = CUBEMAP_LAYOUT_LINE_HORIZONTAL; cubemap.width = image.width/6; }
4155 else if ((image.width/4) == (image.height/3)) { layout = CUBEMAP_LAYOUT_CROSS_FOUR_BY_THREE; cubemap.width = image.width/4; }
4156 }
4157 else if (image.height > image.width)
4158 {
4159 if ((image.height/6) == image.width) { layout = CUBEMAP_LAYOUT_LINE_VERTICAL; cubemap.width = image.height/6; }
4160 else if ((image.width/3) == (image.height/4)) { layout = CUBEMAP_LAYOUT_CROSS_THREE_BY_FOUR; cubemap.width = image.width/3; }
4161 }
4162 }
4163 else
4164 {
4165 if (layout == CUBEMAP_LAYOUT_LINE_VERTICAL) cubemap.width = image.height/6;
4166 if (layout == CUBEMAP_LAYOUT_LINE_HORIZONTAL) cubemap.width = image.width/6;
4167 if (layout == CUBEMAP_LAYOUT_CROSS_THREE_BY_FOUR) cubemap.width = image.width/3;
4168 if (layout == CUBEMAP_LAYOUT_CROSS_FOUR_BY_THREE) cubemap.width = image.width/4;
4169 }
4170
4171 cubemap.height = cubemap.width;
4172
4173 // Layout provided or already auto-detected
4174 if (layout != CUBEMAP_LAYOUT_AUTO_DETECT)
4175 {
4176 int size = cubemap.width;
4177
4178 Image faces = { 0 }; // Vertical column image
4179 Rectangle faceRecs[6] = { 0 }; // Face source rectangles
4180
4181 for (int i = 0; i < 6; i++) faceRecs[i] = (Rectangle){ 0, 0, (float)size, (float)size };
4182
4183 if (layout == CUBEMAP_LAYOUT_LINE_VERTICAL)
4184 {
4185 faces = ImageCopy(image); // Image data already follows expected convention
4186 }
4187 /*else if (layout == CUBEMAP_LAYOUT_PANORAMA)
4188 {
4189 // TODO: Implement panorama by converting image to square faces...
4190 // REF: https://github.com/denivip/panorama/blob/master/panorama.cpp
4191 } */
4192 else
4193 {
4194 if (layout == CUBEMAP_LAYOUT_LINE_HORIZONTAL) for (int i = 0; i < 6; i++) faceRecs[i].x = (float)size*i;
4195 else if (layout == CUBEMAP_LAYOUT_CROSS_THREE_BY_FOUR)
4196 {
4197 faceRecs[0].x = (float)size; faceRecs[0].y = (float)size;
4198 faceRecs[1].x = (float)size; faceRecs[1].y = (float)size*3;
4199 faceRecs[2].x = (float)size; faceRecs[2].y = 0;
4200 faceRecs[3].x = (float)size; faceRecs[3].y = (float)size*2;
4201 faceRecs[4].x = 0; faceRecs[4].y = (float)size;
4202 faceRecs[5].x = (float)size*2; faceRecs[5].y = (float)size;
4203 }
4204 else if (layout == CUBEMAP_LAYOUT_CROSS_FOUR_BY_THREE)
4205 {
4206 faceRecs[0].x = (float)size*2; faceRecs[0].y = (float)size;
4207 faceRecs[1].x = 0; faceRecs[1].y = (float)size;
4208 faceRecs[2].x = (float)size; faceRecs[2].y = 0;
4209 faceRecs[3].x = (float)size; faceRecs[3].y = (float)size*2;
4210 faceRecs[4].x = (float)size; faceRecs[4].y = (float)size;
4211 faceRecs[5].x = (float)size*3; faceRecs[5].y = (float)size;
4212 }
4213
4214 // Convert image data to 6 faces in a vertical column, that's the optimum layout for loading
4215 // NOTE: Image formatting does not work with compressed textures
4216 faces = GenImageColor(size, size*6, MAGENTA);
4217 ImageFormat(&faces, image.format);
4218
4219 Image mipmapped = ImageCopy(image);
4220 if (image.mipmaps > 1)
4221 {
4222 ImageMipmaps(&mipmapped);
4223 ImageMipmaps(&faces);
4224 }
4225
4226 for (int i = 0; i < 6; i++) ImageDraw(&faces, mipmapped, faceRecs[i], (Rectangle){ 0, (float)size*i, (float)size, (float)size }, WHITE);
4227
4228 UnloadImage(mipmapped);
4229 }
4230
4231 // NOTE: Cubemap data is expected to be provided as 6 images in a single data array,
4232 // one after the other (that's a vertical image), following convention: +X, -X, +Y, -Y, +Z, -Z
4233 cubemap.id = rlLoadTextureCubemap(faces.data, size, faces.format, faces.mipmaps);
4234
4235 if (cubemap.id != 0)
4236 {
4237 cubemap.format = faces.format;
4238 cubemap.mipmaps = faces.mipmaps;
4239 }
4240 else TRACELOG(LOG_WARNING, "IMAGE: Failed to load cubemap image");
4241
4242 UnloadImage(faces);
4243 }
4244 else TRACELOG(LOG_WARNING, "IMAGE: Failed to detect cubemap image layout");
4245
4246 return cubemap;
4247 }
4248
4249 // Load texture for rendering (framebuffer)
4250 // NOTE: Render texture is loaded by default with RGBA color attachment and depth RenderBuffer
4251 RenderTexture2D LoadRenderTexture(int width, int height)
4252 {
4253 RenderTexture2D target = { 0 };
4254
4255 target.id = rlLoadFramebuffer(); // Load an empty framebuffer
4256
4257 if (target.id > 0)
4258 {
4259 rlEnableFramebuffer(target.id);
4260
4261 // Create color texture (default to RGBA)
4262 target.texture.id = rlLoadTexture(NULL, width, height, PIXELFORMAT_UNCOMPRESSED_R8G8B8A8, 1);
4263 target.texture.width = width;
4264 target.texture.height = height;
4265 target.texture.format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8;
4266 target.texture.mipmaps = 1;
4267
4268 // Create depth renderbuffer/texture
4269 target.depth.id = rlLoadTextureDepth(width, height, true);
4270 target.depth.width = width;
4271 target.depth.height = height;
4272 target.depth.format = 19; //DEPTH_COMPONENT_24BIT?
4273 target.depth.mipmaps = 1;
4274
4275 // Attach color texture and depth renderbuffer/texture to FBO
4276 rlFramebufferAttach(target.id, target.texture.id, RL_ATTACHMENT_COLOR_CHANNEL0, RL_ATTACHMENT_TEXTURE2D, 0);
4277 rlFramebufferAttach(target.id, target.depth.id, RL_ATTACHMENT_DEPTH, RL_ATTACHMENT_RENDERBUFFER, 0);
4278
4279 // Check if fbo is complete with attachments (valid)
4280 if (rlFramebufferComplete(target.id)) TRACELOG(LOG_INFO, "FBO: [ID %i] Framebuffer object created successfully", target.id);
4281
4282 rlDisableFramebuffer();
4283 }
4284 else TRACELOG(LOG_WARNING, "FBO: Framebuffer object can not be created");
4285
4286 return target;
4287 }
4288
4289 // Check if a texture is valid (loaded in GPU)
4290 bool IsTextureValid(Texture2D texture)
4291 {
4292 bool result = false;
4293
4294 if ((texture.id > 0) && // Validate OpenGL id (texture uplaoded to GPU)
4295 (texture.width > 0) && // Validate texture width
4296 (texture.height > 0) && // Validate texture height
4297 (texture.format > 0) && // Validate texture pixel format
4298 (texture.mipmaps > 0)) result = true; // Validate texture mipmaps (at least 1 for basic mipmap level)
4299
4300 return result;
4301 }
4302
4303 // Unload texture from GPU memory (VRAM)
4304 void UnloadTexture(Texture2D texture)
4305 {
4306 if (texture.id > 0)
4307 {
4308 rlUnloadTexture(texture.id);
4309
4310 TRACELOG(LOG_INFO, "TEXTURE: [ID %i] Unloaded texture data from VRAM (GPU)", texture.id);
4311 }
4312 }
4313
4314 // Check if a render texture is valid (loaded in GPU)
4315 bool IsRenderTextureValid(RenderTexture2D target)
4316 {
4317 bool result = false;
4318
4319 if ((target.id > 0) && // Validate OpenGL id (loaded on GPU)
4320 IsTextureValid(target.depth) && // Validate FBO depth texture/renderbuffer attachment
4321 IsTextureValid(target.texture)) result = true; // Validate FBO texture attachment
4322
4323 return result;
4324 }
4325
4326 // Unload render texture from GPU memory (VRAM)
4327 void UnloadRenderTexture(RenderTexture2D target)
4328 {
4329 if (target.id > 0)
4330 {
4331 if (target.texture.id > 0)
4332 {
4333 // Color texture attached to FBO is deleted
4334 rlUnloadTexture(target.texture.id);
4335 }
4336
4337 // NOTE: Depth texture/renderbuffer is automatically
4338 // queried and deleted before deleting framebuffer
4339 rlUnloadFramebuffer(target.id);
4340 }
4341 }
4342
4343 // Update GPU texture with new data
4344 // NOTE 1: pixels data must match texture.format
4345 // NOTE 2: pixels data must contain at least as many pixels as texture
4346 void UpdateTexture(Texture2D texture, const void *pixels)
4347 {
4348 rlUpdateTexture(texture.id, 0, 0, texture.width, texture.height, texture.format, pixels);
4349 }
4350
4351 // Update GPU texture rectangle with new data
4352 // NOTE 1: pixels data must match texture.format
4353 // NOTE 2: pixels data must contain as many pixels as rec contains
4354 // NOTE 3: rec must fit completely within texture's width and height
4355 void UpdateTextureRec(Texture2D texture, Rectangle rec, const void *pixels)
4356 {
4357 rlUpdateTexture(texture.id, (int)rec.x, (int)rec.y, (int)rec.width, (int)rec.height, texture.format, pixels);
4358 }
4359
4360 //------------------------------------------------------------------------------------
4361 // Texture configuration functions
4362 //------------------------------------------------------------------------------------
4363 // Generate GPU mipmaps for a texture
4364 void GenTextureMipmaps(Texture2D *texture)
4365 {
4366 // NOTE: NPOT textures support check inside function
4367 // On WebGL (OpenGL ES 2.0) NPOT textures support is limited
4368 rlGenTextureMipmaps(texture->id, texture->width, texture->height, texture->format, &texture->mipmaps);
4369 }
4370
4371 // Set texture scaling filter mode
4372 void SetTextureFilter(Texture2D texture, int filter)
4373 {
4374 switch (filter)
4375 {
4376 case TEXTURE_FILTER_POINT:
4377 {
4378 if (texture.mipmaps > 1)
4379 {
4380 // RL_TEXTURE_FILTER_MIP_NEAREST - tex filter: POINT, mipmaps filter: POINT (sharp switching between mipmaps)
4381 rlTextureParameters(texture.id, RL_TEXTURE_MIN_FILTER, RL_TEXTURE_FILTER_MIP_NEAREST);
4382
4383 // RL_TEXTURE_FILTER_NEAREST - tex filter: POINT (no filter), no mipmaps
4384 rlTextureParameters(texture.id, RL_TEXTURE_MAG_FILTER, RL_TEXTURE_FILTER_NEAREST);
4385 }
4386 else
4387 {
4388 // RL_TEXTURE_FILTER_NEAREST - tex filter: POINT (no filter), no mipmaps
4389 rlTextureParameters(texture.id, RL_TEXTURE_MIN_FILTER, RL_TEXTURE_FILTER_NEAREST);
4390 rlTextureParameters(texture.id, RL_TEXTURE_MAG_FILTER, RL_TEXTURE_FILTER_NEAREST);
4391 }
4392 } break;
4393 case TEXTURE_FILTER_BILINEAR:
4394 {
4395 if (texture.mipmaps > 1)
4396 {
4397 // RL_TEXTURE_FILTER_LINEAR_MIP_NEAREST - tex filter: BILINEAR, mipmaps filter: POINT (sharp switching between mipmaps)
4398 // Alternative: RL_TEXTURE_FILTER_NEAREST_MIP_LINEAR - tex filter: POINT, mipmaps filter: BILINEAR (smooth transition between mipmaps)
4399 rlTextureParameters(texture.id, RL_TEXTURE_MIN_FILTER, RL_TEXTURE_FILTER_LINEAR_MIP_NEAREST);
4400
4401 // RL_TEXTURE_FILTER_LINEAR - tex filter: BILINEAR, no mipmaps
4402 rlTextureParameters(texture.id, RL_TEXTURE_MAG_FILTER, RL_TEXTURE_FILTER_LINEAR);
4403 }
4404 else
4405 {
4406 // RL_TEXTURE_FILTER_LINEAR - tex filter: BILINEAR, no mipmaps
4407 rlTextureParameters(texture.id, RL_TEXTURE_MIN_FILTER, RL_TEXTURE_FILTER_LINEAR);
4408 rlTextureParameters(texture.id, RL_TEXTURE_MAG_FILTER, RL_TEXTURE_FILTER_LINEAR);
4409 }
4410 } break;
4411 case TEXTURE_FILTER_TRILINEAR:
4412 {
4413 if (texture.mipmaps > 1)
4414 {
4415 // RL_TEXTURE_FILTER_MIP_LINEAR - tex filter: BILINEAR, mipmaps filter: BILINEAR (smooth transition between mipmaps)
4416 rlTextureParameters(texture.id, RL_TEXTURE_MIN_FILTER, RL_TEXTURE_FILTER_MIP_LINEAR);
4417
4418 // RL_TEXTURE_FILTER_LINEAR - tex filter: BILINEAR, no mipmaps
4419 rlTextureParameters(texture.id, RL_TEXTURE_MAG_FILTER, RL_TEXTURE_FILTER_LINEAR);
4420 }
4421 else
4422 {
4423 TRACELOG(LOG_WARNING, "TEXTURE: [ID %i] No mipmaps available for TRILINEAR texture filtering", texture.id);
4424
4425 // RL_TEXTURE_FILTER_LINEAR - tex filter: BILINEAR, no mipmaps
4426 rlTextureParameters(texture.id, RL_TEXTURE_MIN_FILTER, RL_TEXTURE_FILTER_LINEAR);
4427 rlTextureParameters(texture.id, RL_TEXTURE_MAG_FILTER, RL_TEXTURE_FILTER_LINEAR);
4428 }
4429 } break;
4430 case TEXTURE_FILTER_ANISOTROPIC_4X: rlTextureParameters(texture.id, RL_TEXTURE_FILTER_ANISOTROPIC, 4); break;
4431 case TEXTURE_FILTER_ANISOTROPIC_8X: rlTextureParameters(texture.id, RL_TEXTURE_FILTER_ANISOTROPIC, 8); break;
4432 case TEXTURE_FILTER_ANISOTROPIC_16X: rlTextureParameters(texture.id, RL_TEXTURE_FILTER_ANISOTROPIC, 16); break;
4433 default: break;
4434 }
4435 }
4436
4437 // Set texture wrapping mode
4438 void SetTextureWrap(Texture2D texture, int wrap)
4439 {
4440 switch (wrap)
4441 {
4442 case TEXTURE_WRAP_REPEAT:
4443 {
4444 // NOTE: It only works if NPOT textures are supported, i.e. OpenGL ES 2.0 could not support it
4445 rlTextureParameters(texture.id, RL_TEXTURE_WRAP_S, RL_TEXTURE_WRAP_REPEAT);
4446 rlTextureParameters(texture.id, RL_TEXTURE_WRAP_T, RL_TEXTURE_WRAP_REPEAT);
4447 } break;
4448 case TEXTURE_WRAP_CLAMP:
4449 {
4450 rlTextureParameters(texture.id, RL_TEXTURE_WRAP_S, RL_TEXTURE_WRAP_CLAMP);
4451 rlTextureParameters(texture.id, RL_TEXTURE_WRAP_T, RL_TEXTURE_WRAP_CLAMP);
4452 } break;
4453 case TEXTURE_WRAP_MIRROR_REPEAT:
4454 {
4455 rlTextureParameters(texture.id, RL_TEXTURE_WRAP_S, RL_TEXTURE_WRAP_MIRROR_REPEAT);
4456 rlTextureParameters(texture.id, RL_TEXTURE_WRAP_T, RL_TEXTURE_WRAP_MIRROR_REPEAT);
4457 } break;
4458 case TEXTURE_WRAP_MIRROR_CLAMP:
4459 {
4460 rlTextureParameters(texture.id, RL_TEXTURE_WRAP_S, RL_TEXTURE_WRAP_MIRROR_CLAMP);
4461 rlTextureParameters(texture.id, RL_TEXTURE_WRAP_T, RL_TEXTURE_WRAP_MIRROR_CLAMP);
4462 } break;
4463 default: break;
4464 }
4465 }
4466
4467 //------------------------------------------------------------------------------------
4468 // Texture drawing functions
4469 //------------------------------------------------------------------------------------
4470 // Draw a texture
4471 void DrawTexture(Texture2D texture, int posX, int posY, Color tint)
4472 {
4473 DrawTextureEx(texture, (Vector2){ (float)posX, (float)posY }, 0.0f, 1.0f, tint);
4474 }
4475
4476 // Draw a texture with position defined as Vector2
4477 void DrawTextureV(Texture2D texture, Vector2 position, Color tint)
4478 {
4479 DrawTextureEx(texture, position, 0, 1.0f, tint);
4480 }
4481
4482 // Draw a texture with extended parameters
4483 void DrawTextureEx(Texture2D texture, Vector2 position, float rotation, float scale, Color tint)
4484 {
4485 Rectangle source = { 0.0f, 0.0f, (float)texture.width, (float)texture.height };
4486 Rectangle dest = { position.x, position.y, (float)texture.width*scale, (float)texture.height*scale };
4487 Vector2 origin = { 0.0f, 0.0f };
4488
4489 DrawTexturePro(texture, source, dest, origin, rotation, tint);
4490 }
4491
4492 // Draw a part of a texture (defined by a rectangle)
4493 void DrawTextureRec(Texture2D texture, Rectangle source, Vector2 position, Color tint)
4494 {
4495 Rectangle dest = { position.x, position.y, fabsf(source.width), fabsf(source.height) };
4496 Vector2 origin = { 0.0f, 0.0f };
4497
4498 DrawTexturePro(texture, source, dest, origin, 0.0f, tint);
4499 }
4500
4501 // Draw a part of a texture (defined by a rectangle) with 'pro' parameters
4502 // NOTE: origin is relative to destination rectangle size
4503 void DrawTexturePro(Texture2D texture, Rectangle source, Rectangle dest, Vector2 origin, float rotation, Color tint)
4504 {
4505 // Check if texture is valid
4506 if (texture.id > 0)
4507 {
4508 float width = (float)texture.width;
4509 float height = (float)texture.height;
4510
4511 bool flipX = false;
4512
4513 if (source.width < 0) { flipX = true; source.width *= -1; }
4514 if (source.height < 0) source.y -= source.height;
4515
4516 if (dest.width < 0) dest.width *= -1;
4517 if (dest.height < 0) dest.height *= -1;
4518
4519 Vector2 topLeft = { 0 };
4520 Vector2 topRight = { 0 };
4521 Vector2 bottomLeft = { 0 };
4522 Vector2 bottomRight = { 0 };
4523
4524 // Only calculate rotation if needed
4525 if (rotation == 0.0f)
4526 {
4527 float x = dest.x - origin.x;
4528 float y = dest.y - origin.y;
4529 topLeft = (Vector2){ x, y };
4530 topRight = (Vector2){ x + dest.width, y };
4531 bottomLeft = (Vector2){ x, y + dest.height };
4532 bottomRight = (Vector2){ x + dest.width, y + dest.height };
4533 }
4534 else
4535 {
4536 float sinRotation = sinf(rotation*DEG2RAD);
4537 float cosRotation = cosf(rotation*DEG2RAD);
4538 float x = dest.x;
4539 float y = dest.y;
4540 float dx = -origin.x;
4541 float dy = -origin.y;
4542
4543 topLeft.x = x + dx*cosRotation - dy*sinRotation;
4544 topLeft.y = y + dx*sinRotation + dy*cosRotation;
4545
4546 topRight.x = x + (dx + dest.width)*cosRotation - dy*sinRotation;
4547 topRight.y = y + (dx + dest.width)*sinRotation + dy*cosRotation;
4548
4549 bottomLeft.x = x + dx*cosRotation - (dy + dest.height)*sinRotation;
4550 bottomLeft.y = y + dx*sinRotation + (dy + dest.height)*cosRotation;
4551
4552 bottomRight.x = x + (dx + dest.width)*cosRotation - (dy + dest.height)*sinRotation;
4553 bottomRight.y = y + (dx + dest.width)*sinRotation + (dy + dest.height)*cosRotation;
4554 }
4555
4556 rlSetTexture(texture.id);
4557 rlBegin(RL_QUADS);
4558
4559 rlColor4ub(tint.r, tint.g, tint.b, tint.a);
4560 rlNormal3f(0.0f, 0.0f, 1.0f); // Normal vector pointing towards viewer
4561
4562 // Top-left corner for texture and quad
4563 if (flipX) rlTexCoord2f((source.x + source.width)/width, source.y/height);
4564 else rlTexCoord2f(source.x/width, source.y/height);
4565 rlVertex2f(topLeft.x, topLeft.y);
4566
4567 // Bottom-left corner for texture and quad
4568 if (flipX) rlTexCoord2f((source.x + source.width)/width, (source.y + source.height)/height);
4569 else rlTexCoord2f(source.x/width, (source.y + source.height)/height);
4570 rlVertex2f(bottomLeft.x, bottomLeft.y);
4571
4572 // Bottom-right corner for texture and quad
4573 if (flipX) rlTexCoord2f(source.x/width, (source.y + source.height)/height);
4574 else rlTexCoord2f((source.x + source.width)/width, (source.y + source.height)/height);
4575 rlVertex2f(bottomRight.x, bottomRight.y);
4576
4577 // Top-right corner for texture and quad
4578 if (flipX) rlTexCoord2f(source.x/width, source.y/height);
4579 else rlTexCoord2f((source.x + source.width)/width, source.y/height);
4580 rlVertex2f(topRight.x, topRight.y);
4581
4582 rlEnd();
4583 rlSetTexture(0);
4584
4585 // NOTE: Vertex position can be transformed using matrices
4586 // but the process is way more costly than calculating
4587 // the vertex positions manually, like done above
4588 // Old implementation is left here for educational purposes,
4589 // in case someone wants to do some performance test
4590 /*
4591 rlSetTexture(texture.id);
4592 rlPushMatrix();
4593 rlTranslatef(dest.x, dest.y, 0.0f);
4594 if (rotation != 0.0f) rlRotatef(rotation, 0.0f, 0.0f, 1.0f);
4595 rlTranslatef(-origin.x, -origin.y, 0.0f);
4596
4597 rlBegin(RL_QUADS);
4598 rlColor4ub(tint.r, tint.g, tint.b, tint.a);
4599 rlNormal3f(0.0f, 0.0f, 1.0f); // Normal vector pointing towards viewer
4600
4601 // Bottom-left corner for texture and quad
4602 if (flipX) rlTexCoord2f((source.x + source.width)/width, source.y/height);
4603 else rlTexCoord2f(source.x/width, source.y/height);
4604 rlVertex2f(0.0f, 0.0f);
4605
4606 // Bottom-right corner for texture and quad
4607 if (flipX) rlTexCoord2f((source.x + source.width)/width, (source.y + source.height)/height);
4608 else rlTexCoord2f(source.x/width, (source.y + source.height)/height);
4609 rlVertex2f(0.0f, dest.height);
4610
4611 // Top-right corner for texture and quad
4612 if (flipX) rlTexCoord2f(source.x/width, (source.y + source.height)/height);
4613 else rlTexCoord2f((source.x + source.width)/width, (source.y + source.height)/height);
4614 rlVertex2f(dest.width, dest.height);
4615
4616 // Top-left corner for texture and quad
4617 if (flipX) rlTexCoord2f(source.x/width, source.y/height);
4618 else rlTexCoord2f((source.x + source.width)/width, source.y/height);
4619 rlVertex2f(dest.width, 0.0f);
4620 rlEnd();
4621 rlPopMatrix();
4622 rlSetTexture(0);
4623 */
4624 }
4625 }
4626
4627 // Draws a texture (or part of it) that stretches or shrinks nicely using n-patch info
4628 void DrawTextureNPatch(Texture2D texture, NPatchInfo nPatchInfo, Rectangle dest, Vector2 origin, float rotation, Color tint)
4629 {
4630 if (texture.id > 0)
4631 {
4632 float width = (float)texture.width;
4633 float height = (float)texture.height;
4634
4635 float patchWidth = ((int)dest.width <= 0)? 0.0f : dest.width;
4636 float patchHeight = ((int)dest.height <= 0)? 0.0f : dest.height;
4637
4638 if (nPatchInfo.source.width < 0) nPatchInfo.source.x -= nPatchInfo.source.width;
4639 if (nPatchInfo.source.height < 0) nPatchInfo.source.y -= nPatchInfo.source.height;
4640 if (nPatchInfo.layout == NPATCH_THREE_PATCH_HORIZONTAL) patchHeight = nPatchInfo.source.height;
4641 if (nPatchInfo.layout == NPATCH_THREE_PATCH_VERTICAL) patchWidth = nPatchInfo.source.width;
4642
4643 bool drawCenter = true;
4644 bool drawMiddle = true;
4645 float leftBorder = (float)nPatchInfo.left;
4646 float topBorder = (float)nPatchInfo.top;
4647 float rightBorder = (float)nPatchInfo.right;
4648 float bottomBorder = (float)nPatchInfo.bottom;
4649
4650 // Adjust the lateral (left and right) border widths in case patchWidth < texture.width
4651 if (patchWidth <= (leftBorder + rightBorder) && nPatchInfo.layout != NPATCH_THREE_PATCH_VERTICAL)
4652 {
4653 drawCenter = false;
4654 leftBorder = (leftBorder/(leftBorder + rightBorder))*patchWidth;
4655 rightBorder = patchWidth - leftBorder;
4656 }
4657
4658 // Adjust the lateral (top and bottom) border heights in case patchHeight < texture.height
4659 if (patchHeight <= (topBorder + bottomBorder) && nPatchInfo.layout != NPATCH_THREE_PATCH_HORIZONTAL)
4660 {
4661 drawMiddle = false;
4662 topBorder = (topBorder/(topBorder + bottomBorder))*patchHeight;
4663 bottomBorder = patchHeight - topBorder;
4664 }
4665
4666 Vector2 vertA = { 0 };
4667 Vector2 vertB = { 0 };
4668 Vector2 vertC = { 0 };
4669 Vector2 vertD = { 0 };
4670 vertA.x = 0.0f; // Outer left
4671 vertA.y = 0.0f; // Outer top
4672 vertB.x = leftBorder; // Inner left
4673 vertB.y = topBorder; // Inner top
4674 vertC.x = patchWidth - rightBorder; // Inner right
4675 vertC.y = patchHeight - bottomBorder; // Inner bottom
4676 vertD.x = patchWidth; // Outer right
4677 vertD.y = patchHeight; // Outer bottom
4678
4679 Vector2 coordA = { 0 };
4680 Vector2 coordB = { 0 };
4681 Vector2 coordC = { 0 };
4682 Vector2 coordD = { 0 };
4683 coordA.x = nPatchInfo.source.x/width;
4684 coordA.y = nPatchInfo.source.y/height;
4685 coordB.x = (nPatchInfo.source.x + leftBorder)/width;
4686 coordB.y = (nPatchInfo.source.y + topBorder)/height;
4687 coordC.x = (nPatchInfo.source.x + nPatchInfo.source.width - rightBorder)/width;
4688 coordC.y = (nPatchInfo.source.y + nPatchInfo.source.height - bottomBorder)/height;
4689 coordD.x = (nPatchInfo.source.x + nPatchInfo.source.width)/width;
4690 coordD.y = (nPatchInfo.source.y + nPatchInfo.source.height)/height;
4691
4692 rlSetTexture(texture.id);
4693
4694 rlPushMatrix();
4695 rlTranslatef(dest.x, dest.y, 0.0f);
4696 rlRotatef(rotation, 0.0f, 0.0f, 1.0f);
4697 rlTranslatef(-origin.x, -origin.y, 0.0f);
4698
4699 rlBegin(RL_QUADS);
4700 rlColor4ub(tint.r, tint.g, tint.b, tint.a);
4701 rlNormal3f(0.0f, 0.0f, 1.0f); // Normal vector pointing towards viewer
4702
4703 if (nPatchInfo.layout == NPATCH_NINE_PATCH)
4704 {
4705 // ------------------------------------------------------------
4706 // TOP-LEFT QUAD
4707 rlTexCoord2f(coordA.x, coordB.y); rlVertex2f(vertA.x, vertB.y); // Bottom-left corner for texture and quad
4708 rlTexCoord2f(coordB.x, coordB.y); rlVertex2f(vertB.x, vertB.y); // Bottom-right corner for texture and quad
4709 rlTexCoord2f(coordB.x, coordA.y); rlVertex2f(vertB.x, vertA.y); // Top-right corner for texture and quad
4710 rlTexCoord2f(coordA.x, coordA.y); rlVertex2f(vertA.x, vertA.y); // Top-left corner for texture and quad
4711 if (drawCenter)
4712 {
4713 // TOP-CENTER QUAD
4714 rlTexCoord2f(coordB.x, coordB.y); rlVertex2f(vertB.x, vertB.y); // Bottom-left corner for texture and quad
4715 rlTexCoord2f(coordC.x, coordB.y); rlVertex2f(vertC.x, vertB.y); // Bottom-right corner for texture and quad
4716 rlTexCoord2f(coordC.x, coordA.y); rlVertex2f(vertC.x, vertA.y); // Top-right corner for texture and quad
4717 rlTexCoord2f(coordB.x, coordA.y); rlVertex2f(vertB.x, vertA.y); // Top-left corner for texture and quad
4718 }
4719 // TOP-RIGHT QUAD
4720 rlTexCoord2f(coordC.x, coordB.y); rlVertex2f(vertC.x, vertB.y); // Bottom-left corner for texture and quad
4721 rlTexCoord2f(coordD.x, coordB.y); rlVertex2f(vertD.x, vertB.y); // Bottom-right corner for texture and quad
4722 rlTexCoord2f(coordD.x, coordA.y); rlVertex2f(vertD.x, vertA.y); // Top-right corner for texture and quad
4723 rlTexCoord2f(coordC.x, coordA.y); rlVertex2f(vertC.x, vertA.y); // Top-left corner for texture and quad
4724 if (drawMiddle)
4725 {
4726 // ------------------------------------------------------------
4727 // MIDDLE-LEFT QUAD
4728 rlTexCoord2f(coordA.x, coordC.y); rlVertex2f(vertA.x, vertC.y); // Bottom-left corner for texture and quad
4729 rlTexCoord2f(coordB.x, coordC.y); rlVertex2f(vertB.x, vertC.y); // Bottom-right corner for texture and quad
4730 rlTexCoord2f(coordB.x, coordB.y); rlVertex2f(vertB.x, vertB.y); // Top-right corner for texture and quad
4731 rlTexCoord2f(coordA.x, coordB.y); rlVertex2f(vertA.x, vertB.y); // Top-left corner for texture and quad
4732 if (drawCenter)
4733 {
4734 // MIDDLE-CENTER QUAD
4735 rlTexCoord2f(coordB.x, coordC.y); rlVertex2f(vertB.x, vertC.y); // Bottom-left corner for texture and quad
4736 rlTexCoord2f(coordC.x, coordC.y); rlVertex2f(vertC.x, vertC.y); // Bottom-right corner for texture and quad
4737 rlTexCoord2f(coordC.x, coordB.y); rlVertex2f(vertC.x, vertB.y); // Top-right corner for texture and quad
4738 rlTexCoord2f(coordB.x, coordB.y); rlVertex2f(vertB.x, vertB.y); // Top-left corner for texture and quad
4739 }
4740
4741 // MIDDLE-RIGHT QUAD
4742 rlTexCoord2f(coordC.x, coordC.y); rlVertex2f(vertC.x, vertC.y); // Bottom-left corner for texture and quad
4743 rlTexCoord2f(coordD.x, coordC.y); rlVertex2f(vertD.x, vertC.y); // Bottom-right corner for texture and quad
4744 rlTexCoord2f(coordD.x, coordB.y); rlVertex2f(vertD.x, vertB.y); // Top-right corner for texture and quad
4745 rlTexCoord2f(coordC.x, coordB.y); rlVertex2f(vertC.x, vertB.y); // Top-left corner for texture and quad
4746 }
4747
4748 // ------------------------------------------------------------
4749 // BOTTOM-LEFT QUAD
4750 rlTexCoord2f(coordA.x, coordD.y); rlVertex2f(vertA.x, vertD.y); // Bottom-left corner for texture and quad
4751 rlTexCoord2f(coordB.x, coordD.y); rlVertex2f(vertB.x, vertD.y); // Bottom-right corner for texture and quad
4752 rlTexCoord2f(coordB.x, coordC.y); rlVertex2f(vertB.x, vertC.y); // Top-right corner for texture and quad
4753 rlTexCoord2f(coordA.x, coordC.y); rlVertex2f(vertA.x, vertC.y); // Top-left corner for texture and quad
4754 if (drawCenter)
4755 {
4756 // BOTTOM-CENTER QUAD
4757 rlTexCoord2f(coordB.x, coordD.y); rlVertex2f(vertB.x, vertD.y); // Bottom-left corner for texture and quad
4758 rlTexCoord2f(coordC.x, coordD.y); rlVertex2f(vertC.x, vertD.y); // Bottom-right corner for texture and quad
4759 rlTexCoord2f(coordC.x, coordC.y); rlVertex2f(vertC.x, vertC.y); // Top-right corner for texture and quad
4760 rlTexCoord2f(coordB.x, coordC.y); rlVertex2f(vertB.x, vertC.y); // Top-left corner for texture and quad
4761 }
4762
4763 // BOTTOM-RIGHT QUAD
4764 rlTexCoord2f(coordC.x, coordD.y); rlVertex2f(vertC.x, vertD.y); // Bottom-left corner for texture and quad
4765 rlTexCoord2f(coordD.x, coordD.y); rlVertex2f(vertD.x, vertD.y); // Bottom-right corner for texture and quad
4766 rlTexCoord2f(coordD.x, coordC.y); rlVertex2f(vertD.x, vertC.y); // Top-right corner for texture and quad
4767 rlTexCoord2f(coordC.x, coordC.y); rlVertex2f(vertC.x, vertC.y); // Top-left corner for texture and quad
4768 }
4769 else if (nPatchInfo.layout == NPATCH_THREE_PATCH_VERTICAL)
4770 {
4771 // TOP QUAD
4772 // -----------------------------------------------------------
4773 // Texture coords Vertices
4774 rlTexCoord2f(coordA.x, coordB.y); rlVertex2f(vertA.x, vertB.y); // Bottom-left corner for texture and quad
4775 rlTexCoord2f(coordD.x, coordB.y); rlVertex2f(vertD.x, vertB.y); // Bottom-right corner for texture and quad
4776 rlTexCoord2f(coordD.x, coordA.y); rlVertex2f(vertD.x, vertA.y); // Top-right corner for texture and quad
4777 rlTexCoord2f(coordA.x, coordA.y); rlVertex2f(vertA.x, vertA.y); // Top-left corner for texture and quad
4778 if (drawCenter)
4779 {
4780 // MIDDLE QUAD
4781 // -----------------------------------------------------------
4782 // Texture coords Vertices
4783 rlTexCoord2f(coordA.x, coordC.y); rlVertex2f(vertA.x, vertC.y); // Bottom-left corner for texture and quad
4784 rlTexCoord2f(coordD.x, coordC.y); rlVertex2f(vertD.x, vertC.y); // Bottom-right corner for texture and quad
4785 rlTexCoord2f(coordD.x, coordB.y); rlVertex2f(vertD.x, vertB.y); // Top-right corner for texture and quad
4786 rlTexCoord2f(coordA.x, coordB.y); rlVertex2f(vertA.x, vertB.y); // Top-left corner for texture and quad
4787 }
4788 // BOTTOM QUAD
4789 // -----------------------------------------------------------
4790 // Texture coords Vertices
4791 rlTexCoord2f(coordA.x, coordD.y); rlVertex2f(vertA.x, vertD.y); // Bottom-left corner for texture and quad
4792 rlTexCoord2f(coordD.x, coordD.y); rlVertex2f(vertD.x, vertD.y); // Bottom-right corner for texture and quad
4793 rlTexCoord2f(coordD.x, coordC.y); rlVertex2f(vertD.x, vertC.y); // Top-right corner for texture and quad
4794 rlTexCoord2f(coordA.x, coordC.y); rlVertex2f(vertA.x, vertC.y); // Top-left corner for texture and quad
4795 }
4796 else if (nPatchInfo.layout == NPATCH_THREE_PATCH_HORIZONTAL)
4797 {
4798 // LEFT QUAD
4799 // -----------------------------------------------------------
4800 // Texture coords Vertices
4801 rlTexCoord2f(coordA.x, coordD.y); rlVertex2f(vertA.x, vertD.y); // Bottom-left corner for texture and quad
4802 rlTexCoord2f(coordB.x, coordD.y); rlVertex2f(vertB.x, vertD.y); // Bottom-right corner for texture and quad
4803 rlTexCoord2f(coordB.x, coordA.y); rlVertex2f(vertB.x, vertA.y); // Top-right corner for texture and quad
4804 rlTexCoord2f(coordA.x, coordA.y); rlVertex2f(vertA.x, vertA.y); // Top-left corner for texture and quad
4805 if (drawCenter)
4806 {
4807 // CENTER QUAD
4808 // -----------------------------------------------------------
4809 // Texture coords Vertices
4810 rlTexCoord2f(coordB.x, coordD.y); rlVertex2f(vertB.x, vertD.y); // Bottom-left corner for texture and quad
4811 rlTexCoord2f(coordC.x, coordD.y); rlVertex2f(vertC.x, vertD.y); // Bottom-right corner for texture and quad
4812 rlTexCoord2f(coordC.x, coordA.y); rlVertex2f(vertC.x, vertA.y); // Top-right corner for texture and quad
4813 rlTexCoord2f(coordB.x, coordA.y); rlVertex2f(vertB.x, vertA.y); // Top-left corner for texture and quad
4814 }
4815 // RIGHT QUAD
4816 // -----------------------------------------------------------
4817 // Texture coords Vertices
4818 rlTexCoord2f(coordC.x, coordD.y); rlVertex2f(vertC.x, vertD.y); // Bottom-left corner for texture and quad
4819 rlTexCoord2f(coordD.x, coordD.y); rlVertex2f(vertD.x, vertD.y); // Bottom-right corner for texture and quad
4820 rlTexCoord2f(coordD.x, coordA.y); rlVertex2f(vertD.x, vertA.y); // Top-right corner for texture and quad
4821 rlTexCoord2f(coordC.x, coordA.y); rlVertex2f(vertC.x, vertA.y); // Top-left corner for texture and quad
4822 }
4823 rlEnd();
4824 rlPopMatrix();
4825
4826 rlSetTexture(0);
4827 }
4828 }
4829
4830 // Check if two colors are equal
4831 bool ColorIsEqual(Color col1, Color col2)
4832 {
4833 bool result = false;
4834
4835 if ((col1.r == col2.r) && (col1.g == col2.g) && (col1.b == col2.b) && (col1.a == col2.a)) result = true;
4836
4837 return result;
4838 }
4839
4840 // Get color with alpha applied, alpha goes from 0.0f to 1.0f
4841 Color Fade(Color color, float alpha)
4842 {
4843 Color result = color;
4844
4845 if (alpha < 0.0f) alpha = 0.0f;
4846 else if (alpha > 1.0f) alpha = 1.0f;
4847
4848 result.a = (unsigned char)(255.0f*alpha);
4849
4850 return result;
4851 }
4852
4853 // Get hexadecimal value for a Color
4854 int ColorToInt(Color color)
4855 {
4856 int result = 0;
4857
4858 result = (int)(((unsigned int)color.r << 24) |
4859 ((unsigned int)color.g << 16) |
4860 ((unsigned int)color.b << 8) |
4861 (unsigned int)color.a);
4862
4863 return result;
4864 }
4865
4866 // Get color normalized as float [0..1]
4867 Vector4 ColorNormalize(Color color)
4868 {
4869 Vector4 result;
4870
4871 result.x = (float)color.r/255.0f;
4872 result.y = (float)color.g/255.0f;
4873 result.z = (float)color.b/255.0f;
4874 result.w = (float)color.a/255.0f;
4875
4876 return result;
4877 }
4878
4879 // Get color from normalized values [0..1]
4880 Color ColorFromNormalized(Vector4 normalized)
4881 {
4882 Color result;
4883
4884 result.r = (unsigned char)(normalized.x*255.0f);
4885 result.g = (unsigned char)(normalized.y*255.0f);
4886 result.b = (unsigned char)(normalized.z*255.0f);
4887 result.a = (unsigned char)(normalized.w*255.0f);
4888
4889 return result;
4890 }
4891
4892 // Get HSV values for a Color
4893 // NOTE: Hue is returned as degrees [0..360]
4894 Vector3 ColorToHSV(Color color)
4895 {
4896 Vector3 hsv = { 0 };
4897 Vector3 rgb = { (float)color.r/255.0f, (float)color.g/255.0f, (float)color.b/255.0f };
4898 float min = 0.0f;
4899 float max = 0.0f;
4900 float delta = 0.0f;
4901
4902 min = (rgb.x < rgb.y)? rgb.x : rgb.y;
4903 min = (min < rgb.z)? min : rgb.z;
4904
4905 max = (rgb.x > rgb.y)? rgb.x : rgb.y;
4906 max = (max > rgb.z)? max : rgb.z;
4907
4908 hsv.z = max; // Value
4909 delta = max - min;
4910
4911 if (delta < 0.00001f)
4912 {
4913 hsv.y = 0.0f;
4914 hsv.x = 0.0f; // Undefined, maybe NAN?
4915 return hsv;
4916 }
4917
4918 if (max > 0.0f)
4919 {
4920 // NOTE: If max is 0, this divide would cause a crash
4921 hsv.y = (delta/max); // Saturation
4922 }
4923 else
4924 {
4925 // NOTE: If max is 0, then r = g = b = 0, s = 0, h is undefined
4926 hsv.y = 0.0f;
4927 hsv.x = NAN; // Undefined
4928 return hsv;
4929 }
4930
4931 // NOTE: Comparing float values could not work properly
4932 if (rgb.x >= max) hsv.x = (rgb.y - rgb.z)/delta; // Between yellow & magenta
4933 else
4934 {
4935 if (rgb.y >= max) hsv.x = 2.0f + (rgb.z - rgb.x)/delta; // Between cyan & yellow
4936 else hsv.x = 4.0f + (rgb.x - rgb.y)/delta; // Between magenta & cyan
4937 }
4938
4939 hsv.x *= 60.0f; // Convert to degrees
4940
4941 if (hsv.x < 0.0f) hsv.x += 360.0f;
4942
4943 return hsv;
4944 }
4945
4946 // Get a Color from HSV values
4947 // Implementation reference: https://en.wikipedia.org/wiki/HSL_and_HSV#Alternative_HSV_conversion
4948 // NOTE: Color->HSV->Color conversion will not yield exactly the same color due to rounding errors
4949 // Hue is provided in degrees: [0..360]
4950 // Saturation/Value are provided normalized: [0.0f..1.0f]
4951 Color ColorFromHSV(float hue, float saturation, float value)
4952 {
4953 Color color = { 0, 0, 0, 255 };
4954
4955 // Red channel
4956 float k = fmodf((5.0f + hue/60.0f), 6);
4957 float t = 4.0f - k;
4958 k = (t < k)? t : k;
4959 k = (k < 1)? k : 1;
4960 k = (k > 0)? k : 0;
4961 color.r = (unsigned char)((value - value*saturation*k)*255.0f);
4962
4963 // Green channel
4964 k = fmodf((3.0f + hue/60.0f), 6);
4965 t = 4.0f - k;
4966 k = (t < k)? t : k;
4967 k = (k < 1)? k : 1;
4968 k = (k > 0)? k : 0;
4969 color.g = (unsigned char)((value - value*saturation*k)*255.0f);
4970
4971 // Blue channel
4972 k = fmodf((1.0f + hue/60.0f), 6);
4973 t = 4.0f - k;
4974 k = (t < k)? t : k;
4975 k = (k < 1)? k : 1;
4976 k = (k > 0)? k : 0;
4977 color.b = (unsigned char)((value - value*saturation*k)*255.0f);
4978
4979 return color;
4980 }
4981
4982 // Get color multiplied with another color
4983 Color ColorTint(Color color, Color tint)
4984 {
4985 Color result = color;
4986
4987 unsigned char r = (unsigned char)(((int)color.r*(int)tint.r)/255);
4988 unsigned char g = (unsigned char)(((int)color.g*(int)tint.g)/255);
4989 unsigned char b = (unsigned char)(((int)color.b*(int)tint.b)/255);
4990 unsigned char a = (unsigned char)(((int)color.a*(int)tint.a)/255);
4991
4992 result.r = r;
4993 result.g = g;
4994 result.b = b;
4995 result.a = a;
4996
4997 return result;
4998 }
4999
5000 // Get color with brightness correction, brightness factor goes from -1.0f to 1.0f
5001 Color ColorBrightness(Color color, float factor)
5002 {
5003 Color result = color;
5004
5005 if (factor > 1.0f) factor = 1.0f;
5006 else if (factor < -1.0f) factor = -1.0f;
5007
5008 float red = (float)color.r;
5009 float green = (float)color.g;
5010 float blue = (float)color.b;
5011
5012 if (factor < 0.0f)
5013 {
5014 factor = 1.0f + factor;
5015 red *= factor;
5016 green *= factor;
5017 blue *= factor;
5018 }
5019 else
5020 {
5021 red = (255 - red)*factor + red;
5022 green = (255 - green)*factor + green;
5023 blue = (255 - blue)*factor + blue;
5024 }
5025
5026 result.r = (unsigned char)red;
5027 result.g = (unsigned char)green;
5028 result.b = (unsigned char)blue;
5029
5030 return result;
5031 }
5032
5033 // Get color with contrast correction
5034 // NOTE: Contrast values between -1.0f and 1.0f
5035 Color ColorContrast(Color color, float contrast)
5036 {
5037 Color result = color;
5038
5039 if (contrast < -1.0f) contrast = -1.0f;
5040 else if (contrast > 1.0f) contrast = 1.0f;
5041
5042 contrast = (1.0f + contrast);
5043 contrast *= contrast;
5044
5045 float pR = (float)color.r/255.0f;
5046 pR -= 0.5f;
5047 pR *= contrast;
5048 pR += 0.5f;
5049 pR *= 255;
5050 if (pR < 0) pR = 0;
5051 else if (pR > 255) pR = 255;
5052
5053 float pG = (float)color.g/255.0f;
5054 pG -= 0.5f;
5055 pG *= contrast;
5056 pG += 0.5f;
5057 pG *= 255;
5058 if (pG < 0) pG = 0;
5059 else if (pG > 255) pG = 255;
5060
5061 float pB = (float)color.b/255.0f;
5062 pB -= 0.5f;
5063 pB *= contrast;
5064 pB += 0.5f;
5065 pB *= 255;
5066 if (pB < 0) pB = 0;
5067 else if (pB > 255) pB = 255;
5068
5069 result.r = (unsigned char)pR;
5070 result.g = (unsigned char)pG;
5071 result.b = (unsigned char)pB;
5072
5073 return result;
5074 }
5075
5076 // Get color with alpha applied, alpha goes from 0.0f to 1.0f
5077 Color ColorAlpha(Color color, float alpha)
5078 {
5079 Color result = color;
5080
5081 if (alpha < 0.0f) alpha = 0.0f;
5082 else if (alpha > 1.0f) alpha = 1.0f;
5083
5084 result.a = (unsigned char)(255.0f*alpha);
5085
5086 return result;
5087 }
5088
5089 // Get src alpha-blended into dst color with tint
5090 Color ColorAlphaBlend(Color dst, Color src, Color tint)
5091 {
5092 Color result = WHITE;
5093
5094 // Apply color tint to source color
5095 src.r = (unsigned char)(((unsigned int)src.r*((unsigned int)tint.r+1)) >> 8);
5096 src.g = (unsigned char)(((unsigned int)src.g*((unsigned int)tint.g+1)) >> 8);
5097 src.b = (unsigned char)(((unsigned int)src.b*((unsigned int)tint.b+1)) >> 8);
5098 src.a = (unsigned char)(((unsigned int)src.a*((unsigned int)tint.a+1)) >> 8);
5099
5100 //#define COLORALPHABLEND_FLOAT
5101 #define COLORALPHABLEND_INTEGERS
5102 #if defined(COLORALPHABLEND_INTEGERS)
5103 if (src.a == 0) result = dst;
5104 else if (src.a == 255) result = src;
5105 else
5106 {
5107 unsigned int alpha = (unsigned int)src.a + 1; // Shifting by 8 (dividing by 256), so need to take that excess into account
5108 result.a = (unsigned char)(((unsigned int)alpha*256 + (unsigned int)dst.a*(256 - alpha)) >> 8);
5109
5110 if (result.a > 0)
5111 {
5112 result.r = (unsigned char)((((unsigned int)src.r*alpha*256 + (unsigned int)dst.r*(unsigned int)dst.a*(256 - alpha))/result.a) >> 8);
5113 result.g = (unsigned char)((((unsigned int)src.g*alpha*256 + (unsigned int)dst.g*(unsigned int)dst.a*(256 - alpha))/result.a) >> 8);
5114 result.b = (unsigned char)((((unsigned int)src.b*alpha*256 + (unsigned int)dst.b*(unsigned int)dst.a*(256 - alpha))/result.a) >> 8);
5115 }
5116 }
5117 #endif
5118 #if defined(COLORALPHABLEND_FLOAT)
5119 if (src.a == 0) result = dst;
5120 else if (src.a == 255) result = src;
5121 else
5122 {
5123 Vector4 fdst = ColorNormalize(dst);
5124 Vector4 fsrc = ColorNormalize(src);
5125 Vector4 ftint = ColorNormalize(tint);
5126 Vector4 fout = { 0 };
5127
5128 fout.w = fsrc.w + fdst.w*(1.0f - fsrc.w);
5129
5130 if (fout.w > 0.0f)
5131 {
5132 fout.x = (fsrc.x*fsrc.w + fdst.x*fdst.w*(1 - fsrc.w))/fout.w;
5133 fout.y = (fsrc.y*fsrc.w + fdst.y*fdst.w*(1 - fsrc.w))/fout.w;
5134 fout.z = (fsrc.z*fsrc.w + fdst.z*fdst.w*(1 - fsrc.w))/fout.w;
5135 }
5136
5137 result = (Color){ (unsigned char)(fout.x*255.0f), (unsigned char)(fout.y*255.0f), (unsigned char)(fout.z*255.0f), (unsigned char)(fout.w*255.0f) };
5138 }
5139 #endif
5140
5141 return result;
5142 }
5143
5144 // Get color lerp interpolation between two colors, factor [0.0f..1.0f]
5145 Color ColorLerp(Color color1, Color color2, float factor)
5146 {
5147 Color color = { 0 };
5148
5149 if (factor < 0.0f) factor = 0.0f;
5150 else if (factor > 1.0f) factor = 1.0f;
5151
5152 color.r = (unsigned char)((1.0f - factor)*color1.r + factor*color2.r);
5153 color.g = (unsigned char)((1.0f - factor)*color1.g + factor*color2.g);
5154 color.b = (unsigned char)((1.0f - factor)*color1.b + factor*color2.b);
5155 color.a = (unsigned char)((1.0f - factor)*color1.a + factor*color2.a);
5156
5157 return color;
5158 }
5159
5160 // Get a Color struct from hexadecimal value
5161 Color GetColor(unsigned int hexValue)
5162 {
5163 Color color;
5164
5165 color.r = (unsigned char)(hexValue >> 24) & 0xff;
5166 color.g = (unsigned char)(hexValue >> 16) & 0xff;
5167 color.b = (unsigned char)(hexValue >> 8) & 0xff;
5168 color.a = (unsigned char)hexValue & 0xff;
5169
5170 return color;
5171 }
5172
5173 // Get color from a pixel from certain format
5174 Color GetPixelColor(void *srcPtr, int format)
5175 {
5176 Color color = { 0 };
5177
5178 switch (format)
5179 {
5180 case PIXELFORMAT_UNCOMPRESSED_GRAYSCALE: color = (Color){ ((unsigned char *)srcPtr)[0], ((unsigned char *)srcPtr)[0], ((unsigned char *)srcPtr)[0], 255 }; break;
5181 case PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA: color = (Color){ ((unsigned char *)srcPtr)[0], ((unsigned char *)srcPtr)[0], ((unsigned char *)srcPtr)[0], ((unsigned char *)srcPtr)[1] }; break;
5182 case PIXELFORMAT_UNCOMPRESSED_R5G6B5:
5183 {
5184 color.r = (unsigned char)((((unsigned short *)srcPtr)[0] >> 11)*255/31);
5185 color.g = (unsigned char)(((((unsigned short *)srcPtr)[0] >> 5) & 0b0000000000111111)*255/63);
5186 color.b = (unsigned char)((((unsigned short *)srcPtr)[0] & 0b0000000000011111)*255/31);
5187 color.a = 255;
5188
5189 } break;
5190 case PIXELFORMAT_UNCOMPRESSED_R5G5B5A1:
5191 {
5192 color.r = (unsigned char)((((unsigned short *)srcPtr)[0] >> 11)*255/31);
5193 color.g = (unsigned char)(((((unsigned short *)srcPtr)[0] >> 6) & 0b0000000000011111)*255/31);
5194 color.b = (unsigned char)((((unsigned short *)srcPtr)[0] & 0b0000000000011111)*255/31);
5195 color.a = (((unsigned short *)srcPtr)[0] & 0b0000000000000001)? 255 : 0;
5196
5197 } break;
5198 case PIXELFORMAT_UNCOMPRESSED_R4G4B4A4:
5199 {
5200 color.r = (unsigned char)((((unsigned short *)srcPtr)[0] >> 12)*255/15);
5201 color.g = (unsigned char)(((((unsigned short *)srcPtr)[0] >> 8) & 0b0000000000001111)*255/15);
5202 color.b = (unsigned char)(((((unsigned short *)srcPtr)[0] >> 4) & 0b0000000000001111)*255/15);
5203 color.a = (unsigned char)((((unsigned short *)srcPtr)[0] & 0b0000000000001111)*255/15);
5204
5205 } break;
5206 case PIXELFORMAT_UNCOMPRESSED_R8G8B8A8: color = (Color){ ((unsigned char *)srcPtr)[0], ((unsigned char *)srcPtr)[1], ((unsigned char *)srcPtr)[2], ((unsigned char *)srcPtr)[3] }; break;
5207 case PIXELFORMAT_UNCOMPRESSED_R8G8B8: color = (Color){ ((unsigned char *)srcPtr)[0], ((unsigned char *)srcPtr)[1], ((unsigned char *)srcPtr)[2], 255 }; break;
5208 case PIXELFORMAT_UNCOMPRESSED_R32:
5209 {
5210 // NOTE: Pixel normalized float value is converted to [0..255]
5211 color.r = (unsigned char)(((float *)srcPtr)[0]*255.0f);
5212 color.g = (unsigned char)(((float *)srcPtr)[0]*255.0f);
5213 color.b = (unsigned char)(((float *)srcPtr)[0]*255.0f);
5214 color.a = 255;
5215
5216 } break;
5217 case PIXELFORMAT_UNCOMPRESSED_R32G32B32:
5218 {
5219 // NOTE: Pixel normalized float value is converted to [0..255]
5220 color.r = (unsigned char)(((float *)srcPtr)[0]*255.0f);
5221 color.g = (unsigned char)(((float *)srcPtr)[1]*255.0f);
5222 color.b = (unsigned char)(((float *)srcPtr)[2]*255.0f);
5223 color.a = 255;
5224
5225 } break;
5226 case PIXELFORMAT_UNCOMPRESSED_R32G32B32A32:
5227 {
5228 // NOTE: Pixel normalized float value is converted to [0..255]
5229 color.r = (unsigned char)(((float *)srcPtr)[0]*255.0f);
5230 color.g = (unsigned char)(((float *)srcPtr)[1]*255.0f);
5231 color.b = (unsigned char)(((float *)srcPtr)[2]*255.0f);
5232 color.a = (unsigned char)(((float *)srcPtr)[3]*255.0f);
5233
5234 } break;
5235 case PIXELFORMAT_UNCOMPRESSED_R16:
5236 {
5237 // NOTE: Pixel normalized float value is converted to [0..255]
5238 color.r = (unsigned char)(HalfToFloat(((unsigned short *)srcPtr)[0])*255.0f);
5239 color.g = (unsigned char)(HalfToFloat(((unsigned short *)srcPtr)[0])*255.0f);
5240 color.b = (unsigned char)(HalfToFloat(((unsigned short *)srcPtr)[0])*255.0f);
5241 color.a = 255;
5242
5243 } break;
5244 case PIXELFORMAT_UNCOMPRESSED_R16G16B16:
5245 {
5246 // NOTE: Pixel normalized float value is converted to [0..255]
5247 color.r = (unsigned char)(HalfToFloat(((unsigned short *)srcPtr)[0])*255.0f);
5248 color.g = (unsigned char)(HalfToFloat(((unsigned short *)srcPtr)[1])*255.0f);
5249 color.b = (unsigned char)(HalfToFloat(((unsigned short *)srcPtr)[2])*255.0f);
5250 color.a = 255;
5251
5252 } break;
5253 case PIXELFORMAT_UNCOMPRESSED_R16G16B16A16:
5254 {
5255 // NOTE: Pixel normalized float value is converted to [0..255]
5256 color.r = (unsigned char)(HalfToFloat(((unsigned short *)srcPtr)[0])*255.0f);
5257 color.g = (unsigned char)(HalfToFloat(((unsigned short *)srcPtr)[1])*255.0f);
5258 color.b = (unsigned char)(HalfToFloat(((unsigned short *)srcPtr)[2])*255.0f);
5259 color.a = (unsigned char)(HalfToFloat(((unsigned short *)srcPtr)[3])*255.0f);
5260
5261 } break;
5262 default: break;
5263 }
5264
5265 return color;
5266 }
5267
5268 // Set pixel color formatted into destination pointer
5269 void SetPixelColor(void *dstPtr, Color color, int format)
5270 {
5271 switch (format)
5272 {
5273 case PIXELFORMAT_UNCOMPRESSED_GRAYSCALE:
5274 {
5275 // NOTE: Calculate grayscale equivalent color
5276 Vector3 coln = { (float)color.r/255.0f, (float)color.g/255.0f, (float)color.b/255.0f };
5277 unsigned char gray = (unsigned char)((coln.x*0.299f + coln.y*0.587f + coln.z*0.114f)*255.0f);
5278
5279 ((unsigned char *)dstPtr)[0] = gray;
5280
5281 } break;
5282 case PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA:
5283 {
5284 // NOTE: Calculate grayscale equivalent color
5285 Vector3 coln = { (float)color.r/255.0f, (float)color.g/255.0f, (float)color.b/255.0f };
5286 unsigned char gray = (unsigned char)((coln.x*0.299f + coln.y*0.587f + coln.z*0.114f)*255.0f);
5287
5288 ((unsigned char *)dstPtr)[0] = gray;
5289 ((unsigned char *)dstPtr)[1] = color.a;
5290
5291 } break;
5292 case PIXELFORMAT_UNCOMPRESSED_R5G6B5:
5293 {
5294 // NOTE: Calculate R5G6B5 equivalent color
5295 Vector3 coln = { (float)color.r/255.0f, (float)color.g/255.0f, (float)color.b/255.0f };
5296
5297 unsigned char r = (unsigned char)(round(coln.x*31.0f));
5298 unsigned char g = (unsigned char)(round(coln.y*63.0f));
5299 unsigned char b = (unsigned char)(round(coln.z*31.0f));
5300
5301 ((unsigned short *)dstPtr)[0] = (unsigned short)r << 11 | (unsigned short)g << 5 | (unsigned short)b;
5302
5303 } break;
5304 case PIXELFORMAT_UNCOMPRESSED_R5G5B5A1:
5305 {
5306 // NOTE: Calculate R5G5B5A1 equivalent color
5307 Vector4 coln = { (float)color.r/255.0f, (float)color.g/255.0f, (float)color.b/255.0f, (float)color.a/255.0f };
5308
5309 unsigned char r = (unsigned char)(round(coln.x*31.0f));
5310 unsigned char g = (unsigned char)(round(coln.y*31.0f));
5311 unsigned char b = (unsigned char)(round(coln.z*31.0f));
5312 unsigned char a = (coln.w > ((float)PIXELFORMAT_UNCOMPRESSED_R5G5B5A1_ALPHA_THRESHOLD/255.0f))? 1 : 0;
5313
5314 ((unsigned short *)dstPtr)[0] = (unsigned short)r << 11 | (unsigned short)g << 6 | (unsigned short)b << 1 | (unsigned short)a;
5315
5316 } break;
5317 case PIXELFORMAT_UNCOMPRESSED_R4G4B4A4:
5318 {
5319 // NOTE: Calculate R5G5B5A1 equivalent color
5320 Vector4 coln = { (float)color.r/255.0f, (float)color.g/255.0f, (float)color.b/255.0f, (float)color.a/255.0f };
5321
5322 unsigned char r = (unsigned char)(round(coln.x*15.0f));
5323 unsigned char g = (unsigned char)(round(coln.y*15.0f));
5324 unsigned char b = (unsigned char)(round(coln.z*15.0f));
5325 unsigned char a = (unsigned char)(round(coln.w*15.0f));
5326
5327 ((unsigned short *)dstPtr)[0] = (unsigned short)r << 12 | (unsigned short)g << 8 | (unsigned short)b << 4 | (unsigned short)a;
5328
5329 } break;
5330 case PIXELFORMAT_UNCOMPRESSED_R8G8B8:
5331 {
5332 ((unsigned char *)dstPtr)[0] = color.r;
5333 ((unsigned char *)dstPtr)[1] = color.g;
5334 ((unsigned char *)dstPtr)[2] = color.b;
5335
5336 } break;
5337 case PIXELFORMAT_UNCOMPRESSED_R8G8B8A8:
5338 {
5339 ((unsigned char *)dstPtr)[0] = color.r;
5340 ((unsigned char *)dstPtr)[1] = color.g;
5341 ((unsigned char *)dstPtr)[2] = color.b;
5342 ((unsigned char *)dstPtr)[3] = color.a;
5343
5344 } break;
5345 default: break;
5346 }
5347 }
5348
5349 // Get pixel data size in bytes for certain format
5350 // NOTE: Size can be requested for Image or Texture data
5351 int GetPixelDataSize(int width, int height, int format)
5352 {
5353 int dataSize = 0; // Size in bytes
5354 int bpp = 0; // Bits per pixel
5355
5356 switch (format)
5357 {
5358 case PIXELFORMAT_UNCOMPRESSED_GRAYSCALE: bpp = 8; break;
5359 case PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA:
5360 case PIXELFORMAT_UNCOMPRESSED_R5G6B5:
5361 case PIXELFORMAT_UNCOMPRESSED_R5G5B5A1:
5362 case PIXELFORMAT_UNCOMPRESSED_R4G4B4A4: bpp = 16; break;
5363 case PIXELFORMAT_UNCOMPRESSED_R8G8B8A8: bpp = 32; break;
5364 case PIXELFORMAT_UNCOMPRESSED_R8G8B8: bpp = 24; break;
5365 case PIXELFORMAT_UNCOMPRESSED_R32: bpp = 32; break;
5366 case PIXELFORMAT_UNCOMPRESSED_R32G32B32: bpp = 32*3; break;
5367 case PIXELFORMAT_UNCOMPRESSED_R32G32B32A32: bpp = 32*4; break;
5368 case PIXELFORMAT_UNCOMPRESSED_R16: bpp = 16; break;
5369 case PIXELFORMAT_UNCOMPRESSED_R16G16B16: bpp = 16*3; break;
5370 case PIXELFORMAT_UNCOMPRESSED_R16G16B16A16: bpp = 16*4; break;
5371 case PIXELFORMAT_COMPRESSED_DXT1_RGB:
5372 case PIXELFORMAT_COMPRESSED_DXT1_RGBA:
5373 case PIXELFORMAT_COMPRESSED_ETC1_RGB:
5374 case PIXELFORMAT_COMPRESSED_ETC2_RGB:
5375 case PIXELFORMAT_COMPRESSED_PVRT_RGB:
5376 case PIXELFORMAT_COMPRESSED_PVRT_RGBA: bpp = 4; break;
5377 case PIXELFORMAT_COMPRESSED_DXT3_RGBA:
5378 case PIXELFORMAT_COMPRESSED_DXT5_RGBA:
5379 case PIXELFORMAT_COMPRESSED_ETC2_EAC_RGBA:
5380 case PIXELFORMAT_COMPRESSED_ASTC_4x4_RGBA: bpp = 8; break;
5381 case PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA: bpp = 2; break;
5382 default: break;
5383 }
5384
5385 double bytesPerPixel = (double)bpp/8.0;
5386 dataSize = (int)(bytesPerPixel*width*height); // Total data size in bytes
5387
5388 // Most compressed formats works on 4x4 blocks,
5389 // if texture is smaller, minimum dataSize is 8 or 16
5390 if ((width < 4) && (height < 4))
5391 {
5392 if ((format >= PIXELFORMAT_COMPRESSED_DXT1_RGB) && (format < PIXELFORMAT_COMPRESSED_DXT3_RGBA)) dataSize = 8;
5393 else if ((format >= PIXELFORMAT_COMPRESSED_DXT3_RGBA) && (format < PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA)) dataSize = 16;
5394 }
5395
5396 return dataSize;
5397 }
5398
5399 //----------------------------------------------------------------------------------
5400 // Module Internal Functions Definition
5401 //----------------------------------------------------------------------------------
5402 // Convert half-float (stored as unsigned short) to float
5403 // REF: https://stackoverflow.com/questions/1659440/32-bit-to-16-bit-floating-point-conversion/60047308#60047308
5404 static float HalfToFloat(unsigned short x)
5405 {
5406 float result = 0.0f;
5407
5408 union {
5409 float fm;
5410 unsigned int ui;
5411 } uni;
5412
5413 const unsigned int e = (x & 0x7c00) >> 10; // Exponent
5414 const unsigned int m = (x & 0x03ff) << 13; // Mantissa
5415 uni.fm = (float)m;
5416 const unsigned int v = uni.ui >> 23; // Evil log2 bit hack to count leading zeros in denormalized format
5417 uni.ui = (x & 0x8000) << 16 | (e != 0)*((e + 112) << 23 | m) | ((e == 0)&(m != 0))*((v - 37) << 23 | ((m << (150 - v)) & 0x007fe000)); // sign : normalized : denormalized
5418
5419 result = uni.fm;
5420
5421 return result;
5422 }
5423
5424 // Convert float to half-float (stored as unsigned short)
5425 static unsigned short FloatToHalf(float x)
5426 {
5427 unsigned short result = 0;
5428
5429 union {
5430 float fm;
5431 unsigned int ui;
5432 } uni;
5433 uni.fm = x;
5434
5435 const unsigned int b = uni.ui + 0x00001000; // Round-to-nearest-even: add last bit after truncated mantissa
5436 const unsigned int e = (b & 0x7f800000) >> 23; // Exponent
5437 const unsigned int m = b & 0x007fffff; // Mantissa; in line below: 0x007ff000 = 0x00800000-0x00001000 = decimal indicator flag - initial rounding
5438
5439 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
5440
5441 return result;
5442 }
5443
5444 // Get pixel data from image as Vector4 array (float normalized)
5445 static Vector4 *LoadImageDataNormalized(Image image)
5446 {
5447 Vector4 *pixels = (Vector4 *)RL_MALLOC(image.width*image.height*sizeof(Vector4));
5448
5449 if (image.format >= PIXELFORMAT_COMPRESSED_DXT1_RGB) TRACELOG(LOG_WARNING, "IMAGE: Pixel data retrieval not supported for compressed image formats");
5450 else
5451 {
5452 for (int i = 0, k = 0; i < image.width*image.height; i++)
5453 {
5454 switch (image.format)
5455 {
5456 case PIXELFORMAT_UNCOMPRESSED_GRAYSCALE:
5457 {
5458 pixels[i].x = (float)((unsigned char *)image.data)[i]/255.0f;
5459 pixels[i].y = (float)((unsigned char *)image.data)[i]/255.0f;
5460 pixels[i].z = (float)((unsigned char *)image.data)[i]/255.0f;
5461 pixels[i].w = 1.0f;
5462
5463 } break;
5464 case PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA:
5465 {
5466 pixels[i].x = (float)((unsigned char *)image.data)[k]/255.0f;
5467 pixels[i].y = (float)((unsigned char *)image.data)[k]/255.0f;
5468 pixels[i].z = (float)((unsigned char *)image.data)[k]/255.0f;
5469 pixels[i].w = (float)((unsigned char *)image.data)[k + 1]/255.0f;
5470
5471 k += 2;
5472 } break;
5473 case PIXELFORMAT_UNCOMPRESSED_R5G5B5A1:
5474 {
5475 unsigned short pixel = ((unsigned short *)image.data)[i];
5476
5477 pixels[i].x = (float)((pixel & 0b1111100000000000) >> 11)*(1.0f/31);
5478 pixels[i].y = (float)((pixel & 0b0000011111000000) >> 6)*(1.0f/31);
5479 pixels[i].z = (float)((pixel & 0b0000000000111110) >> 1)*(1.0f/31);
5480 pixels[i].w = ((pixel & 0b0000000000000001) == 0)? 0.0f : 1.0f;
5481
5482 } break;
5483 case PIXELFORMAT_UNCOMPRESSED_R5G6B5:
5484 {
5485 unsigned short pixel = ((unsigned short *)image.data)[i];
5486
5487 pixels[i].x = (float)((pixel & 0b1111100000000000) >> 11)*(1.0f/31);
5488 pixels[i].y = (float)((pixel & 0b0000011111100000) >> 5)*(1.0f/63);
5489 pixels[i].z = (float)(pixel & 0b0000000000011111)*(1.0f/31);
5490 pixels[i].w = 1.0f;
5491
5492 } break;
5493 case PIXELFORMAT_UNCOMPRESSED_R4G4B4A4:
5494 {
5495 unsigned short pixel = ((unsigned short *)image.data)[i];
5496
5497 pixels[i].x = (float)((pixel & 0b1111000000000000) >> 12)*(1.0f/15);
5498 pixels[i].y = (float)((pixel & 0b0000111100000000) >> 8)*(1.0f/15);
5499 pixels[i].z = (float)((pixel & 0b0000000011110000) >> 4)*(1.0f/15);
5500 pixels[i].w = (float)(pixel & 0b0000000000001111)*(1.0f/15);
5501
5502 } break;
5503 case PIXELFORMAT_UNCOMPRESSED_R8G8B8A8:
5504 {
5505 pixels[i].x = (float)((unsigned char *)image.data)[k]/255.0f;
5506 pixels[i].y = (float)((unsigned char *)image.data)[k + 1]/255.0f;
5507 pixels[i].z = (float)((unsigned char *)image.data)[k + 2]/255.0f;
5508 pixels[i].w = (float)((unsigned char *)image.data)[k + 3]/255.0f;
5509
5510 k += 4;
5511 } break;
5512 case PIXELFORMAT_UNCOMPRESSED_R8G8B8:
5513 {
5514 pixels[i].x = (float)((unsigned char *)image.data)[k]/255.0f;
5515 pixels[i].y = (float)((unsigned char *)image.data)[k + 1]/255.0f;
5516 pixels[i].z = (float)((unsigned char *)image.data)[k + 2]/255.0f;
5517 pixels[i].w = 1.0f;
5518
5519 k += 3;
5520 } break;
5521 case PIXELFORMAT_UNCOMPRESSED_R32:
5522 {
5523 pixels[i].x = ((float *)image.data)[k];
5524 pixels[i].y = 0.0f;
5525 pixels[i].z = 0.0f;
5526 pixels[i].w = 1.0f;
5527
5528 k += 1;
5529 } break;
5530 case PIXELFORMAT_UNCOMPRESSED_R32G32B32:
5531 {
5532 pixels[i].x = ((float *)image.data)[k];
5533 pixels[i].y = ((float *)image.data)[k + 1];
5534 pixels[i].z = ((float *)image.data)[k + 2];
5535 pixels[i].w = 1.0f;
5536
5537 k += 3;
5538 } break;
5539 case PIXELFORMAT_UNCOMPRESSED_R32G32B32A32:
5540 {
5541 pixels[i].x = ((float *)image.data)[k];
5542 pixels[i].y = ((float *)image.data)[k + 1];
5543 pixels[i].z = ((float *)image.data)[k + 2];
5544 pixels[i].w = ((float *)image.data)[k + 3];
5545
5546 k += 4;
5547 } break;
5548 case PIXELFORMAT_UNCOMPRESSED_R16:
5549 {
5550 pixels[i].x = HalfToFloat(((unsigned short *)image.data)[k]);
5551 pixels[i].y = 0.0f;
5552 pixels[i].z = 0.0f;
5553 pixels[i].w = 1.0f;
5554
5555 k += 1;
5556 } break;
5557 case PIXELFORMAT_UNCOMPRESSED_R16G16B16:
5558 {
5559 pixels[i].x = HalfToFloat(((unsigned short *)image.data)[k]);
5560 pixels[i].y = HalfToFloat(((unsigned short *)image.data)[k + 1]);
5561 pixels[i].z = HalfToFloat(((unsigned short *)image.data)[k + 2]);
5562 pixels[i].w = 1.0f;
5563
5564 k += 3;
5565 } break;
5566 case PIXELFORMAT_UNCOMPRESSED_R16G16B16A16:
5567 {
5568 pixels[i].x = HalfToFloat(((unsigned short *)image.data)[k]);
5569 pixels[i].y = HalfToFloat(((unsigned short *)image.data)[k + 1]);
5570 pixels[i].z = HalfToFloat(((unsigned short *)image.data)[k + 2]);
5571 pixels[i].w = HalfToFloat(((unsigned short *)image.data)[k + 3]);
5572
5573 k += 4;
5574 } break;
5575 default: break;
5576 }
5577 }
5578 }
5579
5580 return pixels;
5581 }
5582
5583 #endif // SUPPORT_MODULE_RTEXTURES