image.cpp 130 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136
  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 (format > FORMAT_RGBE9995 || p_new_format > FORMAT_RGBE9995) {
  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, class 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, class 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, class 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, class 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.size() == 0, "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 p_format <= FORMAT_RGBE9995;
  1436. }
  1437. template <class 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.size() == 0);
  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.size() == 0);
  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.size() == 0);
  1488. ERR_FAIL_COND(data.size() == 0);
  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 format > FORMAT_RGBE9995;
  2233. }
  2234. Error Image::decompress() {
  2235. if (((format >= FORMAT_DXT1 && format <= FORMAT_RGTC_RG) || (format == FORMAT_DXT5_RA_AS_RG)) && _image_decompress_bc) {
  2236. _image_decompress_bc(this);
  2237. } else if (format >= FORMAT_BPTC_RGBA && format <= FORMAT_BPTC_RGBFU && _image_decompress_bptc) {
  2238. _image_decompress_bptc(this);
  2239. } else if (format == FORMAT_ETC && _image_decompress_etc1) {
  2240. _image_decompress_etc1(this);
  2241. } else if (format >= FORMAT_ETC2_R11 && format <= FORMAT_ETC2_RA_AS_RG && _image_decompress_etc2) {
  2242. _image_decompress_etc2(this);
  2243. } else if (format >= FORMAT_ASTC_4x4 && format <= FORMAT_ASTC_8x8_HDR && _image_decompress_astc) {
  2244. _image_decompress_astc(this);
  2245. } else {
  2246. return ERR_UNAVAILABLE;
  2247. }
  2248. return OK;
  2249. }
  2250. Error Image::compress(CompressMode p_mode, CompressSource p_source, ASTCFormat p_astc_format) {
  2251. ERR_FAIL_INDEX_V_MSG(p_mode, COMPRESS_MAX, ERR_INVALID_PARAMETER, "Invalid compress mode.");
  2252. ERR_FAIL_INDEX_V_MSG(p_source, COMPRESS_SOURCE_MAX, ERR_INVALID_PARAMETER, "Invalid compress source.");
  2253. return compress_from_channels(p_mode, detect_used_channels(p_source), p_astc_format);
  2254. }
  2255. Error Image::compress_from_channels(CompressMode p_mode, UsedChannels p_channels, ASTCFormat p_astc_format) {
  2256. ERR_FAIL_COND_V(data.is_empty(), ERR_INVALID_DATA);
  2257. switch (p_mode) {
  2258. case COMPRESS_S3TC: {
  2259. ERR_FAIL_NULL_V(_image_compress_bc_func, ERR_UNAVAILABLE);
  2260. _image_compress_bc_func(this, p_channels);
  2261. } break;
  2262. case COMPRESS_ETC: {
  2263. ERR_FAIL_NULL_V(_image_compress_etc1_func, ERR_UNAVAILABLE);
  2264. _image_compress_etc1_func(this);
  2265. } break;
  2266. case COMPRESS_ETC2: {
  2267. ERR_FAIL_NULL_V(_image_compress_etc2_func, ERR_UNAVAILABLE);
  2268. _image_compress_etc2_func(this, p_channels);
  2269. } break;
  2270. case COMPRESS_BPTC: {
  2271. ERR_FAIL_NULL_V(_image_compress_bptc_func, ERR_UNAVAILABLE);
  2272. _image_compress_bptc_func(this, p_channels);
  2273. } break;
  2274. case COMPRESS_ASTC: {
  2275. ERR_FAIL_NULL_V(_image_compress_astc_func, ERR_UNAVAILABLE);
  2276. _image_compress_astc_func(this, p_astc_format);
  2277. } break;
  2278. case COMPRESS_MAX: {
  2279. ERR_FAIL_V(ERR_INVALID_PARAMETER);
  2280. } break;
  2281. }
  2282. return OK;
  2283. }
  2284. Image::Image(const char **p_xpm) {
  2285. width = 0;
  2286. height = 0;
  2287. mipmaps = false;
  2288. format = FORMAT_L8;
  2289. initialize_data(p_xpm);
  2290. }
  2291. Image::Image(int p_width, int p_height, bool p_use_mipmaps, Format p_format) {
  2292. width = 0;
  2293. height = 0;
  2294. mipmaps = p_use_mipmaps;
  2295. format = FORMAT_L8;
  2296. initialize_data(p_width, p_height, p_use_mipmaps, p_format);
  2297. }
  2298. Image::Image(int p_width, int p_height, bool p_mipmaps, Format p_format, const Vector<uint8_t> &p_data) {
  2299. width = 0;
  2300. height = 0;
  2301. mipmaps = p_mipmaps;
  2302. format = FORMAT_L8;
  2303. initialize_data(p_width, p_height, p_mipmaps, p_format, p_data);
  2304. }
  2305. Rect2i Image::get_used_rect() const {
  2306. if (format != FORMAT_LA8 && format != FORMAT_RGBA8 && format != FORMAT_RGBAF && format != FORMAT_RGBAH && format != FORMAT_RGBA4444 && format != FORMAT_RGB565) {
  2307. return Rect2i(0, 0, width, height);
  2308. }
  2309. int len = data.size();
  2310. if (len == 0) {
  2311. return Rect2i();
  2312. }
  2313. int minx = 0xFFFFFF, miny = 0xFFFFFFF;
  2314. int maxx = -1, maxy = -1;
  2315. for (int j = 0; j < height; j++) {
  2316. for (int i = 0; i < width; i++) {
  2317. if (!(get_pixel(i, j).a > 0)) {
  2318. continue;
  2319. }
  2320. if (i > maxx) {
  2321. maxx = i;
  2322. }
  2323. if (j > maxy) {
  2324. maxy = j;
  2325. }
  2326. if (i < minx) {
  2327. minx = i;
  2328. }
  2329. if (j < miny) {
  2330. miny = j;
  2331. }
  2332. }
  2333. }
  2334. if (maxx == -1) {
  2335. return Rect2i();
  2336. } else {
  2337. return Rect2i(minx, miny, maxx - minx + 1, maxy - miny + 1);
  2338. }
  2339. }
  2340. Ref<Image> Image::get_region(const Rect2i &p_region) const {
  2341. Ref<Image> img = memnew(Image(p_region.size.x, p_region.size.y, mipmaps, format));
  2342. img->blit_rect(Ref<Image>((Image *)this), p_region, Point2i(0, 0));
  2343. return img;
  2344. }
  2345. 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 {
  2346. r_clipped_dest_rect.position = p_dest;
  2347. r_clipped_src_rect = p_src_rect;
  2348. if (r_clipped_src_rect.position.x < 0) {
  2349. r_clipped_dest_rect.position.x -= r_clipped_src_rect.position.x;
  2350. r_clipped_src_rect.size.x += r_clipped_src_rect.position.x;
  2351. r_clipped_src_rect.position.x = 0;
  2352. }
  2353. if (r_clipped_src_rect.position.y < 0) {
  2354. r_clipped_dest_rect.position.y -= r_clipped_src_rect.position.y;
  2355. r_clipped_src_rect.size.y += r_clipped_src_rect.position.y;
  2356. r_clipped_src_rect.position.y = 0;
  2357. }
  2358. if (r_clipped_dest_rect.position.x < 0) {
  2359. r_clipped_src_rect.position.x -= r_clipped_dest_rect.position.x;
  2360. r_clipped_src_rect.size.x += r_clipped_dest_rect.position.x;
  2361. r_clipped_dest_rect.position.x = 0;
  2362. }
  2363. if (r_clipped_dest_rect.position.y < 0) {
  2364. r_clipped_src_rect.position.y -= r_clipped_dest_rect.position.y;
  2365. r_clipped_src_rect.size.y += r_clipped_dest_rect.position.y;
  2366. r_clipped_dest_rect.position.y = 0;
  2367. }
  2368. 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)));
  2369. 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)));
  2370. r_clipped_dest_rect.size.x = r_clipped_src_rect.size.x;
  2371. r_clipped_dest_rect.size.y = r_clipped_src_rect.size.y;
  2372. }
  2373. void Image::blit_rect(const Ref<Image> &p_src, const Rect2i &p_src_rect, const Point2i &p_dest) {
  2374. ERR_FAIL_COND_MSG(p_src.is_null(), "It's not a reference to a valid Image object.");
  2375. int dsize = data.size();
  2376. int srcdsize = p_src->data.size();
  2377. ERR_FAIL_COND(dsize == 0);
  2378. ERR_FAIL_COND(srcdsize == 0);
  2379. ERR_FAIL_COND(format != p_src->format);
  2380. ERR_FAIL_COND_MSG(!_can_modify(format), "Cannot blit_rect in compressed or custom image formats.");
  2381. Rect2i src_rect;
  2382. Rect2i dest_rect;
  2383. _get_clipped_src_and_dest_rects(p_src, p_src_rect, p_dest, src_rect, dest_rect);
  2384. if (!src_rect.has_area() || !dest_rect.has_area()) {
  2385. return;
  2386. }
  2387. uint8_t *wp = data.ptrw();
  2388. uint8_t *dst_data_ptr = wp;
  2389. const uint8_t *rp = p_src->data.ptr();
  2390. const uint8_t *src_data_ptr = rp;
  2391. int pixel_size = get_format_pixel_size(format);
  2392. for (int i = 0; i < dest_rect.size.y; i++) {
  2393. for (int j = 0; j < dest_rect.size.x; j++) {
  2394. int src_x = src_rect.position.x + j;
  2395. int src_y = src_rect.position.y + i;
  2396. int dst_x = dest_rect.position.x + j;
  2397. int dst_y = dest_rect.position.y + i;
  2398. const uint8_t *src = &src_data_ptr[(src_y * p_src->width + src_x) * pixel_size];
  2399. uint8_t *dst = &dst_data_ptr[(dst_y * width + dst_x) * pixel_size];
  2400. for (int k = 0; k < pixel_size; k++) {
  2401. dst[k] = src[k];
  2402. }
  2403. }
  2404. }
  2405. }
  2406. void Image::blit_rect_mask(const Ref<Image> &p_src, const Ref<Image> &p_mask, const Rect2i &p_src_rect, const Point2i &p_dest) {
  2407. ERR_FAIL_COND_MSG(p_src.is_null(), "It's not a reference to a valid Image object.");
  2408. ERR_FAIL_COND_MSG(p_mask.is_null(), "It's not a reference to a valid Image object.");
  2409. int dsize = data.size();
  2410. int srcdsize = p_src->data.size();
  2411. int maskdsize = p_mask->data.size();
  2412. ERR_FAIL_COND(dsize == 0);
  2413. ERR_FAIL_COND(srcdsize == 0);
  2414. ERR_FAIL_COND(maskdsize == 0);
  2415. ERR_FAIL_COND_MSG(p_src->width != p_mask->width, "Source image width is different from mask width.");
  2416. ERR_FAIL_COND_MSG(p_src->height != p_mask->height, "Source image height is different from mask height.");
  2417. ERR_FAIL_COND(format != p_src->format);
  2418. Rect2i src_rect;
  2419. Rect2i dest_rect;
  2420. _get_clipped_src_and_dest_rects(p_src, p_src_rect, p_dest, src_rect, dest_rect);
  2421. if (!src_rect.has_area() || !dest_rect.has_area()) {
  2422. return;
  2423. }
  2424. uint8_t *wp = data.ptrw();
  2425. uint8_t *dst_data_ptr = wp;
  2426. const uint8_t *rp = p_src->data.ptr();
  2427. const uint8_t *src_data_ptr = rp;
  2428. int pixel_size = get_format_pixel_size(format);
  2429. Ref<Image> msk = p_mask;
  2430. for (int i = 0; i < dest_rect.size.y; i++) {
  2431. for (int j = 0; j < dest_rect.size.x; j++) {
  2432. int src_x = src_rect.position.x + j;
  2433. int src_y = src_rect.position.y + i;
  2434. if (msk->get_pixel(src_x, src_y).a != 0) {
  2435. int dst_x = dest_rect.position.x + j;
  2436. int dst_y = dest_rect.position.y + i;
  2437. const uint8_t *src = &src_data_ptr[(src_y * p_src->width + src_x) * pixel_size];
  2438. uint8_t *dst = &dst_data_ptr[(dst_y * width + dst_x) * pixel_size];
  2439. for (int k = 0; k < pixel_size; k++) {
  2440. dst[k] = src[k];
  2441. }
  2442. }
  2443. }
  2444. }
  2445. }
  2446. void Image::blend_rect(const Ref<Image> &p_src, const Rect2i &p_src_rect, const Point2i &p_dest) {
  2447. ERR_FAIL_COND_MSG(p_src.is_null(), "It's not a reference to a valid Image object.");
  2448. int dsize = data.size();
  2449. int srcdsize = p_src->data.size();
  2450. ERR_FAIL_COND(dsize == 0);
  2451. ERR_FAIL_COND(srcdsize == 0);
  2452. ERR_FAIL_COND(format != p_src->format);
  2453. Rect2i src_rect;
  2454. Rect2i dest_rect;
  2455. _get_clipped_src_and_dest_rects(p_src, p_src_rect, p_dest, src_rect, dest_rect);
  2456. if (!src_rect.has_area() || !dest_rect.has_area()) {
  2457. return;
  2458. }
  2459. Ref<Image> img = p_src;
  2460. for (int i = 0; i < dest_rect.size.y; i++) {
  2461. for (int j = 0; j < dest_rect.size.x; j++) {
  2462. int src_x = src_rect.position.x + j;
  2463. int src_y = src_rect.position.y + i;
  2464. int dst_x = dest_rect.position.x + j;
  2465. int dst_y = dest_rect.position.y + i;
  2466. Color sc = img->get_pixel(src_x, src_y);
  2467. if (sc.a != 0) {
  2468. Color dc = get_pixel(dst_x, dst_y);
  2469. dc = dc.blend(sc);
  2470. set_pixel(dst_x, dst_y, dc);
  2471. }
  2472. }
  2473. }
  2474. }
  2475. void Image::blend_rect_mask(const Ref<Image> &p_src, const Ref<Image> &p_mask, const Rect2i &p_src_rect, const Point2i &p_dest) {
  2476. ERR_FAIL_COND_MSG(p_src.is_null(), "It's not a reference to a valid Image object.");
  2477. ERR_FAIL_COND_MSG(p_mask.is_null(), "It's not a reference to a valid Image object.");
  2478. int dsize = data.size();
  2479. int srcdsize = p_src->data.size();
  2480. int maskdsize = p_mask->data.size();
  2481. ERR_FAIL_COND(dsize == 0);
  2482. ERR_FAIL_COND(srcdsize == 0);
  2483. ERR_FAIL_COND(maskdsize == 0);
  2484. ERR_FAIL_COND_MSG(p_src->width != p_mask->width, "Source image width is different from mask width.");
  2485. ERR_FAIL_COND_MSG(p_src->height != p_mask->height, "Source image height is different from mask height.");
  2486. ERR_FAIL_COND(format != p_src->format);
  2487. Rect2i src_rect;
  2488. Rect2i dest_rect;
  2489. _get_clipped_src_and_dest_rects(p_src, p_src_rect, p_dest, src_rect, dest_rect);
  2490. if (!src_rect.has_area() || !dest_rect.has_area()) {
  2491. return;
  2492. }
  2493. Ref<Image> img = p_src;
  2494. Ref<Image> msk = p_mask;
  2495. for (int i = 0; i < dest_rect.size.y; i++) {
  2496. for (int j = 0; j < dest_rect.size.x; j++) {
  2497. int src_x = src_rect.position.x + j;
  2498. int src_y = src_rect.position.y + i;
  2499. // If the mask's pixel is transparent then we skip it
  2500. //Color c = msk->get_pixel(src_x, src_y);
  2501. //if (c.a == 0) continue;
  2502. if (msk->get_pixel(src_x, src_y).a != 0) {
  2503. int dst_x = dest_rect.position.x + j;
  2504. int dst_y = dest_rect.position.y + i;
  2505. Color sc = img->get_pixel(src_x, src_y);
  2506. if (sc.a != 0) {
  2507. Color dc = get_pixel(dst_x, dst_y);
  2508. dc = dc.blend(sc);
  2509. set_pixel(dst_x, dst_y, dc);
  2510. }
  2511. }
  2512. }
  2513. }
  2514. }
  2515. // Repeats `p_pixel` `p_count` times in consecutive memory.
  2516. // Results in the original pixel and `p_count - 1` subsequent copies of it.
  2517. void Image::_repeat_pixel_over_subsequent_memory(uint8_t *p_pixel, int p_pixel_size, int p_count) {
  2518. int offset = 1;
  2519. for (int stride = 1; offset + stride <= p_count; stride *= 2) {
  2520. memcpy(p_pixel + offset * p_pixel_size, p_pixel, stride * p_pixel_size);
  2521. offset += stride;
  2522. }
  2523. if (offset < p_count) {
  2524. memcpy(p_pixel + offset * p_pixel_size, p_pixel, (p_count - offset) * p_pixel_size);
  2525. }
  2526. }
  2527. void Image::fill(const Color &p_color) {
  2528. if (data.size() == 0) {
  2529. return;
  2530. }
  2531. ERR_FAIL_COND_MSG(!_can_modify(format), "Cannot fill in compressed or custom image formats.");
  2532. uint8_t *dst_data_ptr = data.ptrw();
  2533. int pixel_size = get_format_pixel_size(format);
  2534. // Put first pixel with the format-aware API.
  2535. _set_color_at_ofs(dst_data_ptr, 0, p_color);
  2536. _repeat_pixel_over_subsequent_memory(dst_data_ptr, pixel_size, width * height);
  2537. }
  2538. void Image::fill_rect(const Rect2i &p_rect, const Color &p_color) {
  2539. if (data.size() == 0) {
  2540. return;
  2541. }
  2542. ERR_FAIL_COND_MSG(!_can_modify(format), "Cannot fill rect in compressed or custom image formats.");
  2543. Rect2i r = Rect2i(0, 0, width, height).intersection(p_rect.abs());
  2544. if (!r.has_area()) {
  2545. return;
  2546. }
  2547. uint8_t *dst_data_ptr = data.ptrw();
  2548. int pixel_size = get_format_pixel_size(format);
  2549. // Put first pixel with the format-aware API.
  2550. uint8_t *rect_first_pixel_ptr = &dst_data_ptr[(r.position.y * width + r.position.x) * pixel_size];
  2551. _set_color_at_ofs(rect_first_pixel_ptr, 0, p_color);
  2552. if (r.size.x == width) {
  2553. // No need to fill rows separately.
  2554. _repeat_pixel_over_subsequent_memory(rect_first_pixel_ptr, pixel_size, width * r.size.y);
  2555. } else {
  2556. _repeat_pixel_over_subsequent_memory(rect_first_pixel_ptr, pixel_size, r.size.x);
  2557. for (int y = 1; y < r.size.y; y++) {
  2558. memcpy(rect_first_pixel_ptr + y * width * pixel_size, rect_first_pixel_ptr, r.size.x * pixel_size);
  2559. }
  2560. }
  2561. }
  2562. ImageMemLoadFunc Image::_png_mem_loader_func = nullptr;
  2563. ImageMemLoadFunc Image::_jpg_mem_loader_func = nullptr;
  2564. ImageMemLoadFunc Image::_webp_mem_loader_func = nullptr;
  2565. ImageMemLoadFunc Image::_tga_mem_loader_func = nullptr;
  2566. ImageMemLoadFunc Image::_bmp_mem_loader_func = nullptr;
  2567. ScalableImageMemLoadFunc Image::_svg_scalable_mem_loader_func = nullptr;
  2568. ImageMemLoadFunc Image::_ktx_mem_loader_func = nullptr;
  2569. void (*Image::_image_compress_bc_func)(Image *, Image::UsedChannels) = nullptr;
  2570. void (*Image::_image_compress_bptc_func)(Image *, Image::UsedChannels) = nullptr;
  2571. void (*Image::_image_compress_etc1_func)(Image *) = nullptr;
  2572. void (*Image::_image_compress_etc2_func)(Image *, Image::UsedChannels) = nullptr;
  2573. void (*Image::_image_compress_astc_func)(Image *, Image::ASTCFormat) = nullptr;
  2574. void (*Image::_image_decompress_bc)(Image *) = nullptr;
  2575. void (*Image::_image_decompress_bptc)(Image *) = nullptr;
  2576. void (*Image::_image_decompress_etc1)(Image *) = nullptr;
  2577. void (*Image::_image_decompress_etc2)(Image *) = nullptr;
  2578. void (*Image::_image_decompress_astc)(Image *) = nullptr;
  2579. Vector<uint8_t> (*Image::webp_lossy_packer)(const Ref<Image> &, float) = nullptr;
  2580. Vector<uint8_t> (*Image::webp_lossless_packer)(const Ref<Image> &) = nullptr;
  2581. Ref<Image> (*Image::webp_unpacker)(const Vector<uint8_t> &) = nullptr;
  2582. Vector<uint8_t> (*Image::png_packer)(const Ref<Image> &) = nullptr;
  2583. Ref<Image> (*Image::png_unpacker)(const Vector<uint8_t> &) = nullptr;
  2584. Vector<uint8_t> (*Image::basis_universal_packer)(const Ref<Image> &, Image::UsedChannels) = nullptr;
  2585. Ref<Image> (*Image::basis_universal_unpacker)(const Vector<uint8_t> &) = nullptr;
  2586. Ref<Image> (*Image::basis_universal_unpacker_ptr)(const uint8_t *, int) = nullptr;
  2587. void Image::_set_data(const Dictionary &p_data) {
  2588. ERR_FAIL_COND(!p_data.has("width"));
  2589. ERR_FAIL_COND(!p_data.has("height"));
  2590. ERR_FAIL_COND(!p_data.has("format"));
  2591. ERR_FAIL_COND(!p_data.has("mipmaps"));
  2592. ERR_FAIL_COND(!p_data.has("data"));
  2593. int dwidth = p_data["width"];
  2594. int dheight = p_data["height"];
  2595. String dformat = p_data["format"];
  2596. bool dmipmaps = p_data["mipmaps"];
  2597. Vector<uint8_t> ddata = p_data["data"];
  2598. Format ddformat = FORMAT_MAX;
  2599. for (int i = 0; i < FORMAT_MAX; i++) {
  2600. if (dformat == get_format_name(Format(i))) {
  2601. ddformat = Format(i);
  2602. break;
  2603. }
  2604. }
  2605. ERR_FAIL_COND(ddformat == FORMAT_MAX);
  2606. initialize_data(dwidth, dheight, dmipmaps, ddformat, ddata);
  2607. }
  2608. Dictionary Image::_get_data() const {
  2609. Dictionary d;
  2610. d["width"] = width;
  2611. d["height"] = height;
  2612. d["format"] = get_format_name(format);
  2613. d["mipmaps"] = mipmaps;
  2614. d["data"] = data;
  2615. return d;
  2616. }
  2617. Color Image::get_pixelv(const Point2i &p_point) const {
  2618. return get_pixel(p_point.x, p_point.y);
  2619. }
  2620. Color Image::_get_color_at_ofs(const uint8_t *ptr, uint32_t ofs) const {
  2621. switch (format) {
  2622. case FORMAT_L8: {
  2623. float l = ptr[ofs] / 255.0;
  2624. return Color(l, l, l, 1);
  2625. }
  2626. case FORMAT_LA8: {
  2627. float l = ptr[ofs * 2 + 0] / 255.0;
  2628. float a = ptr[ofs * 2 + 1] / 255.0;
  2629. return Color(l, l, l, a);
  2630. }
  2631. case FORMAT_R8: {
  2632. float r = ptr[ofs] / 255.0;
  2633. return Color(r, 0, 0, 1);
  2634. }
  2635. case FORMAT_RG8: {
  2636. float r = ptr[ofs * 2 + 0] / 255.0;
  2637. float g = ptr[ofs * 2 + 1] / 255.0;
  2638. return Color(r, g, 0, 1);
  2639. }
  2640. case FORMAT_RGB8: {
  2641. float r = ptr[ofs * 3 + 0] / 255.0;
  2642. float g = ptr[ofs * 3 + 1] / 255.0;
  2643. float b = ptr[ofs * 3 + 2] / 255.0;
  2644. return Color(r, g, b, 1);
  2645. }
  2646. case FORMAT_RGBA8: {
  2647. float r = ptr[ofs * 4 + 0] / 255.0;
  2648. float g = ptr[ofs * 4 + 1] / 255.0;
  2649. float b = ptr[ofs * 4 + 2] / 255.0;
  2650. float a = ptr[ofs * 4 + 3] / 255.0;
  2651. return Color(r, g, b, a);
  2652. }
  2653. case FORMAT_RGBA4444: {
  2654. uint16_t u = ((uint16_t *)ptr)[ofs];
  2655. float r = ((u >> 12) & 0xF) / 15.0;
  2656. float g = ((u >> 8) & 0xF) / 15.0;
  2657. float b = ((u >> 4) & 0xF) / 15.0;
  2658. float a = (u & 0xF) / 15.0;
  2659. return Color(r, g, b, a);
  2660. }
  2661. case FORMAT_RGB565: {
  2662. uint16_t u = ((uint16_t *)ptr)[ofs];
  2663. float r = (u & 0x1F) / 31.0;
  2664. float g = ((u >> 5) & 0x3F) / 63.0;
  2665. float b = ((u >> 11) & 0x1F) / 31.0;
  2666. return Color(r, g, b, 1.0);
  2667. }
  2668. case FORMAT_RF: {
  2669. float r = ((float *)ptr)[ofs];
  2670. return Color(r, 0, 0, 1);
  2671. }
  2672. case FORMAT_RGF: {
  2673. float r = ((float *)ptr)[ofs * 2 + 0];
  2674. float g = ((float *)ptr)[ofs * 2 + 1];
  2675. return Color(r, g, 0, 1);
  2676. }
  2677. case FORMAT_RGBF: {
  2678. float r = ((float *)ptr)[ofs * 3 + 0];
  2679. float g = ((float *)ptr)[ofs * 3 + 1];
  2680. float b = ((float *)ptr)[ofs * 3 + 2];
  2681. return Color(r, g, b, 1);
  2682. }
  2683. case FORMAT_RGBAF: {
  2684. float r = ((float *)ptr)[ofs * 4 + 0];
  2685. float g = ((float *)ptr)[ofs * 4 + 1];
  2686. float b = ((float *)ptr)[ofs * 4 + 2];
  2687. float a = ((float *)ptr)[ofs * 4 + 3];
  2688. return Color(r, g, b, a);
  2689. }
  2690. case FORMAT_RH: {
  2691. uint16_t r = ((uint16_t *)ptr)[ofs];
  2692. return Color(Math::half_to_float(r), 0, 0, 1);
  2693. }
  2694. case FORMAT_RGH: {
  2695. uint16_t r = ((uint16_t *)ptr)[ofs * 2 + 0];
  2696. uint16_t g = ((uint16_t *)ptr)[ofs * 2 + 1];
  2697. return Color(Math::half_to_float(r), Math::half_to_float(g), 0, 1);
  2698. }
  2699. case FORMAT_RGBH: {
  2700. uint16_t r = ((uint16_t *)ptr)[ofs * 3 + 0];
  2701. uint16_t g = ((uint16_t *)ptr)[ofs * 3 + 1];
  2702. uint16_t b = ((uint16_t *)ptr)[ofs * 3 + 2];
  2703. return Color(Math::half_to_float(r), Math::half_to_float(g), Math::half_to_float(b), 1);
  2704. }
  2705. case FORMAT_RGBAH: {
  2706. uint16_t r = ((uint16_t *)ptr)[ofs * 4 + 0];
  2707. uint16_t g = ((uint16_t *)ptr)[ofs * 4 + 1];
  2708. uint16_t b = ((uint16_t *)ptr)[ofs * 4 + 2];
  2709. uint16_t a = ((uint16_t *)ptr)[ofs * 4 + 3];
  2710. return Color(Math::half_to_float(r), Math::half_to_float(g), Math::half_to_float(b), Math::half_to_float(a));
  2711. }
  2712. case FORMAT_RGBE9995: {
  2713. return Color::from_rgbe9995(((uint32_t *)ptr)[ofs]);
  2714. }
  2715. default: {
  2716. ERR_FAIL_V_MSG(Color(), "Can't get_pixel() on compressed image, sorry.");
  2717. }
  2718. }
  2719. }
  2720. void Image::_set_color_at_ofs(uint8_t *ptr, uint32_t ofs, const Color &p_color) {
  2721. switch (format) {
  2722. case FORMAT_L8: {
  2723. ptr[ofs] = uint8_t(CLAMP(p_color.get_v() * 255.0, 0, 255));
  2724. } break;
  2725. case FORMAT_LA8: {
  2726. ptr[ofs * 2 + 0] = uint8_t(CLAMP(p_color.get_v() * 255.0, 0, 255));
  2727. ptr[ofs * 2 + 1] = uint8_t(CLAMP(p_color.a * 255.0, 0, 255));
  2728. } break;
  2729. case FORMAT_R8: {
  2730. ptr[ofs] = uint8_t(CLAMP(p_color.r * 255.0, 0, 255));
  2731. } break;
  2732. case FORMAT_RG8: {
  2733. ptr[ofs * 2 + 0] = uint8_t(CLAMP(p_color.r * 255.0, 0, 255));
  2734. ptr[ofs * 2 + 1] = uint8_t(CLAMP(p_color.g * 255.0, 0, 255));
  2735. } break;
  2736. case FORMAT_RGB8: {
  2737. ptr[ofs * 3 + 0] = uint8_t(CLAMP(p_color.r * 255.0, 0, 255));
  2738. ptr[ofs * 3 + 1] = uint8_t(CLAMP(p_color.g * 255.0, 0, 255));
  2739. ptr[ofs * 3 + 2] = uint8_t(CLAMP(p_color.b * 255.0, 0, 255));
  2740. } break;
  2741. case FORMAT_RGBA8: {
  2742. ptr[ofs * 4 + 0] = uint8_t(CLAMP(p_color.r * 255.0, 0, 255));
  2743. ptr[ofs * 4 + 1] = uint8_t(CLAMP(p_color.g * 255.0, 0, 255));
  2744. ptr[ofs * 4 + 2] = uint8_t(CLAMP(p_color.b * 255.0, 0, 255));
  2745. ptr[ofs * 4 + 3] = uint8_t(CLAMP(p_color.a * 255.0, 0, 255));
  2746. } break;
  2747. case FORMAT_RGBA4444: {
  2748. uint16_t rgba = 0;
  2749. rgba = uint16_t(CLAMP(p_color.r * 15.0, 0, 15)) << 12;
  2750. rgba |= uint16_t(CLAMP(p_color.g * 15.0, 0, 15)) << 8;
  2751. rgba |= uint16_t(CLAMP(p_color.b * 15.0, 0, 15)) << 4;
  2752. rgba |= uint16_t(CLAMP(p_color.a * 15.0, 0, 15));
  2753. ((uint16_t *)ptr)[ofs] = rgba;
  2754. } break;
  2755. case FORMAT_RGB565: {
  2756. uint16_t rgba = 0;
  2757. rgba = uint16_t(CLAMP(p_color.r * 31.0, 0, 31));
  2758. rgba |= uint16_t(CLAMP(p_color.g * 63.0, 0, 33)) << 5;
  2759. rgba |= uint16_t(CLAMP(p_color.b * 31.0, 0, 31)) << 11;
  2760. ((uint16_t *)ptr)[ofs] = rgba;
  2761. } break;
  2762. case FORMAT_RF: {
  2763. ((float *)ptr)[ofs] = p_color.r;
  2764. } break;
  2765. case FORMAT_RGF: {
  2766. ((float *)ptr)[ofs * 2 + 0] = p_color.r;
  2767. ((float *)ptr)[ofs * 2 + 1] = p_color.g;
  2768. } break;
  2769. case FORMAT_RGBF: {
  2770. ((float *)ptr)[ofs * 3 + 0] = p_color.r;
  2771. ((float *)ptr)[ofs * 3 + 1] = p_color.g;
  2772. ((float *)ptr)[ofs * 3 + 2] = p_color.b;
  2773. } break;
  2774. case FORMAT_RGBAF: {
  2775. ((float *)ptr)[ofs * 4 + 0] = p_color.r;
  2776. ((float *)ptr)[ofs * 4 + 1] = p_color.g;
  2777. ((float *)ptr)[ofs * 4 + 2] = p_color.b;
  2778. ((float *)ptr)[ofs * 4 + 3] = p_color.a;
  2779. } break;
  2780. case FORMAT_RH: {
  2781. ((uint16_t *)ptr)[ofs] = Math::make_half_float(p_color.r);
  2782. } break;
  2783. case FORMAT_RGH: {
  2784. ((uint16_t *)ptr)[ofs * 2 + 0] = Math::make_half_float(p_color.r);
  2785. ((uint16_t *)ptr)[ofs * 2 + 1] = Math::make_half_float(p_color.g);
  2786. } break;
  2787. case FORMAT_RGBH: {
  2788. ((uint16_t *)ptr)[ofs * 3 + 0] = Math::make_half_float(p_color.r);
  2789. ((uint16_t *)ptr)[ofs * 3 + 1] = Math::make_half_float(p_color.g);
  2790. ((uint16_t *)ptr)[ofs * 3 + 2] = Math::make_half_float(p_color.b);
  2791. } break;
  2792. case FORMAT_RGBAH: {
  2793. ((uint16_t *)ptr)[ofs * 4 + 0] = Math::make_half_float(p_color.r);
  2794. ((uint16_t *)ptr)[ofs * 4 + 1] = Math::make_half_float(p_color.g);
  2795. ((uint16_t *)ptr)[ofs * 4 + 2] = Math::make_half_float(p_color.b);
  2796. ((uint16_t *)ptr)[ofs * 4 + 3] = Math::make_half_float(p_color.a);
  2797. } break;
  2798. case FORMAT_RGBE9995: {
  2799. ((uint32_t *)ptr)[ofs] = p_color.to_rgbe9995();
  2800. } break;
  2801. default: {
  2802. ERR_FAIL_MSG("Can't set_pixel() on compressed image, sorry.");
  2803. }
  2804. }
  2805. }
  2806. Color Image::get_pixel(int p_x, int p_y) const {
  2807. #ifdef DEBUG_ENABLED
  2808. ERR_FAIL_INDEX_V(p_x, width, Color());
  2809. ERR_FAIL_INDEX_V(p_y, height, Color());
  2810. #endif
  2811. uint32_t ofs = p_y * width + p_x;
  2812. return _get_color_at_ofs(data.ptr(), ofs);
  2813. }
  2814. void Image::set_pixelv(const Point2i &p_point, const Color &p_color) {
  2815. set_pixel(p_point.x, p_point.y, p_color);
  2816. }
  2817. void Image::set_pixel(int p_x, int p_y, const Color &p_color) {
  2818. #ifdef DEBUG_ENABLED
  2819. ERR_FAIL_INDEX(p_x, width);
  2820. ERR_FAIL_INDEX(p_y, height);
  2821. #endif
  2822. uint32_t ofs = p_y * width + p_x;
  2823. _set_color_at_ofs(data.ptrw(), ofs, p_color);
  2824. }
  2825. void Image::adjust_bcs(float p_brightness, float p_contrast, float p_saturation) {
  2826. ERR_FAIL_COND_MSG(!_can_modify(format), "Cannot adjust_bcs in compressed or custom image formats.");
  2827. uint8_t *w = data.ptrw();
  2828. uint32_t pixel_size = get_format_pixel_size(format);
  2829. uint32_t pixel_count = data.size() / pixel_size;
  2830. for (uint32_t i = 0; i < pixel_count; i++) {
  2831. Color c = _get_color_at_ofs(w, i);
  2832. Vector3 rgb(c.r, c.g, c.b);
  2833. rgb *= p_brightness;
  2834. rgb = Vector3(0.5, 0.5, 0.5).lerp(rgb, p_contrast);
  2835. float center = (rgb.x + rgb.y + rgb.z) / 3.0;
  2836. rgb = Vector3(center, center, center).lerp(rgb, p_saturation);
  2837. c.r = rgb.x;
  2838. c.g = rgb.y;
  2839. c.b = rgb.z;
  2840. _set_color_at_ofs(w, i, c);
  2841. }
  2842. }
  2843. Image::UsedChannels Image::detect_used_channels(CompressSource p_source) const {
  2844. ERR_FAIL_COND_V(data.size() == 0, USED_CHANNELS_RGBA);
  2845. ERR_FAIL_COND_V(is_compressed(), USED_CHANNELS_RGBA);
  2846. bool r = false, g = false, b = false, a = false, c = false;
  2847. const uint8_t *data_ptr = data.ptr();
  2848. uint32_t data_total = width * height;
  2849. for (uint32_t i = 0; i < data_total; i++) {
  2850. Color col = _get_color_at_ofs(data_ptr, i);
  2851. if (col.r > 0.001) {
  2852. r = true;
  2853. }
  2854. if (col.g > 0.001) {
  2855. g = true;
  2856. }
  2857. if (col.b > 0.001) {
  2858. b = true;
  2859. }
  2860. if (col.a < 0.999) {
  2861. a = true;
  2862. }
  2863. if (col.r != col.b || col.r != col.g || col.b != col.g) {
  2864. c = true;
  2865. }
  2866. }
  2867. UsedChannels used_channels;
  2868. if (!c && !a) {
  2869. used_channels = USED_CHANNELS_L;
  2870. } else if (!c && a) {
  2871. used_channels = USED_CHANNELS_LA;
  2872. } else if (r && !g && !b && !a) {
  2873. used_channels = USED_CHANNELS_R;
  2874. } else if (r && g && !b && !a) {
  2875. used_channels = USED_CHANNELS_RG;
  2876. } else if (r && g && b && !a) {
  2877. used_channels = USED_CHANNELS_RGB;
  2878. } else {
  2879. used_channels = USED_CHANNELS_RGBA;
  2880. }
  2881. if (p_source == COMPRESS_SOURCE_SRGB && (used_channels == USED_CHANNELS_R || used_channels == USED_CHANNELS_RG)) {
  2882. //R and RG do not support SRGB
  2883. used_channels = USED_CHANNELS_RGB;
  2884. }
  2885. if (p_source == COMPRESS_SOURCE_NORMAL) {
  2886. //use RG channels only for normal
  2887. used_channels = USED_CHANNELS_RG;
  2888. }
  2889. return used_channels;
  2890. }
  2891. void Image::optimize_channels() {
  2892. switch (detect_used_channels()) {
  2893. case USED_CHANNELS_L:
  2894. convert(FORMAT_L8);
  2895. break;
  2896. case USED_CHANNELS_LA:
  2897. convert(FORMAT_LA8);
  2898. break;
  2899. case USED_CHANNELS_R:
  2900. convert(FORMAT_R8);
  2901. break;
  2902. case USED_CHANNELS_RG:
  2903. convert(FORMAT_RG8);
  2904. break;
  2905. case USED_CHANNELS_RGB:
  2906. convert(FORMAT_RGB8);
  2907. break;
  2908. case USED_CHANNELS_RGBA:
  2909. convert(FORMAT_RGBA8);
  2910. break;
  2911. }
  2912. }
  2913. void Image::_bind_methods() {
  2914. ClassDB::bind_method(D_METHOD("get_width"), &Image::get_width);
  2915. ClassDB::bind_method(D_METHOD("get_height"), &Image::get_height);
  2916. ClassDB::bind_method(D_METHOD("get_size"), &Image::get_size);
  2917. ClassDB::bind_method(D_METHOD("has_mipmaps"), &Image::has_mipmaps);
  2918. ClassDB::bind_method(D_METHOD("get_format"), &Image::get_format);
  2919. ClassDB::bind_method(D_METHOD("get_data"), &Image::get_data);
  2920. ClassDB::bind_method(D_METHOD("convert", "format"), &Image::convert);
  2921. ClassDB::bind_method(D_METHOD("get_mipmap_count"), &Image::get_mipmap_count);
  2922. ClassDB::bind_method(D_METHOD("get_mipmap_offset", "mipmap"), &Image::get_mipmap_offset);
  2923. ClassDB::bind_method(D_METHOD("resize_to_po2", "square", "interpolation"), &Image::resize_to_po2, DEFVAL(false), DEFVAL(INTERPOLATE_BILINEAR));
  2924. ClassDB::bind_method(D_METHOD("resize", "width", "height", "interpolation"), &Image::resize, DEFVAL(INTERPOLATE_BILINEAR));
  2925. ClassDB::bind_method(D_METHOD("shrink_x2"), &Image::shrink_x2);
  2926. ClassDB::bind_method(D_METHOD("crop", "width", "height"), &Image::crop);
  2927. ClassDB::bind_method(D_METHOD("flip_x"), &Image::flip_x);
  2928. ClassDB::bind_method(D_METHOD("flip_y"), &Image::flip_y);
  2929. ClassDB::bind_method(D_METHOD("generate_mipmaps", "renormalize"), &Image::generate_mipmaps, DEFVAL(false));
  2930. ClassDB::bind_method(D_METHOD("clear_mipmaps"), &Image::clear_mipmaps);
  2931. ClassDB::bind_static_method("Image", D_METHOD("create", "width", "height", "use_mipmaps", "format"), &Image::create_empty);
  2932. ClassDB::bind_static_method("Image", D_METHOD("create_from_data", "width", "height", "use_mipmaps", "format", "data"), &Image::create_from_data);
  2933. ClassDB::bind_method(D_METHOD("set_data", "width", "height", "use_mipmaps", "format", "data"), &Image::set_data);
  2934. ClassDB::bind_method(D_METHOD("is_empty"), &Image::is_empty);
  2935. ClassDB::bind_method(D_METHOD("load", "path"), &Image::load);
  2936. ClassDB::bind_static_method("Image", D_METHOD("load_from_file", "path"), &Image::load_from_file);
  2937. ClassDB::bind_method(D_METHOD("save_png", "path"), &Image::save_png);
  2938. ClassDB::bind_method(D_METHOD("save_png_to_buffer"), &Image::save_png_to_buffer);
  2939. ClassDB::bind_method(D_METHOD("save_jpg", "path", "quality"), &Image::save_jpg, DEFVAL(0.75));
  2940. ClassDB::bind_method(D_METHOD("save_jpg_to_buffer", "quality"), &Image::save_jpg_to_buffer, DEFVAL(0.75));
  2941. ClassDB::bind_method(D_METHOD("save_exr", "path", "grayscale"), &Image::save_exr, DEFVAL(false));
  2942. ClassDB::bind_method(D_METHOD("save_exr_to_buffer", "grayscale"), &Image::save_exr_to_buffer, DEFVAL(false));
  2943. ClassDB::bind_method(D_METHOD("save_webp", "path", "lossy", "quality"), &Image::save_webp, DEFVAL(false), DEFVAL(0.75f));
  2944. ClassDB::bind_method(D_METHOD("save_webp_to_buffer", "lossy", "quality"), &Image::save_webp_to_buffer, DEFVAL(false), DEFVAL(0.75f));
  2945. ClassDB::bind_method(D_METHOD("detect_alpha"), &Image::detect_alpha);
  2946. ClassDB::bind_method(D_METHOD("is_invisible"), &Image::is_invisible);
  2947. ClassDB::bind_method(D_METHOD("detect_used_channels", "source"), &Image::detect_used_channels, DEFVAL(COMPRESS_SOURCE_GENERIC));
  2948. ClassDB::bind_method(D_METHOD("compress", "mode", "source", "astc_format"), &Image::compress, DEFVAL(COMPRESS_SOURCE_GENERIC), DEFVAL(ASTC_FORMAT_4x4));
  2949. ClassDB::bind_method(D_METHOD("compress_from_channels", "mode", "channels", "astc_format"), &Image::compress_from_channels, DEFVAL(ASTC_FORMAT_4x4));
  2950. ClassDB::bind_method(D_METHOD("decompress"), &Image::decompress);
  2951. ClassDB::bind_method(D_METHOD("is_compressed"), &Image::is_compressed);
  2952. ClassDB::bind_method(D_METHOD("rotate_90", "direction"), &Image::rotate_90);
  2953. ClassDB::bind_method(D_METHOD("rotate_180"), &Image::rotate_180);
  2954. ClassDB::bind_method(D_METHOD("fix_alpha_edges"), &Image::fix_alpha_edges);
  2955. ClassDB::bind_method(D_METHOD("premultiply_alpha"), &Image::premultiply_alpha);
  2956. ClassDB::bind_method(D_METHOD("srgb_to_linear"), &Image::srgb_to_linear);
  2957. ClassDB::bind_method(D_METHOD("normal_map_to_xy"), &Image::normal_map_to_xy);
  2958. ClassDB::bind_method(D_METHOD("rgbe_to_srgb"), &Image::rgbe_to_srgb);
  2959. ClassDB::bind_method(D_METHOD("bump_map_to_normal_map", "bump_scale"), &Image::bump_map_to_normal_map, DEFVAL(1.0));
  2960. ClassDB::bind_method(D_METHOD("compute_image_metrics", "compared_image", "use_luma"), &Image::compute_image_metrics);
  2961. ClassDB::bind_method(D_METHOD("blit_rect", "src", "src_rect", "dst"), &Image::blit_rect);
  2962. ClassDB::bind_method(D_METHOD("blit_rect_mask", "src", "mask", "src_rect", "dst"), &Image::blit_rect_mask);
  2963. ClassDB::bind_method(D_METHOD("blend_rect", "src", "src_rect", "dst"), &Image::blend_rect);
  2964. ClassDB::bind_method(D_METHOD("blend_rect_mask", "src", "mask", "src_rect", "dst"), &Image::blend_rect_mask);
  2965. ClassDB::bind_method(D_METHOD("fill", "color"), &Image::fill);
  2966. ClassDB::bind_method(D_METHOD("fill_rect", "rect", "color"), &Image::fill_rect);
  2967. ClassDB::bind_method(D_METHOD("get_used_rect"), &Image::get_used_rect);
  2968. ClassDB::bind_method(D_METHOD("get_region", "region"), &Image::get_region);
  2969. ClassDB::bind_method(D_METHOD("copy_from", "src"), &Image::copy_internals_from);
  2970. ClassDB::bind_method(D_METHOD("_set_data", "data"), &Image::_set_data);
  2971. ClassDB::bind_method(D_METHOD("_get_data"), &Image::_get_data);
  2972. ClassDB::bind_method(D_METHOD("get_pixelv", "point"), &Image::get_pixelv);
  2973. ClassDB::bind_method(D_METHOD("get_pixel", "x", "y"), &Image::get_pixel);
  2974. ClassDB::bind_method(D_METHOD("set_pixelv", "point", "color"), &Image::set_pixelv);
  2975. ClassDB::bind_method(D_METHOD("set_pixel", "x", "y", "color"), &Image::set_pixel);
  2976. ClassDB::bind_method(D_METHOD("adjust_bcs", "brightness", "contrast", "saturation"), &Image::adjust_bcs);
  2977. ClassDB::bind_method(D_METHOD("load_png_from_buffer", "buffer"), &Image::load_png_from_buffer);
  2978. ClassDB::bind_method(D_METHOD("load_jpg_from_buffer", "buffer"), &Image::load_jpg_from_buffer);
  2979. ClassDB::bind_method(D_METHOD("load_webp_from_buffer", "buffer"), &Image::load_webp_from_buffer);
  2980. ClassDB::bind_method(D_METHOD("load_tga_from_buffer", "buffer"), &Image::load_tga_from_buffer);
  2981. ClassDB::bind_method(D_METHOD("load_bmp_from_buffer", "buffer"), &Image::load_bmp_from_buffer);
  2982. ClassDB::bind_method(D_METHOD("load_ktx_from_buffer", "buffer"), &Image::load_ktx_from_buffer);
  2983. ClassDB::bind_method(D_METHOD("load_svg_from_buffer", "buffer", "scale"), &Image::load_svg_from_buffer, DEFVAL(1.0));
  2984. ClassDB::bind_method(D_METHOD("load_svg_from_string", "svg_str", "scale"), &Image::load_svg_from_string, DEFVAL(1.0));
  2985. ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE), "_set_data", "_get_data");
  2986. BIND_CONSTANT(MAX_WIDTH);
  2987. BIND_CONSTANT(MAX_HEIGHT);
  2988. BIND_ENUM_CONSTANT(FORMAT_L8); //luminance
  2989. BIND_ENUM_CONSTANT(FORMAT_LA8); //luminance-alpha
  2990. BIND_ENUM_CONSTANT(FORMAT_R8);
  2991. BIND_ENUM_CONSTANT(FORMAT_RG8);
  2992. BIND_ENUM_CONSTANT(FORMAT_RGB8);
  2993. BIND_ENUM_CONSTANT(FORMAT_RGBA8);
  2994. BIND_ENUM_CONSTANT(FORMAT_RGBA4444);
  2995. BIND_ENUM_CONSTANT(FORMAT_RGB565);
  2996. BIND_ENUM_CONSTANT(FORMAT_RF); //float
  2997. BIND_ENUM_CONSTANT(FORMAT_RGF);
  2998. BIND_ENUM_CONSTANT(FORMAT_RGBF);
  2999. BIND_ENUM_CONSTANT(FORMAT_RGBAF);
  3000. BIND_ENUM_CONSTANT(FORMAT_RH); //half float
  3001. BIND_ENUM_CONSTANT(FORMAT_RGH);
  3002. BIND_ENUM_CONSTANT(FORMAT_RGBH);
  3003. BIND_ENUM_CONSTANT(FORMAT_RGBAH);
  3004. BIND_ENUM_CONSTANT(FORMAT_RGBE9995);
  3005. BIND_ENUM_CONSTANT(FORMAT_DXT1); //s3tc bc1
  3006. BIND_ENUM_CONSTANT(FORMAT_DXT3); //bc2
  3007. BIND_ENUM_CONSTANT(FORMAT_DXT5); //bc3
  3008. BIND_ENUM_CONSTANT(FORMAT_RGTC_R);
  3009. BIND_ENUM_CONSTANT(FORMAT_RGTC_RG);
  3010. BIND_ENUM_CONSTANT(FORMAT_BPTC_RGBA); //btpc bc6h
  3011. BIND_ENUM_CONSTANT(FORMAT_BPTC_RGBF); //float /
  3012. BIND_ENUM_CONSTANT(FORMAT_BPTC_RGBFU); //unsigned float
  3013. BIND_ENUM_CONSTANT(FORMAT_ETC); //etc1
  3014. BIND_ENUM_CONSTANT(FORMAT_ETC2_R11); //etc2
  3015. BIND_ENUM_CONSTANT(FORMAT_ETC2_R11S); //signed ); NOT srgb.
  3016. BIND_ENUM_CONSTANT(FORMAT_ETC2_RG11);
  3017. BIND_ENUM_CONSTANT(FORMAT_ETC2_RG11S);
  3018. BIND_ENUM_CONSTANT(FORMAT_ETC2_RGB8);
  3019. BIND_ENUM_CONSTANT(FORMAT_ETC2_RGBA8);
  3020. BIND_ENUM_CONSTANT(FORMAT_ETC2_RGB8A1);
  3021. BIND_ENUM_CONSTANT(FORMAT_ETC2_RA_AS_RG);
  3022. BIND_ENUM_CONSTANT(FORMAT_DXT5_RA_AS_RG);
  3023. BIND_ENUM_CONSTANT(FORMAT_ASTC_4x4);
  3024. BIND_ENUM_CONSTANT(FORMAT_ASTC_4x4_HDR);
  3025. BIND_ENUM_CONSTANT(FORMAT_ASTC_8x8);
  3026. BIND_ENUM_CONSTANT(FORMAT_ASTC_8x8_HDR);
  3027. BIND_ENUM_CONSTANT(FORMAT_MAX);
  3028. BIND_ENUM_CONSTANT(INTERPOLATE_NEAREST);
  3029. BIND_ENUM_CONSTANT(INTERPOLATE_BILINEAR);
  3030. BIND_ENUM_CONSTANT(INTERPOLATE_CUBIC);
  3031. BIND_ENUM_CONSTANT(INTERPOLATE_TRILINEAR);
  3032. BIND_ENUM_CONSTANT(INTERPOLATE_LANCZOS);
  3033. BIND_ENUM_CONSTANT(ALPHA_NONE);
  3034. BIND_ENUM_CONSTANT(ALPHA_BIT);
  3035. BIND_ENUM_CONSTANT(ALPHA_BLEND);
  3036. BIND_ENUM_CONSTANT(COMPRESS_S3TC);
  3037. BIND_ENUM_CONSTANT(COMPRESS_ETC);
  3038. BIND_ENUM_CONSTANT(COMPRESS_ETC2);
  3039. BIND_ENUM_CONSTANT(COMPRESS_BPTC);
  3040. BIND_ENUM_CONSTANT(COMPRESS_ASTC);
  3041. BIND_ENUM_CONSTANT(COMPRESS_MAX);
  3042. BIND_ENUM_CONSTANT(USED_CHANNELS_L);
  3043. BIND_ENUM_CONSTANT(USED_CHANNELS_LA);
  3044. BIND_ENUM_CONSTANT(USED_CHANNELS_R);
  3045. BIND_ENUM_CONSTANT(USED_CHANNELS_RG);
  3046. BIND_ENUM_CONSTANT(USED_CHANNELS_RGB);
  3047. BIND_ENUM_CONSTANT(USED_CHANNELS_RGBA);
  3048. BIND_ENUM_CONSTANT(COMPRESS_SOURCE_GENERIC);
  3049. BIND_ENUM_CONSTANT(COMPRESS_SOURCE_SRGB);
  3050. BIND_ENUM_CONSTANT(COMPRESS_SOURCE_NORMAL);
  3051. BIND_ENUM_CONSTANT(ASTC_FORMAT_4x4);
  3052. BIND_ENUM_CONSTANT(ASTC_FORMAT_8x8);
  3053. }
  3054. void Image::set_compress_bc_func(void (*p_compress_func)(Image *, UsedChannels)) {
  3055. _image_compress_bc_func = p_compress_func;
  3056. }
  3057. void Image::set_compress_bptc_func(void (*p_compress_func)(Image *, UsedChannels)) {
  3058. _image_compress_bptc_func = p_compress_func;
  3059. }
  3060. void Image::normal_map_to_xy() {
  3061. convert(Image::FORMAT_RGBA8);
  3062. {
  3063. int len = data.size() / 4;
  3064. uint8_t *data_ptr = data.ptrw();
  3065. for (int i = 0; i < len; i++) {
  3066. data_ptr[(i << 2) + 3] = data_ptr[(i << 2) + 0]; //x to w
  3067. data_ptr[(i << 2) + 0] = data_ptr[(i << 2) + 1]; //y to xz
  3068. data_ptr[(i << 2) + 2] = data_ptr[(i << 2) + 1];
  3069. }
  3070. }
  3071. convert(Image::FORMAT_LA8);
  3072. }
  3073. Ref<Image> Image::rgbe_to_srgb() {
  3074. if (data.size() == 0) {
  3075. return Ref<Image>();
  3076. }
  3077. ERR_FAIL_COND_V(format != FORMAT_RGBE9995, Ref<Image>());
  3078. Ref<Image> new_image = create_empty(width, height, false, Image::FORMAT_RGB8);
  3079. for (int row = 0; row < height; row++) {
  3080. for (int col = 0; col < width; col++) {
  3081. new_image->set_pixel(col, row, get_pixel(col, row).linear_to_srgb());
  3082. }
  3083. }
  3084. if (has_mipmaps()) {
  3085. new_image->generate_mipmaps();
  3086. }
  3087. return new_image;
  3088. }
  3089. Ref<Image> Image::get_image_from_mipmap(int p_mipamp) const {
  3090. int ofs, size, w, h;
  3091. get_mipmap_offset_size_and_dimensions(p_mipamp, ofs, size, w, h);
  3092. Vector<uint8_t> new_data;
  3093. new_data.resize(size);
  3094. {
  3095. uint8_t *wr = new_data.ptrw();
  3096. const uint8_t *rd = data.ptr();
  3097. memcpy(wr, rd + ofs, size);
  3098. }
  3099. Ref<Image> image;
  3100. image.instantiate();
  3101. image->width = w;
  3102. image->height = h;
  3103. image->format = format;
  3104. image->data = new_data;
  3105. image->mipmaps = false;
  3106. return image;
  3107. }
  3108. void Image::bump_map_to_normal_map(float bump_scale) {
  3109. ERR_FAIL_COND(!_can_modify(format));
  3110. clear_mipmaps();
  3111. convert(Image::FORMAT_RF);
  3112. Vector<uint8_t> result_image; //rgba output
  3113. result_image.resize(width * height * 4);
  3114. {
  3115. const uint8_t *rp = data.ptr();
  3116. uint8_t *wp = result_image.ptrw();
  3117. ERR_FAIL_NULL(rp);
  3118. unsigned char *write_ptr = wp;
  3119. float *read_ptr = (float *)rp;
  3120. for (int ty = 0; ty < height; ty++) {
  3121. int py = ty + 1;
  3122. if (py >= height) {
  3123. py -= height;
  3124. }
  3125. for (int tx = 0; tx < width; tx++) {
  3126. int px = tx + 1;
  3127. if (px >= width) {
  3128. px -= width;
  3129. }
  3130. float here = read_ptr[ty * width + tx];
  3131. float to_right = read_ptr[ty * width + px];
  3132. float above = read_ptr[py * width + tx];
  3133. Vector3 up = Vector3(0, 1, (here - above) * bump_scale);
  3134. Vector3 across = Vector3(1, 0, (to_right - here) * bump_scale);
  3135. Vector3 normal = across.cross(up);
  3136. normal.normalize();
  3137. write_ptr[((ty * width + tx) << 2) + 0] = (127.5 + normal.x * 127.5);
  3138. write_ptr[((ty * width + tx) << 2) + 1] = (127.5 + normal.y * 127.5);
  3139. write_ptr[((ty * width + tx) << 2) + 2] = (127.5 + normal.z * 127.5);
  3140. write_ptr[((ty * width + tx) << 2) + 3] = 255;
  3141. }
  3142. }
  3143. }
  3144. format = FORMAT_RGBA8;
  3145. data = result_image;
  3146. }
  3147. void Image::srgb_to_linear() {
  3148. if (data.size() == 0) {
  3149. return;
  3150. }
  3151. 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 };
  3152. ERR_FAIL_COND(format != FORMAT_RGB8 && format != FORMAT_RGBA8);
  3153. if (format == FORMAT_RGBA8) {
  3154. int len = data.size() / 4;
  3155. uint8_t *data_ptr = data.ptrw();
  3156. for (int i = 0; i < len; i++) {
  3157. data_ptr[(i << 2) + 0] = srgb2lin[data_ptr[(i << 2) + 0]];
  3158. data_ptr[(i << 2) + 1] = srgb2lin[data_ptr[(i << 2) + 1]];
  3159. data_ptr[(i << 2) + 2] = srgb2lin[data_ptr[(i << 2) + 2]];
  3160. }
  3161. } else if (format == FORMAT_RGB8) {
  3162. int len = data.size() / 3;
  3163. uint8_t *data_ptr = data.ptrw();
  3164. for (int i = 0; i < len; i++) {
  3165. data_ptr[(i * 3) + 0] = srgb2lin[data_ptr[(i * 3) + 0]];
  3166. data_ptr[(i * 3) + 1] = srgb2lin[data_ptr[(i * 3) + 1]];
  3167. data_ptr[(i * 3) + 2] = srgb2lin[data_ptr[(i * 3) + 2]];
  3168. }
  3169. }
  3170. }
  3171. void Image::premultiply_alpha() {
  3172. if (data.size() == 0) {
  3173. return;
  3174. }
  3175. if (format != FORMAT_RGBA8) {
  3176. return; //not needed
  3177. }
  3178. uint8_t *data_ptr = data.ptrw();
  3179. for (int i = 0; i < height; i++) {
  3180. for (int j = 0; j < width; j++) {
  3181. uint8_t *ptr = &data_ptr[(i * width + j) * 4];
  3182. ptr[0] = (uint16_t(ptr[0]) * uint16_t(ptr[3]) + 255U) >> 8;
  3183. ptr[1] = (uint16_t(ptr[1]) * uint16_t(ptr[3]) + 255U) >> 8;
  3184. ptr[2] = (uint16_t(ptr[2]) * uint16_t(ptr[3]) + 255U) >> 8;
  3185. }
  3186. }
  3187. }
  3188. void Image::fix_alpha_edges() {
  3189. if (data.size() == 0) {
  3190. return;
  3191. }
  3192. if (format != FORMAT_RGBA8) {
  3193. return; //not needed
  3194. }
  3195. Vector<uint8_t> dcopy = data;
  3196. const uint8_t *srcptr = dcopy.ptr();
  3197. uint8_t *data_ptr = data.ptrw();
  3198. const int max_radius = 4;
  3199. const int alpha_threshold = 20;
  3200. const int max_dist = 0x7FFFFFFF;
  3201. for (int i = 0; i < height; i++) {
  3202. for (int j = 0; j < width; j++) {
  3203. const uint8_t *rptr = &srcptr[(i * width + j) * 4];
  3204. uint8_t *wptr = &data_ptr[(i * width + j) * 4];
  3205. if (rptr[3] >= alpha_threshold) {
  3206. continue;
  3207. }
  3208. int closest_dist = max_dist;
  3209. uint8_t closest_color[3] = { 0 };
  3210. int from_x = MAX(0, j - max_radius);
  3211. int to_x = MIN(width - 1, j + max_radius);
  3212. int from_y = MAX(0, i - max_radius);
  3213. int to_y = MIN(height - 1, i + max_radius);
  3214. for (int k = from_y; k <= to_y; k++) {
  3215. for (int l = from_x; l <= to_x; l++) {
  3216. int dy = i - k;
  3217. int dx = j - l;
  3218. int dist = dy * dy + dx * dx;
  3219. if (dist >= closest_dist) {
  3220. continue;
  3221. }
  3222. const uint8_t *rp2 = &srcptr[(k * width + l) << 2];
  3223. if (rp2[3] < alpha_threshold) {
  3224. continue;
  3225. }
  3226. closest_dist = dist;
  3227. closest_color[0] = rp2[0];
  3228. closest_color[1] = rp2[1];
  3229. closest_color[2] = rp2[2];
  3230. }
  3231. }
  3232. if (closest_dist != max_dist) {
  3233. wptr[0] = closest_color[0];
  3234. wptr[1] = closest_color[1];
  3235. wptr[2] = closest_color[2];
  3236. }
  3237. }
  3238. }
  3239. }
  3240. String Image::get_format_name(Format p_format) {
  3241. ERR_FAIL_INDEX_V(p_format, FORMAT_MAX, String());
  3242. return format_names[p_format];
  3243. }
  3244. Error Image::load_png_from_buffer(const Vector<uint8_t> &p_array) {
  3245. return _load_from_buffer(p_array, _png_mem_loader_func);
  3246. }
  3247. Error Image::load_jpg_from_buffer(const Vector<uint8_t> &p_array) {
  3248. return _load_from_buffer(p_array, _jpg_mem_loader_func);
  3249. }
  3250. Error Image::load_webp_from_buffer(const Vector<uint8_t> &p_array) {
  3251. return _load_from_buffer(p_array, _webp_mem_loader_func);
  3252. }
  3253. Error Image::load_tga_from_buffer(const Vector<uint8_t> &p_array) {
  3254. ERR_FAIL_NULL_V_MSG(
  3255. _tga_mem_loader_func,
  3256. ERR_UNAVAILABLE,
  3257. "The TGA module isn't enabled. Recompile the Godot editor or export template binary with the `module_tga_enabled=yes` SCons option.");
  3258. return _load_from_buffer(p_array, _tga_mem_loader_func);
  3259. }
  3260. Error Image::load_bmp_from_buffer(const Vector<uint8_t> &p_array) {
  3261. ERR_FAIL_NULL_V_MSG(
  3262. _bmp_mem_loader_func,
  3263. ERR_UNAVAILABLE,
  3264. "The BMP module isn't enabled. Recompile the Godot editor or export template binary with the `module_bmp_enabled=yes` SCons option.");
  3265. return _load_from_buffer(p_array, _bmp_mem_loader_func);
  3266. }
  3267. Error Image::load_svg_from_buffer(const Vector<uint8_t> &p_array, float scale) {
  3268. ERR_FAIL_NULL_V_MSG(
  3269. _svg_scalable_mem_loader_func,
  3270. ERR_UNAVAILABLE,
  3271. "The SVG module isn't enabled. Recompile the Godot editor or export template binary with the `module_svg_enabled=yes` SCons option.");
  3272. int buffer_size = p_array.size();
  3273. ERR_FAIL_COND_V(buffer_size == 0, ERR_INVALID_PARAMETER);
  3274. Ref<Image> image = _svg_scalable_mem_loader_func(p_array.ptr(), buffer_size, scale);
  3275. ERR_FAIL_COND_V(!image.is_valid(), ERR_PARSE_ERROR);
  3276. copy_internals_from(image);
  3277. return OK;
  3278. }
  3279. Error Image::load_svg_from_string(const String &p_svg_str, float scale) {
  3280. return load_svg_from_buffer(p_svg_str.to_utf8_buffer(), scale);
  3281. }
  3282. Error Image::load_ktx_from_buffer(const Vector<uint8_t> &p_array) {
  3283. ERR_FAIL_NULL_V_MSG(
  3284. _ktx_mem_loader_func,
  3285. ERR_UNAVAILABLE,
  3286. "The KTX module isn't enabled. Recompile the Godot editor or export template binary with the `module_ktx_enabled=yes` SCons option.");
  3287. return _load_from_buffer(p_array, _ktx_mem_loader_func);
  3288. }
  3289. void Image::convert_rg_to_ra_rgba8() {
  3290. ERR_FAIL_COND(format != FORMAT_RGBA8);
  3291. ERR_FAIL_COND(!data.size());
  3292. int s = data.size();
  3293. uint8_t *w = data.ptrw();
  3294. for (int i = 0; i < s; i += 4) {
  3295. w[i + 3] = w[i + 1];
  3296. w[i + 1] = 0;
  3297. w[i + 2] = 0;
  3298. }
  3299. }
  3300. void Image::convert_ra_rgba8_to_rg() {
  3301. ERR_FAIL_COND(format != FORMAT_RGBA8);
  3302. ERR_FAIL_COND(!data.size());
  3303. int s = data.size();
  3304. uint8_t *w = data.ptrw();
  3305. for (int i = 0; i < s; i += 4) {
  3306. w[i + 1] = w[i + 3];
  3307. w[i + 2] = 0;
  3308. w[i + 3] = 255;
  3309. }
  3310. }
  3311. void Image::convert_rgba8_to_bgra8() {
  3312. ERR_FAIL_COND(format != FORMAT_RGBA8);
  3313. ERR_FAIL_COND(!data.size());
  3314. int s = data.size();
  3315. uint8_t *w = data.ptrw();
  3316. for (int i = 0; i < s; i += 4) {
  3317. uint8_t r = w[i];
  3318. w[i] = w[i + 2]; // Swap R to B
  3319. w[i + 2] = r; // Swap B to R
  3320. }
  3321. }
  3322. Error Image::_load_from_buffer(const Vector<uint8_t> &p_array, ImageMemLoadFunc p_loader) {
  3323. int buffer_size = p_array.size();
  3324. ERR_FAIL_COND_V(buffer_size == 0, ERR_INVALID_PARAMETER);
  3325. ERR_FAIL_NULL_V(p_loader, ERR_INVALID_PARAMETER);
  3326. const uint8_t *r = p_array.ptr();
  3327. Ref<Image> image = p_loader(r, buffer_size);
  3328. ERR_FAIL_COND_V(!image.is_valid(), ERR_PARSE_ERROR);
  3329. copy_internals_from(image);
  3330. return OK;
  3331. }
  3332. 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) {
  3333. p_out = static_cast<uint8_t>((p_a + p_b + p_c + p_d + 2) >> 2);
  3334. }
  3335. void Image::average_4_float(float &p_out, const float &p_a, const float &p_b, const float &p_c, const float &p_d) {
  3336. p_out = (p_a + p_b + p_c + p_d) * 0.25f;
  3337. }
  3338. 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) {
  3339. 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);
  3340. }
  3341. 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) {
  3342. 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();
  3343. }
  3344. void Image::renormalize_uint8(uint8_t *p_rgb) {
  3345. Vector3 n(p_rgb[0] / 255.0, p_rgb[1] / 255.0, p_rgb[2] / 255.0);
  3346. n *= 2.0;
  3347. n -= Vector3(1, 1, 1);
  3348. n.normalize();
  3349. n += Vector3(1, 1, 1);
  3350. n *= 0.5;
  3351. n *= 255;
  3352. p_rgb[0] = CLAMP(int(n.x), 0, 255);
  3353. p_rgb[1] = CLAMP(int(n.y), 0, 255);
  3354. p_rgb[2] = CLAMP(int(n.z), 0, 255);
  3355. }
  3356. void Image::renormalize_float(float *p_rgb) {
  3357. Vector3 n(p_rgb[0], p_rgb[1], p_rgb[2]);
  3358. n.normalize();
  3359. p_rgb[0] = n.x;
  3360. p_rgb[1] = n.y;
  3361. p_rgb[2] = n.z;
  3362. }
  3363. void Image::renormalize_half(uint16_t *p_rgb) {
  3364. Vector3 n(Math::half_to_float(p_rgb[0]), Math::half_to_float(p_rgb[1]), Math::half_to_float(p_rgb[2]));
  3365. n.normalize();
  3366. p_rgb[0] = Math::make_half_float(n.x);
  3367. p_rgb[1] = Math::make_half_float(n.y);
  3368. p_rgb[2] = Math::make_half_float(n.z);
  3369. }
  3370. void Image::renormalize_rgbe9995(uint32_t *p_rgb) {
  3371. // Never used
  3372. }
  3373. Image::Image(const uint8_t *p_mem_png_jpg, int p_len) {
  3374. width = 0;
  3375. height = 0;
  3376. mipmaps = false;
  3377. format = FORMAT_L8;
  3378. if (_png_mem_loader_func) {
  3379. copy_internals_from(_png_mem_loader_func(p_mem_png_jpg, p_len));
  3380. }
  3381. if (is_empty() && _jpg_mem_loader_func) {
  3382. copy_internals_from(_jpg_mem_loader_func(p_mem_png_jpg, p_len));
  3383. }
  3384. if (is_empty() && _webp_mem_loader_func) {
  3385. copy_internals_from(_webp_mem_loader_func(p_mem_png_jpg, p_len));
  3386. }
  3387. }
  3388. Ref<Resource> Image::duplicate(bool p_subresources) const {
  3389. Ref<Image> copy;
  3390. copy.instantiate();
  3391. copy->_copy_internals_from(*this);
  3392. return copy;
  3393. }
  3394. void Image::set_as_black() {
  3395. memset(data.ptrw(), 0, data.size());
  3396. }
  3397. Dictionary Image::compute_image_metrics(const Ref<Image> p_compared_image, bool p_luma_metric) {
  3398. // https://github.com/richgel999/bc7enc_rdo/blob/master/LICENSE
  3399. //
  3400. // This is free and unencumbered software released into the public domain.
  3401. // Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
  3402. // software, either in source code form or as a compiled binary, for any purpose,
  3403. // commercial or non - commercial, and by any means.
  3404. // In jurisdictions that recognize copyright laws, the author or authors of this
  3405. // software dedicate any and all copyright interest in the software to the public
  3406. // domain. We make this dedication for the benefit of the public at large and to
  3407. // the detriment of our heirs and successors. We intend this dedication to be an
  3408. // overt act of relinquishment in perpetuity of all present and future rights to
  3409. // this software under copyright law.
  3410. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  3411. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  3412. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
  3413. // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  3414. // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  3415. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  3416. Dictionary result;
  3417. result["max"] = INFINITY;
  3418. result["mean"] = INFINITY;
  3419. result["mean_squared"] = INFINITY;
  3420. result["root_mean_squared"] = INFINITY;
  3421. result["peak_snr"] = 0.0f;
  3422. ERR_FAIL_NULL_V(p_compared_image, result);
  3423. Error err = OK;
  3424. Ref<Image> compared_image = duplicate(true);
  3425. if (compared_image->is_compressed()) {
  3426. err = compared_image->decompress();
  3427. }
  3428. ERR_FAIL_COND_V(err != OK, result);
  3429. Ref<Image> source_image = p_compared_image->duplicate(true);
  3430. if (source_image->is_compressed()) {
  3431. err = source_image->decompress();
  3432. }
  3433. ERR_FAIL_COND_V(err != OK, result);
  3434. ERR_FAIL_COND_V(err != OK, result);
  3435. 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.");
  3436. 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.");
  3437. double image_metric_max, image_metric_mean, image_metric_mean_squared, image_metric_root_mean_squared, image_metric_peak_snr = 0.0;
  3438. const bool average_component_error = true;
  3439. const uint32_t w = MIN(compared_image->get_width(), source_image->get_width());
  3440. const uint32_t h = MIN(compared_image->get_height(), source_image->get_height());
  3441. // Histogram approach originally due to Charles Bloom.
  3442. double hist[256];
  3443. memset(hist, 0, sizeof(hist));
  3444. for (uint32_t y = 0; y < h; y++) {
  3445. for (uint32_t x = 0; x < w; x++) {
  3446. const Color color_a = compared_image->get_pixel(x, y);
  3447. const Color color_b = source_image->get_pixel(x, y);
  3448. if (!p_luma_metric) {
  3449. ERR_FAIL_COND_V_MSG(color_a.r > 1.0f, Dictionary(), "Can't compare HDR colors.");
  3450. ERR_FAIL_COND_V_MSG(color_b.r > 1.0f, Dictionary(), "Can't compare HDR colors.");
  3451. hist[Math::abs(color_a.get_r8() - color_b.get_r8())]++;
  3452. ERR_FAIL_COND_V_MSG(color_a.g > 1.0f, Dictionary(), "Can't compare HDR colors.");
  3453. ERR_FAIL_COND_V_MSG(color_b.g > 1.0f, Dictionary(), "Can't compare HDR colors.");
  3454. hist[Math::abs(color_a.get_g8() - color_b.get_g8())]++;
  3455. ERR_FAIL_COND_V_MSG(color_a.b > 1.0f, Dictionary(), "Can't compare HDR colors.");
  3456. ERR_FAIL_COND_V_MSG(color_b.b > 1.0f, Dictionary(), "Can't compare HDR colors.");
  3457. hist[Math::abs(color_a.get_b8() - color_b.get_b8())]++;
  3458. ERR_FAIL_COND_V_MSG(color_a.a > 1.0f, Dictionary(), "Can't compare HDR colors.");
  3459. ERR_FAIL_COND_V_MSG(color_b.a > 1.0f, Dictionary(), "Can't compare HDR colors.");
  3460. hist[Math::abs(color_a.get_a8() - color_b.get_a8())]++;
  3461. } else {
  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. // REC709 weightings
  3465. int luma_a = (13938U * color_a.get_r8() + 46869U * color_a.get_g8() + 4729U * color_a.get_b8() + 32768U) >> 16U;
  3466. int luma_b = (13938U * color_b.get_r8() + 46869U * color_b.get_g8() + 4729U * color_b.get_b8() + 32768U) >> 16U;
  3467. hist[Math::abs(luma_a - luma_b)]++;
  3468. }
  3469. }
  3470. }
  3471. image_metric_max = 0;
  3472. double sum = 0.0f, sum2 = 0.0f;
  3473. for (uint32_t i = 0; i < 256; i++) {
  3474. if (!hist[i]) {
  3475. continue;
  3476. }
  3477. image_metric_max = MAX(image_metric_max, i);
  3478. double x = i * hist[i];
  3479. sum += x;
  3480. sum2 += i * x;
  3481. }
  3482. // See http://richg42.blogspot.com/2016/09/how-to-compute-psnr-from-old-berkeley.html
  3483. double total_values = w * h;
  3484. if (average_component_error) {
  3485. total_values *= 4;
  3486. }
  3487. image_metric_mean = CLAMP(sum / total_values, 0.0f, 255.0f);
  3488. image_metric_mean_squared = CLAMP(sum2 / total_values, 0.0f, 255.0f * 255.0f);
  3489. image_metric_root_mean_squared = sqrt(image_metric_mean_squared);
  3490. if (!image_metric_root_mean_squared) {
  3491. image_metric_peak_snr = 1e+10f;
  3492. } else {
  3493. image_metric_peak_snr = CLAMP(log10(255.0f / image_metric_root_mean_squared) * 20.0f, 0.0f, 500.0f);
  3494. }
  3495. result["max"] = image_metric_max;
  3496. result["mean"] = image_metric_mean;
  3497. result["mean_squared"] = image_metric_mean_squared;
  3498. result["root_mean_squared"] = image_metric_root_mean_squared;
  3499. result["peak_snr"] = image_metric_peak_snr;
  3500. return result;
  3501. }