Texture.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  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_LINEAR_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. Texture* Texture::createCompressedDDS(const char* path)
  417. {
  418. GP_ASSERT(path);
  419. // DDS file structures.
  420. struct dds_pixel_format
  421. {
  422. unsigned int dwSize;
  423. unsigned int dwFlags;
  424. unsigned int dwFourCC;
  425. unsigned int dwRGBBitCount;
  426. unsigned int dwRBitMask;
  427. unsigned int dwGBitMask;
  428. unsigned int dwBBitMask;
  429. unsigned int dwABitMask;
  430. };
  431. struct dds_header
  432. {
  433. unsigned int dwSize;
  434. unsigned int dwFlags;
  435. unsigned int dwHeight;
  436. unsigned int dwWidth;
  437. unsigned int dwPitchOrLinearSize;
  438. unsigned int dwDepth;
  439. unsigned int dwMipMapCount;
  440. unsigned int dwReserved1[11];
  441. dds_pixel_format ddspf;
  442. unsigned int dwCaps;
  443. unsigned int dwCaps2;
  444. unsigned int dwCaps3;
  445. unsigned int dwCaps4;
  446. unsigned int dwReserved2;
  447. };
  448. struct dds_mip_level
  449. {
  450. GLubyte* data;
  451. GLsizei width;
  452. GLsizei height;
  453. GLsizei size;
  454. };
  455. Texture* texture = NULL;
  456. // Read DDS file.
  457. std::auto_ptr<Stream> stream(FileSystem::open(path));
  458. if (stream.get() == NULL || !stream->canRead())
  459. {
  460. GP_ERROR("Failed to open file '%s'.", path);
  461. return NULL;
  462. }
  463. // Validate DDS magic number.
  464. char code[4];
  465. if (stream->read(code, 1, 4) != 4 || strncmp(code, "DDS ", 4) != 0)
  466. {
  467. GP_ERROR("Failed to read DDS file '%s': invalid DDS magic number.", path);
  468. return NULL;
  469. }
  470. // Read DDS header.
  471. dds_header header;
  472. if (stream->read(&header, sizeof(dds_header), 1) != 1)
  473. {
  474. GP_ERROR("Failed to read header for DDS file '%s'.", path);
  475. return NULL;
  476. }
  477. if ((header.dwFlags & 0x20000/*DDSD_MIPMAPCOUNT*/) == 0)
  478. {
  479. // Mipmap count not specified (non-mipmapped texture).
  480. header.dwMipMapCount = 1;
  481. }
  482. // Allocate mip level structures.
  483. dds_mip_level* mipLevels = new dds_mip_level[header.dwMipMapCount];
  484. memset(mipLevels, 0, sizeof(dds_mip_level) * header.dwMipMapCount);
  485. GLenum format, internalFormat;
  486. bool compressed = false;
  487. GLsizei width = header.dwWidth;
  488. GLsizei height = header.dwHeight;
  489. int bytesPerBlock;
  490. if (header.ddspf.dwFlags & 0x4/*DDPF_FOURCC*/)
  491. {
  492. compressed = true;
  493. // Compressed.
  494. switch (header.ddspf.dwFourCC)
  495. {
  496. case ('D'|('X'<<8)|('T'<<16)|('1'<<24)):
  497. format = internalFormat = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
  498. bytesPerBlock = 8;
  499. break;
  500. case ('D'|('X'<<8)|('T'<<16)|('3'<<24)):
  501. format = internalFormat = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
  502. bytesPerBlock = 16;
  503. break;
  504. case ('D'|('X'<<8)|('T'<<16)|('5'<<24)):
  505. format = internalFormat = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
  506. bytesPerBlock = 16;
  507. break;
  508. case ('A'|('T'<<8)|('C'<<16)|(' '<<24)):
  509. format = internalFormat = ATC_RGB_AMD;
  510. bytesPerBlock = 8;
  511. break;
  512. case ('A'|('T'<<8)|('C'<<16)|('A'<<24)):
  513. format = internalFormat = ATC_RGBA_EXPLICIT_ALPHA_AMD;
  514. bytesPerBlock = 16;
  515. break;
  516. case ('A'|('T'<<8)|('C'<<16)|('I'<<24)):
  517. format = internalFormat = ATC_RGBA_INTERPOLATED_ALPHA_AMD;
  518. bytesPerBlock = 16;
  519. break;
  520. default:
  521. GP_ERROR("Unsupported compressed texture format (%d) for DDS file '%s'.", header.ddspf.dwFourCC, path);
  522. SAFE_DELETE_ARRAY(mipLevels);
  523. return NULL;
  524. }
  525. for (unsigned int i = 0; i < header.dwMipMapCount; ++i)
  526. {
  527. mipLevels[i].width = width;
  528. mipLevels[i].height = height;
  529. mipLevels[i].size = std::max(1, (width+3) >> 2) * std::max(1, (height+3) >> 2) * bytesPerBlock;
  530. mipLevels[i].data = new GLubyte[mipLevels[i].size];
  531. if (stream->read(mipLevels[i].data, 1, mipLevels[i].size) != (unsigned int)mipLevels[i].size)
  532. {
  533. GP_ERROR("Failed to load dds compressed texture bytes for texture: %s", path);
  534. // Cleanup mip data.
  535. for (unsigned int i = 0; i < header.dwMipMapCount; ++i)
  536. SAFE_DELETE_ARRAY(mipLevels[i].data);
  537. SAFE_DELETE_ARRAY(mipLevels);
  538. return texture;
  539. }
  540. width = std::max(1, width >> 1);
  541. height = std::max(1, height >> 1);
  542. }
  543. }
  544. else if (header.ddspf.dwFlags == 0x40/*DDPF_RGB*/)
  545. {
  546. // RGB (uncompressed)
  547. // Note: Use GL_BGR as internal format to flip bytes.
  548. GP_ERROR("Failed to create texture from DDS file '%s': uncompressed RGB format is not supported.", path);
  549. SAFE_DELETE_ARRAY(mipLevels);
  550. return NULL;
  551. }
  552. else if (header.ddspf.dwFlags == 0x41/*DDPF_RGB|DDPF_ALPHAPIXELS*/)
  553. {
  554. // RGBA (uncompressed)
  555. // Note: Use GL_BGRA as internal format to flip bytes.
  556. GP_ERROR("Failed to create texture from DDS file '%s': uncompressed RGBA format is not supported.", path);
  557. SAFE_DELETE_ARRAY(mipLevels);
  558. return NULL;
  559. }
  560. else
  561. {
  562. // Unsupported.
  563. GP_ERROR("Failed to create texture from DDS file '%s': unsupported flags (%d).", path, header.ddspf.dwFlags);
  564. SAFE_DELETE_ARRAY(mipLevels);
  565. return NULL;
  566. }
  567. // Close file.
  568. stream->close();
  569. // Generate GL texture.
  570. GLuint textureId;
  571. GL_ASSERT( glGenTextures(1, &textureId) );
  572. GL_ASSERT( glBindTexture(GL_TEXTURE_2D, textureId) );
  573. GL_ASSERT( glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, header.dwMipMapCount > 1 ? GL_LINEAR_MIPMAP_LINEAR : GL_LINEAR ) );
  574. // Create gameplay texture.
  575. texture = new Texture();
  576. texture->_handle = textureId;
  577. texture->_width = header.dwWidth;
  578. texture->_height = header.dwHeight;
  579. texture->_compressed = compressed;
  580. texture->_mipmapped = header.dwMipMapCount > 1;
  581. // Load texture data.
  582. for (unsigned int i = 0; i < header.dwMipMapCount; ++i)
  583. {
  584. if (compressed)
  585. {
  586. GL_ASSERT( glCompressedTexImage2D(GL_TEXTURE_2D, i, format, mipLevels[i].width, mipLevels[i].height, 0, mipLevels[i].size, mipLevels[i].data) );
  587. }
  588. else
  589. {
  590. // TODO: For uncompressed formats, set GL_UNPACK_ALIGNMENT based on stride
  591. GL_ASSERT( glTexImage2D(GL_TEXTURE_2D, i, internalFormat, mipLevels[i].width, mipLevels[i].height, 0, format, GL_UNSIGNED_INT, mipLevels[i].data) );
  592. }
  593. // Clean up the texture data.
  594. SAFE_DELETE_ARRAY(mipLevels[i].data);
  595. }
  596. // Clean up mip levels structure.
  597. SAFE_DELETE_ARRAY(mipLevels);
  598. return texture;
  599. }
  600. Texture::Format Texture::getFormat() const
  601. {
  602. return _format;
  603. }
  604. unsigned int Texture::getWidth() const
  605. {
  606. return _width;
  607. }
  608. unsigned int Texture::getHeight() const
  609. {
  610. return _height;
  611. }
  612. TextureHandle Texture::getHandle() const
  613. {
  614. return _handle;
  615. }
  616. void Texture::setWrapMode(Wrap wrapS, Wrap wrapT)
  617. {
  618. GL_ASSERT( glBindTexture(GL_TEXTURE_2D, _handle) );
  619. GL_ASSERT( glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, (GLenum)wrapS) );
  620. GL_ASSERT( glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, (GLenum)wrapT) );
  621. }
  622. void Texture::setFilterMode(Filter minificationFilter, Filter magnificationFilter)
  623. {
  624. GL_ASSERT( glBindTexture(GL_TEXTURE_2D, _handle) );
  625. GL_ASSERT( glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (GLenum)minificationFilter) );
  626. GL_ASSERT( glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, (GLenum)magnificationFilter) );
  627. }
  628. void Texture::generateMipmaps()
  629. {
  630. if (!_mipmapped)
  631. {
  632. GL_ASSERT( glBindTexture(GL_TEXTURE_2D, _handle) );
  633. GL_ASSERT( glGenerateMipmap(GL_TEXTURE_2D) );
  634. _mipmapped = true;
  635. }
  636. }
  637. bool Texture::isMipmapped() const
  638. {
  639. return _mipmapped;
  640. }
  641. bool Texture::isCompressed() const
  642. {
  643. return _compressed;
  644. }
  645. Texture::Sampler::Sampler(Texture* texture)
  646. : _texture(texture), _wrapS(Texture::REPEAT), _wrapT(Texture::REPEAT), _magFilter(Texture::LINEAR)
  647. {
  648. GP_ASSERT(texture);
  649. _minFilter = texture->isMipmapped() ? Texture::NEAREST_MIPMAP_LINEAR : Texture::LINEAR;
  650. }
  651. Texture::Sampler::~Sampler()
  652. {
  653. SAFE_RELEASE(_texture);
  654. }
  655. Texture::Sampler* Texture::Sampler::create(Texture* texture)
  656. {
  657. GP_ASSERT(texture);
  658. texture->addRef();
  659. return new Sampler(texture);
  660. }
  661. Texture::Sampler* Texture::Sampler::create(const char* path, bool generateMipmaps)
  662. {
  663. Texture* texture = Texture::create(path, generateMipmaps);
  664. return texture ? new Sampler(texture) : NULL;
  665. }
  666. void Texture::Sampler::setWrapMode(Wrap wrapS, Wrap wrapT)
  667. {
  668. _wrapS = wrapS;
  669. _wrapT = wrapT;
  670. }
  671. void Texture::Sampler::setFilterMode(Filter minificationFilter, Filter magnificationFilter)
  672. {
  673. _minFilter = minificationFilter;
  674. _magFilter = magnificationFilter;
  675. }
  676. Texture* Texture::Sampler::getTexture() const
  677. {
  678. return _texture;
  679. }
  680. void Texture::Sampler::bind()
  681. {
  682. GP_ASSERT(_texture);
  683. GL_ASSERT( glBindTexture(GL_TEXTURE_2D, _texture->_handle) );
  684. GL_ASSERT( glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, (GLenum)_wrapS) );
  685. GL_ASSERT( glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, (GLenum)_wrapT) );
  686. GL_ASSERT( glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (GLenum)_minFilter) );
  687. GL_ASSERT( glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, (GLenum)_magFilter) );
  688. }
  689. }