Debian Codegraph @

core/io/image.cpp

raw symbols SCIP
1 /**************************************************************************/
2 /* image.cpp */
3 /**************************************************************************/
4 /* This file is part of: */
5 /* GODOT ENGINE */
6 /* https://godotengine.org */
7 /**************************************************************************/
8 /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9 /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10 /* */
11 /* Permission is hereby granted, free of charge, to any person obtaining */
12 /* a copy of this software and associated documentation files (the */
13 /* "Software"), to deal in the Software without restriction, including */
14 /* without limitation the rights to use, copy, modify, merge, publish, */
15 /* distribute, sublicense, and/or sell copies of the Software, and to */
16 /* permit persons to whom the Software is furnished to do so, subject to */
17 /* the following conditions: */
18 /* */
19 /* The above copyright notice and this permission notice shall be */
20 /* included in all copies or substantial portions of the Software. */
21 /* */
22 /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23 /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24 /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25 /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26 /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27 /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28 /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29 /**************************************************************************/
30
31 #include "image.h"
32
33 #include "core/config/project_settings.h"
34 #include "core/error/error_macros.h"
35 #include "core/io/image_loader.h"
36 #include "core/io/resource_loader.h"
37 #include "core/math/math_funcs.h"
38 #include "core/templates/hash_map.h"
39 #include "core/variant/dictionary.h"
40
41 const char *Image::format_names[Image::FORMAT_MAX] = {
42 "Lum8",
43 "LumAlpha8",
44 "Red8",
45 "RedGreen",
46 "RGB8",
47 "RGBA8",
48 "RGBA4444",
49 "RGBA5551", // Actually RGB565, kept as RGBA5551 for compatibility.
50 "RFloat",
51 "RGFloat",
52 "RGBFloat",
53 "RGBAFloat",
54 "RHalf",
55 "RGHalf",
56 "RGBHalf",
57 "RGBAHalf",
58 "RGBE9995",
59 "DXT1 RGB8",
60 "DXT3 RGBA8",
61 "DXT5 RGBA8",
62 "RGTC Red8",
63 "RGTC RedGreen8",
64 "BPTC_RGBA",
65 "BPTC_RGBF",
66 "BPTC_RGBFU",
67 "ETC",
68 "ETC2_R11",
69 "ETC2_R11S",
70 "ETC2_RG11",
71 "ETC2_RG11S",
72 "ETC2_RGB8",
73 "ETC2_RGBA8",
74 "ETC2_RGB8A1",
75 "ETC2_RA_AS_RG",
76 "FORMAT_DXT5_RA_AS_RG",
77 "ASTC_4x4",
78 "ASTC_4x4_HDR",
79 "ASTC_8x8",
80 "ASTC_8x8_HDR",
81 "R16",
82 "RG16",
83 "RGB16",
84 "RGBA16",
85 "R16Int",
86 "RG16Int",
87 "RGB16Int",
88 "RGBA16Int",
89 };
90
91 // External VRAM compression function pointers.
92
93 void (*Image::_image_compress_bc_func)(Image *, Image::UsedChannels) = nullptr;
94 void (*Image::_image_compress_bptc_func)(Image *, Image::UsedChannels) = nullptr;
95 void (*Image::_image_compress_etc1_func)(Image *) = nullptr;
96 void (*Image::_image_compress_etc2_func)(Image *, Image::UsedChannels) = nullptr;
97 void (*Image::_image_compress_astc_func)(Image *, Image::ASTCFormat) = nullptr;
98
99 Error (*Image::_image_compress_bptc_rd_func)(Image *, Image::UsedChannels) = nullptr;
100 Error (*Image::_image_compress_bc_rd_func)(Image *, Image::UsedChannels) = nullptr;
101
102 // External VRAM decompression function pointers.
103
104 void (*Image::_image_decompress_bc)(Image *) = nullptr;
105 void (*Image::_image_decompress_bptc)(Image *) = nullptr;
106 void (*Image::_image_decompress_etc1)(Image *) = nullptr;
107 void (*Image::_image_decompress_etc2)(Image *) = nullptr;
108 void (*Image::_image_decompress_astc)(Image *) = nullptr;
109
110 // External packer function pointers.
111
112 Vector<uint8_t> (*Image::webp_lossy_packer)(const Ref<Image> &, float) = nullptr;
113 Vector<uint8_t> (*Image::webp_lossless_packer)(const Ref<Image> &) = nullptr;
114 Vector<uint8_t> (*Image::png_packer)(const Ref<Image> &) = nullptr;
115 Vector<uint8_t> (*Image::basis_universal_packer)(const Ref<Image> &, Image::UsedChannels, const BasisUniversalPackerParams &) = nullptr;
116
117 Ref<Image> (*Image::webp_unpacker)(const Vector<uint8_t> &) = nullptr;
118 Ref<Image> (*Image::png_unpacker)(const Vector<uint8_t> &) = nullptr;
119 Ref<Image> (*Image::basis_universal_unpacker)(const Vector<uint8_t> &) = nullptr;
120 Ref<Image> (*Image::basis_universal_unpacker_ptr)(const uint8_t *, int) = nullptr;
121
122 void Image::_put_pixelb(int p_x, int p_y, uint32_t p_pixel_size, uint8_t *p_data, const uint8_t *p_pixel) {
123 uint32_t ofs = (p_y * width + p_x) * p_pixel_size;
124 memcpy(p_data + ofs, p_pixel, p_pixel_size);
125 }
126
127 void Image::_get_pixelb(int p_x, int p_y, uint32_t p_pixel_size, const uint8_t *p_data, uint8_t *p_pixel) {
128 uint32_t ofs = (p_y * width + p_x) * p_pixel_size;
129 memcpy(p_pixel, p_data + ofs, p_pixel_size);
130 }
131
132 int Image::get_format_pixel_size(Format p_format) {
133 switch (p_format) {
134 case FORMAT_L8:
135 return 1;
136 case FORMAT_LA8:
137 return 2;
138 case FORMAT_R8:
139 return 1;
140 case FORMAT_RG8:
141 return 2;
142 case FORMAT_RGB8:
143 return 3;
144 case FORMAT_RGBA8:
145 return 4;
146 case FORMAT_RGBA4444:
147 return 2;
148 case FORMAT_RGB565:
149 return 2;
150 case FORMAT_RF:
151 return 4;
152 case FORMAT_RGF:
153 return 8;
154 case FORMAT_RGBF:
155 return 12;
156 case FORMAT_RGBAF:
157 return 16;
158 case FORMAT_RH:
159 return 2;
160 case FORMAT_RGH:
161 return 4;
162 case FORMAT_RGBH:
163 return 6;
164 case FORMAT_RGBAH:
165 return 8;
166 case FORMAT_RGBE9995:
167 return 4;
168 case FORMAT_DXT1:
169 return 1;
170 case FORMAT_DXT3:
171 return 1;
172 case FORMAT_DXT5:
173 return 1;
174 case FORMAT_RGTC_R:
175 return 1;
176 case FORMAT_RGTC_RG:
177 return 1;
178 case FORMAT_BPTC_RGBA:
179 return 1;
180 case FORMAT_BPTC_RGBF:
181 return 1;
182 case FORMAT_BPTC_RGBFU:
183 return 1;
184 case FORMAT_ETC:
185 return 1;
186 case FORMAT_ETC2_R11:
187 return 1;
188 case FORMAT_ETC2_R11S:
189 return 1;
190 case FORMAT_ETC2_RG11:
191 return 1;
192 case FORMAT_ETC2_RG11S:
193 return 1;
194 case FORMAT_ETC2_RGB8:
195 return 1;
196 case FORMAT_ETC2_RGBA8:
197 return 1;
198 case FORMAT_ETC2_RGB8A1:
199 return 1;
200 case FORMAT_ETC2_RA_AS_RG:
201 return 1;
202 case FORMAT_DXT5_RA_AS_RG:
203 return 1;
204 case FORMAT_ASTC_4x4:
205 return 1;
206 case FORMAT_ASTC_4x4_HDR:
207 return 1;
208 case FORMAT_ASTC_8x8:
209 return 1;
210 case FORMAT_ASTC_8x8_HDR:
211 return 1;
212 case FORMAT_R16:
213 return 2;
214 case FORMAT_RG16:
215 return 4;
216 case FORMAT_RGB16:
217 return 6;
218 case FORMAT_RGBA16:
219 return 8;
220 case FORMAT_R16I:
221 return 2;
222 case FORMAT_RG16I:
223 return 4;
224 case FORMAT_RGB16I:
225 return 6;
226 case FORMAT_RGBA16I:
227 return 8;
228 case FORMAT_MAX: {
229 }
230 }
231 return 0;
232 }
233
234 void Image::get_format_min_pixel_size(Format p_format, int &r_w, int &r_h) {
235 switch (p_format) {
236 case FORMAT_DXT1:
237 case FORMAT_DXT3:
238 case FORMAT_DXT5:
239 case FORMAT_RGTC_R:
240 case FORMAT_RGTC_RG: {
241 r_w = 4;
242 r_h = 4;
243 } break;
244 case FORMAT_ETC: {
245 r_w = 4;
246 r_h = 4;
247 } break;
248 case FORMAT_BPTC_RGBA:
249 case FORMAT_BPTC_RGBF:
250 case FORMAT_BPTC_RGBFU: {
251 r_w = 4;
252 r_h = 4;
253 } break;
254 case FORMAT_ETC2_R11:
255 case FORMAT_ETC2_R11S:
256 case FORMAT_ETC2_RG11:
257 case FORMAT_ETC2_RG11S:
258 case FORMAT_ETC2_RGB8:
259 case FORMAT_ETC2_RGBA8:
260 case FORMAT_ETC2_RGB8A1:
261 case FORMAT_ETC2_RA_AS_RG:
262 case FORMAT_DXT5_RA_AS_RG: {
263 r_w = 4;
264 r_h = 4;
265 } break;
266 case FORMAT_ASTC_4x4:
267 case FORMAT_ASTC_4x4_HDR: {
268 r_w = 4;
269 r_h = 4;
270 } break;
271 case FORMAT_ASTC_8x8:
272 case FORMAT_ASTC_8x8_HDR: {
273 r_w = 8;
274 r_h = 8;
275 } break;
276 default: {
277 r_w = 1;
278 r_h = 1;
279 } break;
280 }
281 }
282
283 int Image::get_format_pixel_rshift(Format p_format) {
284 if (p_format == FORMAT_ASTC_8x8) {
285 return 2;
286 } else if (p_format == FORMAT_DXT1 || p_format == FORMAT_RGTC_R || p_format == FORMAT_ETC || p_format == FORMAT_ETC2_R11 || p_format == FORMAT_ETC2_R11S || p_format == FORMAT_ETC2_RGB8 || p_format == FORMAT_ETC2_RGB8A1) {
287 return 1;
288 } else {
289 return 0;
290 }
291 }
292
293 int Image::get_format_block_size(Format p_format) {
294 switch (p_format) {
295 case FORMAT_DXT1:
296 case FORMAT_DXT3:
297 case FORMAT_DXT5:
298 case FORMAT_RGTC_R:
299 case FORMAT_RGTC_RG: {
300 return 4;
301 }
302 case FORMAT_ETC: {
303 return 4;
304 }
305 case FORMAT_BPTC_RGBA:
306 case FORMAT_BPTC_RGBF:
307 case FORMAT_BPTC_RGBFU: {
308 return 4;
309 }
310 case FORMAT_ETC2_R11:
311 case FORMAT_ETC2_R11S:
312 case FORMAT_ETC2_RG11:
313 case FORMAT_ETC2_RG11S:
314 case FORMAT_ETC2_RGB8:
315 case FORMAT_ETC2_RGBA8:
316 case FORMAT_ETC2_RGB8A1:
317 case FORMAT_ETC2_RA_AS_RG:
318 case FORMAT_DXT5_RA_AS_RG: {
319 return 4;
320 }
321 case FORMAT_ASTC_4x4:
322 case FORMAT_ASTC_4x4_HDR: {
323 return 4;
324 }
325 case FORMAT_ASTC_8x8:
326 case FORMAT_ASTC_8x8_HDR: {
327 return 8;
328 }
329 default: {
330 }
331 }
332
333 return 1;
334 }
335
336 void Image::_get_mipmap_offset_and_size(int p_mipmap, int64_t &r_offset, int &r_width, int &r_height) const {
337 int w = width;
338 int h = height;
339 int64_t ofs = 0;
340
341 int pixel_size = get_format_pixel_size(format);
342 int pixel_rshift = get_format_pixel_rshift(format);
343 int block = get_format_block_size(format);
344 int minw, minh;
345 get_format_min_pixel_size(format, minw, minh);
346
347 for (int i = 0; i < p_mipmap; i++) {
348 int bw = w % block != 0 ? w + (block - w % block) : w;
349 int bh = h % block != 0 ? h + (block - h % block) : h;
350
351 int64_t s = bw * bh;
352
353 s *= pixel_size;
354 s >>= pixel_rshift;
355 ofs += s;
356 w = MAX(minw, w >> 1);
357 h = MAX(minh, h >> 1);
358 }
359
360 r_offset = ofs;
361 r_width = w;
362 r_height = h;
363 }
364
365 int64_t Image::get_mipmap_offset(int p_mipmap) const {
366 ERR_FAIL_INDEX_V(p_mipmap, get_mipmap_count() + 1, -1);
367
368 int64_t ofs;
369 int w, h;
370 _get_mipmap_offset_and_size(p_mipmap, ofs, w, h);
371 return ofs;
372 }
373
374 void Image::get_mipmap_offset_and_size(int p_mipmap, int64_t &r_ofs, int64_t &r_size) const {
375 int64_t ofs;
376 int w, h;
377 _get_mipmap_offset_and_size(p_mipmap, ofs, w, h);
378 int64_t ofs2;
379 _get_mipmap_offset_and_size(p_mipmap + 1, ofs2, w, h);
380 r_ofs = ofs;
381 r_size = ofs2 - ofs;
382 }
383
384 void Image::get_mipmap_offset_size_and_dimensions(int p_mipmap, int64_t &r_ofs, int64_t &r_size, int &w, int &h) const {
385 int64_t ofs;
386 _get_mipmap_offset_and_size(p_mipmap, ofs, w, h);
387 int64_t ofs2;
388 int w2, h2;
389 _get_mipmap_offset_and_size(p_mipmap + 1, ofs2, w2, h2);
390 r_ofs = ofs;
391 r_size = ofs2 - ofs;
392 }
393
394 Image::Image3DValidateError Image::validate_3d_image(Image::Format p_format, int p_width, int p_height, int p_depth, bool p_mipmaps, const Vector<Ref<Image>> &p_images) {
395 int w = p_width;
396 int h = p_height;
397 int d = p_depth;
398
399 int arr_ofs = 0;
400
401 while (true) {
402 for (int i = 0; i < d; i++) {
403 int idx = i + arr_ofs;
404 if (idx >= p_images.size()) {
405 return VALIDATE_3D_ERR_MISSING_IMAGES;
406 }
407 if (p_images[idx].is_null() || p_images[idx]->is_empty()) {
408 return VALIDATE_3D_ERR_IMAGE_EMPTY;
409 }
410 if (p_images[idx]->get_format() != p_format) {
411 return VALIDATE_3D_ERR_IMAGE_FORMAT_MISMATCH;
412 }
413 if (p_images[idx]->get_width() != w || p_images[idx]->get_height() != h) {
414 return VALIDATE_3D_ERR_IMAGE_SIZE_MISMATCH;
415 }
416 if (p_images[idx]->has_mipmaps()) {
417 return VALIDATE_3D_ERR_IMAGE_HAS_MIPMAPS;
418 }
419 }
420
421 arr_ofs += d;
422
423 if (!p_mipmaps) {
424 break;
425 }
426
427 if (w == 1 && h == 1 && d == 1) {
428 break;
429 }
430
431 w = MAX(1, w >> 1);
432 h = MAX(1, h >> 1);
433 d = MAX(1, d >> 1);
434 }
435
436 if (arr_ofs != p_images.size()) {
437 return VALIDATE_3D_ERR_EXTRA_IMAGES;
438 }
439
440 return VALIDATE_3D_OK;
441 }
442
443 String Image::get_3d_image_validation_error_text(Image3DValidateError p_error) {
444 switch (p_error) {
445 case VALIDATE_3D_OK: {
446 return "Ok";
447 } break;
448 case VALIDATE_3D_ERR_IMAGE_EMPTY: {
449 return "Empty Image found";
450 } break;
451 case VALIDATE_3D_ERR_MISSING_IMAGES: {
452 return "Missing Images";
453 } break;
454 case VALIDATE_3D_ERR_EXTRA_IMAGES: {
455 return "Too many Images";
456 } break;
457 case VALIDATE_3D_ERR_IMAGE_SIZE_MISMATCH: {
458 return "Image size mismatch";
459 } break;
460 case VALIDATE_3D_ERR_IMAGE_FORMAT_MISMATCH: {
461 return "Image format mismatch";
462 } break;
463 case VALIDATE_3D_ERR_IMAGE_HAS_MIPMAPS: {
464 return "Image has included mipmaps";
465 } break;
466 }
467 return String();
468 }
469
470 int Image::get_width() const {
471 return width;
472 }
473
474 int Image::get_height() const {
475 return height;
476 }
477
478 Size2i Image::get_size() const {
479 return Size2i(width, height);
480 }
481
482 bool Image::has_mipmaps() const {
483 return mipmaps;
484 }
485
486 int Image::get_mipmap_count() const {
487 if (mipmaps) {
488 return get_image_required_mipmaps(width, height, format);
489 } else {
490 return 0;
491 }
492 }
493
494 // Using template generates perfectly optimized code due to constant expression reduction and unused variable removal present in all compilers.
495 template <uint32_t read_bytes, bool read_alpha, uint32_t write_bytes, bool write_alpha, bool read_gray, bool write_gray>
496 static void _convert(int p_width, int p_height, const uint8_t *p_src, uint8_t *p_dst) {
497 constexpr uint32_t max_bytes = MAX(read_bytes, write_bytes);
498
499 for (int y = 0; y < p_height; y++) {
500 for (int x = 0; x < p_width; x++) {
501 const uint8_t *rofs = &p_src[((y * p_width) + x) * (read_bytes + (read_alpha ? 1 : 0))];
502 uint8_t *wofs = &p_dst[((y * p_width) + x) * (write_bytes + (write_alpha ? 1 : 0))];
503
504 uint8_t rgba[4] = { 0, 0, 0, 255 };
505
506 if constexpr (read_gray) {
507 rgba[0] = rofs[0];
508 rgba[1] = rofs[0];
509 rgba[2] = rofs[0];
510 } else {
511 for (uint32_t i = 0; i < max_bytes; i++) {
512 rgba[i] = (i < read_bytes) ? rofs[i] : 0;
513 }
514 }
515
516 if constexpr (read_alpha || write_alpha) {
517 rgba[3] = read_alpha ? rofs[read_bytes] : 255;
518 }
519
520 if constexpr (write_gray) {
521 // REC.709
522 const uint8_t luminance = (13938U * rgba[0] + 46869U * rgba[1] + 4729U * rgba[2] + 32768U) >> 16U;
523 wofs[0] = luminance;
524 } else {
525 for (uint32_t i = 0; i < write_bytes; i++) {
526 wofs[i] = rgba[i];
527 }
528 }
529
530 if constexpr (write_alpha) {
531 wofs[write_bytes] = rgba[3];
532 }
533 }
534 }
535 }
536
537 template <typename T, uint32_t read_channels, uint32_t write_channels, T def_zero, T def_one>
538 static void _convert_fast(int p_width, int p_height, const T *p_src, T *p_dst) {
539 uint32_t dst_count = 0;
540 uint32_t src_count = 0;
541
542 const int resolution = p_width * p_height;
543
544 for (int i = 0; i < resolution; i++) {
545 memcpy(p_dst + dst_count, p_src + src_count, MIN(read_channels, write_channels) * sizeof(T));
546
547 if constexpr (write_channels > read_channels) {
548 const T def_value[4] = { def_zero, def_zero, def_zero, def_one };
549 memcpy(p_dst + dst_count + read_channels, &def_value[read_channels], (write_channels - read_channels) * sizeof(T));
550 }
551
552 dst_count += write_channels;
553 src_count += read_channels;
554 }
555 }
556
557 static bool _are_formats_compatible(Image::Format p_format0, Image::Format p_format1) {
558 if (p_format0 <= Image::FORMAT_RGBA8 && p_format1 <= Image::FORMAT_RGBA8) {
559 return true;
560 } else if (p_format0 <= Image::FORMAT_RGBAH && p_format0 >= Image::FORMAT_RH && p_format1 <= Image::FORMAT_RGBAH && p_format1 >= Image::FORMAT_RH) {
561 return true;
562 } else if (p_format0 <= Image::FORMAT_RGBAF && p_format0 >= Image::FORMAT_RF && p_format1 <= Image::FORMAT_RGBAF && p_format1 >= Image::FORMAT_RF) {
563 return true;
564 }
565
566 return false;
567 }
568
569 void Image::convert(Format p_new_format) {
570 ERR_FAIL_INDEX_MSG(p_new_format, FORMAT_MAX, vformat("The Image format specified (%d) is out of range. See Image's Format enum.", p_new_format));
571 ERR_FAIL_COND_MSG(Image::is_format_compressed(format) || Image::is_format_compressed(p_new_format),
572 "Cannot convert to (or from) compressed formats. Use compress() and decompress() instead.");
573
574 if (data.is_empty() || p_new_format == format) {
575 return;
576 }
577
578 // Includes the main image.
579 const int mipmap_count = get_mipmap_count() + 1;
580
581 if (!_are_formats_compatible(format, p_new_format)) {
582 // Use put/set pixel which is slower but works with non-byte formats.
583 Image new_img(width, height, mipmaps, p_new_format);
584
585 for (int mip = 0; mip < mipmap_count; mip++) {
586 int64_t src_mip_ofs, dst_mip_ofs;
587 int w, h;
588 _get_mipmap_offset_and_size(mip, src_mip_ofs, w, h);
589 new_img._get_mipmap_offset_and_size(mip, dst_mip_ofs, w, h);
590
591 uint8_t *dst_mip_ptr = new_img.ptrw() + dst_mip_ofs;
592 const uint8_t *src_mip_ptr = ptr() + src_mip_ofs;
593
594 for (int y = 0; y < h; y++) {
595 for (int x = 0; x < w; x++) {
596 uint32_t mip_ofs = y * w + x;
597 new_img._set_color_at_ofs(dst_mip_ptr, mip_ofs, _get_color_at_ofs(src_mip_ptr, mip_ofs));
598 }
599 }
600 }
601
602 _copy_internals_from(new_img);
603 return;
604 }
605
606 // Convert the formats in an optimized way by removing/adding color channels if necessary.
607 Image new_img(width, height, mipmaps, p_new_format);
608
609 const int conversion_type = format | p_new_format << 8;
610
611 for (int mip = 0; mip < mipmap_count; mip++) {
612 int64_t mip_offset = 0;
613 int64_t mip_size = 0;
614 int mip_width = 0;
615 int mip_height = 0;
616 get_mipmap_offset_size_and_dimensions(mip, mip_offset, mip_size, mip_width, mip_height);
617
618 const uint8_t *rptr = data.ptr() + mip_offset;
619 uint8_t *wptr = new_img.data.ptrw() + new_img.get_mipmap_offset(mip);
620
621 switch (conversion_type) {
622 case FORMAT_L8 | (FORMAT_LA8 << 8):
623 _convert<1, false, 1, true, true, true>(mip_width, mip_height, rptr, wptr);
624 break;
625 case FORMAT_L8 | (FORMAT_R8 << 8):
626 _convert<1, false, 1, false, true, false>(mip_width, mip_height, rptr, wptr);
627 break;
628 case FORMAT_L8 | (FORMAT_RG8 << 8):
629 _convert<1, false, 2, false, true, false>(mip_width, mip_height, rptr, wptr);
630 break;
631 case FORMAT_L8 | (FORMAT_RGB8 << 8):
632 _convert<1, false, 3, false, true, false>(mip_width, mip_height, rptr, wptr);
633 break;
634 case FORMAT_L8 | (FORMAT_RGBA8 << 8):
635 _convert<1, false, 3, true, true, false>(mip_width, mip_height, rptr, wptr);
636 break;
637 case FORMAT_LA8 | (FORMAT_L8 << 8):
638 _convert<1, true, 1, false, true, true>(mip_width, mip_height, rptr, wptr);
639 break;
640 case FORMAT_LA8 | (FORMAT_R8 << 8):
641 _convert<1, true, 1, false, true, false>(mip_width, mip_height, rptr, wptr);
642 break;
643 case FORMAT_LA8 | (FORMAT_RG8 << 8):
644 _convert<1, true, 2, false, true, false>(mip_width, mip_height, rptr, wptr);
645 break;
646 case FORMAT_LA8 | (FORMAT_RGB8 << 8):
647 _convert<1, true, 3, false, true, false>(mip_width, mip_height, rptr, wptr);
648 break;
649 case FORMAT_LA8 | (FORMAT_RGBA8 << 8):
650 _convert<1, true, 3, true, true, false>(mip_width, mip_height, rptr, wptr);
651 break;
652 case FORMAT_R8 | (FORMAT_L8 << 8):
653 _convert<1, false, 1, false, false, true>(mip_width, mip_height, rptr, wptr);
654 break;
655 case FORMAT_R8 | (FORMAT_LA8 << 8):
656 _convert<1, false, 1, true, false, true>(mip_width, mip_height, rptr, wptr);
657 break;
658 case FORMAT_R8 | (FORMAT_RG8 << 8):
659 _convert<1, false, 2, false, false, false>(mip_width, mip_height, rptr, wptr);
660 break;
661 case FORMAT_R8 | (FORMAT_RGB8 << 8):
662 _convert<1, false, 3, false, false, false>(mip_width, mip_height, rptr, wptr);
663 break;
664 case FORMAT_R8 | (FORMAT_RGBA8 << 8):
665 _convert<1, false, 3, true, false, false>(mip_width, mip_height, rptr, wptr);
666 break;
667 case FORMAT_RG8 | (FORMAT_L8 << 8):
668 _convert<2, false, 1, false, false, true>(mip_width, mip_height, rptr, wptr);
669 break;
670 case FORMAT_RG8 | (FORMAT_LA8 << 8):
671 _convert<2, false, 1, true, false, true>(mip_width, mip_height, rptr, wptr);
672 break;
673 case FORMAT_RG8 | (FORMAT_R8 << 8):
674 _convert<2, false, 1, false, false, false>(mip_width, mip_height, rptr, wptr);
675 break;
676 case FORMAT_RG8 | (FORMAT_RGB8 << 8):
677 _convert<2, false, 3, false, false, false>(mip_width, mip_height, rptr, wptr);
678 break;
679 case FORMAT_RG8 | (FORMAT_RGBA8 << 8):
680 _convert<2, false, 3, true, false, false>(mip_width, mip_height, rptr, wptr);
681 break;
682 case FORMAT_RGB8 | (FORMAT_L8 << 8):
683 _convert<3, false, 1, false, false, true>(mip_width, mip_height, rptr, wptr);
684 break;
685 case FORMAT_RGB8 | (FORMAT_LA8 << 8):
686 _convert<3, false, 1, true, false, true>(mip_width, mip_height, rptr, wptr);
687 break;
688 case FORMAT_RGB8 | (FORMAT_R8 << 8):
689 _convert<3, false, 1, false, false, false>(mip_width, mip_height, rptr, wptr);
690 break;
691 case FORMAT_RGB8 | (FORMAT_RG8 << 8):
692 _convert<3, false, 2, false, false, false>(mip_width, mip_height, rptr, wptr);
693 break;
694 case FORMAT_RGB8 | (FORMAT_RGBA8 << 8):
695 _convert<3, false, 3, true, false, false>(mip_width, mip_height, rptr, wptr);
696 break;
697 case FORMAT_RGBA8 | (FORMAT_L8 << 8):
698 _convert<3, true, 1, false, false, true>(mip_width, mip_height, rptr, wptr);
699 break;
700 case FORMAT_RGBA8 | (FORMAT_LA8 << 8):
701 _convert<3, true, 1, true, false, true>(mip_width, mip_height, rptr, wptr);
702 break;
703 case FORMAT_RGBA8 | (FORMAT_R8 << 8):
704 _convert<3, true, 1, false, false, false>(mip_width, mip_height, rptr, wptr);
705 break;
706 case FORMAT_RGBA8 | (FORMAT_RG8 << 8):
707 _convert<3, true, 2, false, false, false>(mip_width, mip_height, rptr, wptr);
708 break;
709 case FORMAT_RGBA8 | (FORMAT_RGB8 << 8):
710 _convert<3, true, 3, false, false, false>(mip_width, mip_height, rptr, wptr);
711 break;
712 case FORMAT_RH | (FORMAT_RGH << 8):
713 _convert_fast<uint16_t, 1, 2, 0x0000, 0x3C00>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
714 break;
715 case FORMAT_RH | (FORMAT_RGBH << 8):
716 _convert_fast<uint16_t, 1, 3, 0x0000, 0x3C00>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
717 break;
718 case FORMAT_RH | (FORMAT_RGBAH << 8):
719 _convert_fast<uint16_t, 1, 4, 0x0000, 0x3C00>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
720 break;
721 case FORMAT_RGH | (FORMAT_RH << 8):
722 _convert_fast<uint16_t, 2, 1, 0x0000, 0x3C00>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
723 break;
724 case FORMAT_RGH | (FORMAT_RGBH << 8):
725 _convert_fast<uint16_t, 2, 3, 0x0000, 0x3C00>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
726 break;
727 case FORMAT_RGH | (FORMAT_RGBAH << 8):
728 _convert_fast<uint16_t, 2, 4, 0x0000, 0x3C00>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
729 break;
730 case FORMAT_RGBH | (FORMAT_RH << 8):
731 _convert_fast<uint16_t, 3, 1, 0x0000, 0x3C00>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
732 break;
733 case FORMAT_RGBH | (FORMAT_RGH << 8):
734 _convert_fast<uint16_t, 3, 2, 0x0000, 0x3C00>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
735 break;
736 case FORMAT_RGBH | (FORMAT_RGBAH << 8):
737 _convert_fast<uint16_t, 3, 4, 0x0000, 0x3C00>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
738 break;
739 case FORMAT_RGBAH | (FORMAT_RH << 8):
740 _convert_fast<uint16_t, 4, 1, 0x0000, 0x3C00>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
741 break;
742 case FORMAT_RGBAH | (FORMAT_RGH << 8):
743 _convert_fast<uint16_t, 4, 2, 0x0000, 0x3C00>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
744 break;
745 case FORMAT_RGBAH | (FORMAT_RGBH << 8):
746 _convert_fast<uint16_t, 4, 3, 0x0000, 0x3C00>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
747 break;
748 case FORMAT_RF | (FORMAT_RGF << 8):
749 _convert_fast<uint32_t, 1, 2, 0x00000000, 0x3F800000>(mip_width, mip_height, (const uint32_t *)rptr, (uint32_t *)wptr);
750 break;
751 case FORMAT_RF | (FORMAT_RGBF << 8):
752 _convert_fast<uint32_t, 1, 3, 0x00000000, 0x3F800000>(mip_width, mip_height, (const uint32_t *)rptr, (uint32_t *)wptr);
753 break;
754 case FORMAT_RF | (FORMAT_RGBAF << 8):
755 _convert_fast<uint32_t, 1, 4, 0x00000000, 0x3F800000>(mip_width, mip_height, (const uint32_t *)rptr, (uint32_t *)wptr);
756 break;
757 case FORMAT_RGF | (FORMAT_RF << 8):
758 _convert_fast<uint32_t, 2, 1, 0x00000000, 0x3F800000>(mip_width, mip_height, (const uint32_t *)rptr, (uint32_t *)wptr);
759 break;
760 case FORMAT_RGF | (FORMAT_RGBF << 8):
761 _convert_fast<uint32_t, 2, 3, 0x00000000, 0x3F800000>(mip_width, mip_height, (const uint32_t *)rptr, (uint32_t *)wptr);
762 break;
763 case FORMAT_RGF | (FORMAT_RGBAF << 8):
764 _convert_fast<uint32_t, 2, 4, 0x00000000, 0x3F800000>(mip_width, mip_height, (const uint32_t *)rptr, (uint32_t *)wptr);
765 break;
766 case FORMAT_RGBF | (FORMAT_RF << 8):
767 _convert_fast<uint32_t, 3, 1, 0x00000000, 0x3F800000>(mip_width, mip_height, (const uint32_t *)rptr, (uint32_t *)wptr);
768 break;
769 case FORMAT_RGBF | (FORMAT_RGF << 8):
770 _convert_fast<uint32_t, 3, 2, 0x00000000, 0x3F800000>(mip_width, mip_height, (const uint32_t *)rptr, (uint32_t *)wptr);
771 break;
772 case FORMAT_RGBF | (FORMAT_RGBAF << 8):
773 _convert_fast<uint32_t, 3, 4, 0x00000000, 0x3F800000>(mip_width, mip_height, (const uint32_t *)rptr, (uint32_t *)wptr);
774 break;
775 case FORMAT_RGBAF | (FORMAT_RF << 8):
776 _convert_fast<uint32_t, 4, 1, 0x00000000, 0x3F800000>(mip_width, mip_height, (const uint32_t *)rptr, (uint32_t *)wptr);
777 break;
778 case FORMAT_RGBAF | (FORMAT_RGF << 8):
779 _convert_fast<uint32_t, 4, 2, 0x00000000, 0x3F800000>(mip_width, mip_height, (const uint32_t *)rptr, (uint32_t *)wptr);
780 break;
781 case FORMAT_RGBAF | (FORMAT_RGBF << 8):
782 _convert_fast<uint32_t, 4, 3, 0x00000000, 0x3F800000>(mip_width, mip_height, (const uint32_t *)rptr, (uint32_t *)wptr);
783 break;
784 case FORMAT_R16 | (FORMAT_RG16 << 8):
785 _convert_fast<uint16_t, 1, 2, 0x0000, 0xFFFF>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
786 break;
787 case FORMAT_R16 | (FORMAT_RGB16 << 8):
788 _convert_fast<uint16_t, 1, 3, 0x0000, 0xFFFF>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
789 break;
790 case FORMAT_R16 | (FORMAT_RGBA16 << 8):
791 _convert_fast<uint16_t, 1, 4, 0x0000, 0xFFFF>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
792 break;
793 case FORMAT_RG16 | (FORMAT_R16 << 8):
794 _convert_fast<uint16_t, 2, 1, 0x0000, 0xFFFF>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
795 break;
796 case FORMAT_RG16 | (FORMAT_RGB16 << 8):
797 _convert_fast<uint16_t, 2, 3, 0x0000, 0xFFFF>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
798 break;
799 case FORMAT_RG16 | (FORMAT_RGBA16 << 8):
800 _convert_fast<uint16_t, 2, 4, 0x0000, 0xFFFF>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
801 break;
802 case FORMAT_RGB16 | (FORMAT_R16 << 8):
803 _convert_fast<uint16_t, 3, 1, 0x0000, 0xFFFF>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
804 break;
805 case FORMAT_RGB16 | (FORMAT_RG16 << 8):
806 _convert_fast<uint16_t, 3, 2, 0x0000, 0xFFFF>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
807 break;
808 case FORMAT_RGB16 | (FORMAT_RGBA16 << 8):
809 _convert_fast<uint16_t, 3, 4, 0x0000, 0xFFFF>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
810 break;
811 case FORMAT_RGBA16 | (FORMAT_R16 << 8):
812 _convert_fast<uint16_t, 4, 1, 0x0000, 0xFFFF>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
813 break;
814 case FORMAT_RGBA16 | (FORMAT_RG16 << 8):
815 _convert_fast<uint16_t, 4, 2, 0x0000, 0xFFFF>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
816 break;
817 case FORMAT_RGBA16 | (FORMAT_RGB16 << 8):
818 _convert_fast<uint16_t, 4, 3, 0x0000, 0xFFFF>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
819 break;
820 case FORMAT_R16I | (FORMAT_RG16I << 8):
821 _convert_fast<uint16_t, 1, 2, 0x0000, 0x0001>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
822 break;
823 case FORMAT_R16I | (FORMAT_RGB16I << 8):
824 _convert_fast<uint16_t, 1, 3, 0x0000, 0x0001>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
825 break;
826 case FORMAT_R16I | (FORMAT_RGBA16I << 8):
827 _convert_fast<uint16_t, 1, 4, 0x0000, 0x0001>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
828 break;
829 case FORMAT_RG16I | (FORMAT_R16I << 8):
830 _convert_fast<uint16_t, 2, 1, 0x0000, 0x0001>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
831 break;
832 case FORMAT_RG16I | (FORMAT_RGB16I << 8):
833 _convert_fast<uint16_t, 2, 3, 0x0000, 0x0001>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
834 break;
835 case FORMAT_RG16I | (FORMAT_RGBA16I << 8):
836 _convert_fast<uint16_t, 2, 4, 0x0000, 0x0001>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
837 break;
838 case FORMAT_RGB16I | (FORMAT_R16I << 8):
839 _convert_fast<uint16_t, 3, 1, 0x0000, 0x0001>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
840 break;
841 case FORMAT_RGB16I | (FORMAT_RG16I << 8):
842 _convert_fast<uint16_t, 3, 2, 0x0000, 0x0001>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
843 break;
844 case FORMAT_RGB16I | (FORMAT_RGBA16I << 8):
845 _convert_fast<uint16_t, 3, 4, 0x0000, 0x0001>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
846 break;
847 case FORMAT_RGBA16I | (FORMAT_R16I << 8):
848 _convert_fast<uint16_t, 4, 1, 0x0000, 0x0001>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
849 break;
850 case FORMAT_RGBA16I | (FORMAT_RG16I << 8):
851 _convert_fast<uint16_t, 4, 2, 0x0000, 0x0001>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
852 break;
853 case FORMAT_RGBA16I | (FORMAT_RGB16I << 8):
854 _convert_fast<uint16_t, 4, 3, 0x0000, 0x0001>(mip_width, mip_height, (const uint16_t *)rptr, (uint16_t *)wptr);
855 break;
856 }
857 }
858
859 _copy_internals_from(new_img);
860 }
861
862 Image::Format Image::get_format() const {
863 return format;
864 }
865
866 enum ImageScaleType {
867 IMAGE_SCALING_INT,
868 IMAGE_SCALING_FLOAT,
869 };
870
871 static double _bicubic_interp_kernel(double x) {
872 x = Math::abs(x);
873
874 double bc = 0;
875
876 if (x <= 1) {
877 bc = (1.5 * x - 2.5) * x * x + 1;
878 } else if (x < 2) {
879 bc = ((-0.5 * x + 2.5) * x - 4) * x + 2;
880 }
881
882 return bc;
883 }
884
885 template <int CC, typename T, ImageScaleType TYPE>
886 static void _scale_cubic(const uint8_t *__restrict p_src, uint8_t *__restrict p_dst, uint32_t p_src_width, uint32_t p_src_height, uint32_t p_dst_width, uint32_t p_dst_height) {
887 // get source image size
888 int width = p_src_width;
889 int height = p_src_height;
890 double xfac = (double)width / p_dst_width;
891 double yfac = (double)height / p_dst_height;
892 // coordinates of source points and coefficients
893 double ox, oy, dx, dy;
894 int ox1, oy1, ox2, oy2;
895 // destination pixel values
896 // width and height decreased by 1
897 int ymax = height - 1;
898 int xmax = width - 1;
899 // temporary pointer
900
901 for (uint32_t y = 0; y < p_dst_height; y++) {
902 // Y coordinates
903 oy = (double)(y + 0.5) * yfac - 0.5;
904 oy1 = (int)oy;
905 dy = oy - (double)oy1;
906
907 for (uint32_t x = 0; x < p_dst_width; x++) {
908 // X coordinates
909 ox = (double)(x + 0.5) * xfac - 0.5;
910 ox1 = (int)ox;
911 dx = ox - (double)ox1;
912
913 // initial pixel value
914
915 T *__restrict dst = ((T *)p_dst) + (y * p_dst_width + x) * CC;
916
917 double color[CC] = {};
918
919 for (int n = -1; n < 3; n++) {
920 // get Y coefficient
921 [[maybe_unused]] double k1 = _bicubic_interp_kernel(dy - (double)n);
922
923 oy2 = oy1 + n;
924 if (oy2 < 0) {
925 oy2 = 0;
926 }
927 if (oy2 > ymax) {
928 oy2 = ymax;
929 }
930
931 for (int m = -1; m < 3; m++) {
932 // get X coefficient
933 [[maybe_unused]] double k2 = k1 * _bicubic_interp_kernel((double)m - dx);
934
935 ox2 = ox1 + m;
936 if (ox2 < 0) {
937 ox2 = 0;
938 }
939 if (ox2 > xmax) {
940 ox2 = xmax;
941 }
942
943 // get pixel of original image
944 const T *__restrict p = ((T *)p_src) + (oy2 * p_src_width + ox2) * CC;
945
946 for (int i = 0; i < CC; i++) {
947 if constexpr (sizeof(T) == 2 && TYPE == IMAGE_SCALING_FLOAT) { //half float
948 color[i] = Math::half_to_float(p[i]);
949 } else {
950 color[i] += p[i] * k2;
951 }
952 }
953 }
954 }
955
956 for (int i = 0; i < CC; i++) {
957 if constexpr (sizeof(T) == 1) { //byte
958 dst[i] = CLAMP(Math::fast_ftoi(color[i]), 0, 255);
959 } else if constexpr (sizeof(T) == 2) {
960 if constexpr (TYPE == IMAGE_SCALING_FLOAT) {
961 dst[i] = Math::make_half_float(color[i]); //half float
962 } else {
963 dst[i] = CLAMP(Math::fast_ftoi(color[i]), 0, 65535); // uint16
964 }
965 } else {
966 dst[i] = color[i];
967 }
968 }
969 }
970 }
971 }
972
973 template <int CC, typename T, ImageScaleType TYPE>
974 static void _scale_bilinear(const uint8_t *__restrict p_src, uint8_t *__restrict p_dst, uint32_t p_src_width, uint32_t p_src_height, uint32_t p_dst_width, uint32_t p_dst_height) {
975 constexpr uint32_t FRAC_BITS = 8;
976 constexpr uint32_t FRAC_LEN = (1 << FRAC_BITS);
977 constexpr uint32_t FRAC_HALF = (FRAC_LEN >> 1);
978 constexpr uint32_t FRAC_MASK = FRAC_LEN - 1;
979
980 for (uint32_t i = 0; i < p_dst_height; i++) {
981 // Add 0.5 in order to interpolate based on pixel center
982 uint32_t src_yofs_up_fp = (i + 0.5) * p_src_height * FRAC_LEN / p_dst_height;
983 // Calculate nearest src pixel center above current, and truncate to get y index
984 uint32_t src_yofs_up = src_yofs_up_fp >= FRAC_HALF ? (src_yofs_up_fp - FRAC_HALF) >> FRAC_BITS : 0;
985 uint32_t src_yofs_down = (src_yofs_up_fp + FRAC_HALF) >> FRAC_BITS;
986 if (src_yofs_down >= p_src_height) {
987 src_yofs_down = p_src_height - 1;
988 }
989 // Calculate distance to pixel center of src_yofs_up
990 uint32_t src_yofs_frac = src_yofs_up_fp & FRAC_MASK;
991 src_yofs_frac = src_yofs_frac >= FRAC_HALF ? src_yofs_frac - FRAC_HALF : src_yofs_frac + FRAC_HALF;
992
993 uint32_t y_ofs_up = src_yofs_up * p_src_width * CC;
994 uint32_t y_ofs_down = src_yofs_down * p_src_width * CC;
995
996 for (uint32_t j = 0; j < p_dst_width; j++) {
997 uint32_t src_xofs_left_fp = (j + 0.5) * p_src_width * FRAC_LEN / p_dst_width;
998 uint32_t src_xofs_left = src_xofs_left_fp >= FRAC_HALF ? (src_xofs_left_fp - FRAC_HALF) >> FRAC_BITS : 0;
999 uint32_t src_xofs_right = (src_xofs_left_fp + FRAC_HALF) >> FRAC_BITS;
1000 if (src_xofs_right >= p_src_width) {
1001 src_xofs_right = p_src_width - 1;
1002 }
1003 uint32_t src_xofs_frac = src_xofs_left_fp & FRAC_MASK;
1004 src_xofs_frac = src_xofs_frac >= FRAC_HALF ? src_xofs_frac - FRAC_HALF : src_xofs_frac + FRAC_HALF;
1005
1006 src_xofs_left *= CC;
1007 src_xofs_right *= CC;
1008
1009 for (uint32_t l = 0; l < CC; l++) {
1010 if constexpr (sizeof(T) == 1) { //uint8
1011 uint32_t p00 = p_src[y_ofs_up + src_xofs_left + l] << FRAC_BITS;
1012 uint32_t p10 = p_src[y_ofs_up + src_xofs_right + l] << FRAC_BITS;
1013 uint32_t p01 = p_src[y_ofs_down + src_xofs_left + l] << FRAC_BITS;
1014 uint32_t p11 = p_src[y_ofs_down + src_xofs_right + l] << FRAC_BITS;
1015
1016 uint32_t interp_up = p00 + (((p10 - p00) * src_xofs_frac) >> FRAC_BITS);
1017 uint32_t interp_down = p01 + (((p11 - p01) * src_xofs_frac) >> FRAC_BITS);
1018 uint32_t interp = interp_up + (((interp_down - interp_up) * src_yofs_frac) >> FRAC_BITS);
1019 interp >>= FRAC_BITS;
1020 p_dst[i * p_dst_width * CC + j * CC + l] = uint8_t(interp);
1021 } else if constexpr (sizeof(T) == 2) {
1022 if constexpr (TYPE == IMAGE_SCALING_FLOAT) { //half float
1023 float xofs_frac = float(src_xofs_frac) / (1 << FRAC_BITS);
1024 float yofs_frac = float(src_yofs_frac) / (1 << FRAC_BITS);
1025 const T *src = ((const T *)p_src);
1026 T *dst = ((T *)p_dst);
1027
1028 float p00 = Math::half_to_float(src[y_ofs_up + src_xofs_left + l]);
1029 float p10 = Math::half_to_float(src[y_ofs_up + src_xofs_right + l]);
1030 float p01 = Math::half_to_float(src[y_ofs_down + src_xofs_left + l]);
1031 float p11 = Math::half_to_float(src[y_ofs_down + src_xofs_right + l]);
1032
1033 float interp_up = p00 + (p10 - p00) * xofs_frac;
1034 float interp_down = p01 + (p11 - p01) * xofs_frac;
1035 float interp = interp_up + ((interp_down - interp_up) * yofs_frac);
1036
1037 dst[i * p_dst_width * CC + j * CC + l] = Math::make_half_float(interp);
1038 } else { //uint16
1039 float xofs_frac = float(src_xofs_frac) / (1 << FRAC_BITS);
1040 float yofs_frac = float(src_yofs_frac) / (1 << FRAC_BITS);
1041 const T *src = ((const T *)p_src);
1042 T *dst = ((T *)p_dst);
1043
1044 float p00 = src[y_ofs_up + src_xofs_left + l];
1045 float p10 = src[y_ofs_up + src_xofs_right + l];
1046 float p01 = src[y_ofs_down + src_xofs_left + l];
1047 float p11 = src[y_ofs_down + src_xofs_right + l];
1048
1049 float interp_up = p00 + (p10 - p00) * xofs_frac;
1050 float interp_down = p01 + (p11 - p01) * xofs_frac;
1051 float interp = interp_up + ((interp_down - interp_up) * yofs_frac);
1052
1053 dst[i * p_dst_width * CC + j * CC + l] = uint16_t(interp);
1054 }
1055 } else if constexpr (sizeof(T) == 4) { //float
1056
1057 float xofs_frac = float(src_xofs_frac) / (1 << FRAC_BITS);
1058 float yofs_frac = float(src_yofs_frac) / (1 << FRAC_BITS);
1059 const T *src = ((const T *)p_src);
1060 T *dst = ((T *)p_dst);
1061
1062 float p00 = src[y_ofs_up + src_xofs_left + l];
1063 float p10 = src[y_ofs_up + src_xofs_right + l];
1064 float p01 = src[y_ofs_down + src_xofs_left + l];
1065 float p11 = src[y_ofs_down + src_xofs_right + l];
1066
1067 float interp_up = p00 + (p10 - p00) * xofs_frac;
1068 float interp_down = p01 + (p11 - p01) * xofs_frac;
1069 float interp = interp_up + ((interp_down - interp_up) * yofs_frac);
1070
1071 dst[i * p_dst_width * CC + j * CC + l] = interp;
1072 }
1073 }
1074 }
1075 }
1076 }
1077
1078 template <int CC, typename T>
1079 static void _scale_nearest(const uint8_t *__restrict p_src, uint8_t *__restrict p_dst, uint32_t p_src_width, uint32_t p_src_height, uint32_t p_dst_width, uint32_t p_dst_height) {
1080 for (uint32_t i = 0; i < p_dst_height; i++) {
1081 uint32_t src_yofs = (i + 0.5) * p_src_height / p_dst_height;
1082 uint32_t y_ofs = src_yofs * p_src_width * CC;
1083
1084 for (uint32_t j = 0; j < p_dst_width; j++) {
1085 uint32_t src_xofs = (j + 0.5) * p_src_width / p_dst_width;
1086 src_xofs *= CC;
1087
1088 for (uint32_t l = 0; l < CC; l++) {
1089 const T *src = ((const T *)p_src);
1090 T *dst = ((T *)p_dst);
1091
1092 T p = src[y_ofs + src_xofs + l];
1093 dst[i * p_dst_width * CC + j * CC + l] = p;
1094 }
1095 }
1096 }
1097 }
1098
1099 #define LANCZOS_TYPE 3
1100
1101 static float _lanczos(float p_x) {
1102 return Math::abs(p_x) >= LANCZOS_TYPE ? 0 : Math::sincn(p_x) * Math::sincn(p_x / LANCZOS_TYPE);
1103 }
1104
1105 template <int CC, typename T, ImageScaleType TYPE>
1106 static void _scale_lanczos(const uint8_t *__restrict p_src, uint8_t *__restrict p_dst, uint32_t p_src_width, uint32_t p_src_height, uint32_t p_dst_width, uint32_t p_dst_height) {
1107 int32_t src_width = p_src_width;
1108 int32_t src_height = p_src_height;
1109 int32_t dst_height = p_dst_height;
1110 int32_t dst_width = p_dst_width;
1111
1112 uint32_t buffer_size = src_height * dst_width * CC;
1113 float *buffer = memnew_arr(float, buffer_size); // Store the first pass in a buffer
1114
1115 { // FIRST PASS (horizontal)
1116
1117 float x_scale = float(src_width) / float(dst_width);
1118
1119 float scale_factor = MAX(x_scale, 1); // A larger kernel is required only when downscaling
1120 int32_t half_kernel = LANCZOS_TYPE * scale_factor;
1121
1122 float *kernel = memnew_arr(float, half_kernel * 2);
1123
1124 for (int32_t buffer_x = 0; buffer_x < dst_width; buffer_x++) {
1125 // The corresponding point on the source image
1126 float src_x = (buffer_x + 0.5f) * x_scale; // Offset by 0.5 so it uses the pixel's center
1127 int32_t start_x = MAX(0, int32_t(src_x) - half_kernel + 1);
1128 int32_t end_x = MIN(src_width - 1, int32_t(src_x) + half_kernel);
1129
1130 // Create the kernel used by all the pixels of the column
1131 for (int32_t target_x = start_x; target_x <= end_x; target_x++) {
1132 kernel[target_x - start_x] = _lanczos((target_x + 0.5f - src_x) / scale_factor);
1133 }
1134
1135 for (int32_t buffer_y = 0; buffer_y < src_height; buffer_y++) {
1136 float pixel[CC] = { 0 };
1137 float weight = 0;
1138
1139 for (int32_t target_x = start_x; target_x <= end_x; target_x++) {
1140 float lanczos_val = kernel[target_x - start_x];
1141 weight += lanczos_val;
1142
1143 const T *__restrict src_data = ((const T *)p_src) + (buffer_y * src_width + target_x) * CC;
1144
1145 for (uint32_t i = 0; i < CC; i++) {
1146 if constexpr (sizeof(T) == 2 && TYPE == IMAGE_SCALING_FLOAT) { //half float
1147 pixel[i] += Math::half_to_float(src_data[i]) * lanczos_val;
1148 } else {
1149 pixel[i] += src_data[i] * lanczos_val;
1150 }
1151 }
1152 }
1153
1154 float *dst_data = ((float *)buffer) + (buffer_y * dst_width + buffer_x) * CC;
1155
1156 for (uint32_t i = 0; i < CC; i++) {
1157 dst_data[i] = pixel[i] / weight; // Normalize the sum of all the samples
1158 }
1159 }
1160 }
1161
1162 memdelete_arr(kernel);
1163 } // End of first pass
1164
1165 { // SECOND PASS (vertical + result)
1166
1167 float y_scale = float(src_height) / float(dst_height);
1168
1169 float scale_factor = MAX(y_scale, 1);
1170 int32_t half_kernel = LANCZOS_TYPE * scale_factor;
1171
1172 float *kernel = memnew_arr(float, half_kernel * 2);
1173
1174 for (int32_t dst_y = 0; dst_y < dst_height; dst_y++) {
1175 float buffer_y = (dst_y + 0.5f) * y_scale;
1176 int32_t start_y = MAX(0, int32_t(buffer_y) - half_kernel + 1);
1177 int32_t end_y = MIN(src_height - 1, int32_t(buffer_y) + half_kernel);
1178
1179 for (int32_t target_y = start_y; target_y <= end_y; target_y++) {
1180 kernel[target_y - start_y] = _lanczos((target_y + 0.5f - buffer_y) / scale_factor);
1181 }
1182
1183 for (int32_t dst_x = 0; dst_x < dst_width; dst_x++) {
1184 float pixel[CC] = { 0 };
1185 float weight = 0;
1186
1187 for (int32_t target_y = start_y; target_y <= end_y; target_y++) {
1188 float lanczos_val = kernel[target_y - start_y];
1189 weight += lanczos_val;
1190
1191 float *buffer_data = ((float *)buffer) + (target_y * dst_width + dst_x) * CC;
1192
1193 for (uint32_t i = 0; i < CC; i++) {
1194 pixel[i] += buffer_data[i] * lanczos_val;
1195 }
1196 }
1197
1198 T *dst_data = ((T *)p_dst) + (dst_y * dst_width + dst_x) * CC;
1199
1200 for (uint32_t i = 0; i < CC; i++) {
1201 pixel[i] /= weight;
1202
1203 if constexpr (sizeof(T) == 1) { //byte
1204 dst_data[i] = CLAMP(Math::fast_ftoi(pixel[i]), 0, 255);
1205 } else if constexpr (sizeof(T) == 2) {
1206 if constexpr (TYPE == IMAGE_SCALING_FLOAT) { //half float
1207 dst_data[i] = Math::make_half_float(pixel[i]);
1208 } else { //uint16
1209 dst_data[i] = CLAMP(Math::fast_ftoi(pixel[i]), 0, 65535);
1210 }
1211
1212 } else { // float
1213 dst_data[i] = pixel[i];
1214 }
1215 }
1216 }
1217 }
1218
1219 memdelete_arr(kernel);
1220 } // End of second pass
1221
1222 memdelete_arr(buffer);
1223 }
1224
1225 static void _overlay(const uint8_t *__restrict p_src, uint8_t *__restrict p_dst, float p_alpha, uint32_t p_width, uint32_t p_height, uint32_t p_pixel_size) {
1226 uint16_t alpha = MIN((uint16_t)(p_alpha * 256.0f), 256);
1227
1228 for (uint32_t i = 0; i < p_width * p_height * p_pixel_size; i++) {
1229 p_dst[i] = (p_dst[i] * (256 - alpha) + p_src[i] * alpha) >> 8;
1230 }
1231 }
1232
1233 bool Image::is_size_po2() const {
1234 return is_power_of_2(width) && is_power_of_2(height);
1235 }
1236
1237 void Image::resize_to_po2(bool p_square, Interpolation p_interpolation) {
1238 ERR_FAIL_COND_MSG(is_compressed(), "Cannot resize in compressed image formats.");
1239
1240 int w = next_power_of_2((uint32_t)width);
1241 int h = next_power_of_2((uint32_t)height);
1242 if (p_square) {
1243 w = h = MAX(w, h);
1244 }
1245
1246 if (w == width && h == height) {
1247 if (!p_square || w == h) {
1248 return; //nothing to do
1249 }
1250 }
1251
1252 resize(w, h, p_interpolation);
1253 }
1254
1255 void Image::resize(int p_width, int p_height, Interpolation p_interpolation) {
1256 ERR_FAIL_COND_MSG(data.is_empty(), "Cannot resize image before creating it, use set_data() first.");
1257 ERR_FAIL_COND_MSG(is_compressed(), "Cannot resize in compressed image formats.");
1258
1259 bool mipmap_aware = p_interpolation == INTERPOLATE_TRILINEAR /* || p_interpolation == INTERPOLATE_TRICUBIC */;
1260
1261 ERR_FAIL_COND_MSG(p_width <= 0, "Image width must be greater than 0.");
1262 ERR_FAIL_COND_MSG(p_height <= 0, "Image height must be greater than 0.");
1263 ERR_FAIL_COND_MSG(p_width > MAX_WIDTH, vformat("Image width cannot be greater than %d pixels.", MAX_WIDTH));
1264 ERR_FAIL_COND_MSG(p_height > MAX_HEIGHT, vformat("Image height cannot be greater than %d pixels.", MAX_HEIGHT));
1265 ERR_FAIL_COND_MSG(p_width * p_height > MAX_PIXELS, vformat("Too many pixels for image, maximum is %d pixels.", MAX_PIXELS));
1266
1267 if (p_width == width && p_height == height) {
1268 return;
1269 }
1270
1271 Image dst(p_width, p_height, false, format);
1272
1273 // Setup mipmap-aware scaling
1274 Image dst2;
1275 int mip1 = 0;
1276 int mip2 = 0;
1277 float mip1_weight = 0;
1278 if (mipmap_aware) {
1279 float avg_scale = ((float)p_width / width + (float)p_height / height) * 0.5f;
1280 if (avg_scale >= 1.0f) {
1281 mipmap_aware = false;
1282 } else {
1283 float level = Math::log(1.0f / avg_scale) / Math::log(2.0f);
1284 mip1 = CLAMP((int)Math::floor(level), 0, get_mipmap_count());
1285 mip2 = CLAMP((int)Math::ceil(level), 0, get_mipmap_count());
1286 mip1_weight = 1.0f - (level - mip1);
1287 }
1288 }
1289 bool interpolate_mipmaps = mipmap_aware && mip1 != mip2;
1290 if (interpolate_mipmaps) {
1291 dst2.initialize_data(p_width, p_height, false, format);
1292 }
1293
1294 bool had_mipmaps = mipmaps;
1295 if (interpolate_mipmaps && !had_mipmaps) {
1296 generate_mipmaps();
1297 }
1298 // --
1299
1300 const uint8_t *r = data.ptr();
1301 const unsigned char *r_ptr = r;
1302
1303 uint8_t *w = dst.data.ptrw();
1304 unsigned char *w_ptr = w;
1305
1306 switch (p_interpolation) {
1307 case INTERPOLATE_NEAREST: {
1308 if (format >= FORMAT_L8 && format <= FORMAT_RGBA8) {
1309 switch (get_format_pixel_size(format)) {
1310 case 1:
1311 _scale_nearest<1, uint8_t>(r_ptr, w_ptr, width, height, p_width, p_height);
1312 break;
1313 case 2:
1314 _scale_nearest<2, uint8_t>(r_ptr, w_ptr, width, height, p_width, p_height);
1315 break;
1316 case 3:
1317 _scale_nearest<3, uint8_t>(r_ptr, w_ptr, width, height, p_width, p_height);
1318 break;
1319 case 4:
1320 _scale_nearest<4, uint8_t>(r_ptr, w_ptr, width, height, p_width, p_height);
1321 break;
1322 }
1323 } else if (format >= FORMAT_RF && format <= FORMAT_RGBAF) {
1324 switch (get_format_pixel_size(format)) {
1325 case 4:
1326 _scale_nearest<1, float>(r_ptr, w_ptr, width, height, p_width, p_height);
1327 break;
1328 case 8:
1329 _scale_nearest<2, float>(r_ptr, w_ptr, width, height, p_width, p_height);
1330 break;
1331 case 12:
1332 _scale_nearest<3, float>(r_ptr, w_ptr, width, height, p_width, p_height);
1333 break;
1334 case 16:
1335 _scale_nearest<4, float>(r_ptr, w_ptr, width, height, p_width, p_height);
1336 break;
1337 }
1338
1339 } else if (format >= FORMAT_RH && format <= FORMAT_RGBAH) {
1340 switch (get_format_pixel_size(format)) {
1341 case 2:
1342 _scale_nearest<1, uint16_t>(r_ptr, w_ptr, width, height, p_width, p_height);
1343 break;
1344 case 4:
1345 _scale_nearest<2, uint16_t>(r_ptr, w_ptr, width, height, p_width, p_height);
1346 break;
1347 case 6:
1348 _scale_nearest<3, uint16_t>(r_ptr, w_ptr, width, height, p_width, p_height);
1349 break;
1350 case 8:
1351 _scale_nearest<4, uint16_t>(r_ptr, w_ptr, width, height, p_width, p_height);
1352 break;
1353 }
1354 } else if (format >= FORMAT_R16 && format <= FORMAT_RGBA16I) {
1355 switch (get_format_pixel_size(format)) {
1356 case 2:
1357 _scale_nearest<1, uint16_t>(r_ptr, w_ptr, width, height, p_width, p_height);
1358 break;
1359 case 4:
1360 _scale_nearest<2, uint16_t>(r_ptr, w_ptr, width, height, p_width, p_height);
1361 break;
1362 case 6:
1363 _scale_nearest<3, uint16_t>(r_ptr, w_ptr, width, height, p_width, p_height);
1364 break;
1365 case 8:
1366 _scale_nearest<4, uint16_t>(r_ptr, w_ptr, width, height, p_width, p_height);
1367 break;
1368 }
1369 }
1370
1371 } break;
1372 case INTERPOLATE_BILINEAR:
1373 case INTERPOLATE_TRILINEAR: {
1374 for (int i = 0; i < 2; ++i) {
1375 int src_width;
1376 int src_height;
1377 const unsigned char *src_ptr;
1378
1379 if (!mipmap_aware) {
1380 if (i == 0) {
1381 // Standard behavior
1382 src_width = width;
1383 src_height = height;
1384 src_ptr = r_ptr;
1385 } else {
1386 // No need for a second iteration
1387 break;
1388 }
1389 } else {
1390 if (i == 0) {
1391 // Read from the first mipmap that will be interpolated
1392 // (if both levels are the same, we will not interpolate, but at least we'll sample from the right level)
1393 int64_t offs;
1394 _get_mipmap_offset_and_size(mip1, offs, src_width, src_height);
1395 src_ptr = r_ptr + offs;
1396 } else if (!interpolate_mipmaps) {
1397 // No need generate a second image
1398 break;
1399 } else {
1400 // Switch to read from the second mipmap that will be interpolated
1401 int64_t offs;
1402 _get_mipmap_offset_and_size(mip2, offs, src_width, src_height);
1403 src_ptr = r_ptr + offs;
1404 // Switch to write to the second destination image
1405 w = dst2.data.ptrw();
1406 w_ptr = w;
1407 }
1408 }
1409
1410 if (format >= FORMAT_L8 && format <= FORMAT_RGBA8) {
1411 switch (get_format_pixel_size(format)) {
1412 case 1:
1413 _scale_bilinear<1, uint8_t, IMAGE_SCALING_INT>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
1414 break;
1415 case 2:
1416 _scale_bilinear<2, uint8_t, IMAGE_SCALING_INT>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
1417 break;
1418 case 3:
1419 _scale_bilinear<3, uint8_t, IMAGE_SCALING_INT>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
1420 break;
1421 case 4:
1422 _scale_bilinear<4, uint8_t, IMAGE_SCALING_INT>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
1423 break;
1424 }
1425 } else if (format >= FORMAT_RF && format <= FORMAT_RGBAF) {
1426 switch (get_format_pixel_size(format)) {
1427 case 4:
1428 _scale_bilinear<1, float, IMAGE_SCALING_FLOAT>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
1429 break;
1430 case 8:
1431 _scale_bilinear<2, float, IMAGE_SCALING_FLOAT>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
1432 break;
1433 case 12:
1434 _scale_bilinear<3, float, IMAGE_SCALING_FLOAT>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
1435 break;
1436 case 16:
1437 _scale_bilinear<4, float, IMAGE_SCALING_FLOAT>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
1438 break;
1439 }
1440 } else if (format >= FORMAT_RH && format <= FORMAT_RGBAH) {
1441 switch (get_format_pixel_size(format)) {
1442 case 2:
1443 _scale_bilinear<1, uint16_t, IMAGE_SCALING_FLOAT>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
1444 break;
1445 case 4:
1446 _scale_bilinear<2, uint16_t, IMAGE_SCALING_FLOAT>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
1447 break;
1448 case 6:
1449 _scale_bilinear<3, uint16_t, IMAGE_SCALING_FLOAT>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
1450 break;
1451 case 8:
1452 _scale_bilinear<4, uint16_t, IMAGE_SCALING_FLOAT>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
1453 break;
1454 }
1455 } else if (format >= FORMAT_R16 && format <= FORMAT_RGBA16I) {
1456 switch (get_format_pixel_size(format)) {
1457 case 2:
1458 _scale_bilinear<1, uint16_t, IMAGE_SCALING_INT>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
1459 break;
1460 case 4:
1461 _scale_bilinear<2, uint16_t, IMAGE_SCALING_INT>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
1462 break;
1463 case 6:
1464 _scale_bilinear<3, uint16_t, IMAGE_SCALING_INT>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
1465 break;
1466 case 8:
1467 _scale_bilinear<4, uint16_t, IMAGE_SCALING_INT>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
1468 break;
1469 }
1470 }
1471 }
1472
1473 if (interpolate_mipmaps) {
1474 // Switch to read again from the first scaled mipmap to overlay it over the second
1475 r = dst.data.ptr();
1476 _overlay(r, w, mip1_weight, p_width, p_height, get_format_pixel_size(format));
1477 }
1478
1479 } break;
1480 case INTERPOLATE_CUBIC: {
1481 if (format >= FORMAT_L8 && format <= FORMAT_RGBA8) {
1482 switch (get_format_pixel_size(format)) {
1483 case 1:
1484 _scale_cubic<1, uint8_t, IMAGE_SCALING_INT>(r_ptr, w_ptr, width, height, p_width, p_height);
1485 break;
1486 case 2:
1487 _scale_cubic<2, uint8_t, IMAGE_SCALING_INT>(r_ptr, w_ptr, width, height, p_width, p_height);
1488 break;
1489 case 3:
1490 _scale_cubic<3, uint8_t, IMAGE_SCALING_INT>(r_ptr, w_ptr, width, height, p_width, p_height);
1491 break;
1492 case 4:
1493 _scale_cubic<4, uint8_t, IMAGE_SCALING_INT>(r_ptr, w_ptr, width, height, p_width, p_height);
1494 break;
1495 }
1496 } else if (format >= FORMAT_RF && format <= FORMAT_RGBAF) {
1497 switch (get_format_pixel_size(format)) {
1498 case 4:
1499 _scale_cubic<1, float, IMAGE_SCALING_FLOAT>(r_ptr, w_ptr, width, height, p_width, p_height);
1500 break;
1501 case 8:
1502 _scale_cubic<2, float, IMAGE_SCALING_FLOAT>(r_ptr, w_ptr, width, height, p_width, p_height);
1503 break;
1504 case 12:
1505 _scale_cubic<3, float, IMAGE_SCALING_FLOAT>(r_ptr, w_ptr, width, height, p_width, p_height);
1506 break;
1507 case 16:
1508 _scale_cubic<4, float, IMAGE_SCALING_FLOAT>(r_ptr, w_ptr, width, height, p_width, p_height);
1509 break;
1510 }
1511 } else if (format >= FORMAT_RH && format <= FORMAT_RGBAH) {
1512 switch (get_format_pixel_size(format)) {
1513 case 2:
1514 _scale_cubic<1, uint16_t, IMAGE_SCALING_FLOAT>(r_ptr, w_ptr, width, height, p_width, p_height);
1515 break;
1516 case 4:
1517 _scale_cubic<2, uint16_t, IMAGE_SCALING_FLOAT>(r_ptr, w_ptr, width, height, p_width, p_height);
1518 break;
1519 case 6:
1520 _scale_cubic<3, uint16_t, IMAGE_SCALING_FLOAT>(r_ptr, w_ptr, width, height, p_width, p_height);
1521 break;
1522 case 8:
1523 _scale_cubic<4, uint16_t, IMAGE_SCALING_FLOAT>(r_ptr, w_ptr, width, height, p_width, p_height);
1524 break;
1525 }
1526 } else if (format >= FORMAT_R16 && format <= FORMAT_RGBA16I) {
1527 switch (get_format_pixel_size(format)) {
1528 case 2:
1529 _scale_cubic<1, uint16_t, IMAGE_SCALING_INT>(r_ptr, w_ptr, width, height, p_width, p_height);
1530 break;
1531 case 4:
1532 _scale_cubic<2, uint16_t, IMAGE_SCALING_INT>(r_ptr, w_ptr, width, height, p_width, p_height);
1533 break;
1534 case 6:
1535 _scale_cubic<3, uint16_t, IMAGE_SCALING_INT>(r_ptr, w_ptr, width, height, p_width, p_height);
1536 break;
1537 case 8:
1538 _scale_cubic<4, uint16_t, IMAGE_SCALING_INT>(r_ptr, w_ptr, width, height, p_width, p_height);
1539 break;
1540 }
1541 }
1542 } break;
1543 case INTERPOLATE_LANCZOS: {
1544 if (format >= FORMAT_L8 && format <= FORMAT_RGBA8) {
1545 switch (get_format_pixel_size(format)) {
1546 case 1:
1547 _scale_lanczos<1, uint8_t, IMAGE_SCALING_INT>(r_ptr, w_ptr, width, height, p_width, p_height);
1548 break;
1549 case 2:
1550 _scale_lanczos<2, uint8_t, IMAGE_SCALING_INT>(r_ptr, w_ptr, width, height, p_width, p_height);
1551 break;
1552 case 3:
1553 _scale_lanczos<3, uint8_t, IMAGE_SCALING_INT>(r_ptr, w_ptr, width, height, p_width, p_height);
1554 break;
1555 case 4:
1556 _scale_lanczos<4, uint8_t, IMAGE_SCALING_INT>(r_ptr, w_ptr, width, height, p_width, p_height);
1557 break;
1558 }
1559 } else if (format >= FORMAT_RF && format <= FORMAT_RGBAF) {
1560 switch (get_format_pixel_size(format)) {
1561 case 4:
1562 _scale_lanczos<1, float, IMAGE_SCALING_FLOAT>(r_ptr, w_ptr, width, height, p_width, p_height);
1563 break;
1564 case 8:
1565 _scale_lanczos<2, float, IMAGE_SCALING_FLOAT>(r_ptr, w_ptr, width, height, p_width, p_height);
1566 break;
1567 case 12:
1568 _scale_lanczos<3, float, IMAGE_SCALING_FLOAT>(r_ptr, w_ptr, width, height, p_width, p_height);
1569 break;
1570 case 16:
1571 _scale_lanczos<4, float, IMAGE_SCALING_FLOAT>(r_ptr, w_ptr, width, height, p_width, p_height);
1572 break;
1573 }
1574 } else if (format >= FORMAT_RH && format <= FORMAT_RGBAH) {
1575 switch (get_format_pixel_size(format)) {
1576 case 2:
1577 _scale_lanczos<1, uint16_t, IMAGE_SCALING_FLOAT>(r_ptr, w_ptr, width, height, p_width, p_height);
1578 break;
1579 case 4:
1580 _scale_lanczos<2, uint16_t, IMAGE_SCALING_FLOAT>(r_ptr, w_ptr, width, height, p_width, p_height);
1581 break;
1582 case 6:
1583 _scale_lanczos<3, uint16_t, IMAGE_SCALING_FLOAT>(r_ptr, w_ptr, width, height, p_width, p_height);
1584 break;
1585 case 8:
1586 _scale_lanczos<4, uint16_t, IMAGE_SCALING_FLOAT>(r_ptr, w_ptr, width, height, p_width, p_height);
1587 break;
1588 }
1589 } else if (format >= FORMAT_R16 && format <= FORMAT_RGBA16I) {
1590 switch (get_format_pixel_size(format)) {
1591 case 2:
1592 _scale_lanczos<1, uint16_t, IMAGE_SCALING_INT>(r_ptr, w_ptr, width, height, p_width, p_height);
1593 break;
1594 case 4:
1595 _scale_lanczos<2, uint16_t, IMAGE_SCALING_INT>(r_ptr, w_ptr, width, height, p_width, p_height);
1596 break;
1597 case 6:
1598 _scale_lanczos<3, uint16_t, IMAGE_SCALING_INT>(r_ptr, w_ptr, width, height, p_width, p_height);
1599 break;
1600 case 8:
1601 _scale_lanczos<4, uint16_t, IMAGE_SCALING_INT>(r_ptr, w_ptr, width, height, p_width, p_height);
1602 break;
1603 }
1604 }
1605 } break;
1606 }
1607
1608 if (interpolate_mipmaps) {
1609 dst._copy_internals_from(dst2);
1610 }
1611
1612 if (had_mipmaps) {
1613 dst.generate_mipmaps();
1614 }
1615
1616 _copy_internals_from(dst);
1617 }
1618
1619 void Image::crop_from_point(int p_x, int p_y, int p_width, int p_height) {
1620 ERR_FAIL_COND_MSG(is_compressed(), "Cannot crop in compressed image formats.");
1621 ERR_FAIL_COND_MSG(p_x < 0, "Start x position cannot be smaller than 0.");
1622 ERR_FAIL_COND_MSG(p_y < 0, "Start y position cannot be smaller than 0.");
1623 ERR_FAIL_COND_MSG(p_width <= 0, "Width of image must be greater than 0.");
1624 ERR_FAIL_COND_MSG(p_height <= 0, "Height of image must be greater than 0.");
1625 ERR_FAIL_COND_MSG(p_x + p_width > MAX_WIDTH, vformat("End x position cannot be greater than %d.", MAX_WIDTH));
1626 ERR_FAIL_COND_MSG(p_y + p_height > MAX_HEIGHT, vformat("End y position cannot be greater than %d.", MAX_HEIGHT));
1627
1628 /* to save memory, cropping should be done in-place, however, since this function
1629 will most likely either not be used much, or in critical areas, for now it won't, because
1630 it's a waste of time. */
1631
1632 if (p_width == width && p_height == height && p_x == 0 && p_y == 0) {
1633 return;
1634 }
1635
1636 uint8_t pdata[16]; //largest is 16
1637 uint32_t pixel_size = get_format_pixel_size(format);
1638
1639 Image dst(p_width, p_height, false, format);
1640
1641 {
1642 const uint8_t *r = data.ptr();
1643 uint8_t *w = dst.data.ptrw();
1644
1645 int m_h = p_y + p_height;
1646 int m_w = p_x + p_width;
1647 for (int y = p_y; y < m_h; y++) {
1648 for (int x = p_x; x < m_w; x++) {
1649 if ((x >= width || y >= height)) {
1650 for (uint32_t i = 0; i < pixel_size; i++) {
1651 pdata[i] = 0;
1652 }
1653 } else {
1654 _get_pixelb(x, y, pixel_size, r, pdata);
1655 }
1656
1657 dst._put_pixelb(x - p_x, y - p_y, pixel_size, w, pdata);
1658 }
1659 }
1660 }
1661
1662 if (has_mipmaps()) {
1663 dst.generate_mipmaps();
1664 }
1665 _copy_internals_from(dst);
1666 }
1667
1668 void Image::crop(int p_width, int p_height) {
1669 crop_from_point(0, 0, p_width, p_height);
1670 }
1671
1672 void Image::rotate_90(ClockDirection p_direction) {
1673 ERR_FAIL_COND_MSG(is_compressed(), "Cannot rotate in compressed image formats.");
1674 ERR_FAIL_COND_MSG(width <= 0, vformat("The Image width specified (%d pixels) must be greater than 0 pixels.", width));
1675 ERR_FAIL_COND_MSG(height <= 0, vformat("The Image height specified (%d pixels) must be greater than 0 pixels.", height));
1676
1677 bool used_mipmaps = has_mipmaps();
1678 if (used_mipmaps) {
1679 clear_mipmaps();
1680 }
1681
1682 // In-place 90 degrees rotation by following the permutation cycles.
1683 {
1684 // Explanation by example (clockwise):
1685 //
1686 // abc da
1687 // def -> eb
1688 // fc
1689 //
1690 // In memory:
1691 // 012345 012345
1692 // abcdef -> daebfc
1693 //
1694 // Permutation cycles:
1695 // (0 --a--> 1 --b--> 3 --d--> 0)
1696 // (2 --c--> 5 --f--> 4 --e--> 2)
1697 //
1698 // Applying cycles (backwards):
1699 // 0->s s=a (store)
1700 // 3->0 abcdef -> dbcdef
1701 // 1->3 dbcdef -> dbcbef
1702 // s->1 dbcbef -> dacbef
1703 //
1704 // 2->s s=c
1705 // 4->2 dacbef -> daebef
1706 // 5->4 daebef -> daebff
1707 // s->5 daebff -> daebfc
1708
1709 const int w = width;
1710 const int h = height;
1711 const int size = w * h;
1712
1713 uint8_t *data_ptr = data.ptrw();
1714 uint32_t pixel_size = get_format_pixel_size(format);
1715
1716 uint8_t single_pixel_buffer[16];
1717
1718 #define PREV_INDEX_IN_CYCLE(index) (p_direction == CLOCKWISE) ? ((h - 1 - (index % h)) * w + (index / h)) : ((index % h) * w + (w - 1 - (index / h)))
1719
1720 if (w == h) { // Square case, 4-length cycles only (plus irrelevant thus skipped 1-length cycle in the middle for odd-sized squares).
1721 for (int y = 0; y < h / 2; y++) {
1722 for (int x = 0; x < (w + 1) / 2; x++) {
1723 int current = y * w + x;
1724 memcpy(single_pixel_buffer, data_ptr + current * pixel_size, pixel_size);
1725 for (int i = 0; i < 3; i++) {
1726 int prev = PREV_INDEX_IN_CYCLE(current);
1727 memcpy(data_ptr + current * pixel_size, data_ptr + prev * pixel_size, pixel_size);
1728 current = prev;
1729 }
1730 memcpy(data_ptr + current * pixel_size, single_pixel_buffer, pixel_size);
1731 }
1732 }
1733 } else { // Rectangular case (w != h), kinda unpredictable cycles.
1734 int permuted_pixels_count = 0;
1735
1736 for (int i = 0; i < size; i++) {
1737 int prev = PREV_INDEX_IN_CYCLE(i);
1738 if (prev == i) {
1739 // 1-length cycle, pixel remains at the same index.
1740 permuted_pixels_count++;
1741 continue;
1742 }
1743
1744 // Check whether we already processed this cycle.
1745 // We iterate over it and if we'll find an index smaller than `i` then we already
1746 // processed this cycle because we always start at the smallest index in the cycle.
1747 // TODO: Improve this naive approach, can be done better.
1748 while (prev > i) {
1749 prev = PREV_INDEX_IN_CYCLE(prev);
1750 }
1751 if (prev < i) {
1752 continue;
1753 }
1754
1755 // Save the in-cycle pixel with the smallest index (`i`).
1756 memcpy(single_pixel_buffer, data_ptr + i * pixel_size, pixel_size);
1757
1758 // Overwrite pixels one by one by the preceding pixel in the cycle.
1759 int current = i;
1760 prev = PREV_INDEX_IN_CYCLE(current);
1761 while (prev != i) {
1762 memcpy(data_ptr + current * pixel_size, data_ptr + prev * pixel_size, pixel_size);
1763 permuted_pixels_count++;
1764
1765 current = prev;
1766 prev = PREV_INDEX_IN_CYCLE(current);
1767 };
1768
1769 // Overwrite the remaining pixel in the cycle by the saved pixel with the smallest index.
1770 memcpy(data_ptr + current * pixel_size, single_pixel_buffer, pixel_size);
1771 permuted_pixels_count++;
1772
1773 if (permuted_pixels_count == size) {
1774 break;
1775 }
1776 }
1777
1778 width = h;
1779 height = w;
1780 }
1781
1782 #undef PREV_INDEX_IN_CYCLE
1783 }
1784
1785 if (used_mipmaps) {
1786 generate_mipmaps();
1787 }
1788 }
1789
1790 void Image::rotate_180() {
1791 ERR_FAIL_COND_MSG(is_compressed(), "Cannot rotate in compressed image formats.");
1792 ERR_FAIL_COND_MSG(width <= 0, vformat("The Image width specified (%d pixels) must be greater than 0 pixels.", width));
1793 ERR_FAIL_COND_MSG(height <= 0, vformat("The Image height specified (%d pixels) must be greater than 0 pixels.", height));
1794
1795 bool used_mipmaps = has_mipmaps();
1796 if (used_mipmaps) {
1797 clear_mipmaps();
1798 }
1799
1800 {
1801 uint8_t *data_ptr = data.ptrw();
1802 uint32_t pixel_size = get_format_pixel_size(format);
1803
1804 uint8_t single_pixel_buffer[16];
1805
1806 uint8_t *from_begin_ptr = data_ptr;
1807 uint8_t *from_end_ptr = data_ptr + (width * height - 1) * pixel_size;
1808
1809 while (from_begin_ptr < from_end_ptr) {
1810 memcpy(single_pixel_buffer, from_begin_ptr, pixel_size);
1811 memcpy(from_begin_ptr, from_end_ptr, pixel_size);
1812 memcpy(from_end_ptr, single_pixel_buffer, pixel_size);
1813
1814 from_begin_ptr += pixel_size;
1815 from_end_ptr -= pixel_size;
1816 }
1817 }
1818
1819 if (used_mipmaps) {
1820 generate_mipmaps();
1821 }
1822 }
1823
1824 void Image::flip_y() {
1825 ERR_FAIL_COND_MSG(is_compressed(), "Cannot flip_y in compressed image formats.");
1826
1827 bool used_mipmaps = has_mipmaps();
1828 if (used_mipmaps) {
1829 clear_mipmaps();
1830 }
1831
1832 {
1833 uint8_t *w = data.ptrw();
1834 uint8_t up[16];
1835 uint8_t down[16];
1836 uint32_t pixel_size = get_format_pixel_size(format);
1837
1838 for (int y = 0; y < height / 2; y++) {
1839 for (int x = 0; x < width; x++) {
1840 _get_pixelb(x, y, pixel_size, w, up);
1841 _get_pixelb(x, height - y - 1, pixel_size, w, down);
1842
1843 _put_pixelb(x, height - y - 1, pixel_size, w, up);
1844 _put_pixelb(x, y, pixel_size, w, down);
1845 }
1846 }
1847 }
1848
1849 if (used_mipmaps) {
1850 generate_mipmaps();
1851 }
1852 }
1853
1854 void Image::flip_x() {
1855 ERR_FAIL_COND_MSG(is_compressed(), "Cannot flip_x in compressed image formats.");
1856
1857 bool used_mipmaps = has_mipmaps();
1858 if (used_mipmaps) {
1859 clear_mipmaps();
1860 }
1861
1862 {
1863 uint8_t *w = data.ptrw();
1864 uint8_t up[16];
1865 uint8_t down[16];
1866 uint32_t pixel_size = get_format_pixel_size(format);
1867
1868 for (int y = 0; y < height; y++) {
1869 for (int x = 0; x < width / 2; x++) {
1870 _get_pixelb(x, y, pixel_size, w, up);
1871 _get_pixelb(width - x - 1, y, pixel_size, w, down);
1872
1873 _put_pixelb(width - x - 1, y, pixel_size, w, up);
1874 _put_pixelb(x, y, pixel_size, w, down);
1875 }
1876 }
1877 }
1878
1879 if (used_mipmaps) {
1880 generate_mipmaps();
1881 }
1882 }
1883
1884 // Get mipmap size and offset.
1885 int64_t Image::_get_dst_image_size(int p_width, int p_height, Format p_format, int &r_mipmaps, int p_mipmaps, int *r_mm_width, int *r_mm_height) {
1886 // Data offset in mipmaps (including the original texture).
1887 int64_t size = 0;
1888
1889 int w = p_width;
1890 int h = p_height;
1891
1892 // Current mipmap index in the loop below. p_mipmaps is the target mipmap index.
1893 // In this function, mipmap 0 represents the first mipmap instead of the original texture.
1894 int mm = 0;
1895
1896 int pixsize = get_format_pixel_size(p_format);
1897 int pixshift = get_format_pixel_rshift(p_format);
1898 int block = get_format_block_size(p_format);
1899
1900 // Technically, you can still compress up to 1 px no matter the format, so commenting this.
1901 //int minw, minh;
1902 //get_format_min_pixel_size(p_format, minw, minh);
1903 int minw = 1, minh = 1;
1904
1905 while (true) {
1906 int bw = w % block != 0 ? w + (block - w % block) : w;
1907 int bh = h % block != 0 ? h + (block - h % block) : h;
1908
1909 int64_t s = bw * bh;
1910
1911 s *= pixsize;
1912 s >>= pixshift;
1913
1914 size += s;
1915
1916 if (p_mipmaps >= 0) {
1917 w = MAX(minw, w >> 1);
1918 h = MAX(minh, h >> 1);
1919 } else {
1920 if (w == minw && h == minh) {
1921 break;
1922 }
1923 w = MAX(minw, w >> 1);
1924 h = MAX(minh, h >> 1);
1925 }
1926
1927 // Set mipmap size.
1928 if (r_mm_width) {
1929 *r_mm_width = w;
1930 }
1931 if (r_mm_height) {
1932 *r_mm_height = h;
1933 }
1934
1935 // Reach target mipmap.
1936 if (p_mipmaps >= 0 && mm == p_mipmaps) {
1937 break;
1938 }
1939
1940 mm++;
1941 }
1942
1943 r_mipmaps = mm;
1944 return size;
1945 }
1946
1947 template <typename Component, int CC, bool renormalize,
1948 void (*average_func)(Component &, const Component &, const Component &, const Component &, const Component &),
1949 void (*renormalize_func)(Component *)>
1950 static void _generate_po2_mipmap(const Component *p_src, Component *p_dst, uint32_t p_width, uint32_t p_height) {
1951 // Fast power of 2 mipmap generation.
1952 uint32_t dst_w = MAX(p_width >> 1, 1u);
1953 uint32_t dst_h = MAX(p_height >> 1, 1u);
1954
1955 int right_step = (p_width == 1) ? 0 : CC;
1956 int down_step = (p_height == 1) ? 0 : (p_width * CC);
1957
1958 for (uint32_t i = 0; i < dst_h; i++) {
1959 const Component *rup_ptr = &p_src[i * 2 * down_step];
1960 const Component *rdown_ptr = rup_ptr + down_step;
1961 Component *dst_ptr = &p_dst[i * dst_w * CC];
1962 uint32_t count = dst_w;
1963
1964 while (count) {
1965 count--;
1966 for (int j = 0; j < CC; j++) {
1967 average_func(dst_ptr[j], rup_ptr[j], rup_ptr[j + right_step], rdown_ptr[j], rdown_ptr[j + right_step]);
1968 }
1969
1970 if constexpr (renormalize) {
1971 renormalize_func(dst_ptr);
1972 }
1973
1974 dst_ptr += CC;
1975 rup_ptr += right_step * 2;
1976 rdown_ptr += right_step * 2;
1977 }
1978 }
1979 }
1980
1981 void Image::_generate_mipmap_from_format(Image::Format p_format, const uint8_t *p_src, uint8_t *p_dst, uint32_t p_width, uint32_t p_height, bool p_renormalize) {
1982 const float *src_float = reinterpret_cast<const float *>(p_src);
1983 float *dst_float = reinterpret_cast<float *>(p_dst);
1984
1985 const uint16_t *src_u16 = reinterpret_cast<const uint16_t *>(p_src);
1986 uint16_t *dst_u16 = reinterpret_cast<uint16_t *>(p_dst);
1987
1988 const uint32_t *src_u32 = reinterpret_cast<const uint32_t *>(p_src);
1989 uint32_t *dst_u32 = reinterpret_cast<uint32_t *>(p_dst);
1990
1991 switch (p_format) {
1992 case Image::FORMAT_L8:
1993 case Image::FORMAT_R8:
1994 _generate_po2_mipmap<uint8_t, 1, false, Image::average_4_uint8, Image::renormalize_uint8>(p_src, p_dst, p_width, p_height);
1995 break;
1996 case Image::FORMAT_LA8:
1997 _generate_po2_mipmap<uint8_t, 2, false, Image::average_4_uint8, Image::renormalize_uint8>(p_src, p_dst, p_width, p_height);
1998 break;
1999 case Image::FORMAT_RG8:
2000 _generate_po2_mipmap<uint8_t, 2, false, Image::average_4_uint8, Image::renormalize_uint8>(p_src, p_dst, p_width, p_height);
2001 break;
2002 case Image::FORMAT_RGB8: {
2003 if (p_renormalize) {
2004 _generate_po2_mipmap<uint8_t, 3, true, Image::average_4_uint8, Image::renormalize_uint8>(p_src, p_dst, p_width, p_height);
2005 } else {
2006 _generate_po2_mipmap<uint8_t, 3, false, Image::average_4_uint8, Image::renormalize_uint8>(p_src, p_dst, p_width, p_height);
2007 }
2008 } break;
2009 case Image::FORMAT_RGBA8: {
2010 if (p_renormalize) {
2011 _generate_po2_mipmap<uint8_t, 4, true, Image::average_4_uint8, Image::renormalize_uint8>(p_src, p_dst, p_width, p_height);
2012 } else {
2013 _generate_po2_mipmap<uint8_t, 4, false, Image::average_4_uint8, Image::renormalize_uint8>(p_src, p_dst, p_width, p_height);
2014 }
2015 } break;
2016 case Image::FORMAT_RGBA4444: {
2017 _generate_po2_mipmap<uint16_t, 1, false, Image::average_4_rgba4444, nullptr>(src_u16, dst_u16, p_width, p_height);
2018 } break;
2019 case Image::FORMAT_RGB565: {
2020 _generate_po2_mipmap<uint16_t, 1, false, Image::average_4_rgb565, nullptr>(src_u16, dst_u16, p_width, p_height);
2021 } break;
2022 case Image::FORMAT_RF:
2023 _generate_po2_mipmap<float, 1, false, Image::average_4_float, Image::renormalize_float>(src_float, dst_float, p_width, p_height);
2024 break;
2025 case Image::FORMAT_RGF:
2026 _generate_po2_mipmap<float, 2, false, Image::average_4_float, Image::renormalize_float>(src_float, dst_float, p_width, p_height);
2027 break;
2028 case Image::FORMAT_RGBF: {
2029 if (p_renormalize) {
2030 _generate_po2_mipmap<float, 3, true, Image::average_4_float, Image::renormalize_float>(src_float, dst_float, p_width, p_height);
2031 } else {
2032 _generate_po2_mipmap<float, 3, false, Image::average_4_float, Image::renormalize_float>(src_float, dst_float, p_width, p_height);
2033 }
2034 } break;
2035 case Image::FORMAT_RGBAF: {
2036 if (p_renormalize) {
2037 _generate_po2_mipmap<float, 4, true, Image::average_4_float, Image::renormalize_float>(src_float, dst_float, p_width, p_height);
2038 } else {
2039 _generate_po2_mipmap<float, 4, false, Image::average_4_float, Image::renormalize_float>(src_float, dst_float, p_width, p_height);
2040 }
2041 } break;
2042 case Image::FORMAT_RH:
2043 _generate_po2_mipmap<uint16_t, 1, false, Image::average_4_half, Image::renormalize_half>(src_u16, dst_u16, p_width, p_height);
2044 break;
2045 case Image::FORMAT_RGH:
2046 _generate_po2_mipmap<uint16_t, 2, false, Image::average_4_half, Image::renormalize_half>(src_u16, dst_u16, p_width, p_height);
2047 break;
2048 case Image::FORMAT_RGBH: {
2049 if (p_renormalize) {
2050 _generate_po2_mipmap<uint16_t, 3, true, Image::average_4_half, Image::renormalize_half>(src_u16, dst_u16, p_width, p_height);
2051 } else {
2052 _generate_po2_mipmap<uint16_t, 3, false, Image::average_4_half, Image::renormalize_half>(src_u16, dst_u16, p_width, p_height);
2053 }
2054 } break;
2055 case Image::FORMAT_RGBAH: {
2056 if (p_renormalize) {
2057 _generate_po2_mipmap<uint16_t, 4, true, Image::average_4_half, Image::renormalize_half>(src_u16, dst_u16, p_width, p_height);
2058 } else {
2059 _generate_po2_mipmap<uint16_t, 4, false, Image::average_4_half, Image::renormalize_half>(src_u16, dst_u16, p_width, p_height);
2060 }
2061 } break;
2062 case Image::FORMAT_RGBE9995:
2063 _generate_po2_mipmap<uint32_t, 1, false, Image::average_4_rgbe9995, nullptr>(src_u32, dst_u32, p_width, p_height);
2064 break;
2065 case Image::FORMAT_R16:
2066 case Image::FORMAT_R16I:
2067 _generate_po2_mipmap<uint16_t, 1, false, Image::average_4_uint16, Image::renormalize_uint16>(src_u16, dst_u16, p_width, p_height);
2068 break;
2069 case Image::FORMAT_RG16:
2070 case Image::FORMAT_RG16I:
2071 _generate_po2_mipmap<uint16_t, 2, false, Image::average_4_uint16, Image::renormalize_uint16>(src_u16, dst_u16, p_width, p_height);
2072 break;
2073 case Image::FORMAT_RGB16:
2074 case Image::FORMAT_RGB16I: {
2075 if (p_renormalize) {
2076 _generate_po2_mipmap<uint16_t, 3, true, Image::average_4_uint16, Image::renormalize_uint16>(src_u16, dst_u16, p_width, p_height);
2077 } else {
2078 _generate_po2_mipmap<uint16_t, 3, false, Image::average_4_uint16, Image::renormalize_uint16>(src_u16, dst_u16, p_width, p_height);
2079 }
2080 } break;
2081 case Image::FORMAT_RGBA16:
2082 case Image::FORMAT_RGBA16I: {
2083 if (p_renormalize) {
2084 _generate_po2_mipmap<uint16_t, 4, true, Image::average_4_uint16, Image::renormalize_uint16>(src_u16, dst_u16, p_width, p_height);
2085 } else {
2086 _generate_po2_mipmap<uint16_t, 4, false, Image::average_4_uint16, Image::renormalize_uint16>(src_u16, dst_u16, p_width, p_height);
2087 }
2088 } break;
2089
2090 default:
2091 return;
2092 }
2093 }
2094
2095 void Image::shrink_x2() {
2096 ERR_FAIL_COND(data.is_empty());
2097 Vector<uint8_t> new_data;
2098
2099 if (mipmaps) {
2100 // Just use the lower mipmap as base and copy all.
2101 int64_t ofs = get_mipmap_offset(1);
2102 int64_t new_size = data.size() - ofs;
2103
2104 new_data.resize(new_size);
2105 ERR_FAIL_COND(new_data.is_empty());
2106
2107 memcpy(new_data.ptrw(), data.ptr() + ofs, new_size);
2108 } else {
2109 // Generate a mipmap and replace the original.
2110 ERR_FAIL_COND(is_compressed());
2111
2112 new_data.resize((width / 2) * (height / 2) * get_format_pixel_size(format));
2113 ERR_FAIL_COND(data.is_empty() || new_data.is_empty());
2114
2115 _generate_mipmap_from_format(format, data.ptr(), new_data.ptrw(), width, height, false);
2116 }
2117
2118 width = MAX(width / 2, 1);
2119 height = MAX(height / 2, 1);
2120 data = new_data;
2121 }
2122
2123 void Image::normalize() {
2124 bool used_mipmaps = has_mipmaps();
2125 if (used_mipmaps) {
2126 clear_mipmaps();
2127 }
2128
2129 for (int y = 0; y < height; y++) {
2130 for (int x = 0; x < width; x++) {
2131 Color c = get_pixel(x, y);
2132 Vector3 v(c.r * 2.0 - 1.0, c.g * 2.0 - 1.0, c.b * 2.0 - 1.0);
2133 v.normalize();
2134 c.r = v.x * 0.5 + 0.5;
2135 c.g = v.y * 0.5 + 0.5;
2136 c.b = v.z * 0.5 + 0.5;
2137 set_pixel(x, y, c);
2138 }
2139 }
2140
2141 if (used_mipmaps) {
2142 generate_mipmaps(true);
2143 }
2144 }
2145
2146 Error Image::generate_mipmaps(bool p_renormalize) {
2147 ERR_FAIL_COND_V_MSG(is_compressed(), ERR_UNAVAILABLE, "Cannot generate mipmaps from compressed image formats.");
2148 ERR_FAIL_COND_V_MSG(width == 0 || height == 0, ERR_UNCONFIGURED, "Cannot generate mipmaps with width or height equal to 0.");
2149
2150 int gen_mipmap_count;
2151
2152 int64_t size = _get_dst_image_size(width, height, format, gen_mipmap_count);
2153 data.resize(size);
2154 uint8_t *wp = data.ptrw();
2155
2156 int prev_ofs = 0;
2157 int prev_h = height;
2158 int prev_w = width;
2159
2160 for (int i = 1; i <= gen_mipmap_count; i++) {
2161 int64_t ofs;
2162 int w, h;
2163 _get_mipmap_offset_and_size(i, ofs, w, h);
2164
2165 _generate_mipmap_from_format(format, wp + prev_ofs, wp + ofs, prev_w, prev_h, p_renormalize);
2166
2167 prev_ofs = ofs;
2168 prev_w = w;
2169 prev_h = h;
2170 }
2171
2172 mipmaps = true;
2173
2174 return OK;
2175 }
2176
2177 Error Image::generate_mipmap_roughness(RoughnessChannel p_roughness_channel, const Ref<Image> &p_normal_map) {
2178 LocalVector<double> normal_sat_vec; //summed area table
2179 int normal_w = 0, normal_h = 0;
2180
2181 ERR_FAIL_COND_V_MSG(p_normal_map.is_null() || p_normal_map->is_empty(), ERR_INVALID_PARAMETER, "Must provide a valid normal map for roughness mipmaps");
2182
2183 Ref<Image> nm = p_normal_map->duplicate();
2184 if (nm->is_compressed()) {
2185 nm->decompress();
2186 }
2187
2188 normal_w = nm->get_width();
2189 normal_h = nm->get_height();
2190
2191 normal_sat_vec.resize(normal_w * normal_h * 3);
2192 double *normal_sat = normal_sat_vec.ptr();
2193
2194 // Create summed area table.
2195 for (int y = 0; y < normal_h; y++) {
2196 double line_sum[3] = { 0, 0, 0 };
2197 for (int x = 0; x < normal_w; x++) {
2198 double normal[3];
2199 Color color = nm->get_pixel(x, y);
2200 normal[0] = color.r * 2.0 - 1.0;
2201 normal[1] = color.g * 2.0 - 1.0;
2202 normal[2] = Math::sqrt(MAX(0.0, 1.0 - (normal[0] * normal[0] + normal[1] * normal[1]))); //reconstruct if missing
2203
2204 line_sum[0] += normal[0];
2205 line_sum[1] += normal[1];
2206 line_sum[2] += normal[2];
2207
2208 uint32_t ofs = (y * normal_w + x) * 3;
2209
2210 normal_sat[ofs + 0] = line_sum[0];
2211 normal_sat[ofs + 1] = line_sum[1];
2212 normal_sat[ofs + 2] = line_sum[2];
2213
2214 if (y > 0) {
2215 uint32_t prev_ofs = ((y - 1) * normal_w + x) * 3;
2216 normal_sat[ofs + 0] += normal_sat[prev_ofs + 0];
2217 normal_sat[ofs + 1] += normal_sat[prev_ofs + 1];
2218 normal_sat[ofs + 2] += normal_sat[prev_ofs + 2];
2219 }
2220 }
2221 }
2222
2223 int mmcount;
2224
2225 _get_dst_image_size(width, height, format, mmcount);
2226
2227 uint8_t *base_ptr = data.ptrw();
2228
2229 for (int i = 1; i <= mmcount; i++) {
2230 int64_t ofs;
2231 int w, h;
2232 _get_mipmap_offset_and_size(i, ofs, w, h);
2233 uint8_t *ptr = &base_ptr[ofs];
2234
2235 for (int x = 0; x < w; x++) {
2236 for (int y = 0; y < h; y++) {
2237 int from_x = x * normal_w / w;
2238 int from_y = y * normal_h / h;
2239 int to_x = (x + 1) * normal_w / w;
2240 int to_y = (y + 1) * normal_h / h;
2241 to_x = MIN(to_x - 1, normal_w);
2242 to_y = MIN(to_y - 1, normal_h);
2243
2244 int size_x = (to_x - from_x) + 1;
2245 int size_y = (to_y - from_y) + 1;
2246
2247 //summed area table version (much faster)
2248
2249 double avg[3] = { 0, 0, 0 };
2250
2251 if (from_x > 0 && from_y > 0) {
2252 uint32_t tofs = ((from_y - 1) * normal_w + (from_x - 1)) * 3;
2253 avg[0] += normal_sat[tofs + 0];
2254 avg[1] += normal_sat[tofs + 1];
2255 avg[2] += normal_sat[tofs + 2];
2256 }
2257
2258 if (from_y > 0 && to_x > 0) {
2259 uint32_t tofs = ((from_y - 1) * normal_w + to_x) * 3;
2260 avg[0] -= normal_sat[tofs + 0];
2261 avg[1] -= normal_sat[tofs + 1];
2262 avg[2] -= normal_sat[tofs + 2];
2263 }
2264
2265 if (from_x > 0 && to_y > 0) {
2266 uint32_t tofs = (to_y * normal_w + (from_x - 1)) * 3;
2267 avg[0] -= normal_sat[tofs + 0];
2268 avg[1] -= normal_sat[tofs + 1];
2269 avg[2] -= normal_sat[tofs + 2];
2270 }
2271
2272 if (to_y > 0 && to_x > 0) {
2273 uint32_t tofs = (to_y * normal_w + to_x) * 3;
2274 avg[0] += normal_sat[tofs + 0];
2275 avg[1] += normal_sat[tofs + 1];
2276 avg[2] += normal_sat[tofs + 2];
2277 }
2278
2279 double div = double(size_x * size_y);
2280 Vector3 vec(avg[0] / div, avg[1] / div, avg[2] / div);
2281
2282 float r = vec.length();
2283
2284 int pixel_ofs = y * w + x;
2285 Color c = _get_color_at_ofs(ptr, pixel_ofs);
2286
2287 float roughness = 0;
2288
2289 switch (p_roughness_channel) {
2290 case ROUGHNESS_CHANNEL_R: {
2291 roughness = c.r;
2292 } break;
2293 case ROUGHNESS_CHANNEL_G: {
2294 roughness = c.g;
2295 } break;
2296 case ROUGHNESS_CHANNEL_B: {
2297 roughness = c.b;
2298 } break;
2299 case ROUGHNESS_CHANNEL_L: {
2300 roughness = c.get_v();
2301 } break;
2302 case ROUGHNESS_CHANNEL_A: {
2303 roughness = c.a;
2304 } break;
2305 }
2306
2307 float variance = 0;
2308 if (r < 1.0f) {
2309 float r2 = r * r;
2310 float kappa = (3.0f * r - r * r2) / (1.0f - r2);
2311 variance = 0.25f / kappa;
2312 }
2313
2314 float threshold = 0.4;
2315 roughness = Math::sqrt(roughness * roughness + MIN(3.0f * variance, threshold * threshold));
2316
2317 switch (p_roughness_channel) {
2318 case ROUGHNESS_CHANNEL_R: {
2319 c.r = roughness;
2320 } break;
2321 case ROUGHNESS_CHANNEL_G: {
2322 c.g = roughness;
2323 } break;
2324 case ROUGHNESS_CHANNEL_B: {
2325 c.b = roughness;
2326 } break;
2327 case ROUGHNESS_CHANNEL_L: {
2328 c.r = roughness;
2329 c.g = roughness;
2330 c.b = roughness;
2331 } break;
2332 case ROUGHNESS_CHANNEL_A: {
2333 c.a = roughness;
2334 } break;
2335 }
2336
2337 _set_color_at_ofs(ptr, pixel_ofs, c);
2338 }
2339 }
2340 }
2341
2342 return OK;
2343 }
2344
2345 void Image::clear_mipmaps() {
2346 if (!mipmaps) {
2347 return;
2348 }
2349
2350 if (is_empty()) {
2351 return;
2352 }
2353
2354 int64_t ofs;
2355 int w, h;
2356 _get_mipmap_offset_and_size(1, ofs, w, h);
2357 data.resize(ofs);
2358
2359 mipmaps = false;
2360 }
2361
2362 bool Image::is_empty() const {
2363 return (data.is_empty());
2364 }
2365
2366 Vector<uint8_t> Image::get_data() const {
2367 return data;
2368 }
2369
2370 Ref<Image> Image::create_empty(int p_width, int p_height, bool p_use_mipmaps, Format p_format) {
2371 Ref<Image> image;
2372 image.instantiate();
2373 image->initialize_data(p_width, p_height, p_use_mipmaps, p_format);
2374 return image;
2375 }
2376
2377 Ref<Image> Image::create_from_data(int p_width, int p_height, bool p_use_mipmaps, Format p_format, const Vector<uint8_t> &p_data) {
2378 Ref<Image> image;
2379 image.instantiate();
2380 image->initialize_data(p_width, p_height, p_use_mipmaps, p_format, p_data);
2381 return image;
2382 }
2383
2384 void Image::set_data(int p_width, int p_height, bool p_use_mipmaps, Format p_format, const Vector<uint8_t> &p_data) {
2385 initialize_data(p_width, p_height, p_use_mipmaps, p_format, p_data);
2386 }
2387
2388 void Image::initialize_data(int p_width, int p_height, bool p_use_mipmaps, Format p_format) {
2389 ERR_FAIL_COND_MSG(p_width <= 0, vformat("The Image width specified (%d pixels) must be greater than 0 pixels.", p_width));
2390 ERR_FAIL_COND_MSG(p_height <= 0, vformat("The Image height specified (%d pixels) must be greater than 0 pixels.", p_height));
2391 ERR_FAIL_COND_MSG(p_width > MAX_WIDTH,
2392 vformat("The Image width specified (%d pixels) cannot be greater than %d pixels.", p_width, MAX_WIDTH));
2393 ERR_FAIL_COND_MSG(p_height > MAX_HEIGHT,
2394 vformat("The Image height specified (%d pixels) cannot be greater than %d pixels.", p_height, MAX_HEIGHT));
2395 ERR_FAIL_COND_MSG(p_width * p_height > MAX_PIXELS,
2396 vformat("Too many pixels for Image. Maximum is %dx%d = %d pixels.", MAX_WIDTH, MAX_HEIGHT, MAX_PIXELS));
2397 ERR_FAIL_INDEX_MSG(p_format, FORMAT_MAX, vformat("The Image format specified (%d) is out of range. See Image's Format enum.", p_format));
2398
2399 int mm = 0;
2400 int64_t size = _get_dst_image_size(p_width, p_height, p_format, mm, p_use_mipmaps ? -1 : 0);
2401 data.resize(size);
2402
2403 {
2404 uint8_t *w = data.ptrw();
2405 memset(w, 0, size);
2406 }
2407
2408 width = p_width;
2409 height = p_height;
2410 mipmaps = p_use_mipmaps;
2411 format = p_format;
2412 }
2413
2414 void Image::initialize_data(int p_width, int p_height, bool p_use_mipmaps, Format p_format, const Vector<uint8_t> &p_data) {
2415 ERR_FAIL_COND_MSG(p_width <= 0, vformat("The Image width specified (%d pixels) must be greater than 0 pixels.", p_width));
2416 ERR_FAIL_COND_MSG(p_height <= 0, vformat("The Image height specified (%d pixels) must be greater than 0 pixels.", p_height));
2417 ERR_FAIL_COND_MSG(p_width > MAX_WIDTH,
2418 vformat("The Image width specified (%d pixels) cannot be greater than %d pixels.", p_width, MAX_WIDTH));
2419 ERR_FAIL_COND_MSG(p_height > MAX_HEIGHT,
2420 vformat("The Image height specified (%d pixels) cannot be greater than %d pixels.", p_height, MAX_HEIGHT));
2421 ERR_FAIL_COND_MSG(p_width * p_height > MAX_PIXELS,
2422 vformat("Too many pixels for Image. Maximum is %dx%d = %d pixels.", MAX_WIDTH, MAX_HEIGHT, MAX_PIXELS));
2423 ERR_FAIL_INDEX_MSG(p_format, FORMAT_MAX, vformat("The Image format specified (%d) is out of range. See Image's Format enum.", p_format));
2424
2425 int mm;
2426 int64_t size = _get_dst_image_size(p_width, p_height, p_format, mm, p_use_mipmaps ? -1 : 0);
2427
2428 if (unlikely(p_data.size() != size)) {
2429 String description_mipmaps = get_format_name(p_format) + " ";
2430 if (p_use_mipmaps) {
2431 const int num_mipmaps = get_image_required_mipmaps(p_width, p_height, p_format);
2432 if (num_mipmaps != 1) {
2433 description_mipmaps += vformat("with %d mipmaps", num_mipmaps);
2434 } else {
2435 description_mipmaps += "with 1 mipmap";
2436 }
2437 } else {
2438 description_mipmaps += "without mipmaps";
2439 }
2440 const String description = vformat("%dx%dx%d (%s)", p_width, p_height, get_format_pixel_size(p_format), description_mipmaps);
2441 ERR_FAIL_MSG(vformat("Expected Image data size of %s = %d bytes, got %d bytes instead.", description, size, p_data.size()));
2442 }
2443
2444 height = p_height;
2445 width = p_width;
2446 format = p_format;
2447 data = p_data;
2448
2449 mipmaps = p_use_mipmaps;
2450 }
2451
2452 void Image::initialize_data(const char **p_xpm) {
2453 int size_width = 0;
2454 int size_height = 0;
2455 int pixelchars = 0;
2456 mipmaps = false;
2457 bool has_alpha = false;
2458
2459 enum Status {
2460 READING_HEADER,
2461 READING_COLORS,
2462 READING_PIXELS,
2463 DONE
2464 };
2465
2466 Status status = READING_HEADER;
2467 int line = 0;
2468
2469 HashMap<String, Color> colormap;
2470 int colormap_size = 0;
2471 uint32_t pixel_size = 0;
2472 uint8_t *data_write = nullptr;
2473
2474 while (status != DONE) {
2475 const char *line_ptr = p_xpm[line];
2476
2477 switch (status) {
2478 case READING_HEADER: {
2479 String line_str = line_ptr;
2480 line_str = line_str.replace_char('\t', ' ');
2481
2482 size_width = line_str.get_slicec(' ', 0).to_int();
2483 size_height = line_str.get_slicec(' ', 1).to_int();
2484 colormap_size = line_str.get_slicec(' ', 2).to_int();
2485 pixelchars = line_str.get_slicec(' ', 3).to_int();
2486 ERR_FAIL_COND(colormap_size > 32766);
2487 ERR_FAIL_COND(pixelchars > 5);
2488 ERR_FAIL_COND(size_width > 32767);
2489 ERR_FAIL_COND(size_height > 32767);
2490 status = READING_COLORS;
2491 } break;
2492 case READING_COLORS: {
2493 String colorstring;
2494 for (int i = 0; i < pixelchars; i++) {
2495 colorstring += *line_ptr;
2496 line_ptr++;
2497 }
2498 //skip spaces
2499 while (*line_ptr == ' ' || *line_ptr == '\t' || *line_ptr == 0) {
2500 if (*line_ptr == 0) {
2501 break;
2502 }
2503 line_ptr++;
2504 }
2505 if (*line_ptr == 'c') {
2506 line_ptr++;
2507 while (*line_ptr == ' ' || *line_ptr == '\t' || *line_ptr == 0) {
2508 if (*line_ptr == 0) {
2509 break;
2510 }
2511 line_ptr++;
2512 }
2513
2514 if (*line_ptr == '#') {
2515 line_ptr++;
2516 uint8_t col_r = 0;
2517 uint8_t col_g = 0;
2518 uint8_t col_b = 0;
2519 //uint8_t col_a=255;
2520
2521 for (int i = 0; i < 6; i++) {
2522 char v = line_ptr[i];
2523
2524 if (is_digit(v)) {
2525 v -= '0';
2526 } else if (v >= 'A' && v <= 'F') {
2527 v = (v - 'A') + 10;
2528 } else if (v >= 'a' && v <= 'f') {
2529 v = (v - 'a') + 10;
2530 } else {
2531 break;
2532 }
2533
2534 switch (i) {
2535 case 0:
2536 col_r = v << 4;
2537 break;
2538 case 1:
2539 col_r |= v;
2540 break;
2541 case 2:
2542 col_g = v << 4;
2543 break;
2544 case 3:
2545 col_g |= v;
2546 break;
2547 case 4:
2548 col_b = v << 4;
2549 break;
2550 case 5:
2551 col_b |= v;
2552 break;
2553 }
2554 }
2555
2556 // magenta mask
2557 if (col_r == 255 && col_g == 0 && col_b == 255) {
2558 colormap[colorstring] = Color(0, 0, 0, 0);
2559 has_alpha = true;
2560 } else {
2561 colormap[colorstring] = Color(col_r / 255.0, col_g / 255.0, col_b / 255.0, 1.0);
2562 }
2563 }
2564 }
2565 if (line == colormap_size) {
2566 status = READING_PIXELS;
2567 initialize_data(size_width, size_height, false, has_alpha ? FORMAT_RGBA8 : FORMAT_RGB8);
2568 data_write = data.ptrw();
2569 pixel_size = has_alpha ? 4 : 3;
2570 }
2571 } break;
2572 case READING_PIXELS: {
2573 int y = line - colormap_size - 1;
2574 for (int x = 0; x < size_width; x++) {
2575 char pixelstr[6] = { 0, 0, 0, 0, 0, 0 };
2576 for (int i = 0; i < pixelchars; i++) {
2577 pixelstr[i] = line_ptr[x * pixelchars + i];
2578 }
2579
2580 Color *colorptr = colormap.getptr(pixelstr);
2581 ERR_FAIL_NULL(colorptr);
2582 uint8_t pixel[4];
2583 for (uint32_t i = 0; i < pixel_size; i++) {
2584 pixel[i] = CLAMP((*colorptr)[i] * 255, 0, 255);
2585 }
2586 _put_pixelb(x, y, pixel_size, data_write, pixel);
2587 }
2588
2589 if (y == (size_height - 1)) {
2590 status = DONE;
2591 }
2592 } break;
2593 default: {
2594 }
2595 }
2596
2597 line++;
2598 }
2599 }
2600 #define DETECT_ALPHA_MAX_THRESHOLD 254
2601 #define DETECT_ALPHA_MIN_THRESHOLD 2
2602
2603 #define DETECT_ALPHA(m_value) \
2604 { \
2605 uint8_t value = m_value; \
2606 if (value < DETECT_ALPHA_MIN_THRESHOLD) \
2607 bit = true; \
2608 else if (value < DETECT_ALPHA_MAX_THRESHOLD) { \
2609 detected = true; \
2610 break; \
2611 } \
2612 }
2613
2614 #define DETECT_NON_ALPHA(m_value) \
2615 { \
2616 uint8_t value = m_value; \
2617 if (value > 0) { \
2618 detected = true; \
2619 break; \
2620 } \
2621 }
2622
2623 bool Image::is_invisible() const {
2624 int w, h;
2625 int64_t len;
2626 _get_mipmap_offset_and_size(1, len, w, h);
2627
2628 if (len == 0) {
2629 return true;
2630 }
2631
2632 switch (format) {
2633 case FORMAT_LA8: {
2634 const int pixel_count = len / 2;
2635 const uint16_t *pixeldata = reinterpret_cast<const uint16_t *>(data.ptr());
2636
2637 for (int i = 0; i < pixel_count; i++) {
2638 if ((pixeldata[i] & 0xFF00) != 0) {
2639 return false;
2640 }
2641 }
2642 } break;
2643 case FORMAT_RGBA8: {
2644 const int pixel_count = len / 4;
2645 const uint32_t *pixeldata = reinterpret_cast<const uint32_t *>(data.ptr());
2646
2647 for (int i = 0; i < pixel_count; i++) {
2648 if ((pixeldata[i] & 0xFF000000) != 0) {
2649 return false;
2650 }
2651 }
2652 } break;
2653 case FORMAT_RGBA4444: {
2654 const int pixel_count = len / 2;
2655 const uint16_t *pixeldata = reinterpret_cast<const uint16_t *>(data.ptr());
2656
2657 for (int i = 0; i < pixel_count; i++) {
2658 if ((pixeldata[i] & 0x000F) != 0) {
2659 return false;
2660 }
2661 }
2662 } break;
2663 case FORMAT_RGBAH: {
2664 // The alpha mask accounts for the sign bit.
2665 const int pixel_count = len / 8;
2666 const uint16_t *pixeldata = reinterpret_cast<const uint16_t *>(data.ptr());
2667
2668 for (int i = 0; i < pixel_count; i++) {
2669 if ((pixeldata[i * 4 + 3] & 0x7FFF) != 0) {
2670 return false;
2671 }
2672 }
2673 } break;
2674 case FORMAT_RGBAF: {
2675 // The alpha mask accounts for the sign bit.
2676 const int pixel_count = len / 16;
2677 const uint32_t *pixeldata = reinterpret_cast<const uint32_t *>(data.ptr());
2678
2679 for (int i = 0; i < pixel_count; i++) {
2680 if ((pixeldata[i * 4 + 3] & 0x7FFFFFFF) != 0) {
2681 return false;
2682 }
2683 }
2684 } break;
2685 case FORMAT_RGBA16:
2686 case FORMAT_RGBA16I: {
2687 const int pixel_count = len / 8;
2688 const uint16_t *pixeldata = reinterpret_cast<const uint16_t *>(data.ptr());
2689
2690 for (int i = 0; i < pixel_count; i++) {
2691 if (pixeldata[i * 4 + 3] != 0) {
2692 return false;
2693 }
2694 }
2695 } break;
2696 default: {
2697 // Formats that are compressed or don't support alpha channels are presumed to be visible.
2698 return false;
2699 }
2700 }
2701
2702 // Every pixel has been checked, the image is invisible.
2703 return true;
2704 }
2705
2706 Image::AlphaMode Image::detect_alpha() const {
2707 int64_t len = data.size();
2708
2709 if (len == 0) {
2710 return ALPHA_NONE;
2711 }
2712
2713 int w, h;
2714 _get_mipmap_offset_and_size(1, len, w, h);
2715
2716 const uint8_t *r = data.ptr();
2717 const unsigned char *data_ptr = r;
2718
2719 bool bit = false;
2720 bool detected = false;
2721
2722 switch (format) {
2723 case FORMAT_LA8: {
2724 for (int i = 0; i < (len >> 1); i++) {
2725 DETECT_ALPHA(data_ptr[(i << 1) + 1]);
2726 }
2727
2728 } break;
2729 case FORMAT_RGBA8: {
2730 for (int i = 0; i < (len >> 2); i++) {
2731 DETECT_ALPHA(data_ptr[(i << 2) + 3])
2732 }
2733
2734 } break;
2735 case FORMAT_DXT3:
2736 case FORMAT_DXT5: {
2737 detected = true;
2738 } break;
2739 default: {
2740 }
2741 }
2742
2743 if (detected) {
2744 return ALPHA_BLEND;
2745 } else if (bit) {
2746 return ALPHA_BIT;
2747 } else {
2748 return ALPHA_NONE;
2749 }
2750 }
2751
2752 Error Image::load(const String &p_path) {
2753 String path = ResourceUID::ensure_path(p_path);
2754 #ifdef DEBUG_ENABLED
2755 if (path.begins_with("res://") && ResourceLoader::exists(path)) {
2756 WARN_PRINT(vformat("Loaded resource as image file, this will not work on export: '%s'. Instead, import the image file as an Image resource and load it normally as a resource.", path));
2757 }
2758 #endif
2759 return ImageLoader::load_image(path, this);
2760 }
2761
2762 Ref<Image> Image::load_from_file(const String &p_path) {
2763 String path = ResourceUID::ensure_path(p_path);
2764 #ifdef DEBUG_ENABLED
2765 if (path.begins_with("res://") && ResourceLoader::exists(path)) {
2766 WARN_PRINT(vformat("Loaded resource as image file, this will not work on export: '%s'. Instead, import the image file as an Image resource and load it normally as a resource.", path));
2767 }
2768 #endif
2769 Ref<Image> image;
2770 image.instantiate();
2771 Error err = ImageLoader::load_image(path, image);
2772 if (err != OK) {
2773 ERR_FAIL_V_MSG(Ref<Image>(), vformat("Failed to load image. Error %d", err));
2774 }
2775 return image;
2776 }
2777
2778 Error Image::save_png(const String &p_path) const {
2779 if (save_png_func == nullptr) {
2780 return ERR_UNAVAILABLE;
2781 }
2782
2783 return save_png_func(p_path, Ref<Image>((Image *)this));
2784 }
2785
2786 Error Image::save_jpg(const String &p_path, float p_quality) const {
2787 if (save_jpg_func == nullptr) {
2788 return ERR_UNAVAILABLE;
2789 }
2790
2791 return save_jpg_func(p_path, Ref<Image>((Image *)this), p_quality);
2792 }
2793
2794 Vector<uint8_t> Image::save_png_to_buffer() const {
2795 if (save_png_buffer_func == nullptr) {
2796 return Vector<uint8_t>();
2797 }
2798
2799 return save_png_buffer_func(Ref<Image>((Image *)this));
2800 }
2801
2802 Vector<uint8_t> Image::save_jpg_to_buffer(float p_quality) const {
2803 if (save_jpg_buffer_func == nullptr) {
2804 return Vector<uint8_t>();
2805 }
2806
2807 return save_jpg_buffer_func(Ref<Image>((Image *)this), p_quality);
2808 }
2809
2810 Error Image::save_exr(const String &p_path, bool p_grayscale) const {
2811 if (save_exr_func == nullptr) {
2812 return ERR_UNAVAILABLE;
2813 }
2814
2815 return save_exr_func(p_path, Ref<Image>((Image *)this), p_grayscale);
2816 }
2817
2818 Vector<uint8_t> Image::save_exr_to_buffer(bool p_grayscale) const {
2819 if (save_exr_buffer_func == nullptr) {
2820 return Vector<uint8_t>();
2821 }
2822 return save_exr_buffer_func(Ref<Image>((Image *)this), p_grayscale);
2823 }
2824
2825 Error Image::save_dds(const String &p_path) const {
2826 if (save_dds_func == nullptr) {
2827 return ERR_UNAVAILABLE;
2828 }
2829
2830 return save_dds_func(p_path, Ref<Image>((Image *)this));
2831 }
2832
2833 Vector<uint8_t> Image::save_dds_to_buffer() const {
2834 if (save_dds_buffer_func == nullptr) {
2835 return Vector<uint8_t>();
2836 }
2837 return save_dds_buffer_func(Ref<Image>((Image *)this));
2838 }
2839
2840 Error Image::save_webp(const String &p_path, const bool p_lossy, const float p_quality) const {
2841 if (save_webp_func == nullptr) {
2842 return ERR_UNAVAILABLE;
2843 }
2844 ERR_FAIL_COND_V_MSG(p_lossy && !(0.0f <= p_quality && p_quality <= 1.0f), ERR_INVALID_PARAMETER, vformat("The WebP lossy quality was set to %f, which is not valid. WebP lossy quality must be between 0.0 and 1.0 (inclusive).", p_quality));
2845
2846 return save_webp_func(p_path, Ref<Image>((Image *)this), p_lossy, p_quality);
2847 }
2848
2849 Vector<uint8_t> Image::save_webp_to_buffer(const bool p_lossy, const float p_quality) const {
2850 if (save_webp_buffer_func == nullptr) {
2851 return Vector<uint8_t>();
2852 }
2853 ERR_FAIL_COND_V_MSG(p_lossy && !(0.0f <= p_quality && p_quality <= 1.0f), Vector<uint8_t>(), vformat("The WebP lossy quality was set to %f, which is not valid. WebP lossy quality must be between 0.0 and 1.0 (inclusive).", p_quality));
2854
2855 return save_webp_buffer_func(Ref<Image>((Image *)this), p_lossy, p_quality);
2856 }
2857
2858 int64_t Image::get_image_data_size(int p_width, int p_height, Format p_format, bool p_mipmaps) {
2859 int mm;
2860 return _get_dst_image_size(p_width, p_height, p_format, mm, p_mipmaps ? -1 : 0);
2861 }
2862
2863 int Image::get_image_required_mipmaps(int p_width, int p_height, Format p_format) {
2864 int mm;
2865 _get_dst_image_size(p_width, p_height, p_format, mm, -1);
2866 return mm;
2867 }
2868
2869 Size2i Image::get_image_mipmap_size(int p_width, int p_height, Format p_format, int p_mipmap) {
2870 int mm;
2871 Size2i ret;
2872 _get_dst_image_size(p_width, p_height, p_format, mm, p_mipmap, &ret.x, &ret.y);
2873 return ret;
2874 }
2875
2876 int64_t Image::get_image_mipmap_offset(int p_width, int p_height, Format p_format, int p_mipmap) {
2877 if (p_mipmap <= 0) {
2878 return 0;
2879 }
2880 int mm;
2881 return _get_dst_image_size(p_width, p_height, p_format, mm, p_mipmap - 1);
2882 }
2883
2884 int64_t Image::get_image_mipmap_offset_and_dimensions(int p_width, int p_height, Format p_format, int p_mipmap, int &r_w, int &r_h) {
2885 if (p_mipmap <= 0) {
2886 r_w = p_width;
2887 r_h = p_height;
2888 return 0;
2889 }
2890 int mm;
2891 return _get_dst_image_size(p_width, p_height, p_format, mm, p_mipmap - 1, &r_w, &r_h);
2892 }
2893
2894 bool Image::is_compressed() const {
2895 return is_format_compressed(format);
2896 }
2897
2898 bool Image::is_format_compressed(Format p_format) {
2899 return p_format > FORMAT_RGBE9995 && p_format < FORMAT_R16;
2900 }
2901
2902 Error Image::decompress() {
2903 if (((format >= FORMAT_DXT1 && format <= FORMAT_RGTC_RG) || (format == FORMAT_DXT5_RA_AS_RG)) && _image_decompress_bc) {
2904 _image_decompress_bc(this);
2905 } else if (format >= FORMAT_BPTC_RGBA && format <= FORMAT_BPTC_RGBFU && _image_decompress_bptc) {
2906 _image_decompress_bptc(this);
2907 } else if (format == FORMAT_ETC && _image_decompress_etc1) {
2908 _image_decompress_etc1(this);
2909 } else if (format >= FORMAT_ETC2_R11 && format <= FORMAT_ETC2_RA_AS_RG && _image_decompress_etc2) {
2910 _image_decompress_etc2(this);
2911 } else if (format >= FORMAT_ASTC_4x4 && format <= FORMAT_ASTC_8x8_HDR && _image_decompress_astc) {
2912 _image_decompress_astc(this);
2913 } else {
2914 return ERR_UNAVAILABLE;
2915 }
2916 return OK;
2917 }
2918
2919 bool Image::can_decompress(const String &p_format_tag) {
2920 if (p_format_tag == "astc") {
2921 return _image_decompress_astc != nullptr;
2922 } else if (p_format_tag == "bptc") {
2923 return _image_decompress_bptc != nullptr;
2924 } else if (p_format_tag == "etc2") {
2925 return _image_decompress_etc2 != nullptr;
2926 } else if (p_format_tag == "s3tc") {
2927 return _image_decompress_bc != nullptr;
2928 }
2929 return false;
2930 }
2931
2932 Error Image::compress(CompressMode p_mode, CompressSource p_source, ASTCFormat p_astc_format) {
2933 ERR_FAIL_INDEX_V_MSG(p_mode, COMPRESS_MAX, ERR_INVALID_PARAMETER, "Invalid compress mode.");
2934 ERR_FAIL_INDEX_V_MSG(p_source, COMPRESS_SOURCE_MAX, ERR_INVALID_PARAMETER, "Invalid compress source.");
2935 return compress_from_channels(p_mode, detect_used_channels(p_source), p_astc_format);
2936 }
2937
2938 Error Image::compress_from_channels(CompressMode p_mode, UsedChannels p_channels, ASTCFormat p_astc_format) {
2939 ERR_FAIL_COND_V(data.is_empty(), ERR_INVALID_DATA);
2940
2941 // RenderingDevice only.
2942 if (GLOBAL_GET("rendering/textures/vram_compression/compress_with_gpu")) {
2943 switch (p_mode) {
2944 case COMPRESS_BPTC: {
2945 // BC7 is unsupported currently.
2946 if ((format >= FORMAT_RF && format <= FORMAT_RGBE9995) && _image_compress_bptc_rd_func) {
2947 Error result = _image_compress_bptc_rd_func(this, p_channels);
2948
2949 // If the image was compressed successfully, we return here. If not, we fall back to the default compression scheme.
2950 if (result == OK) {
2951 return OK;
2952 }
2953 }
2954 } break;
2955 case COMPRESS_S3TC: {
2956 if (_image_compress_bc_rd_func) {
2957 Error result = _image_compress_bc_rd_func(this, p_channels);
2958
2959 // If the image was compressed successfully, we return here. If not, we fall back to the default compression scheme.
2960 if (result == OK) {
2961 return OK;
2962 }
2963 }
2964 } break;
2965
2966 default: {
2967 }
2968 }
2969 }
2970
2971 switch (p_mode) {
2972 case COMPRESS_S3TC: {
2973 ERR_FAIL_NULL_V(_image_compress_bc_func, ERR_UNAVAILABLE);
2974 _image_compress_bc_func(this, p_channels);
2975 } break;
2976 case COMPRESS_ETC: {
2977 ERR_FAIL_NULL_V(_image_compress_etc1_func, ERR_UNAVAILABLE);
2978 _image_compress_etc1_func(this);
2979 } break;
2980 case COMPRESS_ETC2: {
2981 ERR_FAIL_NULL_V(_image_compress_etc2_func, ERR_UNAVAILABLE);
2982 _image_compress_etc2_func(this, p_channels);
2983 } break;
2984 case COMPRESS_BPTC: {
2985 ERR_FAIL_NULL_V(_image_compress_bptc_func, ERR_UNAVAILABLE);
2986 _image_compress_bptc_func(this, p_channels);
2987 } break;
2988 case COMPRESS_ASTC: {
2989 ERR_FAIL_NULL_V(_image_compress_astc_func, ERR_UNAVAILABLE);
2990 _image_compress_astc_func(this, p_astc_format);
2991 } break;
2992 case COMPRESS_MAX: {
2993 ERR_FAIL_V(ERR_INVALID_PARAMETER);
2994 } break;
2995 }
2996
2997 return OK;
2998 }
2999
3000 Image::Image(const char **p_xpm) {
3001 width = 0;
3002 height = 0;
3003 mipmaps = false;
3004 format = FORMAT_L8;
3005
3006 initialize_data(p_xpm);
3007 }
3008
3009 Image::Image(int p_width, int p_height, bool p_use_mipmaps, Format p_format) {
3010 width = 0;
3011 height = 0;
3012 mipmaps = p_use_mipmaps;
3013 format = FORMAT_L8;
3014
3015 initialize_data(p_width, p_height, p_use_mipmaps, p_format);
3016 }
3017
3018 Image::Image(int p_width, int p_height, bool p_mipmaps, Format p_format, const Vector<uint8_t> &p_data) {
3019 width = 0;
3020 height = 0;
3021 mipmaps = p_mipmaps;
3022 format = FORMAT_L8;
3023
3024 initialize_data(p_width, p_height, p_mipmaps, p_format, p_data);
3025 }
3026
3027 Rect2i Image::get_used_rect() const {
3028 if (format != FORMAT_LA8 && format != FORMAT_RGBA8 && format != FORMAT_RGBAF && format != FORMAT_RGBAH && format != FORMAT_RGBA4444 && format != FORMAT_RGB565) {
3029 return Rect2i(0, 0, width, height);
3030 }
3031
3032 int len = data.size();
3033
3034 if (len == 0) {
3035 return Rect2i();
3036 }
3037
3038 int minx = 0xFFFFFF, miny = 0xFFFFFFF;
3039 int maxx = -1, maxy = -1;
3040 for (int j = 0; j < height; j++) {
3041 for (int i = 0; i < width; i++) {
3042 if (!(get_pixel(i, j).a > 0)) {
3043 continue;
3044 }
3045 if (i > maxx) {
3046 maxx = i;
3047 }
3048 if (j > maxy) {
3049 maxy = j;
3050 }
3051 if (i < minx) {
3052 minx = i;
3053 }
3054 if (j < miny) {
3055 miny = j;
3056 }
3057 }
3058 }
3059
3060 if (maxx == -1) {
3061 return Rect2i();
3062 } else {
3063 return Rect2i(minx, miny, maxx - minx + 1, maxy - miny + 1);
3064 }
3065 }
3066
3067 Ref<Image> Image::get_region(const Rect2i &p_region) const {
3068 Ref<Image> img = memnew(Image(p_region.size.x, p_region.size.y, mipmaps, format));
3069 img->blit_rect(Ref<Image>((Image *)this), p_region, Point2i(0, 0));
3070 return img;
3071 }
3072
3073 void Image::_get_clipped_src_and_dest_rects(const Ref<Image> &p_src, const Rect2i &p_src_rect, const Point2i &p_dest, Rect2i &r_clipped_src_rect, Rect2i &r_clipped_dest_rect) const {
3074 r_clipped_dest_rect.position = p_dest;
3075 r_clipped_src_rect = p_src_rect;
3076
3077 if (r_clipped_src_rect.position.x < 0) {
3078 r_clipped_dest_rect.position.x -= r_clipped_src_rect.position.x;
3079 r_clipped_src_rect.size.x += r_clipped_src_rect.position.x;
3080 r_clipped_src_rect.position.x = 0;
3081 }
3082 if (r_clipped_src_rect.position.y < 0) {
3083 r_clipped_dest_rect.position.y -= r_clipped_src_rect.position.y;
3084 r_clipped_src_rect.size.y += r_clipped_src_rect.position.y;
3085 r_clipped_src_rect.position.y = 0;
3086 }
3087
3088 if (r_clipped_dest_rect.position.x < 0) {
3089 r_clipped_src_rect.position.x -= r_clipped_dest_rect.position.x;
3090 r_clipped_src_rect.size.x += r_clipped_dest_rect.position.x;
3091 r_clipped_dest_rect.position.x = 0;
3092 }
3093 if (r_clipped_dest_rect.position.y < 0) {
3094 r_clipped_src_rect.position.y -= r_clipped_dest_rect.position.y;
3095 r_clipped_src_rect.size.y += r_clipped_dest_rect.position.y;
3096 r_clipped_dest_rect.position.y = 0;
3097 }
3098
3099 r_clipped_src_rect.size.x = MAX(0, MIN(r_clipped_src_rect.size.x, MIN(p_src->width - r_clipped_src_rect.position.x, width - r_clipped_dest_rect.position.x)));
3100 r_clipped_src_rect.size.y = MAX(0, MIN(r_clipped_src_rect.size.y, MIN(p_src->height - r_clipped_src_rect.position.y, height - r_clipped_dest_rect.position.y)));
3101
3102 r_clipped_dest_rect.size.x = r_clipped_src_rect.size.x;
3103 r_clipped_dest_rect.size.y = r_clipped_src_rect.size.y;
3104 }
3105
3106 void Image::blit_rect(const Ref<Image> &p_src, const Rect2i &p_src_rect, const Point2i &p_dest) {
3107 ERR_FAIL_COND_MSG(p_src.is_null(), "Cannot blit_rect an image: invalid source Image object.");
3108 int dsize = data.size();
3109 int srcdsize = p_src->data.size();
3110 ERR_FAIL_COND(dsize == 0);
3111 ERR_FAIL_COND(srcdsize == 0);
3112 ERR_FAIL_COND(format != p_src->format);
3113 ERR_FAIL_COND_MSG(is_compressed(), "Cannot blit_rect in compressed image formats.");
3114
3115 Rect2i src_rect;
3116 Rect2i dest_rect;
3117 _get_clipped_src_and_dest_rects(p_src, p_src_rect, p_dest, src_rect, dest_rect);
3118 if (!src_rect.has_area() || !dest_rect.has_area()) {
3119 return;
3120 }
3121
3122 uint8_t *wp = data.ptrw();
3123 uint8_t *dst_data_ptr = wp;
3124
3125 const uint8_t *rp = p_src->data.ptr();
3126 const uint8_t *src_data_ptr = rp;
3127
3128 int pixel_size = get_format_pixel_size(format);
3129
3130 // If the rect width is equivalent for both src and dst and the x offset is 0, we can blit in a single memcpy.
3131 // Else, we do a per-line copy.
3132 if ((dest_rect.size.x == p_src->width) && (p_src->width == width) && (dest_rect.position.x == 0) && (src_rect.position.x == 0)) {
3133 const uint8_t *src = &src_data_ptr[(src_rect.position.y * p_src->width) * pixel_size];
3134 uint8_t *dst = &dst_data_ptr[(dest_rect.position.y * width) * pixel_size];
3135 memcpy(dst, src, width * dest_rect.size.y * pixel_size);
3136 } else {
3137 for (int i = 0; i < dest_rect.size.y; i++) {
3138 const uint8_t *src = &src_data_ptr[((src_rect.position.y + i) * p_src->width + src_rect.position.x) * pixel_size];
3139 uint8_t *dst = &dst_data_ptr[((dest_rect.position.y + i) * width + dest_rect.position.x) * pixel_size];
3140 memcpy(dst, src, pixel_size * dest_rect.size.x);
3141 }
3142 }
3143 }
3144
3145 void Image::blit_rect_mask(const Ref<Image> &p_src, const Ref<Image> &p_mask, const Rect2i &p_src_rect, const Point2i &p_dest) {
3146 ERR_FAIL_COND_MSG(p_src.is_null(), "Cannot blit_rect_mask an image: invalid source Image object.");
3147 ERR_FAIL_COND_MSG(p_mask.is_null(), "Cannot blit_rect_mask an image: invalid mask Image object.");
3148 int dsize = data.size();
3149 int srcdsize = p_src->data.size();
3150 int maskdsize = p_mask->data.size();
3151 ERR_FAIL_COND(dsize == 0);
3152 ERR_FAIL_COND(srcdsize == 0);
3153 ERR_FAIL_COND(maskdsize == 0);
3154 ERR_FAIL_COND_MSG(p_src->width != p_mask->width, "Source image width is different from mask width.");
3155 ERR_FAIL_COND_MSG(p_src->height != p_mask->height, "Source image height is different from mask height.");
3156 ERR_FAIL_COND(format != p_src->format);
3157
3158 Rect2i src_rect;
3159 Rect2i dest_rect;
3160 _get_clipped_src_and_dest_rects(p_src, p_src_rect, p_dest, src_rect, dest_rect);
3161 if (!src_rect.has_area() || !dest_rect.has_area()) {
3162 return;
3163 }
3164
3165 uint8_t *wp = data.ptrw();
3166 uint8_t *dst_data_ptr = wp;
3167
3168 const uint8_t *rp = p_src->data.ptr();
3169 const uint8_t *src_data_ptr = rp;
3170
3171 int pixel_size = get_format_pixel_size(format);
3172
3173 Ref<Image> msk = p_mask;
3174
3175 for (int i = 0; i < dest_rect.size.y; i++) {
3176 for (int j = 0; j < dest_rect.size.x; j++) {
3177 int src_x = src_rect.position.x + j;
3178 int src_y = src_rect.position.y + i;
3179
3180 if (msk->get_pixel(src_x, src_y).a != 0) {
3181 int dst_x = dest_rect.position.x + j;
3182 int dst_y = dest_rect.position.y + i;
3183
3184 const uint8_t *src = &src_data_ptr[(src_y * p_src->width + src_x) * pixel_size];
3185 uint8_t *dst = &dst_data_ptr[(dst_y * width + dst_x) * pixel_size];
3186
3187 for (int k = 0; k < pixel_size; k++) {
3188 dst[k] = src[k];
3189 }
3190 }
3191 }
3192 }
3193 }
3194
3195 void Image::blend_rect(const Ref<Image> &p_src, const Rect2i &p_src_rect, const Point2i &p_dest) {
3196 ERR_FAIL_COND_MSG(p_src.is_null(), "Cannot blend_rect an image: invalid source Image object.");
3197 int dsize = data.size();
3198 int srcdsize = p_src->data.size();
3199 ERR_FAIL_COND(dsize == 0);
3200 ERR_FAIL_COND(srcdsize == 0);
3201 ERR_FAIL_COND(format != p_src->format);
3202
3203 Rect2i src_rect;
3204 Rect2i dest_rect;
3205 _get_clipped_src_and_dest_rects(p_src, p_src_rect, p_dest, src_rect, dest_rect);
3206 if (!src_rect.has_area() || !dest_rect.has_area()) {
3207 return;
3208 }
3209
3210 Ref<Image> img = p_src;
3211
3212 for (int i = 0; i < dest_rect.size.y; i++) {
3213 for (int j = 0; j < dest_rect.size.x; j++) {
3214 int src_x = src_rect.position.x + j;
3215 int src_y = src_rect.position.y + i;
3216
3217 int dst_x = dest_rect.position.x + j;
3218 int dst_y = dest_rect.position.y + i;
3219
3220 Color sc = img->get_pixel(src_x, src_y);
3221 if (sc.a != 0) {
3222 Color dc = get_pixel(dst_x, dst_y);
3223 dc = dc.blend(sc);
3224 set_pixel(dst_x, dst_y, dc);
3225 }
3226 }
3227 }
3228 }
3229
3230 void Image::blend_rect_mask(const Ref<Image> &p_src, const Ref<Image> &p_mask, const Rect2i &p_src_rect, const Point2i &p_dest) {
3231 ERR_FAIL_COND_MSG(p_src.is_null(), "Cannot blend_rect_mask an image: invalid source Image object.");
3232 ERR_FAIL_COND_MSG(p_mask.is_null(), "Cannot blend_rect_mask an image: invalid mask Image object.");
3233 int dsize = data.size();
3234 int srcdsize = p_src->data.size();
3235 int maskdsize = p_mask->data.size();
3236 ERR_FAIL_COND(dsize == 0);
3237 ERR_FAIL_COND(srcdsize == 0);
3238 ERR_FAIL_COND(maskdsize == 0);
3239 ERR_FAIL_COND_MSG(p_src->width != p_mask->width, "Source image width is different from mask width.");
3240 ERR_FAIL_COND_MSG(p_src->height != p_mask->height, "Source image height is different from mask height.");
3241 ERR_FAIL_COND(format != p_src->format);
3242
3243 Rect2i src_rect;
3244 Rect2i dest_rect;
3245 _get_clipped_src_and_dest_rects(p_src, p_src_rect, p_dest, src_rect, dest_rect);
3246 if (!src_rect.has_area() || !dest_rect.has_area()) {
3247 return;
3248 }
3249
3250 Ref<Image> img = p_src;
3251 Ref<Image> msk = p_mask;
3252
3253 for (int i = 0; i < dest_rect.size.y; i++) {
3254 for (int j = 0; j < dest_rect.size.x; j++) {
3255 int src_x = src_rect.position.x + j;
3256 int src_y = src_rect.position.y + i;
3257
3258 // If the mask's pixel is transparent then we skip it
3259 //Color c = msk->get_pixel(src_x, src_y);
3260 //if (c.a == 0) continue;
3261 if (msk->get_pixel(src_x, src_y).a != 0) {
3262 int dst_x = dest_rect.position.x + j;
3263 int dst_y = dest_rect.position.y + i;
3264
3265 Color sc = img->get_pixel(src_x, src_y);
3266 if (sc.a != 0) {
3267 Color dc = get_pixel(dst_x, dst_y);
3268 dc = dc.blend(sc);
3269 set_pixel(dst_x, dst_y, dc);
3270 }
3271 }
3272 }
3273 }
3274 }
3275
3276 // Repeats `p_pixel` `p_count` times in consecutive memory.
3277 // Results in the original pixel and `p_count - 1` subsequent copies of it.
3278 void Image::_repeat_pixel_over_subsequent_memory(uint8_t *p_pixel, int p_pixel_size, int p_count) {
3279 int offset = 1;
3280 for (int stride = 1; offset + stride <= p_count; stride *= 2) {
3281 memcpy(p_pixel + offset * p_pixel_size, p_pixel, stride * p_pixel_size);
3282 offset += stride;
3283 }
3284 if (offset < p_count) {
3285 memcpy(p_pixel + offset * p_pixel_size, p_pixel, (p_count - offset) * p_pixel_size);
3286 }
3287 }
3288
3289 void Image::fill(const Color &p_color) {
3290 if (data.is_empty()) {
3291 return;
3292 }
3293 ERR_FAIL_COND_MSG(is_compressed(), "Cannot fill in compressed image formats.");
3294
3295 uint8_t *dst_data_ptr = data.ptrw();
3296 int pixel_size = get_format_pixel_size(format);
3297 int64_t pixel_count = data.size() / pixel_size;
3298
3299 // Put first pixel with the format-aware API.
3300 _set_color_at_ofs(dst_data_ptr, 0, p_color);
3301
3302 _repeat_pixel_over_subsequent_memory(dst_data_ptr, pixel_size, pixel_count);
3303 }
3304
3305 void Image::fill_rect(const Rect2i &p_rect, const Color &p_color) {
3306 if (data.is_empty()) {
3307 return;
3308 }
3309 ERR_FAIL_COND_MSG(is_compressed(), "Cannot fill rect in compressed image formats.");
3310
3311 Rect2i r = Rect2i(0, 0, width, height).intersection(p_rect.abs());
3312 if (!r.has_area()) {
3313 return;
3314 }
3315
3316 uint8_t *dst_data_ptr = data.ptrw();
3317
3318 int pixel_size = get_format_pixel_size(format);
3319
3320 // Put first pixel with the format-aware API.
3321 uint8_t *rect_first_pixel_ptr = &dst_data_ptr[(r.position.y * width + r.position.x) * pixel_size];
3322 _set_color_at_ofs(rect_first_pixel_ptr, 0, p_color);
3323
3324 if (r.size.x == width) {
3325 // No need to fill rows separately.
3326 _repeat_pixel_over_subsequent_memory(rect_first_pixel_ptr, pixel_size, width * r.size.y);
3327 } else {
3328 _repeat_pixel_over_subsequent_memory(rect_first_pixel_ptr, pixel_size, r.size.x);
3329 for (int y = 1; y < r.size.y; y++) {
3330 memcpy(rect_first_pixel_ptr + y * width * pixel_size, rect_first_pixel_ptr, r.size.x * pixel_size);
3331 }
3332 }
3333 }
3334
3335 void Image::_set_data(const Dictionary &p_data) {
3336 ERR_FAIL_COND(!p_data.has("width"));
3337 ERR_FAIL_COND(!p_data.has("height"));
3338 ERR_FAIL_COND(!p_data.has("format"));
3339 ERR_FAIL_COND(!p_data.has("mipmaps"));
3340 ERR_FAIL_COND(!p_data.has("data"));
3341
3342 int dwidth = p_data["width"];
3343 int dheight = p_data["height"];
3344 String dformat = p_data["format"];
3345 bool dmipmaps = p_data["mipmaps"];
3346 Vector<uint8_t> ddata = p_data["data"];
3347 Format ddformat = FORMAT_MAX;
3348 for (int i = 0; i < FORMAT_MAX; i++) {
3349 if (dformat == get_format_name(Format(i))) {
3350 ddformat = Format(i);
3351 break;
3352 }
3353 }
3354
3355 ERR_FAIL_COND(ddformat == FORMAT_MAX);
3356
3357 initialize_data(dwidth, dheight, dmipmaps, ddformat, ddata);
3358 }
3359
3360 Dictionary Image::_get_data() const {
3361 Dictionary d;
3362 d["width"] = width;
3363 d["height"] = height;
3364 d["format"] = get_format_name(format);
3365 d["mipmaps"] = mipmaps;
3366 d["data"] = data;
3367 return d;
3368 }
3369
3370 Color Image::get_pixelv(const Point2i &p_point) const {
3371 return get_pixel(p_point.x, p_point.y);
3372 }
3373
3374 void Image::_copy_internals_from(const Image &p_image) {
3375 format = p_image.format;
3376 width = p_image.width;
3377 height = p_image.height;
3378 mipmaps = p_image.mipmaps;
3379 data = p_image.data;
3380 }
3381
3382 _FORCE_INLINE_ Color color_from_rgba4444(uint16_t p_col) {
3383 float r = ((p_col >> 12) & 0xF) / 15.0;
3384 float g = ((p_col >> 8) & 0xF) / 15.0;
3385 float b = ((p_col >> 4) & 0xF) / 15.0;
3386 float a = (p_col & 0xF) / 15.0;
3387 return Color(r, g, b, a);
3388 }
3389
3390 _FORCE_INLINE_ uint16_t color_to_rgba4444(Color p_col) {
3391 uint16_t rgba = 0;
3392
3393 rgba = uint16_t(CLAMP(p_col.r * 15.0, 0, 15)) << 12;
3394 rgba |= uint16_t(CLAMP(p_col.g * 15.0, 0, 15)) << 8;
3395 rgba |= uint16_t(CLAMP(p_col.b * 15.0, 0, 15)) << 4;
3396 rgba |= uint16_t(CLAMP(p_col.a * 15.0, 0, 15));
3397
3398 return rgba;
3399 }
3400
3401 _FORCE_INLINE_ Color color_from_rgb565(uint16_t p_col) {
3402 float r = ((p_col >> 11) & 0x1F) / 31.0;
3403 float g = ((p_col >> 5) & 0x3F) / 63.0;
3404 float b = (p_col & 0x1F) / 31.0;
3405 return Color(r, g, b, 1.0);
3406 }
3407
3408 _FORCE_INLINE_ uint16_t color_to_rgb565(Color p_col) {
3409 uint16_t rgba = 0;
3410
3411 rgba = uint16_t(CLAMP(p_col.r * 31.0, 0, 31)) << 11;
3412 rgba |= uint16_t(CLAMP(p_col.g * 63.0, 0, 63)) << 5;
3413 rgba |= uint16_t(CLAMP(p_col.b * 31.0, 0, 31));
3414
3415 return rgba;
3416 }
3417
3418 Color Image::_get_color_at_ofs(const uint8_t *ptr, uint32_t ofs) const {
3419 switch (format) {
3420 case FORMAT_L8: {
3421 float l = ptr[ofs] / 255.0;
3422 return Color(l, l, l, 1);
3423 }
3424 case FORMAT_LA8: {
3425 float l = ptr[ofs * 2 + 0] / 255.0;
3426 float a = ptr[ofs * 2 + 1] / 255.0;
3427 return Color(l, l, l, a);
3428 }
3429 case FORMAT_R8: {
3430 float r = ptr[ofs] / 255.0;
3431 return Color(r, 0, 0, 1);
3432 }
3433 case FORMAT_RG8: {
3434 float r = ptr[ofs * 2 + 0] / 255.0;
3435 float g = ptr[ofs * 2 + 1] / 255.0;
3436 return Color(r, g, 0, 1);
3437 }
3438 case FORMAT_RGB8: {
3439 float r = ptr[ofs * 3 + 0] / 255.0;
3440 float g = ptr[ofs * 3 + 1] / 255.0;
3441 float b = ptr[ofs * 3 + 2] / 255.0;
3442 return Color(r, g, b, 1);
3443 }
3444 case FORMAT_RGBA8: {
3445 float r = ptr[ofs * 4 + 0] / 255.0;
3446 float g = ptr[ofs * 4 + 1] / 255.0;
3447 float b = ptr[ofs * 4 + 2] / 255.0;
3448 float a = ptr[ofs * 4 + 3] / 255.0;
3449 return Color(r, g, b, a);
3450 }
3451 case FORMAT_RGBA4444: {
3452 return color_from_rgba4444(((uint16_t *)ptr)[ofs]);
3453 }
3454 case FORMAT_RGB565: {
3455 return color_from_rgb565(((uint16_t *)ptr)[ofs]);
3456 }
3457 case FORMAT_RF: {
3458 float r = ((float *)ptr)[ofs];
3459 return Color(r, 0, 0, 1);
3460 }
3461 case FORMAT_RGF: {
3462 float r = ((float *)ptr)[ofs * 2 + 0];
3463 float g = ((float *)ptr)[ofs * 2 + 1];
3464 return Color(r, g, 0, 1);
3465 }
3466 case FORMAT_RGBF: {
3467 float r = ((float *)ptr)[ofs * 3 + 0];
3468 float g = ((float *)ptr)[ofs * 3 + 1];
3469 float b = ((float *)ptr)[ofs * 3 + 2];
3470 return Color(r, g, b, 1);
3471 }
3472 case FORMAT_RGBAF: {
3473 float r = ((float *)ptr)[ofs * 4 + 0];
3474 float g = ((float *)ptr)[ofs * 4 + 1];
3475 float b = ((float *)ptr)[ofs * 4 + 2];
3476 float a = ((float *)ptr)[ofs * 4 + 3];
3477 return Color(r, g, b, a);
3478 }
3479 case FORMAT_RH: {
3480 uint16_t r = ((uint16_t *)ptr)[ofs];
3481 return Color(Math::half_to_float(r), 0, 0, 1);
3482 }
3483 case FORMAT_RGH: {
3484 uint16_t r = ((uint16_t *)ptr)[ofs * 2 + 0];
3485 uint16_t g = ((uint16_t *)ptr)[ofs * 2 + 1];
3486 return Color(Math::half_to_float(r), Math::half_to_float(g), 0, 1);
3487 }
3488 case FORMAT_RGBH: {
3489 uint16_t r = ((uint16_t *)ptr)[ofs * 3 + 0];
3490 uint16_t g = ((uint16_t *)ptr)[ofs * 3 + 1];
3491 uint16_t b = ((uint16_t *)ptr)[ofs * 3 + 2];
3492 return Color(Math::half_to_float(r), Math::half_to_float(g), Math::half_to_float(b), 1);
3493 }
3494 case FORMAT_RGBAH: {
3495 uint16_t r = ((uint16_t *)ptr)[ofs * 4 + 0];
3496 uint16_t g = ((uint16_t *)ptr)[ofs * 4 + 1];
3497 uint16_t b = ((uint16_t *)ptr)[ofs * 4 + 2];
3498 uint16_t a = ((uint16_t *)ptr)[ofs * 4 + 3];
3499 return Color(Math::half_to_float(r), Math::half_to_float(g), Math::half_to_float(b), Math::half_to_float(a));
3500 }
3501 case FORMAT_RGBE9995: {
3502 return Color::from_rgbe9995(((uint32_t *)ptr)[ofs]);
3503 }
3504 case FORMAT_R16: {
3505 float r = ((uint16_t *)ptr)[ofs] / 65535.0f;
3506 return Color(r, 0, 0, 1);
3507 }
3508 case FORMAT_RG16: {
3509 float r = ((uint16_t *)ptr)[ofs * 2 + 0] / 65535.0f;
3510 float g = ((uint16_t *)ptr)[ofs * 2 + 1] / 65535.0f;
3511 return Color(r, g, 0, 1);
3512 }
3513 case FORMAT_RGB16: {
3514 float r = ((uint16_t *)ptr)[ofs * 3 + 0] / 65535.0f;
3515 float g = ((uint16_t *)ptr)[ofs * 3 + 1] / 65535.0f;
3516 float b = ((uint16_t *)ptr)[ofs * 3 + 2] / 65535.0f;
3517 return Color(r, g, b, 1);
3518 }
3519 case FORMAT_RGBA16: {
3520 float r = ((uint16_t *)ptr)[ofs * 4 + 0] / 65535.0f;
3521 float g = ((uint16_t *)ptr)[ofs * 4 + 1] / 65535.0f;
3522 float b = ((uint16_t *)ptr)[ofs * 4 + 2] / 65535.0f;
3523 float a = ((uint16_t *)ptr)[ofs * 4 + 3] / 65535.0f;
3524 return Color(r, g, b, a);
3525 }
3526 case FORMAT_R16I: {
3527 uint16_t r = ((uint16_t *)ptr)[ofs];
3528 return Color(r, 0, 0, 1);
3529 }
3530 case FORMAT_RG16I: {
3531 uint16_t r = ((uint16_t *)ptr)[ofs * 2 + 0];
3532 uint16_t g = ((uint16_t *)ptr)[ofs * 2 + 1];
3533 return Color(r, g, 0, 1);
3534 }
3535 case FORMAT_RGB16I: {
3536 uint16_t r = ((uint16_t *)ptr)[ofs * 3 + 0];
3537 uint16_t g = ((uint16_t *)ptr)[ofs * 3 + 1];
3538 uint16_t b = ((uint16_t *)ptr)[ofs * 3 + 2];
3539 return Color(r, g, b, 1);
3540 }
3541 case FORMAT_RGBA16I: {
3542 uint16_t r = ((uint16_t *)ptr)[ofs * 4 + 0];
3543 uint16_t g = ((uint16_t *)ptr)[ofs * 4 + 1];
3544 uint16_t b = ((uint16_t *)ptr)[ofs * 4 + 2];
3545 uint16_t a = ((uint16_t *)ptr)[ofs * 4 + 3];
3546 return Color(r, g, b, a);
3547 }
3548
3549 default: {
3550 ERR_FAIL_V_MSG(Color(), "Can't get_pixel() on compressed image, sorry.");
3551 }
3552 }
3553 }
3554
3555 void Image::_set_color_at_ofs(uint8_t *ptr, uint32_t ofs, const Color &p_color) {
3556 switch (format) {
3557 case FORMAT_L8: {
3558 ptr[ofs] = uint8_t(CLAMP(p_color.get_v() * 255.0, 0, 255));
3559 } break;
3560 case FORMAT_LA8: {
3561 ptr[ofs * 2 + 0] = uint8_t(CLAMP(p_color.get_v() * 255.0, 0, 255));
3562 ptr[ofs * 2 + 1] = uint8_t(CLAMP(p_color.a * 255.0, 0, 255));
3563 } break;
3564 case FORMAT_R8: {
3565 ptr[ofs] = uint8_t(CLAMP(p_color.r * 255.0, 0, 255));
3566 } break;
3567 case FORMAT_RG8: {
3568 ptr[ofs * 2 + 0] = uint8_t(CLAMP(p_color.r * 255.0, 0, 255));
3569 ptr[ofs * 2 + 1] = uint8_t(CLAMP(p_color.g * 255.0, 0, 255));
3570 } break;
3571 case FORMAT_RGB8: {
3572 ptr[ofs * 3 + 0] = uint8_t(CLAMP(p_color.r * 255.0, 0, 255));
3573 ptr[ofs * 3 + 1] = uint8_t(CLAMP(p_color.g * 255.0, 0, 255));
3574 ptr[ofs * 3 + 2] = uint8_t(CLAMP(p_color.b * 255.0, 0, 255));
3575 } break;
3576 case FORMAT_RGBA8: {
3577 ptr[ofs * 4 + 0] = uint8_t(CLAMP(p_color.r * 255.0, 0, 255));
3578 ptr[ofs * 4 + 1] = uint8_t(CLAMP(p_color.g * 255.0, 0, 255));
3579 ptr[ofs * 4 + 2] = uint8_t(CLAMP(p_color.b * 255.0, 0, 255));
3580 ptr[ofs * 4 + 3] = uint8_t(CLAMP(p_color.a * 255.0, 0, 255));
3581 } break;
3582 case FORMAT_RGBA4444: {
3583 ((uint16_t *)ptr)[ofs] = color_to_rgba4444(p_color);
3584 } break;
3585 case FORMAT_RGB565: {
3586 ((uint16_t *)ptr)[ofs] = color_to_rgb565(p_color);
3587 } break;
3588 case FORMAT_RF: {
3589 ((float *)ptr)[ofs] = p_color.r;
3590 } break;
3591 case FORMAT_RGF: {
3592 ((float *)ptr)[ofs * 2 + 0] = p_color.r;
3593 ((float *)ptr)[ofs * 2 + 1] = p_color.g;
3594 } break;
3595 case FORMAT_RGBF: {
3596 ((float *)ptr)[ofs * 3 + 0] = p_color.r;
3597 ((float *)ptr)[ofs * 3 + 1] = p_color.g;
3598 ((float *)ptr)[ofs * 3 + 2] = p_color.b;
3599 } break;
3600 case FORMAT_RGBAF: {
3601 ((float *)ptr)[ofs * 4 + 0] = p_color.r;
3602 ((float *)ptr)[ofs * 4 + 1] = p_color.g;
3603 ((float *)ptr)[ofs * 4 + 2] = p_color.b;
3604 ((float *)ptr)[ofs * 4 + 3] = p_color.a;
3605 } break;
3606 case FORMAT_RH: {
3607 ((uint16_t *)ptr)[ofs] = Math::make_half_float(p_color.r);
3608 } break;
3609 case FORMAT_RGH: {
3610 ((uint16_t *)ptr)[ofs * 2 + 0] = Math::make_half_float(p_color.r);
3611 ((uint16_t *)ptr)[ofs * 2 + 1] = Math::make_half_float(p_color.g);
3612 } break;
3613 case FORMAT_RGBH: {
3614 ((uint16_t *)ptr)[ofs * 3 + 0] = Math::make_half_float(p_color.r);
3615 ((uint16_t *)ptr)[ofs * 3 + 1] = Math::make_half_float(p_color.g);
3616 ((uint16_t *)ptr)[ofs * 3 + 2] = Math::make_half_float(p_color.b);
3617 } break;
3618 case FORMAT_RGBAH: {
3619 ((uint16_t *)ptr)[ofs * 4 + 0] = Math::make_half_float(p_color.r);
3620 ((uint16_t *)ptr)[ofs * 4 + 1] = Math::make_half_float(p_color.g);
3621 ((uint16_t *)ptr)[ofs * 4 + 2] = Math::make_half_float(p_color.b);
3622 ((uint16_t *)ptr)[ofs * 4 + 3] = Math::make_half_float(p_color.a);
3623 } break;
3624 case FORMAT_RGBE9995: {
3625 ((uint32_t *)ptr)[ofs] = p_color.to_rgbe9995();
3626 } break;
3627 case FORMAT_R16: {
3628 ((uint16_t *)ptr)[ofs] = uint16_t(CLAMP(p_color.r * 65535.0, 0, 65535));
3629 } break;
3630 case FORMAT_RG16: {
3631 ((uint16_t *)ptr)[ofs * 2 + 0] = uint16_t(CLAMP(p_color.r * 65535.0, 0, 65535));
3632 ((uint16_t *)ptr)[ofs * 2 + 1] = uint16_t(CLAMP(p_color.g * 65535.0, 0, 65535));
3633 } break;
3634 case FORMAT_RGB16: {
3635 ((uint16_t *)ptr)[ofs * 3 + 0] = uint16_t(CLAMP(p_color.r * 65535.0, 0, 65535));
3636 ((uint16_t *)ptr)[ofs * 3 + 1] = uint16_t(CLAMP(p_color.g * 65535.0, 0, 65535));
3637 ((uint16_t *)ptr)[ofs * 3 + 2] = uint16_t(CLAMP(p_color.b * 65535.0, 0, 65535));
3638 } break;
3639 case FORMAT_RGBA16: {
3640 ((uint16_t *)ptr)[ofs * 4 + 0] = uint16_t(CLAMP(p_color.r * 65535.0, 0, 65535));
3641 ((uint16_t *)ptr)[ofs * 4 + 1] = uint16_t(CLAMP(p_color.g * 65535.0, 0, 65535));
3642 ((uint16_t *)ptr)[ofs * 4 + 2] = uint16_t(CLAMP(p_color.b * 65535.0, 0, 65535));
3643 ((uint16_t *)ptr)[ofs * 4 + 3] = uint16_t(CLAMP(p_color.a * 65535.0, 0, 65535));
3644 } break;
3645 case FORMAT_R16I: {
3646 ((uint16_t *)ptr)[ofs] = uint16_t(CLAMP(p_color.r, 0, 65535));
3647 } break;
3648 case FORMAT_RG16I: {
3649 ((uint16_t *)ptr)[ofs * 2 + 0] = uint16_t(CLAMP(p_color.r, 0, 65535));
3650 ((uint16_t *)ptr)[ofs * 2 + 1] = uint16_t(CLAMP(p_color.g, 0, 65535));
3651 } break;
3652 case FORMAT_RGB16I: {
3653 ((uint16_t *)ptr)[ofs * 3 + 0] = uint16_t(CLAMP(p_color.r, 0, 65535));
3654 ((uint16_t *)ptr)[ofs * 3 + 1] = uint16_t(CLAMP(p_color.g, 0, 65535));
3655 ((uint16_t *)ptr)[ofs * 3 + 2] = uint16_t(CLAMP(p_color.b, 0, 65535));
3656 } break;
3657 case FORMAT_RGBA16I: {
3658 ((uint16_t *)ptr)[ofs * 4 + 0] = uint16_t(CLAMP(p_color.r, 0, 65535));
3659 ((uint16_t *)ptr)[ofs * 4 + 1] = uint16_t(CLAMP(p_color.g, 0, 65535));
3660 ((uint16_t *)ptr)[ofs * 4 + 2] = uint16_t(CLAMP(p_color.b, 0, 65535));
3661 ((uint16_t *)ptr)[ofs * 4 + 3] = uint16_t(CLAMP(p_color.a, 0, 65535));
3662 } break;
3663
3664 default: {
3665 ERR_FAIL_MSG("Can't set_pixel() on compressed image, sorry.");
3666 }
3667 }
3668 }
3669
3670 Color Image::get_pixel(int p_x, int p_y) const {
3671 #ifdef DEBUG_ENABLED
3672 ERR_FAIL_INDEX_V(p_x, width, Color());
3673 ERR_FAIL_INDEX_V(p_y, height, Color());
3674 #endif
3675
3676 uint32_t ofs = p_y * width + p_x;
3677 return _get_color_at_ofs(data.ptr(), ofs);
3678 }
3679
3680 void Image::set_pixelv(const Point2i &p_point, const Color &p_color) {
3681 set_pixel(p_point.x, p_point.y, p_color);
3682 }
3683
3684 void Image::set_pixel(int p_x, int p_y, const Color &p_color) {
3685 #ifdef DEBUG_ENABLED
3686 ERR_FAIL_INDEX(p_x, width);
3687 ERR_FAIL_INDEX(p_y, height);
3688 #endif
3689
3690 uint32_t ofs = p_y * width + p_x;
3691 _set_color_at_ofs(data.ptrw(), ofs, p_color);
3692 }
3693
3694 const uint8_t *Image::ptr() const {
3695 return data.ptr();
3696 }
3697
3698 uint8_t *Image::ptrw() {
3699 return data.ptrw();
3700 }
3701
3702 int64_t Image::get_data_size() const {
3703 return data.size();
3704 }
3705
3706 void Image::adjust_bcs(float p_brightness, float p_contrast, float p_saturation) {
3707 ERR_FAIL_COND_MSG(is_compressed(), "Cannot adjust_bcs in compressed image formats.");
3708
3709 uint8_t *w = data.ptrw();
3710 uint32_t pixel_size = get_format_pixel_size(format);
3711 uint32_t pixel_count = data.size() / pixel_size;
3712
3713 for (uint32_t i = 0; i < pixel_count; i++) {
3714 Color c = _get_color_at_ofs(w, i);
3715 Vector3 rgb(c.r, c.g, c.b);
3716
3717 rgb *= p_brightness;
3718 rgb = Vector3(0.5, 0.5, 0.5).lerp(rgb, p_contrast);
3719 float center = (rgb.x + rgb.y + rgb.z) / 3.0;
3720 rgb = Vector3(center, center, center).lerp(rgb, p_saturation);
3721 c.r = rgb.x;
3722 c.g = rgb.y;
3723 c.b = rgb.z;
3724 _set_color_at_ofs(w, i, c);
3725 }
3726 }
3727
3728 Image::UsedChannels Image::detect_used_channels(CompressSource p_source) const {
3729 ERR_FAIL_COND_V(data.is_empty(), USED_CHANNELS_RGBA);
3730 ERR_FAIL_COND_V(is_compressed(), USED_CHANNELS_RGBA);
3731
3732 if (p_source == COMPRESS_SOURCE_NORMAL) {
3733 return USED_CHANNELS_RG; // Normal maps only use RG channels.
3734 }
3735
3736 if (format == FORMAT_L8) {
3737 return USED_CHANNELS_L; // Grayscale only cannot have any channel less.
3738 } else if (format == FORMAT_R8 || format == FORMAT_RH || format == FORMAT_RF || format == FORMAT_R16 || format == FORMAT_R16I) {
3739 return USED_CHANNELS_R; // Red only cannot have any channel less.
3740 }
3741
3742 const bool supports_alpha = format == FORMAT_RGBA8 || format == FORMAT_RGBA4444 || format == FORMAT_RGBAH || format == FORMAT_RGBAF || format == FORMAT_RGBA16 || format == FORMAT_RGBA16I;
3743 bool r = false, g = false, b = false, a = false, c = false;
3744
3745 const uint8_t *data_ptr = data.ptr();
3746 const uint32_t data_total = width * height;
3747
3748 for (uint32_t i = 0; i < data_total; i++) {
3749 Color col = _get_color_at_ofs(data_ptr, i);
3750
3751 if (!r && col.r > 0.001) {
3752 r = true;
3753 }
3754 if (!g && col.g > 0.001) {
3755 g = true;
3756 }
3757 if (!b && col.b > 0.001) {
3758 b = true;
3759 }
3760 if (!a && col.a < 0.999) {
3761 a = true;
3762 }
3763
3764 if (col.r != col.b || col.r != col.g || col.b != col.g) {
3765 c = true; // The image is not grayscale.
3766 }
3767
3768 if (r && g && b && c) {
3769 // All channels are used, no need to continue.
3770 if (!supports_alpha) {
3771 break;
3772 } else if (a) {
3773 break;
3774 }
3775 }
3776 }
3777
3778 UsedChannels used_channels;
3779
3780 if (!c) {
3781 // Uniform RGB (grayscale).
3782 if (a) {
3783 used_channels = USED_CHANNELS_LA;
3784 } else {
3785 used_channels = USED_CHANNELS_L;
3786 }
3787 } else {
3788 // Colored image.
3789 if (a) {
3790 used_channels = USED_CHANNELS_RGBA;
3791 } else if (b) {
3792 used_channels = USED_CHANNELS_RGB;
3793 } else if (g) {
3794 used_channels = USED_CHANNELS_RG;
3795 } else {
3796 used_channels = USED_CHANNELS_R;
3797 }
3798 }
3799
3800 if (p_source == COMPRESS_SOURCE_SRGB && (used_channels == USED_CHANNELS_R || used_channels == USED_CHANNELS_RG)) {
3801 used_channels = USED_CHANNELS_RGB; // R and RG do not support SRGB.
3802 }
3803
3804 return used_channels;
3805 }
3806
3807 void Image::optimize_channels() {
3808 switch (detect_used_channels()) {
3809 case USED_CHANNELS_L:
3810 convert(FORMAT_L8);
3811 break;
3812 case USED_CHANNELS_LA:
3813 convert(FORMAT_LA8);
3814 break;
3815 case USED_CHANNELS_R:
3816 convert(FORMAT_R8);
3817 break;
3818 case USED_CHANNELS_RG:
3819 convert(FORMAT_RG8);
3820 break;
3821 case USED_CHANNELS_RGB:
3822 convert(FORMAT_RGB8);
3823 break;
3824 case USED_CHANNELS_RGBA:
3825 convert(FORMAT_RGBA8);
3826 break;
3827 }
3828 }
3829
3830 void Image::_bind_methods() {
3831 ClassDB::bind_method(D_METHOD("get_width"), &Image::get_width);
3832 ClassDB::bind_method(D_METHOD("get_height"), &Image::get_height);
3833 ClassDB::bind_method(D_METHOD("get_size"), &Image::get_size);
3834 ClassDB::bind_method(D_METHOD("has_mipmaps"), &Image::has_mipmaps);
3835 ClassDB::bind_method(D_METHOD("get_format"), &Image::get_format);
3836 ClassDB::bind_method(D_METHOD("get_data"), &Image::get_data);
3837 ClassDB::bind_method(D_METHOD("get_data_size"), &Image::get_data_size);
3838
3839 ClassDB::bind_method(D_METHOD("convert", "format"), &Image::convert);
3840
3841 ClassDB::bind_method(D_METHOD("get_mipmap_count"), &Image::get_mipmap_count);
3842 ClassDB::bind_method(D_METHOD("get_mipmap_offset", "mipmap"), &Image::get_mipmap_offset);
3843
3844 ClassDB::bind_method(D_METHOD("resize_to_po2", "square", "interpolation"), &Image::resize_to_po2, DEFVAL(false), DEFVAL(INTERPOLATE_BILINEAR));
3845 ClassDB::bind_method(D_METHOD("resize", "width", "height", "interpolation"), &Image::resize, DEFVAL(INTERPOLATE_BILINEAR));
3846 ClassDB::bind_method(D_METHOD("shrink_x2"), &Image::shrink_x2);
3847
3848 ClassDB::bind_method(D_METHOD("crop", "width", "height"), &Image::crop);
3849 ClassDB::bind_method(D_METHOD("flip_x"), &Image::flip_x);
3850 ClassDB::bind_method(D_METHOD("flip_y"), &Image::flip_y);
3851 ClassDB::bind_method(D_METHOD("generate_mipmaps", "renormalize"), &Image::generate_mipmaps, DEFVAL(false));
3852 ClassDB::bind_method(D_METHOD("clear_mipmaps"), &Image::clear_mipmaps);
3853
3854 #ifndef DISABLE_DEPRECATED
3855 ClassDB::bind_static_method("Image", D_METHOD("create", "width", "height", "use_mipmaps", "format"), &Image::create_empty);
3856 #endif
3857 ClassDB::bind_static_method("Image", D_METHOD("create_empty", "width", "height", "use_mipmaps", "format"), &Image::create_empty);
3858 ClassDB::bind_static_method("Image", D_METHOD("create_from_data", "width", "height", "use_mipmaps", "format", "data"), &Image::create_from_data);
3859 ClassDB::bind_method(D_METHOD("set_data", "width", "height", "use_mipmaps", "format", "data"), &Image::set_data);
3860
3861 ClassDB::bind_method(D_METHOD("is_empty"), &Image::is_empty);
3862
3863 ClassDB::bind_method(D_METHOD("load", "path"), &Image::load);
3864 ClassDB::bind_static_method("Image", D_METHOD("load_from_file", "path"), &Image::load_from_file);
3865 ClassDB::bind_method(D_METHOD("save_png", "path"), &Image::save_png);
3866 ClassDB::bind_method(D_METHOD("save_png_to_buffer"), &Image::save_png_to_buffer);
3867 ClassDB::bind_method(D_METHOD("save_jpg", "path", "quality"), &Image::save_jpg, DEFVAL(0.75));
3868 ClassDB::bind_method(D_METHOD("save_jpg_to_buffer", "quality"), &Image::save_jpg_to_buffer, DEFVAL(0.75));
3869 ClassDB::bind_method(D_METHOD("save_exr", "path", "grayscale"), &Image::save_exr, DEFVAL(false));
3870 ClassDB::bind_method(D_METHOD("save_exr_to_buffer", "grayscale"), &Image::save_exr_to_buffer, DEFVAL(false));
3871 ClassDB::bind_method(D_METHOD("save_dds", "path"), &Image::save_dds);
3872 ClassDB::bind_method(D_METHOD("save_dds_to_buffer"), &Image::save_dds_to_buffer);
3873
3874 ClassDB::bind_method(D_METHOD("save_webp", "path", "lossy", "quality"), &Image::save_webp, DEFVAL(false), DEFVAL(0.75f));
3875 ClassDB::bind_method(D_METHOD("save_webp_to_buffer", "lossy", "quality"), &Image::save_webp_to_buffer, DEFVAL(false), DEFVAL(0.75f));
3876
3877 ClassDB::bind_method(D_METHOD("detect_alpha"), &Image::detect_alpha);
3878 ClassDB::bind_method(D_METHOD("is_invisible"), &Image::is_invisible);
3879
3880 ClassDB::bind_method(D_METHOD("detect_used_channels", "source"), &Image::detect_used_channels, DEFVAL(COMPRESS_SOURCE_GENERIC));
3881 ClassDB::bind_method(D_METHOD("compress", "mode", "source", "astc_format"), &Image::compress, DEFVAL(COMPRESS_SOURCE_GENERIC), DEFVAL(ASTC_FORMAT_4x4));
3882 ClassDB::bind_method(D_METHOD("compress_from_channels", "mode", "channels", "astc_format"), &Image::compress_from_channels, DEFVAL(ASTC_FORMAT_4x4));
3883 ClassDB::bind_method(D_METHOD("decompress"), &Image::decompress);
3884 ClassDB::bind_method(D_METHOD("is_compressed"), &Image::is_compressed);
3885
3886 ClassDB::bind_method(D_METHOD("rotate_90", "direction"), &Image::rotate_90);
3887 ClassDB::bind_method(D_METHOD("rotate_180"), &Image::rotate_180);
3888
3889 ClassDB::bind_method(D_METHOD("fix_alpha_edges"), &Image::fix_alpha_edges);
3890 ClassDB::bind_method(D_METHOD("premultiply_alpha"), &Image::premultiply_alpha);
3891 ClassDB::bind_method(D_METHOD("srgb_to_linear"), &Image::srgb_to_linear);
3892 ClassDB::bind_method(D_METHOD("linear_to_srgb"), &Image::linear_to_srgb);
3893 ClassDB::bind_method(D_METHOD("normal_map_to_xy"), &Image::normal_map_to_xy);
3894 ClassDB::bind_method(D_METHOD("rgbe_to_srgb"), &Image::rgbe_to_srgb);
3895 ClassDB::bind_method(D_METHOD("bump_map_to_normal_map", "bump_scale"), &Image::bump_map_to_normal_map, DEFVAL(1.0));
3896
3897 ClassDB::bind_method(D_METHOD("compute_image_metrics", "compared_image", "use_luma"), &Image::compute_image_metrics);
3898
3899 ClassDB::bind_method(D_METHOD("blit_rect", "src", "src_rect", "dst"), &Image::blit_rect);
3900 ClassDB::bind_method(D_METHOD("blit_rect_mask", "src", "mask", "src_rect", "dst"), &Image::blit_rect_mask);
3901 ClassDB::bind_method(D_METHOD("blend_rect", "src", "src_rect", "dst"), &Image::blend_rect);
3902 ClassDB::bind_method(D_METHOD("blend_rect_mask", "src", "mask", "src_rect", "dst"), &Image::blend_rect_mask);
3903 ClassDB::bind_method(D_METHOD("fill", "color"), &Image::fill);
3904 ClassDB::bind_method(D_METHOD("fill_rect", "rect", "color"), &Image::fill_rect);
3905
3906 ClassDB::bind_method(D_METHOD("get_used_rect"), &Image::get_used_rect);
3907 ClassDB::bind_method(D_METHOD("get_region", "region"), &Image::get_region);
3908
3909 ClassDB::bind_method(D_METHOD("copy_from", "src"), &Image::copy_internals_from);
3910
3911 ClassDB::bind_method(D_METHOD("_set_data", "data"), &Image::_set_data);
3912 ClassDB::bind_method(D_METHOD("_get_data"), &Image::_get_data);
3913
3914 ClassDB::bind_method(D_METHOD("get_pixelv", "point"), &Image::get_pixelv);
3915 ClassDB::bind_method(D_METHOD("get_pixel", "x", "y"), &Image::get_pixel);
3916 ClassDB::bind_method(D_METHOD("set_pixelv", "point", "color"), &Image::set_pixelv);
3917 ClassDB::bind_method(D_METHOD("set_pixel", "x", "y", "color"), &Image::set_pixel);
3918
3919 ClassDB::bind_method(D_METHOD("adjust_bcs", "brightness", "contrast", "saturation"), &Image::adjust_bcs);
3920
3921 ClassDB::bind_method(D_METHOD("load_png_from_buffer", "buffer"), &Image::load_png_from_buffer);
3922 ClassDB::bind_method(D_METHOD("load_jpg_from_buffer", "buffer"), &Image::load_jpg_from_buffer);
3923 ClassDB::bind_method(D_METHOD("load_webp_from_buffer", "buffer"), &Image::load_webp_from_buffer);
3924 ClassDB::bind_method(D_METHOD("load_tga_from_buffer", "buffer"), &Image::load_tga_from_buffer);
3925 ClassDB::bind_method(D_METHOD("load_bmp_from_buffer", "buffer"), &Image::load_bmp_from_buffer);
3926 ClassDB::bind_method(D_METHOD("load_ktx_from_buffer", "buffer"), &Image::load_ktx_from_buffer);
3927 ClassDB::bind_method(D_METHOD("load_dds_from_buffer", "buffer"), &Image::load_dds_from_buffer);
3928 ClassDB::bind_method(D_METHOD("load_exr_from_buffer", "buffer"), &Image::load_exr_from_buffer);
3929
3930 ClassDB::bind_method(D_METHOD("load_svg_from_buffer", "buffer", "scale"), &Image::load_svg_from_buffer, DEFVAL(1.0));
3931 ClassDB::bind_method(D_METHOD("load_svg_from_string", "svg_str", "scale"), &Image::load_svg_from_string, DEFVAL(1.0));
3932
3933 ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE), "_set_data", "_get_data");
3934
3935 BIND_CONSTANT(MAX_WIDTH);
3936 BIND_CONSTANT(MAX_HEIGHT);
3937
3938 BIND_ENUM_CONSTANT(FORMAT_L8);
3939 BIND_ENUM_CONSTANT(FORMAT_LA8);
3940 BIND_ENUM_CONSTANT(FORMAT_R8);
3941 BIND_ENUM_CONSTANT(FORMAT_RG8);
3942 BIND_ENUM_CONSTANT(FORMAT_RGB8);
3943 BIND_ENUM_CONSTANT(FORMAT_RGBA8);
3944 BIND_ENUM_CONSTANT(FORMAT_RGBA4444);
3945 BIND_ENUM_CONSTANT(FORMAT_RGB565);
3946 BIND_ENUM_CONSTANT(FORMAT_RF);
3947 BIND_ENUM_CONSTANT(FORMAT_RGF);
3948 BIND_ENUM_CONSTANT(FORMAT_RGBF);
3949 BIND_ENUM_CONSTANT(FORMAT_RGBAF);
3950 BIND_ENUM_CONSTANT(FORMAT_RH);
3951 BIND_ENUM_CONSTANT(FORMAT_RGH);
3952 BIND_ENUM_CONSTANT(FORMAT_RGBH);
3953 BIND_ENUM_CONSTANT(FORMAT_RGBAH);
3954 BIND_ENUM_CONSTANT(FORMAT_RGBE9995);
3955 BIND_ENUM_CONSTANT(FORMAT_DXT1);
3956 BIND_ENUM_CONSTANT(FORMAT_DXT3);
3957 BIND_ENUM_CONSTANT(FORMAT_DXT5);
3958 BIND_ENUM_CONSTANT(FORMAT_RGTC_R);
3959 BIND_ENUM_CONSTANT(FORMAT_RGTC_RG);
3960 BIND_ENUM_CONSTANT(FORMAT_BPTC_RGBA);
3961 BIND_ENUM_CONSTANT(FORMAT_BPTC_RGBF);
3962 BIND_ENUM_CONSTANT(FORMAT_BPTC_RGBFU);
3963 BIND_ENUM_CONSTANT(FORMAT_ETC);
3964 BIND_ENUM_CONSTANT(FORMAT_ETC2_R11);
3965 BIND_ENUM_CONSTANT(FORMAT_ETC2_R11S);
3966 BIND_ENUM_CONSTANT(FORMAT_ETC2_RG11);
3967 BIND_ENUM_CONSTANT(FORMAT_ETC2_RG11S);
3968 BIND_ENUM_CONSTANT(FORMAT_ETC2_RGB8);
3969 BIND_ENUM_CONSTANT(FORMAT_ETC2_RGBA8);
3970 BIND_ENUM_CONSTANT(FORMAT_ETC2_RGB8A1);
3971 BIND_ENUM_CONSTANT(FORMAT_ETC2_RA_AS_RG);
3972 BIND_ENUM_CONSTANT(FORMAT_DXT5_RA_AS_RG);
3973 BIND_ENUM_CONSTANT(FORMAT_ASTC_4x4);
3974 BIND_ENUM_CONSTANT(FORMAT_ASTC_4x4_HDR);
3975 BIND_ENUM_CONSTANT(FORMAT_ASTC_8x8);
3976 BIND_ENUM_CONSTANT(FORMAT_ASTC_8x8_HDR);
3977 BIND_ENUM_CONSTANT(FORMAT_R16);
3978 BIND_ENUM_CONSTANT(FORMAT_RG16);
3979 BIND_ENUM_CONSTANT(FORMAT_RGB16);
3980 BIND_ENUM_CONSTANT(FORMAT_RGBA16);
3981 BIND_ENUM_CONSTANT(FORMAT_R16I);
3982 BIND_ENUM_CONSTANT(FORMAT_RG16I);
3983 BIND_ENUM_CONSTANT(FORMAT_RGB16I);
3984 BIND_ENUM_CONSTANT(FORMAT_RGBA16I);
3985 BIND_ENUM_CONSTANT(FORMAT_MAX);
3986
3987 BIND_ENUM_CONSTANT(INTERPOLATE_NEAREST);
3988 BIND_ENUM_CONSTANT(INTERPOLATE_BILINEAR);
3989 BIND_ENUM_CONSTANT(INTERPOLATE_CUBIC);
3990 BIND_ENUM_CONSTANT(INTERPOLATE_TRILINEAR);
3991 BIND_ENUM_CONSTANT(INTERPOLATE_LANCZOS);
3992
3993 BIND_ENUM_CONSTANT(ALPHA_NONE);
3994 BIND_ENUM_CONSTANT(ALPHA_BIT);
3995 BIND_ENUM_CONSTANT(ALPHA_BLEND);
3996
3997 BIND_ENUM_CONSTANT(COMPRESS_S3TC);
3998 BIND_ENUM_CONSTANT(COMPRESS_ETC);
3999 BIND_ENUM_CONSTANT(COMPRESS_ETC2);
4000 BIND_ENUM_CONSTANT(COMPRESS_BPTC);
4001 BIND_ENUM_CONSTANT(COMPRESS_ASTC);
4002 BIND_ENUM_CONSTANT(COMPRESS_MAX);
4003
4004 BIND_ENUM_CONSTANT(USED_CHANNELS_L);
4005 BIND_ENUM_CONSTANT(USED_CHANNELS_LA);
4006 BIND_ENUM_CONSTANT(USED_CHANNELS_R);
4007 BIND_ENUM_CONSTANT(USED_CHANNELS_RG);
4008 BIND_ENUM_CONSTANT(USED_CHANNELS_RGB);
4009 BIND_ENUM_CONSTANT(USED_CHANNELS_RGBA);
4010
4011 BIND_ENUM_CONSTANT(COMPRESS_SOURCE_GENERIC);
4012 BIND_ENUM_CONSTANT(COMPRESS_SOURCE_SRGB);
4013 BIND_ENUM_CONSTANT(COMPRESS_SOURCE_NORMAL);
4014
4015 BIND_ENUM_CONSTANT(ASTC_FORMAT_4x4);
4016 BIND_ENUM_CONSTANT(ASTC_FORMAT_8x8);
4017 }
4018
4019 void Image::normal_map_to_xy() {
4020 convert(Image::FORMAT_RGBA8);
4021
4022 {
4023 int len = data.size() / 4;
4024 uint8_t *data_ptr = data.ptrw();
4025
4026 for (int i = 0; i < len; i++) {
4027 data_ptr[(i << 2) + 3] = data_ptr[(i << 2) + 0]; //x to w
4028 data_ptr[(i << 2) + 0] = data_ptr[(i << 2) + 1]; //y to xz
4029 data_ptr[(i << 2) + 2] = data_ptr[(i << 2) + 1];
4030 }
4031 }
4032
4033 convert(Image::FORMAT_LA8);
4034 }
4035
4036 Ref<Image> Image::rgbe_to_srgb() {
4037 if (data.is_empty()) {
4038 return Ref<Image>();
4039 }
4040
4041 ERR_FAIL_COND_V(format != FORMAT_RGBE9995, Ref<Image>());
4042
4043 Ref<Image> new_image = create_empty(width, height, false, Image::FORMAT_RGB8);
4044
4045 for (int row = 0; row < height; row++) {
4046 for (int col = 0; col < width; col++) {
4047 new_image->set_pixel(col, row, get_pixel(col, row).linear_to_srgb());
4048 }
4049 }
4050
4051 if (has_mipmaps()) {
4052 new_image->generate_mipmaps();
4053 }
4054
4055 return new_image;
4056 }
4057
4058 Ref<Image> Image::get_image_from_mipmap(int p_mipmap) const {
4059 int64_t ofs, size;
4060 int w, h;
4061 get_mipmap_offset_size_and_dimensions(p_mipmap, ofs, size, w, h);
4062
4063 Vector<uint8_t> new_data;
4064 new_data.resize(size);
4065
4066 {
4067 uint8_t *wr = new_data.ptrw();
4068 const uint8_t *rd = data.ptr();
4069 memcpy(wr, rd + ofs, size);
4070 }
4071
4072 Ref<Image> image;
4073 image.instantiate();
4074 image->width = w;
4075 image->height = h;
4076 image->format = format;
4077 image->data = new_data;
4078
4079 image->mipmaps = false;
4080 return image;
4081 }
4082
4083 void Image::bump_map_to_normal_map(float bump_scale) {
4084 ERR_FAIL_COND(is_compressed());
4085 clear_mipmaps();
4086 convert(Image::FORMAT_RF);
4087
4088 Vector<uint8_t> result_image; //rgba output
4089 result_image.resize(width * height * 4);
4090
4091 {
4092 const uint8_t *rp = data.ptr();
4093 uint8_t *wp = result_image.ptrw();
4094
4095 ERR_FAIL_NULL(rp);
4096
4097 unsigned char *write_ptr = wp;
4098 float *read_ptr = (float *)rp;
4099
4100 for (int ty = 0; ty < height; ty++) {
4101 int py = ty + 1;
4102 if (py >= height) {
4103 py -= height;
4104 }
4105
4106 for (int tx = 0; tx < width; tx++) {
4107 int px = tx + 1;
4108 if (px >= width) {
4109 px -= width;
4110 }
4111 float here = read_ptr[ty * width + tx];
4112 float to_right = read_ptr[ty * width + px];
4113 float above = read_ptr[py * width + tx];
4114 Vector3 up = Vector3(0, 1, (here - above) * bump_scale);
4115 Vector3 across = Vector3(1, 0, (to_right - here) * bump_scale);
4116
4117 Vector3 normal = across.cross(up);
4118 normal.normalize();
4119
4120 write_ptr[((ty * width + tx) << 2) + 0] = (127.5 + normal.x * 127.5);
4121 write_ptr[((ty * width + tx) << 2) + 1] = (127.5 + normal.y * 127.5);
4122 write_ptr[((ty * width + tx) << 2) + 2] = (127.5 + normal.z * 127.5);
4123 write_ptr[((ty * width + tx) << 2) + 3] = 255;
4124 }
4125 }
4126 }
4127 format = FORMAT_RGBA8;
4128 data = result_image;
4129 }
4130
4131 bool Image::detect_signed(bool p_include_mips) const {
4132 ERR_FAIL_COND_V(is_compressed(), false);
4133
4134 if (format >= Image::FORMAT_RH && format <= Image::FORMAT_RGBAH) {
4135 const uint16_t *img_data = reinterpret_cast<const uint16_t *>(data.ptr());
4136 const uint64_t img_size = p_include_mips ? (data.size() / 2) : (width * height * get_format_pixel_size(format) / 2);
4137
4138 for (uint64_t i = 0; i < img_size; i++) {
4139 if ((img_data[i] & 0x8000) != 0 && (img_data[i] & 0x7fff) != 0) {
4140 return true;
4141 }
4142 }
4143
4144 } else if (format >= Image::FORMAT_RF && format <= Image::FORMAT_RGBAF) {
4145 const uint32_t *img_data = reinterpret_cast<const uint32_t *>(data.ptr());
4146 const uint64_t img_size = p_include_mips ? (data.size() / 4) : (width * height * get_format_pixel_size(format) / 4);
4147
4148 for (uint64_t i = 0; i < img_size; i++) {
4149 if ((img_data[i] & 0x80000000) != 0 && (img_data[i] & 0x7fffffff) != 0) {
4150 return true;
4151 }
4152 }
4153 }
4154
4155 return false;
4156 }
4157
4158 void Image::srgb_to_linear() {
4159 if (data.is_empty()) {
4160 return;
4161 }
4162
4163 static const uint8_t srgb2lin[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 22, 22, 23, 23, 24, 24, 25, 26, 26, 27, 27, 28, 29, 29, 30, 31, 31, 32, 33, 33, 34, 35, 36, 36, 37, 38, 38, 39, 40, 41, 42, 42, 43, 44, 45, 46, 47, 47, 48, 49, 50, 51, 52, 53, 54, 55, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 70, 71, 72, 73, 74, 75, 76, 77, 78, 80, 81, 82, 83, 84, 85, 87, 88, 89, 90, 92, 93, 94, 95, 97, 98, 99, 101, 102, 103, 105, 106, 107, 109, 110, 112, 113, 114, 116, 117, 119, 120, 122, 123, 125, 126, 128, 129, 131, 132, 134, 135, 137, 139, 140, 142, 144, 145, 147, 148, 150, 152, 153, 155, 157, 159, 160, 162, 164, 166, 167, 169, 171, 173, 175, 176, 178, 180, 182, 184, 186, 188, 190, 192, 193, 195, 197, 199, 201, 203, 205, 207, 209, 211, 213, 215, 218, 220, 222, 224, 226, 228, 230, 232, 235, 237, 239, 241, 243, 245, 248, 250, 252, 255 };
4164
4165 ERR_FAIL_COND(format != FORMAT_RGB8 && format != FORMAT_RGBA8);
4166
4167 if (format == FORMAT_RGBA8) {
4168 int len = data.size() / 4;
4169 uint8_t *data_ptr = data.ptrw();
4170
4171 for (int i = 0; i < len; i++) {
4172 data_ptr[(i << 2) + 0] = srgb2lin[data_ptr[(i << 2) + 0]];
4173 data_ptr[(i << 2) + 1] = srgb2lin[data_ptr[(i << 2) + 1]];
4174 data_ptr[(i << 2) + 2] = srgb2lin[data_ptr[(i << 2) + 2]];
4175 }
4176
4177 } else if (format == FORMAT_RGB8) {
4178 int len = data.size() / 3;
4179 uint8_t *data_ptr = data.ptrw();
4180
4181 for (int i = 0; i < len; i++) {
4182 data_ptr[(i * 3) + 0] = srgb2lin[data_ptr[(i * 3) + 0]];
4183 data_ptr[(i * 3) + 1] = srgb2lin[data_ptr[(i * 3) + 1]];
4184 data_ptr[(i * 3) + 2] = srgb2lin[data_ptr[(i * 3) + 2]];
4185 }
4186 }
4187 }
4188
4189 void Image::linear_to_srgb() {
4190 if (data.is_empty()) {
4191 return;
4192 }
4193
4194 static const uint8_t lin2srgb[256] = { 0, 12, 21, 28, 33, 38, 42, 46, 49, 52, 55, 58, 61, 63, 66, 68, 70, 73, 75, 77, 79, 81, 82, 84, 86, 88, 89, 91, 93, 94, 96, 97, 99, 100, 102, 103, 104, 106, 107, 109, 110, 111, 112, 114, 115, 116, 117, 118, 120, 121, 122, 123, 124, 125, 126, 127, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 151, 152, 153, 154, 155, 156, 157, 157, 158, 159, 160, 161, 161, 162, 163, 164, 165, 165, 166, 167, 168, 168, 169, 170, 171, 171, 172, 173, 174, 174, 175, 176, 176, 177, 178, 179, 179, 180, 181, 181, 182, 183, 183, 184, 185, 185, 186, 187, 187, 188, 189, 189, 190, 191, 191, 192, 193, 193, 194, 194, 195, 196, 196, 197, 197, 198, 199, 199, 200, 201, 201, 202, 202, 203, 204, 204, 205, 205, 206, 206, 207, 208, 208, 209, 209, 210, 210, 211, 212, 212, 213, 213, 214, 214, 215, 215, 216, 217, 217, 218, 218, 219, 219, 220, 220, 221, 221, 222, 222, 223, 223, 224, 224, 225, 226, 226, 227, 227, 228, 228, 229, 229, 230, 230, 231, 231, 232, 232, 233, 233, 234, 234, 235, 235, 236, 236, 237, 237, 237, 238, 238, 239, 239, 240, 240, 241, 241, 242, 242, 243, 243, 244, 244, 245, 245, 245, 246, 246, 247, 247, 248, 248, 249, 249, 250, 250, 251, 251, 251, 252, 252, 253, 253, 254, 254, 255 };
4195
4196 ERR_FAIL_COND(format != FORMAT_RGB8 && format != FORMAT_RGBA8);
4197
4198 if (format == FORMAT_RGBA8) {
4199 int len = data.size() / 4;
4200 uint8_t *data_ptr = data.ptrw();
4201
4202 for (int i = 0; i < len; i++) {
4203 data_ptr[(i << 2) + 0] = lin2srgb[data_ptr[(i << 2) + 0]];
4204 data_ptr[(i << 2) + 1] = lin2srgb[data_ptr[(i << 2) + 1]];
4205 data_ptr[(i << 2) + 2] = lin2srgb[data_ptr[(i << 2) + 2]];
4206 }
4207
4208 } else if (format == FORMAT_RGB8) {
4209 int len = data.size() / 3;
4210 uint8_t *data_ptr = data.ptrw();
4211
4212 for (int i = 0; i < len; i++) {
4213 data_ptr[(i * 3) + 0] = lin2srgb[data_ptr[(i * 3) + 0]];
4214 data_ptr[(i * 3) + 1] = lin2srgb[data_ptr[(i * 3) + 1]];
4215 data_ptr[(i * 3) + 2] = lin2srgb[data_ptr[(i * 3) + 2]];
4216 }
4217 }
4218 }
4219
4220 void Image::premultiply_alpha() {
4221 if (data.is_empty()) {
4222 return;
4223 }
4224
4225 if (format != FORMAT_RGBA8) {
4226 return; //not needed
4227 }
4228
4229 uint8_t *data_ptr = data.ptrw();
4230
4231 for (int i = 0; i < height; i++) {
4232 for (int j = 0; j < width; j++) {
4233 uint8_t *ptr = &data_ptr[(i * width + j) * 4];
4234
4235 ptr[0] = (uint16_t(ptr[0]) * uint16_t(ptr[3]) + 255U) >> 8;
4236 ptr[1] = (uint16_t(ptr[1]) * uint16_t(ptr[3]) + 255U) >> 8;
4237 ptr[2] = (uint16_t(ptr[2]) * uint16_t(ptr[3]) + 255U) >> 8;
4238 }
4239 }
4240 }
4241
4242 void Image::fix_alpha_edges() {
4243 if (data.is_empty()) {
4244 return;
4245 }
4246
4247 if (format != FORMAT_RGBA8) {
4248 return; //not needed
4249 }
4250
4251 Vector<uint8_t> dcopy = data;
4252 const uint8_t *srcptr = dcopy.ptr();
4253
4254 uint8_t *data_ptr = data.ptrw();
4255
4256 const int max_radius = 4;
4257 const int alpha_threshold = 20;
4258 const int max_dist = 0x7FFFFFFF;
4259
4260 for (int i = 0; i < height; i++) {
4261 for (int j = 0; j < width; j++) {
4262 const uint8_t *rptr = &srcptr[(i * width + j) * 4];
4263 uint8_t *wptr = &data_ptr[(i * width + j) * 4];
4264
4265 if (rptr[3] >= alpha_threshold) {
4266 continue;
4267 }
4268
4269 int closest_dist = max_dist;
4270 uint8_t closest_color[3] = { 0 };
4271
4272 int from_x = MAX(0, j - max_radius);
4273 int to_x = MIN(width - 1, j + max_radius);
4274 int from_y = MAX(0, i - max_radius);
4275 int to_y = MIN(height - 1, i + max_radius);
4276
4277 for (int k = from_y; k <= to_y; k++) {
4278 for (int l = from_x; l <= to_x; l++) {
4279 int dy = i - k;
4280 int dx = j - l;
4281 int dist = dy * dy + dx * dx;
4282 if (dist >= closest_dist) {
4283 continue;
4284 }
4285
4286 const uint8_t *rp2 = &srcptr[(k * width + l) << 2];
4287
4288 if (rp2[3] < alpha_threshold) {
4289 continue;
4290 }
4291
4292 closest_dist = dist;
4293 closest_color[0] = rp2[0];
4294 closest_color[1] = rp2[1];
4295 closest_color[2] = rp2[2];
4296 }
4297 }
4298
4299 if (closest_dist != max_dist) {
4300 wptr[0] = closest_color[0];
4301 wptr[1] = closest_color[1];
4302 wptr[2] = closest_color[2];
4303 }
4304 }
4305 }
4306 }
4307
4308 String Image::get_format_name(Format p_format) {
4309 ERR_FAIL_INDEX_V(p_format, FORMAT_MAX, String());
4310 return format_names[p_format];
4311 }
4312
4313 uint32_t Image::get_format_component_mask(Format p_format) {
4314 const uint32_t r = 1;
4315 const uint32_t rg = 3;
4316 const uint32_t rgb = 7;
4317 const uint32_t rgba = 15;
4318
4319 switch (p_format) {
4320 case FORMAT_L8:
4321 return rgb;
4322 case FORMAT_LA8:
4323 return rgba;
4324 case FORMAT_R8:
4325 return r;
4326 case FORMAT_RG8:
4327 return rg;
4328 case FORMAT_RGB8:
4329 return rgb;
4330 case FORMAT_RGBA8:
4331 return rgba;
4332 case FORMAT_RGBA4444:
4333 return rgba;
4334 case FORMAT_RGB565:
4335 return rgb;
4336 case FORMAT_RF:
4337 return r;
4338 case FORMAT_RGF:
4339 return rg;
4340 case FORMAT_RGBF:
4341 return rgb;
4342 case FORMAT_RGBAF:
4343 return rgba;
4344 case FORMAT_RH:
4345 return r;
4346 case FORMAT_RGH:
4347 return rg;
4348 case FORMAT_RGBH:
4349 return rgb;
4350 case FORMAT_RGBAH:
4351 return rgba;
4352 case FORMAT_RGBE9995:
4353 return rgb;
4354 case FORMAT_DXT1:
4355 return rgb;
4356 case FORMAT_DXT3:
4357 return rgba;
4358 case FORMAT_DXT5:
4359 return rgba;
4360 case FORMAT_RGTC_R:
4361 return r;
4362 case FORMAT_RGTC_RG:
4363 return rg;
4364 case FORMAT_BPTC_RGBA:
4365 return rgba;
4366 case FORMAT_BPTC_RGBF:
4367 return rgb;
4368 case FORMAT_BPTC_RGBFU:
4369 return rgb;
4370 case FORMAT_ETC:
4371 return rgb;
4372 case FORMAT_ETC2_R11:
4373 return r;
4374 case FORMAT_ETC2_R11S:
4375 return r;
4376 case FORMAT_ETC2_RG11:
4377 return rg;
4378 case FORMAT_ETC2_RG11S:
4379 return rg;
4380 case FORMAT_ETC2_RGB8:
4381 return rgb;
4382 case FORMAT_ETC2_RGBA8:
4383 return rgba;
4384 case FORMAT_ETC2_RGB8A1:
4385 return rgba;
4386 case FORMAT_ETC2_RA_AS_RG:
4387 return rg;
4388 case FORMAT_DXT5_RA_AS_RG:
4389 return rg;
4390 case FORMAT_ASTC_4x4:
4391 return rgba;
4392 case FORMAT_ASTC_4x4_HDR:
4393 return rgba;
4394 case FORMAT_ASTC_8x8:
4395 return rgba;
4396 case FORMAT_ASTC_8x8_HDR:
4397 return rgba;
4398 case FORMAT_R16:
4399 return r;
4400 case FORMAT_RG16:
4401 return rg;
4402 case FORMAT_RGB16:
4403 return rgb;
4404 case FORMAT_RGBA16:
4405 return rgba;
4406 case FORMAT_R16I:
4407 return r;
4408 case FORMAT_RG16I:
4409 return rg;
4410 case FORMAT_RGB16I:
4411 return rgb;
4412 case FORMAT_RGBA16I:
4413 return rgba;
4414 default:
4415 ERR_PRINT("Unhandled format.");
4416 return rgba;
4417 }
4418 }
4419
4420 Error Image::load_png_from_buffer(const Vector<uint8_t> &p_array) {
4421 return _load_from_buffer(p_array, _png_mem_loader_func);
4422 }
4423
4424 Error Image::load_jpg_from_buffer(const Vector<uint8_t> &p_array) {
4425 return _load_from_buffer(p_array, _jpg_mem_loader_func);
4426 }
4427
4428 Error Image::load_exr_from_buffer(const Vector<uint8_t> &p_array) {
4429 ERR_FAIL_NULL_V_MSG(
4430 _exr_mem_loader_func,
4431 ERR_UNAVAILABLE,
4432 "The TinyEXR module isn't enabled. Recompile the Godot editor or export template binary with the `tinyexr_export_templates=yes` SCons option.");
4433 return _load_from_buffer(p_array, _exr_mem_loader_func);
4434 }
4435
4436 Error Image::load_webp_from_buffer(const Vector<uint8_t> &p_array) {
4437 return _load_from_buffer(p_array, _webp_mem_loader_func);
4438 }
4439
4440 Error Image::load_tga_from_buffer(const Vector<uint8_t> &p_array) {
4441 ERR_FAIL_NULL_V_MSG(
4442 _tga_mem_loader_func,
4443 ERR_UNAVAILABLE,
4444 "The TGA module isn't enabled. Recompile the Godot editor or export template binary with the `module_tga_enabled=yes` SCons option.");
4445 return _load_from_buffer(p_array, _tga_mem_loader_func);
4446 }
4447
4448 Error Image::load_bmp_from_buffer(const Vector<uint8_t> &p_array) {
4449 ERR_FAIL_NULL_V_MSG(
4450 _bmp_mem_loader_func,
4451 ERR_UNAVAILABLE,
4452 "The BMP module isn't enabled. Recompile the Godot editor or export template binary with the `module_bmp_enabled=yes` SCons option.");
4453 return _load_from_buffer(p_array, _bmp_mem_loader_func);
4454 }
4455
4456 Error Image::load_dds_from_buffer(const Vector<uint8_t> &p_array) {
4457 ERR_FAIL_NULL_V_MSG(
4458 _dds_mem_loader_func,
4459 ERR_UNAVAILABLE,
4460 "The DDS module isn't enabled. Recompile the Godot editor or export template binary with the `module_dds_enabled=yes` SCons option.");
4461 return _load_from_buffer(p_array, _dds_mem_loader_func);
4462 }
4463
4464 Error Image::load_svg_from_buffer(const Vector<uint8_t> &p_array, float scale) {
4465 ERR_FAIL_NULL_V_MSG(
4466 _svg_scalable_mem_loader_func,
4467 ERR_UNAVAILABLE,
4468 "The SVG module isn't enabled. Recompile the Godot editor or export template binary with the `module_svg_enabled=yes` SCons option.");
4469
4470 int buffer_size = p_array.size();
4471
4472 ERR_FAIL_COND_V(buffer_size == 0, ERR_INVALID_PARAMETER);
4473
4474 Ref<Image> image = _svg_scalable_mem_loader_func(p_array.ptr(), buffer_size, scale);
4475 ERR_FAIL_COND_V(image.is_null(), ERR_PARSE_ERROR);
4476
4477 copy_internals_from(image);
4478
4479 return OK;
4480 }
4481
4482 Error Image::load_svg_from_string(const String &p_svg_str, float scale) {
4483 return load_svg_from_buffer(p_svg_str.to_utf8_buffer(), scale);
4484 }
4485
4486 Error Image::load_ktx_from_buffer(const Vector<uint8_t> &p_array) {
4487 ERR_FAIL_NULL_V_MSG(
4488 _ktx_mem_loader_func,
4489 ERR_UNAVAILABLE,
4490 "The KTX module isn't enabled. Recompile the Godot editor or export template binary with the `module_ktx_enabled=yes` SCons option.");
4491 return _load_from_buffer(p_array, _ktx_mem_loader_func);
4492 }
4493
4494 void Image::convert_rg_to_ra_rgba8() {
4495 ERR_FAIL_COND(format != FORMAT_RGBA8);
4496 ERR_FAIL_COND(data.is_empty());
4497
4498 int s = data.size();
4499 uint8_t *w = data.ptrw();
4500 for (int i = 0; i < s; i += 4) {
4501 w[i + 3] = w[i + 1];
4502 w[i + 1] = 0;
4503 w[i + 2] = 0;
4504 }
4505 }
4506
4507 void Image::convert_ra_rgba8_to_rg() {
4508 ERR_FAIL_COND(format != FORMAT_RGBA8);
4509 ERR_FAIL_COND(data.is_empty());
4510
4511 int s = data.size();
4512 uint8_t *w = data.ptrw();
4513 for (int i = 0; i < s; i += 4) {
4514 w[i + 1] = w[i + 3];
4515 w[i + 2] = 0;
4516 w[i + 3] = 255;
4517 }
4518 }
4519
4520 void Image::convert_rgba8_to_bgra8() {
4521 ERR_FAIL_COND(format != FORMAT_RGBA8);
4522 ERR_FAIL_COND(data.is_empty());
4523
4524 int s = data.size();
4525 uint8_t *w = data.ptrw();
4526 for (int i = 0; i < s; i += 4) {
4527 uint8_t r = w[i];
4528 w[i] = w[i + 2]; // Swap R to B
4529 w[i + 2] = r; // Swap B to R
4530 }
4531 }
4532
4533 Error Image::_load_from_buffer(const Vector<uint8_t> &p_array, ImageMemLoadFunc p_loader) {
4534 int buffer_size = p_array.size();
4535
4536 ERR_FAIL_COND_V(buffer_size == 0, ERR_INVALID_PARAMETER);
4537 ERR_FAIL_NULL_V(p_loader, ERR_INVALID_PARAMETER);
4538
4539 const uint8_t *r = p_array.ptr();
4540
4541 Ref<Image> image = p_loader(r, buffer_size);
4542 ERR_FAIL_COND_V(image.is_null(), ERR_PARSE_ERROR);
4543
4544 copy_internals_from(image);
4545
4546 return OK;
4547 }
4548
4549 void Image::average_4_uint8(uint8_t &p_out, const uint8_t &p_a, const uint8_t &p_b, const uint8_t &p_c, const uint8_t &p_d) {
4550 p_out = static_cast<uint8_t>((p_a + p_b + p_c + p_d + 2) >> 2);
4551 }
4552
4553 void Image::average_4_float(float &p_out, const float &p_a, const float &p_b, const float &p_c, const float &p_d) {
4554 p_out = (p_a + p_b + p_c + p_d) * 0.25f;
4555 }
4556
4557 void Image::average_4_half(uint16_t &p_out, const uint16_t &p_a, const uint16_t &p_b, const uint16_t &p_c, const uint16_t &p_d) {
4558 p_out = Math::make_half_float((Math::half_to_float(p_a) + Math::half_to_float(p_b) + Math::half_to_float(p_c) + Math::half_to_float(p_d)) * 0.25f);
4559 }
4560
4561 void Image::average_4_rgbe9995(uint32_t &p_out, const uint32_t &p_a, const uint32_t &p_b, const uint32_t &p_c, const uint32_t &p_d) {
4562 p_out = ((Color::from_rgbe9995(p_a) + Color::from_rgbe9995(p_b) + Color::from_rgbe9995(p_c) + Color::from_rgbe9995(p_d)) * 0.25f).to_rgbe9995();
4563 }
4564
4565 void Image::average_4_uint16(uint16_t &p_out, const uint16_t &p_a, const uint16_t &p_b, const uint16_t &p_c, const uint16_t &p_d) {
4566 p_out = static_cast<uint16_t>((p_a + p_b + p_c + p_d + 2) >> 2);
4567 }
4568
4569 void Image::average_4_rgba4444(uint16_t &p_out, const uint16_t &p_a, const uint16_t &p_b, const uint16_t &p_c, const uint16_t &p_d) {
4570 p_out = color_to_rgba4444((color_from_rgba4444(p_a) + color_from_rgba4444(p_b) + color_from_rgba4444(p_c) + color_from_rgba4444(p_d)) * 0.25f);
4571 }
4572
4573 void Image::average_4_rgb565(uint16_t &p_out, const uint16_t &p_a, const uint16_t &p_b, const uint16_t &p_c, const uint16_t &p_d) {
4574 p_out = color_to_rgb565((color_from_rgb565(p_a) + color_from_rgb565(p_b) + color_from_rgb565(p_c) + color_from_rgb565(p_d)) * 0.25f);
4575 }
4576
4577 void Image::renormalize_uint8(uint8_t *p_rgb) {
4578 Vector3 n(p_rgb[0] / 255.0, p_rgb[1] / 255.0, p_rgb[2] / 255.0);
4579 n *= 2.0;
4580 n -= Vector3(1, 1, 1);
4581 n.normalize();
4582 n += Vector3(1, 1, 1);
4583 n *= 0.5;
4584 n *= 255;
4585 p_rgb[0] = CLAMP(int(Math::round(n.x)), 0, 255);
4586 p_rgb[1] = CLAMP(int(Math::round(n.y)), 0, 255);
4587 p_rgb[2] = CLAMP(int(Math::round(n.z)), 0, 255);
4588 }
4589
4590 void Image::renormalize_float(float *p_rgb) {
4591 Vector3 n(p_rgb[0], p_rgb[1], p_rgb[2]);
4592 n *= 2.0;
4593 n -= Vector3(1, 1, 1);
4594 n.normalize();
4595 n += Vector3(1, 1, 1);
4596 n *= 0.5;
4597 p_rgb[0] = n.x;
4598 p_rgb[1] = n.y;
4599 p_rgb[2] = n.z;
4600 }
4601
4602 void Image::renormalize_half(uint16_t *p_rgb) {
4603 Vector3 n(Math::half_to_float(p_rgb[0]), Math::half_to_float(p_rgb[1]), Math::half_to_float(p_rgb[2]));
4604 n *= 2.0;
4605 n -= Vector3(1, 1, 1);
4606 n.normalize();
4607 n += Vector3(1, 1, 1);
4608 n *= 0.5;
4609 p_rgb[0] = Math::make_half_float(n.x);
4610 p_rgb[1] = Math::make_half_float(n.y);
4611 p_rgb[2] = Math::make_half_float(n.z);
4612 }
4613
4614 void Image::renormalize_uint16(uint16_t *p_rgb) {
4615 Vector3 n(p_rgb[0] / 65535.0, p_rgb[1] / 65535.0, p_rgb[2] / 65535.0);
4616 n *= 2.0;
4617 n -= Vector3(1, 1, 1);
4618 n.normalize();
4619 n += Vector3(1, 1, 1);
4620 n *= 0.5;
4621 n *= 65535;
4622 p_rgb[0] = CLAMP(int(Math::round(n.x)), 0, 65535);
4623 p_rgb[1] = CLAMP(int(Math::round(n.y)), 0, 65535);
4624 p_rgb[2] = CLAMP(int(Math::round(n.z)), 0, 65535);
4625 }
4626
4627 Image::Image(const uint8_t *p_mem_png_jpg, int p_len) {
4628 width = 0;
4629 height = 0;
4630 mipmaps = false;
4631 format = FORMAT_L8;
4632
4633 if (_png_mem_loader_func) {
4634 copy_internals_from(_png_mem_loader_func(p_mem_png_jpg, p_len));
4635 }
4636
4637 if (is_empty() && _jpg_mem_loader_func) {
4638 copy_internals_from(_jpg_mem_loader_func(p_mem_png_jpg, p_len));
4639 }
4640
4641 if (is_empty() && _webp_mem_loader_func) {
4642 copy_internals_from(_webp_mem_loader_func(p_mem_png_jpg, p_len));
4643 }
4644 }
4645
4646 Ref<Resource> Image::_duplicate(const DuplicateParams &p_params) const {
4647 Ref<Image> copy;
4648 copy.instantiate();
4649 copy->_copy_internals_from(*this);
4650 return copy;
4651 }
4652
4653 void Image::set_as_black() {
4654 memset(data.ptrw(), 0, data.size());
4655 }
4656
4657 void Image::copy_internals_from(const Ref<Image> &p_image) {
4658 ERR_FAIL_COND_MSG(p_image.is_null(), "Cannot copy image internals: invalid Image object.");
4659 format = p_image->format;
4660 width = p_image->width;
4661 height = p_image->height;
4662 mipmaps = p_image->mipmaps;
4663 data = p_image->data;
4664 }
4665
4666 Dictionary Image::compute_image_metrics(const Ref<Image> p_compared_image, bool p_luma_metric) {
4667 // https://github.com/richgel999/bc7enc_rdo/blob/master/LICENSE
4668 //
4669 // This is free and unencumbered software released into the public domain.
4670 // Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
4671 // software, either in source code form or as a compiled binary, for any purpose,
4672 // commercial or non - commercial, and by any means.
4673 // In jurisdictions that recognize copyright laws, the author or authors of this
4674 // software dedicate any and all copyright interest in the software to the public
4675 // domain. We make this dedication for the benefit of the public at large and to
4676 // the detriment of our heirs and successors. We intend this dedication to be an
4677 // overt act of relinquishment in perpetuity of all present and future rights to
4678 // this software under copyright law.
4679 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
4680 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
4681 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
4682 // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
4683 // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
4684 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
4685
4686 Dictionary result;
4687 result["max"] = Math::INF;
4688 result["mean"] = Math::INF;
4689 result["mean_squared"] = Math::INF;
4690 result["root_mean_squared"] = Math::INF;
4691 result["peak_snr"] = 0.0f;
4692
4693 ERR_FAIL_COND_V(p_compared_image.is_null(), result);
4694 Error err = OK;
4695 Ref<Image> compared_image = duplicate(true);
4696 if (compared_image->is_compressed()) {
4697 err = compared_image->decompress();
4698 }
4699 ERR_FAIL_COND_V(err != OK, result);
4700 Ref<Image> source_image = p_compared_image->duplicate(true);
4701 if (source_image->is_compressed()) {
4702 err = source_image->decompress();
4703 }
4704 ERR_FAIL_COND_V(err != OK, result);
4705
4706 ERR_FAIL_COND_V_MSG((compared_image->get_format() >= Image::FORMAT_RH) && (compared_image->get_format() <= Image::FORMAT_RGBE9995), result, "Metrics on HDR images are not supported.");
4707 ERR_FAIL_COND_V_MSG((source_image->get_format() >= Image::FORMAT_RH) && (source_image->get_format() <= Image::FORMAT_RGBE9995), result, "Metrics on HDR images are not supported.");
4708
4709 double image_metric_max, image_metric_mean, image_metric_mean_squared, image_metric_root_mean_squared, image_metric_peak_snr = 0.0;
4710 const bool average_component_error = true;
4711
4712 const uint32_t w = MIN(compared_image->get_width(), source_image->get_width());
4713 const uint32_t h = MIN(compared_image->get_height(), source_image->get_height());
4714
4715 // Histogram approach originally due to Charles Bloom.
4716 double hist[256];
4717 memset(hist, 0, sizeof(hist));
4718
4719 for (uint32_t y = 0; y < h; y++) {
4720 for (uint32_t x = 0; x < w; x++) {
4721 const Color color_a = compared_image->get_pixel(x, y);
4722
4723 const Color color_b = source_image->get_pixel(x, y);
4724
4725 if (!p_luma_metric) {
4726 ERR_FAIL_COND_V_MSG(color_a.r > 1.0f, Dictionary(), "Can't compare HDR colors.");
4727 ERR_FAIL_COND_V_MSG(color_b.r > 1.0f, Dictionary(), "Can't compare HDR colors.");
4728 hist[Math::abs(color_a.get_r8() - color_b.get_r8())]++;
4729 ERR_FAIL_COND_V_MSG(color_a.g > 1.0f, Dictionary(), "Can't compare HDR colors.");
4730 ERR_FAIL_COND_V_MSG(color_b.g > 1.0f, Dictionary(), "Can't compare HDR colors.");
4731 hist[Math::abs(color_a.get_g8() - color_b.get_g8())]++;
4732 ERR_FAIL_COND_V_MSG(color_a.b > 1.0f, Dictionary(), "Can't compare HDR colors.");
4733 ERR_FAIL_COND_V_MSG(color_b.b > 1.0f, Dictionary(), "Can't compare HDR colors.");
4734 hist[Math::abs(color_a.get_b8() - color_b.get_b8())]++;
4735 ERR_FAIL_COND_V_MSG(color_a.a > 1.0f, Dictionary(), "Can't compare HDR colors.");
4736 ERR_FAIL_COND_V_MSG(color_b.a > 1.0f, Dictionary(), "Can't compare HDR colors.");
4737 hist[Math::abs(color_a.get_a8() - color_b.get_a8())]++;
4738 } else {
4739 ERR_FAIL_COND_V_MSG(color_a.r > 1.0f, Dictionary(), "Can't compare HDR colors.");
4740 ERR_FAIL_COND_V_MSG(color_b.r > 1.0f, Dictionary(), "Can't compare HDR colors.");
4741 // REC709 weightings
4742 int luma_a = (13938U * color_a.get_r8() + 46869U * color_a.get_g8() + 4729U * color_a.get_b8() + 32768U) >> 16U;
4743 int luma_b = (13938U * color_b.get_r8() + 46869U * color_b.get_g8() + 4729U * color_b.get_b8() + 32768U) >> 16U;
4744 hist[Math::abs(luma_a - luma_b)]++;
4745 }
4746 }
4747 }
4748
4749 image_metric_max = 0;
4750 double sum = 0.0f, sum2 = 0.0f;
4751 for (uint32_t i = 0; i < 256; i++) {
4752 if (!hist[i]) {
4753 continue;
4754 }
4755
4756 image_metric_max = i;
4757
4758 double x = i * hist[i];
4759
4760 sum += x;
4761 sum2 += i * x;
4762 }
4763
4764 // See http://richg42.blogspot.com/2016/09/how-to-compute-psnr-from-old-berkeley.html
4765 double total_values = w * h;
4766
4767 if (average_component_error) {
4768 total_values *= 4;
4769 }
4770
4771 image_metric_mean = CLAMP(sum / total_values, 0.0f, 255.0f);
4772 image_metric_mean_squared = CLAMP(sum2 / total_values, 0.0f, 255.0f * 255.0f);
4773
4774 image_metric_root_mean_squared = std::sqrt(image_metric_mean_squared);
4775
4776 if (!image_metric_root_mean_squared) {
4777 image_metric_peak_snr = 1e+10f;
4778 } else {
4779 image_metric_peak_snr = CLAMP(std::log10(255.0f / image_metric_root_mean_squared) * 20.0f, 0.0f, 500.0f);
4780 }
4781 result["max"] = image_metric_max;
4782 result["mean"] = image_metric_mean;
4783 result["mean_squared"] = image_metric_mean_squared;
4784 result["root_mean_squared"] = image_metric_root_mean_squared;
4785 result["peak_snr"] = image_metric_peak_snr;
4786 return result;
4787 }