gBitmap.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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. #ifndef _GBITMAP_H_
  23. #define _GBITMAP_H_
  24. #ifndef __RESOURCE_H__
  25. #include "core/resource.h"
  26. #endif
  27. #ifndef _SWIZZLE_H_
  28. #include "core/util/swizzle.h"
  29. #endif
  30. #ifndef _TVECTOR_H_
  31. #include "core/util/tVector.h"
  32. #endif
  33. #ifndef _GFXENUMS_H_
  34. #include "gfx/gfxEnums.h" // For the format
  35. #endif
  36. #ifndef _PROFILER_H_
  37. #include "platform/profiler.h"
  38. #endif
  39. //-------------------------------------- Forward decls.
  40. class Stream;
  41. class RectI;
  42. class Point2I;
  43. class ColorI;
  44. class LinearColorF;
  45. //------------------------------------------------------------------------------
  46. //-------------------------------------- GBitmap
  47. class GBitmap
  48. {
  49. public:
  50. enum Constants
  51. {
  52. /// The maximum mipmap levels we support. The current
  53. /// value lets us support up to 8192 x 8192 images.
  54. c_maxMipLevels = 14
  55. };
  56. enum TextureOp
  57. {
  58. Add,
  59. Subtract
  60. };
  61. struct Registration
  62. {
  63. /// The read functions prototype.
  64. typedef bool(*ReadFunc)(const Torque::Path& path, GBitmap* bitmap);
  65. typedef bool(*ReadStreamFunc)(Stream& stream, GBitmap* bitmap, U32 len);
  66. /// The write functions prototype. Compression levels are image-specific - see their registration declaration for details.
  67. typedef bool(*WriteFunc)(const Torque::Path& path, GBitmap* bitmap, U32 compressionLevel);
  68. typedef bool(*WriteStreamFunc)(const String& bmType, Stream& stream, GBitmap* bitmap, U32 compressionLevel);
  69. /// Used to sort the registrations so that
  70. /// lookups occur in a fixed order.
  71. U32 priority;
  72. Vector<String> extensions; ///< the list of file extensions for this bitmap type [these should be lower case]
  73. ReadFunc readFunc; ///< the read function to read from a file.
  74. WriteFunc writeFunc; ///< the write function to write to a file.
  75. ReadStreamFunc readStreamFunc; ///< the read function to read from a stream.
  76. WriteStreamFunc writeStreamFunc; ///< the write function to write to a stream.
  77. U32 defaultCompression; ///< the default compression level [levels are image-specific - see their registration declaration for details]
  78. Registration()
  79. {
  80. readFunc = NULL;
  81. writeFunc = NULL;
  82. readStreamFunc = NULL;
  83. writeStreamFunc = NULL;
  84. defaultCompression = 0;
  85. priority = 0;
  86. VECTOR_SET_ASSOCIATION( extensions );
  87. }
  88. };
  89. /// Load the given bitmap file. It will try known file
  90. /// extensions if one is not specified. If all else fails
  91. /// it will look up the folder hierarchy for a match.
  92. ///
  93. /// Important: Don't do something like this...
  94. ///
  95. /// @code
  96. /// GBitmap* bitmap; // WRONG TYPE!
  97. /// bitmap = GBitmap::load( filename );
  98. /// @endcode
  99. ///
  100. /// Resources are reference-counted and the smart pointer conversion will
  101. /// release the bitmap and thus render the resulting bitmap pointer invalid!
  102. /// The right way is like this:
  103. ///
  104. /// @code
  105. /// Resource<GBitmap> bitmap; // Correct!
  106. /// bitmap = GBitmap::load( filename );
  107. /// @endcode
  108. ///
  109. static Resource<GBitmap> load(const Torque::Path &path);
  110. protected:
  111. static Resource<GBitmap> _load(const Torque::Path &path);
  112. static Resource<GBitmap> _search(const Torque::Path &path);
  113. public:
  114. GBitmap();
  115. GBitmap(const GBitmap&);
  116. GBitmap(const U32 in_width,
  117. const U32 in_height,
  118. const bool in_extrudeMipLevels = false,
  119. const GFXFormat in_format = GFXFormatR8G8B8 );
  120. // This builds a GBitmap with the R8G8B8A8 format using the passed in
  121. // data (assumes that there is width * height * 4 U8's in data)
  122. GBitmap(const U32 in_width,
  123. const U32 in_height,
  124. const U8* data );
  125. virtual ~GBitmap();
  126. static void sRegisterFormat( const Registration &reg );
  127. static const Registration* sFindRegInfo( const String &extension );
  128. /// Find the first file matching the registered extensions
  129. /// skipping the original.
  130. static bool sFindFile( const Torque::Path &path, Torque::Path *outPath );
  131. /// Given a path to a file, try all known extensions. If the file exists on disk, fill in path
  132. /// with the correct extension and return true. Otherwise, return false.
  133. static bool sFindFiles( const Torque::Path &path, Vector<Torque::Path> *outFoundPaths );
  134. /// Returns a space separated string of all registered extensions.
  135. static String sGetExtensionList();
  136. void allocateBitmap(const U32 in_width,
  137. const U32 in_height,
  138. const bool in_extrudeMipLevels = false,
  139. const GFXFormat in_format = GFXFormatR8G8B8 );
  140. void allocateBitmapWithMips(const U32 in_width,
  141. const U32 in_height,
  142. const U32 in_numMips,
  143. const GFXFormat in_format = GFXFormatR8G8B8);
  144. void extrudeMipLevels(bool clearBorders = false);
  145. void chopTopMips(U32 mipsToChop);
  146. void extrudeMipLevelsDetail();
  147. U32 getNumMipLevels() const { return mNumMipLevels; }
  148. GBitmap *createPaddedBitmap() const;
  149. GBitmap *createPow2Bitmap() const;
  150. /// Copies a color channel by index into the first channel
  151. /// of the output bitmap. The output bitmap must be the same
  152. /// dimensions as the source.
  153. void copyChannel( U32 index, GBitmap *outBitmap ) const;
  154. void copyRect(const GBitmap *in, const RectI &srcRect, const Point2I &dstPoint, const U32 srcMipLevel = 0, const U32 dstMipLevel = 0);
  155. GFXFormat getFormat() const { return mInternalFormat; }
  156. bool setFormat(GFXFormat fmt);
  157. U32 getWidth(const U32 in_mipLevel = 0) const;
  158. U32 getHeight(const U32 in_mipLevel = 0) const;
  159. U32 getDepth(const U32 in_mipLevel = 0) const;
  160. U8* getAddress(const S32 in_x, const S32 in_y, const U32 mipLevel = 0);
  161. const U8* getAddress(const S32 in_x, const S32 in_y, const U32 mipLevel = 0) const;
  162. const U8* getBits(const U32 in_mipLevel = 0) const;
  163. U8* getWritableBits(const U32 in_mipLevel = 0);
  164. U32 getByteSize() const { return mByteSize; }
  165. U32 getBytesPerPixel() const { return mBytesPerPixel; }
  166. U32 getSurfaceSize(const U32 mipLevel) const;
  167. /// Use these functions to set and get the mHasTransparency value
  168. /// This is used to indicate that this bitmap has pixels that have
  169. /// an alpha value less than 255 (used by the auto-Material mapper)
  170. bool getHasTransparency() const { return mHasTransparency; }
  171. void setHasTransparency(bool hasTransparency) { mHasTransparency = hasTransparency; }
  172. /// In general you will want to use this function if there is not a
  173. /// good spot in the bitmap loader(s) to check the alpha value of
  174. /// the pixels. This function uses the texture format to loop over
  175. /// the bitmap bits and to check for alpha values less than 255
  176. bool checkForTransparency();
  177. LinearColorF sampleTexel(F32 u, F32 v, bool retAlpha = false) const;
  178. bool getColor(const U32 x, const U32 y, ColorI& rColor) const;
  179. bool setColor(const U32 x, const U32 y, const ColorI& rColor);
  180. U8 getChanelValueAt(U32 x, U32 y, U32 chan);
  181. /// This method will combine bitmapA and bitmapB using the operation specified
  182. /// by combineOp. The result will be stored in the bitmap that this method is
  183. /// called on. The size of the resulting bitmap will be the larger of A and B.
  184. /// The format of the resulting bitmap will be the format of A or B, whichever
  185. /// has a larger byte size.
  186. ///
  187. /// @note There are some restrictions on ops and formats that will probably change
  188. /// based on how we use this function.
  189. bool combine( const GBitmap *bitmapA, const GBitmap *bitmapB, const TextureOp combineOp );
  190. /// Fills the first mip level of the bitmap with the specified color.
  191. void fill( const ColorI &rColor );
  192. /// An optimized version of fill().
  193. void fillWhite();
  194. //-------------------------------------- Internal data/operators
  195. void deleteImage();
  196. //-------------------------------------- Input/Output interface
  197. /// Read a bitmap from a file
  198. /// @param bmType This is a file extension to describe the type of the data [i.e. "png" for PNG file, etc]
  199. /// @param ioStream The stream to read from
  200. bool readBitmap(const String& bmType, const Torque::Path& path);
  201. /// Sane as above but reads from a stream.
  202. bool readBitmapStream(const String& bmType, Stream& ioStream, U32 len);
  203. /// Write a bitmap to a file
  204. /// @param bmType This is a file extension to describe the type of the data [i.e. "png" for PNG file, etc]
  205. /// @param ioStream The stream to read from
  206. /// @param compressionLevel Image format specific compression level. For JPEG sets the quality level percentage, range 0 to 100.
  207. /// For PNG compression level is 0 - 10
  208. /// Not used for other image formats.
  209. bool writeBitmap( const String &bmType, const Torque::Path& path, U32 compressionLevel = U32_MAX );
  210. /// Sane as above but writes to a stream.
  211. bool writeBitmapStream(const String& bmType, Stream& ioStream, U32 compressionLevel = U32_MAX);
  212. bool readMNG(Stream& io_rStream); // located in bitmapMng.cc
  213. bool writeMNG(Stream& io_rStream) const;
  214. bool read(Stream& io_rStream);
  215. bool write(Stream& io_rStream) const;
  216. template<class T, dsize_t mapLength>
  217. void swizzle(const Swizzle<T,mapLength> *s);
  218. static Vector<Registration> sRegistrations;
  219. private:
  220. GFXFormat mInternalFormat;
  221. U8* mBits; // Master bytes
  222. U32 mByteSize;
  223. U32 mWidth;
  224. U32 mHeight;
  225. U32 mBytesPerPixel;
  226. U32 mNumMipLevels;
  227. U32 mMipLevelOffsets[c_maxMipLevels];
  228. bool mHasTransparency;
  229. static const U32 csFileVersion;
  230. };
  231. //------------------------------------------------------------------------------
  232. //-------------------------------------- Inlines
  233. //
  234. inline U32 GBitmap::getWidth(const U32 in_mipLevel) const
  235. {
  236. AssertFatal(in_mipLevel < mNumMipLevels,
  237. avar("GBitmap::getWidth: mip level out of range: (%d, %d)",
  238. in_mipLevel, mNumMipLevels));
  239. U32 retVal = mWidth >> in_mipLevel;
  240. return (retVal != 0) ? retVal : 1;
  241. }
  242. inline U32 GBitmap::getHeight(const U32 in_mipLevel) const
  243. {
  244. AssertFatal(in_mipLevel < mNumMipLevels,
  245. avar("Bitmap::getHeight: mip level out of range: (%d, %d)",
  246. in_mipLevel, mNumMipLevels));
  247. U32 retVal = mHeight >> in_mipLevel;
  248. return (retVal != 0) ? retVal : 1;
  249. }
  250. inline const U8* GBitmap::getBits(const U32 in_mipLevel) const
  251. {
  252. AssertFatal(in_mipLevel < mNumMipLevels,
  253. avar("GBitmap::getBits: mip level out of range: (%d, %d)",
  254. in_mipLevel, mNumMipLevels));
  255. return &mBits[mMipLevelOffsets[in_mipLevel]];
  256. }
  257. inline U8* GBitmap::getWritableBits(const U32 in_mipLevel)
  258. {
  259. AssertFatal(in_mipLevel < mNumMipLevels,
  260. avar("GBitmap::getWritableBits: mip level out of range: (%d, %d)",
  261. in_mipLevel, mNumMipLevels));
  262. return &mBits[mMipLevelOffsets[in_mipLevel]];
  263. }
  264. inline U8* GBitmap::getAddress(const S32 in_x, const S32 in_y, const U32 mipLevel)
  265. {
  266. return (getWritableBits(mipLevel) + (U64)(((in_y * getWidth(mipLevel)) + in_x) * mBytesPerPixel));
  267. }
  268. inline const U8* GBitmap::getAddress(const S32 in_x, const S32 in_y, const U32 mipLevel) const
  269. {
  270. return (getBits(mipLevel) + ((in_y * getWidth(mipLevel)) + in_x) * mBytesPerPixel);
  271. }
  272. template<class T, dsize_t mapLength>
  273. void GBitmap::swizzle(const Swizzle<T,mapLength> *s )
  274. {
  275. const U32 memSize = getWidth() * getHeight() * mBytesPerPixel;
  276. void *b = dMalloc(memSize);
  277. s->ToBuffer(b, getWritableBits(), memSize);
  278. dMemcpy(getWritableBits(), b, memSize);
  279. dFree(b);
  280. }
  281. #endif //_GBITMAP_H_