Texture.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  1. #include "Base.h"
  2. #include "Image.h"
  3. #include "Texture.h"
  4. #include "FileSystem.h"
  5. // PVRTC (GL_IMG_texture_compression_pvrtc) : Imagination based gpus
  6. #ifndef GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG
  7. #define GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG 0x8C01
  8. #endif
  9. #ifndef GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG
  10. #define GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG 0x8C03
  11. #endif
  12. #ifndef GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG
  13. #define GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG 0x8C00
  14. #endif
  15. #ifndef GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG
  16. #define GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG 0x8C02
  17. #endif
  18. // S3TC/DXT (GL_EXT_texture_compression_s3tc) : Most desktop/console gpus
  19. #ifndef GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
  20. #define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1
  21. #endif
  22. #ifndef GL_COMPRESSED_RGBA_S3TC_DXT3_EXT
  23. #define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2
  24. #endif
  25. #ifndef GL_COMPRESSED_RGBA_S3TC_DXT5_EXT
  26. #define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3
  27. #endif
  28. // ATC (GL_AMD_compressed_ATC_texture) : Qualcomm/Adreno based gpus
  29. #ifndef ATC_RGB_AMD
  30. #define ATC_RGB_AMD 0x8C92
  31. #endif
  32. #ifndef ATC_RGBA_EXPLICIT_ALPHA_AMD
  33. #define ATC_RGBA_EXPLICIT_ALPHA_AMD 0x8C93
  34. #endif
  35. #ifndef ATC_RGBA_INTERPOLATED_ALPHA_AMD
  36. #define ATC_RGBA_INTERPOLATED_ALPHA_AMD 0x87EE
  37. #endif
  38. namespace gameplay
  39. {
  40. static std::vector<Texture*> __textureCache;
  41. static TextureHandle __currentTextureId;
  42. Texture::Texture() : _handle(0), _format(UNKNOWN), _width(0), _height(0), _mipmapped(false), _cached(false), _compressed(false)
  43. {
  44. }
  45. Texture::~Texture()
  46. {
  47. if (_handle)
  48. {
  49. GL_ASSERT( glDeleteTextures(1, &_handle) );
  50. _handle = 0;
  51. }
  52. // Remove ourself from the texture cache.
  53. if (_cached)
  54. {
  55. std::vector<Texture*>::iterator itr = std::find(__textureCache.begin(), __textureCache.end(), this);
  56. if (itr != __textureCache.end())
  57. {
  58. __textureCache.erase(itr);
  59. }
  60. }
  61. }
  62. Texture* Texture::create(const char* path, bool generateMipmaps)
  63. {
  64. GP_ASSERT(path);
  65. // Search texture cache first.
  66. for (size_t i = 0, count = __textureCache.size(); i < count; ++i)
  67. {
  68. Texture* t = __textureCache[i];
  69. GP_ASSERT(t);
  70. if (t->_path == path)
  71. {
  72. // If 'generateMipmaps' is true, call Texture::generateMipamps() to force the
  73. // texture to generate its mipmap chain if it hasn't already done so.
  74. if (generateMipmaps)
  75. {
  76. t->generateMipmaps();
  77. }
  78. // Found a match.
  79. t->addRef();
  80. return t;
  81. }
  82. }
  83. Texture* texture = NULL;
  84. // Filter loading based on file extension.
  85. const char* ext = strrchr(FileSystem::resolvePath(path), '.');
  86. if (ext)
  87. {
  88. switch (strlen(ext))
  89. {
  90. case 4:
  91. if (tolower(ext[1]) == 'p' && tolower(ext[2]) == 'n' && tolower(ext[3]) == 'g')
  92. {
  93. Image* image = Image::create(path);
  94. if (image)
  95. texture = create(image, generateMipmaps);
  96. SAFE_RELEASE(image);
  97. }
  98. else if (tolower(ext[1]) == 'p' && tolower(ext[2]) == 'v' && tolower(ext[3]) == 'r')
  99. {
  100. // PowerVR Compressed Texture RGBA.
  101. texture = createCompressedPVRTC(path);
  102. }
  103. else if (tolower(ext[1]) == 'd' && tolower(ext[2]) == 'd' && tolower(ext[3]) == 's')
  104. {
  105. // DDS file format (DXT/S3TC) compressed textures
  106. texture = createCompressedDDS(path);
  107. }
  108. break;
  109. }
  110. }
  111. if (texture)
  112. {
  113. texture->_path = path;
  114. texture->_cached = true;
  115. // Add to texture cache.
  116. __textureCache.push_back(texture);
  117. return texture;
  118. }
  119. GP_ERROR("Failed to load texture from file '%s'.", path);
  120. return NULL;
  121. }
  122. Texture* Texture::create(Image* image, bool generateMipmaps)
  123. {
  124. GP_ASSERT(image);
  125. switch (image->getFormat())
  126. {
  127. case Image::RGB:
  128. return create(Texture::RGB, image->getWidth(), image->getHeight(), image->getData(), generateMipmaps);
  129. case Image::RGBA:
  130. return create(Texture::RGBA, image->getWidth(), image->getHeight(), image->getData(), generateMipmaps);
  131. default:
  132. GP_ERROR("Unsupported image format (%d).", image->getFormat());
  133. return NULL;
  134. }
  135. }
  136. Texture* Texture::create(Format format, unsigned int width, unsigned int height, unsigned char* data, bool generateMipmaps)
  137. {
  138. // Create and load the texture.
  139. GLuint textureId;
  140. GL_ASSERT( glGenTextures(1, &textureId) );
  141. GL_ASSERT( glBindTexture(GL_TEXTURE_2D, textureId) );
  142. GL_ASSERT( glPixelStorei(GL_UNPACK_ALIGNMENT, 1) );
  143. GL_ASSERT( glTexImage2D(GL_TEXTURE_2D, 0, (GLenum)format, width, height, 0, (GLenum)format, GL_UNSIGNED_BYTE, data) );
  144. // Set initial minification filter based on whether or not mipmaping was enabled.
  145. GL_ASSERT( glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, generateMipmaps ? GL_NEAREST_MIPMAP_LINEAR : GL_LINEAR) );
  146. Texture* texture = new Texture();
  147. texture->_handle = textureId;
  148. texture->_format = format;
  149. texture->_width = width;
  150. texture->_height = height;
  151. if (generateMipmaps)
  152. {
  153. texture->generateMipmaps();
  154. }
  155. // Restore the texture id
  156. GL_ASSERT( glBindTexture(GL_TEXTURE_2D, __currentTextureId) );
  157. return texture;
  158. }
  159. Texture* Texture::create(TextureHandle handle, int width, int height, Format format)
  160. {
  161. GP_ASSERT(handle);
  162. Texture* texture = new Texture();
  163. texture->_handle = handle;
  164. texture->_format = format;
  165. texture->_width = width;
  166. texture->_height = height;
  167. return texture;
  168. }
  169. // Computes the size of a PVRTC data chunk for a mipmap level of the given size.
  170. static unsigned int computePVRTCDataSize(int width, int height, int bpp)
  171. {
  172. int blockSize;
  173. int widthBlocks;
  174. int heightBlocks;
  175. if (bpp == 4)
  176. {
  177. blockSize = 4 * 4; // Pixel by pixel block size for 4bpp
  178. widthBlocks = std::max(width >> 2, 2);
  179. heightBlocks = std::max(height >> 2, 2);
  180. }
  181. else
  182. {
  183. blockSize = 8 * 4; // Pixel by pixel block size for 2bpp
  184. widthBlocks = std::max(width >> 3, 2);
  185. heightBlocks = std::max(height >> 2, 2);
  186. }
  187. return widthBlocks * heightBlocks * ((blockSize * bpp) >> 3);
  188. }
  189. Texture* Texture::createCompressedPVRTC(const char* path)
  190. {
  191. std::auto_ptr<Stream> stream(FileSystem::open(path));
  192. if (stream.get() == NULL || !stream->canRead())
  193. {
  194. GP_ERROR("Failed to load file '%s'.", path);
  195. return NULL;
  196. }
  197. // Read first 4 bytes to determine PVRTC format.
  198. size_t read;
  199. unsigned int version;
  200. read = stream->read(&version, sizeof(unsigned int), 1);
  201. if (read != 1)
  202. {
  203. GP_ERROR("Failed to read PVR version.");
  204. return NULL;
  205. }
  206. // Rewind to start of header.
  207. if (stream->seek(0, SEEK_SET) == false)
  208. {
  209. GP_ERROR("Failed to seek backwards to beginning of file after reading PVR version.");
  210. return NULL;
  211. }
  212. // Read texture data.
  213. GLsizei width, height;
  214. GLenum format;
  215. GLubyte* data = NULL;
  216. unsigned int mipMapCount;
  217. if (version == 0x03525650)
  218. {
  219. // Modern PVR file format.
  220. data = readCompressedPVRTC(path, stream.get(), &width, &height, &format, &mipMapCount);
  221. }
  222. else
  223. {
  224. // Legacy PVR file format.
  225. data = readCompressedPVRTCLegacy(path, stream.get(), &width, &height, &format, &mipMapCount);
  226. }
  227. if (data == NULL)
  228. {
  229. GP_ERROR("Failed to read texture data from PVR file '%s'.", path);
  230. return NULL;
  231. }
  232. stream->close();
  233. int bpp = (format == GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG || format == GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG) ? 2 : 4;
  234. // Generate our texture.
  235. GLuint textureId;
  236. GL_ASSERT( glGenTextures(1, &textureId) );
  237. GL_ASSERT( glBindTexture(GL_TEXTURE_2D, textureId) );
  238. GL_ASSERT( glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, mipMapCount > 1 ? GL_NEAREST_MIPMAP_LINEAR : GL_LINEAR) );
  239. Texture* texture = new Texture();
  240. texture->_handle = textureId;
  241. texture->_width = width;
  242. texture->_height = height;
  243. texture->_mipmapped = mipMapCount > 1;
  244. texture->_compressed = true;
  245. // Load the data for each level.
  246. GLubyte* ptr = data;
  247. for (unsigned int level = 0; level < mipMapCount; ++level)
  248. {
  249. unsigned int dataSize = computePVRTCDataSize(width, height, bpp);
  250. // Upload data to GL.
  251. GL_ASSERT( glCompressedTexImage2D(GL_TEXTURE_2D, level, format, width, height, 0, dataSize, ptr) );
  252. width = std::max(width >> 1, 1);
  253. height = std::max(height >> 1, 1);
  254. ptr += dataSize;
  255. }
  256. // Free data.
  257. SAFE_DELETE_ARRAY(data);
  258. return texture;
  259. }
  260. GLubyte* Texture::readCompressedPVRTC(const char* path, Stream* stream, GLsizei* width, GLsizei* height, GLenum* format, unsigned int* mipMapCount)
  261. {
  262. GP_ASSERT(stream);
  263. GP_ASSERT(path);
  264. GP_ASSERT(width);
  265. GP_ASSERT(height);
  266. GP_ASSERT(format);
  267. GP_ASSERT(mipMapCount);
  268. struct pvrtc_file_header
  269. {
  270. unsigned int version;
  271. unsigned int flags;
  272. unsigned int pixelFormat[2];
  273. unsigned int colorSpace;
  274. unsigned int channelType;
  275. unsigned int height;
  276. unsigned int width;
  277. unsigned int depth;
  278. unsigned int surfaceCount;
  279. unsigned int faceCount;
  280. unsigned int mipMapCount;
  281. unsigned int metaDataSize;
  282. };
  283. size_t read;
  284. // Read header data.
  285. pvrtc_file_header header;
  286. read = stream->read(&header, sizeof(pvrtc_file_header), 1);
  287. if (read != 1)
  288. {
  289. GP_ERROR("Failed to read PVR header data for file '%s'.", path);
  290. return NULL;
  291. }
  292. if (header.pixelFormat[1] != 0)
  293. {
  294. // Unsupported pixel format.
  295. GP_ERROR("Unsupported pixel format in PVR file '%s'. (MSB == %d != 0)", path, header.pixelFormat[1]);
  296. return NULL;
  297. }
  298. int bpp;
  299. switch (header.pixelFormat[0])
  300. {
  301. case 0:
  302. *format = GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  303. bpp = 2;
  304. break;
  305. case 1:
  306. *format = GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  307. bpp = 2;
  308. break;
  309. case 2:
  310. *format = GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  311. bpp = 4;
  312. break;
  313. case 3:
  314. *format = GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  315. bpp = 4;
  316. break;
  317. default:
  318. // Unsupported format.
  319. GP_ERROR("Unsupported pixel format value (%d) in PVR file '%s'.", header.pixelFormat[0], path);
  320. return NULL;
  321. }
  322. *width = (GLsizei)header.width;
  323. *height = (GLsizei)header.height;
  324. *mipMapCount = header.mipMapCount;
  325. // Skip meta-data.
  326. if (stream->seek(header.metaDataSize, SEEK_CUR) == false)
  327. {
  328. GP_ERROR("Failed to seek past header meta data in PVR file '%s'.", path);
  329. return NULL;
  330. }
  331. // Compute total size of data to be read.
  332. int w = *width;
  333. int h = *height;
  334. size_t dataSize = 0;
  335. for (unsigned int level = 0; level < header.mipMapCount; ++level)
  336. {
  337. dataSize += computePVRTCDataSize(w, h, bpp);
  338. w = std::max(w>>1, 1);
  339. h = std::max(h>>1, 1);
  340. }
  341. // Read data.
  342. GLubyte* data = new GLubyte[dataSize];
  343. read = stream->read(data, 1, dataSize);
  344. if (read != dataSize)
  345. {
  346. SAFE_DELETE_ARRAY(data);
  347. GP_ERROR("Failed to read texture data from PVR file '%s'.", path);
  348. return NULL;
  349. }
  350. return data;
  351. }
  352. GLubyte* Texture::readCompressedPVRTCLegacy(const char* path, Stream* stream, GLsizei* width, GLsizei* height, GLenum* format, unsigned int* mipMapCount)
  353. {
  354. char PVRTCIdentifier[] = "PVR!";
  355. struct pvrtc_file_header_legacy
  356. {
  357. unsigned int size; // size of the structure
  358. unsigned int height; // height of surface to be created
  359. unsigned int width; // width of input surface
  360. unsigned int mipmapCount; // number of mip-map levels requested
  361. unsigned int formatflags; // pixel format flags
  362. unsigned int dataSize; // total size in bytes
  363. unsigned int bpp; // number of bits per pixel
  364. unsigned int redBitMask; // mask for red bit
  365. unsigned int greenBitMask; // mask for green bits
  366. unsigned int blueBitMask; // mask for blue bits
  367. unsigned int alphaBitMask; // mask for alpha channel
  368. unsigned int pvrtcTag; // magic number identifying pvrtc file
  369. unsigned int surfaceCount; // number of surfaces present in the pvrtc
  370. };
  371. // Read the file header.
  372. unsigned int size = sizeof(pvrtc_file_header_legacy);
  373. pvrtc_file_header_legacy header;
  374. unsigned int read = (int)stream->read(&header, 1, size);
  375. if (read != size)
  376. {
  377. GP_ERROR("Failed to read file header for pvrtc file '%s'.", path);
  378. return NULL;
  379. }
  380. // Proper file header identifier.
  381. if (PVRTCIdentifier[0] != (char)((header.pvrtcTag >> 0) & 0xff) ||
  382. PVRTCIdentifier[1] != (char)((header.pvrtcTag >> 8) & 0xff) ||
  383. PVRTCIdentifier[2] != (char)((header.pvrtcTag >> 16) & 0xff) ||
  384. PVRTCIdentifier[3] != (char)((header.pvrtcTag >> 24) & 0xff))
  385. {
  386. GP_ERROR("Failed to load pvrtc file '%s': invalid header.", path);
  387. return NULL;
  388. }
  389. // Format flags for GLenum format.
  390. if (header.bpp == 4)
  391. {
  392. *format = header.alphaBitMask ? GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG : GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  393. }
  394. else if (header.bpp == 2)
  395. {
  396. *format = header.alphaBitMask ? GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG : GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  397. }
  398. else
  399. {
  400. GP_ERROR("Failed to load pvrtc file '%s': invalid pvrtc compressed texture format flags.", path);
  401. return NULL;
  402. }
  403. *width = (GLsizei)header.width;
  404. *height = (GLsizei)header.height;
  405. *mipMapCount = header.mipmapCount + 1; // +1 because mipmapCount does not include the base level
  406. GLubyte* data = new GLubyte[header.dataSize];
  407. read = (int)stream->read(data, 1, header.dataSize);
  408. if (read != header.dataSize)
  409. {
  410. GP_ERROR("Failed to load texture data for pvrtc file '%s'.", path);
  411. SAFE_DELETE_ARRAY(data);
  412. return NULL;
  413. }
  414. return data;
  415. }
  416. int Texture::getMaskByteIndex(unsigned int mask)
  417. {
  418. switch (mask)
  419. {
  420. case 0xff000000:
  421. return 3;
  422. case 0x00ff0000:
  423. return 2;
  424. case 0x0000ff00:
  425. return 1;
  426. case 0x000000ff:
  427. return 0;
  428. default:
  429. return -1; // no or invalid mask
  430. }
  431. }
  432. Texture* Texture::createCompressedDDS(const char* path)
  433. {
  434. GP_ASSERT(path);
  435. // DDS file structures.
  436. struct dds_pixel_format
  437. {
  438. unsigned int dwSize;
  439. unsigned int dwFlags;
  440. unsigned int dwFourCC;
  441. unsigned int dwRGBBitCount;
  442. unsigned int dwRBitMask;
  443. unsigned int dwGBitMask;
  444. unsigned int dwBBitMask;
  445. unsigned int dwABitMask;
  446. };
  447. struct dds_header
  448. {
  449. unsigned int dwSize;
  450. unsigned int dwFlags;
  451. unsigned int dwHeight;
  452. unsigned int dwWidth;
  453. unsigned int dwPitchOrLinearSize;
  454. unsigned int dwDepth;
  455. unsigned int dwMipMapCount;
  456. unsigned int dwReserved1[11];
  457. dds_pixel_format ddspf;
  458. unsigned int dwCaps;
  459. unsigned int dwCaps2;
  460. unsigned int dwCaps3;
  461. unsigned int dwCaps4;
  462. unsigned int dwReserved2;
  463. };
  464. struct dds_mip_level
  465. {
  466. GLubyte* data;
  467. GLsizei width;
  468. GLsizei height;
  469. GLsizei size;
  470. };
  471. Texture* texture = NULL;
  472. // Read DDS file.
  473. std::auto_ptr<Stream> stream(FileSystem::open(path));
  474. if (stream.get() == NULL || !stream->canRead())
  475. {
  476. GP_ERROR("Failed to open file '%s'.", path);
  477. return NULL;
  478. }
  479. // Validate DDS magic number.
  480. char code[4];
  481. if (stream->read(code, 1, 4) != 4 || strncmp(code, "DDS ", 4) != 0)
  482. {
  483. GP_ERROR("Failed to read DDS file '%s': invalid DDS magic number.", path);
  484. return NULL;
  485. }
  486. // Read DDS header.
  487. dds_header header;
  488. if (stream->read(&header, sizeof(dds_header), 1) != 1)
  489. {
  490. GP_ERROR("Failed to read header for DDS file '%s'.", path);
  491. return NULL;
  492. }
  493. if ((header.dwFlags & 0x20000/*DDSD_MIPMAPCOUNT*/) == 0)
  494. {
  495. // Mipmap count not specified (non-mipmapped texture).
  496. header.dwMipMapCount = 1;
  497. }
  498. // Allocate mip level structures.
  499. dds_mip_level* mipLevels = new dds_mip_level[header.dwMipMapCount];
  500. memset(mipLevels, 0, sizeof(dds_mip_level) * header.dwMipMapCount);
  501. GLenum format = 0;
  502. GLenum internalFormat = 0;
  503. bool compressed = false;
  504. GLsizei width = header.dwWidth;
  505. GLsizei height = header.dwHeight;
  506. Texture::Format textureFormat = Texture::UNKNOWN;
  507. if (header.ddspf.dwFlags & 0x4/*DDPF_FOURCC*/)
  508. {
  509. compressed = true;
  510. int bytesPerBlock;
  511. // Compressed.
  512. switch (header.ddspf.dwFourCC)
  513. {
  514. case ('D'|('X'<<8)|('T'<<16)|('1'<<24)):
  515. format = internalFormat = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
  516. bytesPerBlock = 8;
  517. break;
  518. case ('D'|('X'<<8)|('T'<<16)|('3'<<24)):
  519. format = internalFormat = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
  520. bytesPerBlock = 16;
  521. break;
  522. case ('D'|('X'<<8)|('T'<<16)|('5'<<24)):
  523. format = internalFormat = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
  524. bytesPerBlock = 16;
  525. break;
  526. case ('A'|('T'<<8)|('C'<<16)|(' '<<24)):
  527. format = internalFormat = ATC_RGB_AMD;
  528. bytesPerBlock = 8;
  529. break;
  530. case ('A'|('T'<<8)|('C'<<16)|('A'<<24)):
  531. format = internalFormat = ATC_RGBA_EXPLICIT_ALPHA_AMD;
  532. bytesPerBlock = 16;
  533. break;
  534. case ('A'|('T'<<8)|('C'<<16)|('I'<<24)):
  535. format = internalFormat = ATC_RGBA_INTERPOLATED_ALPHA_AMD;
  536. bytesPerBlock = 16;
  537. break;
  538. default:
  539. GP_ERROR("Unsupported compressed texture format (%d) for DDS file '%s'.", header.ddspf.dwFourCC, path);
  540. SAFE_DELETE_ARRAY(mipLevels);
  541. return NULL;
  542. }
  543. for (unsigned int i = 0; i < header.dwMipMapCount; ++i)
  544. {
  545. dds_mip_level& level = mipLevels[i];
  546. level.width = width;
  547. level.height = height;
  548. level.size = std::max(1, (width+3) >> 2) * std::max(1, (height+3) >> 2) * bytesPerBlock;
  549. level.data = new GLubyte[level.size];
  550. if (stream->read(level.data, 1, level.size) != (unsigned int)level.size)
  551. {
  552. GP_ERROR("Failed to load dds compressed texture bytes for texture: %s", path);
  553. // Cleanup mip data.
  554. for (unsigned int i = 0; i < header.dwMipMapCount; ++i)
  555. SAFE_DELETE_ARRAY(level.data);
  556. SAFE_DELETE_ARRAY(mipLevels);
  557. return texture;
  558. }
  559. width = std::max(1, width >> 1);
  560. height = std::max(1, height >> 1);
  561. }
  562. }
  563. else if (header.ddspf.dwFlags & 0x40/*DDPF_RGB*/)
  564. {
  565. // RGB/RGBA (uncompressed)
  566. bool colorConvert = false;
  567. unsigned int rmask = header.ddspf.dwRBitMask;
  568. unsigned int gmask = header.ddspf.dwGBitMask;
  569. unsigned int bmask = header.ddspf.dwBBitMask;
  570. unsigned int amask = header.ddspf.dwABitMask;
  571. int ridx = getMaskByteIndex(rmask);
  572. int gidx = getMaskByteIndex(gmask);
  573. int bidx = getMaskByteIndex(bmask);
  574. int aidx = getMaskByteIndex(amask);
  575. if (header.ddspf.dwRGBBitCount == 24)
  576. {
  577. format = internalFormat = GL_RGB;
  578. textureFormat = Texture::RGB;
  579. colorConvert = (ridx != 0) || (gidx != 1) || (bidx != 2);
  580. }
  581. else if (header.ddspf.dwRGBBitCount == 32)
  582. {
  583. format = internalFormat = GL_RGBA;
  584. textureFormat = Texture::RGBA;
  585. if (ridx == 0 && gidx == 1 && bidx == 2)
  586. {
  587. aidx = 3; // XBGR or ABGR
  588. colorConvert = false;
  589. }
  590. else if (ridx == 2 && gidx == 1 && bidx == 0)
  591. {
  592. aidx = 3; // XRGB or ARGB
  593. colorConvert = true;
  594. }
  595. else
  596. {
  597. format = 0; // invalid format
  598. }
  599. }
  600. if (format == 0)
  601. {
  602. GP_ERROR("Failed to create texture from uncompressed DDS file '%s': Unsupported color format (must be one of R8G8B8, A8R8G8B8, A8B8G8R8, X8R8G8B8, X8B8G8R8.", path);
  603. SAFE_DELETE_ARRAY(mipLevels);
  604. return NULL;
  605. }
  606. // Read data.
  607. for (unsigned int i = 0; i < header.dwMipMapCount; ++i)
  608. {
  609. dds_mip_level& level = mipLevels[i];
  610. level.width = width;
  611. level.height = height;
  612. level.size = width * height * (header.ddspf.dwRGBBitCount >> 3);
  613. level.data = new GLubyte[level.size];
  614. if (stream->read(level.data, 1, level.size) != (unsigned int)level.size)
  615. {
  616. GP_ERROR("Failed to load bytes for RGB dds texture: %s", path);
  617. // Cleanup mip data.
  618. for (unsigned int i = 0; i < header.dwMipMapCount; ++i)
  619. SAFE_DELETE_ARRAY(level.data);
  620. SAFE_DELETE_ARRAY(mipLevels);
  621. return texture;
  622. }
  623. width = std::max(1, width >> 1);
  624. height = std::max(1, height >> 1);
  625. }
  626. // Perform color conversion.
  627. if (colorConvert)
  628. {
  629. // Note: While it's possible to use BGRA_EXT texture formats here and avoid CPU color conversion below,
  630. // there seems to be different flavors of the BGRA extension, with some vendors requiring an internal
  631. // format of RGBA and others requiring an internal format of BGRA.
  632. // We could be smarter here later and skip color conversion in favor of GL_BGRA_EXT (for format
  633. // and/or internal format) based on which GL extensions are available.
  634. // Tip: Using A8B8G8R8 and X8B8G8R8 DDS format maps directly to GL RGBA and requires on no color conversion.
  635. GLubyte *pixel, r, g, b, a;
  636. if (format == GL_RGB)
  637. {
  638. for (unsigned int i = 0; i < header.dwMipMapCount; ++i)
  639. {
  640. dds_mip_level& level = mipLevels[i];
  641. for (int j = 0; j < level.size; j += 3)
  642. {
  643. pixel = &level.data[j];
  644. r = pixel[ridx]; g = pixel[gidx]; b = pixel[bidx];
  645. pixel[0] = r; pixel[1] = g; pixel[2] = b;
  646. }
  647. }
  648. }
  649. else if (format == GL_RGBA)
  650. {
  651. for (unsigned int i = 0; i < header.dwMipMapCount; ++i)
  652. {
  653. dds_mip_level& level = mipLevels[i];
  654. for (int j = 0; j < level.size; j += 4)
  655. {
  656. pixel = &level.data[j];
  657. r = pixel[ridx]; g = pixel[gidx]; b = pixel[bidx]; a = pixel[aidx];
  658. pixel[0] = r; pixel[1] = g; pixel[2] = b; pixel[3] = a;
  659. }
  660. }
  661. }
  662. }
  663. }
  664. else
  665. {
  666. // Unsupported.
  667. GP_ERROR("Failed to create texture from DDS file '%s': unsupported flags (%d).", path, header.ddspf.dwFlags);
  668. SAFE_DELETE_ARRAY(mipLevels);
  669. return NULL;
  670. }
  671. // Close file.
  672. stream->close();
  673. // Generate GL texture.
  674. GLuint textureId;
  675. GL_ASSERT( glGenTextures(1, &textureId) );
  676. GL_ASSERT( glBindTexture(GL_TEXTURE_2D, textureId) );
  677. GL_ASSERT( glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, header.dwMipMapCount > 1 ? GL_NEAREST_MIPMAP_LINEAR : GL_LINEAR ) );
  678. // Create gameplay texture.
  679. texture = new Texture();
  680. texture->_handle = textureId;
  681. texture->_width = header.dwWidth;
  682. texture->_height = header.dwHeight;
  683. texture->_compressed = compressed;
  684. texture->_mipmapped = header.dwMipMapCount > 1;
  685. // Load texture data.
  686. for (unsigned int i = 0; i < header.dwMipMapCount; ++i)
  687. {
  688. dds_mip_level& level = mipLevels[i];
  689. if (compressed)
  690. {
  691. GL_ASSERT( glCompressedTexImage2D(GL_TEXTURE_2D, i, format, level.width, level.height, 0, level.size, level.data) );
  692. }
  693. else
  694. {
  695. GL_ASSERT( glTexImage2D(GL_TEXTURE_2D, i, internalFormat, level.width, level.height, 0, format, GL_UNSIGNED_BYTE, level.data) );
  696. }
  697. // Clean up the texture data.
  698. SAFE_DELETE_ARRAY(level.data);
  699. }
  700. // Clean up mip levels structure.
  701. SAFE_DELETE_ARRAY(mipLevels);
  702. return texture;
  703. }
  704. Texture::Format Texture::getFormat() const
  705. {
  706. return _format;
  707. }
  708. const char* Texture::getPath() const
  709. {
  710. return _path.c_str();
  711. }
  712. unsigned int Texture::getWidth() const
  713. {
  714. return _width;
  715. }
  716. unsigned int Texture::getHeight() const
  717. {
  718. return _height;
  719. }
  720. TextureHandle Texture::getHandle() const
  721. {
  722. return _handle;
  723. }
  724. void Texture::setWrapMode(Wrap wrapS, Wrap wrapT)
  725. {
  726. GL_ASSERT( glBindTexture(GL_TEXTURE_2D, _handle) );
  727. GL_ASSERT( glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, (GLenum)wrapS) );
  728. GL_ASSERT( glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, (GLenum)wrapT) );
  729. }
  730. void Texture::setFilterMode(Filter minificationFilter, Filter magnificationFilter)
  731. {
  732. GL_ASSERT( glBindTexture(GL_TEXTURE_2D, _handle) );
  733. GL_ASSERT( glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (GLenum)minificationFilter) );
  734. GL_ASSERT( glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, (GLenum)magnificationFilter) );
  735. }
  736. void Texture::generateMipmaps()
  737. {
  738. if (!_mipmapped)
  739. {
  740. GL_ASSERT( glBindTexture(GL_TEXTURE_2D, _handle) );
  741. GL_ASSERT( glHint(GL_GENERATE_MIPMAP_HINT, GL_NICEST) );
  742. GL_ASSERT( glGenerateMipmap(GL_TEXTURE_2D) );
  743. _mipmapped = true;
  744. }
  745. }
  746. bool Texture::isMipmapped() const
  747. {
  748. return _mipmapped;
  749. }
  750. bool Texture::isCompressed() const
  751. {
  752. return _compressed;
  753. }
  754. Texture::Sampler::Sampler(Texture* texture)
  755. : _texture(texture), _wrapS(Texture::REPEAT), _wrapT(Texture::REPEAT), _magFilter(Texture::LINEAR)
  756. {
  757. GP_ASSERT(texture);
  758. _minFilter = texture->isMipmapped() ? Texture::NEAREST_MIPMAP_LINEAR : Texture::LINEAR;
  759. }
  760. Texture::Sampler::~Sampler()
  761. {
  762. SAFE_RELEASE(_texture);
  763. }
  764. Texture::Sampler* Texture::Sampler::create(Texture* texture)
  765. {
  766. GP_ASSERT(texture);
  767. texture->addRef();
  768. return new Sampler(texture);
  769. }
  770. Texture::Sampler* Texture::Sampler::create(const char* path, bool generateMipmaps)
  771. {
  772. Texture* texture = Texture::create(path, generateMipmaps);
  773. return texture ? new Sampler(texture) : NULL;
  774. }
  775. void Texture::Sampler::setWrapMode(Wrap wrapS, Wrap wrapT)
  776. {
  777. _wrapS = wrapS;
  778. _wrapT = wrapT;
  779. _texture->setWrapMode(wrapS, wrapT);
  780. }
  781. void Texture::Sampler::setFilterMode(Filter minificationFilter, Filter magnificationFilter)
  782. {
  783. _minFilter = minificationFilter;
  784. _magFilter = magnificationFilter;
  785. _texture->setFilterMode(minificationFilter, magnificationFilter);
  786. }
  787. Texture* Texture::Sampler::getTexture() const
  788. {
  789. return _texture;
  790. }
  791. void Texture::Sampler::bind()
  792. {
  793. GP_ASSERT(_texture);
  794. GL_ASSERT( glBindTexture(GL_TEXTURE_2D, _texture->_handle) );
  795. }
  796. }