gBitmap.cpp 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "gfx/bitmap/gBitmap.h"
  24. #include "core/resourceManager.h"
  25. #include "core/stream/fileStream.h"
  26. #include "core/strings/stringFunctions.h"
  27. #include "core/color.h"
  28. #include "gfx/bitmap/bitmapUtils.h"
  29. #include "math/mRect.h"
  30. #include "console/console.h"
  31. #include "platform/profiler.h"
  32. #include "console/engineAPI.h"
  33. using namespace Torque;
  34. const U32 GBitmap::csFileVersion = 3;
  35. Vector<GBitmap::Registration> GBitmap::sRegistrations( __FILE__, __LINE__ );
  36. GBitmap::GBitmap()
  37. : mInternalFormat(GFXFormatR8G8B8),
  38. mBits(NULL),
  39. mByteSize(0),
  40. mWidth(0),
  41. mHeight(0),
  42. mBytesPerPixel(0),
  43. mNumMipLevels(0),
  44. mHasTransparency(false)
  45. {
  46. for (U32 i = 0; i < c_maxMipLevels; i++)
  47. mMipLevelOffsets[i] = 0xffffffff;
  48. }
  49. GBitmap::GBitmap(const GBitmap& rCopy)
  50. {
  51. mInternalFormat = rCopy.mInternalFormat;
  52. mByteSize = rCopy.mByteSize;
  53. mBits = new U8[mByteSize];
  54. dMemcpy(mBits, rCopy.mBits, mByteSize);
  55. mWidth = rCopy.mWidth;
  56. mHeight = rCopy.mHeight;
  57. mBytesPerPixel = rCopy.mBytesPerPixel;
  58. mNumMipLevels = rCopy.mNumMipLevels;
  59. dMemcpy(mMipLevelOffsets, rCopy.mMipLevelOffsets, sizeof(mMipLevelOffsets));
  60. mHasTransparency = rCopy.mHasTransparency;
  61. }
  62. GBitmap::GBitmap(const U32 in_width,
  63. const U32 in_height,
  64. const bool in_extrudeMipLevels,
  65. const GFXFormat in_format)
  66. : mBits(NULL),
  67. mByteSize(0)
  68. {
  69. for (U32 i = 0; i < c_maxMipLevels; i++)
  70. mMipLevelOffsets[i] = 0xffffffff;
  71. allocateBitmap(in_width, in_height, in_extrudeMipLevels, in_format);
  72. mHasTransparency = false;
  73. }
  74. GBitmap::GBitmap(const U32 in_width,
  75. const U32 in_height,
  76. const U8* data )
  77. : mBits(NULL),
  78. mByteSize(0)
  79. {
  80. allocateBitmap(in_width, in_height, false, GFXFormatR8G8B8A8);
  81. mHasTransparency = false;
  82. for (U32 x = 0; x < in_width; x++)
  83. {
  84. for (U32 y = 0; y < in_height; y++)
  85. {
  86. U32 offset = (x + y * in_width) * 4;
  87. ColorI color(data[offset],
  88. data[offset + 1],
  89. data[offset + 2],
  90. data[offset + 3]);
  91. if (color.alpha < 255)
  92. mHasTransparency = true;
  93. setColor(x, y, color);
  94. }
  95. }
  96. }
  97. //--------------------------------------------------------------------------
  98. GBitmap::~GBitmap()
  99. {
  100. deleteImage();
  101. }
  102. //--------------------------------------------------------------------------
  103. void GBitmap::sRegisterFormat( const GBitmap::Registration &reg )
  104. {
  105. U32 insert = sRegistrations.size();
  106. for ( U32 i = 0; i < sRegistrations.size(); i++ )
  107. {
  108. if ( sRegistrations[i].priority <= reg.priority )
  109. {
  110. insert = i;
  111. break;
  112. }
  113. }
  114. sRegistrations.insert( insert, reg );
  115. }
  116. const GBitmap::Registration *GBitmap::sFindRegInfo( const String &extension )
  117. {
  118. for ( U32 i = 0; i < GBitmap::sRegistrations.size(); i++ )
  119. {
  120. const GBitmap::Registration &reg = GBitmap::sRegistrations[i];
  121. const Vector<String> &extensions = reg.extensions;
  122. for ( U32 j = 0; j < extensions.size(); ++j )
  123. {
  124. if ( extensions[j].equal( extension, String::NoCase ) )
  125. return &reg;
  126. }
  127. }
  128. return NULL;
  129. }
  130. bool GBitmap::sFindFile( const Path &path, Path *outPath )
  131. {
  132. PROFILE_SCOPE( GBitmap_sFindFile );
  133. const String origExt( String::ToLower( path.getExtension() ) );
  134. Path tryPath( path );
  135. for ( U32 i = 0; i < sRegistrations.size(); i++ )
  136. {
  137. const Registration &reg = sRegistrations[i];
  138. const Vector<String> &extensions = reg.extensions;
  139. for ( U32 j = 0; j < extensions.size(); ++j )
  140. {
  141. // We've already tried this one.
  142. if ( extensions[j] == origExt )
  143. continue;
  144. tryPath.setExtension( extensions[j] );
  145. if ( !Torque::FS::IsFile( tryPath ) )
  146. continue;
  147. if ( outPath )
  148. *outPath = tryPath;
  149. return true;
  150. }
  151. }
  152. return false;
  153. }
  154. bool GBitmap::sFindFiles( const Path &path, Vector<Path> *outFoundPaths )
  155. {
  156. PROFILE_SCOPE( GBitmap_sFindFiles );
  157. Path tryPath( path );
  158. for ( U32 i = 0; i < GBitmap::sRegistrations.size(); i++ )
  159. {
  160. const GBitmap::Registration &reg = GBitmap::sRegistrations[i];
  161. const Vector<String> &extensions = reg.extensions;
  162. for ( U32 j = 0; j < extensions.size(); ++j )
  163. {
  164. tryPath.setExtension( extensions[j] );
  165. if ( Torque::FS::IsFile( tryPath ) )
  166. {
  167. if ( outFoundPaths )
  168. outFoundPaths->push_back( tryPath );
  169. else
  170. return true;
  171. }
  172. }
  173. }
  174. return outFoundPaths ? outFoundPaths->size() > 0 : false;
  175. }
  176. String GBitmap::sGetExtensionList()
  177. {
  178. String list;
  179. for ( U32 i = 0; i < sRegistrations.size(); i++ )
  180. {
  181. const Registration &reg = sRegistrations[i];
  182. for ( U32 j = 0; j < reg.extensions.size(); j++ )
  183. {
  184. list += reg.extensions[j];
  185. list += " ";
  186. }
  187. }
  188. return list;
  189. }
  190. //--------------------------------------------------------------------------
  191. void GBitmap::deleteImage()
  192. {
  193. delete [] mBits;
  194. mBits = NULL;
  195. mByteSize = 0;
  196. mWidth = 0;
  197. mHeight = 0;
  198. mNumMipLevels = 0;
  199. }
  200. //--------------------------------------------------------------------------
  201. void GBitmap::copyRect(const GBitmap *src, const RectI &srcRect, const Point2I &dstPt, const U32 srcMipLevel, const U32 dstMipLevel)
  202. {
  203. if(src->getFormat() != getFormat())
  204. return;
  205. if(srcRect.extent.x + srcRect.point.x > src->getWidth(srcMipLevel) || srcRect.extent.y + srcRect.point.y > src->getHeight(srcMipLevel))
  206. return;
  207. if(srcRect.extent.x + dstPt.x > getWidth(dstMipLevel) || srcRect.extent.y + dstPt.y > getHeight(dstMipLevel))
  208. return;
  209. for(U32 i = 0; i < srcRect.extent.y; i++)
  210. {
  211. dMemcpy(getAddress(dstPt.x, dstPt.y + i, dstMipLevel),
  212. src->getAddress(srcRect.point.x, srcRect.point.y + i, srcMipLevel),
  213. mBytesPerPixel * srcRect.extent.x);
  214. }
  215. }
  216. //--------------------------------------------------------------------------
  217. void GBitmap::allocateBitmap(const U32 in_width, const U32 in_height, const bool in_extrudeMipLevels, const GFXFormat in_format )
  218. {
  219. //-------------------------------------- Some debug checks...
  220. U32 svByteSize = mByteSize;
  221. U8 *svBits = mBits;
  222. AssertFatal(in_width != 0 && in_height != 0, "GBitmap::allocateBitmap: width or height is 0");
  223. if (in_extrudeMipLevels == true)
  224. {
  225. AssertFatal(isPow2(in_width) == true && isPow2(in_height) == true, "GBitmap::GBitmap: in order to extrude mip levels, bitmap w/h must be pow2");
  226. }
  227. mInternalFormat = in_format;
  228. mWidth = in_width;
  229. mHeight = in_height;
  230. mBytesPerPixel = 1;
  231. switch (mInternalFormat)
  232. {
  233. case GFXFormatA8:
  234. case GFXFormatL8: mBytesPerPixel = 1;
  235. break;
  236. case GFXFormatR8G8B8: mBytesPerPixel = 3;
  237. break;
  238. case GFXFormatR8G8B8A8_LINEAR_FORCE:
  239. case GFXFormatR8G8B8X8:
  240. case GFXFormatR8G8B8A8: mBytesPerPixel = 4;
  241. break;
  242. case GFXFormatR5G6B5:
  243. case GFXFormatR5G5B5A1: mBytesPerPixel = 2;
  244. break;
  245. default:
  246. AssertFatal(false, "GBitmap::GBitmap: misunderstood format specifier");
  247. break;
  248. }
  249. // Set up the mip levels, if necessary...
  250. mNumMipLevels = 1;
  251. U32 allocPixels = in_width * in_height * mBytesPerPixel;
  252. mMipLevelOffsets[0] = 0;
  253. if (in_extrudeMipLevels == true)
  254. {
  255. U32 currWidth = in_width;
  256. U32 currHeight = in_height;
  257. do
  258. {
  259. mMipLevelOffsets[mNumMipLevels] = mMipLevelOffsets[mNumMipLevels - 1] +
  260. (currWidth * currHeight * mBytesPerPixel);
  261. currWidth >>= 1;
  262. currHeight >>= 1;
  263. if (currWidth == 0) currWidth = 1;
  264. if (currHeight == 0) currHeight = 1;
  265. mNumMipLevels++;
  266. allocPixels += currWidth * currHeight * mBytesPerPixel;
  267. } while (currWidth != 1 && currHeight != 1);
  268. }
  269. AssertFatal(mNumMipLevels <= c_maxMipLevels, "GBitmap::allocateBitmap: too many miplevels");
  270. // Set up the memory...
  271. mByteSize = allocPixels;
  272. mBits = new U8[mByteSize];
  273. dMemset(mBits, 0xFF, mByteSize);
  274. if(svBits != NULL)
  275. {
  276. dMemcpy(mBits, svBits, getMin(mByteSize, svByteSize));
  277. delete[] svBits;
  278. }
  279. }
  280. //--------------------------------------------------------------------------
  281. void GBitmap::extrudeMipLevels(bool clearBorders)
  282. {
  283. if(mNumMipLevels == 1)
  284. allocateBitmap(getWidth(), getHeight(), true, getFormat());
  285. switch (getFormat())
  286. {
  287. case GFXFormatR5G5B5A1:
  288. {
  289. for(U32 i = 1; i < mNumMipLevels; i++)
  290. bitmapExtrude5551(getBits(i - 1), getWritableBits(i), getHeight(i), getWidth(i));
  291. break;
  292. }
  293. case GFXFormatR8G8B8:
  294. {
  295. for(U32 i = 1; i < mNumMipLevels; i++)
  296. bitmapExtrudeRGB(getBits(i - 1), getWritableBits(i), getHeight(i-1), getWidth(i-1));
  297. break;
  298. }
  299. case GFXFormatR8G8B8A8:
  300. case GFXFormatR8G8B8X8:
  301. {
  302. for(U32 i = 1; i < mNumMipLevels; i++)
  303. bitmapExtrudeRGBA(getBits(i - 1), getWritableBits(i), getHeight(i-1), getWidth(i-1));
  304. break;
  305. }
  306. default:
  307. break;
  308. }
  309. if (clearBorders)
  310. {
  311. for (U32 i = 1; i<mNumMipLevels; i++)
  312. {
  313. U32 width = getWidth(i);
  314. U32 height = getHeight(i);
  315. if (height<3 || width<3)
  316. // bmp is all borders at this mip level
  317. dMemset(getWritableBits(i),0,width*height*mBytesPerPixel);
  318. else
  319. {
  320. width *= mBytesPerPixel;
  321. U8 * bytes = getWritableBits(i);
  322. U8 * end = bytes + (height-1)*width - mBytesPerPixel; // end = last row, 2nd column
  323. // clear first row sans the last pixel
  324. dMemset(bytes,0,width-mBytesPerPixel);
  325. bytes -= mBytesPerPixel;
  326. while (bytes<end)
  327. {
  328. // clear last pixel of row N-1 and first pixel of row N
  329. bytes += width;
  330. dMemset(bytes,0,mBytesPerPixel*2);
  331. }
  332. // clear last row sans the first pixel
  333. dMemset(bytes+2*mBytesPerPixel,0,width-mBytesPerPixel);
  334. }
  335. }
  336. }
  337. }
  338. //--------------------------------------------------------------------------
  339. void GBitmap::extrudeMipLevelsDetail()
  340. {
  341. AssertFatal(getFormat() == GFXFormatR8G8B8, "Error, only handles RGB for now...");
  342. U32 i,j;
  343. if(mNumMipLevels == 1)
  344. allocateBitmap(getWidth(), getHeight(), true, getFormat());
  345. for (i = 1; i < mNumMipLevels; i++) {
  346. bitmapExtrudeRGB(getBits(i - 1), getWritableBits(i), getHeight(i-1), getWidth(i-1));
  347. }
  348. // Ok, now that we have the levels extruded, we need to move the lower miplevels
  349. // closer to 0.5.
  350. for (i = 1; i < mNumMipLevels - 1; i++) {
  351. U8* pMipBits = (U8*)getWritableBits(i);
  352. U32 numBytes = getWidth(i) * getHeight(i) * 3;
  353. U32 shift = i;
  354. U32 start = ((1 << i) - 1) * 0x80;
  355. for (j = 0; j < numBytes; j++) {
  356. U32 newVal = (start + pMipBits[j]) >> shift;
  357. AssertFatal(newVal <= 255, "Error, oob");
  358. pMipBits[j] = U8(newVal);
  359. }
  360. }
  361. AssertFatal(getWidth(mNumMipLevels - 1) == 1 && getHeight(mNumMipLevels - 1) == 1,
  362. "Error, last miplevel should be 1x1!");
  363. ((U8*)getWritableBits(mNumMipLevels - 1))[0] = 0x80;
  364. ((U8*)getWritableBits(mNumMipLevels - 1))[1] = 0x80;
  365. ((U8*)getWritableBits(mNumMipLevels - 1))[2] = 0x80;
  366. }
  367. //--------------------------------------------------------------------------
  368. bool GBitmap::setFormat(GFXFormat fmt)
  369. {
  370. if (getFormat() == fmt)
  371. return true;
  372. PROFILE_SCOPE(GBitmap_setFormat);
  373. // this is a nasty pointer math hack
  374. // is there a quick way to calc pixels of a fully mipped bitmap?
  375. U32 pixels = 0;
  376. for (U32 i=0; i < mNumMipLevels; i++)
  377. pixels += getHeight(i) * getWidth(i);
  378. switch( getFormat() )
  379. {
  380. case GFXFormatR8G8B8:
  381. switch ( fmt )
  382. {
  383. case GFXFormatR5G5B5A1:
  384. #ifdef _XBOX
  385. bitmapConvertRGB_to_1555(mBits, pixels);
  386. #else
  387. bitmapConvertRGB_to_5551(mBits, pixels);
  388. #endif
  389. mInternalFormat = GFXFormatR5G5B5A1;
  390. mBytesPerPixel = 2;
  391. break;
  392. case GFXFormatR8G8B8A8:
  393. case GFXFormatR8G8B8X8:
  394. // Took this out, it may crash -patw
  395. //AssertFatal( mNumMipLevels == 1, "Do the mip-mapping in hardware." );
  396. bitmapConvertRGB_to_RGBX( &mBits, pixels );
  397. mInternalFormat = fmt;
  398. mBytesPerPixel = 4;
  399. mByteSize = pixels * 4;
  400. break;
  401. default:
  402. AssertWarn(0, "GBitmap::setFormat: unable to convert bitmap to requested format.");
  403. return false;
  404. }
  405. break;
  406. case GFXFormatR8G8B8X8:
  407. switch( fmt )
  408. {
  409. // No change needed for this
  410. case GFXFormatR8G8B8A8:
  411. mInternalFormat = GFXFormatR8G8B8A8;
  412. break;
  413. case GFXFormatR8G8B8:
  414. bitmapConvertRGBX_to_RGB( &mBits, pixels );
  415. mInternalFormat = GFXFormatR8G8B8;
  416. mBytesPerPixel = 3;
  417. mByteSize = pixels * 3;
  418. break;
  419. default:
  420. AssertWarn(0, "GBitmap::setFormat: unable to convert bitmap to requested format.");
  421. return false;
  422. }
  423. break;
  424. case GFXFormatR8G8B8A8:
  425. switch( fmt )
  426. {
  427. // No change needed for this
  428. case GFXFormatR8G8B8X8:
  429. mInternalFormat = GFXFormatR8G8B8X8;
  430. break;
  431. case GFXFormatR8G8B8:
  432. bitmapConvertRGBX_to_RGB( &mBits, pixels );
  433. mInternalFormat = GFXFormatR8G8B8;
  434. mBytesPerPixel = 3;
  435. mByteSize = pixels * 3;
  436. break;
  437. default:
  438. AssertWarn(0, "GBitmap::setFormat: unable to convert bitmap to requested format.");
  439. return false;
  440. }
  441. break;
  442. case GFXFormatA8:
  443. switch( fmt )
  444. {
  445. case GFXFormatR8G8B8A8:
  446. mInternalFormat = GFXFormatR8G8B8A8;
  447. bitmapConvertA8_to_RGBA( &mBits, pixels );
  448. mBytesPerPixel = 4;
  449. mByteSize = pixels * 4;
  450. break;
  451. default:
  452. AssertWarn(0, "GBitmap::setFormat: unable to convert bitmap to requested format.");
  453. return false;
  454. }
  455. break;
  456. default:
  457. AssertWarn(0, "GBitmap::setFormat: unable to convert bitmap to requested format.");
  458. return false;
  459. }
  460. U32 offset = 0;
  461. for (U32 j=0; j < mNumMipLevels; j++)
  462. {
  463. mMipLevelOffsets[j] = offset;
  464. offset += getHeight(j) * getWidth(j) * mBytesPerPixel;
  465. }
  466. return true;
  467. }
  468. //------------------------------------------------------------------------------
  469. bool GBitmap::checkForTransparency()
  470. {
  471. mHasTransparency = false;
  472. ColorI pixel(255, 255, 255, 255);
  473. switch (mInternalFormat)
  474. {
  475. // Non-transparent formats
  476. case GFXFormatL8:
  477. case GFXFormatR8G8B8:
  478. case GFXFormatR5G6B5:
  479. break;
  480. // Transparent formats
  481. case GFXFormatA8:
  482. case GFXFormatR8G8B8A8:
  483. case GFXFormatR5G5B5A1:
  484. // Let getColor() do the heavy lifting
  485. for (U32 x = 0; x < mWidth; x++)
  486. {
  487. for (U32 y = 0; y < mHeight; y++)
  488. {
  489. if (getColor(x, y, pixel))
  490. {
  491. if (pixel.alpha < 255)
  492. {
  493. mHasTransparency = true;
  494. break;
  495. }
  496. }
  497. }
  498. }
  499. break;
  500. default:
  501. AssertFatal(false, "GBitmap::checkForTransparency: misunderstood format specifier");
  502. break;
  503. }
  504. return mHasTransparency;
  505. }
  506. //------------------------------------------------------------------------------
  507. ColorF GBitmap::sampleTexel(F32 u, F32 v) const
  508. {
  509. ColorF col(0.5f, 0.5f, 0.5f);
  510. // normally sampling wraps all the way around at 1.0,
  511. // but locking doesn't support this, and we seem to calc
  512. // the uv based on a clamped 0 - 1...
  513. Point2F max((F32)(getWidth()-1), (F32)(getHeight()-1));
  514. Point2F posf;
  515. posf.x = mClampF(((u) * max.x), 0.0f, max.x);
  516. posf.y = mClampF(((v) * max.y), 0.0f, max.y);
  517. Point2I posi((S32)posf.x, (S32)posf.y);
  518. const U8 *buffer = getBits();
  519. U32 lexelindex = ((posi.y * getWidth()) + posi.x) * mBytesPerPixel;
  520. if(mBytesPerPixel == 2)
  521. {
  522. //U16 *buffer = (U16 *)lockrect->pBits;
  523. }
  524. else if(mBytesPerPixel > 2)
  525. {
  526. col.red = F32(buffer[lexelindex + 0]) / 255.0f;
  527. col.green = F32(buffer[lexelindex + 1]) / 255.0f;
  528. col.blue = F32(buffer[lexelindex + 2]) / 255.0f;
  529. }
  530. return col;
  531. }
  532. //--------------------------------------------------------------------------
  533. bool GBitmap::getColor(const U32 x, const U32 y, ColorI& rColor) const
  534. {
  535. if (x >= mWidth || y >= mHeight)
  536. return false;
  537. const U8* pLoc = getAddress(x, y);
  538. switch (mInternalFormat) {
  539. case GFXFormatA8:
  540. case GFXFormatL8:
  541. rColor.set( *pLoc, *pLoc, *pLoc, *pLoc );
  542. break;
  543. case GFXFormatR8G8B8:
  544. case GFXFormatR8G8B8X8:
  545. rColor.set( pLoc[0], pLoc[1], pLoc[2], 255 );
  546. break;
  547. case GFXFormatR8G8B8A8:
  548. rColor.set( pLoc[0], pLoc[1], pLoc[2], pLoc[3] );
  549. break;
  550. case GFXFormatR5G5B5A1:
  551. #if defined(TORQUE_OS_MAC)
  552. rColor.set( (*((U16*)pLoc) >> 0) & 0x1F,
  553. (*((U16*)pLoc) >> 5) & 0x1F,
  554. (*((U16*)pLoc) >> 10) & 0x1F,
  555. ((*((U16*)pLoc) >> 15) & 0x01) ? 255 : 0 );
  556. #else
  557. rColor.set( *((U16*)pLoc) >> 11,
  558. (*((U16*)pLoc) >> 6) & 0x1f,
  559. (*((U16*)pLoc) >> 1) & 0x1f,
  560. (*((U16*)pLoc) & 1) ? 255 : 0 );
  561. #endif
  562. break;
  563. default:
  564. AssertFatal(false, "Bad internal format");
  565. return false;
  566. }
  567. return true;
  568. }
  569. //--------------------------------------------------------------------------
  570. bool GBitmap::setColor(const U32 x, const U32 y, const ColorI& rColor)
  571. {
  572. if (x >= mWidth || y >= mHeight)
  573. return false;
  574. U8* pLoc = getAddress(x, y);
  575. switch (mInternalFormat) {
  576. case GFXFormatA8:
  577. case GFXFormatL8:
  578. *pLoc = rColor.alpha;
  579. break;
  580. case GFXFormatR8G8B8:
  581. dMemcpy( pLoc, &rColor, 3 * sizeof( U8 ) );
  582. break;
  583. case GFXFormatR8G8B8A8:
  584. case GFXFormatR8G8B8X8:
  585. dMemcpy( pLoc, &rColor, 4 * sizeof( U8 ) );
  586. break;
  587. case GFXFormatR5G6B5:
  588. #ifdef TORQUE_OS_MAC
  589. *((U16*)pLoc) = (rColor.red << 11) | (rColor.green << 5) | (rColor.blue << 0) ;
  590. #else
  591. *((U16*)pLoc) = (rColor.blue << 0) | (rColor.green << 5) | (rColor.red << 11);
  592. #endif
  593. break;
  594. case GFXFormatR5G5B5A1:
  595. #ifdef TORQUE_OS_MAC
  596. *((U16*)pLoc) = (((rColor.alpha>0) ? 1 : 0)<<15) | (rColor.blue << 10) | (rColor.green << 5) | (rColor.red << 0);
  597. #else
  598. *((U16*)pLoc) = (rColor.blue << 1) | (rColor.green << 6) | (rColor.red << 11) | ((rColor.alpha>0) ? 1 : 0);
  599. #endif
  600. break;
  601. default:
  602. AssertFatal(false, "Bad internal format");
  603. return false;
  604. }
  605. return true;
  606. }
  607. //-----------------------------------------------------------------------------
  608. bool GBitmap::combine( const GBitmap *bitmapA, const GBitmap *bitmapB, const GFXTextureOp combineOp )
  609. {
  610. // Check valid texture ops
  611. switch( combineOp )
  612. {
  613. case GFXTOPAdd:
  614. case GFXTOPSubtract:
  615. break;
  616. default:
  617. Con::errorf( "GBitmap::combine - Invalid op type" );
  618. return false;
  619. }
  620. // Check bitmapA format
  621. switch( bitmapA->getFormat() )
  622. {
  623. case GFXFormatR8G8B8:
  624. case GFXFormatR8G8B8X8:
  625. case GFXFormatR8G8B8A8:
  626. break;
  627. default:
  628. Con::errorf( "GBitmap::combine - invalid format for bitmapA" );
  629. return false;
  630. }
  631. // Check bitmapB format
  632. switch( bitmapB->getFormat() )
  633. {
  634. case GFXFormatR8G8B8:
  635. case GFXFormatR8G8B8X8:
  636. case GFXFormatR8G8B8A8:
  637. break;
  638. default:
  639. Con::errorf( "GBitmap::combine - invalid format for bitmapB" );
  640. return false;
  641. }
  642. // Determine format of result texture
  643. // CodeReview: This is dependent on the order of the GFXFormat enum. [5/11/2007 Pat]
  644. GFXFormat resFmt = static_cast<GFXFormat>( getMax( bitmapA->getFormat(), bitmapB->getFormat() ) );
  645. U32 resWidth = getMax( bitmapA->getWidth(), bitmapB->getWidth() );
  646. U32 resHeight = getMax( bitmapA->getHeight(), bitmapB->getHeight() );
  647. // Adjust size OF bitmap based on the biggest one
  648. if( bitmapA->getWidth() != bitmapB->getWidth() ||
  649. bitmapA->getHeight() != bitmapB->getHeight() )
  650. {
  651. // Delete old bitmap
  652. deleteImage();
  653. // Allocate new one
  654. allocateBitmap( resWidth, resHeight, false, resFmt );
  655. }
  656. // Adjust format of result bitmap (if resFmt == getFormat() it will not perform the format convert)
  657. setFormat( resFmt );
  658. // Perform combine
  659. U8 *destBits = getWritableBits();
  660. const U8 *aBits = bitmapA->getBits();
  661. const U8 *bBits = bitmapB->getBits();
  662. for( S32 y = 0; y < getHeight(); y++ )
  663. {
  664. for( S32 x = 0; x < getWidth(); x++ )
  665. {
  666. for( S32 _byte = 0; _byte < mBytesPerPixel; _byte++ )
  667. {
  668. U8 pxA = 0;
  669. U8 pxB = 0;
  670. // Get contributions from A and B
  671. if( y < bitmapA->getHeight() &&
  672. x < bitmapA->getWidth() &&
  673. _byte < bitmapA->mBytesPerPixel )
  674. pxA = *aBits++;
  675. if( y < bitmapB->getHeight() &&
  676. x < bitmapB->getWidth() &&
  677. _byte < bitmapB->mBytesPerPixel )
  678. pxB = *bBits++;
  679. // Combine them (clamp values 0-U8_MAX)
  680. switch( combineOp )
  681. {
  682. case GFXTOPAdd:
  683. *destBits++ = getMin( U8( pxA + pxB ), U8_MAX );
  684. break;
  685. case GFXTOPSubtract:
  686. *destBits++ = getMax( U8( pxA - pxB ), U8( 0 ) );
  687. break;
  688. default:
  689. AssertFatal(false, "GBitmap::combine - Invalid combineOp");
  690. break;
  691. }
  692. }
  693. }
  694. }
  695. return true;
  696. }
  697. void GBitmap::fill( const ColorI &rColor )
  698. {
  699. // Set the first pixel using the slow
  700. // but proper method.
  701. setColor( 0, 0, rColor );
  702. mHasTransparency = rColor.alpha < 255;
  703. // Now fill the first row of the bitmap by
  704. // copying the first pixel across the row.
  705. const U32 stride = getWidth() * mBytesPerPixel;
  706. const U8 *src = getBits();
  707. U8 *dest = getWritableBits() + mBytesPerPixel;
  708. const U8 *end = src + stride;
  709. for ( ; dest != end; dest += mBytesPerPixel )
  710. dMemcpy( dest, src, mBytesPerPixel );
  711. // Now copy the first row to all the others.
  712. //
  713. // TODO: This could adaptively size the copy
  714. // amount to copy more rows from the source
  715. // and reduce the total number of memcpy calls.
  716. //
  717. dest = getWritableBits() + stride;
  718. end = src + ( stride * getHeight() );
  719. for ( ; dest != end; dest += stride )
  720. dMemcpy( dest, src, stride );
  721. }
  722. void GBitmap::fillWhite()
  723. {
  724. dMemset( getWritableBits(), 255, mByteSize );
  725. mHasTransparency = false;
  726. }
  727. GBitmap* GBitmap::createPaddedBitmap() const
  728. {
  729. if (isPow2(getWidth()) && isPow2(getHeight()))
  730. return NULL;
  731. AssertFatal(getNumMipLevels() == 1,
  732. "Cannot have non-pow2 bitmap with miplevels");
  733. U32 width = getWidth();
  734. U32 height = getHeight();
  735. U32 newWidth = getNextPow2(getWidth());
  736. U32 newHeight = getNextPow2(getHeight());
  737. GBitmap* pReturn = new GBitmap(newWidth, newHeight, false, getFormat());
  738. for (U32 i = 0; i < height; i++)
  739. {
  740. U8* pDest = (U8*)pReturn->getAddress(0, i);
  741. const U8* pSrc = (const U8*)getAddress(0, i);
  742. dMemcpy(pDest, pSrc, width * mBytesPerPixel);
  743. pDest += width * mBytesPerPixel;
  744. // set the src pixel to the last pixel in the row
  745. const U8 *pSrcPixel = pDest - mBytesPerPixel;
  746. for(U32 j = width; j < newWidth; j++)
  747. for(U32 k = 0; k < mBytesPerPixel; k++)
  748. *pDest++ = pSrcPixel[k];
  749. }
  750. for(U32 i = height; i < newHeight; i++)
  751. {
  752. U8* pDest = (U8*)pReturn->getAddress(0, i);
  753. U8* pSrc = (U8*)pReturn->getAddress(0, height-1);
  754. dMemcpy(pDest, pSrc, newWidth * mBytesPerPixel);
  755. }
  756. return pReturn;
  757. }
  758. GBitmap* GBitmap::createPow2Bitmap() const
  759. {
  760. if (isPow2(getWidth()) && isPow2(getHeight()))
  761. return NULL;
  762. AssertFatal(getNumMipLevels() == 1,
  763. "Cannot have non-pow2 bitmap with miplevels");
  764. U32 width = getWidth();
  765. U32 height = getHeight();
  766. U32 newWidth = getNextPow2(getWidth());
  767. U32 newHeight = getNextPow2(getHeight());
  768. GBitmap* pReturn = new GBitmap(newWidth, newHeight, false, getFormat());
  769. U8* pDest = (U8*)pReturn->getAddress(0, 0);
  770. const U8* pSrc = (const U8*)getAddress(0, 0);
  771. F32 yCoeff = (F32) height / (F32) newHeight;
  772. F32 xCoeff = (F32) width / (F32) newWidth;
  773. F32 currY = 0.0f;
  774. for (U32 y = 0; y < newHeight; y++)
  775. {
  776. F32 currX = 0.0f;
  777. //U32 yDestOffset = (pReturn->mWidth * pReturn->mBytesPerPixel) * y;
  778. //U32 xDestOffset = 0;
  779. //U32 ySourceOffset = (U32)((mWidth * mBytesPerPixel) * currY);
  780. //F32 xSourceOffset = 0.0f;
  781. for (U32 x = 0; x < newWidth; x++)
  782. {
  783. pDest = (U8*) pReturn->getAddress(x, y);
  784. pSrc = (U8*) getAddress((S32)currX, (S32)currY);
  785. for (U32 p = 0; p < pReturn->mBytesPerPixel; p++)
  786. {
  787. pDest[p] = pSrc[p];
  788. }
  789. currX += xCoeff;
  790. }
  791. currY += yCoeff;
  792. }
  793. return pReturn;
  794. }
  795. void GBitmap::copyChannel( U32 index, GBitmap *outBitmap ) const
  796. {
  797. AssertFatal( index < mBytesPerPixel, "GBitmap::copyChannel() - Bad channel offset!" );
  798. AssertFatal( outBitmap, "GBitmap::copyChannel() - Null output bitmap!" );
  799. AssertFatal( outBitmap->getWidth() == getWidth(), "GBitmap::copyChannel() - Width mismatch!" );
  800. AssertFatal( outBitmap->getHeight() == getHeight(), "GBitmap::copyChannel() - Height mismatch!" );
  801. U8 *outBits = outBitmap->getWritableBits();
  802. const U32 outBytesPerPixel = outBitmap->getBytesPerPixel();
  803. const U8 *srcBits = getBits() + index;
  804. const U8 *endBits = getBits() + mByteSize;
  805. for ( ; srcBits < endBits; )
  806. {
  807. *outBits = *srcBits;
  808. outBits += outBytesPerPixel;
  809. srcBits += mBytesPerPixel;
  810. }
  811. }
  812. //------------------------------------------------------------------------------
  813. bool GBitmap::read(Stream& io_rStream)
  814. {
  815. // Handle versioning
  816. U32 version;
  817. io_rStream.read(&version);
  818. AssertFatal(version == csFileVersion, "Bitmap::read: incorrect file version");
  819. //-------------------------------------- Read the object
  820. U32 fmt;
  821. io_rStream.read(&fmt);
  822. mInternalFormat = GFXFormat(fmt);
  823. mBytesPerPixel = 1;
  824. switch (mInternalFormat) {
  825. case GFXFormatA8:
  826. case GFXFormatL8: mBytesPerPixel = 1;
  827. break;
  828. case GFXFormatR8G8B8: mBytesPerPixel = 3;
  829. break;
  830. case GFXFormatR8G8B8A8: mBytesPerPixel = 4;
  831. break;
  832. case GFXFormatR5G6B5:
  833. case GFXFormatR5G5B5A1: mBytesPerPixel = 2;
  834. break;
  835. default:
  836. AssertFatal(false, "GBitmap::read: misunderstood format specifier");
  837. break;
  838. }
  839. io_rStream.read(&mByteSize);
  840. mBits = new U8[mByteSize];
  841. io_rStream.read(mByteSize, mBits);
  842. io_rStream.read(&mWidth);
  843. io_rStream.read(&mHeight);
  844. io_rStream.read(&mNumMipLevels);
  845. for (U32 i = 0; i < c_maxMipLevels; i++)
  846. io_rStream.read(&mMipLevelOffsets[i]);
  847. checkForTransparency();
  848. return (io_rStream.getStatus() == Stream::Ok);
  849. }
  850. bool GBitmap::write(Stream& io_rStream) const
  851. {
  852. // Handle versioning
  853. io_rStream.write(csFileVersion);
  854. //-------------------------------------- Write the object
  855. io_rStream.write(U32(mInternalFormat));
  856. io_rStream.write(mByteSize);
  857. io_rStream.write(mByteSize, mBits);
  858. io_rStream.write(mWidth);
  859. io_rStream.write(mHeight);
  860. io_rStream.write(mNumMipLevels);
  861. for (U32 i = 0; i < c_maxMipLevels; i++)
  862. io_rStream.write(mMipLevelOffsets[i]);
  863. return (io_rStream.getStatus() == Stream::Ok);
  864. }
  865. //------------------------------------------------------------------------------
  866. //-------------------------------------- Persistent I/O
  867. //
  868. bool GBitmap::readBitmap( const String &bmType, Stream &ioStream )
  869. {
  870. const GBitmap::Registration *regInfo = GBitmap::sFindRegInfo( bmType );
  871. if ( regInfo == NULL )
  872. {
  873. Con::errorf( "[GBitmap::readBitmap] unable to find registration for extension [%s]", bmType.c_str() );
  874. return NULL;
  875. }
  876. return regInfo->readFunc( ioStream, this );
  877. }
  878. bool GBitmap::writeBitmap( const String &bmType, Stream &ioStream, U32 compressionLevel )
  879. {
  880. const GBitmap::Registration *regInfo = GBitmap::sFindRegInfo( bmType );
  881. if ( regInfo == NULL )
  882. {
  883. Con::errorf( "[GBitmap::writeBitmap] unable to find registration for extension [%s]", bmType.c_str() );
  884. return NULL;
  885. }
  886. return regInfo->writeFunc( this, ioStream, (compressionLevel == U32_MAX) ? regInfo->defaultCompression : compressionLevel );
  887. }
  888. template<> void *Resource<GBitmap>::create(const Torque::Path &path)
  889. {
  890. PROFILE_SCOPE( ResourceGBitmap_create );
  891. #ifdef TORQUE_DEBUG_RES_MANAGER
  892. Con::printf( "Resource<GBitmap>::create - [%s]", path.getFullPath().c_str() );
  893. #endif
  894. FileStream stream;
  895. stream.open( path.getFullPath(), Torque::FS::File::Read );
  896. if ( stream.getStatus() != Stream::Ok )
  897. {
  898. Con::errorf( "Resource<GBitmap>::create - failed to open '%s'", path.getFullPath().c_str() );
  899. return NULL;
  900. }
  901. GBitmap *bmp = new GBitmap;
  902. const String extension = path.getExtension();
  903. if( !bmp->readBitmap( extension, stream ) )
  904. {
  905. Con::errorf( "Resource<GBitmap>::create - error reading '%s'", path.getFullPath().c_str() );
  906. delete bmp;
  907. bmp = NULL;
  908. }
  909. return bmp;
  910. }
  911. template<> ResourceBase::Signature Resource<GBitmap>::signature()
  912. {
  913. return MakeFourCC('b','i','t','m');
  914. }
  915. Resource<GBitmap> GBitmap::load(const Torque::Path &path)
  916. {
  917. Resource<GBitmap> ret = _load( path );
  918. if ( ret != NULL )
  919. return ret;
  920. // Do a recursive search.
  921. return _search( path );
  922. }
  923. Resource<GBitmap> GBitmap::_load(const Torque::Path &path)
  924. {
  925. PROFILE_SCOPE( GBitmap_load );
  926. if ( Torque::FS::IsFile( path ) )
  927. return ResourceManager::get().load( path );
  928. Path foundPath;
  929. if ( GBitmap::sFindFile( path, &foundPath ) )
  930. {
  931. Resource<GBitmap> ret = ResourceManager::get().load( foundPath );
  932. if ( ret != NULL )
  933. return ret;
  934. }
  935. return Resource< GBitmap >( NULL );
  936. }
  937. Resource<GBitmap> GBitmap::_search(const Torque::Path &path)
  938. {
  939. PROFILE_SCOPE( GBitmap_search );
  940. // If unable to load texture in current directory
  941. // look in the parent directory. But never look in the root.
  942. Path newPath( path );
  943. while ( true )
  944. {
  945. String filePath = newPath.getPath();
  946. String::SizeType slash = filePath.find( '/', filePath.length(), String::Right );
  947. if ( slash == String::NPos )
  948. break;
  949. slash = filePath.find( '/', filePath.length(), String::Right );
  950. if ( slash == String::NPos )
  951. break;
  952. String truncPath = filePath.substr( 0, slash );
  953. newPath.setPath( truncPath );
  954. Resource<GBitmap> ret = _load( newPath );
  955. if ( ret != NULL )
  956. return ret;
  957. }
  958. return Resource< GBitmap >( NULL );
  959. }
  960. DefineEngineFunction( getBitmapInfo, String, ( const char *filename ),,
  961. "Returns image info in the following format: width TAB height TAB bytesPerPixel. "
  962. "It will return an empty string if the file is not found.\n"
  963. "@ingroup Rendering\n" )
  964. {
  965. Resource<GBitmap> image = GBitmap::load( filename );
  966. if ( !image )
  967. return String::EmptyString;
  968. return String::ToString( "%d\t%d\t%d", image->getWidth(),
  969. image->getHeight(),
  970. image->getBytesPerPixel() );
  971. }