Texture.cpp 26 KB

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