tile.cpp 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333
  1. /*
  2. Minetest
  3. Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #include "tile.h"
  17. #include <algorithm>
  18. #include <ICameraSceneNode.h>
  19. #include <IrrCompileConfig.h>
  20. #include "util/string.h"
  21. #include "util/container.h"
  22. #include "util/thread.h"
  23. #include "filesys.h"
  24. #include "settings.h"
  25. #include "mesh.h"
  26. #include "gamedef.h"
  27. #include "util/strfnd.h"
  28. #include "imagefilters.h"
  29. #include "guiscalingfilter.h"
  30. #include "renderingengine.h"
  31. #include "util/base64.h"
  32. /*
  33. A cache from texture name to texture path
  34. */
  35. MutexedMap<std::string, std::string> g_texturename_to_path_cache;
  36. /*
  37. Replaces the filename extension.
  38. eg:
  39. std::string image = "a/image.png"
  40. replace_ext(image, "jpg")
  41. -> image = "a/image.jpg"
  42. Returns true on success.
  43. */
  44. static bool replace_ext(std::string &path, const char *ext)
  45. {
  46. if (ext == NULL)
  47. return false;
  48. // Find place of last dot, fail if \ or / found.
  49. s32 last_dot_i = -1;
  50. for (s32 i=path.size()-1; i>=0; i--)
  51. {
  52. if (path[i] == '.')
  53. {
  54. last_dot_i = i;
  55. break;
  56. }
  57. if (path[i] == '\\' || path[i] == '/')
  58. break;
  59. }
  60. // If not found, return an empty string
  61. if (last_dot_i == -1)
  62. return false;
  63. // Else make the new path
  64. path = path.substr(0, last_dot_i+1) + ext;
  65. return true;
  66. }
  67. /*
  68. Find out the full path of an image by trying different filename
  69. extensions.
  70. If failed, return "".
  71. */
  72. std::string getImagePath(std::string path)
  73. {
  74. // A NULL-ended list of possible image extensions
  75. const char *extensions[] = { "png", "jpg", "bmp", "tga", NULL };
  76. // If there is no extension, assume PNG
  77. if (removeStringEnd(path, extensions).empty())
  78. path = path + ".png";
  79. // Check paths until something is found to exist
  80. const char **ext = extensions;
  81. do{
  82. bool r = replace_ext(path, *ext);
  83. if (!r)
  84. return "";
  85. if (fs::PathExists(path))
  86. return path;
  87. }
  88. while((++ext) != NULL);
  89. return "";
  90. }
  91. /*
  92. Gets the path to a texture by first checking if the texture exists
  93. in texture_path and if not, using the data path.
  94. Checks all supported extensions by replacing the original extension.
  95. If not found, returns "".
  96. Utilizes a thread-safe cache.
  97. */
  98. std::string getTexturePath(const std::string &filename, bool *is_base_pack)
  99. {
  100. std::string fullpath;
  101. // This can set a wrong value on cached textures, but is irrelevant because
  102. // is_base_pack is only passed when initializing the textures the first time
  103. if (is_base_pack)
  104. *is_base_pack = false;
  105. /*
  106. Check from cache
  107. */
  108. bool incache = g_texturename_to_path_cache.get(filename, &fullpath);
  109. if (incache)
  110. return fullpath;
  111. /*
  112. Check from texture_path
  113. */
  114. for (const auto &path : getTextureDirs()) {
  115. std::string testpath = path + DIR_DELIM;
  116. testpath.append(filename);
  117. // Check all filename extensions. Returns "" if not found.
  118. fullpath = getImagePath(testpath);
  119. if (!fullpath.empty())
  120. break;
  121. }
  122. /*
  123. Check from default data directory
  124. */
  125. if (fullpath.empty())
  126. {
  127. std::string base_path = porting::path_share + DIR_DELIM + "textures"
  128. + DIR_DELIM + "base" + DIR_DELIM + "pack";
  129. std::string testpath = base_path + DIR_DELIM + filename;
  130. // Check all filename extensions. Returns "" if not found.
  131. fullpath = getImagePath(testpath);
  132. if (is_base_pack && !fullpath.empty())
  133. *is_base_pack = true;
  134. }
  135. // Add to cache (also an empty result is cached)
  136. g_texturename_to_path_cache.set(filename, fullpath);
  137. // Finally return it
  138. return fullpath;
  139. }
  140. void clearTextureNameCache()
  141. {
  142. g_texturename_to_path_cache.clear();
  143. }
  144. /*
  145. Stores internal information about a texture.
  146. */
  147. struct TextureInfo
  148. {
  149. std::string name;
  150. video::ITexture *texture;
  151. TextureInfo(
  152. const std::string &name_,
  153. video::ITexture *texture_=NULL
  154. ):
  155. name(name_),
  156. texture(texture_)
  157. {
  158. }
  159. };
  160. /*
  161. SourceImageCache: A cache used for storing source images.
  162. */
  163. class SourceImageCache
  164. {
  165. public:
  166. ~SourceImageCache() {
  167. for (auto &m_image : m_images) {
  168. m_image.second->drop();
  169. }
  170. m_images.clear();
  171. }
  172. void insert(const std::string &name, video::IImage *img, bool prefer_local)
  173. {
  174. assert(img); // Pre-condition
  175. // Remove old image
  176. std::map<std::string, video::IImage*>::iterator n;
  177. n = m_images.find(name);
  178. if (n != m_images.end()){
  179. if (n->second)
  180. n->second->drop();
  181. }
  182. video::IImage* toadd = img;
  183. bool need_to_grab = true;
  184. // Try to use local texture instead if asked to
  185. if (prefer_local) {
  186. bool is_base_pack;
  187. std::string path = getTexturePath(name, &is_base_pack);
  188. // Ignore base pack
  189. if (!path.empty() && !is_base_pack) {
  190. video::IImage *img2 = RenderingEngine::get_video_driver()->
  191. createImageFromFile(path.c_str());
  192. if (img2){
  193. toadd = img2;
  194. need_to_grab = false;
  195. }
  196. }
  197. }
  198. if (need_to_grab)
  199. toadd->grab();
  200. m_images[name] = toadd;
  201. }
  202. video::IImage* get(const std::string &name)
  203. {
  204. std::map<std::string, video::IImage*>::iterator n;
  205. n = m_images.find(name);
  206. if (n != m_images.end())
  207. return n->second;
  208. return NULL;
  209. }
  210. // Primarily fetches from cache, secondarily tries to read from filesystem
  211. video::IImage *getOrLoad(const std::string &name)
  212. {
  213. std::map<std::string, video::IImage*>::iterator n;
  214. n = m_images.find(name);
  215. if (n != m_images.end()){
  216. n->second->grab(); // Grab for caller
  217. return n->second;
  218. }
  219. video::IVideoDriver *driver = RenderingEngine::get_video_driver();
  220. std::string path = getTexturePath(name);
  221. if (path.empty()) {
  222. infostream<<"SourceImageCache::getOrLoad(): No path found for \""
  223. <<name<<"\""<<std::endl;
  224. return NULL;
  225. }
  226. infostream<<"SourceImageCache::getOrLoad(): Loading path \""<<path
  227. <<"\""<<std::endl;
  228. video::IImage *img = driver->createImageFromFile(path.c_str());
  229. if (img){
  230. m_images[name] = img;
  231. img->grab(); // Grab for caller
  232. }
  233. return img;
  234. }
  235. private:
  236. std::map<std::string, video::IImage*> m_images;
  237. };
  238. /*
  239. TextureSource
  240. */
  241. class TextureSource : public IWritableTextureSource
  242. {
  243. public:
  244. TextureSource();
  245. virtual ~TextureSource();
  246. /*
  247. Example case:
  248. Now, assume a texture with the id 1 exists, and has the name
  249. "stone.png^mineral1".
  250. Then a random thread calls getTextureId for a texture called
  251. "stone.png^mineral1^crack0".
  252. ...Now, WTF should happen? Well:
  253. - getTextureId strips off stuff recursively from the end until
  254. the remaining part is found, or nothing is left when
  255. something is stripped out
  256. But it is slow to search for textures by names and modify them
  257. like that?
  258. - ContentFeatures is made to contain ids for the basic plain
  259. textures
  260. - Crack textures can be slow by themselves, but the framework
  261. must be fast.
  262. Example case #2:
  263. - Assume a texture with the id 1 exists, and has the name
  264. "stone.png^mineral_coal.png".
  265. - Now getNodeTile() stumbles upon a node which uses
  266. texture id 1, and determines that MATERIAL_FLAG_CRACK
  267. must be applied to the tile
  268. - MapBlockMesh::animate() finds the MATERIAL_FLAG_CRACK and
  269. has received the current crack level 0 from the client. It
  270. finds out the name of the texture with getTextureName(1),
  271. appends "^crack0" to it and gets a new texture id with
  272. getTextureId("stone.png^mineral_coal.png^crack0").
  273. */
  274. /*
  275. Gets a texture id from cache or
  276. - if main thread, generates the texture, adds to cache and returns id.
  277. - if other thread, adds to request queue and waits for main thread.
  278. The id 0 points to a NULL texture. It is returned in case of error.
  279. */
  280. u32 getTextureId(const std::string &name);
  281. // Finds out the name of a cached texture.
  282. std::string getTextureName(u32 id);
  283. /*
  284. If texture specified by the name pointed by the id doesn't
  285. exist, create it, then return the cached texture.
  286. Can be called from any thread. If called from some other thread
  287. and not found in cache, the call is queued to the main thread
  288. for processing.
  289. */
  290. video::ITexture* getTexture(u32 id);
  291. video::ITexture* getTexture(const std::string &name, u32 *id = NULL);
  292. /*
  293. Get a texture specifically intended for mesh
  294. application, i.e. not HUD, compositing, or other 2D
  295. use. This texture may be a different size and may
  296. have had additional filters applied.
  297. */
  298. video::ITexture* getTextureForMesh(const std::string &name, u32 *id);
  299. virtual Palette* getPalette(const std::string &name);
  300. bool isKnownSourceImage(const std::string &name)
  301. {
  302. bool is_known = false;
  303. bool cache_found = m_source_image_existence.get(name, &is_known);
  304. if (cache_found)
  305. return is_known;
  306. // Not found in cache; find out if a local file exists
  307. is_known = (!getTexturePath(name).empty());
  308. m_source_image_existence.set(name, is_known);
  309. return is_known;
  310. }
  311. // Processes queued texture requests from other threads.
  312. // Shall be called from the main thread.
  313. void processQueue();
  314. // Insert an image into the cache without touching the filesystem.
  315. // Shall be called from the main thread.
  316. void insertSourceImage(const std::string &name, video::IImage *img);
  317. // Rebuild images and textures from the current set of source images
  318. // Shall be called from the main thread.
  319. void rebuildImagesAndTextures();
  320. video::ITexture* getNormalTexture(const std::string &name);
  321. video::SColor getTextureAverageColor(const std::string &name);
  322. video::ITexture *getShaderFlagsTexture(bool normamap_present);
  323. private:
  324. // The id of the thread that is allowed to use irrlicht directly
  325. std::thread::id m_main_thread;
  326. // Cache of source images
  327. // This should be only accessed from the main thread
  328. SourceImageCache m_sourcecache;
  329. // Generate a texture
  330. u32 generateTexture(const std::string &name);
  331. // Generate image based on a string like "stone.png" or "[crack:1:0".
  332. // if baseimg is NULL, it is created. Otherwise stuff is made on it.
  333. bool generateImagePart(std::string part_of_name, video::IImage *& baseimg);
  334. /*! Generates an image from a full string like
  335. * "stone.png^mineral_coal.png^[crack:1:0".
  336. * Shall be called from the main thread.
  337. * The returned Image should be dropped.
  338. */
  339. video::IImage* generateImage(const std::string &name);
  340. // Thread-safe cache of what source images are known (true = known)
  341. MutexedMap<std::string, bool> m_source_image_existence;
  342. // A texture id is index in this array.
  343. // The first position contains a NULL texture.
  344. std::vector<TextureInfo> m_textureinfo_cache;
  345. // Maps a texture name to an index in the former.
  346. std::map<std::string, u32> m_name_to_id;
  347. // The two former containers are behind this mutex
  348. std::mutex m_textureinfo_cache_mutex;
  349. // Queued texture fetches (to be processed by the main thread)
  350. RequestQueue<std::string, u32, u8, u8> m_get_texture_queue;
  351. // Textures that have been overwritten with other ones
  352. // but can't be deleted because the ITexture* might still be used
  353. std::vector<video::ITexture*> m_texture_trash;
  354. // Maps image file names to loaded palettes.
  355. std::unordered_map<std::string, Palette> m_palettes;
  356. // Cached settings needed for making textures from meshes
  357. bool m_setting_mipmap;
  358. bool m_setting_trilinear_filter;
  359. bool m_setting_bilinear_filter;
  360. };
  361. IWritableTextureSource *createTextureSource()
  362. {
  363. return new TextureSource();
  364. }
  365. TextureSource::TextureSource()
  366. {
  367. m_main_thread = std::this_thread::get_id();
  368. // Add a NULL TextureInfo as the first index, named ""
  369. m_textureinfo_cache.emplace_back("");
  370. m_name_to_id[""] = 0;
  371. // Cache some settings
  372. // Note: Since this is only done once, the game must be restarted
  373. // for these settings to take effect
  374. m_setting_mipmap = g_settings->getBool("mip_map");
  375. m_setting_trilinear_filter = g_settings->getBool("trilinear_filter");
  376. m_setting_bilinear_filter = g_settings->getBool("bilinear_filter");
  377. }
  378. TextureSource::~TextureSource()
  379. {
  380. video::IVideoDriver *driver = RenderingEngine::get_video_driver();
  381. unsigned int textures_before = driver->getTextureCount();
  382. for (const auto &iter : m_textureinfo_cache) {
  383. //cleanup texture
  384. if (iter.texture)
  385. driver->removeTexture(iter.texture);
  386. }
  387. m_textureinfo_cache.clear();
  388. for (auto t : m_texture_trash) {
  389. //cleanup trashed texture
  390. driver->removeTexture(t);
  391. }
  392. infostream << "~TextureSource() before cleanup: "<< textures_before
  393. << " after: " << driver->getTextureCount() << std::endl;
  394. }
  395. u32 TextureSource::getTextureId(const std::string &name)
  396. {
  397. //infostream<<"getTextureId(): \""<<name<<"\""<<std::endl;
  398. {
  399. /*
  400. See if texture already exists
  401. */
  402. MutexAutoLock lock(m_textureinfo_cache_mutex);
  403. std::map<std::string, u32>::iterator n;
  404. n = m_name_to_id.find(name);
  405. if (n != m_name_to_id.end())
  406. {
  407. return n->second;
  408. }
  409. }
  410. /*
  411. Get texture
  412. */
  413. if (std::this_thread::get_id() == m_main_thread) {
  414. return generateTexture(name);
  415. }
  416. infostream<<"getTextureId(): Queued: name=\""<<name<<"\""<<std::endl;
  417. // We're gonna ask the result to be put into here
  418. static ResultQueue<std::string, u32, u8, u8> result_queue;
  419. // Throw a request in
  420. m_get_texture_queue.add(name, 0, 0, &result_queue);
  421. try {
  422. while(true) {
  423. // Wait result for a second
  424. GetResult<std::string, u32, u8, u8>
  425. result = result_queue.pop_front(1000);
  426. if (result.key == name) {
  427. return result.item;
  428. }
  429. }
  430. } catch(ItemNotFoundException &e) {
  431. errorstream << "Waiting for texture " << name << " timed out." << std::endl;
  432. return 0;
  433. }
  434. infostream << "getTextureId(): Failed" << std::endl;
  435. return 0;
  436. }
  437. // Draw an image on top of an another one, using the alpha channel of the
  438. // source image
  439. static void blit_with_alpha(video::IImage *src, video::IImage *dst,
  440. v2s32 src_pos, v2s32 dst_pos, v2u32 size);
  441. // Like blit_with_alpha, but only modifies destination pixels that
  442. // are fully opaque
  443. static void blit_with_alpha_overlay(video::IImage *src, video::IImage *dst,
  444. v2s32 src_pos, v2s32 dst_pos, v2u32 size);
  445. // Apply a color to an image. Uses an int (0-255) to calculate the ratio.
  446. // If the ratio is 255 or -1 and keep_alpha is true, then it multiples the
  447. // color alpha with the destination alpha.
  448. // Otherwise, any pixels that are not fully transparent get the color alpha.
  449. static void apply_colorize(video::IImage *dst, v2u32 dst_pos, v2u32 size,
  450. const video::SColor &color, int ratio, bool keep_alpha);
  451. // paint a texture using the given color
  452. static void apply_multiplication(video::IImage *dst, v2u32 dst_pos, v2u32 size,
  453. const video::SColor &color);
  454. // Apply a mask to an image
  455. static void apply_mask(video::IImage *mask, video::IImage *dst,
  456. v2s32 mask_pos, v2s32 dst_pos, v2u32 size);
  457. // Draw or overlay a crack
  458. static void draw_crack(video::IImage *crack, video::IImage *dst,
  459. bool use_overlay, s32 frame_count, s32 progression,
  460. video::IVideoDriver *driver, u8 tiles = 1);
  461. // Brighten image
  462. void brighten(video::IImage *image);
  463. // Parse a transform name
  464. u32 parseImageTransform(const std::string& s);
  465. // Apply transform to image dimension
  466. core::dimension2d<u32> imageTransformDimension(u32 transform, core::dimension2d<u32> dim);
  467. // Apply transform to image data
  468. void imageTransform(u32 transform, video::IImage *src, video::IImage *dst);
  469. /*
  470. This method generates all the textures
  471. */
  472. u32 TextureSource::generateTexture(const std::string &name)
  473. {
  474. //infostream << "generateTexture(): name=\"" << name << "\"" << std::endl;
  475. // Empty name means texture 0
  476. if (name.empty()) {
  477. infostream<<"generateTexture(): name is empty"<<std::endl;
  478. return 0;
  479. }
  480. {
  481. /*
  482. See if texture already exists
  483. */
  484. MutexAutoLock lock(m_textureinfo_cache_mutex);
  485. std::map<std::string, u32>::iterator n;
  486. n = m_name_to_id.find(name);
  487. if (n != m_name_to_id.end()) {
  488. return n->second;
  489. }
  490. }
  491. /*
  492. Calling only allowed from main thread
  493. */
  494. if (std::this_thread::get_id() != m_main_thread) {
  495. errorstream<<"TextureSource::generateTexture() "
  496. "called not from main thread"<<std::endl;
  497. return 0;
  498. }
  499. video::IVideoDriver *driver = RenderingEngine::get_video_driver();
  500. sanity_check(driver);
  501. video::IImage *img = generateImage(name);
  502. video::ITexture *tex = NULL;
  503. if (img != NULL) {
  504. #if ENABLE_GLES
  505. img = Align2Npot2(img, driver);
  506. #endif
  507. // Create texture from resulting image
  508. tex = driver->addTexture(name.c_str(), img);
  509. guiScalingCache(io::path(name.c_str()), driver, img);
  510. img->drop();
  511. }
  512. /*
  513. Add texture to caches (add NULL textures too)
  514. */
  515. MutexAutoLock lock(m_textureinfo_cache_mutex);
  516. u32 id = m_textureinfo_cache.size();
  517. TextureInfo ti(name, tex);
  518. m_textureinfo_cache.push_back(ti);
  519. m_name_to_id[name] = id;
  520. return id;
  521. }
  522. std::string TextureSource::getTextureName(u32 id)
  523. {
  524. MutexAutoLock lock(m_textureinfo_cache_mutex);
  525. if (id >= m_textureinfo_cache.size())
  526. {
  527. errorstream<<"TextureSource::getTextureName(): id="<<id
  528. <<" >= m_textureinfo_cache.size()="
  529. <<m_textureinfo_cache.size()<<std::endl;
  530. return "";
  531. }
  532. return m_textureinfo_cache[id].name;
  533. }
  534. video::ITexture* TextureSource::getTexture(u32 id)
  535. {
  536. MutexAutoLock lock(m_textureinfo_cache_mutex);
  537. if (id >= m_textureinfo_cache.size())
  538. return NULL;
  539. return m_textureinfo_cache[id].texture;
  540. }
  541. video::ITexture* TextureSource::getTexture(const std::string &name, u32 *id)
  542. {
  543. u32 actual_id = getTextureId(name);
  544. if (id){
  545. *id = actual_id;
  546. }
  547. return getTexture(actual_id);
  548. }
  549. video::ITexture* TextureSource::getTextureForMesh(const std::string &name, u32 *id)
  550. {
  551. static thread_local bool filter_needed =
  552. g_settings->getBool("texture_clean_transparent") || m_setting_mipmap ||
  553. ((m_setting_trilinear_filter || m_setting_bilinear_filter) &&
  554. g_settings->getS32("texture_min_size") > 1);
  555. // Avoid duplicating texture if it won't actually change
  556. if (filter_needed)
  557. return getTexture(name + "^[applyfiltersformesh", id);
  558. return getTexture(name, id);
  559. }
  560. Palette* TextureSource::getPalette(const std::string &name)
  561. {
  562. // Only the main thread may load images
  563. sanity_check(std::this_thread::get_id() == m_main_thread);
  564. if (name.empty())
  565. return NULL;
  566. auto it = m_palettes.find(name);
  567. if (it == m_palettes.end()) {
  568. // Create palette
  569. video::IImage *img = generateImage(name);
  570. if (!img) {
  571. warningstream << "TextureSource::getPalette(): palette \"" << name
  572. << "\" could not be loaded." << std::endl;
  573. return NULL;
  574. }
  575. Palette new_palette;
  576. u32 w = img->getDimension().Width;
  577. u32 h = img->getDimension().Height;
  578. // Real area of the image
  579. u32 area = h * w;
  580. if (area == 0)
  581. return NULL;
  582. if (area > 256) {
  583. warningstream << "TextureSource::getPalette(): the specified"
  584. << " palette image \"" << name << "\" is larger than 256"
  585. << " pixels, using the first 256." << std::endl;
  586. area = 256;
  587. } else if (256 % area != 0)
  588. warningstream << "TextureSource::getPalette(): the "
  589. << "specified palette image \"" << name << "\" does not "
  590. << "contain power of two pixels." << std::endl;
  591. // We stretch the palette so it will fit 256 values
  592. // This many param2 values will have the same color
  593. u32 step = 256 / area;
  594. // For each pixel in the image
  595. for (u32 i = 0; i < area; i++) {
  596. video::SColor c = img->getPixel(i % w, i / w);
  597. // Fill in palette with 'step' colors
  598. for (u32 j = 0; j < step; j++)
  599. new_palette.push_back(c);
  600. }
  601. img->drop();
  602. // Fill in remaining elements
  603. while (new_palette.size() < 256)
  604. new_palette.emplace_back(0xFFFFFFFF);
  605. m_palettes[name] = new_palette;
  606. it = m_palettes.find(name);
  607. }
  608. if (it != m_palettes.end())
  609. return &((*it).second);
  610. return NULL;
  611. }
  612. void TextureSource::processQueue()
  613. {
  614. /*
  615. Fetch textures
  616. */
  617. //NOTE this is only thread safe for ONE consumer thread!
  618. if (!m_get_texture_queue.empty())
  619. {
  620. GetRequest<std::string, u32, u8, u8>
  621. request = m_get_texture_queue.pop();
  622. /*infostream<<"TextureSource::processQueue(): "
  623. <<"got texture request with "
  624. <<"name=\""<<request.key<<"\""
  625. <<std::endl;*/
  626. m_get_texture_queue.pushResult(request, generateTexture(request.key));
  627. }
  628. }
  629. void TextureSource::insertSourceImage(const std::string &name, video::IImage *img)
  630. {
  631. //infostream<<"TextureSource::insertSourceImage(): name="<<name<<std::endl;
  632. sanity_check(std::this_thread::get_id() == m_main_thread);
  633. m_sourcecache.insert(name, img, true);
  634. m_source_image_existence.set(name, true);
  635. }
  636. void TextureSource::rebuildImagesAndTextures()
  637. {
  638. MutexAutoLock lock(m_textureinfo_cache_mutex);
  639. video::IVideoDriver *driver = RenderingEngine::get_video_driver();
  640. sanity_check(driver);
  641. infostream << "TextureSource: recreating " << m_textureinfo_cache.size()
  642. << " textures" << std::endl;
  643. // Recreate textures
  644. for (TextureInfo &ti : m_textureinfo_cache) {
  645. if (ti.name.empty())
  646. continue; // Skip dummy entry
  647. video::IImage *img = generateImage(ti.name);
  648. #if ENABLE_GLES
  649. img = Align2Npot2(img, driver);
  650. #endif
  651. // Create texture from resulting image
  652. video::ITexture *t = NULL;
  653. if (img) {
  654. t = driver->addTexture(ti.name.c_str(), img);
  655. guiScalingCache(io::path(ti.name.c_str()), driver, img);
  656. img->drop();
  657. }
  658. video::ITexture *t_old = ti.texture;
  659. // Replace texture
  660. ti.texture = t;
  661. if (t_old)
  662. m_texture_trash.push_back(t_old);
  663. }
  664. }
  665. inline static void applyShadeFactor(video::SColor &color, u32 factor)
  666. {
  667. u32 f = core::clamp<u32>(factor, 0, 256);
  668. color.setRed(color.getRed() * f / 256);
  669. color.setGreen(color.getGreen() * f / 256);
  670. color.setBlue(color.getBlue() * f / 256);
  671. }
  672. static video::IImage *createInventoryCubeImage(
  673. video::IImage *top, video::IImage *left, video::IImage *right)
  674. {
  675. core::dimension2du size_top = top->getDimension();
  676. core::dimension2du size_left = left->getDimension();
  677. core::dimension2du size_right = right->getDimension();
  678. u32 size = npot2(std::max({
  679. size_top.Width, size_top.Height,
  680. size_left.Width, size_left.Height,
  681. size_right.Width, size_right.Height,
  682. }));
  683. // It must be divisible by 4, to let everything work correctly.
  684. // But it is a power of 2, so being at least 4 is the same.
  685. // And the resulting texture should't be too large as well.
  686. size = core::clamp<u32>(size, 4, 64);
  687. // With such parameters, the cube fits exactly, touching each image line
  688. // from `0` to `cube_size - 1`. (Note that division is exact here).
  689. u32 cube_size = 9 * size;
  690. u32 offset = size / 2;
  691. video::IVideoDriver *driver = RenderingEngine::get_video_driver();
  692. auto lock_image = [size, driver] (video::IImage *&image) -> const u32 * {
  693. image->grab();
  694. core::dimension2du dim = image->getDimension();
  695. video::ECOLOR_FORMAT format = image->getColorFormat();
  696. if (dim.Width != size || dim.Height != size || format != video::ECF_A8R8G8B8) {
  697. video::IImage *scaled = driver->createImage(video::ECF_A8R8G8B8, {size, size});
  698. image->copyToScaling(scaled);
  699. image->drop();
  700. image = scaled;
  701. }
  702. sanity_check(image->getPitch() == 4 * size);
  703. return reinterpret_cast<u32 *>(image->getData());
  704. };
  705. auto free_image = [] (video::IImage *image) -> void {
  706. image->drop();
  707. };
  708. video::IImage *result = driver->createImage(video::ECF_A8R8G8B8, {cube_size, cube_size});
  709. sanity_check(result->getPitch() == 4 * cube_size);
  710. result->fill(video::SColor(0x00000000u));
  711. u32 *target = reinterpret_cast<u32 *>(result->getData());
  712. // Draws single cube face
  713. // `shade_factor` is face brightness, in range [0.0, 1.0]
  714. // (xu, xv, x1; yu, yv, y1) form coordinate transformation matrix
  715. // `offsets` list pixels to be drawn for single source pixel
  716. auto draw_image = [=] (video::IImage *image, float shade_factor,
  717. s16 xu, s16 xv, s16 x1,
  718. s16 yu, s16 yv, s16 y1,
  719. std::initializer_list<v2s16> offsets) -> void {
  720. u32 brightness = core::clamp<u32>(256 * shade_factor, 0, 256);
  721. const u32 *source = lock_image(image);
  722. for (u16 v = 0; v < size; v++) {
  723. for (u16 u = 0; u < size; u++) {
  724. video::SColor pixel(*source);
  725. applyShadeFactor(pixel, brightness);
  726. s16 x = xu * u + xv * v + x1;
  727. s16 y = yu * u + yv * v + y1;
  728. for (const auto &off : offsets)
  729. target[(y + off.Y) * cube_size + (x + off.X) + offset] = pixel.color;
  730. source++;
  731. }
  732. }
  733. free_image(image);
  734. };
  735. draw_image(top, 1.000000f,
  736. 4, -4, 4 * (size - 1),
  737. 2, 2, 0,
  738. {
  739. {2, 0}, {3, 0}, {4, 0}, {5, 0},
  740. {0, 1}, {1, 1}, {2, 1}, {3, 1}, {4, 1}, {5, 1}, {6, 1}, {7, 1},
  741. {2, 2}, {3, 2}, {4, 2}, {5, 2},
  742. });
  743. draw_image(left, 0.836660f,
  744. 4, 0, 0,
  745. 2, 5, 2 * size,
  746. {
  747. {0, 0}, {1, 0},
  748. {0, 1}, {1, 1}, {2, 1}, {3, 1},
  749. {0, 2}, {1, 2}, {2, 2}, {3, 2},
  750. {0, 3}, {1, 3}, {2, 3}, {3, 3},
  751. {0, 4}, {1, 4}, {2, 4}, {3, 4},
  752. {2, 5}, {3, 5},
  753. });
  754. draw_image(right, 0.670820f,
  755. 4, 0, 4 * size,
  756. -2, 5, 4 * size - 2,
  757. {
  758. {2, 0}, {3, 0},
  759. {0, 1}, {1, 1}, {2, 1}, {3, 1},
  760. {0, 2}, {1, 2}, {2, 2}, {3, 2},
  761. {0, 3}, {1, 3}, {2, 3}, {3, 3},
  762. {0, 4}, {1, 4}, {2, 4}, {3, 4},
  763. {0, 5}, {1, 5},
  764. });
  765. return result;
  766. }
  767. video::IImage* TextureSource::generateImage(const std::string &name)
  768. {
  769. // Get the base image
  770. const char separator = '^';
  771. const char escape = '\\';
  772. const char paren_open = '(';
  773. const char paren_close = ')';
  774. // Find last separator in the name
  775. s32 last_separator_pos = -1;
  776. u8 paren_bal = 0;
  777. for (s32 i = name.size() - 1; i >= 0; i--) {
  778. if (i > 0 && name[i-1] == escape)
  779. continue;
  780. switch (name[i]) {
  781. case separator:
  782. if (paren_bal == 0) {
  783. last_separator_pos = i;
  784. i = -1; // break out of loop
  785. }
  786. break;
  787. case paren_open:
  788. if (paren_bal == 0) {
  789. errorstream << "generateImage(): unbalanced parentheses"
  790. << "(extranous '(') while generating texture \""
  791. << name << "\"" << std::endl;
  792. return NULL;
  793. }
  794. paren_bal--;
  795. break;
  796. case paren_close:
  797. paren_bal++;
  798. break;
  799. default:
  800. break;
  801. }
  802. }
  803. if (paren_bal > 0) {
  804. errorstream << "generateImage(): unbalanced parentheses"
  805. << "(missing matching '(') while generating texture \""
  806. << name << "\"" << std::endl;
  807. return NULL;
  808. }
  809. video::IImage *baseimg = NULL;
  810. /*
  811. If separator was found, make the base image
  812. using a recursive call.
  813. */
  814. if (last_separator_pos != -1) {
  815. baseimg = generateImage(name.substr(0, last_separator_pos));
  816. }
  817. /*
  818. Parse out the last part of the name of the image and act
  819. according to it
  820. */
  821. std::string last_part_of_name = name.substr(last_separator_pos + 1);
  822. /*
  823. If this name is enclosed in parentheses, generate it
  824. and blit it onto the base image
  825. */
  826. if (last_part_of_name[0] == paren_open
  827. && last_part_of_name[last_part_of_name.size() - 1] == paren_close) {
  828. std::string name2 = last_part_of_name.substr(1,
  829. last_part_of_name.size() - 2);
  830. video::IImage *tmp = generateImage(name2);
  831. if (!tmp) {
  832. errorstream << "generateImage(): "
  833. "Failed to generate \"" << name2 << "\""
  834. << std::endl;
  835. return NULL;
  836. }
  837. core::dimension2d<u32> dim = tmp->getDimension();
  838. if (baseimg) {
  839. blit_with_alpha(tmp, baseimg, v2s32(0, 0), v2s32(0, 0), dim);
  840. tmp->drop();
  841. } else {
  842. baseimg = tmp;
  843. }
  844. } else if (!generateImagePart(last_part_of_name, baseimg)) {
  845. // Generate image according to part of name
  846. errorstream << "generateImage(): "
  847. "Failed to generate \"" << last_part_of_name << "\""
  848. << std::endl;
  849. }
  850. // If no resulting image, print a warning
  851. if (baseimg == NULL) {
  852. errorstream << "generateImage(): baseimg is NULL (attempted to"
  853. " create texture \"" << name << "\")" << std::endl;
  854. }
  855. return baseimg;
  856. }
  857. #if ENABLE_GLES
  858. /**
  859. * Check and align image to npot2 if required by hardware
  860. * @param image image to check for npot2 alignment
  861. * @param driver driver to use for image operations
  862. * @return image or copy of image aligned to npot2
  863. */
  864. video::IImage *Align2Npot2(video::IImage *image,
  865. video::IVideoDriver *driver)
  866. {
  867. if (image == NULL)
  868. return image;
  869. if (driver->queryFeature(video::EVDF_TEXTURE_NPOT))
  870. return image;
  871. core::dimension2d<u32> dim = image->getDimension();
  872. unsigned int height = npot2(dim.Height);
  873. unsigned int width = npot2(dim.Width);
  874. if (dim.Height == height && dim.Width == width)
  875. return image;
  876. if (dim.Height > height)
  877. height *= 2;
  878. if (dim.Width > width)
  879. width *= 2;
  880. video::IImage *targetimage =
  881. driver->createImage(video::ECF_A8R8G8B8,
  882. core::dimension2d<u32>(width, height));
  883. if (targetimage != NULL)
  884. image->copyToScaling(targetimage);
  885. image->drop();
  886. return targetimage;
  887. }
  888. #endif
  889. static std::string unescape_string(const std::string &str, const char esc = '\\')
  890. {
  891. std::string out;
  892. size_t pos = 0, cpos;
  893. out.reserve(str.size());
  894. while (1) {
  895. cpos = str.find_first_of(esc, pos);
  896. if (cpos == std::string::npos) {
  897. out += str.substr(pos);
  898. break;
  899. }
  900. out += str.substr(pos, cpos - pos) + str[cpos + 1];
  901. pos = cpos + 2;
  902. }
  903. return out;
  904. }
  905. void blitBaseImage(video::IImage* &src, video::IImage* &dst)
  906. {
  907. //infostream<<"Blitting "<<part_of_name<<" on base"<<std::endl;
  908. // Size of the copied area
  909. core::dimension2d<u32> dim = src->getDimension();
  910. //core::dimension2d<u32> dim(16,16);
  911. // Position to copy the blitted to in the base image
  912. core::position2d<s32> pos_to(0,0);
  913. // Position to copy the blitted from in the blitted image
  914. core::position2d<s32> pos_from(0,0);
  915. // Blit
  916. /*image->copyToWithAlpha(baseimg, pos_to,
  917. core::rect<s32>(pos_from, dim),
  918. video::SColor(255,255,255,255),
  919. NULL);*/
  920. core::dimension2d<u32> dim_dst = dst->getDimension();
  921. if (dim == dim_dst) {
  922. blit_with_alpha(src, dst, pos_from, pos_to, dim);
  923. } else if (dim.Width * dim.Height < dim_dst.Width * dim_dst.Height) {
  924. // Upscale overlying image
  925. video::IImage *scaled_image = RenderingEngine::get_video_driver()->
  926. createImage(video::ECF_A8R8G8B8, dim_dst);
  927. src->copyToScaling(scaled_image);
  928. blit_with_alpha(scaled_image, dst, pos_from, pos_to, dim_dst);
  929. scaled_image->drop();
  930. } else {
  931. // Upscale base image
  932. video::IImage *scaled_base = RenderingEngine::get_video_driver()->
  933. createImage(video::ECF_A8R8G8B8, dim);
  934. dst->copyToScaling(scaled_base);
  935. dst->drop();
  936. dst = scaled_base;
  937. blit_with_alpha(src, dst, pos_from, pos_to, dim);
  938. }
  939. }
  940. bool TextureSource::generateImagePart(std::string part_of_name,
  941. video::IImage *& baseimg)
  942. {
  943. const char escape = '\\'; // same as in generateImage()
  944. video::IVideoDriver *driver = RenderingEngine::get_video_driver();
  945. sanity_check(driver);
  946. // Stuff starting with [ are special commands
  947. if (part_of_name.empty() || part_of_name[0] != '[') {
  948. video::IImage *image = m_sourcecache.getOrLoad(part_of_name);
  949. if (image == NULL) {
  950. if (!part_of_name.empty()) {
  951. // Do not create normalmap dummies
  952. if (part_of_name.find("_normal.png") != std::string::npos) {
  953. warningstream << "generateImage(): Could not load normal map \""
  954. << part_of_name << "\"" << std::endl;
  955. return true;
  956. }
  957. errorstream << "generateImage(): Could not load image \""
  958. << part_of_name << "\" while building texture; "
  959. "Creating a dummy image" << std::endl;
  960. }
  961. // Just create a dummy image
  962. //core::dimension2d<u32> dim(2,2);
  963. core::dimension2d<u32> dim(1,1);
  964. image = driver->createImage(video::ECF_A8R8G8B8, dim);
  965. sanity_check(image != NULL);
  966. /*image->setPixel(0,0, video::SColor(255,255,0,0));
  967. image->setPixel(1,0, video::SColor(255,0,255,0));
  968. image->setPixel(0,1, video::SColor(255,0,0,255));
  969. image->setPixel(1,1, video::SColor(255,255,0,255));*/
  970. image->setPixel(0,0, video::SColor(255,myrand()%256,
  971. myrand()%256,myrand()%256));
  972. /*image->setPixel(1,0, video::SColor(255,myrand()%256,
  973. myrand()%256,myrand()%256));
  974. image->setPixel(0,1, video::SColor(255,myrand()%256,
  975. myrand()%256,myrand()%256));
  976. image->setPixel(1,1, video::SColor(255,myrand()%256,
  977. myrand()%256,myrand()%256));*/
  978. }
  979. // If base image is NULL, load as base.
  980. if (baseimg == NULL)
  981. {
  982. //infostream<<"Setting "<<part_of_name<<" as base"<<std::endl;
  983. /*
  984. Copy it this way to get an alpha channel.
  985. Otherwise images with alpha cannot be blitted on
  986. images that don't have alpha in the original file.
  987. */
  988. core::dimension2d<u32> dim = image->getDimension();
  989. baseimg = driver->createImage(video::ECF_A8R8G8B8, dim);
  990. image->copyTo(baseimg);
  991. }
  992. // Else blit on base.
  993. else
  994. {
  995. blitBaseImage(image, baseimg);
  996. }
  997. //cleanup
  998. image->drop();
  999. }
  1000. else
  1001. {
  1002. // A special texture modification
  1003. /*infostream<<"generateImage(): generating special "
  1004. <<"modification \""<<part_of_name<<"\""
  1005. <<std::endl;*/
  1006. /*
  1007. [crack:N:P
  1008. [cracko:N:P
  1009. Adds a cracking texture
  1010. N = animation frame count, P = crack progression
  1011. */
  1012. if (str_starts_with(part_of_name, "[crack"))
  1013. {
  1014. if (baseimg == NULL) {
  1015. errorstream<<"generateImagePart(): baseimg == NULL "
  1016. <<"for part_of_name=\""<<part_of_name
  1017. <<"\", cancelling."<<std::endl;
  1018. return false;
  1019. }
  1020. // Crack image number and overlay option
  1021. // Format: crack[o][:<tiles>]:<frame_count>:<frame>
  1022. bool use_overlay = (part_of_name[6] == 'o');
  1023. Strfnd sf(part_of_name);
  1024. sf.next(":");
  1025. s32 frame_count = stoi(sf.next(":"));
  1026. s32 progression = stoi(sf.next(":"));
  1027. s32 tiles = 1;
  1028. // Check whether there is the <tiles> argument, that is,
  1029. // whether there are 3 arguments. If so, shift values
  1030. // as the first and not the last argument is optional.
  1031. auto s = sf.next(":");
  1032. if (!s.empty()) {
  1033. tiles = frame_count;
  1034. frame_count = progression;
  1035. progression = stoi(s);
  1036. }
  1037. if (progression >= 0) {
  1038. /*
  1039. Load crack image.
  1040. It is an image with a number of cracking stages
  1041. horizontally tiled.
  1042. */
  1043. video::IImage *img_crack = m_sourcecache.getOrLoad(
  1044. "crack_anylength.png");
  1045. if (img_crack) {
  1046. draw_crack(img_crack, baseimg,
  1047. use_overlay, frame_count,
  1048. progression, driver, tiles);
  1049. img_crack->drop();
  1050. }
  1051. }
  1052. }
  1053. /*
  1054. [combine:WxH:X,Y=filename:X,Y=filename2
  1055. Creates a bigger texture from any amount of smaller ones
  1056. */
  1057. else if (str_starts_with(part_of_name, "[combine"))
  1058. {
  1059. Strfnd sf(part_of_name);
  1060. sf.next(":");
  1061. u32 w0 = stoi(sf.next("x"));
  1062. u32 h0 = stoi(sf.next(":"));
  1063. core::dimension2d<u32> dim(w0,h0);
  1064. if (baseimg == NULL) {
  1065. baseimg = driver->createImage(video::ECF_A8R8G8B8, dim);
  1066. baseimg->fill(video::SColor(0,0,0,0));
  1067. }
  1068. while (!sf.at_end()) {
  1069. u32 x = stoi(sf.next(","));
  1070. u32 y = stoi(sf.next("="));
  1071. std::string filename = unescape_string(sf.next_esc(":", escape), escape);
  1072. infostream<<"Adding \""<<filename
  1073. <<"\" to combined ("<<x<<","<<y<<")"
  1074. <<std::endl;
  1075. video::IImage *img = generateImage(filename);
  1076. if (img) {
  1077. core::dimension2d<u32> dim = img->getDimension();
  1078. core::position2d<s32> pos_base(x, y);
  1079. video::IImage *img2 =
  1080. driver->createImage(video::ECF_A8R8G8B8, dim);
  1081. img->copyTo(img2);
  1082. img->drop();
  1083. /*img2->copyToWithAlpha(baseimg, pos_base,
  1084. core::rect<s32>(v2s32(0,0), dim),
  1085. video::SColor(255,255,255,255),
  1086. NULL);*/
  1087. blit_with_alpha(img2, baseimg, v2s32(0,0), pos_base, dim);
  1088. img2->drop();
  1089. } else {
  1090. errorstream << "generateImagePart(): Failed to load image \""
  1091. << filename << "\" for [combine" << std::endl;
  1092. }
  1093. }
  1094. }
  1095. /*
  1096. [brighten
  1097. */
  1098. else if (str_starts_with(part_of_name, "[brighten"))
  1099. {
  1100. if (baseimg == NULL) {
  1101. errorstream<<"generateImagePart(): baseimg==NULL "
  1102. <<"for part_of_name=\""<<part_of_name
  1103. <<"\", cancelling."<<std::endl;
  1104. return false;
  1105. }
  1106. brighten(baseimg);
  1107. }
  1108. /*
  1109. [noalpha
  1110. Make image completely opaque.
  1111. Used for the leaves texture when in old leaves mode, so
  1112. that the transparent parts don't look completely black
  1113. when simple alpha channel is used for rendering.
  1114. */
  1115. else if (str_starts_with(part_of_name, "[noalpha"))
  1116. {
  1117. if (baseimg == NULL){
  1118. errorstream<<"generateImagePart(): baseimg==NULL "
  1119. <<"for part_of_name=\""<<part_of_name
  1120. <<"\", cancelling."<<std::endl;
  1121. return false;
  1122. }
  1123. core::dimension2d<u32> dim = baseimg->getDimension();
  1124. // Set alpha to full
  1125. for (u32 y=0; y<dim.Height; y++)
  1126. for (u32 x=0; x<dim.Width; x++)
  1127. {
  1128. video::SColor c = baseimg->getPixel(x,y);
  1129. c.setAlpha(255);
  1130. baseimg->setPixel(x,y,c);
  1131. }
  1132. }
  1133. /*
  1134. [makealpha:R,G,B
  1135. Convert one color to transparent.
  1136. */
  1137. else if (str_starts_with(part_of_name, "[makealpha:"))
  1138. {
  1139. if (baseimg == NULL) {
  1140. errorstream<<"generateImagePart(): baseimg == NULL "
  1141. <<"for part_of_name=\""<<part_of_name
  1142. <<"\", cancelling."<<std::endl;
  1143. return false;
  1144. }
  1145. Strfnd sf(part_of_name.substr(11));
  1146. u32 r1 = stoi(sf.next(","));
  1147. u32 g1 = stoi(sf.next(","));
  1148. u32 b1 = stoi(sf.next(""));
  1149. core::dimension2d<u32> dim = baseimg->getDimension();
  1150. /*video::IImage *oldbaseimg = baseimg;
  1151. baseimg = driver->createImage(video::ECF_A8R8G8B8, dim);
  1152. oldbaseimg->copyTo(baseimg);
  1153. oldbaseimg->drop();*/
  1154. // Set alpha to full
  1155. for (u32 y=0; y<dim.Height; y++)
  1156. for (u32 x=0; x<dim.Width; x++)
  1157. {
  1158. video::SColor c = baseimg->getPixel(x,y);
  1159. u32 r = c.getRed();
  1160. u32 g = c.getGreen();
  1161. u32 b = c.getBlue();
  1162. if (!(r == r1 && g == g1 && b == b1))
  1163. continue;
  1164. c.setAlpha(0);
  1165. baseimg->setPixel(x,y,c);
  1166. }
  1167. }
  1168. /*
  1169. [transformN
  1170. Rotates and/or flips the image.
  1171. N can be a number (between 0 and 7) or a transform name.
  1172. Rotations are counter-clockwise.
  1173. 0 I identity
  1174. 1 R90 rotate by 90 degrees
  1175. 2 R180 rotate by 180 degrees
  1176. 3 R270 rotate by 270 degrees
  1177. 4 FX flip X
  1178. 5 FXR90 flip X then rotate by 90 degrees
  1179. 6 FY flip Y
  1180. 7 FYR90 flip Y then rotate by 90 degrees
  1181. Note: Transform names can be concatenated to produce
  1182. their product (applies the first then the second).
  1183. The resulting transform will be equivalent to one of the
  1184. eight existing ones, though (see: dihedral group).
  1185. */
  1186. else if (str_starts_with(part_of_name, "[transform"))
  1187. {
  1188. if (baseimg == NULL) {
  1189. errorstream<<"generateImagePart(): baseimg == NULL "
  1190. <<"for part_of_name=\""<<part_of_name
  1191. <<"\", cancelling."<<std::endl;
  1192. return false;
  1193. }
  1194. u32 transform = parseImageTransform(part_of_name.substr(10));
  1195. core::dimension2d<u32> dim = imageTransformDimension(
  1196. transform, baseimg->getDimension());
  1197. video::IImage *image = driver->createImage(
  1198. baseimg->getColorFormat(), dim);
  1199. sanity_check(image != NULL);
  1200. imageTransform(transform, baseimg, image);
  1201. baseimg->drop();
  1202. baseimg = image;
  1203. }
  1204. /*
  1205. [inventorycube{topimage{leftimage{rightimage
  1206. In every subimage, replace ^ with &.
  1207. Create an "inventory cube".
  1208. NOTE: This should be used only on its own.
  1209. Example (a grass block (not actually used in game):
  1210. "[inventorycube{grass.png{mud.png&grass_side.png{mud.png&grass_side.png"
  1211. */
  1212. else if (str_starts_with(part_of_name, "[inventorycube"))
  1213. {
  1214. if (baseimg != NULL){
  1215. errorstream<<"generateImagePart(): baseimg != NULL "
  1216. <<"for part_of_name=\""<<part_of_name
  1217. <<"\", cancelling."<<std::endl;
  1218. return false;
  1219. }
  1220. str_replace(part_of_name, '&', '^');
  1221. Strfnd sf(part_of_name);
  1222. sf.next("{");
  1223. std::string imagename_top = sf.next("{");
  1224. std::string imagename_left = sf.next("{");
  1225. std::string imagename_right = sf.next("{");
  1226. // Generate images for the faces of the cube
  1227. video::IImage *img_top = generateImage(imagename_top);
  1228. video::IImage *img_left = generateImage(imagename_left);
  1229. video::IImage *img_right = generateImage(imagename_right);
  1230. if (img_top == NULL || img_left == NULL || img_right == NULL) {
  1231. errorstream << "generateImagePart(): Failed to create textures"
  1232. << " for inventorycube \"" << part_of_name << "\""
  1233. << std::endl;
  1234. baseimg = generateImage(imagename_top);
  1235. return true;
  1236. }
  1237. baseimg = createInventoryCubeImage(img_top, img_left, img_right);
  1238. // Face images are not needed anymore
  1239. img_top->drop();
  1240. img_left->drop();
  1241. img_right->drop();
  1242. return true;
  1243. }
  1244. /*
  1245. [lowpart:percent:filename
  1246. Adds the lower part of a texture
  1247. */
  1248. else if (str_starts_with(part_of_name, "[lowpart:"))
  1249. {
  1250. Strfnd sf(part_of_name);
  1251. sf.next(":");
  1252. u32 percent = stoi(sf.next(":"));
  1253. std::string filename = unescape_string(sf.next_esc(":", escape), escape);
  1254. if (baseimg == NULL)
  1255. baseimg = driver->createImage(video::ECF_A8R8G8B8, v2u32(16,16));
  1256. video::IImage *img = generateImage(filename);
  1257. if (img)
  1258. {
  1259. core::dimension2d<u32> dim = img->getDimension();
  1260. core::position2d<s32> pos_base(0, 0);
  1261. video::IImage *img2 =
  1262. driver->createImage(video::ECF_A8R8G8B8, dim);
  1263. img->copyTo(img2);
  1264. img->drop();
  1265. core::position2d<s32> clippos(0, 0);
  1266. clippos.Y = dim.Height * (100-percent) / 100;
  1267. core::dimension2d<u32> clipdim = dim;
  1268. clipdim.Height = clipdim.Height * percent / 100 + 1;
  1269. core::rect<s32> cliprect(clippos, clipdim);
  1270. img2->copyToWithAlpha(baseimg, pos_base,
  1271. core::rect<s32>(v2s32(0,0), dim),
  1272. video::SColor(255,255,255,255),
  1273. &cliprect);
  1274. img2->drop();
  1275. }
  1276. }
  1277. /*
  1278. [verticalframe:N:I
  1279. Crops a frame of a vertical animation.
  1280. N = frame count, I = frame index
  1281. */
  1282. else if (str_starts_with(part_of_name, "[verticalframe:"))
  1283. {
  1284. Strfnd sf(part_of_name);
  1285. sf.next(":");
  1286. u32 frame_count = stoi(sf.next(":"));
  1287. u32 frame_index = stoi(sf.next(":"));
  1288. if (baseimg == NULL){
  1289. errorstream<<"generateImagePart(): baseimg != NULL "
  1290. <<"for part_of_name=\""<<part_of_name
  1291. <<"\", cancelling."<<std::endl;
  1292. return false;
  1293. }
  1294. v2u32 frame_size = baseimg->getDimension();
  1295. frame_size.Y /= frame_count;
  1296. video::IImage *img = driver->createImage(video::ECF_A8R8G8B8,
  1297. frame_size);
  1298. if (!img){
  1299. errorstream<<"generateImagePart(): Could not create image "
  1300. <<"for part_of_name=\""<<part_of_name
  1301. <<"\", cancelling."<<std::endl;
  1302. return false;
  1303. }
  1304. // Fill target image with transparency
  1305. img->fill(video::SColor(0,0,0,0));
  1306. core::dimension2d<u32> dim = frame_size;
  1307. core::position2d<s32> pos_dst(0, 0);
  1308. core::position2d<s32> pos_src(0, frame_index * frame_size.Y);
  1309. baseimg->copyToWithAlpha(img, pos_dst,
  1310. core::rect<s32>(pos_src, dim),
  1311. video::SColor(255,255,255,255),
  1312. NULL);
  1313. // Replace baseimg
  1314. baseimg->drop();
  1315. baseimg = img;
  1316. }
  1317. /*
  1318. [mask:filename
  1319. Applies a mask to an image
  1320. */
  1321. else if (str_starts_with(part_of_name, "[mask:"))
  1322. {
  1323. if (baseimg == NULL) {
  1324. errorstream << "generateImage(): baseimg == NULL "
  1325. << "for part_of_name=\"" << part_of_name
  1326. << "\", cancelling." << std::endl;
  1327. return false;
  1328. }
  1329. Strfnd sf(part_of_name);
  1330. sf.next(":");
  1331. std::string filename = unescape_string(sf.next_esc(":", escape), escape);
  1332. video::IImage *img = generateImage(filename);
  1333. if (img) {
  1334. apply_mask(img, baseimg, v2s32(0, 0), v2s32(0, 0),
  1335. img->getDimension());
  1336. img->drop();
  1337. } else {
  1338. errorstream << "generateImage(): Failed to load \""
  1339. << filename << "\".";
  1340. }
  1341. }
  1342. /*
  1343. [multiply:color
  1344. multiplys a given color to any pixel of an image
  1345. color = color as ColorString
  1346. */
  1347. else if (str_starts_with(part_of_name, "[multiply:")) {
  1348. Strfnd sf(part_of_name);
  1349. sf.next(":");
  1350. std::string color_str = sf.next(":");
  1351. if (baseimg == NULL) {
  1352. errorstream << "generateImagePart(): baseimg != NULL "
  1353. << "for part_of_name=\"" << part_of_name
  1354. << "\", cancelling." << std::endl;
  1355. return false;
  1356. }
  1357. video::SColor color;
  1358. if (!parseColorString(color_str, color, false))
  1359. return false;
  1360. apply_multiplication(baseimg, v2u32(0, 0), baseimg->getDimension(), color);
  1361. }
  1362. /*
  1363. [colorize:color
  1364. Overlays image with given color
  1365. color = color as ColorString
  1366. */
  1367. else if (str_starts_with(part_of_name, "[colorize:"))
  1368. {
  1369. Strfnd sf(part_of_name);
  1370. sf.next(":");
  1371. std::string color_str = sf.next(":");
  1372. std::string ratio_str = sf.next(":");
  1373. if (baseimg == NULL) {
  1374. errorstream << "generateImagePart(): baseimg != NULL "
  1375. << "for part_of_name=\"" << part_of_name
  1376. << "\", cancelling." << std::endl;
  1377. return false;
  1378. }
  1379. video::SColor color;
  1380. int ratio = -1;
  1381. bool keep_alpha = false;
  1382. if (!parseColorString(color_str, color, false))
  1383. return false;
  1384. if (is_number(ratio_str))
  1385. ratio = mystoi(ratio_str, 0, 255);
  1386. else if (ratio_str == "alpha")
  1387. keep_alpha = true;
  1388. apply_colorize(baseimg, v2u32(0, 0), baseimg->getDimension(), color, ratio, keep_alpha);
  1389. }
  1390. /*
  1391. [applyfiltersformesh
  1392. Internal modifier
  1393. */
  1394. else if (str_starts_with(part_of_name, "[applyfiltersformesh"))
  1395. {
  1396. /* IMPORTANT: When changing this, getTextureForMesh() needs to be
  1397. * updated too. */
  1398. if (!baseimg) {
  1399. errorstream << "generateImagePart(): baseimg == NULL "
  1400. << "for part_of_name=\"" << part_of_name
  1401. << "\", cancelling." << std::endl;
  1402. return false;
  1403. }
  1404. // Apply the "clean transparent" filter, if needed
  1405. if (m_setting_mipmap || g_settings->getBool("texture_clean_transparent"))
  1406. imageCleanTransparent(baseimg, 127);
  1407. /* Upscale textures to user's requested minimum size. This is a trick to make
  1408. * filters look as good on low-res textures as on high-res ones, by making
  1409. * low-res textures BECOME high-res ones. This is helpful for worlds that
  1410. * mix high- and low-res textures, or for mods with least-common-denominator
  1411. * textures that don't have the resources to offer high-res alternatives.
  1412. */
  1413. const bool filter = m_setting_trilinear_filter || m_setting_bilinear_filter;
  1414. const s32 scaleto = filter ? g_settings->getU16("texture_min_size") : 1;
  1415. if (scaleto > 1) {
  1416. const core::dimension2d<u32> dim = baseimg->getDimension();
  1417. /* Calculate scaling needed to make the shortest texture dimension
  1418. * equal to the target minimum. If e.g. this is a vertical frames
  1419. * animation, the short dimension will be the real size.
  1420. */
  1421. if ((dim.Width == 0) || (dim.Height == 0)) {
  1422. errorstream << "generateImagePart(): Illegal 0 dimension "
  1423. << "for part_of_name=\""<< part_of_name
  1424. << "\", cancelling." << std::endl;
  1425. return false;
  1426. }
  1427. u32 xscale = scaleto / dim.Width;
  1428. u32 yscale = scaleto / dim.Height;
  1429. u32 scale = (xscale > yscale) ? xscale : yscale;
  1430. // Never downscale; only scale up by 2x or more.
  1431. if (scale > 1) {
  1432. u32 w = scale * dim.Width;
  1433. u32 h = scale * dim.Height;
  1434. const core::dimension2d<u32> newdim = core::dimension2d<u32>(w, h);
  1435. video::IImage *newimg = driver->createImage(
  1436. baseimg->getColorFormat(), newdim);
  1437. baseimg->copyToScaling(newimg);
  1438. baseimg->drop();
  1439. baseimg = newimg;
  1440. }
  1441. }
  1442. }
  1443. /*
  1444. [resize:WxH
  1445. Resizes the base image to the given dimensions
  1446. */
  1447. else if (str_starts_with(part_of_name, "[resize"))
  1448. {
  1449. if (baseimg == NULL) {
  1450. errorstream << "generateImagePart(): baseimg == NULL "
  1451. << "for part_of_name=\""<< part_of_name
  1452. << "\", cancelling." << std::endl;
  1453. return false;
  1454. }
  1455. Strfnd sf(part_of_name);
  1456. sf.next(":");
  1457. u32 width = stoi(sf.next("x"));
  1458. u32 height = stoi(sf.next(""));
  1459. core::dimension2d<u32> dim(width, height);
  1460. video::IImage *image = RenderingEngine::get_video_driver()->
  1461. createImage(video::ECF_A8R8G8B8, dim);
  1462. baseimg->copyToScaling(image);
  1463. baseimg->drop();
  1464. baseimg = image;
  1465. }
  1466. /*
  1467. [opacity:R
  1468. Makes the base image transparent according to the given ratio.
  1469. R must be between 0 and 255.
  1470. 0 means totally transparent.
  1471. 255 means totally opaque.
  1472. */
  1473. else if (str_starts_with(part_of_name, "[opacity:")) {
  1474. if (baseimg == NULL) {
  1475. errorstream << "generateImagePart(): baseimg == NULL "
  1476. << "for part_of_name=\"" << part_of_name
  1477. << "\", cancelling." << std::endl;
  1478. return false;
  1479. }
  1480. Strfnd sf(part_of_name);
  1481. sf.next(":");
  1482. u32 ratio = mystoi(sf.next(""), 0, 255);
  1483. core::dimension2d<u32> dim = baseimg->getDimension();
  1484. for (u32 y = 0; y < dim.Height; y++)
  1485. for (u32 x = 0; x < dim.Width; x++)
  1486. {
  1487. video::SColor c = baseimg->getPixel(x, y);
  1488. c.setAlpha(floor((c.getAlpha() * ratio) / 255 + 0.5));
  1489. baseimg->setPixel(x, y, c);
  1490. }
  1491. }
  1492. /*
  1493. [invert:mode
  1494. Inverts the given channels of the base image.
  1495. Mode may contain the characters "r", "g", "b", "a".
  1496. Only the channels that are mentioned in the mode string
  1497. will be inverted.
  1498. */
  1499. else if (str_starts_with(part_of_name, "[invert:")) {
  1500. if (baseimg == NULL) {
  1501. errorstream << "generateImagePart(): baseimg == NULL "
  1502. << "for part_of_name=\"" << part_of_name
  1503. << "\", cancelling." << std::endl;
  1504. return false;
  1505. }
  1506. Strfnd sf(part_of_name);
  1507. sf.next(":");
  1508. std::string mode = sf.next("");
  1509. u32 mask = 0;
  1510. if (mode.find('a') != std::string::npos)
  1511. mask |= 0xff000000UL;
  1512. if (mode.find('r') != std::string::npos)
  1513. mask |= 0x00ff0000UL;
  1514. if (mode.find('g') != std::string::npos)
  1515. mask |= 0x0000ff00UL;
  1516. if (mode.find('b') != std::string::npos)
  1517. mask |= 0x000000ffUL;
  1518. core::dimension2d<u32> dim = baseimg->getDimension();
  1519. for (u32 y = 0; y < dim.Height; y++)
  1520. for (u32 x = 0; x < dim.Width; x++)
  1521. {
  1522. video::SColor c = baseimg->getPixel(x, y);
  1523. c.color ^= mask;
  1524. baseimg->setPixel(x, y, c);
  1525. }
  1526. }
  1527. /*
  1528. [sheet:WxH:X,Y
  1529. Retrieves a tile at position X,Y (in tiles)
  1530. from the base image it assumes to be a
  1531. tilesheet with dimensions W,H (in tiles).
  1532. */
  1533. else if (part_of_name.substr(0,7) == "[sheet:") {
  1534. if (baseimg == NULL) {
  1535. errorstream << "generateImagePart(): baseimg != NULL "
  1536. << "for part_of_name=\"" << part_of_name
  1537. << "\", cancelling." << std::endl;
  1538. return false;
  1539. }
  1540. Strfnd sf(part_of_name);
  1541. sf.next(":");
  1542. u32 w0 = stoi(sf.next("x"));
  1543. u32 h0 = stoi(sf.next(":"));
  1544. u32 x0 = stoi(sf.next(","));
  1545. u32 y0 = stoi(sf.next(":"));
  1546. core::dimension2d<u32> img_dim = baseimg->getDimension();
  1547. core::dimension2d<u32> tile_dim(v2u32(img_dim) / v2u32(w0, h0));
  1548. video::IImage *img = driver->createImage(
  1549. video::ECF_A8R8G8B8, tile_dim);
  1550. if (!img) {
  1551. errorstream << "generateImagePart(): Could not create image "
  1552. << "for part_of_name=\"" << part_of_name
  1553. << "\", cancelling." << std::endl;
  1554. return false;
  1555. }
  1556. img->fill(video::SColor(0,0,0,0));
  1557. v2u32 vdim(tile_dim);
  1558. core::rect<s32> rect(v2s32(x0 * vdim.X, y0 * vdim.Y), tile_dim);
  1559. baseimg->copyToWithAlpha(img, v2s32(0), rect,
  1560. video::SColor(255,255,255,255), NULL);
  1561. // Replace baseimg
  1562. baseimg->drop();
  1563. baseimg = img;
  1564. }
  1565. /*
  1566. [png:base64
  1567. Decodes a PNG image in base64 form.
  1568. Use minetest.encode_png and minetest.encode_base64
  1569. to produce a valid string.
  1570. */
  1571. else if (str_starts_with(part_of_name, "[png:")) {
  1572. Strfnd sf(part_of_name);
  1573. sf.next(":");
  1574. std::string png;
  1575. {
  1576. std::string blob = sf.next("");
  1577. if (!base64_is_valid(blob)) {
  1578. errorstream << "generateImagePart(): "
  1579. << "malformed base64 in '[png'"
  1580. << std::endl;
  1581. return false;
  1582. }
  1583. png = base64_decode(blob);
  1584. }
  1585. auto *device = RenderingEngine::get_raw_device();
  1586. auto *fs = device->getFileSystem();
  1587. auto *vd = device->getVideoDriver();
  1588. auto *memfile = fs->createMemoryReadFile(png.data(), png.size(), "__temp_png");
  1589. video::IImage* pngimg = vd->createImageFromFile(memfile);
  1590. memfile->drop();
  1591. if (baseimg) {
  1592. blitBaseImage(pngimg, baseimg);
  1593. } else {
  1594. core::dimension2d<u32> dim = pngimg->getDimension();
  1595. baseimg = driver->createImage(video::ECF_A8R8G8B8, dim);
  1596. pngimg->copyTo(baseimg);
  1597. }
  1598. pngimg->drop();
  1599. }
  1600. else
  1601. {
  1602. errorstream << "generateImagePart(): Invalid "
  1603. " modification: \"" << part_of_name << "\"" << std::endl;
  1604. }
  1605. }
  1606. return true;
  1607. }
  1608. /*
  1609. Calculate the color of a single pixel drawn on top of another pixel.
  1610. This is a little more complicated than just video::SColor::getInterpolated
  1611. because getInterpolated does not handle alpha correctly. For example, a
  1612. pixel with alpha=64 drawn atop a pixel with alpha=128 should yield a
  1613. pixel with alpha=160, while getInterpolated would yield alpha=96.
  1614. */
  1615. static inline video::SColor blitPixel(const video::SColor &src_c, const video::SColor &dst_c, u32 ratio)
  1616. {
  1617. if (dst_c.getAlpha() == 0)
  1618. return src_c;
  1619. video::SColor out_c = src_c.getInterpolated(dst_c, (float)ratio / 255.0f);
  1620. out_c.setAlpha(dst_c.getAlpha() + (255 - dst_c.getAlpha()) *
  1621. src_c.getAlpha() * ratio / (255 * 255));
  1622. return out_c;
  1623. }
  1624. /*
  1625. Draw an image on top of an another one, using the alpha channel of the
  1626. source image
  1627. This exists because IImage::copyToWithAlpha() doesn't seem to always
  1628. work.
  1629. */
  1630. static void blit_with_alpha(video::IImage *src, video::IImage *dst,
  1631. v2s32 src_pos, v2s32 dst_pos, v2u32 size)
  1632. {
  1633. for (u32 y0=0; y0<size.Y; y0++)
  1634. for (u32 x0=0; x0<size.X; x0++)
  1635. {
  1636. s32 src_x = src_pos.X + x0;
  1637. s32 src_y = src_pos.Y + y0;
  1638. s32 dst_x = dst_pos.X + x0;
  1639. s32 dst_y = dst_pos.Y + y0;
  1640. video::SColor src_c = src->getPixel(src_x, src_y);
  1641. video::SColor dst_c = dst->getPixel(dst_x, dst_y);
  1642. dst_c = blitPixel(src_c, dst_c, src_c.getAlpha());
  1643. dst->setPixel(dst_x, dst_y, dst_c);
  1644. }
  1645. }
  1646. /*
  1647. Draw an image on top of an another one, using the alpha channel of the
  1648. source image; only modify fully opaque pixels in destinaion
  1649. */
  1650. static void blit_with_alpha_overlay(video::IImage *src, video::IImage *dst,
  1651. v2s32 src_pos, v2s32 dst_pos, v2u32 size)
  1652. {
  1653. for (u32 y0=0; y0<size.Y; y0++)
  1654. for (u32 x0=0; x0<size.X; x0++)
  1655. {
  1656. s32 src_x = src_pos.X + x0;
  1657. s32 src_y = src_pos.Y + y0;
  1658. s32 dst_x = dst_pos.X + x0;
  1659. s32 dst_y = dst_pos.Y + y0;
  1660. video::SColor src_c = src->getPixel(src_x, src_y);
  1661. video::SColor dst_c = dst->getPixel(dst_x, dst_y);
  1662. if (dst_c.getAlpha() == 255 && src_c.getAlpha() != 0)
  1663. {
  1664. dst_c = blitPixel(src_c, dst_c, src_c.getAlpha());
  1665. dst->setPixel(dst_x, dst_y, dst_c);
  1666. }
  1667. }
  1668. }
  1669. // This function has been disabled because it is currently unused.
  1670. // Feel free to re-enable if you find it handy.
  1671. #if 0
  1672. /*
  1673. Draw an image on top of an another one, using the specified ratio
  1674. modify all partially-opaque pixels in the destination.
  1675. */
  1676. static void blit_with_interpolate_overlay(video::IImage *src, video::IImage *dst,
  1677. v2s32 src_pos, v2s32 dst_pos, v2u32 size, int ratio)
  1678. {
  1679. for (u32 y0 = 0; y0 < size.Y; y0++)
  1680. for (u32 x0 = 0; x0 < size.X; x0++)
  1681. {
  1682. s32 src_x = src_pos.X + x0;
  1683. s32 src_y = src_pos.Y + y0;
  1684. s32 dst_x = dst_pos.X + x0;
  1685. s32 dst_y = dst_pos.Y + y0;
  1686. video::SColor src_c = src->getPixel(src_x, src_y);
  1687. video::SColor dst_c = dst->getPixel(dst_x, dst_y);
  1688. if (dst_c.getAlpha() > 0 && src_c.getAlpha() != 0)
  1689. {
  1690. if (ratio == -1)
  1691. dst_c = src_c.getInterpolated(dst_c, (float)src_c.getAlpha()/255.0f);
  1692. else
  1693. dst_c = src_c.getInterpolated(dst_c, (float)ratio/255.0f);
  1694. dst->setPixel(dst_x, dst_y, dst_c);
  1695. }
  1696. }
  1697. }
  1698. #endif
  1699. /*
  1700. Apply color to destination
  1701. */
  1702. static void apply_colorize(video::IImage *dst, v2u32 dst_pos, v2u32 size,
  1703. const video::SColor &color, int ratio, bool keep_alpha)
  1704. {
  1705. u32 alpha = color.getAlpha();
  1706. video::SColor dst_c;
  1707. if ((ratio == -1 && alpha == 255) || ratio == 255) { // full replacement of color
  1708. if (keep_alpha) { // replace the color with alpha = dest alpha * color alpha
  1709. dst_c = color;
  1710. for (u32 y = dst_pos.Y; y < dst_pos.Y + size.Y; y++)
  1711. for (u32 x = dst_pos.X; x < dst_pos.X + size.X; x++) {
  1712. u32 dst_alpha = dst->getPixel(x, y).getAlpha();
  1713. if (dst_alpha > 0) {
  1714. dst_c.setAlpha(dst_alpha * alpha / 255);
  1715. dst->setPixel(x, y, dst_c);
  1716. }
  1717. }
  1718. } else { // replace the color including the alpha
  1719. for (u32 y = dst_pos.Y; y < dst_pos.Y + size.Y; y++)
  1720. for (u32 x = dst_pos.X; x < dst_pos.X + size.X; x++)
  1721. if (dst->getPixel(x, y).getAlpha() > 0)
  1722. dst->setPixel(x, y, color);
  1723. }
  1724. } else { // interpolate between the color and destination
  1725. float interp = (ratio == -1 ? color.getAlpha() / 255.0f : ratio / 255.0f);
  1726. for (u32 y = dst_pos.Y; y < dst_pos.Y + size.Y; y++)
  1727. for (u32 x = dst_pos.X; x < dst_pos.X + size.X; x++) {
  1728. dst_c = dst->getPixel(x, y);
  1729. if (dst_c.getAlpha() > 0) {
  1730. dst_c = color.getInterpolated(dst_c, interp);
  1731. dst->setPixel(x, y, dst_c);
  1732. }
  1733. }
  1734. }
  1735. }
  1736. /*
  1737. Apply color to destination
  1738. */
  1739. static void apply_multiplication(video::IImage *dst, v2u32 dst_pos, v2u32 size,
  1740. const video::SColor &color)
  1741. {
  1742. video::SColor dst_c;
  1743. for (u32 y = dst_pos.Y; y < dst_pos.Y + size.Y; y++)
  1744. for (u32 x = dst_pos.X; x < dst_pos.X + size.X; x++) {
  1745. dst_c = dst->getPixel(x, y);
  1746. dst_c.set(
  1747. dst_c.getAlpha(),
  1748. (dst_c.getRed() * color.getRed()) / 255,
  1749. (dst_c.getGreen() * color.getGreen()) / 255,
  1750. (dst_c.getBlue() * color.getBlue()) / 255
  1751. );
  1752. dst->setPixel(x, y, dst_c);
  1753. }
  1754. }
  1755. /*
  1756. Apply mask to destination
  1757. */
  1758. static void apply_mask(video::IImage *mask, video::IImage *dst,
  1759. v2s32 mask_pos, v2s32 dst_pos, v2u32 size)
  1760. {
  1761. for (u32 y0 = 0; y0 < size.Y; y0++) {
  1762. for (u32 x0 = 0; x0 < size.X; x0++) {
  1763. s32 mask_x = x0 + mask_pos.X;
  1764. s32 mask_y = y0 + mask_pos.Y;
  1765. s32 dst_x = x0 + dst_pos.X;
  1766. s32 dst_y = y0 + dst_pos.Y;
  1767. video::SColor mask_c = mask->getPixel(mask_x, mask_y);
  1768. video::SColor dst_c = dst->getPixel(dst_x, dst_y);
  1769. dst_c.color &= mask_c.color;
  1770. dst->setPixel(dst_x, dst_y, dst_c);
  1771. }
  1772. }
  1773. }
  1774. video::IImage *create_crack_image(video::IImage *crack, s32 frame_index,
  1775. core::dimension2d<u32> size, u8 tiles, video::IVideoDriver *driver)
  1776. {
  1777. core::dimension2d<u32> strip_size = crack->getDimension();
  1778. core::dimension2d<u32> frame_size(strip_size.Width, strip_size.Width);
  1779. core::dimension2d<u32> tile_size(size / tiles);
  1780. s32 frame_count = strip_size.Height / strip_size.Width;
  1781. if (frame_index >= frame_count)
  1782. frame_index = frame_count - 1;
  1783. core::rect<s32> frame(v2s32(0, frame_index * frame_size.Height), frame_size);
  1784. video::IImage *result = nullptr;
  1785. // extract crack frame
  1786. video::IImage *crack_tile = driver->createImage(video::ECF_A8R8G8B8, tile_size);
  1787. if (!crack_tile)
  1788. return nullptr;
  1789. if (tile_size == frame_size) {
  1790. crack->copyTo(crack_tile, v2s32(0, 0), frame);
  1791. } else {
  1792. video::IImage *crack_frame = driver->createImage(video::ECF_A8R8G8B8, frame_size);
  1793. if (!crack_frame)
  1794. goto exit__has_tile;
  1795. crack->copyTo(crack_frame, v2s32(0, 0), frame);
  1796. crack_frame->copyToScaling(crack_tile);
  1797. crack_frame->drop();
  1798. }
  1799. if (tiles == 1)
  1800. return crack_tile;
  1801. // tile it
  1802. result = driver->createImage(video::ECF_A8R8G8B8, size);
  1803. if (!result)
  1804. goto exit__has_tile;
  1805. result->fill({});
  1806. for (u8 i = 0; i < tiles; i++)
  1807. for (u8 j = 0; j < tiles; j++)
  1808. crack_tile->copyTo(result, v2s32(i * tile_size.Width, j * tile_size.Height));
  1809. exit__has_tile:
  1810. crack_tile->drop();
  1811. return result;
  1812. }
  1813. static void draw_crack(video::IImage *crack, video::IImage *dst,
  1814. bool use_overlay, s32 frame_count, s32 progression,
  1815. video::IVideoDriver *driver, u8 tiles)
  1816. {
  1817. // Dimension of destination image
  1818. core::dimension2d<u32> dim_dst = dst->getDimension();
  1819. // Limit frame_count
  1820. if (frame_count > (s32) dim_dst.Height)
  1821. frame_count = dim_dst.Height;
  1822. if (frame_count < 1)
  1823. frame_count = 1;
  1824. // Dimension of the scaled crack stage,
  1825. // which is the same as the dimension of a single destination frame
  1826. core::dimension2d<u32> frame_size(
  1827. dim_dst.Width,
  1828. dim_dst.Height / frame_count
  1829. );
  1830. video::IImage *crack_scaled = create_crack_image(crack, progression,
  1831. frame_size, tiles, driver);
  1832. if (!crack_scaled)
  1833. return;
  1834. auto blit = use_overlay ? blit_with_alpha_overlay : blit_with_alpha;
  1835. for (s32 i = 0; i < frame_count; ++i) {
  1836. v2s32 dst_pos(0, frame_size.Height * i);
  1837. blit(crack_scaled, dst, v2s32(0,0), dst_pos, frame_size);
  1838. }
  1839. crack_scaled->drop();
  1840. }
  1841. void brighten(video::IImage *image)
  1842. {
  1843. if (image == NULL)
  1844. return;
  1845. core::dimension2d<u32> dim = image->getDimension();
  1846. for (u32 y=0; y<dim.Height; y++)
  1847. for (u32 x=0; x<dim.Width; x++)
  1848. {
  1849. video::SColor c = image->getPixel(x,y);
  1850. c.setRed(0.5 * 255 + 0.5 * (float)c.getRed());
  1851. c.setGreen(0.5 * 255 + 0.5 * (float)c.getGreen());
  1852. c.setBlue(0.5 * 255 + 0.5 * (float)c.getBlue());
  1853. image->setPixel(x,y,c);
  1854. }
  1855. }
  1856. u32 parseImageTransform(const std::string& s)
  1857. {
  1858. int total_transform = 0;
  1859. std::string transform_names[8];
  1860. transform_names[0] = "i";
  1861. transform_names[1] = "r90";
  1862. transform_names[2] = "r180";
  1863. transform_names[3] = "r270";
  1864. transform_names[4] = "fx";
  1865. transform_names[6] = "fy";
  1866. std::size_t pos = 0;
  1867. while(pos < s.size())
  1868. {
  1869. int transform = -1;
  1870. for (int i = 0; i <= 7; ++i)
  1871. {
  1872. const std::string &name_i = transform_names[i];
  1873. if (s[pos] == ('0' + i))
  1874. {
  1875. transform = i;
  1876. pos++;
  1877. break;
  1878. }
  1879. if (!(name_i.empty()) && lowercase(s.substr(pos, name_i.size())) == name_i) {
  1880. transform = i;
  1881. pos += name_i.size();
  1882. break;
  1883. }
  1884. }
  1885. if (transform < 0)
  1886. break;
  1887. // Multiply total_transform and transform in the group D4
  1888. int new_total = 0;
  1889. if (transform < 4)
  1890. new_total = (transform + total_transform) % 4;
  1891. else
  1892. new_total = (transform - total_transform + 8) % 4;
  1893. if ((transform >= 4) ^ (total_transform >= 4))
  1894. new_total += 4;
  1895. total_transform = new_total;
  1896. }
  1897. return total_transform;
  1898. }
  1899. core::dimension2d<u32> imageTransformDimension(u32 transform, core::dimension2d<u32> dim)
  1900. {
  1901. if (transform % 2 == 0)
  1902. return dim;
  1903. return core::dimension2d<u32>(dim.Height, dim.Width);
  1904. }
  1905. void imageTransform(u32 transform, video::IImage *src, video::IImage *dst)
  1906. {
  1907. if (src == NULL || dst == NULL)
  1908. return;
  1909. core::dimension2d<u32> dstdim = dst->getDimension();
  1910. // Pre-conditions
  1911. assert(dstdim == imageTransformDimension(transform, src->getDimension()));
  1912. assert(transform <= 7);
  1913. /*
  1914. Compute the transformation from source coordinates (sx,sy)
  1915. to destination coordinates (dx,dy).
  1916. */
  1917. int sxn = 0;
  1918. int syn = 2;
  1919. if (transform == 0) // identity
  1920. sxn = 0, syn = 2; // sx = dx, sy = dy
  1921. else if (transform == 1) // rotate by 90 degrees ccw
  1922. sxn = 3, syn = 0; // sx = (H-1) - dy, sy = dx
  1923. else if (transform == 2) // rotate by 180 degrees
  1924. sxn = 1, syn = 3; // sx = (W-1) - dx, sy = (H-1) - dy
  1925. else if (transform == 3) // rotate by 270 degrees ccw
  1926. sxn = 2, syn = 1; // sx = dy, sy = (W-1) - dx
  1927. else if (transform == 4) // flip x
  1928. sxn = 1, syn = 2; // sx = (W-1) - dx, sy = dy
  1929. else if (transform == 5) // flip x then rotate by 90 degrees ccw
  1930. sxn = 2, syn = 0; // sx = dy, sy = dx
  1931. else if (transform == 6) // flip y
  1932. sxn = 0, syn = 3; // sx = dx, sy = (H-1) - dy
  1933. else if (transform == 7) // flip y then rotate by 90 degrees ccw
  1934. sxn = 3, syn = 1; // sx = (H-1) - dy, sy = (W-1) - dx
  1935. for (u32 dy=0; dy<dstdim.Height; dy++)
  1936. for (u32 dx=0; dx<dstdim.Width; dx++)
  1937. {
  1938. u32 entries[4] = {dx, dstdim.Width-1-dx, dy, dstdim.Height-1-dy};
  1939. u32 sx = entries[sxn];
  1940. u32 sy = entries[syn];
  1941. video::SColor c = src->getPixel(sx,sy);
  1942. dst->setPixel(dx,dy,c);
  1943. }
  1944. }
  1945. video::ITexture* TextureSource::getNormalTexture(const std::string &name)
  1946. {
  1947. if (isKnownSourceImage("override_normal.png"))
  1948. return getTexture("override_normal.png");
  1949. std::string fname_base = name;
  1950. static const char *normal_ext = "_normal.png";
  1951. static const u32 normal_ext_size = strlen(normal_ext);
  1952. size_t pos = fname_base.find('.');
  1953. std::string fname_normal = fname_base.substr(0, pos) + normal_ext;
  1954. if (isKnownSourceImage(fname_normal)) {
  1955. // look for image extension and replace it
  1956. size_t i = 0;
  1957. while ((i = fname_base.find('.', i)) != std::string::npos) {
  1958. fname_base.replace(i, 4, normal_ext);
  1959. i += normal_ext_size;
  1960. }
  1961. return getTexture(fname_base);
  1962. }
  1963. return NULL;
  1964. }
  1965. namespace {
  1966. // For more colourspace transformations, see for example
  1967. // https://github.com/tobspr/GLSL-Color-Spaces/blob/master/ColorSpaces.inc.glsl
  1968. inline float linear_to_srgb_component(float v)
  1969. {
  1970. if (v > 0.0031308f)
  1971. return 1.055f * powf(v, 1.0f / 2.4f) - 0.055f;
  1972. return 12.92f * v;
  1973. }
  1974. inline float srgb_to_linear_component(float v)
  1975. {
  1976. if (v > 0.04045f)
  1977. return powf((v + 0.055f) / 1.055f, 2.4f);
  1978. return v / 12.92f;
  1979. }
  1980. v3f srgb_to_linear(const video::SColor &col_srgb)
  1981. {
  1982. v3f col(col_srgb.getRed(), col_srgb.getGreen(), col_srgb.getBlue());
  1983. col /= 255.0f;
  1984. col.X = srgb_to_linear_component(col.X);
  1985. col.Y = srgb_to_linear_component(col.Y);
  1986. col.Z = srgb_to_linear_component(col.Z);
  1987. return col;
  1988. }
  1989. video::SColor linear_to_srgb(const v3f &col_linear)
  1990. {
  1991. v3f col;
  1992. col.X = linear_to_srgb_component(col_linear.X);
  1993. col.Y = linear_to_srgb_component(col_linear.Y);
  1994. col.Z = linear_to_srgb_component(col_linear.Z);
  1995. col *= 255.0f;
  1996. col.X = core::clamp<float>(col.X, 0.0f, 255.0f);
  1997. col.Y = core::clamp<float>(col.Y, 0.0f, 255.0f);
  1998. col.Z = core::clamp<float>(col.Z, 0.0f, 255.0f);
  1999. return video::SColor(0xff, myround(col.X), myround(col.Y),
  2000. myround(col.Z));
  2001. }
  2002. }
  2003. video::SColor TextureSource::getTextureAverageColor(const std::string &name)
  2004. {
  2005. video::IVideoDriver *driver = RenderingEngine::get_video_driver();
  2006. video::SColor c(0, 0, 0, 0);
  2007. video::ITexture *texture = getTexture(name);
  2008. if (!texture)
  2009. return c;
  2010. video::IImage *image = driver->createImage(texture,
  2011. core::position2d<s32>(0, 0),
  2012. texture->getOriginalSize());
  2013. if (!image)
  2014. return c;
  2015. u32 total = 0;
  2016. v3f col_acc(0, 0, 0);
  2017. core::dimension2d<u32> dim = image->getDimension();
  2018. u16 step = 1;
  2019. if (dim.Width > 16)
  2020. step = dim.Width / 16;
  2021. for (u16 x = 0; x < dim.Width; x += step) {
  2022. for (u16 y = 0; y < dim.Width; y += step) {
  2023. c = image->getPixel(x,y);
  2024. if (c.getAlpha() > 0) {
  2025. total++;
  2026. col_acc += srgb_to_linear(c);
  2027. }
  2028. }
  2029. }
  2030. image->drop();
  2031. if (total > 0) {
  2032. col_acc /= total;
  2033. c = linear_to_srgb(col_acc);
  2034. }
  2035. c.setAlpha(255);
  2036. return c;
  2037. }
  2038. video::ITexture *TextureSource::getShaderFlagsTexture(bool normalmap_present)
  2039. {
  2040. std::string tname = "__shaderFlagsTexture";
  2041. tname += normalmap_present ? "1" : "0";
  2042. if (isKnownSourceImage(tname)) {
  2043. return getTexture(tname);
  2044. }
  2045. video::IVideoDriver *driver = RenderingEngine::get_video_driver();
  2046. video::IImage *flags_image = driver->createImage(
  2047. video::ECF_A8R8G8B8, core::dimension2d<u32>(1, 1));
  2048. sanity_check(flags_image != NULL);
  2049. video::SColor c(255, normalmap_present ? 255 : 0, 0, 0);
  2050. flags_image->setPixel(0, 0, c);
  2051. insertSourceImage(tname, flags_image);
  2052. flags_image->drop();
  2053. return getTexture(tname);
  2054. }
  2055. std::vector<std::string> getTextureDirs()
  2056. {
  2057. return fs::GetRecursiveDirs(g_settings->get("texture_path"));
  2058. }