image.cpp 130 KB

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