image.cpp 127 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078
  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. #include "image.h"
  31. #include "core/error/error_list.h"
  32. #include "core/error/error_macros.h"
  33. #include "core/io/image_loader.h"
  34. #include "core/io/resource_loader.h"
  35. #include "core/math/math_funcs.h"
  36. #include "core/string/print_string.h"
  37. #include "core/templates/hash_map.h"
  38. #include "core/variant/dictionary.h"
  39. #include <stdio.h>
  40. #include <cmath>
  41. const char *Image::format_names[Image::FORMAT_MAX] = {
  42. "Lum8", //luminance
  43. "LumAlpha8", //luminance-alpha
  44. "Red8",
  45. "RedGreen",
  46. "RGB8",
  47. "RGBA8",
  48. "RGBA4444",
  49. "RGBA5551",
  50. "RFloat", //float
  51. "RGFloat",
  52. "RGBFloat",
  53. "RGBAFloat",
  54. "RHalf", //half float
  55. "RGHalf",
  56. "RGBHalf",
  57. "RGBAHalf",
  58. "RGBE9995",
  59. "DXT1 RGB8", //s3tc
  60. "DXT3 RGBA8",
  61. "DXT5 RGBA8",
  62. "RGTC Red8",
  63. "RGTC RedGreen8",
  64. "BPTC_RGBA",
  65. "BPTC_RGBF",
  66. "BPTC_RGBFU",
  67. "ETC", //etc1
  68. "ETC2_R11", //etc2
  69. "ETC2_R11S", //signed", NOT srgb.
  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. };
  78. SavePNGFunc Image::save_png_func = nullptr;
  79. SaveJPGFunc Image::save_jpg_func = nullptr;
  80. SaveEXRFunc Image::save_exr_func = nullptr;
  81. SavePNGBufferFunc Image::save_png_buffer_func = nullptr;
  82. SaveEXRBufferFunc Image::save_exr_buffer_func = nullptr;
  83. SaveJPGBufferFunc Image::save_jpg_buffer_func = nullptr;
  84. SaveWebPFunc Image::save_webp_func = nullptr;
  85. SaveWebPBufferFunc Image::save_webp_buffer_func = nullptr;
  86. void Image::_put_pixelb(int p_x, int p_y, uint32_t p_pixel_size, uint8_t *p_data, const uint8_t *p_pixel) {
  87. uint32_t ofs = (p_y * width + p_x) * p_pixel_size;
  88. memcpy(p_data + ofs, p_pixel, p_pixel_size);
  89. }
  90. void Image::_get_pixelb(int p_x, int p_y, uint32_t p_pixel_size, const uint8_t *p_data, uint8_t *p_pixel) {
  91. uint32_t ofs = (p_y * width + p_x) * p_pixel_size;
  92. memcpy(p_pixel, p_data + ofs, p_pixel_size);
  93. }
  94. int Image::get_format_pixel_size(Format p_format) {
  95. switch (p_format) {
  96. case FORMAT_L8:
  97. return 1; //luminance
  98. case FORMAT_LA8:
  99. return 2; //luminance-alpha
  100. case FORMAT_R8:
  101. return 1;
  102. case FORMAT_RG8:
  103. return 2;
  104. case FORMAT_RGB8:
  105. return 3;
  106. case FORMAT_RGBA8:
  107. return 4;
  108. case FORMAT_RGBA4444:
  109. return 2;
  110. case FORMAT_RGB565:
  111. return 2;
  112. case FORMAT_RF:
  113. return 4; //float
  114. case FORMAT_RGF:
  115. return 8;
  116. case FORMAT_RGBF:
  117. return 12;
  118. case FORMAT_RGBAF:
  119. return 16;
  120. case FORMAT_RH:
  121. return 2; //half float
  122. case FORMAT_RGH:
  123. return 4;
  124. case FORMAT_RGBH:
  125. return 6;
  126. case FORMAT_RGBAH:
  127. return 8;
  128. case FORMAT_RGBE9995:
  129. return 4;
  130. case FORMAT_DXT1:
  131. return 1; //s3tc bc1
  132. case FORMAT_DXT3:
  133. return 1; //bc2
  134. case FORMAT_DXT5:
  135. return 1; //bc3
  136. case FORMAT_RGTC_R:
  137. return 1; //bc4
  138. case FORMAT_RGTC_RG:
  139. return 1; //bc5
  140. case FORMAT_BPTC_RGBA:
  141. return 1; //btpc bc6h
  142. case FORMAT_BPTC_RGBF:
  143. return 1; //float /
  144. case FORMAT_BPTC_RGBFU:
  145. return 1; //unsigned float
  146. case FORMAT_ETC:
  147. return 1; //etc1
  148. case FORMAT_ETC2_R11:
  149. return 1; //etc2
  150. case FORMAT_ETC2_R11S:
  151. return 1; //signed: return 1; NOT srgb.
  152. case FORMAT_ETC2_RG11:
  153. return 1;
  154. case FORMAT_ETC2_RG11S:
  155. return 1;
  156. case FORMAT_ETC2_RGB8:
  157. return 1;
  158. case FORMAT_ETC2_RGBA8:
  159. return 1;
  160. case FORMAT_ETC2_RGB8A1:
  161. return 1;
  162. case FORMAT_ETC2_RA_AS_RG:
  163. return 1;
  164. case FORMAT_DXT5_RA_AS_RG:
  165. return 1;
  166. case FORMAT_ASTC_4x4:
  167. return 1;
  168. case FORMAT_ASTC_4x4_HDR:
  169. return 1;
  170. case FORMAT_ASTC_8x8:
  171. return 1;
  172. case FORMAT_ASTC_8x8_HDR:
  173. return 1;
  174. case FORMAT_MAX: {
  175. }
  176. }
  177. return 0;
  178. }
  179. void Image::get_format_min_pixel_size(Format p_format, int &r_w, int &r_h) {
  180. switch (p_format) {
  181. case FORMAT_DXT1: //s3tc bc1
  182. case FORMAT_DXT3: //bc2
  183. case FORMAT_DXT5: //bc3
  184. case FORMAT_RGTC_R: //bc4
  185. case FORMAT_RGTC_RG: { //bc5 case case FORMAT_DXT1:
  186. r_w = 4;
  187. r_h = 4;
  188. } break;
  189. case FORMAT_ETC: {
  190. r_w = 4;
  191. r_h = 4;
  192. } break;
  193. case FORMAT_BPTC_RGBA:
  194. case FORMAT_BPTC_RGBF:
  195. case FORMAT_BPTC_RGBFU: {
  196. r_w = 4;
  197. r_h = 4;
  198. } break;
  199. case FORMAT_ETC2_R11: //etc2
  200. case FORMAT_ETC2_R11S: //signed: NOT srgb.
  201. case FORMAT_ETC2_RG11:
  202. case FORMAT_ETC2_RG11S:
  203. case FORMAT_ETC2_RGB8:
  204. case FORMAT_ETC2_RGBA8:
  205. case FORMAT_ETC2_RGB8A1:
  206. case FORMAT_ETC2_RA_AS_RG:
  207. case FORMAT_DXT5_RA_AS_RG: {
  208. r_w = 4;
  209. r_h = 4;
  210. } break;
  211. case FORMAT_ASTC_4x4:
  212. case FORMAT_ASTC_4x4_HDR: {
  213. r_w = 4;
  214. r_h = 4;
  215. } break;
  216. case FORMAT_ASTC_8x8:
  217. case FORMAT_ASTC_8x8_HDR: {
  218. r_w = 8;
  219. r_h = 8;
  220. } break;
  221. default: {
  222. r_w = 1;
  223. r_h = 1;
  224. } break;
  225. }
  226. }
  227. int Image::get_format_pixel_rshift(Format p_format) {
  228. if (p_format == FORMAT_ASTC_8x8) {
  229. return 2;
  230. } 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) {
  231. return 1;
  232. } else {
  233. return 0;
  234. }
  235. }
  236. int Image::get_format_block_size(Format p_format) {
  237. switch (p_format) {
  238. case FORMAT_DXT1: //s3tc bc1
  239. case FORMAT_DXT3: //bc2
  240. case FORMAT_DXT5: //bc3
  241. case FORMAT_RGTC_R: //bc4
  242. case FORMAT_RGTC_RG: { //bc5 case case FORMAT_DXT1:
  243. return 4;
  244. }
  245. case FORMAT_ETC: {
  246. return 4;
  247. }
  248. case FORMAT_BPTC_RGBA:
  249. case FORMAT_BPTC_RGBF:
  250. case FORMAT_BPTC_RGBFU: {
  251. return 4;
  252. }
  253. case FORMAT_ETC2_R11: //etc2
  254. case FORMAT_ETC2_R11S: //signed: NOT srgb.
  255. case FORMAT_ETC2_RG11:
  256. case FORMAT_ETC2_RG11S:
  257. case FORMAT_ETC2_RGB8:
  258. case FORMAT_ETC2_RGBA8:
  259. case FORMAT_ETC2_RGB8A1:
  260. case FORMAT_ETC2_RA_AS_RG: //used to make basis universal happy
  261. case FORMAT_DXT5_RA_AS_RG: //used to make basis universal happy
  262. {
  263. return 4;
  264. }
  265. case FORMAT_ASTC_4x4:
  266. case FORMAT_ASTC_4x4_HDR: {
  267. return 4;
  268. }
  269. case FORMAT_ASTC_8x8:
  270. case FORMAT_ASTC_8x8_HDR: {
  271. return 8;
  272. }
  273. default: {
  274. }
  275. }
  276. return 1;
  277. }
  278. void Image::_get_mipmap_offset_and_size(int p_mipmap, int &r_offset, int &r_width, int &r_height) const {
  279. int w = width;
  280. int h = height;
  281. int ofs = 0;
  282. int pixel_size = get_format_pixel_size(format);
  283. int pixel_rshift = get_format_pixel_rshift(format);
  284. int block = get_format_block_size(format);
  285. int minw, minh;
  286. get_format_min_pixel_size(format, minw, minh);
  287. for (int i = 0; i < p_mipmap; i++) {
  288. int bw = w % block != 0 ? w + (block - w % block) : w;
  289. int bh = h % block != 0 ? h + (block - h % block) : h;
  290. int s = bw * bh;
  291. s *= pixel_size;
  292. s >>= pixel_rshift;
  293. ofs += s;
  294. w = MAX(minw, w >> 1);
  295. h = MAX(minh, h >> 1);
  296. }
  297. r_offset = ofs;
  298. r_width = w;
  299. r_height = h;
  300. }
  301. int Image::get_mipmap_offset(int p_mipmap) const {
  302. ERR_FAIL_INDEX_V(p_mipmap, get_mipmap_count() + 1, -1);
  303. int ofs, w, h;
  304. _get_mipmap_offset_and_size(p_mipmap, ofs, w, h);
  305. return ofs;
  306. }
  307. int Image::get_mipmap_byte_size(int p_mipmap) const {
  308. ERR_FAIL_INDEX_V(p_mipmap, get_mipmap_count() + 1, -1);
  309. int ofs, w, h;
  310. _get_mipmap_offset_and_size(p_mipmap, ofs, w, h);
  311. int ofs2;
  312. _get_mipmap_offset_and_size(p_mipmap + 1, ofs2, w, h);
  313. return ofs2 - ofs;
  314. }
  315. void Image::get_mipmap_offset_and_size(int p_mipmap, int &r_ofs, int &r_size) const {
  316. int ofs, w, h;
  317. _get_mipmap_offset_and_size(p_mipmap, ofs, w, h);
  318. int ofs2;
  319. _get_mipmap_offset_and_size(p_mipmap + 1, ofs2, w, h);
  320. r_ofs = ofs;
  321. r_size = ofs2 - ofs;
  322. }
  323. void Image::get_mipmap_offset_size_and_dimensions(int p_mipmap, int &r_ofs, int &r_size, int &w, int &h) const {
  324. int ofs;
  325. _get_mipmap_offset_and_size(p_mipmap, ofs, w, h);
  326. int ofs2, w2, h2;
  327. _get_mipmap_offset_and_size(p_mipmap + 1, ofs2, w2, h2);
  328. r_ofs = ofs;
  329. r_size = ofs2 - ofs;
  330. }
  331. 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) {
  332. int w = p_width;
  333. int h = p_height;
  334. int d = p_depth;
  335. int arr_ofs = 0;
  336. while (true) {
  337. for (int i = 0; i < d; i++) {
  338. int idx = i + arr_ofs;
  339. if (idx >= p_images.size()) {
  340. return VALIDATE_3D_ERR_MISSING_IMAGES;
  341. }
  342. if (p_images[idx].is_null() || p_images[idx]->is_empty()) {
  343. return VALIDATE_3D_ERR_IMAGE_EMPTY;
  344. }
  345. if (p_images[idx]->get_format() != p_format) {
  346. return VALIDATE_3D_ERR_IMAGE_FORMAT_MISMATCH;
  347. }
  348. if (p_images[idx]->get_width() != w || p_images[idx]->get_height() != h) {
  349. return VALIDATE_3D_ERR_IMAGE_SIZE_MISMATCH;
  350. }
  351. if (p_images[idx]->has_mipmaps()) {
  352. return VALIDATE_3D_ERR_IMAGE_HAS_MIPMAPS;
  353. }
  354. }
  355. arr_ofs += d;
  356. if (!p_mipmaps) {
  357. break;
  358. }
  359. if (w == 1 && h == 1 && d == 1) {
  360. break;
  361. }
  362. w = MAX(1, w >> 1);
  363. h = MAX(1, h >> 1);
  364. d = MAX(1, d >> 1);
  365. }
  366. if (arr_ofs != p_images.size()) {
  367. return VALIDATE_3D_ERR_EXTRA_IMAGES;
  368. }
  369. return VALIDATE_3D_OK;
  370. }
  371. String Image::get_3d_image_validation_error_text(Image3DValidateError p_error) {
  372. switch (p_error) {
  373. case VALIDATE_3D_OK: {
  374. return "Ok";
  375. } break;
  376. case VALIDATE_3D_ERR_IMAGE_EMPTY: {
  377. return "Empty Image found";
  378. } break;
  379. case VALIDATE_3D_ERR_MISSING_IMAGES: {
  380. return "Missing Images";
  381. } break;
  382. case VALIDATE_3D_ERR_EXTRA_IMAGES: {
  383. return "Too many Images";
  384. } break;
  385. case VALIDATE_3D_ERR_IMAGE_SIZE_MISMATCH: {
  386. return "Image size mismatch";
  387. } break;
  388. case VALIDATE_3D_ERR_IMAGE_FORMAT_MISMATCH: {
  389. return "Image format mismatch";
  390. } break;
  391. case VALIDATE_3D_ERR_IMAGE_HAS_MIPMAPS: {
  392. return "Image has included mipmaps";
  393. } break;
  394. }
  395. return String();
  396. }
  397. int Image::get_width() const {
  398. return width;
  399. }
  400. int Image::get_height() const {
  401. return height;
  402. }
  403. Size2i Image::get_size() const {
  404. return Size2i(width, height);
  405. }
  406. bool Image::has_mipmaps() const {
  407. return mipmaps;
  408. }
  409. int Image::get_mipmap_count() const {
  410. if (mipmaps) {
  411. return get_image_required_mipmaps(width, height, format);
  412. } else {
  413. return 0;
  414. }
  415. }
  416. //using template generates perfectly optimized code due to constant expression reduction and unused variable removal present in all compilers
  417. template <uint32_t read_bytes, bool read_alpha, uint32_t write_bytes, bool write_alpha, bool read_gray, bool write_gray>
  418. static void _convert(int p_width, int p_height, const uint8_t *p_src, uint8_t *p_dst) {
  419. uint32_t max_bytes = MAX(read_bytes, write_bytes);
  420. for (int y = 0; y < p_height; y++) {
  421. for (int x = 0; x < p_width; x++) {
  422. const uint8_t *rofs = &p_src[((y * p_width) + x) * (read_bytes + (read_alpha ? 1 : 0))];
  423. uint8_t *wofs = &p_dst[((y * p_width) + x) * (write_bytes + (write_alpha ? 1 : 0))];
  424. uint8_t rgba[4] = { 0, 0, 0, 255 };
  425. if constexpr (read_gray) {
  426. rgba[0] = rofs[0];
  427. rgba[1] = rofs[0];
  428. rgba[2] = rofs[0];
  429. } else {
  430. for (uint32_t i = 0; i < max_bytes; i++) {
  431. rgba[i] = (i < read_bytes) ? rofs[i] : 0;
  432. }
  433. }
  434. if constexpr (read_alpha || write_alpha) {
  435. rgba[3] = read_alpha ? rofs[read_bytes] : 255;
  436. }
  437. if constexpr (write_gray) {
  438. //TODO: not correct grayscale, should use fixed point version of actual weights
  439. wofs[0] = uint8_t((uint16_t(rgba[0]) + uint16_t(rgba[1]) + uint16_t(rgba[2])) / 3);
  440. } else {
  441. for (uint32_t i = 0; i < write_bytes; i++) {
  442. wofs[i] = rgba[i];
  443. }
  444. }
  445. if constexpr (write_alpha) {
  446. wofs[write_bytes] = rgba[3];
  447. }
  448. }
  449. }
  450. }
  451. void Image::convert(Format p_new_format) {
  452. if (data.size() == 0) {
  453. return;
  454. }
  455. if (p_new_format == format) {
  456. return;
  457. }
  458. if (format > FORMAT_RGBE9995 || p_new_format > FORMAT_RGBE9995) {
  459. ERR_FAIL_MSG("Cannot convert to <-> from compressed formats. Use compress() and decompress() instead.");
  460. } else if (format > FORMAT_RGBA8 || p_new_format > FORMAT_RGBA8) {
  461. //use put/set pixel which is slower but works with non byte formats
  462. Image new_img(width, height, false, p_new_format);
  463. for (int i = 0; i < width; i++) {
  464. for (int j = 0; j < height; j++) {
  465. new_img.set_pixel(i, j, get_pixel(i, j));
  466. }
  467. }
  468. if (has_mipmaps()) {
  469. new_img.generate_mipmaps();
  470. }
  471. _copy_internals_from(new_img);
  472. return;
  473. }
  474. Image new_img(width, height, false, p_new_format);
  475. const uint8_t *rptr = data.ptr();
  476. uint8_t *wptr = new_img.data.ptrw();
  477. int conversion_type = format | p_new_format << 8;
  478. switch (conversion_type) {
  479. case FORMAT_L8 | (FORMAT_LA8 << 8):
  480. _convert<1, false, 1, true, true, true>(width, height, rptr, wptr);
  481. break;
  482. case FORMAT_L8 | (FORMAT_R8 << 8):
  483. _convert<1, false, 1, false, true, false>(width, height, rptr, wptr);
  484. break;
  485. case FORMAT_L8 | (FORMAT_RG8 << 8):
  486. _convert<1, false, 2, false, true, false>(width, height, rptr, wptr);
  487. break;
  488. case FORMAT_L8 | (FORMAT_RGB8 << 8):
  489. _convert<1, false, 3, false, true, false>(width, height, rptr, wptr);
  490. break;
  491. case FORMAT_L8 | (FORMAT_RGBA8 << 8):
  492. _convert<1, false, 3, true, true, false>(width, height, rptr, wptr);
  493. break;
  494. case FORMAT_LA8 | (FORMAT_L8 << 8):
  495. _convert<1, true, 1, false, true, true>(width, height, rptr, wptr);
  496. break;
  497. case FORMAT_LA8 | (FORMAT_R8 << 8):
  498. _convert<1, true, 1, false, true, false>(width, height, rptr, wptr);
  499. break;
  500. case FORMAT_LA8 | (FORMAT_RG8 << 8):
  501. _convert<1, true, 2, false, true, false>(width, height, rptr, wptr);
  502. break;
  503. case FORMAT_LA8 | (FORMAT_RGB8 << 8):
  504. _convert<1, true, 3, false, true, false>(width, height, rptr, wptr);
  505. break;
  506. case FORMAT_LA8 | (FORMAT_RGBA8 << 8):
  507. _convert<1, true, 3, true, true, false>(width, height, rptr, wptr);
  508. break;
  509. case FORMAT_R8 | (FORMAT_L8 << 8):
  510. _convert<1, false, 1, false, false, true>(width, height, rptr, wptr);
  511. break;
  512. case FORMAT_R8 | (FORMAT_LA8 << 8):
  513. _convert<1, false, 1, true, false, true>(width, height, rptr, wptr);
  514. break;
  515. case FORMAT_R8 | (FORMAT_RG8 << 8):
  516. _convert<1, false, 2, false, false, false>(width, height, rptr, wptr);
  517. break;
  518. case FORMAT_R8 | (FORMAT_RGB8 << 8):
  519. _convert<1, false, 3, false, false, false>(width, height, rptr, wptr);
  520. break;
  521. case FORMAT_R8 | (FORMAT_RGBA8 << 8):
  522. _convert<1, false, 3, true, false, false>(width, height, rptr, wptr);
  523. break;
  524. case FORMAT_RG8 | (FORMAT_L8 << 8):
  525. _convert<2, false, 1, false, false, true>(width, height, rptr, wptr);
  526. break;
  527. case FORMAT_RG8 | (FORMAT_LA8 << 8):
  528. _convert<2, false, 1, true, false, true>(width, height, rptr, wptr);
  529. break;
  530. case FORMAT_RG8 | (FORMAT_R8 << 8):
  531. _convert<2, false, 1, false, false, false>(width, height, rptr, wptr);
  532. break;
  533. case FORMAT_RG8 | (FORMAT_RGB8 << 8):
  534. _convert<2, false, 3, false, false, false>(width, height, rptr, wptr);
  535. break;
  536. case FORMAT_RG8 | (FORMAT_RGBA8 << 8):
  537. _convert<2, false, 3, true, false, false>(width, height, rptr, wptr);
  538. break;
  539. case FORMAT_RGB8 | (FORMAT_L8 << 8):
  540. _convert<3, false, 1, false, false, true>(width, height, rptr, wptr);
  541. break;
  542. case FORMAT_RGB8 | (FORMAT_LA8 << 8):
  543. _convert<3, false, 1, true, false, true>(width, height, rptr, wptr);
  544. break;
  545. case FORMAT_RGB8 | (FORMAT_R8 << 8):
  546. _convert<3, false, 1, false, false, false>(width, height, rptr, wptr);
  547. break;
  548. case FORMAT_RGB8 | (FORMAT_RG8 << 8):
  549. _convert<3, false, 2, false, false, false>(width, height, rptr, wptr);
  550. break;
  551. case FORMAT_RGB8 | (FORMAT_RGBA8 << 8):
  552. _convert<3, false, 3, true, false, false>(width, height, rptr, wptr);
  553. break;
  554. case FORMAT_RGBA8 | (FORMAT_L8 << 8):
  555. _convert<3, true, 1, false, false, true>(width, height, rptr, wptr);
  556. break;
  557. case FORMAT_RGBA8 | (FORMAT_LA8 << 8):
  558. _convert<3, true, 1, true, false, true>(width, height, rptr, wptr);
  559. break;
  560. case FORMAT_RGBA8 | (FORMAT_R8 << 8):
  561. _convert<3, true, 1, false, false, false>(width, height, rptr, wptr);
  562. break;
  563. case FORMAT_RGBA8 | (FORMAT_RG8 << 8):
  564. _convert<3, true, 2, false, false, false>(width, height, rptr, wptr);
  565. break;
  566. case FORMAT_RGBA8 | (FORMAT_RGB8 << 8):
  567. _convert<3, true, 3, false, false, false>(width, height, rptr, wptr);
  568. break;
  569. }
  570. bool gen_mipmaps = mipmaps;
  571. _copy_internals_from(new_img);
  572. if (gen_mipmaps) {
  573. generate_mipmaps();
  574. }
  575. }
  576. Image::Format Image::get_format() const {
  577. return format;
  578. }
  579. static double _bicubic_interp_kernel(double x) {
  580. x = ABS(x);
  581. double bc = 0;
  582. if (x <= 1) {
  583. bc = (1.5 * x - 2.5) * x * x + 1;
  584. } else if (x < 2) {
  585. bc = ((-0.5 * x + 2.5) * x - 4) * x + 2;
  586. }
  587. return bc;
  588. }
  589. template <int CC, class T>
  590. 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) {
  591. // get source image size
  592. int width = p_src_width;
  593. int height = p_src_height;
  594. double xfac = (double)width / p_dst_width;
  595. double yfac = (double)height / p_dst_height;
  596. // coordinates of source points and coefficients
  597. double ox, oy, dx, dy;
  598. int ox1, oy1, ox2, oy2;
  599. // destination pixel values
  600. // width and height decreased by 1
  601. int ymax = height - 1;
  602. int xmax = width - 1;
  603. // temporary pointer
  604. for (uint32_t y = 0; y < p_dst_height; y++) {
  605. // Y coordinates
  606. oy = (double)y * yfac - 0.5f;
  607. oy1 = (int)oy;
  608. dy = oy - (double)oy1;
  609. for (uint32_t x = 0; x < p_dst_width; x++) {
  610. // X coordinates
  611. ox = (double)x * xfac - 0.5f;
  612. ox1 = (int)ox;
  613. dx = ox - (double)ox1;
  614. // initial pixel value
  615. T *__restrict dst = ((T *)p_dst) + (y * p_dst_width + x) * CC;
  616. double color[CC];
  617. for (int i = 0; i < CC; i++) {
  618. color[i] = 0;
  619. }
  620. for (int n = -1; n < 3; n++) {
  621. // get Y coefficient
  622. [[maybe_unused]] double k1 = _bicubic_interp_kernel(dy - (double)n);
  623. oy2 = oy1 + n;
  624. if (oy2 < 0) {
  625. oy2 = 0;
  626. }
  627. if (oy2 > ymax) {
  628. oy2 = ymax;
  629. }
  630. for (int m = -1; m < 3; m++) {
  631. // get X coefficient
  632. [[maybe_unused]] double k2 = k1 * _bicubic_interp_kernel((double)m - dx);
  633. ox2 = ox1 + m;
  634. if (ox2 < 0) {
  635. ox2 = 0;
  636. }
  637. if (ox2 > xmax) {
  638. ox2 = xmax;
  639. }
  640. // get pixel of original image
  641. const T *__restrict p = ((T *)p_src) + (oy2 * p_src_width + ox2) * CC;
  642. for (int i = 0; i < CC; i++) {
  643. if constexpr (sizeof(T) == 2) { //half float
  644. color[i] = Math::half_to_float(p[i]);
  645. } else {
  646. color[i] += p[i] * k2;
  647. }
  648. }
  649. }
  650. }
  651. for (int i = 0; i < CC; i++) {
  652. if constexpr (sizeof(T) == 1) { //byte
  653. dst[i] = CLAMP(Math::fast_ftoi(color[i]), 0, 255);
  654. } else if constexpr (sizeof(T) == 2) { //half float
  655. dst[i] = Math::make_half_float(color[i]);
  656. } else {
  657. dst[i] = color[i];
  658. }
  659. }
  660. }
  661. }
  662. }
  663. template <int CC, class T>
  664. 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) {
  665. enum {
  666. FRAC_BITS = 8,
  667. FRAC_LEN = (1 << FRAC_BITS),
  668. FRAC_HALF = (FRAC_LEN >> 1),
  669. FRAC_MASK = FRAC_LEN - 1
  670. };
  671. for (uint32_t i = 0; i < p_dst_height; i++) {
  672. // Add 0.5 in order to interpolate based on pixel center
  673. uint32_t src_yofs_up_fp = (i + 0.5) * p_src_height * FRAC_LEN / p_dst_height;
  674. // Calculate nearest src pixel center above current, and truncate to get y index
  675. uint32_t src_yofs_up = src_yofs_up_fp >= FRAC_HALF ? (src_yofs_up_fp - FRAC_HALF) >> FRAC_BITS : 0;
  676. uint32_t src_yofs_down = (src_yofs_up_fp + FRAC_HALF) >> FRAC_BITS;
  677. if (src_yofs_down >= p_src_height) {
  678. src_yofs_down = p_src_height - 1;
  679. }
  680. // Calculate distance to pixel center of src_yofs_up
  681. uint32_t src_yofs_frac = src_yofs_up_fp & FRAC_MASK;
  682. src_yofs_frac = src_yofs_frac >= FRAC_HALF ? src_yofs_frac - FRAC_HALF : src_yofs_frac + FRAC_HALF;
  683. uint32_t y_ofs_up = src_yofs_up * p_src_width * CC;
  684. uint32_t y_ofs_down = src_yofs_down * p_src_width * CC;
  685. for (uint32_t j = 0; j < p_dst_width; j++) {
  686. uint32_t src_xofs_left_fp = (j + 0.5) * p_src_width * FRAC_LEN / p_dst_width;
  687. uint32_t src_xofs_left = src_xofs_left_fp >= FRAC_HALF ? (src_xofs_left_fp - FRAC_HALF) >> FRAC_BITS : 0;
  688. uint32_t src_xofs_right = (src_xofs_left_fp + FRAC_HALF) >> FRAC_BITS;
  689. if (src_xofs_right >= p_src_width) {
  690. src_xofs_right = p_src_width - 1;
  691. }
  692. uint32_t src_xofs_frac = src_xofs_left_fp & FRAC_MASK;
  693. src_xofs_frac = src_xofs_frac >= FRAC_HALF ? src_xofs_frac - FRAC_HALF : src_xofs_frac + FRAC_HALF;
  694. src_xofs_left *= CC;
  695. src_xofs_right *= CC;
  696. for (uint32_t l = 0; l < CC; l++) {
  697. if constexpr (sizeof(T) == 1) { //uint8
  698. uint32_t p00 = p_src[y_ofs_up + src_xofs_left + l] << FRAC_BITS;
  699. uint32_t p10 = p_src[y_ofs_up + src_xofs_right + l] << FRAC_BITS;
  700. uint32_t p01 = p_src[y_ofs_down + src_xofs_left + l] << FRAC_BITS;
  701. uint32_t p11 = p_src[y_ofs_down + src_xofs_right + l] << FRAC_BITS;
  702. uint32_t interp_up = p00 + (((p10 - p00) * src_xofs_frac) >> FRAC_BITS);
  703. uint32_t interp_down = p01 + (((p11 - p01) * src_xofs_frac) >> FRAC_BITS);
  704. uint32_t interp = interp_up + (((interp_down - interp_up) * src_yofs_frac) >> FRAC_BITS);
  705. interp >>= FRAC_BITS;
  706. p_dst[i * p_dst_width * CC + j * CC + l] = uint8_t(interp);
  707. } else if constexpr (sizeof(T) == 2) { //half float
  708. float xofs_frac = float(src_xofs_frac) / (1 << FRAC_BITS);
  709. float yofs_frac = float(src_yofs_frac) / (1 << FRAC_BITS);
  710. const T *src = ((const T *)p_src);
  711. T *dst = ((T *)p_dst);
  712. float p00 = Math::half_to_float(src[y_ofs_up + src_xofs_left + l]);
  713. float p10 = Math::half_to_float(src[y_ofs_up + src_xofs_right + l]);
  714. float p01 = Math::half_to_float(src[y_ofs_down + src_xofs_left + l]);
  715. float p11 = Math::half_to_float(src[y_ofs_down + src_xofs_right + l]);
  716. float interp_up = p00 + (p10 - p00) * xofs_frac;
  717. float interp_down = p01 + (p11 - p01) * xofs_frac;
  718. float interp = interp_up + ((interp_down - interp_up) * yofs_frac);
  719. dst[i * p_dst_width * CC + j * CC + l] = Math::make_half_float(interp);
  720. } else if constexpr (sizeof(T) == 4) { //float
  721. float xofs_frac = float(src_xofs_frac) / (1 << FRAC_BITS);
  722. float yofs_frac = float(src_yofs_frac) / (1 << FRAC_BITS);
  723. const T *src = ((const T *)p_src);
  724. T *dst = ((T *)p_dst);
  725. float p00 = src[y_ofs_up + src_xofs_left + l];
  726. float p10 = src[y_ofs_up + src_xofs_right + l];
  727. float p01 = src[y_ofs_down + src_xofs_left + l];
  728. float p11 = src[y_ofs_down + src_xofs_right + l];
  729. float interp_up = p00 + (p10 - p00) * xofs_frac;
  730. float interp_down = p01 + (p11 - p01) * xofs_frac;
  731. float interp = interp_up + ((interp_down - interp_up) * yofs_frac);
  732. dst[i * p_dst_width * CC + j * CC + l] = interp;
  733. }
  734. }
  735. }
  736. }
  737. }
  738. template <int CC, class T>
  739. 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) {
  740. for (uint32_t i = 0; i < p_dst_height; i++) {
  741. uint32_t src_yofs = i * p_src_height / p_dst_height;
  742. uint32_t y_ofs = src_yofs * p_src_width * CC;
  743. for (uint32_t j = 0; j < p_dst_width; j++) {
  744. uint32_t src_xofs = j * p_src_width / p_dst_width;
  745. src_xofs *= CC;
  746. for (uint32_t l = 0; l < CC; l++) {
  747. const T *src = ((const T *)p_src);
  748. T *dst = ((T *)p_dst);
  749. T p = src[y_ofs + src_xofs + l];
  750. dst[i * p_dst_width * CC + j * CC + l] = p;
  751. }
  752. }
  753. }
  754. }
  755. #define LANCZOS_TYPE 3
  756. static float _lanczos(float p_x) {
  757. return Math::abs(p_x) >= LANCZOS_TYPE ? 0 : Math::sincn(p_x) * Math::sincn(p_x / LANCZOS_TYPE);
  758. }
  759. template <int CC, class T>
  760. 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) {
  761. int32_t src_width = p_src_width;
  762. int32_t src_height = p_src_height;
  763. int32_t dst_height = p_dst_height;
  764. int32_t dst_width = p_dst_width;
  765. uint32_t buffer_size = src_height * dst_width * CC;
  766. float *buffer = memnew_arr(float, buffer_size); // Store the first pass in a buffer
  767. { // FIRST PASS (horizontal)
  768. float x_scale = float(src_width) / float(dst_width);
  769. float scale_factor = MAX(x_scale, 1); // A larger kernel is required only when downscaling
  770. int32_t half_kernel = LANCZOS_TYPE * scale_factor;
  771. float *kernel = memnew_arr(float, half_kernel * 2);
  772. for (int32_t buffer_x = 0; buffer_x < dst_width; buffer_x++) {
  773. // The corresponding point on the source image
  774. float src_x = (buffer_x + 0.5f) * x_scale; // Offset by 0.5 so it uses the pixel's center
  775. int32_t start_x = MAX(0, int32_t(src_x) - half_kernel + 1);
  776. int32_t end_x = MIN(src_width - 1, int32_t(src_x) + half_kernel);
  777. // Create the kernel used by all the pixels of the column
  778. for (int32_t target_x = start_x; target_x <= end_x; target_x++) {
  779. kernel[target_x - start_x] = _lanczos((target_x + 0.5f - src_x) / scale_factor);
  780. }
  781. for (int32_t buffer_y = 0; buffer_y < src_height; buffer_y++) {
  782. float pixel[CC] = { 0 };
  783. float weight = 0;
  784. for (int32_t target_x = start_x; target_x <= end_x; target_x++) {
  785. float lanczos_val = kernel[target_x - start_x];
  786. weight += lanczos_val;
  787. const T *__restrict src_data = ((const T *)p_src) + (buffer_y * src_width + target_x) * CC;
  788. for (uint32_t i = 0; i < CC; i++) {
  789. if constexpr (sizeof(T) == 2) { //half float
  790. pixel[i] += Math::half_to_float(src_data[i]) * lanczos_val;
  791. } else {
  792. pixel[i] += src_data[i] * lanczos_val;
  793. }
  794. }
  795. }
  796. float *dst_data = ((float *)buffer) + (buffer_y * dst_width + buffer_x) * CC;
  797. for (uint32_t i = 0; i < CC; i++) {
  798. dst_data[i] = pixel[i] / weight; // Normalize the sum of all the samples
  799. }
  800. }
  801. }
  802. memdelete_arr(kernel);
  803. } // End of first pass
  804. { // SECOND PASS (vertical + result)
  805. float y_scale = float(src_height) / float(dst_height);
  806. float scale_factor = MAX(y_scale, 1);
  807. int32_t half_kernel = LANCZOS_TYPE * scale_factor;
  808. float *kernel = memnew_arr(float, half_kernel * 2);
  809. for (int32_t dst_y = 0; dst_y < dst_height; dst_y++) {
  810. float buffer_y = (dst_y + 0.5f) * y_scale;
  811. int32_t start_y = MAX(0, int32_t(buffer_y) - half_kernel + 1);
  812. int32_t end_y = MIN(src_height - 1, int32_t(buffer_y) + half_kernel);
  813. for (int32_t target_y = start_y; target_y <= end_y; target_y++) {
  814. kernel[target_y - start_y] = _lanczos((target_y + 0.5f - buffer_y) / scale_factor);
  815. }
  816. for (int32_t dst_x = 0; dst_x < dst_width; dst_x++) {
  817. float pixel[CC] = { 0 };
  818. float weight = 0;
  819. for (int32_t target_y = start_y; target_y <= end_y; target_y++) {
  820. float lanczos_val = kernel[target_y - start_y];
  821. weight += lanczos_val;
  822. float *buffer_data = ((float *)buffer) + (target_y * dst_width + dst_x) * CC;
  823. for (uint32_t i = 0; i < CC; i++) {
  824. pixel[i] += buffer_data[i] * lanczos_val;
  825. }
  826. }
  827. T *dst_data = ((T *)p_dst) + (dst_y * dst_width + dst_x) * CC;
  828. for (uint32_t i = 0; i < CC; i++) {
  829. pixel[i] /= weight;
  830. if constexpr (sizeof(T) == 1) { //byte
  831. dst_data[i] = CLAMP(Math::fast_ftoi(pixel[i]), 0, 255);
  832. } else if constexpr (sizeof(T) == 2) { //half float
  833. dst_data[i] = Math::make_half_float(pixel[i]);
  834. } else { // float
  835. dst_data[i] = pixel[i];
  836. }
  837. }
  838. }
  839. }
  840. memdelete_arr(kernel);
  841. } // End of second pass
  842. memdelete_arr(buffer);
  843. }
  844. 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) {
  845. uint16_t alpha = MIN((uint16_t)(p_alpha * 256.0f), 256);
  846. for (uint32_t i = 0; i < p_width * p_height * p_pixel_size; i++) {
  847. p_dst[i] = (p_dst[i] * (256 - alpha) + p_src[i] * alpha) >> 8;
  848. }
  849. }
  850. bool Image::is_size_po2() const {
  851. return uint32_t(width) == next_power_of_2(width) && uint32_t(height) == next_power_of_2(height);
  852. }
  853. void Image::resize_to_po2(bool p_square, Interpolation p_interpolation) {
  854. ERR_FAIL_COND_MSG(!_can_modify(format), "Cannot resize in compressed or custom image formats.");
  855. int w = next_power_of_2(width);
  856. int h = next_power_of_2(height);
  857. if (p_square) {
  858. w = h = MAX(w, h);
  859. }
  860. if (w == width && h == height) {
  861. if (!p_square || w == h) {
  862. return; //nothing to do
  863. }
  864. }
  865. resize(w, h, p_interpolation);
  866. }
  867. void Image::resize(int p_width, int p_height, Interpolation p_interpolation) {
  868. ERR_FAIL_COND_MSG(data.size() == 0, "Cannot resize image before creating it, use set_data() first.");
  869. ERR_FAIL_COND_MSG(!_can_modify(format), "Cannot resize in compressed or custom image formats.");
  870. bool mipmap_aware = p_interpolation == INTERPOLATE_TRILINEAR /* || p_interpolation == INTERPOLATE_TRICUBIC */;
  871. ERR_FAIL_COND_MSG(p_width <= 0, "Image width must be greater than 0.");
  872. ERR_FAIL_COND_MSG(p_height <= 0, "Image height must be greater than 0.");
  873. ERR_FAIL_COND_MSG(p_width > MAX_WIDTH, "Image width cannot be greater than " + itos(MAX_WIDTH) + ".");
  874. ERR_FAIL_COND_MSG(p_height > MAX_HEIGHT, "Image height cannot be greater than " + itos(MAX_HEIGHT) + ".");
  875. ERR_FAIL_COND_MSG(p_width * p_height > MAX_PIXELS, "Too many pixels for image, maximum is " + itos(MAX_PIXELS));
  876. if (p_width == width && p_height == height) {
  877. return;
  878. }
  879. Image dst(p_width, p_height, false, format);
  880. // Setup mipmap-aware scaling
  881. Image dst2;
  882. int mip1 = 0;
  883. int mip2 = 0;
  884. float mip1_weight = 0;
  885. if (mipmap_aware) {
  886. float avg_scale = ((float)p_width / width + (float)p_height / height) * 0.5f;
  887. if (avg_scale >= 1.0f) {
  888. mipmap_aware = false;
  889. } else {
  890. float level = Math::log(1.0f / avg_scale) / Math::log(2.0f);
  891. mip1 = CLAMP((int)Math::floor(level), 0, get_mipmap_count());
  892. mip2 = CLAMP((int)Math::ceil(level), 0, get_mipmap_count());
  893. mip1_weight = 1.0f - (level - mip1);
  894. }
  895. }
  896. bool interpolate_mipmaps = mipmap_aware && mip1 != mip2;
  897. if (interpolate_mipmaps) {
  898. dst2.initialize_data(p_width, p_height, false, format);
  899. }
  900. bool had_mipmaps = mipmaps;
  901. if (interpolate_mipmaps && !had_mipmaps) {
  902. generate_mipmaps();
  903. }
  904. // --
  905. const uint8_t *r = data.ptr();
  906. const unsigned char *r_ptr = r;
  907. uint8_t *w = dst.data.ptrw();
  908. unsigned char *w_ptr = w;
  909. switch (p_interpolation) {
  910. case INTERPOLATE_NEAREST: {
  911. if (format >= FORMAT_L8 && format <= FORMAT_RGBA8) {
  912. switch (get_format_pixel_size(format)) {
  913. case 1:
  914. _scale_nearest<1, uint8_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  915. break;
  916. case 2:
  917. _scale_nearest<2, uint8_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  918. break;
  919. case 3:
  920. _scale_nearest<3, uint8_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  921. break;
  922. case 4:
  923. _scale_nearest<4, uint8_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  924. break;
  925. }
  926. } else if (format >= FORMAT_RF && format <= FORMAT_RGBAF) {
  927. switch (get_format_pixel_size(format)) {
  928. case 4:
  929. _scale_nearest<1, float>(r_ptr, w_ptr, width, height, p_width, p_height);
  930. break;
  931. case 8:
  932. _scale_nearest<2, float>(r_ptr, w_ptr, width, height, p_width, p_height);
  933. break;
  934. case 12:
  935. _scale_nearest<3, float>(r_ptr, w_ptr, width, height, p_width, p_height);
  936. break;
  937. case 16:
  938. _scale_nearest<4, float>(r_ptr, w_ptr, width, height, p_width, p_height);
  939. break;
  940. }
  941. } else if (format >= FORMAT_RH && format <= FORMAT_RGBAH) {
  942. switch (get_format_pixel_size(format)) {
  943. case 2:
  944. _scale_nearest<1, uint16_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  945. break;
  946. case 4:
  947. _scale_nearest<2, uint16_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  948. break;
  949. case 6:
  950. _scale_nearest<3, uint16_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  951. break;
  952. case 8:
  953. _scale_nearest<4, uint16_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  954. break;
  955. }
  956. }
  957. } break;
  958. case INTERPOLATE_BILINEAR:
  959. case INTERPOLATE_TRILINEAR: {
  960. for (int i = 0; i < 2; ++i) {
  961. int src_width;
  962. int src_height;
  963. const unsigned char *src_ptr;
  964. if (!mipmap_aware) {
  965. if (i == 0) {
  966. // Standard behavior
  967. src_width = width;
  968. src_height = height;
  969. src_ptr = r_ptr;
  970. } else {
  971. // No need for a second iteration
  972. break;
  973. }
  974. } else {
  975. if (i == 0) {
  976. // Read from the first mipmap that will be interpolated
  977. // (if both levels are the same, we will not interpolate, but at least we'll sample from the right level)
  978. int offs;
  979. _get_mipmap_offset_and_size(mip1, offs, src_width, src_height);
  980. src_ptr = r_ptr + offs;
  981. } else if (!interpolate_mipmaps) {
  982. // No need generate a second image
  983. break;
  984. } else {
  985. // Switch to read from the second mipmap that will be interpolated
  986. int offs;
  987. _get_mipmap_offset_and_size(mip2, offs, src_width, src_height);
  988. src_ptr = r_ptr + offs;
  989. // Switch to write to the second destination image
  990. w = dst2.data.ptrw();
  991. w_ptr = w;
  992. }
  993. }
  994. if (format >= FORMAT_L8 && format <= FORMAT_RGBA8) {
  995. switch (get_format_pixel_size(format)) {
  996. case 1:
  997. _scale_bilinear<1, uint8_t>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
  998. break;
  999. case 2:
  1000. _scale_bilinear<2, uint8_t>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
  1001. break;
  1002. case 3:
  1003. _scale_bilinear<3, uint8_t>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
  1004. break;
  1005. case 4:
  1006. _scale_bilinear<4, uint8_t>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
  1007. break;
  1008. }
  1009. } else if (format >= FORMAT_RF && format <= FORMAT_RGBAF) {
  1010. switch (get_format_pixel_size(format)) {
  1011. case 4:
  1012. _scale_bilinear<1, float>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
  1013. break;
  1014. case 8:
  1015. _scale_bilinear<2, float>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
  1016. break;
  1017. case 12:
  1018. _scale_bilinear<3, float>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
  1019. break;
  1020. case 16:
  1021. _scale_bilinear<4, float>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
  1022. break;
  1023. }
  1024. } else if (format >= FORMAT_RH && format <= FORMAT_RGBAH) {
  1025. switch (get_format_pixel_size(format)) {
  1026. case 2:
  1027. _scale_bilinear<1, uint16_t>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
  1028. break;
  1029. case 4:
  1030. _scale_bilinear<2, uint16_t>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
  1031. break;
  1032. case 6:
  1033. _scale_bilinear<3, uint16_t>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
  1034. break;
  1035. case 8:
  1036. _scale_bilinear<4, uint16_t>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
  1037. break;
  1038. }
  1039. }
  1040. }
  1041. if (interpolate_mipmaps) {
  1042. // Switch to read again from the first scaled mipmap to overlay it over the second
  1043. r = dst.data.ptr();
  1044. _overlay(r, w, mip1_weight, p_width, p_height, get_format_pixel_size(format));
  1045. }
  1046. } break;
  1047. case INTERPOLATE_CUBIC: {
  1048. if (format >= FORMAT_L8 && format <= FORMAT_RGBA8) {
  1049. switch (get_format_pixel_size(format)) {
  1050. case 1:
  1051. _scale_cubic<1, uint8_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  1052. break;
  1053. case 2:
  1054. _scale_cubic<2, uint8_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  1055. break;
  1056. case 3:
  1057. _scale_cubic<3, uint8_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  1058. break;
  1059. case 4:
  1060. _scale_cubic<4, uint8_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  1061. break;
  1062. }
  1063. } else if (format >= FORMAT_RF && format <= FORMAT_RGBAF) {
  1064. switch (get_format_pixel_size(format)) {
  1065. case 4:
  1066. _scale_cubic<1, float>(r_ptr, w_ptr, width, height, p_width, p_height);
  1067. break;
  1068. case 8:
  1069. _scale_cubic<2, float>(r_ptr, w_ptr, width, height, p_width, p_height);
  1070. break;
  1071. case 12:
  1072. _scale_cubic<3, float>(r_ptr, w_ptr, width, height, p_width, p_height);
  1073. break;
  1074. case 16:
  1075. _scale_cubic<4, float>(r_ptr, w_ptr, width, height, p_width, p_height);
  1076. break;
  1077. }
  1078. } else if (format >= FORMAT_RH && format <= FORMAT_RGBAH) {
  1079. switch (get_format_pixel_size(format)) {
  1080. case 2:
  1081. _scale_cubic<1, uint16_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  1082. break;
  1083. case 4:
  1084. _scale_cubic<2, uint16_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  1085. break;
  1086. case 6:
  1087. _scale_cubic<3, uint16_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  1088. break;
  1089. case 8:
  1090. _scale_cubic<4, uint16_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  1091. break;
  1092. }
  1093. }
  1094. } break;
  1095. case INTERPOLATE_LANCZOS: {
  1096. if (format >= FORMAT_L8 && format <= FORMAT_RGBA8) {
  1097. switch (get_format_pixel_size(format)) {
  1098. case 1:
  1099. _scale_lanczos<1, uint8_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  1100. break;
  1101. case 2:
  1102. _scale_lanczos<2, uint8_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  1103. break;
  1104. case 3:
  1105. _scale_lanczos<3, uint8_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  1106. break;
  1107. case 4:
  1108. _scale_lanczos<4, uint8_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  1109. break;
  1110. }
  1111. } else if (format >= FORMAT_RF && format <= FORMAT_RGBAF) {
  1112. switch (get_format_pixel_size(format)) {
  1113. case 4:
  1114. _scale_lanczos<1, float>(r_ptr, w_ptr, width, height, p_width, p_height);
  1115. break;
  1116. case 8:
  1117. _scale_lanczos<2, float>(r_ptr, w_ptr, width, height, p_width, p_height);
  1118. break;
  1119. case 12:
  1120. _scale_lanczos<3, float>(r_ptr, w_ptr, width, height, p_width, p_height);
  1121. break;
  1122. case 16:
  1123. _scale_lanczos<4, float>(r_ptr, w_ptr, width, height, p_width, p_height);
  1124. break;
  1125. }
  1126. } else if (format >= FORMAT_RH && format <= FORMAT_RGBAH) {
  1127. switch (get_format_pixel_size(format)) {
  1128. case 2:
  1129. _scale_lanczos<1, uint16_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  1130. break;
  1131. case 4:
  1132. _scale_lanczos<2, uint16_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  1133. break;
  1134. case 6:
  1135. _scale_lanczos<3, uint16_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  1136. break;
  1137. case 8:
  1138. _scale_lanczos<4, uint16_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  1139. break;
  1140. }
  1141. }
  1142. } break;
  1143. }
  1144. if (interpolate_mipmaps) {
  1145. dst._copy_internals_from(dst2);
  1146. }
  1147. if (had_mipmaps) {
  1148. dst.generate_mipmaps();
  1149. }
  1150. _copy_internals_from(dst);
  1151. }
  1152. void Image::crop_from_point(int p_x, int p_y, int p_width, int p_height) {
  1153. ERR_FAIL_COND_MSG(!_can_modify(format), "Cannot crop in compressed or custom image formats.");
  1154. ERR_FAIL_COND_MSG(p_x < 0, "Start x position cannot be smaller than 0.");
  1155. ERR_FAIL_COND_MSG(p_y < 0, "Start y position cannot be smaller than 0.");
  1156. ERR_FAIL_COND_MSG(p_width <= 0, "Width of image must be greater than 0.");
  1157. ERR_FAIL_COND_MSG(p_height <= 0, "Height of image must be greater than 0.");
  1158. ERR_FAIL_COND_MSG(p_x + p_width > MAX_WIDTH, "End x position cannot be greater than " + itos(MAX_WIDTH) + ".");
  1159. ERR_FAIL_COND_MSG(p_y + p_height > MAX_HEIGHT, "End y position cannot be greater than " + itos(MAX_HEIGHT) + ".");
  1160. /* to save memory, cropping should be done in-place, however, since this function
  1161. will most likely either not be used much, or in critical areas, for now it won't, because
  1162. it's a waste of time. */
  1163. if (p_width == width && p_height == height && p_x == 0 && p_y == 0) {
  1164. return;
  1165. }
  1166. uint8_t pdata[16]; //largest is 16
  1167. uint32_t pixel_size = get_format_pixel_size(format);
  1168. Image dst(p_width, p_height, false, format);
  1169. {
  1170. const uint8_t *r = data.ptr();
  1171. uint8_t *w = dst.data.ptrw();
  1172. int m_h = p_y + p_height;
  1173. int m_w = p_x + p_width;
  1174. for (int y = p_y; y < m_h; y++) {
  1175. for (int x = p_x; x < m_w; x++) {
  1176. if ((x >= width || y >= height)) {
  1177. for (uint32_t i = 0; i < pixel_size; i++) {
  1178. pdata[i] = 0;
  1179. }
  1180. } else {
  1181. _get_pixelb(x, y, pixel_size, r, pdata);
  1182. }
  1183. dst._put_pixelb(x - p_x, y - p_y, pixel_size, w, pdata);
  1184. }
  1185. }
  1186. }
  1187. if (has_mipmaps()) {
  1188. dst.generate_mipmaps();
  1189. }
  1190. _copy_internals_from(dst);
  1191. }
  1192. void Image::crop(int p_width, int p_height) {
  1193. crop_from_point(0, 0, p_width, p_height);
  1194. }
  1195. void Image::rotate_90(ClockDirection p_direction) {
  1196. ERR_FAIL_COND_MSG(!_can_modify(format), "Cannot rotate in compressed or custom image formats.");
  1197. ERR_FAIL_COND_MSG(width <= 0, "The Image width specified (" + itos(width) + " pixels) must be greater than 0 pixels.");
  1198. ERR_FAIL_COND_MSG(height <= 0, "The Image height specified (" + itos(height) + " pixels) must be greater than 0 pixels.");
  1199. bool used_mipmaps = has_mipmaps();
  1200. if (used_mipmaps) {
  1201. clear_mipmaps();
  1202. }
  1203. // In-place 90 degrees rotation by following the permutation cycles.
  1204. {
  1205. // Explanation by example (clockwise):
  1206. //
  1207. // abc da
  1208. // def -> eb
  1209. // fc
  1210. //
  1211. // In memory:
  1212. // 012345 012345
  1213. // abcdef -> daebfc
  1214. //
  1215. // Permutation cycles:
  1216. // (0 --a--> 1 --b--> 3 --d--> 0)
  1217. // (2 --c--> 5 --f--> 4 --e--> 2)
  1218. //
  1219. // Applying cycles (backwards):
  1220. // 0->s s=a (store)
  1221. // 3->0 abcdef -> dbcdef
  1222. // 1->3 dbcdef -> dbcbef
  1223. // s->1 dbcbef -> dacbef
  1224. //
  1225. // 2->s s=c
  1226. // 4->2 dacbef -> daebef
  1227. // 5->4 daebef -> daebff
  1228. // s->5 daebff -> daebfc
  1229. const int w = width;
  1230. const int h = height;
  1231. const int size = w * h;
  1232. uint8_t *data_ptr = data.ptrw();
  1233. uint32_t pixel_size = get_format_pixel_size(format);
  1234. uint8_t single_pixel_buffer[16];
  1235. #define PREV_INDEX_IN_CYCLE(index) (p_direction == CLOCKWISE) ? ((h - 1 - (index % h)) * w + (index / h)) : ((index % h) * w + (w - 1 - (index / h)))
  1236. if (w == h) { // Square case, 4-length cycles only (plus irrelevant thus skipped 1-length cycle in the middle for odd-sized squares).
  1237. for (int y = 0; y < h / 2; y++) {
  1238. for (int x = 0; x < (w + 1) / 2; x++) {
  1239. int current = y * w + x;
  1240. memcpy(single_pixel_buffer, data_ptr + current * pixel_size, pixel_size);
  1241. for (int i = 0; i < 3; i++) {
  1242. int prev = PREV_INDEX_IN_CYCLE(current);
  1243. memcpy(data_ptr + current * pixel_size, data_ptr + prev * pixel_size, pixel_size);
  1244. current = prev;
  1245. }
  1246. memcpy(data_ptr + current * pixel_size, single_pixel_buffer, pixel_size);
  1247. }
  1248. }
  1249. } else { // Rectangular case (w != h), kinda unpredictable cycles.
  1250. int permuted_pixels_count = 0;
  1251. for (int i = 0; i < size; i++) {
  1252. int prev = PREV_INDEX_IN_CYCLE(i);
  1253. if (prev == i) {
  1254. // 1-length cycle, pixel remains at the same index.
  1255. permuted_pixels_count++;
  1256. continue;
  1257. }
  1258. // Check whether we already processed this cycle.
  1259. // We iterate over it and if we'll find an index smaller than `i` then we already
  1260. // processed this cycle because we always start at the smallest index in the cycle.
  1261. // TODO: Improve this naive approach, can be done better.
  1262. while (prev > i) {
  1263. prev = PREV_INDEX_IN_CYCLE(prev);
  1264. }
  1265. if (prev < i) {
  1266. continue;
  1267. }
  1268. // Save the in-cycle pixel with the smallest index (`i`).
  1269. memcpy(single_pixel_buffer, data_ptr + i * pixel_size, pixel_size);
  1270. // Overwrite pixels one by one by the preceding pixel in the cycle.
  1271. int current = i;
  1272. prev = PREV_INDEX_IN_CYCLE(current);
  1273. while (prev != i) {
  1274. memcpy(data_ptr + current * pixel_size, data_ptr + prev * pixel_size, pixel_size);
  1275. permuted_pixels_count++;
  1276. current = prev;
  1277. prev = PREV_INDEX_IN_CYCLE(current);
  1278. };
  1279. // Overwrite the remaining pixel in the cycle by the saved pixel with the smallest index.
  1280. memcpy(data_ptr + current * pixel_size, single_pixel_buffer, pixel_size);
  1281. permuted_pixels_count++;
  1282. if (permuted_pixels_count == size) {
  1283. break;
  1284. }
  1285. }
  1286. width = h;
  1287. height = w;
  1288. }
  1289. #undef PREV_INDEX_IN_CYCLE
  1290. }
  1291. if (used_mipmaps) {
  1292. generate_mipmaps();
  1293. }
  1294. }
  1295. void Image::rotate_180() {
  1296. ERR_FAIL_COND_MSG(!_can_modify(format), "Cannot rotate in compressed or custom image formats.");
  1297. ERR_FAIL_COND_MSG(width <= 0, "The Image width specified (" + itos(width) + " pixels) must be greater than 0 pixels.");
  1298. ERR_FAIL_COND_MSG(height <= 0, "The Image height specified (" + itos(height) + " pixels) must be greater than 0 pixels.");
  1299. bool used_mipmaps = has_mipmaps();
  1300. if (used_mipmaps) {
  1301. clear_mipmaps();
  1302. }
  1303. {
  1304. uint8_t *data_ptr = data.ptrw();
  1305. uint32_t pixel_size = get_format_pixel_size(format);
  1306. uint8_t single_pixel_buffer[16];
  1307. uint8_t *from_begin_ptr = data_ptr;
  1308. uint8_t *from_end_ptr = data_ptr + (width * height - 1) * pixel_size;
  1309. while (from_begin_ptr < from_end_ptr) {
  1310. memcpy(single_pixel_buffer, from_begin_ptr, pixel_size);
  1311. memcpy(from_begin_ptr, from_end_ptr, pixel_size);
  1312. memcpy(from_end_ptr, single_pixel_buffer, pixel_size);
  1313. from_begin_ptr += pixel_size;
  1314. from_end_ptr -= pixel_size;
  1315. }
  1316. }
  1317. if (used_mipmaps) {
  1318. generate_mipmaps();
  1319. }
  1320. }
  1321. void Image::flip_y() {
  1322. ERR_FAIL_COND_MSG(!_can_modify(format), "Cannot flip_y in compressed or custom image formats.");
  1323. bool used_mipmaps = has_mipmaps();
  1324. if (used_mipmaps) {
  1325. clear_mipmaps();
  1326. }
  1327. {
  1328. uint8_t *w = data.ptrw();
  1329. uint8_t up[16];
  1330. uint8_t down[16];
  1331. uint32_t pixel_size = get_format_pixel_size(format);
  1332. for (int y = 0; y < height / 2; y++) {
  1333. for (int x = 0; x < width; x++) {
  1334. _get_pixelb(x, y, pixel_size, w, up);
  1335. _get_pixelb(x, height - y - 1, pixel_size, w, down);
  1336. _put_pixelb(x, height - y - 1, pixel_size, w, up);
  1337. _put_pixelb(x, y, pixel_size, w, down);
  1338. }
  1339. }
  1340. }
  1341. if (used_mipmaps) {
  1342. generate_mipmaps();
  1343. }
  1344. }
  1345. void Image::flip_x() {
  1346. ERR_FAIL_COND_MSG(!_can_modify(format), "Cannot flip_x in compressed or custom image formats.");
  1347. bool used_mipmaps = has_mipmaps();
  1348. if (used_mipmaps) {
  1349. clear_mipmaps();
  1350. }
  1351. {
  1352. uint8_t *w = data.ptrw();
  1353. uint8_t up[16];
  1354. uint8_t down[16];
  1355. uint32_t pixel_size = get_format_pixel_size(format);
  1356. for (int y = 0; y < height; y++) {
  1357. for (int x = 0; x < width / 2; x++) {
  1358. _get_pixelb(x, y, pixel_size, w, up);
  1359. _get_pixelb(width - x - 1, y, pixel_size, w, down);
  1360. _put_pixelb(width - x - 1, y, pixel_size, w, up);
  1361. _put_pixelb(x, y, pixel_size, w, down);
  1362. }
  1363. }
  1364. }
  1365. if (used_mipmaps) {
  1366. generate_mipmaps();
  1367. }
  1368. }
  1369. /// Get mipmap size and offset.
  1370. int 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) {
  1371. // Data offset in mipmaps (including the original texture).
  1372. int size = 0;
  1373. int w = p_width;
  1374. int h = p_height;
  1375. // Current mipmap index in the loop below. p_mipmaps is the target mipmap index.
  1376. // In this function, mipmap 0 represents the first mipmap instead of the original texture.
  1377. int mm = 0;
  1378. int pixsize = get_format_pixel_size(p_format);
  1379. int pixshift = get_format_pixel_rshift(p_format);
  1380. int block = get_format_block_size(p_format);
  1381. // Technically, you can still compress up to 1 px no matter the format, so commenting this.
  1382. //int minw, minh;
  1383. //get_format_min_pixel_size(p_format, minw, minh);
  1384. int minw = 1, minh = 1;
  1385. while (true) {
  1386. int bw = w % block != 0 ? w + (block - w % block) : w;
  1387. int bh = h % block != 0 ? h + (block - h % block) : h;
  1388. int s = bw * bh;
  1389. s *= pixsize;
  1390. s >>= pixshift;
  1391. size += s;
  1392. if (p_mipmaps >= 0) {
  1393. w = MAX(minw, w >> 1);
  1394. h = MAX(minh, h >> 1);
  1395. } else {
  1396. if (w == minw && h == minh) {
  1397. break;
  1398. }
  1399. w = MAX(minw, w >> 1);
  1400. h = MAX(minh, h >> 1);
  1401. }
  1402. // Set mipmap size.
  1403. if (r_mm_width) {
  1404. *r_mm_width = w;
  1405. }
  1406. if (r_mm_height) {
  1407. *r_mm_height = h;
  1408. }
  1409. // Reach target mipmap.
  1410. if (p_mipmaps >= 0 && mm == p_mipmaps) {
  1411. break;
  1412. }
  1413. mm++;
  1414. }
  1415. r_mipmaps = mm;
  1416. return size;
  1417. }
  1418. bool Image::_can_modify(Format p_format) const {
  1419. return p_format <= FORMAT_RGBE9995;
  1420. }
  1421. template <class Component, int CC, bool renormalize,
  1422. void (*average_func)(Component &, const Component &, const Component &, const Component &, const Component &),
  1423. void (*renormalize_func)(Component *)>
  1424. static void _generate_po2_mipmap(const Component *p_src, Component *p_dst, uint32_t p_width, uint32_t p_height) {
  1425. //fast power of 2 mipmap generation
  1426. uint32_t dst_w = MAX(p_width >> 1, 1u);
  1427. uint32_t dst_h = MAX(p_height >> 1, 1u);
  1428. int right_step = (p_width == 1) ? 0 : CC;
  1429. int down_step = (p_height == 1) ? 0 : (p_width * CC);
  1430. for (uint32_t i = 0; i < dst_h; i++) {
  1431. const Component *rup_ptr = &p_src[i * 2 * down_step];
  1432. const Component *rdown_ptr = rup_ptr + down_step;
  1433. Component *dst_ptr = &p_dst[i * dst_w * CC];
  1434. uint32_t count = dst_w;
  1435. while (count) {
  1436. count--;
  1437. for (int j = 0; j < CC; j++) {
  1438. average_func(dst_ptr[j], rup_ptr[j], rup_ptr[j + right_step], rdown_ptr[j], rdown_ptr[j + right_step]);
  1439. }
  1440. if (renormalize) {
  1441. renormalize_func(dst_ptr);
  1442. }
  1443. dst_ptr += CC;
  1444. rup_ptr += right_step * 2;
  1445. rdown_ptr += right_step * 2;
  1446. }
  1447. }
  1448. }
  1449. void Image::shrink_x2() {
  1450. ERR_FAIL_COND(data.size() == 0);
  1451. if (mipmaps) {
  1452. //just use the lower mipmap as base and copy all
  1453. Vector<uint8_t> new_img;
  1454. int ofs = get_mipmap_offset(1);
  1455. int new_size = data.size() - ofs;
  1456. new_img.resize(new_size);
  1457. ERR_FAIL_COND(new_img.size() == 0);
  1458. {
  1459. uint8_t *w = new_img.ptrw();
  1460. const uint8_t *r = data.ptr();
  1461. memcpy(w, &r[ofs], new_size);
  1462. }
  1463. width = MAX(width / 2, 1);
  1464. height = MAX(height / 2, 1);
  1465. data = new_img;
  1466. } else {
  1467. Vector<uint8_t> new_img;
  1468. ERR_FAIL_COND(!_can_modify(format));
  1469. int ps = get_format_pixel_size(format);
  1470. new_img.resize((width / 2) * (height / 2) * ps);
  1471. ERR_FAIL_COND(new_img.size() == 0);
  1472. ERR_FAIL_COND(data.size() == 0);
  1473. {
  1474. uint8_t *w = new_img.ptrw();
  1475. const uint8_t *r = data.ptr();
  1476. switch (format) {
  1477. case FORMAT_L8:
  1478. case FORMAT_R8:
  1479. _generate_po2_mipmap<uint8_t, 1, false, Image::average_4_uint8, Image::renormalize_uint8>(r, w, width, height);
  1480. break;
  1481. case FORMAT_LA8:
  1482. _generate_po2_mipmap<uint8_t, 2, false, Image::average_4_uint8, Image::renormalize_uint8>(r, w, width, height);
  1483. break;
  1484. case FORMAT_RG8:
  1485. _generate_po2_mipmap<uint8_t, 2, false, Image::average_4_uint8, Image::renormalize_uint8>(r, w, width, height);
  1486. break;
  1487. case FORMAT_RGB8:
  1488. _generate_po2_mipmap<uint8_t, 3, false, Image::average_4_uint8, Image::renormalize_uint8>(r, w, width, height);
  1489. break;
  1490. case FORMAT_RGBA8:
  1491. _generate_po2_mipmap<uint8_t, 4, false, Image::average_4_uint8, Image::renormalize_uint8>(r, w, width, height);
  1492. break;
  1493. case FORMAT_RF:
  1494. _generate_po2_mipmap<float, 1, false, Image::average_4_float, Image::renormalize_float>(reinterpret_cast<const float *>(r), reinterpret_cast<float *>(w), width, height);
  1495. break;
  1496. case FORMAT_RGF:
  1497. _generate_po2_mipmap<float, 2, false, Image::average_4_float, Image::renormalize_float>(reinterpret_cast<const float *>(r), reinterpret_cast<float *>(w), width, height);
  1498. break;
  1499. case FORMAT_RGBF:
  1500. _generate_po2_mipmap<float, 3, false, Image::average_4_float, Image::renormalize_float>(reinterpret_cast<const float *>(r), reinterpret_cast<float *>(w), width, height);
  1501. break;
  1502. case FORMAT_RGBAF:
  1503. _generate_po2_mipmap<float, 4, false, Image::average_4_float, Image::renormalize_float>(reinterpret_cast<const float *>(r), reinterpret_cast<float *>(w), width, height);
  1504. break;
  1505. case FORMAT_RH:
  1506. _generate_po2_mipmap<uint16_t, 1, false, Image::average_4_half, Image::renormalize_half>(reinterpret_cast<const uint16_t *>(r), reinterpret_cast<uint16_t *>(w), width, height);
  1507. break;
  1508. case FORMAT_RGH:
  1509. _generate_po2_mipmap<uint16_t, 2, false, Image::average_4_half, Image::renormalize_half>(reinterpret_cast<const uint16_t *>(r), reinterpret_cast<uint16_t *>(w), width, height);
  1510. break;
  1511. case FORMAT_RGBH:
  1512. _generate_po2_mipmap<uint16_t, 3, false, Image::average_4_half, Image::renormalize_half>(reinterpret_cast<const uint16_t *>(r), reinterpret_cast<uint16_t *>(w), width, height);
  1513. break;
  1514. case FORMAT_RGBAH:
  1515. _generate_po2_mipmap<uint16_t, 4, false, Image::average_4_half, Image::renormalize_half>(reinterpret_cast<const uint16_t *>(r), reinterpret_cast<uint16_t *>(w), width, height);
  1516. break;
  1517. case FORMAT_RGBE9995:
  1518. _generate_po2_mipmap<uint32_t, 1, false, Image::average_4_rgbe9995, Image::renormalize_rgbe9995>(reinterpret_cast<const uint32_t *>(r), reinterpret_cast<uint32_t *>(w), width, height);
  1519. break;
  1520. default: {
  1521. }
  1522. }
  1523. }
  1524. width /= 2;
  1525. height /= 2;
  1526. data = new_img;
  1527. }
  1528. }
  1529. void Image::normalize() {
  1530. bool used_mipmaps = has_mipmaps();
  1531. if (used_mipmaps) {
  1532. clear_mipmaps();
  1533. }
  1534. for (int y = 0; y < height; y++) {
  1535. for (int x = 0; x < width; x++) {
  1536. Color c = get_pixel(x, y);
  1537. Vector3 v(c.r * 2.0 - 1.0, c.g * 2.0 - 1.0, c.b * 2.0 - 1.0);
  1538. v.normalize();
  1539. c.r = v.x * 0.5 + 0.5;
  1540. c.g = v.y * 0.5 + 0.5;
  1541. c.b = v.z * 0.5 + 0.5;
  1542. set_pixel(x, y, c);
  1543. }
  1544. }
  1545. if (used_mipmaps) {
  1546. generate_mipmaps(true);
  1547. }
  1548. }
  1549. Error Image::generate_mipmaps(bool p_renormalize) {
  1550. ERR_FAIL_COND_V_MSG(!_can_modify(format), ERR_UNAVAILABLE, "Cannot generate mipmaps in compressed or custom image formats.");
  1551. ERR_FAIL_COND_V_MSG(format == FORMAT_RGBA4444, ERR_UNAVAILABLE, "Cannot generate mipmaps from RGBA4444 format.");
  1552. ERR_FAIL_COND_V_MSG(width == 0 || height == 0, ERR_UNCONFIGURED, "Cannot generate mipmaps with width or height equal to 0.");
  1553. int mmcount;
  1554. int size = _get_dst_image_size(width, height, format, mmcount);
  1555. data.resize(size);
  1556. uint8_t *wp = data.ptrw();
  1557. int prev_ofs = 0;
  1558. int prev_h = height;
  1559. int prev_w = width;
  1560. for (int i = 1; i <= mmcount; i++) {
  1561. int ofs, w, h;
  1562. _get_mipmap_offset_and_size(i, ofs, w, h);
  1563. switch (format) {
  1564. case FORMAT_L8:
  1565. case FORMAT_R8:
  1566. _generate_po2_mipmap<uint8_t, 1, false, Image::average_4_uint8, Image::renormalize_uint8>(&wp[prev_ofs], &wp[ofs], prev_w, prev_h);
  1567. break;
  1568. case FORMAT_LA8:
  1569. case FORMAT_RG8:
  1570. _generate_po2_mipmap<uint8_t, 2, false, Image::average_4_uint8, Image::renormalize_uint8>(&wp[prev_ofs], &wp[ofs], prev_w, prev_h);
  1571. break;
  1572. case FORMAT_RGB8:
  1573. if (p_renormalize) {
  1574. _generate_po2_mipmap<uint8_t, 3, true, Image::average_4_uint8, Image::renormalize_uint8>(&wp[prev_ofs], &wp[ofs], prev_w, prev_h);
  1575. } else {
  1576. _generate_po2_mipmap<uint8_t, 3, false, Image::average_4_uint8, Image::renormalize_uint8>(&wp[prev_ofs], &wp[ofs], prev_w, prev_h);
  1577. }
  1578. break;
  1579. case FORMAT_RGBA8:
  1580. if (p_renormalize) {
  1581. _generate_po2_mipmap<uint8_t, 4, true, Image::average_4_uint8, Image::renormalize_uint8>(&wp[prev_ofs], &wp[ofs], prev_w, prev_h);
  1582. } else {
  1583. _generate_po2_mipmap<uint8_t, 4, false, Image::average_4_uint8, Image::renormalize_uint8>(&wp[prev_ofs], &wp[ofs], prev_w, prev_h);
  1584. }
  1585. break;
  1586. case FORMAT_RF:
  1587. _generate_po2_mipmap<float, 1, false, Image::average_4_float, Image::renormalize_float>(reinterpret_cast<const float *>(&wp[prev_ofs]), reinterpret_cast<float *>(&wp[ofs]), prev_w, prev_h);
  1588. break;
  1589. case FORMAT_RGF:
  1590. _generate_po2_mipmap<float, 2, false, Image::average_4_float, Image::renormalize_float>(reinterpret_cast<const float *>(&wp[prev_ofs]), reinterpret_cast<float *>(&wp[ofs]), prev_w, prev_h);
  1591. break;
  1592. case FORMAT_RGBF:
  1593. if (p_renormalize) {
  1594. _generate_po2_mipmap<float, 3, true, Image::average_4_float, Image::renormalize_float>(reinterpret_cast<const float *>(&wp[prev_ofs]), reinterpret_cast<float *>(&wp[ofs]), prev_w, prev_h);
  1595. } else {
  1596. _generate_po2_mipmap<float, 3, false, Image::average_4_float, Image::renormalize_float>(reinterpret_cast<const float *>(&wp[prev_ofs]), reinterpret_cast<float *>(&wp[ofs]), prev_w, prev_h);
  1597. }
  1598. break;
  1599. case FORMAT_RGBAF:
  1600. if (p_renormalize) {
  1601. _generate_po2_mipmap<float, 4, true, Image::average_4_float, Image::renormalize_float>(reinterpret_cast<const float *>(&wp[prev_ofs]), reinterpret_cast<float *>(&wp[ofs]), prev_w, prev_h);
  1602. } else {
  1603. _generate_po2_mipmap<float, 4, false, Image::average_4_float, Image::renormalize_float>(reinterpret_cast<const float *>(&wp[prev_ofs]), reinterpret_cast<float *>(&wp[ofs]), prev_w, prev_h);
  1604. }
  1605. break;
  1606. case FORMAT_RH:
  1607. _generate_po2_mipmap<uint16_t, 1, false, Image::average_4_half, Image::renormalize_half>(reinterpret_cast<const uint16_t *>(&wp[prev_ofs]), reinterpret_cast<uint16_t *>(&wp[ofs]), prev_w, prev_h);
  1608. break;
  1609. case FORMAT_RGH:
  1610. _generate_po2_mipmap<uint16_t, 2, false, Image::average_4_half, Image::renormalize_half>(reinterpret_cast<const uint16_t *>(&wp[prev_ofs]), reinterpret_cast<uint16_t *>(&wp[ofs]), prev_w, prev_h);
  1611. break;
  1612. case FORMAT_RGBH:
  1613. if (p_renormalize) {
  1614. _generate_po2_mipmap<uint16_t, 3, true, Image::average_4_half, Image::renormalize_half>(reinterpret_cast<const uint16_t *>(&wp[prev_ofs]), reinterpret_cast<uint16_t *>(&wp[ofs]), prev_w, prev_h);
  1615. } else {
  1616. _generate_po2_mipmap<uint16_t, 3, false, Image::average_4_half, Image::renormalize_half>(reinterpret_cast<const uint16_t *>(&wp[prev_ofs]), reinterpret_cast<uint16_t *>(&wp[ofs]), prev_w, prev_h);
  1617. }
  1618. break;
  1619. case FORMAT_RGBAH:
  1620. if (p_renormalize) {
  1621. _generate_po2_mipmap<uint16_t, 4, true, Image::average_4_half, Image::renormalize_half>(reinterpret_cast<const uint16_t *>(&wp[prev_ofs]), reinterpret_cast<uint16_t *>(&wp[ofs]), prev_w, prev_h);
  1622. } else {
  1623. _generate_po2_mipmap<uint16_t, 4, false, Image::average_4_half, Image::renormalize_half>(reinterpret_cast<const uint16_t *>(&wp[prev_ofs]), reinterpret_cast<uint16_t *>(&wp[ofs]), prev_w, prev_h);
  1624. }
  1625. break;
  1626. case FORMAT_RGBE9995:
  1627. if (p_renormalize) {
  1628. _generate_po2_mipmap<uint32_t, 1, true, Image::average_4_rgbe9995, Image::renormalize_rgbe9995>(reinterpret_cast<const uint32_t *>(&wp[prev_ofs]), reinterpret_cast<uint32_t *>(&wp[ofs]), prev_w, prev_h);
  1629. } else {
  1630. _generate_po2_mipmap<uint32_t, 1, false, Image::average_4_rgbe9995, Image::renormalize_rgbe9995>(reinterpret_cast<const uint32_t *>(&wp[prev_ofs]), reinterpret_cast<uint32_t *>(&wp[ofs]), prev_w, prev_h);
  1631. }
  1632. break;
  1633. default: {
  1634. }
  1635. }
  1636. prev_ofs = ofs;
  1637. prev_w = w;
  1638. prev_h = h;
  1639. }
  1640. mipmaps = true;
  1641. return OK;
  1642. }
  1643. Error Image::generate_mipmap_roughness(RoughnessChannel p_roughness_channel, const Ref<Image> &p_normal_map) {
  1644. Vector<double> normal_sat_vec; //summed area table
  1645. double *normal_sat = nullptr; //summed area table for normal map
  1646. int normal_w = 0, normal_h = 0;
  1647. 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");
  1648. Ref<Image> nm = p_normal_map->duplicate();
  1649. if (nm->is_compressed()) {
  1650. nm->decompress();
  1651. }
  1652. normal_w = nm->get_width();
  1653. normal_h = nm->get_height();
  1654. normal_sat_vec.resize(normal_w * normal_h * 3);
  1655. normal_sat = normal_sat_vec.ptrw();
  1656. //create summed area table
  1657. for (int y = 0; y < normal_h; y++) {
  1658. double line_sum[3] = { 0, 0, 0 };
  1659. for (int x = 0; x < normal_w; x++) {
  1660. double normal[3];
  1661. Color color = nm->get_pixel(x, y);
  1662. normal[0] = color.r * 2.0 - 1.0;
  1663. normal[1] = color.g * 2.0 - 1.0;
  1664. normal[2] = Math::sqrt(MAX(0.0, 1.0 - (normal[0] * normal[0] + normal[1] * normal[1]))); //reconstruct if missing
  1665. line_sum[0] += normal[0];
  1666. line_sum[1] += normal[1];
  1667. line_sum[2] += normal[2];
  1668. uint32_t ofs = (y * normal_w + x) * 3;
  1669. normal_sat[ofs + 0] = line_sum[0];
  1670. normal_sat[ofs + 1] = line_sum[1];
  1671. normal_sat[ofs + 2] = line_sum[2];
  1672. if (y > 0) {
  1673. uint32_t prev_ofs = ((y - 1) * normal_w + x) * 3;
  1674. normal_sat[ofs + 0] += normal_sat[prev_ofs + 0];
  1675. normal_sat[ofs + 1] += normal_sat[prev_ofs + 1];
  1676. normal_sat[ofs + 2] += normal_sat[prev_ofs + 2];
  1677. }
  1678. }
  1679. }
  1680. #if 0
  1681. {
  1682. Vector3 beg(normal_sat_vec[0], normal_sat_vec[1], normal_sat_vec[2]);
  1683. Vector3 end(normal_sat_vec[normal_sat_vec.size() - 3], normal_sat_vec[normal_sat_vec.size() - 2], normal_sat_vec[normal_sat_vec.size() - 1]);
  1684. Vector3 avg = (end - beg) / (normal_w * normal_h);
  1685. print_line("average: " + avg);
  1686. }
  1687. #endif
  1688. int mmcount;
  1689. _get_dst_image_size(width, height, format, mmcount);
  1690. uint8_t *base_ptr = data.ptrw();
  1691. for (int i = 1; i <= mmcount; i++) {
  1692. int ofs, w, h;
  1693. _get_mipmap_offset_and_size(i, ofs, w, h);
  1694. uint8_t *ptr = &base_ptr[ofs];
  1695. for (int x = 0; x < w; x++) {
  1696. for (int y = 0; y < h; y++) {
  1697. int from_x = x * normal_w / w;
  1698. int from_y = y * normal_h / h;
  1699. int to_x = (x + 1) * normal_w / w;
  1700. int to_y = (y + 1) * normal_h / h;
  1701. to_x = MIN(to_x - 1, normal_w);
  1702. to_y = MIN(to_y - 1, normal_h);
  1703. int size_x = (to_x - from_x) + 1;
  1704. int size_y = (to_y - from_y) + 1;
  1705. //summed area table version (much faster)
  1706. double avg[3] = { 0, 0, 0 };
  1707. if (from_x > 0 && from_y > 0) {
  1708. uint32_t tofs = ((from_y - 1) * normal_w + (from_x - 1)) * 3;
  1709. avg[0] += normal_sat[tofs + 0];
  1710. avg[1] += normal_sat[tofs + 1];
  1711. avg[2] += normal_sat[tofs + 2];
  1712. }
  1713. if (from_y > 0) {
  1714. uint32_t tofs = ((from_y - 1) * normal_w + to_x) * 3;
  1715. avg[0] -= normal_sat[tofs + 0];
  1716. avg[1] -= normal_sat[tofs + 1];
  1717. avg[2] -= normal_sat[tofs + 2];
  1718. }
  1719. if (from_x > 0) {
  1720. uint32_t tofs = (to_y * normal_w + (from_x - 1)) * 3;
  1721. avg[0] -= normal_sat[tofs + 0];
  1722. avg[1] -= normal_sat[tofs + 1];
  1723. avg[2] -= normal_sat[tofs + 2];
  1724. }
  1725. uint32_t tofs = (to_y * normal_w + to_x) * 3;
  1726. avg[0] += normal_sat[tofs + 0];
  1727. avg[1] += normal_sat[tofs + 1];
  1728. avg[2] += normal_sat[tofs + 2];
  1729. double div = double(size_x * size_y);
  1730. Vector3 vec(avg[0] / div, avg[1] / div, avg[2] / div);
  1731. float r = vec.length();
  1732. int pixel_ofs = y * w + x;
  1733. Color c = _get_color_at_ofs(ptr, pixel_ofs);
  1734. float roughness = 0;
  1735. switch (p_roughness_channel) {
  1736. case ROUGHNESS_CHANNEL_R: {
  1737. roughness = c.r;
  1738. } break;
  1739. case ROUGHNESS_CHANNEL_G: {
  1740. roughness = c.g;
  1741. } break;
  1742. case ROUGHNESS_CHANNEL_B: {
  1743. roughness = c.b;
  1744. } break;
  1745. case ROUGHNESS_CHANNEL_L: {
  1746. roughness = c.get_v();
  1747. } break;
  1748. case ROUGHNESS_CHANNEL_A: {
  1749. roughness = c.a;
  1750. } break;
  1751. }
  1752. float variance = 0;
  1753. if (r < 1.0f) {
  1754. float r2 = r * r;
  1755. float kappa = (3.0f * r - r * r2) / (1.0f - r2);
  1756. variance = 0.25f / kappa;
  1757. }
  1758. float threshold = 0.4;
  1759. roughness = Math::sqrt(roughness * roughness + MIN(3.0f * variance, threshold * threshold));
  1760. switch (p_roughness_channel) {
  1761. case ROUGHNESS_CHANNEL_R: {
  1762. c.r = roughness;
  1763. } break;
  1764. case ROUGHNESS_CHANNEL_G: {
  1765. c.g = roughness;
  1766. } break;
  1767. case ROUGHNESS_CHANNEL_B: {
  1768. c.b = roughness;
  1769. } break;
  1770. case ROUGHNESS_CHANNEL_L: {
  1771. c.r = roughness;
  1772. c.g = roughness;
  1773. c.b = roughness;
  1774. } break;
  1775. case ROUGHNESS_CHANNEL_A: {
  1776. c.a = roughness;
  1777. } break;
  1778. }
  1779. _set_color_at_ofs(ptr, pixel_ofs, c);
  1780. }
  1781. }
  1782. #if 0
  1783. {
  1784. int size = get_mipmap_byte_size(i);
  1785. print_line("size for mimpap " + itos(i) + ": " + itos(size));
  1786. Vector<uint8_t> imgdata;
  1787. imgdata.resize(size);
  1788. uint8_t* wr = imgdata.ptrw();
  1789. memcpy(wr.ptr(), ptr, size);
  1790. wr = uint8_t*();
  1791. Ref<Image> im = Image::create_from_data(w, h, false, format, imgdata);
  1792. im->save_png("res://mipmap_" + itos(i) + ".png");
  1793. }
  1794. #endif
  1795. }
  1796. return OK;
  1797. }
  1798. void Image::clear_mipmaps() {
  1799. if (!mipmaps) {
  1800. return;
  1801. }
  1802. if (is_empty()) {
  1803. return;
  1804. }
  1805. int ofs, w, h;
  1806. _get_mipmap_offset_and_size(1, ofs, w, h);
  1807. data.resize(ofs);
  1808. mipmaps = false;
  1809. }
  1810. bool Image::is_empty() const {
  1811. return (data.size() == 0);
  1812. }
  1813. Vector<uint8_t> Image::get_data() const {
  1814. return data;
  1815. }
  1816. Ref<Image> Image::create_empty(int p_width, int p_height, bool p_use_mipmaps, Format p_format) {
  1817. Ref<Image> image;
  1818. image.instantiate();
  1819. image->initialize_data(p_width, p_height, p_use_mipmaps, p_format);
  1820. return image;
  1821. }
  1822. 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) {
  1823. Ref<Image> image;
  1824. image.instantiate();
  1825. image->initialize_data(p_width, p_height, p_use_mipmaps, p_format, p_data);
  1826. return image;
  1827. }
  1828. void Image::set_data(int p_width, int p_height, bool p_use_mipmaps, Format p_format, const Vector<uint8_t> &p_data) {
  1829. initialize_data(p_width, p_height, p_use_mipmaps, p_format, p_data);
  1830. }
  1831. void Image::initialize_data(int p_width, int p_height, bool p_use_mipmaps, Format p_format) {
  1832. ERR_FAIL_COND_MSG(p_width <= 0, "The Image width specified (" + itos(p_width) + " pixels) must be greater than 0 pixels.");
  1833. ERR_FAIL_COND_MSG(p_height <= 0, "The Image height specified (" + itos(p_height) + " pixels) must be greater than 0 pixels.");
  1834. ERR_FAIL_COND_MSG(p_width > MAX_WIDTH,
  1835. "The Image width specified (" + itos(p_width) + " pixels) cannot be greater than " + itos(MAX_WIDTH) + "pixels.");
  1836. ERR_FAIL_COND_MSG(p_height > MAX_HEIGHT,
  1837. "The Image height specified (" + itos(p_height) + " pixels) cannot be greater than " + itos(MAX_HEIGHT) + "pixels.");
  1838. ERR_FAIL_COND_MSG(p_width * p_height > MAX_PIXELS,
  1839. "Too many pixels for Image. Maximum is " + itos(MAX_WIDTH) + "x" + itos(MAX_HEIGHT) + " = " + itos(MAX_PIXELS) + "pixels.");
  1840. ERR_FAIL_INDEX_MSG(p_format, FORMAT_MAX, "The Image format specified (" + itos(p_format) + ") is out of range. See Image's Format enum.");
  1841. int mm = 0;
  1842. int size = _get_dst_image_size(p_width, p_height, p_format, mm, p_use_mipmaps ? -1 : 0);
  1843. data.resize(size);
  1844. {
  1845. uint8_t *w = data.ptrw();
  1846. memset(w, 0, size);
  1847. }
  1848. width = p_width;
  1849. height = p_height;
  1850. mipmaps = p_use_mipmaps;
  1851. format = p_format;
  1852. }
  1853. void Image::initialize_data(int p_width, int p_height, bool p_use_mipmaps, Format p_format, const Vector<uint8_t> &p_data) {
  1854. ERR_FAIL_COND_MSG(p_width <= 0, "The Image width specified (" + itos(p_width) + " pixels) must be greater than 0 pixels.");
  1855. ERR_FAIL_COND_MSG(p_height <= 0, "The Image height specified (" + itos(p_height) + " pixels) must be greater than 0 pixels.");
  1856. ERR_FAIL_COND_MSG(p_width > MAX_WIDTH,
  1857. "The Image width specified (" + itos(p_width) + " pixels) cannot be greater than " + itos(MAX_WIDTH) + " pixels.");
  1858. ERR_FAIL_COND_MSG(p_height > MAX_HEIGHT,
  1859. "The Image height specified (" + itos(p_height) + " pixels) cannot be greater than " + itos(MAX_HEIGHT) + " pixels.");
  1860. ERR_FAIL_COND_MSG(p_width * p_height > MAX_PIXELS,
  1861. "Too many pixels for Image. Maximum is " + itos(MAX_WIDTH) + "x" + itos(MAX_HEIGHT) + " = " + itos(MAX_PIXELS) + "pixels .");
  1862. ERR_FAIL_INDEX_MSG(p_format, FORMAT_MAX, "The Image format specified (" + itos(p_format) + ") is out of range. See Image's Format enum.");
  1863. int mm;
  1864. int size = _get_dst_image_size(p_width, p_height, p_format, mm, p_use_mipmaps ? -1 : 0);
  1865. if (unlikely(p_data.size() != size)) {
  1866. String description_mipmaps;
  1867. if (p_use_mipmaps) {
  1868. const int num_mipmaps = get_image_required_mipmaps(p_width, p_height, p_format);
  1869. if (num_mipmaps != 1) {
  1870. description_mipmaps = vformat("with %d mipmaps", num_mipmaps);
  1871. } else {
  1872. description_mipmaps = "with 1 mipmap";
  1873. }
  1874. } else {
  1875. description_mipmaps = "without mipmaps";
  1876. }
  1877. const String description = vformat("%dx%dx%d (%s)", p_width, p_height, get_format_pixel_size(p_format), description_mipmaps);
  1878. ERR_FAIL_MSG(vformat("Expected Image data size of %s = %d bytes, got %d bytes instead.", description, size, p_data.size()));
  1879. }
  1880. height = p_height;
  1881. width = p_width;
  1882. format = p_format;
  1883. data = p_data;
  1884. mipmaps = p_use_mipmaps;
  1885. }
  1886. void Image::initialize_data(const char **p_xpm) {
  1887. int size_width = 0;
  1888. int size_height = 0;
  1889. int pixelchars = 0;
  1890. mipmaps = false;
  1891. bool has_alpha = false;
  1892. enum Status {
  1893. READING_HEADER,
  1894. READING_COLORS,
  1895. READING_PIXELS,
  1896. DONE
  1897. };
  1898. Status status = READING_HEADER;
  1899. int line = 0;
  1900. HashMap<String, Color> colormap;
  1901. int colormap_size = 0;
  1902. uint32_t pixel_size = 0;
  1903. uint8_t *data_write = nullptr;
  1904. while (status != DONE) {
  1905. const char *line_ptr = p_xpm[line];
  1906. switch (status) {
  1907. case READING_HEADER: {
  1908. String line_str = line_ptr;
  1909. line_str.replace("\t", " ");
  1910. size_width = line_str.get_slicec(' ', 0).to_int();
  1911. size_height = line_str.get_slicec(' ', 1).to_int();
  1912. colormap_size = line_str.get_slicec(' ', 2).to_int();
  1913. pixelchars = line_str.get_slicec(' ', 3).to_int();
  1914. ERR_FAIL_COND(colormap_size > 32766);
  1915. ERR_FAIL_COND(pixelchars > 5);
  1916. ERR_FAIL_COND(size_width > 32767);
  1917. ERR_FAIL_COND(size_height > 32767);
  1918. status = READING_COLORS;
  1919. } break;
  1920. case READING_COLORS: {
  1921. String colorstring;
  1922. for (int i = 0; i < pixelchars; i++) {
  1923. colorstring += *line_ptr;
  1924. line_ptr++;
  1925. }
  1926. //skip spaces
  1927. while (*line_ptr == ' ' || *line_ptr == '\t' || *line_ptr == 0) {
  1928. if (*line_ptr == 0) {
  1929. break;
  1930. }
  1931. line_ptr++;
  1932. }
  1933. if (*line_ptr == 'c') {
  1934. line_ptr++;
  1935. while (*line_ptr == ' ' || *line_ptr == '\t' || *line_ptr == 0) {
  1936. if (*line_ptr == 0) {
  1937. break;
  1938. }
  1939. line_ptr++;
  1940. }
  1941. if (*line_ptr == '#') {
  1942. line_ptr++;
  1943. uint8_t col_r = 0;
  1944. uint8_t col_g = 0;
  1945. uint8_t col_b = 0;
  1946. //uint8_t col_a=255;
  1947. for (int i = 0; i < 6; i++) {
  1948. char v = line_ptr[i];
  1949. if (is_digit(v)) {
  1950. v -= '0';
  1951. } else if (v >= 'A' && v <= 'F') {
  1952. v = (v - 'A') + 10;
  1953. } else if (v >= 'a' && v <= 'f') {
  1954. v = (v - 'a') + 10;
  1955. } else {
  1956. break;
  1957. }
  1958. switch (i) {
  1959. case 0:
  1960. col_r = v << 4;
  1961. break;
  1962. case 1:
  1963. col_r |= v;
  1964. break;
  1965. case 2:
  1966. col_g = v << 4;
  1967. break;
  1968. case 3:
  1969. col_g |= v;
  1970. break;
  1971. case 4:
  1972. col_b = v << 4;
  1973. break;
  1974. case 5:
  1975. col_b |= v;
  1976. break;
  1977. }
  1978. }
  1979. // magenta mask
  1980. if (col_r == 255 && col_g == 0 && col_b == 255) {
  1981. colormap[colorstring] = Color(0, 0, 0, 0);
  1982. has_alpha = true;
  1983. } else {
  1984. colormap[colorstring] = Color(col_r / 255.0, col_g / 255.0, col_b / 255.0, 1.0);
  1985. }
  1986. }
  1987. }
  1988. if (line == colormap_size) {
  1989. status = READING_PIXELS;
  1990. initialize_data(size_width, size_height, false, has_alpha ? FORMAT_RGBA8 : FORMAT_RGB8);
  1991. data_write = data.ptrw();
  1992. pixel_size = has_alpha ? 4 : 3;
  1993. }
  1994. } break;
  1995. case READING_PIXELS: {
  1996. int y = line - colormap_size - 1;
  1997. for (int x = 0; x < size_width; x++) {
  1998. char pixelstr[6] = { 0, 0, 0, 0, 0, 0 };
  1999. for (int i = 0; i < pixelchars; i++) {
  2000. pixelstr[i] = line_ptr[x * pixelchars + i];
  2001. }
  2002. Color *colorptr = colormap.getptr(pixelstr);
  2003. ERR_FAIL_COND(!colorptr);
  2004. uint8_t pixel[4];
  2005. for (uint32_t i = 0; i < pixel_size; i++) {
  2006. pixel[i] = CLAMP((*colorptr)[i] * 255, 0, 255);
  2007. }
  2008. _put_pixelb(x, y, pixel_size, data_write, pixel);
  2009. }
  2010. if (y == (size_height - 1)) {
  2011. status = DONE;
  2012. }
  2013. } break;
  2014. default: {
  2015. }
  2016. }
  2017. line++;
  2018. }
  2019. }
  2020. #define DETECT_ALPHA_MAX_THRESHOLD 254
  2021. #define DETECT_ALPHA_MIN_THRESHOLD 2
  2022. #define DETECT_ALPHA(m_value) \
  2023. { \
  2024. uint8_t value = m_value; \
  2025. if (value < DETECT_ALPHA_MIN_THRESHOLD) \
  2026. bit = true; \
  2027. else if (value < DETECT_ALPHA_MAX_THRESHOLD) { \
  2028. detected = true; \
  2029. break; \
  2030. } \
  2031. }
  2032. #define DETECT_NON_ALPHA(m_value) \
  2033. { \
  2034. uint8_t value = m_value; \
  2035. if (value > 0) { \
  2036. detected = true; \
  2037. break; \
  2038. } \
  2039. }
  2040. bool Image::is_invisible() const {
  2041. if (format == FORMAT_L8 ||
  2042. format == FORMAT_RGB8 || format == FORMAT_RG8) {
  2043. return false;
  2044. }
  2045. int len = data.size();
  2046. if (len == 0) {
  2047. return true;
  2048. }
  2049. int w, h;
  2050. _get_mipmap_offset_and_size(1, len, w, h);
  2051. const uint8_t *r = data.ptr();
  2052. const unsigned char *data_ptr = r;
  2053. bool detected = false;
  2054. switch (format) {
  2055. case FORMAT_LA8: {
  2056. for (int i = 0; i < (len >> 1); i++) {
  2057. DETECT_NON_ALPHA(data_ptr[(i << 1) + 1]);
  2058. }
  2059. } break;
  2060. case FORMAT_RGBA8: {
  2061. for (int i = 0; i < (len >> 2); i++) {
  2062. DETECT_NON_ALPHA(data_ptr[(i << 2) + 3])
  2063. }
  2064. } break;
  2065. case FORMAT_DXT3:
  2066. case FORMAT_DXT5: {
  2067. detected = true;
  2068. } break;
  2069. default: {
  2070. }
  2071. }
  2072. return !detected;
  2073. }
  2074. Image::AlphaMode Image::detect_alpha() const {
  2075. int len = data.size();
  2076. if (len == 0) {
  2077. return ALPHA_NONE;
  2078. }
  2079. int w, h;
  2080. _get_mipmap_offset_and_size(1, len, w, h);
  2081. const uint8_t *r = data.ptr();
  2082. const unsigned char *data_ptr = r;
  2083. bool bit = false;
  2084. bool detected = false;
  2085. switch (format) {
  2086. case FORMAT_LA8: {
  2087. for (int i = 0; i < (len >> 1); i++) {
  2088. DETECT_ALPHA(data_ptr[(i << 1) + 1]);
  2089. }
  2090. } break;
  2091. case FORMAT_RGBA8: {
  2092. for (int i = 0; i < (len >> 2); i++) {
  2093. DETECT_ALPHA(data_ptr[(i << 2) + 3])
  2094. }
  2095. } break;
  2096. case FORMAT_DXT3:
  2097. case FORMAT_DXT5: {
  2098. detected = true;
  2099. } break;
  2100. default: {
  2101. }
  2102. }
  2103. if (detected) {
  2104. return ALPHA_BLEND;
  2105. } else if (bit) {
  2106. return ALPHA_BIT;
  2107. } else {
  2108. return ALPHA_NONE;
  2109. }
  2110. }
  2111. Error Image::load(const String &p_path) {
  2112. #ifdef DEBUG_ENABLED
  2113. if (p_path.begins_with("res://") && ResourceLoader::exists(p_path)) {
  2114. WARN_PRINT("Loaded resource as image file, this will not work on export: '" + p_path + "'. Instead, import the image file as an Image resource and load it normally as a resource.");
  2115. }
  2116. #endif
  2117. return ImageLoader::load_image(p_path, this);
  2118. }
  2119. Ref<Image> Image::load_from_file(const String &p_path) {
  2120. #ifdef DEBUG_ENABLED
  2121. if (p_path.begins_with("res://") && ResourceLoader::exists(p_path)) {
  2122. WARN_PRINT("Loaded resource as image file, this will not work on export: '" + p_path + "'. Instead, import the image file as an Image resource and load it normally as a resource.");
  2123. }
  2124. #endif
  2125. Ref<Image> image;
  2126. image.instantiate();
  2127. Error err = ImageLoader::load_image(p_path, image);
  2128. if (err != OK) {
  2129. ERR_FAIL_V_MSG(Ref<Image>(), vformat("Failed to load image. Error %d", err));
  2130. }
  2131. return image;
  2132. }
  2133. Error Image::save_png(const String &p_path) const {
  2134. if (save_png_func == nullptr) {
  2135. return ERR_UNAVAILABLE;
  2136. }
  2137. return save_png_func(p_path, Ref<Image>((Image *)this));
  2138. }
  2139. Error Image::save_jpg(const String &p_path, float p_quality) const {
  2140. if (save_jpg_func == nullptr) {
  2141. return ERR_UNAVAILABLE;
  2142. }
  2143. return save_jpg_func(p_path, Ref<Image>((Image *)this), p_quality);
  2144. }
  2145. Vector<uint8_t> Image::save_png_to_buffer() const {
  2146. if (save_png_buffer_func == nullptr) {
  2147. return Vector<uint8_t>();
  2148. }
  2149. return save_png_buffer_func(Ref<Image>((Image *)this));
  2150. }
  2151. Vector<uint8_t> Image::save_jpg_to_buffer(float p_quality) const {
  2152. if (save_jpg_buffer_func == nullptr) {
  2153. return Vector<uint8_t>();
  2154. }
  2155. return save_jpg_buffer_func(Ref<Image>((Image *)this), p_quality);
  2156. }
  2157. Error Image::save_exr(const String &p_path, bool p_grayscale) const {
  2158. if (save_exr_func == nullptr) {
  2159. return ERR_UNAVAILABLE;
  2160. }
  2161. return save_exr_func(p_path, Ref<Image>((Image *)this), p_grayscale);
  2162. }
  2163. Vector<uint8_t> Image::save_exr_to_buffer(bool p_grayscale) const {
  2164. if (save_exr_buffer_func == nullptr) {
  2165. return Vector<uint8_t>();
  2166. }
  2167. return save_exr_buffer_func(Ref<Image>((Image *)this), p_grayscale);
  2168. }
  2169. Error Image::save_webp(const String &p_path, const bool p_lossy, const float p_quality) const {
  2170. if (save_webp_func == nullptr) {
  2171. return ERR_UNAVAILABLE;
  2172. }
  2173. ERR_FAIL_COND_V_MSG(p_lossy && !(0.0f <= p_quality && p_quality <= 1.0f), ERR_INVALID_PARAMETER, "The WebP lossy quality was set to " + rtos(p_quality) + ", which is not valid. WebP lossy quality must be between 0.0 and 1.0 (inclusive).");
  2174. return save_webp_func(p_path, Ref<Image>((Image *)this), p_lossy, p_quality);
  2175. }
  2176. Vector<uint8_t> Image::save_webp_to_buffer(const bool p_lossy, const float p_quality) const {
  2177. if (save_webp_buffer_func == nullptr) {
  2178. return Vector<uint8_t>();
  2179. }
  2180. ERR_FAIL_COND_V_MSG(p_lossy && !(0.0f <= p_quality && p_quality <= 1.0f), Vector<uint8_t>(), "The WebP lossy quality was set to " + rtos(p_quality) + ", which is not valid. WebP lossy quality must be between 0.0 and 1.0 (inclusive).");
  2181. return save_webp_buffer_func(Ref<Image>((Image *)this), p_lossy, p_quality);
  2182. }
  2183. int Image::get_image_data_size(int p_width, int p_height, Format p_format, bool p_mipmaps) {
  2184. int mm;
  2185. return _get_dst_image_size(p_width, p_height, p_format, mm, p_mipmaps ? -1 : 0);
  2186. }
  2187. int Image::get_image_required_mipmaps(int p_width, int p_height, Format p_format) {
  2188. int mm;
  2189. _get_dst_image_size(p_width, p_height, p_format, mm, -1);
  2190. return mm;
  2191. }
  2192. Size2i Image::get_image_mipmap_size(int p_width, int p_height, Format p_format, int p_mipmap) {
  2193. int mm;
  2194. Size2i ret;
  2195. _get_dst_image_size(p_width, p_height, p_format, mm, p_mipmap, &ret.x, &ret.y);
  2196. return ret;
  2197. }
  2198. int Image::get_image_mipmap_offset(int p_width, int p_height, Format p_format, int p_mipmap) {
  2199. if (p_mipmap <= 0) {
  2200. return 0;
  2201. }
  2202. int mm;
  2203. return _get_dst_image_size(p_width, p_height, p_format, mm, p_mipmap - 1);
  2204. }
  2205. int 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) {
  2206. if (p_mipmap <= 0) {
  2207. r_w = p_width;
  2208. r_h = p_height;
  2209. return 0;
  2210. }
  2211. int mm;
  2212. return _get_dst_image_size(p_width, p_height, p_format, mm, p_mipmap - 1, &r_w, &r_h);
  2213. }
  2214. bool Image::is_compressed() const {
  2215. return format > FORMAT_RGBE9995;
  2216. }
  2217. Error Image::decompress() {
  2218. if (((format >= FORMAT_DXT1 && format <= FORMAT_RGTC_RG) || (format == FORMAT_DXT5_RA_AS_RG)) && _image_decompress_bc) {
  2219. _image_decompress_bc(this);
  2220. } else if (format >= FORMAT_BPTC_RGBA && format <= FORMAT_BPTC_RGBFU && _image_decompress_bptc) {
  2221. _image_decompress_bptc(this);
  2222. } else if (format == FORMAT_ETC && _image_decompress_etc1) {
  2223. _image_decompress_etc1(this);
  2224. } else if (format >= FORMAT_ETC2_R11 && format <= FORMAT_ETC2_RA_AS_RG && _image_decompress_etc2) {
  2225. _image_decompress_etc2(this);
  2226. } else if (format >= FORMAT_ASTC_4x4 && format <= FORMAT_ASTC_8x8_HDR && _image_decompress_astc) {
  2227. _image_decompress_astc(this);
  2228. } else {
  2229. return ERR_UNAVAILABLE;
  2230. }
  2231. return OK;
  2232. }
  2233. Error Image::compress(CompressMode p_mode, CompressSource p_source, float p_lossy_quality, ASTCFormat p_astc_format) {
  2234. ERR_FAIL_INDEX_V_MSG(p_mode, COMPRESS_MAX, ERR_INVALID_PARAMETER, "Invalid compress mode.");
  2235. ERR_FAIL_INDEX_V_MSG(p_source, COMPRESS_SOURCE_MAX, ERR_INVALID_PARAMETER, "Invalid compress source.");
  2236. return compress_from_channels(p_mode, detect_used_channels(p_source), p_lossy_quality, p_astc_format);
  2237. }
  2238. Error Image::compress_from_channels(CompressMode p_mode, UsedChannels p_channels, float p_lossy_quality, ASTCFormat p_astc_format) {
  2239. ERR_FAIL_COND_V(data.is_empty(), ERR_INVALID_DATA);
  2240. switch (p_mode) {
  2241. case COMPRESS_S3TC: {
  2242. ERR_FAIL_COND_V(!_image_compress_bc_func, ERR_UNAVAILABLE);
  2243. _image_compress_bc_func(this, p_lossy_quality, p_channels);
  2244. } break;
  2245. case COMPRESS_ETC: {
  2246. ERR_FAIL_COND_V(!_image_compress_etc1_func, ERR_UNAVAILABLE);
  2247. _image_compress_etc1_func(this, p_lossy_quality);
  2248. } break;
  2249. case COMPRESS_ETC2: {
  2250. ERR_FAIL_COND_V(!_image_compress_etc2_func, ERR_UNAVAILABLE);
  2251. _image_compress_etc2_func(this, p_lossy_quality, p_channels);
  2252. } break;
  2253. case COMPRESS_BPTC: {
  2254. ERR_FAIL_COND_V(!_image_compress_bptc_func, ERR_UNAVAILABLE);
  2255. _image_compress_bptc_func(this, p_lossy_quality, p_channels);
  2256. } break;
  2257. case COMPRESS_ASTC: {
  2258. ERR_FAIL_COND_V(!_image_compress_bptc_func, ERR_UNAVAILABLE);
  2259. _image_compress_astc_func(this, p_lossy_quality, p_astc_format);
  2260. } break;
  2261. case COMPRESS_MAX: {
  2262. ERR_FAIL_V(ERR_INVALID_PARAMETER);
  2263. } break;
  2264. }
  2265. return OK;
  2266. }
  2267. Image::Image(const char **p_xpm) {
  2268. width = 0;
  2269. height = 0;
  2270. mipmaps = false;
  2271. format = FORMAT_L8;
  2272. initialize_data(p_xpm);
  2273. }
  2274. Image::Image(int p_width, int p_height, bool p_use_mipmaps, Format p_format) {
  2275. width = 0;
  2276. height = 0;
  2277. mipmaps = p_use_mipmaps;
  2278. format = FORMAT_L8;
  2279. initialize_data(p_width, p_height, p_use_mipmaps, p_format);
  2280. }
  2281. Image::Image(int p_width, int p_height, bool p_mipmaps, Format p_format, const Vector<uint8_t> &p_data) {
  2282. width = 0;
  2283. height = 0;
  2284. mipmaps = p_mipmaps;
  2285. format = FORMAT_L8;
  2286. initialize_data(p_width, p_height, p_mipmaps, p_format, p_data);
  2287. }
  2288. Rect2i Image::get_used_rect() const {
  2289. if (format != FORMAT_LA8 && format != FORMAT_RGBA8 && format != FORMAT_RGBAF && format != FORMAT_RGBAH && format != FORMAT_RGBA4444 && format != FORMAT_RGB565) {
  2290. return Rect2i(0, 0, width, height);
  2291. }
  2292. int len = data.size();
  2293. if (len == 0) {
  2294. return Rect2i();
  2295. }
  2296. int minx = 0xFFFFFF, miny = 0xFFFFFFF;
  2297. int maxx = -1, maxy = -1;
  2298. for (int j = 0; j < height; j++) {
  2299. for (int i = 0; i < width; i++) {
  2300. if (!(get_pixel(i, j).a > 0)) {
  2301. continue;
  2302. }
  2303. if (i > maxx) {
  2304. maxx = i;
  2305. }
  2306. if (j > maxy) {
  2307. maxy = j;
  2308. }
  2309. if (i < minx) {
  2310. minx = i;
  2311. }
  2312. if (j < miny) {
  2313. miny = j;
  2314. }
  2315. }
  2316. }
  2317. if (maxx == -1) {
  2318. return Rect2i();
  2319. } else {
  2320. return Rect2i(minx, miny, maxx - minx + 1, maxy - miny + 1);
  2321. }
  2322. }
  2323. Ref<Image> Image::get_region(const Rect2i &p_region) const {
  2324. Ref<Image> img = memnew(Image(p_region.size.x, p_region.size.y, mipmaps, format));
  2325. img->blit_rect(Ref<Image>((Image *)this), p_region, Point2i(0, 0));
  2326. return img;
  2327. }
  2328. 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 {
  2329. r_clipped_dest_rect.position = p_dest;
  2330. r_clipped_src_rect = p_src_rect;
  2331. if (r_clipped_src_rect.position.x < 0) {
  2332. r_clipped_dest_rect.position.x -= r_clipped_src_rect.position.x;
  2333. r_clipped_src_rect.size.x += r_clipped_src_rect.position.x;
  2334. r_clipped_src_rect.position.x = 0;
  2335. }
  2336. if (r_clipped_src_rect.position.y < 0) {
  2337. r_clipped_dest_rect.position.y -= r_clipped_src_rect.position.y;
  2338. r_clipped_src_rect.size.y += r_clipped_src_rect.position.y;
  2339. r_clipped_src_rect.position.y = 0;
  2340. }
  2341. if (r_clipped_dest_rect.position.x < 0) {
  2342. r_clipped_src_rect.position.x -= r_clipped_dest_rect.position.x;
  2343. r_clipped_src_rect.size.x += r_clipped_dest_rect.position.x;
  2344. r_clipped_dest_rect.position.x = 0;
  2345. }
  2346. if (r_clipped_dest_rect.position.y < 0) {
  2347. r_clipped_src_rect.position.y -= r_clipped_dest_rect.position.y;
  2348. r_clipped_src_rect.size.y += r_clipped_dest_rect.position.y;
  2349. r_clipped_dest_rect.position.y = 0;
  2350. }
  2351. 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)));
  2352. 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)));
  2353. r_clipped_dest_rect.size.x = r_clipped_src_rect.size.x;
  2354. r_clipped_dest_rect.size.y = r_clipped_src_rect.size.y;
  2355. }
  2356. void Image::blit_rect(const Ref<Image> &p_src, const Rect2i &p_src_rect, const Point2i &p_dest) {
  2357. ERR_FAIL_COND_MSG(p_src.is_null(), "It's not a reference to a valid Image object.");
  2358. int dsize = data.size();
  2359. int srcdsize = p_src->data.size();
  2360. ERR_FAIL_COND(dsize == 0);
  2361. ERR_FAIL_COND(srcdsize == 0);
  2362. ERR_FAIL_COND(format != p_src->format);
  2363. ERR_FAIL_COND_MSG(!_can_modify(format), "Cannot blit_rect in compressed or custom image formats.");
  2364. Rect2i src_rect;
  2365. Rect2i dest_rect;
  2366. _get_clipped_src_and_dest_rects(p_src, p_src_rect, p_dest, src_rect, dest_rect);
  2367. if (!src_rect.has_area() || !dest_rect.has_area()) {
  2368. return;
  2369. }
  2370. uint8_t *wp = data.ptrw();
  2371. uint8_t *dst_data_ptr = wp;
  2372. const uint8_t *rp = p_src->data.ptr();
  2373. const uint8_t *src_data_ptr = rp;
  2374. int pixel_size = get_format_pixel_size(format);
  2375. for (int i = 0; i < dest_rect.size.y; i++) {
  2376. for (int j = 0; j < dest_rect.size.x; j++) {
  2377. int src_x = src_rect.position.x + j;
  2378. int src_y = src_rect.position.y + i;
  2379. int dst_x = dest_rect.position.x + j;
  2380. int dst_y = dest_rect.position.y + i;
  2381. const uint8_t *src = &src_data_ptr[(src_y * p_src->width + src_x) * pixel_size];
  2382. uint8_t *dst = &dst_data_ptr[(dst_y * width + dst_x) * pixel_size];
  2383. for (int k = 0; k < pixel_size; k++) {
  2384. dst[k] = src[k];
  2385. }
  2386. }
  2387. }
  2388. }
  2389. void Image::blit_rect_mask(const Ref<Image> &p_src, const Ref<Image> &p_mask, const Rect2i &p_src_rect, const Point2i &p_dest) {
  2390. ERR_FAIL_COND_MSG(p_src.is_null(), "It's not a reference to a valid Image object.");
  2391. ERR_FAIL_COND_MSG(p_mask.is_null(), "It's not a reference to a valid Image object.");
  2392. int dsize = data.size();
  2393. int srcdsize = p_src->data.size();
  2394. int maskdsize = p_mask->data.size();
  2395. ERR_FAIL_COND(dsize == 0);
  2396. ERR_FAIL_COND(srcdsize == 0);
  2397. ERR_FAIL_COND(maskdsize == 0);
  2398. ERR_FAIL_COND_MSG(p_src->width != p_mask->width, "Source image width is different from mask width.");
  2399. ERR_FAIL_COND_MSG(p_src->height != p_mask->height, "Source image height is different from mask height.");
  2400. ERR_FAIL_COND(format != p_src->format);
  2401. Rect2i src_rect;
  2402. Rect2i dest_rect;
  2403. _get_clipped_src_and_dest_rects(p_src, p_src_rect, p_dest, src_rect, dest_rect);
  2404. if (!src_rect.has_area() || !dest_rect.has_area()) {
  2405. return;
  2406. }
  2407. uint8_t *wp = data.ptrw();
  2408. uint8_t *dst_data_ptr = wp;
  2409. const uint8_t *rp = p_src->data.ptr();
  2410. const uint8_t *src_data_ptr = rp;
  2411. int pixel_size = get_format_pixel_size(format);
  2412. Ref<Image> msk = p_mask;
  2413. for (int i = 0; i < dest_rect.size.y; i++) {
  2414. for (int j = 0; j < dest_rect.size.x; j++) {
  2415. int src_x = src_rect.position.x + j;
  2416. int src_y = src_rect.position.y + i;
  2417. if (msk->get_pixel(src_x, src_y).a != 0) {
  2418. int dst_x = dest_rect.position.x + j;
  2419. int dst_y = dest_rect.position.y + i;
  2420. const uint8_t *src = &src_data_ptr[(src_y * p_src->width + src_x) * pixel_size];
  2421. uint8_t *dst = &dst_data_ptr[(dst_y * width + dst_x) * pixel_size];
  2422. for (int k = 0; k < pixel_size; k++) {
  2423. dst[k] = src[k];
  2424. }
  2425. }
  2426. }
  2427. }
  2428. }
  2429. void Image::blend_rect(const Ref<Image> &p_src, const Rect2i &p_src_rect, const Point2i &p_dest) {
  2430. ERR_FAIL_COND_MSG(p_src.is_null(), "It's not a reference to a valid Image object.");
  2431. int dsize = data.size();
  2432. int srcdsize = p_src->data.size();
  2433. ERR_FAIL_COND(dsize == 0);
  2434. ERR_FAIL_COND(srcdsize == 0);
  2435. ERR_FAIL_COND(format != p_src->format);
  2436. Rect2i src_rect;
  2437. Rect2i dest_rect;
  2438. _get_clipped_src_and_dest_rects(p_src, p_src_rect, p_dest, src_rect, dest_rect);
  2439. if (!src_rect.has_area() || !dest_rect.has_area()) {
  2440. return;
  2441. }
  2442. Ref<Image> img = p_src;
  2443. for (int i = 0; i < dest_rect.size.y; i++) {
  2444. for (int j = 0; j < dest_rect.size.x; j++) {
  2445. int src_x = src_rect.position.x + j;
  2446. int src_y = src_rect.position.y + i;
  2447. int dst_x = dest_rect.position.x + j;
  2448. int dst_y = dest_rect.position.y + i;
  2449. Color sc = img->get_pixel(src_x, src_y);
  2450. if (sc.a != 0) {
  2451. Color dc = get_pixel(dst_x, dst_y);
  2452. dc = dc.blend(sc);
  2453. set_pixel(dst_x, dst_y, dc);
  2454. }
  2455. }
  2456. }
  2457. }
  2458. void Image::blend_rect_mask(const Ref<Image> &p_src, const Ref<Image> &p_mask, const Rect2i &p_src_rect, const Point2i &p_dest) {
  2459. ERR_FAIL_COND_MSG(p_src.is_null(), "It's not a reference to a valid Image object.");
  2460. ERR_FAIL_COND_MSG(p_mask.is_null(), "It's not a reference to a valid Image object.");
  2461. int dsize = data.size();
  2462. int srcdsize = p_src->data.size();
  2463. int maskdsize = p_mask->data.size();
  2464. ERR_FAIL_COND(dsize == 0);
  2465. ERR_FAIL_COND(srcdsize == 0);
  2466. ERR_FAIL_COND(maskdsize == 0);
  2467. ERR_FAIL_COND_MSG(p_src->width != p_mask->width, "Source image width is different from mask width.");
  2468. ERR_FAIL_COND_MSG(p_src->height != p_mask->height, "Source image height is different from mask height.");
  2469. ERR_FAIL_COND(format != p_src->format);
  2470. Rect2i src_rect;
  2471. Rect2i dest_rect;
  2472. _get_clipped_src_and_dest_rects(p_src, p_src_rect, p_dest, src_rect, dest_rect);
  2473. if (!src_rect.has_area() || !dest_rect.has_area()) {
  2474. return;
  2475. }
  2476. Ref<Image> img = p_src;
  2477. Ref<Image> msk = p_mask;
  2478. for (int i = 0; i < dest_rect.size.y; i++) {
  2479. for (int j = 0; j < dest_rect.size.x; j++) {
  2480. int src_x = src_rect.position.x + j;
  2481. int src_y = src_rect.position.y + i;
  2482. // If the mask's pixel is transparent then we skip it
  2483. //Color c = msk->get_pixel(src_x, src_y);
  2484. //if (c.a == 0) continue;
  2485. if (msk->get_pixel(src_x, src_y).a != 0) {
  2486. int dst_x = dest_rect.position.x + j;
  2487. int dst_y = dest_rect.position.y + i;
  2488. Color sc = img->get_pixel(src_x, src_y);
  2489. if (sc.a != 0) {
  2490. Color dc = get_pixel(dst_x, dst_y);
  2491. dc = dc.blend(sc);
  2492. set_pixel(dst_x, dst_y, dc);
  2493. }
  2494. }
  2495. }
  2496. }
  2497. }
  2498. // Repeats `p_pixel` `p_count` times in consecutive memory.
  2499. // Results in the original pixel and `p_count - 1` subsequent copies of it.
  2500. void Image::_repeat_pixel_over_subsequent_memory(uint8_t *p_pixel, int p_pixel_size, int p_count) {
  2501. int offset = 1;
  2502. for (int stride = 1; offset + stride <= p_count; stride *= 2) {
  2503. memcpy(p_pixel + offset * p_pixel_size, p_pixel, stride * p_pixel_size);
  2504. offset += stride;
  2505. }
  2506. if (offset < p_count) {
  2507. memcpy(p_pixel + offset * p_pixel_size, p_pixel, (p_count - offset) * p_pixel_size);
  2508. }
  2509. }
  2510. void Image::fill(const Color &p_color) {
  2511. if (data.size() == 0) {
  2512. return;
  2513. }
  2514. ERR_FAIL_COND_MSG(!_can_modify(format), "Cannot fill in compressed or custom image formats.");
  2515. uint8_t *dst_data_ptr = data.ptrw();
  2516. int pixel_size = get_format_pixel_size(format);
  2517. // Put first pixel with the format-aware API.
  2518. _set_color_at_ofs(dst_data_ptr, 0, p_color);
  2519. _repeat_pixel_over_subsequent_memory(dst_data_ptr, pixel_size, width * height);
  2520. }
  2521. void Image::fill_rect(const Rect2i &p_rect, const Color &p_color) {
  2522. if (data.size() == 0) {
  2523. return;
  2524. }
  2525. ERR_FAIL_COND_MSG(!_can_modify(format), "Cannot fill rect in compressed or custom image formats.");
  2526. Rect2i r = Rect2i(0, 0, width, height).intersection(p_rect.abs());
  2527. if (!r.has_area()) {
  2528. return;
  2529. }
  2530. uint8_t *dst_data_ptr = data.ptrw();
  2531. int pixel_size = get_format_pixel_size(format);
  2532. // Put first pixel with the format-aware API.
  2533. uint8_t *rect_first_pixel_ptr = &dst_data_ptr[(r.position.y * width + r.position.x) * pixel_size];
  2534. _set_color_at_ofs(rect_first_pixel_ptr, 0, p_color);
  2535. if (r.size.x == width) {
  2536. // No need to fill rows separately.
  2537. _repeat_pixel_over_subsequent_memory(rect_first_pixel_ptr, pixel_size, width * r.size.y);
  2538. } else {
  2539. _repeat_pixel_over_subsequent_memory(rect_first_pixel_ptr, pixel_size, r.size.x);
  2540. for (int y = 1; y < r.size.y; y++) {
  2541. memcpy(rect_first_pixel_ptr + y * width * pixel_size, rect_first_pixel_ptr, r.size.x * pixel_size);
  2542. }
  2543. }
  2544. }
  2545. ImageMemLoadFunc Image::_png_mem_loader_func = nullptr;
  2546. ImageMemLoadFunc Image::_jpg_mem_loader_func = nullptr;
  2547. ImageMemLoadFunc Image::_webp_mem_loader_func = nullptr;
  2548. ImageMemLoadFunc Image::_tga_mem_loader_func = nullptr;
  2549. ImageMemLoadFunc Image::_bmp_mem_loader_func = nullptr;
  2550. void (*Image::_image_compress_bc_func)(Image *, float, Image::UsedChannels) = nullptr;
  2551. void (*Image::_image_compress_bptc_func)(Image *, float, Image::UsedChannels) = nullptr;
  2552. void (*Image::_image_compress_etc1_func)(Image *, float) = nullptr;
  2553. void (*Image::_image_compress_etc2_func)(Image *, float, Image::UsedChannels) = nullptr;
  2554. void (*Image::_image_compress_astc_func)(Image *, float, Image::ASTCFormat) = nullptr;
  2555. void (*Image::_image_decompress_bc)(Image *) = nullptr;
  2556. void (*Image::_image_decompress_bptc)(Image *) = nullptr;
  2557. void (*Image::_image_decompress_etc1)(Image *) = nullptr;
  2558. void (*Image::_image_decompress_etc2)(Image *) = nullptr;
  2559. void (*Image::_image_decompress_astc)(Image *) = nullptr;
  2560. Vector<uint8_t> (*Image::webp_lossy_packer)(const Ref<Image> &, float) = nullptr;
  2561. Vector<uint8_t> (*Image::webp_lossless_packer)(const Ref<Image> &) = nullptr;
  2562. Ref<Image> (*Image::webp_unpacker)(const Vector<uint8_t> &) = nullptr;
  2563. Vector<uint8_t> (*Image::png_packer)(const Ref<Image> &) = nullptr;
  2564. Ref<Image> (*Image::png_unpacker)(const Vector<uint8_t> &) = nullptr;
  2565. Vector<uint8_t> (*Image::basis_universal_packer)(const Ref<Image> &, Image::UsedChannels) = nullptr;
  2566. Ref<Image> (*Image::basis_universal_unpacker)(const Vector<uint8_t> &) = nullptr;
  2567. Ref<Image> (*Image::basis_universal_unpacker_ptr)(const uint8_t *, int) = nullptr;
  2568. void Image::_set_data(const Dictionary &p_data) {
  2569. ERR_FAIL_COND(!p_data.has("width"));
  2570. ERR_FAIL_COND(!p_data.has("height"));
  2571. ERR_FAIL_COND(!p_data.has("format"));
  2572. ERR_FAIL_COND(!p_data.has("mipmaps"));
  2573. ERR_FAIL_COND(!p_data.has("data"));
  2574. int dwidth = p_data["width"];
  2575. int dheight = p_data["height"];
  2576. String dformat = p_data["format"];
  2577. bool dmipmaps = p_data["mipmaps"];
  2578. Vector<uint8_t> ddata = p_data["data"];
  2579. Format ddformat = FORMAT_MAX;
  2580. for (int i = 0; i < FORMAT_MAX; i++) {
  2581. if (dformat == get_format_name(Format(i))) {
  2582. ddformat = Format(i);
  2583. break;
  2584. }
  2585. }
  2586. ERR_FAIL_COND(ddformat == FORMAT_MAX);
  2587. initialize_data(dwidth, dheight, dmipmaps, ddformat, ddata);
  2588. }
  2589. Dictionary Image::_get_data() const {
  2590. Dictionary d;
  2591. d["width"] = width;
  2592. d["height"] = height;
  2593. d["format"] = get_format_name(format);
  2594. d["mipmaps"] = mipmaps;
  2595. d["data"] = data;
  2596. return d;
  2597. }
  2598. Color Image::get_pixelv(const Point2i &p_point) const {
  2599. return get_pixel(p_point.x, p_point.y);
  2600. }
  2601. Color Image::_get_color_at_ofs(const uint8_t *ptr, uint32_t ofs) const {
  2602. switch (format) {
  2603. case FORMAT_L8: {
  2604. float l = ptr[ofs] / 255.0;
  2605. return Color(l, l, l, 1);
  2606. }
  2607. case FORMAT_LA8: {
  2608. float l = ptr[ofs * 2 + 0] / 255.0;
  2609. float a = ptr[ofs * 2 + 1] / 255.0;
  2610. return Color(l, l, l, a);
  2611. }
  2612. case FORMAT_R8: {
  2613. float r = ptr[ofs] / 255.0;
  2614. return Color(r, 0, 0, 1);
  2615. }
  2616. case FORMAT_RG8: {
  2617. float r = ptr[ofs * 2 + 0] / 255.0;
  2618. float g = ptr[ofs * 2 + 1] / 255.0;
  2619. return Color(r, g, 0, 1);
  2620. }
  2621. case FORMAT_RGB8: {
  2622. float r = ptr[ofs * 3 + 0] / 255.0;
  2623. float g = ptr[ofs * 3 + 1] / 255.0;
  2624. float b = ptr[ofs * 3 + 2] / 255.0;
  2625. return Color(r, g, b, 1);
  2626. }
  2627. case FORMAT_RGBA8: {
  2628. float r = ptr[ofs * 4 + 0] / 255.0;
  2629. float g = ptr[ofs * 4 + 1] / 255.0;
  2630. float b = ptr[ofs * 4 + 2] / 255.0;
  2631. float a = ptr[ofs * 4 + 3] / 255.0;
  2632. return Color(r, g, b, a);
  2633. }
  2634. case FORMAT_RGBA4444: {
  2635. uint16_t u = ((uint16_t *)ptr)[ofs];
  2636. float r = ((u >> 12) & 0xF) / 15.0;
  2637. float g = ((u >> 8) & 0xF) / 15.0;
  2638. float b = ((u >> 4) & 0xF) / 15.0;
  2639. float a = (u & 0xF) / 15.0;
  2640. return Color(r, g, b, a);
  2641. }
  2642. case FORMAT_RGB565: {
  2643. uint16_t u = ((uint16_t *)ptr)[ofs];
  2644. float r = (u & 0x1F) / 31.0;
  2645. float g = ((u >> 5) & 0x3F) / 63.0;
  2646. float b = ((u >> 11) & 0x1F) / 31.0;
  2647. return Color(r, g, b, 1.0);
  2648. }
  2649. case FORMAT_RF: {
  2650. float r = ((float *)ptr)[ofs];
  2651. return Color(r, 0, 0, 1);
  2652. }
  2653. case FORMAT_RGF: {
  2654. float r = ((float *)ptr)[ofs * 2 + 0];
  2655. float g = ((float *)ptr)[ofs * 2 + 1];
  2656. return Color(r, g, 0, 1);
  2657. }
  2658. case FORMAT_RGBF: {
  2659. float r = ((float *)ptr)[ofs * 3 + 0];
  2660. float g = ((float *)ptr)[ofs * 3 + 1];
  2661. float b = ((float *)ptr)[ofs * 3 + 2];
  2662. return Color(r, g, b, 1);
  2663. }
  2664. case FORMAT_RGBAF: {
  2665. float r = ((float *)ptr)[ofs * 4 + 0];
  2666. float g = ((float *)ptr)[ofs * 4 + 1];
  2667. float b = ((float *)ptr)[ofs * 4 + 2];
  2668. float a = ((float *)ptr)[ofs * 4 + 3];
  2669. return Color(r, g, b, a);
  2670. }
  2671. case FORMAT_RH: {
  2672. uint16_t r = ((uint16_t *)ptr)[ofs];
  2673. return Color(Math::half_to_float(r), 0, 0, 1);
  2674. }
  2675. case FORMAT_RGH: {
  2676. uint16_t r = ((uint16_t *)ptr)[ofs * 2 + 0];
  2677. uint16_t g = ((uint16_t *)ptr)[ofs * 2 + 1];
  2678. return Color(Math::half_to_float(r), Math::half_to_float(g), 0, 1);
  2679. }
  2680. case FORMAT_RGBH: {
  2681. uint16_t r = ((uint16_t *)ptr)[ofs * 3 + 0];
  2682. uint16_t g = ((uint16_t *)ptr)[ofs * 3 + 1];
  2683. uint16_t b = ((uint16_t *)ptr)[ofs * 3 + 2];
  2684. return Color(Math::half_to_float(r), Math::half_to_float(g), Math::half_to_float(b), 1);
  2685. }
  2686. case FORMAT_RGBAH: {
  2687. uint16_t r = ((uint16_t *)ptr)[ofs * 4 + 0];
  2688. uint16_t g = ((uint16_t *)ptr)[ofs * 4 + 1];
  2689. uint16_t b = ((uint16_t *)ptr)[ofs * 4 + 2];
  2690. uint16_t a = ((uint16_t *)ptr)[ofs * 4 + 3];
  2691. return Color(Math::half_to_float(r), Math::half_to_float(g), Math::half_to_float(b), Math::half_to_float(a));
  2692. }
  2693. case FORMAT_RGBE9995: {
  2694. return Color::from_rgbe9995(((uint32_t *)ptr)[ofs]);
  2695. }
  2696. default: {
  2697. ERR_FAIL_V_MSG(Color(), "Can't get_pixel() on compressed image, sorry.");
  2698. }
  2699. }
  2700. }
  2701. void Image::_set_color_at_ofs(uint8_t *ptr, uint32_t ofs, const Color &p_color) {
  2702. switch (format) {
  2703. case FORMAT_L8: {
  2704. ptr[ofs] = uint8_t(CLAMP(p_color.get_v() * 255.0, 0, 255));
  2705. } break;
  2706. case FORMAT_LA8: {
  2707. ptr[ofs * 2 + 0] = uint8_t(CLAMP(p_color.get_v() * 255.0, 0, 255));
  2708. ptr[ofs * 2 + 1] = uint8_t(CLAMP(p_color.a * 255.0, 0, 255));
  2709. } break;
  2710. case FORMAT_R8: {
  2711. ptr[ofs] = uint8_t(CLAMP(p_color.r * 255.0, 0, 255));
  2712. } break;
  2713. case FORMAT_RG8: {
  2714. ptr[ofs * 2 + 0] = uint8_t(CLAMP(p_color.r * 255.0, 0, 255));
  2715. ptr[ofs * 2 + 1] = uint8_t(CLAMP(p_color.g * 255.0, 0, 255));
  2716. } break;
  2717. case FORMAT_RGB8: {
  2718. ptr[ofs * 3 + 0] = uint8_t(CLAMP(p_color.r * 255.0, 0, 255));
  2719. ptr[ofs * 3 + 1] = uint8_t(CLAMP(p_color.g * 255.0, 0, 255));
  2720. ptr[ofs * 3 + 2] = uint8_t(CLAMP(p_color.b * 255.0, 0, 255));
  2721. } break;
  2722. case FORMAT_RGBA8: {
  2723. ptr[ofs * 4 + 0] = uint8_t(CLAMP(p_color.r * 255.0, 0, 255));
  2724. ptr[ofs * 4 + 1] = uint8_t(CLAMP(p_color.g * 255.0, 0, 255));
  2725. ptr[ofs * 4 + 2] = uint8_t(CLAMP(p_color.b * 255.0, 0, 255));
  2726. ptr[ofs * 4 + 3] = uint8_t(CLAMP(p_color.a * 255.0, 0, 255));
  2727. } break;
  2728. case FORMAT_RGBA4444: {
  2729. uint16_t rgba = 0;
  2730. rgba = uint16_t(CLAMP(p_color.r * 15.0, 0, 15)) << 12;
  2731. rgba |= uint16_t(CLAMP(p_color.g * 15.0, 0, 15)) << 8;
  2732. rgba |= uint16_t(CLAMP(p_color.b * 15.0, 0, 15)) << 4;
  2733. rgba |= uint16_t(CLAMP(p_color.a * 15.0, 0, 15));
  2734. ((uint16_t *)ptr)[ofs] = rgba;
  2735. } break;
  2736. case FORMAT_RGB565: {
  2737. uint16_t rgba = 0;
  2738. rgba = uint16_t(CLAMP(p_color.r * 31.0, 0, 31));
  2739. rgba |= uint16_t(CLAMP(p_color.g * 63.0, 0, 33)) << 5;
  2740. rgba |= uint16_t(CLAMP(p_color.b * 31.0, 0, 31)) << 11;
  2741. ((uint16_t *)ptr)[ofs] = rgba;
  2742. } break;
  2743. case FORMAT_RF: {
  2744. ((float *)ptr)[ofs] = p_color.r;
  2745. } break;
  2746. case FORMAT_RGF: {
  2747. ((float *)ptr)[ofs * 2 + 0] = p_color.r;
  2748. ((float *)ptr)[ofs * 2 + 1] = p_color.g;
  2749. } break;
  2750. case FORMAT_RGBF: {
  2751. ((float *)ptr)[ofs * 3 + 0] = p_color.r;
  2752. ((float *)ptr)[ofs * 3 + 1] = p_color.g;
  2753. ((float *)ptr)[ofs * 3 + 2] = p_color.b;
  2754. } break;
  2755. case FORMAT_RGBAF: {
  2756. ((float *)ptr)[ofs * 4 + 0] = p_color.r;
  2757. ((float *)ptr)[ofs * 4 + 1] = p_color.g;
  2758. ((float *)ptr)[ofs * 4 + 2] = p_color.b;
  2759. ((float *)ptr)[ofs * 4 + 3] = p_color.a;
  2760. } break;
  2761. case FORMAT_RH: {
  2762. ((uint16_t *)ptr)[ofs] = Math::make_half_float(p_color.r);
  2763. } break;
  2764. case FORMAT_RGH: {
  2765. ((uint16_t *)ptr)[ofs * 2 + 0] = Math::make_half_float(p_color.r);
  2766. ((uint16_t *)ptr)[ofs * 2 + 1] = Math::make_half_float(p_color.g);
  2767. } break;
  2768. case FORMAT_RGBH: {
  2769. ((uint16_t *)ptr)[ofs * 3 + 0] = Math::make_half_float(p_color.r);
  2770. ((uint16_t *)ptr)[ofs * 3 + 1] = Math::make_half_float(p_color.g);
  2771. ((uint16_t *)ptr)[ofs * 3 + 2] = Math::make_half_float(p_color.b);
  2772. } break;
  2773. case FORMAT_RGBAH: {
  2774. ((uint16_t *)ptr)[ofs * 4 + 0] = Math::make_half_float(p_color.r);
  2775. ((uint16_t *)ptr)[ofs * 4 + 1] = Math::make_half_float(p_color.g);
  2776. ((uint16_t *)ptr)[ofs * 4 + 2] = Math::make_half_float(p_color.b);
  2777. ((uint16_t *)ptr)[ofs * 4 + 3] = Math::make_half_float(p_color.a);
  2778. } break;
  2779. case FORMAT_RGBE9995: {
  2780. ((uint32_t *)ptr)[ofs] = p_color.to_rgbe9995();
  2781. } break;
  2782. default: {
  2783. ERR_FAIL_MSG("Can't set_pixel() on compressed image, sorry.");
  2784. }
  2785. }
  2786. }
  2787. Color Image::get_pixel(int p_x, int p_y) const {
  2788. #ifdef DEBUG_ENABLED
  2789. ERR_FAIL_INDEX_V(p_x, width, Color());
  2790. ERR_FAIL_INDEX_V(p_y, height, Color());
  2791. #endif
  2792. uint32_t ofs = p_y * width + p_x;
  2793. return _get_color_at_ofs(data.ptr(), ofs);
  2794. }
  2795. void Image::set_pixelv(const Point2i &p_point, const Color &p_color) {
  2796. set_pixel(p_point.x, p_point.y, p_color);
  2797. }
  2798. void Image::set_pixel(int p_x, int p_y, const Color &p_color) {
  2799. #ifdef DEBUG_ENABLED
  2800. ERR_FAIL_INDEX(p_x, width);
  2801. ERR_FAIL_INDEX(p_y, height);
  2802. #endif
  2803. uint32_t ofs = p_y * width + p_x;
  2804. _set_color_at_ofs(data.ptrw(), ofs, p_color);
  2805. }
  2806. void Image::adjust_bcs(float p_brightness, float p_contrast, float p_saturation) {
  2807. ERR_FAIL_COND_MSG(!_can_modify(format), "Cannot adjust_bcs in compressed or custom image formats.");
  2808. uint8_t *w = data.ptrw();
  2809. uint32_t pixel_size = get_format_pixel_size(format);
  2810. uint32_t pixel_count = data.size() / pixel_size;
  2811. for (uint32_t i = 0; i < pixel_count; i++) {
  2812. Color c = _get_color_at_ofs(w, i);
  2813. Vector3 rgb(c.r, c.g, c.b);
  2814. rgb *= p_brightness;
  2815. rgb = Vector3(0.5, 0.5, 0.5).lerp(rgb, p_contrast);
  2816. float center = (rgb.x + rgb.y + rgb.z) / 3.0;
  2817. rgb = Vector3(center, center, center).lerp(rgb, p_saturation);
  2818. c.r = rgb.x;
  2819. c.g = rgb.y;
  2820. c.b = rgb.z;
  2821. _set_color_at_ofs(w, i, c);
  2822. }
  2823. }
  2824. Image::UsedChannels Image::detect_used_channels(CompressSource p_source) const {
  2825. ERR_FAIL_COND_V(data.size() == 0, USED_CHANNELS_RGBA);
  2826. ERR_FAIL_COND_V(is_compressed(), USED_CHANNELS_RGBA);
  2827. bool r = false, g = false, b = false, a = false, c = false;
  2828. const uint8_t *data_ptr = data.ptr();
  2829. uint32_t data_total = width * height;
  2830. for (uint32_t i = 0; i < data_total; i++) {
  2831. Color col = _get_color_at_ofs(data_ptr, i);
  2832. if (col.r > 0.001) {
  2833. r = true;
  2834. }
  2835. if (col.g > 0.001) {
  2836. g = true;
  2837. }
  2838. if (col.b > 0.001) {
  2839. b = true;
  2840. }
  2841. if (col.a < 0.999) {
  2842. a = true;
  2843. }
  2844. if (col.r != col.b || col.r != col.g || col.b != col.g) {
  2845. c = true;
  2846. }
  2847. }
  2848. UsedChannels used_channels;
  2849. if (!c && !a) {
  2850. used_channels = USED_CHANNELS_L;
  2851. } else if (!c && a) {
  2852. used_channels = USED_CHANNELS_LA;
  2853. } else if (r && !g && !b && !a) {
  2854. used_channels = USED_CHANNELS_R;
  2855. } else if (r && g && !b && !a) {
  2856. used_channels = USED_CHANNELS_RG;
  2857. } else if (r && g && b && !a) {
  2858. used_channels = USED_CHANNELS_RGB;
  2859. } else {
  2860. used_channels = USED_CHANNELS_RGBA;
  2861. }
  2862. if (p_source == COMPRESS_SOURCE_SRGB && (used_channels == USED_CHANNELS_R || used_channels == USED_CHANNELS_RG)) {
  2863. //R and RG do not support SRGB
  2864. used_channels = USED_CHANNELS_RGB;
  2865. }
  2866. if (p_source == COMPRESS_SOURCE_NORMAL) {
  2867. //use RG channels only for normal
  2868. used_channels = USED_CHANNELS_RG;
  2869. }
  2870. return used_channels;
  2871. }
  2872. void Image::optimize_channels() {
  2873. switch (detect_used_channels()) {
  2874. case USED_CHANNELS_L:
  2875. convert(FORMAT_L8);
  2876. break;
  2877. case USED_CHANNELS_LA:
  2878. convert(FORMAT_LA8);
  2879. break;
  2880. case USED_CHANNELS_R:
  2881. convert(FORMAT_R8);
  2882. break;
  2883. case USED_CHANNELS_RG:
  2884. convert(FORMAT_RG8);
  2885. break;
  2886. case USED_CHANNELS_RGB:
  2887. convert(FORMAT_RGB8);
  2888. break;
  2889. case USED_CHANNELS_RGBA:
  2890. convert(FORMAT_RGBA8);
  2891. break;
  2892. }
  2893. }
  2894. void Image::_bind_methods() {
  2895. ClassDB::bind_method(D_METHOD("get_width"), &Image::get_width);
  2896. ClassDB::bind_method(D_METHOD("get_height"), &Image::get_height);
  2897. ClassDB::bind_method(D_METHOD("get_size"), &Image::get_size);
  2898. ClassDB::bind_method(D_METHOD("has_mipmaps"), &Image::has_mipmaps);
  2899. ClassDB::bind_method(D_METHOD("get_format"), &Image::get_format);
  2900. ClassDB::bind_method(D_METHOD("get_data"), &Image::get_data);
  2901. ClassDB::bind_method(D_METHOD("convert", "format"), &Image::convert);
  2902. ClassDB::bind_method(D_METHOD("get_mipmap_offset", "mipmap"), &Image::get_mipmap_offset);
  2903. ClassDB::bind_method(D_METHOD("resize_to_po2", "square", "interpolation"), &Image::resize_to_po2, DEFVAL(false), DEFVAL(INTERPOLATE_BILINEAR));
  2904. ClassDB::bind_method(D_METHOD("resize", "width", "height", "interpolation"), &Image::resize, DEFVAL(INTERPOLATE_BILINEAR));
  2905. ClassDB::bind_method(D_METHOD("shrink_x2"), &Image::shrink_x2);
  2906. ClassDB::bind_method(D_METHOD("crop", "width", "height"), &Image::crop);
  2907. ClassDB::bind_method(D_METHOD("flip_x"), &Image::flip_x);
  2908. ClassDB::bind_method(D_METHOD("flip_y"), &Image::flip_y);
  2909. ClassDB::bind_method(D_METHOD("generate_mipmaps", "renormalize"), &Image::generate_mipmaps, DEFVAL(false));
  2910. ClassDB::bind_method(D_METHOD("clear_mipmaps"), &Image::clear_mipmaps);
  2911. ClassDB::bind_static_method("Image", D_METHOD("create", "width", "height", "use_mipmaps", "format"), &Image::create_empty);
  2912. ClassDB::bind_static_method("Image", D_METHOD("create_from_data", "width", "height", "use_mipmaps", "format", "data"), &Image::create_from_data);
  2913. ClassDB::bind_method(D_METHOD("set_data", "width", "height", "use_mipmaps", "format", "data"), &Image::set_data);
  2914. ClassDB::bind_method(D_METHOD("is_empty"), &Image::is_empty);
  2915. ClassDB::bind_method(D_METHOD("load", "path"), &Image::load);
  2916. ClassDB::bind_static_method("Image", D_METHOD("load_from_file", "path"), &Image::load_from_file);
  2917. ClassDB::bind_method(D_METHOD("save_png", "path"), &Image::save_png);
  2918. ClassDB::bind_method(D_METHOD("save_png_to_buffer"), &Image::save_png_to_buffer);
  2919. ClassDB::bind_method(D_METHOD("save_jpg", "path", "quality"), &Image::save_jpg, DEFVAL(0.75));
  2920. ClassDB::bind_method(D_METHOD("save_jpg_to_buffer", "quality"), &Image::save_jpg_to_buffer, DEFVAL(0.75));
  2921. ClassDB::bind_method(D_METHOD("save_exr", "path", "grayscale"), &Image::save_exr, DEFVAL(false));
  2922. ClassDB::bind_method(D_METHOD("save_exr_to_buffer", "grayscale"), &Image::save_exr_to_buffer, DEFVAL(false));
  2923. ClassDB::bind_method(D_METHOD("save_webp", "path", "lossy", "quality"), &Image::save_webp, DEFVAL(false), DEFVAL(0.75f));
  2924. ClassDB::bind_method(D_METHOD("save_webp_to_buffer", "lossy", "quality"), &Image::save_webp_to_buffer, DEFVAL(false), DEFVAL(0.75f));
  2925. ClassDB::bind_method(D_METHOD("detect_alpha"), &Image::detect_alpha);
  2926. ClassDB::bind_method(D_METHOD("is_invisible"), &Image::is_invisible);
  2927. ClassDB::bind_method(D_METHOD("detect_used_channels", "source"), &Image::detect_used_channels, DEFVAL(COMPRESS_SOURCE_GENERIC));
  2928. ClassDB::bind_method(D_METHOD("compress", "mode", "source", "lossy_quality", "astc_format"), &Image::compress, DEFVAL(COMPRESS_SOURCE_GENERIC), DEFVAL(0.7), DEFVAL(ASTC_FORMAT_4x4));
  2929. ClassDB::bind_method(D_METHOD("compress_from_channels", "mode", "channels", "lossy_quality", "astc_format"), &Image::compress_from_channels, DEFVAL(0.7), DEFVAL(ASTC_FORMAT_4x4));
  2930. ClassDB::bind_method(D_METHOD("decompress"), &Image::decompress);
  2931. ClassDB::bind_method(D_METHOD("is_compressed"), &Image::is_compressed);
  2932. ClassDB::bind_method(D_METHOD("rotate_90", "direction"), &Image::rotate_90);
  2933. ClassDB::bind_method(D_METHOD("rotate_180"), &Image::rotate_180);
  2934. ClassDB::bind_method(D_METHOD("fix_alpha_edges"), &Image::fix_alpha_edges);
  2935. ClassDB::bind_method(D_METHOD("premultiply_alpha"), &Image::premultiply_alpha);
  2936. ClassDB::bind_method(D_METHOD("srgb_to_linear"), &Image::srgb_to_linear);
  2937. ClassDB::bind_method(D_METHOD("normal_map_to_xy"), &Image::normal_map_to_xy);
  2938. ClassDB::bind_method(D_METHOD("rgbe_to_srgb"), &Image::rgbe_to_srgb);
  2939. ClassDB::bind_method(D_METHOD("bump_map_to_normal_map", "bump_scale"), &Image::bump_map_to_normal_map, DEFVAL(1.0));
  2940. ClassDB::bind_method(D_METHOD("compute_image_metrics", "compared_image", "use_luma"), &Image::compute_image_metrics);
  2941. ClassDB::bind_method(D_METHOD("blit_rect", "src", "src_rect", "dst"), &Image::blit_rect);
  2942. ClassDB::bind_method(D_METHOD("blit_rect_mask", "src", "mask", "src_rect", "dst"), &Image::blit_rect_mask);
  2943. ClassDB::bind_method(D_METHOD("blend_rect", "src", "src_rect", "dst"), &Image::blend_rect);
  2944. ClassDB::bind_method(D_METHOD("blend_rect_mask", "src", "mask", "src_rect", "dst"), &Image::blend_rect_mask);
  2945. ClassDB::bind_method(D_METHOD("fill", "color"), &Image::fill);
  2946. ClassDB::bind_method(D_METHOD("fill_rect", "rect", "color"), &Image::fill_rect);
  2947. ClassDB::bind_method(D_METHOD("get_used_rect"), &Image::get_used_rect);
  2948. ClassDB::bind_method(D_METHOD("get_region", "region"), &Image::get_region);
  2949. ClassDB::bind_method(D_METHOD("copy_from", "src"), &Image::copy_internals_from);
  2950. ClassDB::bind_method(D_METHOD("_set_data", "data"), &Image::_set_data);
  2951. ClassDB::bind_method(D_METHOD("_get_data"), &Image::_get_data);
  2952. ClassDB::bind_method(D_METHOD("get_pixelv", "point"), &Image::get_pixelv);
  2953. ClassDB::bind_method(D_METHOD("get_pixel", "x", "y"), &Image::get_pixel);
  2954. ClassDB::bind_method(D_METHOD("set_pixelv", "point", "color"), &Image::set_pixelv);
  2955. ClassDB::bind_method(D_METHOD("set_pixel", "x", "y", "color"), &Image::set_pixel);
  2956. ClassDB::bind_method(D_METHOD("adjust_bcs", "brightness", "contrast", "saturation"), &Image::adjust_bcs);
  2957. ClassDB::bind_method(D_METHOD("load_png_from_buffer", "buffer"), &Image::load_png_from_buffer);
  2958. ClassDB::bind_method(D_METHOD("load_jpg_from_buffer", "buffer"), &Image::load_jpg_from_buffer);
  2959. ClassDB::bind_method(D_METHOD("load_webp_from_buffer", "buffer"), &Image::load_webp_from_buffer);
  2960. ClassDB::bind_method(D_METHOD("load_tga_from_buffer", "buffer"), &Image::load_tga_from_buffer);
  2961. ClassDB::bind_method(D_METHOD("load_bmp_from_buffer", "buffer"), &Image::load_bmp_from_buffer);
  2962. ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE), "_set_data", "_get_data");
  2963. BIND_CONSTANT(MAX_WIDTH);
  2964. BIND_CONSTANT(MAX_HEIGHT);
  2965. BIND_ENUM_CONSTANT(FORMAT_L8); //luminance
  2966. BIND_ENUM_CONSTANT(FORMAT_LA8); //luminance-alpha
  2967. BIND_ENUM_CONSTANT(FORMAT_R8);
  2968. BIND_ENUM_CONSTANT(FORMAT_RG8);
  2969. BIND_ENUM_CONSTANT(FORMAT_RGB8);
  2970. BIND_ENUM_CONSTANT(FORMAT_RGBA8);
  2971. BIND_ENUM_CONSTANT(FORMAT_RGBA4444);
  2972. BIND_ENUM_CONSTANT(FORMAT_RGB565);
  2973. BIND_ENUM_CONSTANT(FORMAT_RF); //float
  2974. BIND_ENUM_CONSTANT(FORMAT_RGF);
  2975. BIND_ENUM_CONSTANT(FORMAT_RGBF);
  2976. BIND_ENUM_CONSTANT(FORMAT_RGBAF);
  2977. BIND_ENUM_CONSTANT(FORMAT_RH); //half float
  2978. BIND_ENUM_CONSTANT(FORMAT_RGH);
  2979. BIND_ENUM_CONSTANT(FORMAT_RGBH);
  2980. BIND_ENUM_CONSTANT(FORMAT_RGBAH);
  2981. BIND_ENUM_CONSTANT(FORMAT_RGBE9995);
  2982. BIND_ENUM_CONSTANT(FORMAT_DXT1); //s3tc bc1
  2983. BIND_ENUM_CONSTANT(FORMAT_DXT3); //bc2
  2984. BIND_ENUM_CONSTANT(FORMAT_DXT5); //bc3
  2985. BIND_ENUM_CONSTANT(FORMAT_RGTC_R);
  2986. BIND_ENUM_CONSTANT(FORMAT_RGTC_RG);
  2987. BIND_ENUM_CONSTANT(FORMAT_BPTC_RGBA); //btpc bc6h
  2988. BIND_ENUM_CONSTANT(FORMAT_BPTC_RGBF); //float /
  2989. BIND_ENUM_CONSTANT(FORMAT_BPTC_RGBFU); //unsigned float
  2990. BIND_ENUM_CONSTANT(FORMAT_ETC); //etc1
  2991. BIND_ENUM_CONSTANT(FORMAT_ETC2_R11); //etc2
  2992. BIND_ENUM_CONSTANT(FORMAT_ETC2_R11S); //signed ); NOT srgb.
  2993. BIND_ENUM_CONSTANT(FORMAT_ETC2_RG11);
  2994. BIND_ENUM_CONSTANT(FORMAT_ETC2_RG11S);
  2995. BIND_ENUM_CONSTANT(FORMAT_ETC2_RGB8);
  2996. BIND_ENUM_CONSTANT(FORMAT_ETC2_RGBA8);
  2997. BIND_ENUM_CONSTANT(FORMAT_ETC2_RGB8A1);
  2998. BIND_ENUM_CONSTANT(FORMAT_ETC2_RA_AS_RG);
  2999. BIND_ENUM_CONSTANT(FORMAT_DXT5_RA_AS_RG);
  3000. BIND_ENUM_CONSTANT(FORMAT_ASTC_4x4);
  3001. BIND_ENUM_CONSTANT(FORMAT_ASTC_4x4_HDR);
  3002. BIND_ENUM_CONSTANT(FORMAT_ASTC_8x8);
  3003. BIND_ENUM_CONSTANT(FORMAT_ASTC_8x8_HDR);
  3004. BIND_ENUM_CONSTANT(FORMAT_MAX);
  3005. BIND_ENUM_CONSTANT(INTERPOLATE_NEAREST);
  3006. BIND_ENUM_CONSTANT(INTERPOLATE_BILINEAR);
  3007. BIND_ENUM_CONSTANT(INTERPOLATE_CUBIC);
  3008. BIND_ENUM_CONSTANT(INTERPOLATE_TRILINEAR);
  3009. BIND_ENUM_CONSTANT(INTERPOLATE_LANCZOS);
  3010. BIND_ENUM_CONSTANT(ALPHA_NONE);
  3011. BIND_ENUM_CONSTANT(ALPHA_BIT);
  3012. BIND_ENUM_CONSTANT(ALPHA_BLEND);
  3013. BIND_ENUM_CONSTANT(COMPRESS_S3TC);
  3014. BIND_ENUM_CONSTANT(COMPRESS_ETC);
  3015. BIND_ENUM_CONSTANT(COMPRESS_ETC2);
  3016. BIND_ENUM_CONSTANT(COMPRESS_BPTC);
  3017. BIND_ENUM_CONSTANT(USED_CHANNELS_L);
  3018. BIND_ENUM_CONSTANT(USED_CHANNELS_LA);
  3019. BIND_ENUM_CONSTANT(USED_CHANNELS_R);
  3020. BIND_ENUM_CONSTANT(USED_CHANNELS_RG);
  3021. BIND_ENUM_CONSTANT(USED_CHANNELS_RGB);
  3022. BIND_ENUM_CONSTANT(USED_CHANNELS_RGBA);
  3023. BIND_ENUM_CONSTANT(COMPRESS_SOURCE_GENERIC);
  3024. BIND_ENUM_CONSTANT(COMPRESS_SOURCE_SRGB);
  3025. BIND_ENUM_CONSTANT(COMPRESS_SOURCE_NORMAL);
  3026. BIND_ENUM_CONSTANT(ASTC_FORMAT_4x4);
  3027. BIND_ENUM_CONSTANT(ASTC_FORMAT_8x8);
  3028. }
  3029. void Image::set_compress_bc_func(void (*p_compress_func)(Image *, float, UsedChannels)) {
  3030. _image_compress_bc_func = p_compress_func;
  3031. }
  3032. void Image::set_compress_bptc_func(void (*p_compress_func)(Image *, float, UsedChannels)) {
  3033. _image_compress_bptc_func = p_compress_func;
  3034. }
  3035. void Image::normal_map_to_xy() {
  3036. convert(Image::FORMAT_RGBA8);
  3037. {
  3038. int len = data.size() / 4;
  3039. uint8_t *data_ptr = data.ptrw();
  3040. for (int i = 0; i < len; i++) {
  3041. data_ptr[(i << 2) + 3] = data_ptr[(i << 2) + 0]; //x to w
  3042. data_ptr[(i << 2) + 0] = data_ptr[(i << 2) + 1]; //y to xz
  3043. data_ptr[(i << 2) + 2] = data_ptr[(i << 2) + 1];
  3044. }
  3045. }
  3046. convert(Image::FORMAT_LA8);
  3047. }
  3048. Ref<Image> Image::rgbe_to_srgb() {
  3049. if (data.size() == 0) {
  3050. return Ref<Image>();
  3051. }
  3052. ERR_FAIL_COND_V(format != FORMAT_RGBE9995, Ref<Image>());
  3053. Ref<Image> new_image = create_empty(width, height, false, Image::FORMAT_RGB8);
  3054. for (int row = 0; row < height; row++) {
  3055. for (int col = 0; col < width; col++) {
  3056. new_image->set_pixel(col, row, get_pixel(col, row).linear_to_srgb());
  3057. }
  3058. }
  3059. if (has_mipmaps()) {
  3060. new_image->generate_mipmaps();
  3061. }
  3062. return new_image;
  3063. }
  3064. Ref<Image> Image::get_image_from_mipmap(int p_mipamp) const {
  3065. int ofs, size, w, h;
  3066. get_mipmap_offset_size_and_dimensions(p_mipamp, ofs, size, w, h);
  3067. Vector<uint8_t> new_data;
  3068. new_data.resize(size);
  3069. {
  3070. uint8_t *wr = new_data.ptrw();
  3071. const uint8_t *rd = data.ptr();
  3072. memcpy(wr, rd + ofs, size);
  3073. }
  3074. Ref<Image> image;
  3075. image.instantiate();
  3076. image->width = w;
  3077. image->height = h;
  3078. image->format = format;
  3079. image->data = new_data;
  3080. image->mipmaps = false;
  3081. return image;
  3082. }
  3083. void Image::bump_map_to_normal_map(float bump_scale) {
  3084. ERR_FAIL_COND(!_can_modify(format));
  3085. clear_mipmaps();
  3086. convert(Image::FORMAT_RF);
  3087. Vector<uint8_t> result_image; //rgba output
  3088. result_image.resize(width * height * 4);
  3089. {
  3090. const uint8_t *rp = data.ptr();
  3091. uint8_t *wp = result_image.ptrw();
  3092. ERR_FAIL_COND(!rp);
  3093. unsigned char *write_ptr = wp;
  3094. float *read_ptr = (float *)rp;
  3095. for (int ty = 0; ty < height; ty++) {
  3096. int py = ty + 1;
  3097. if (py >= height) {
  3098. py -= height;
  3099. }
  3100. for (int tx = 0; tx < width; tx++) {
  3101. int px = tx + 1;
  3102. if (px >= width) {
  3103. px -= width;
  3104. }
  3105. float here = read_ptr[ty * width + tx];
  3106. float to_right = read_ptr[ty * width + px];
  3107. float above = read_ptr[py * width + tx];
  3108. Vector3 up = Vector3(0, 1, (here - above) * bump_scale);
  3109. Vector3 across = Vector3(1, 0, (to_right - here) * bump_scale);
  3110. Vector3 normal = across.cross(up);
  3111. normal.normalize();
  3112. write_ptr[((ty * width + tx) << 2) + 0] = (127.5 + normal.x * 127.5);
  3113. write_ptr[((ty * width + tx) << 2) + 1] = (127.5 + normal.y * 127.5);
  3114. write_ptr[((ty * width + tx) << 2) + 2] = (127.5 + normal.z * 127.5);
  3115. write_ptr[((ty * width + tx) << 2) + 3] = 255;
  3116. }
  3117. }
  3118. }
  3119. format = FORMAT_RGBA8;
  3120. data = result_image;
  3121. }
  3122. void Image::srgb_to_linear() {
  3123. if (data.size() == 0) {
  3124. return;
  3125. }
  3126. 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 };
  3127. ERR_FAIL_COND(format != FORMAT_RGB8 && format != FORMAT_RGBA8);
  3128. if (format == FORMAT_RGBA8) {
  3129. int len = data.size() / 4;
  3130. uint8_t *data_ptr = data.ptrw();
  3131. for (int i = 0; i < len; i++) {
  3132. data_ptr[(i << 2) + 0] = srgb2lin[data_ptr[(i << 2) + 0]];
  3133. data_ptr[(i << 2) + 1] = srgb2lin[data_ptr[(i << 2) + 1]];
  3134. data_ptr[(i << 2) + 2] = srgb2lin[data_ptr[(i << 2) + 2]];
  3135. }
  3136. } else if (format == FORMAT_RGB8) {
  3137. int len = data.size() / 3;
  3138. uint8_t *data_ptr = data.ptrw();
  3139. for (int i = 0; i < len; i++) {
  3140. data_ptr[(i * 3) + 0] = srgb2lin[data_ptr[(i * 3) + 0]];
  3141. data_ptr[(i * 3) + 1] = srgb2lin[data_ptr[(i * 3) + 1]];
  3142. data_ptr[(i * 3) + 2] = srgb2lin[data_ptr[(i * 3) + 2]];
  3143. }
  3144. }
  3145. }
  3146. void Image::premultiply_alpha() {
  3147. if (data.size() == 0) {
  3148. return;
  3149. }
  3150. if (format != FORMAT_RGBA8) {
  3151. return; //not needed
  3152. }
  3153. uint8_t *data_ptr = data.ptrw();
  3154. for (int i = 0; i < height; i++) {
  3155. for (int j = 0; j < width; j++) {
  3156. uint8_t *ptr = &data_ptr[(i * width + j) * 4];
  3157. ptr[0] = (uint16_t(ptr[0]) * uint16_t(ptr[3])) >> 8;
  3158. ptr[1] = (uint16_t(ptr[1]) * uint16_t(ptr[3])) >> 8;
  3159. ptr[2] = (uint16_t(ptr[2]) * uint16_t(ptr[3])) >> 8;
  3160. }
  3161. }
  3162. }
  3163. void Image::fix_alpha_edges() {
  3164. if (data.size() == 0) {
  3165. return;
  3166. }
  3167. if (format != FORMAT_RGBA8) {
  3168. return; //not needed
  3169. }
  3170. Vector<uint8_t> dcopy = data;
  3171. const uint8_t *srcptr = dcopy.ptr();
  3172. uint8_t *data_ptr = data.ptrw();
  3173. const int max_radius = 4;
  3174. const int alpha_threshold = 20;
  3175. const int max_dist = 0x7FFFFFFF;
  3176. for (int i = 0; i < height; i++) {
  3177. for (int j = 0; j < width; j++) {
  3178. const uint8_t *rptr = &srcptr[(i * width + j) * 4];
  3179. uint8_t *wptr = &data_ptr[(i * width + j) * 4];
  3180. if (rptr[3] >= alpha_threshold) {
  3181. continue;
  3182. }
  3183. int closest_dist = max_dist;
  3184. uint8_t closest_color[3];
  3185. int from_x = MAX(0, j - max_radius);
  3186. int to_x = MIN(width - 1, j + max_radius);
  3187. int from_y = MAX(0, i - max_radius);
  3188. int to_y = MIN(height - 1, i + max_radius);
  3189. for (int k = from_y; k <= to_y; k++) {
  3190. for (int l = from_x; l <= to_x; l++) {
  3191. int dy = i - k;
  3192. int dx = j - l;
  3193. int dist = dy * dy + dx * dx;
  3194. if (dist >= closest_dist) {
  3195. continue;
  3196. }
  3197. const uint8_t *rp2 = &srcptr[(k * width + l) << 2];
  3198. if (rp2[3] < alpha_threshold) {
  3199. continue;
  3200. }
  3201. closest_dist = dist;
  3202. closest_color[0] = rp2[0];
  3203. closest_color[1] = rp2[1];
  3204. closest_color[2] = rp2[2];
  3205. }
  3206. }
  3207. if (closest_dist != max_dist) {
  3208. wptr[0] = closest_color[0];
  3209. wptr[1] = closest_color[1];
  3210. wptr[2] = closest_color[2];
  3211. }
  3212. }
  3213. }
  3214. }
  3215. String Image::get_format_name(Format p_format) {
  3216. ERR_FAIL_INDEX_V(p_format, FORMAT_MAX, String());
  3217. return format_names[p_format];
  3218. }
  3219. Error Image::load_png_from_buffer(const Vector<uint8_t> &p_array) {
  3220. return _load_from_buffer(p_array, _png_mem_loader_func);
  3221. }
  3222. Error Image::load_jpg_from_buffer(const Vector<uint8_t> &p_array) {
  3223. return _load_from_buffer(p_array, _jpg_mem_loader_func);
  3224. }
  3225. Error Image::load_webp_from_buffer(const Vector<uint8_t> &p_array) {
  3226. return _load_from_buffer(p_array, _webp_mem_loader_func);
  3227. }
  3228. Error Image::load_tga_from_buffer(const Vector<uint8_t> &p_array) {
  3229. ERR_FAIL_NULL_V_MSG(
  3230. _tga_mem_loader_func,
  3231. ERR_UNAVAILABLE,
  3232. "The TGA module isn't enabled. Recompile the Godot editor or export template binary with the `module_tga_enabled=yes` SCons option.");
  3233. return _load_from_buffer(p_array, _tga_mem_loader_func);
  3234. }
  3235. Error Image::load_bmp_from_buffer(const Vector<uint8_t> &p_array) {
  3236. ERR_FAIL_NULL_V_MSG(
  3237. _bmp_mem_loader_func,
  3238. ERR_UNAVAILABLE,
  3239. "The BMP module isn't enabled. Recompile the Godot editor or export template binary with the `module_bmp_enabled=yes` SCons option.");
  3240. return _load_from_buffer(p_array, _bmp_mem_loader_func);
  3241. }
  3242. void Image::convert_rg_to_ra_rgba8() {
  3243. ERR_FAIL_COND(format != FORMAT_RGBA8);
  3244. ERR_FAIL_COND(!data.size());
  3245. int s = data.size();
  3246. uint8_t *w = data.ptrw();
  3247. for (int i = 0; i < s; i += 4) {
  3248. w[i + 3] = w[i + 1];
  3249. w[i + 1] = 0;
  3250. w[i + 2] = 0;
  3251. }
  3252. }
  3253. void Image::convert_ra_rgba8_to_rg() {
  3254. ERR_FAIL_COND(format != FORMAT_RGBA8);
  3255. ERR_FAIL_COND(!data.size());
  3256. int s = data.size();
  3257. uint8_t *w = data.ptrw();
  3258. for (int i = 0; i < s; i += 4) {
  3259. w[i + 1] = w[i + 3];
  3260. w[i + 2] = 0;
  3261. w[i + 3] = 255;
  3262. }
  3263. }
  3264. void Image::convert_rgba8_to_bgra8() {
  3265. ERR_FAIL_COND(format != FORMAT_RGBA8);
  3266. ERR_FAIL_COND(!data.size());
  3267. int s = data.size();
  3268. uint8_t *w = data.ptrw();
  3269. for (int i = 0; i < s; i += 4) {
  3270. uint8_t r = w[i];
  3271. w[i] = w[i + 2]; // Swap R to B
  3272. w[i + 2] = r; // Swap B to R
  3273. }
  3274. }
  3275. Error Image::_load_from_buffer(const Vector<uint8_t> &p_array, ImageMemLoadFunc p_loader) {
  3276. int buffer_size = p_array.size();
  3277. ERR_FAIL_COND_V(buffer_size == 0, ERR_INVALID_PARAMETER);
  3278. ERR_FAIL_COND_V(!p_loader, ERR_INVALID_PARAMETER);
  3279. const uint8_t *r = p_array.ptr();
  3280. Ref<Image> image = p_loader(r, buffer_size);
  3281. ERR_FAIL_COND_V(!image.is_valid(), ERR_PARSE_ERROR);
  3282. copy_internals_from(image);
  3283. return OK;
  3284. }
  3285. 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) {
  3286. p_out = static_cast<uint8_t>((p_a + p_b + p_c + p_d + 2) >> 2);
  3287. }
  3288. void Image::average_4_float(float &p_out, const float &p_a, const float &p_b, const float &p_c, const float &p_d) {
  3289. p_out = (p_a + p_b + p_c + p_d) * 0.25f;
  3290. }
  3291. 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) {
  3292. 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);
  3293. }
  3294. 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) {
  3295. 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();
  3296. }
  3297. void Image::renormalize_uint8(uint8_t *p_rgb) {
  3298. Vector3 n(p_rgb[0] / 255.0, p_rgb[1] / 255.0, p_rgb[2] / 255.0);
  3299. n *= 2.0;
  3300. n -= Vector3(1, 1, 1);
  3301. n.normalize();
  3302. n += Vector3(1, 1, 1);
  3303. n *= 0.5;
  3304. n *= 255;
  3305. p_rgb[0] = CLAMP(int(n.x), 0, 255);
  3306. p_rgb[1] = CLAMP(int(n.y), 0, 255);
  3307. p_rgb[2] = CLAMP(int(n.z), 0, 255);
  3308. }
  3309. void Image::renormalize_float(float *p_rgb) {
  3310. Vector3 n(p_rgb[0], p_rgb[1], p_rgb[2]);
  3311. n.normalize();
  3312. p_rgb[0] = n.x;
  3313. p_rgb[1] = n.y;
  3314. p_rgb[2] = n.z;
  3315. }
  3316. void Image::renormalize_half(uint16_t *p_rgb) {
  3317. Vector3 n(Math::half_to_float(p_rgb[0]), Math::half_to_float(p_rgb[1]), Math::half_to_float(p_rgb[2]));
  3318. n.normalize();
  3319. p_rgb[0] = Math::make_half_float(n.x);
  3320. p_rgb[1] = Math::make_half_float(n.y);
  3321. p_rgb[2] = Math::make_half_float(n.z);
  3322. }
  3323. void Image::renormalize_rgbe9995(uint32_t *p_rgb) {
  3324. // Never used
  3325. }
  3326. Image::Image(const uint8_t *p_mem_png_jpg, int p_len) {
  3327. width = 0;
  3328. height = 0;
  3329. mipmaps = false;
  3330. format = FORMAT_L8;
  3331. if (_png_mem_loader_func) {
  3332. copy_internals_from(_png_mem_loader_func(p_mem_png_jpg, p_len));
  3333. }
  3334. if (is_empty() && _jpg_mem_loader_func) {
  3335. copy_internals_from(_jpg_mem_loader_func(p_mem_png_jpg, p_len));
  3336. }
  3337. if (is_empty() && _webp_mem_loader_func) {
  3338. copy_internals_from(_webp_mem_loader_func(p_mem_png_jpg, p_len));
  3339. }
  3340. }
  3341. Ref<Resource> Image::duplicate(bool p_subresources) const {
  3342. Ref<Image> copy;
  3343. copy.instantiate();
  3344. copy->_copy_internals_from(*this);
  3345. return copy;
  3346. }
  3347. void Image::set_as_black() {
  3348. memset(data.ptrw(), 0, data.size());
  3349. }
  3350. Dictionary Image::compute_image_metrics(const Ref<Image> p_compared_image, bool p_luma_metric) {
  3351. // https://github.com/richgel999/bc7enc_rdo/blob/master/LICENSE
  3352. //
  3353. // This is free and unencumbered software released into the public domain.
  3354. // Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
  3355. // software, either in source code form or as a compiled binary, for any purpose,
  3356. // commercial or non - commercial, and by any means.
  3357. // In jurisdictions that recognize copyright laws, the author or authors of this
  3358. // software dedicate any and all copyright interest in the software to the public
  3359. // domain. We make this dedication for the benefit of the public at large and to
  3360. // the detriment of our heirs and successors. We intend this dedication to be an
  3361. // overt act of relinquishment in perpetuity of all present and future rights to
  3362. // this software under copyright law.
  3363. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  3364. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  3365. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
  3366. // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  3367. // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  3368. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  3369. Dictionary result;
  3370. result["max"] = INFINITY;
  3371. result["mean"] = INFINITY;
  3372. result["mean_squared"] = INFINITY;
  3373. result["root_mean_squared"] = INFINITY;
  3374. result["peak_snr"] = 0.0f;
  3375. ERR_FAIL_NULL_V(p_compared_image, result);
  3376. Error err = OK;
  3377. Ref<Image> compared_image = duplicate(true);
  3378. if (compared_image->is_compressed()) {
  3379. err = compared_image->decompress();
  3380. }
  3381. ERR_FAIL_COND_V(err != OK, result);
  3382. Ref<Image> source_image = p_compared_image->duplicate(true);
  3383. if (source_image->is_compressed()) {
  3384. err = source_image->decompress();
  3385. }
  3386. ERR_FAIL_COND_V(err != OK, result);
  3387. ERR_FAIL_COND_V(err != OK, result);
  3388. 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.");
  3389. 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.");
  3390. double image_metric_max, image_metric_mean, image_metric_mean_squared, image_metric_root_mean_squared, image_metric_peak_snr = 0.0;
  3391. const bool average_component_error = true;
  3392. const uint32_t w = MIN(compared_image->get_width(), source_image->get_width());
  3393. const uint32_t h = MIN(compared_image->get_height(), source_image->get_height());
  3394. // Histogram approach originally due to Charles Bloom.
  3395. double hist[256];
  3396. memset(hist, 0, sizeof(hist));
  3397. for (uint32_t y = 0; y < h; y++) {
  3398. for (uint32_t x = 0; x < w; x++) {
  3399. const Color color_a = compared_image->get_pixel(x, y);
  3400. const Color color_b = source_image->get_pixel(x, y);
  3401. if (!p_luma_metric) {
  3402. ERR_FAIL_COND_V_MSG(color_a.r > 1.0f, Dictionary(), "Can't compare HDR colors.");
  3403. ERR_FAIL_COND_V_MSG(color_b.r > 1.0f, Dictionary(), "Can't compare HDR colors.");
  3404. hist[Math::abs(color_a.get_r8() - color_b.get_r8())]++;
  3405. ERR_FAIL_COND_V_MSG(color_a.g > 1.0f, Dictionary(), "Can't compare HDR colors.");
  3406. ERR_FAIL_COND_V_MSG(color_b.g > 1.0f, Dictionary(), "Can't compare HDR colors.");
  3407. hist[Math::abs(color_a.get_g8() - color_b.get_g8())]++;
  3408. ERR_FAIL_COND_V_MSG(color_a.b > 1.0f, Dictionary(), "Can't compare HDR colors.");
  3409. ERR_FAIL_COND_V_MSG(color_b.b > 1.0f, Dictionary(), "Can't compare HDR colors.");
  3410. hist[Math::abs(color_a.get_b8() - color_b.get_b8())]++;
  3411. ERR_FAIL_COND_V_MSG(color_a.a > 1.0f, Dictionary(), "Can't compare HDR colors.");
  3412. ERR_FAIL_COND_V_MSG(color_b.a > 1.0f, Dictionary(), "Can't compare HDR colors.");
  3413. hist[Math::abs(color_a.get_a8() - color_b.get_a8())]++;
  3414. } else {
  3415. ERR_FAIL_COND_V_MSG(color_a.r > 1.0f, Dictionary(), "Can't compare HDR colors.");
  3416. ERR_FAIL_COND_V_MSG(color_b.r > 1.0f, Dictionary(), "Can't compare HDR colors.");
  3417. // REC709 weightings
  3418. int luma_a = (13938U * color_a.get_r8() + 46869U * color_a.get_g8() + 4729U * color_a.get_b8() + 32768U) >> 16U;
  3419. int luma_b = (13938U * color_b.get_r8() + 46869U * color_b.get_g8() + 4729U * color_b.get_b8() + 32768U) >> 16U;
  3420. hist[Math::abs(luma_a - luma_b)]++;
  3421. }
  3422. }
  3423. }
  3424. image_metric_max = 0;
  3425. double sum = 0.0f, sum2 = 0.0f;
  3426. for (uint32_t i = 0; i < 256; i++) {
  3427. if (!hist[i]) {
  3428. continue;
  3429. }
  3430. image_metric_max = MAX(image_metric_max, i);
  3431. double x = i * hist[i];
  3432. sum += x;
  3433. sum2 += i * x;
  3434. }
  3435. // See http://richg42.blogspot.com/2016/09/how-to-compute-psnr-from-old-berkeley.html
  3436. double total_values = w * h;
  3437. if (average_component_error) {
  3438. total_values *= 4;
  3439. }
  3440. image_metric_mean = CLAMP(sum / total_values, 0.0f, 255.0f);
  3441. image_metric_mean_squared = CLAMP(sum2 / total_values, 0.0f, 255.0f * 255.0f);
  3442. image_metric_root_mean_squared = sqrt(image_metric_mean_squared);
  3443. if (!image_metric_root_mean_squared) {
  3444. image_metric_peak_snr = 1e+10f;
  3445. } else {
  3446. image_metric_peak_snr = CLAMP(log10(255.0f / image_metric_root_mean_squared) * 20.0f, 0.0f, 500.0f);
  3447. }
  3448. result["max"] = image_metric_max;
  3449. result["mean"] = image_metric_mean;
  3450. result["mean_squared"] = image_metric_mean_squared;
  3451. result["root_mean_squared"] = image_metric_root_mean_squared;
  3452. result["peak_snr"] = image_metric_peak_snr;
  3453. return result;
  3454. }