tile.cpp 60 KB

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