rtextures.c 222 KB

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