CmGLTexture.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. /*
  2. -----------------------------------------------------------------------------
  3. This source file is part of OGRE
  4. (Object-oriented Graphics Rendering Engine)
  5. For the latest info, see http://www.ogre3d.org
  6. Copyright (c) 2000-2011 Torus Knot Software Ltd
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in
  14. all copies or substantial portions of the Software.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. THE SOFTWARE.
  22. -----------------------------------------------------------------------------
  23. */
  24. #include "CmGLTexture.h"
  25. #include "CmGLSupport.h"
  26. #include "CmGLPixelFormat.h"
  27. #include "CmGLHardwarePixelBuffer.h"
  28. //#include "CmTextureManager.h"
  29. #include "CmCamera.h"
  30. #include "CmException.h"
  31. #include "CmBitwise.h"
  32. #include "CmTextureManager.h"
  33. #include "CmRenderSystemManager.h"
  34. #include "CmGLFBORenderTexture.h"
  35. #if CM_PLATFORM == CM_PLATFORM_WIN32
  36. # define WIN32_LEAN_AND_MEAN
  37. # if !defined(NOMINMAX) && defined(_MSC_VER)
  38. # define NOMINMAX // required to stop windows.h messing up std::min
  39. # endif
  40. # include <windows.h>
  41. # include <wingdi.h>
  42. #endif
  43. namespace CamelotEngine {
  44. GLTexture::GLTexture(GLSupport& support)
  45. : Texture(),
  46. mTextureID(0), mGLSupport(support)
  47. {
  48. }
  49. GLTexture::~GLTexture()
  50. {
  51. freeInternalResources();
  52. }
  53. GLenum GLTexture::getGLTextureTarget(void) const
  54. {
  55. switch(mTextureType)
  56. {
  57. case TEX_TYPE_1D:
  58. return GL_TEXTURE_1D;
  59. case TEX_TYPE_2D:
  60. return GL_TEXTURE_2D;
  61. case TEX_TYPE_3D:
  62. return GL_TEXTURE_3D;
  63. case TEX_TYPE_CUBE_MAP:
  64. return GL_TEXTURE_CUBE_MAP;
  65. default:
  66. return 0;
  67. };
  68. }
  69. //* Creation / loading methods ********************************************
  70. void GLTexture::createInternalResourcesImpl(void)
  71. {
  72. if (!GLEW_VERSION_1_2 && mTextureType == TEX_TYPE_3D)
  73. CM_EXCEPT(NotImplementedException,
  74. "3D Textures not supported before OpenGL 1.2");
  75. // Convert to nearest power-of-two size if required
  76. mWidth = GLPixelUtil::optionalPO2(mWidth);
  77. mHeight = GLPixelUtil::optionalPO2(mHeight);
  78. mDepth = GLPixelUtil::optionalPO2(mDepth);
  79. // Adjust format if required
  80. mFormat = TextureManager::instance().getNativeFormat(mTextureType, mFormat, mUsage);
  81. // Check requested number of mipmaps
  82. size_t maxMips = GLPixelUtil::getMaxMipmaps(mWidth, mHeight, mDepth, mFormat);
  83. mNumMipmaps = mNumRequestedMipmaps;
  84. if(mNumMipmaps>maxMips)
  85. mNumMipmaps = maxMips;
  86. // Generate texture name
  87. glGenTextures( 1, &mTextureID );
  88. // Set texture type
  89. glBindTexture( getGLTextureTarget(), mTextureID );
  90. // This needs to be set otherwise the texture doesn't get rendered
  91. if (GLEW_VERSION_1_2)
  92. glTexParameteri( getGLTextureTarget(), GL_TEXTURE_MAX_LEVEL, mNumMipmaps );
  93. // Set some misc default parameters so NVidia won't complain, these can of course be changed later
  94. glTexParameteri(getGLTextureTarget(), GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  95. glTexParameteri(getGLTextureTarget(), GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  96. if (GLEW_VERSION_1_2)
  97. {
  98. glTexParameteri(getGLTextureTarget(), GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  99. glTexParameteri(getGLTextureTarget(), GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  100. }
  101. // If we can do automip generation and the user desires this, do so
  102. mMipmapsHardwareGenerated =
  103. CamelotEngine::RenderSystemManager::getActive()->getCapabilities()->hasCapability(RSC_AUTOMIPMAP);
  104. // NVIDIA 175.16 drivers break hardware mip generation for non-compressed
  105. // textures - disable until fixed
  106. // Leave hardware gen on compressed textures since that's the only way we
  107. // can realistically do it since GLU doesn't support DXT
  108. // However DON'T do this on Apple, their drivers aren't subject to this
  109. // problem yet and in fact software generation appears to cause a crash
  110. // in some cases which I've yet to track down
  111. #if CM_PLATFORM != CM_PLATFORM_APPLE
  112. if (CamelotEngine::RenderSystemManager::getActive()->getCapabilities()->getVendor() == GPU_NVIDIA
  113. && !PixelUtil::isCompressed(mFormat))
  114. {
  115. mMipmapsHardwareGenerated = false;
  116. }
  117. #endif
  118. if((mUsage & TU_AUTOMIPMAP) &&
  119. mNumRequestedMipmaps && mMipmapsHardwareGenerated)
  120. {
  121. glTexParameteri( getGLTextureTarget(), GL_GENERATE_MIPMAP, GL_TRUE );
  122. }
  123. // Allocate internal buffer so that glTexSubImageXD can be used
  124. // Internal format
  125. GLenum format = GLPixelUtil::getClosestGLInternalFormat(mFormat, mHwGamma);
  126. size_t width = mWidth;
  127. size_t height = mHeight;
  128. size_t depth = mDepth;
  129. if(PixelUtil::isCompressed(mFormat))
  130. {
  131. // Compressed formats
  132. size_t size = PixelUtil::getMemorySize(mWidth, mHeight, mDepth, mFormat);
  133. // Provide temporary buffer filled with zeroes as glCompressedTexImageXD does not
  134. // accept a 0 pointer like normal glTexImageXD
  135. // Run through this process for every mipmap to pregenerate mipmap piramid
  136. UINT8 *tmpdata = new UINT8[size];
  137. memset(tmpdata, 0, size);
  138. for(size_t mip=0; mip<=mNumMipmaps; mip++)
  139. {
  140. size = PixelUtil::getMemorySize(width, height, depth, mFormat);
  141. switch(mTextureType)
  142. {
  143. case TEX_TYPE_1D:
  144. glCompressedTexImage1DARB(GL_TEXTURE_1D, mip, format,
  145. width, 0,
  146. size, tmpdata);
  147. break;
  148. case TEX_TYPE_2D:
  149. glCompressedTexImage2DARB(GL_TEXTURE_2D, mip, format,
  150. width, height, 0,
  151. size, tmpdata);
  152. break;
  153. case TEX_TYPE_3D:
  154. glCompressedTexImage3DARB(GL_TEXTURE_3D, mip, format,
  155. width, height, depth, 0,
  156. size, tmpdata);
  157. break;
  158. case TEX_TYPE_CUBE_MAP:
  159. for(int face=0; face<6; face++) {
  160. glCompressedTexImage2DARB(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, mip, format,
  161. width, height, 0,
  162. size, tmpdata);
  163. }
  164. break;
  165. };
  166. if(width>1) width = width/2;
  167. if(height>1) height = height/2;
  168. if(depth>1) depth = depth/2;
  169. }
  170. delete [] tmpdata;
  171. }
  172. else
  173. {
  174. // Run through this process to pregenerate mipmap piramid
  175. for(size_t mip=0; mip<=mNumMipmaps; mip++)
  176. {
  177. // Normal formats
  178. switch(mTextureType)
  179. {
  180. case TEX_TYPE_1D:
  181. glTexImage1D(GL_TEXTURE_1D, mip, format,
  182. width, 0,
  183. GL_RGBA, GL_UNSIGNED_BYTE, 0);
  184. break;
  185. case TEX_TYPE_2D:
  186. glTexImage2D(GL_TEXTURE_2D, mip, format,
  187. width, height, 0,
  188. GL_RGBA, GL_UNSIGNED_BYTE, 0);
  189. break;
  190. case TEX_TYPE_3D:
  191. glTexImage3D(GL_TEXTURE_3D, mip, format,
  192. width, height, depth, 0,
  193. GL_RGBA, GL_UNSIGNED_BYTE, 0);
  194. break;
  195. case TEX_TYPE_CUBE_MAP:
  196. for(int face=0; face<6; face++) {
  197. glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, mip, format,
  198. width, height, 0,
  199. GL_RGBA, GL_UNSIGNED_BYTE, 0);
  200. }
  201. break;
  202. };
  203. if(width>1) width = width/2;
  204. if(height>1) height = height/2;
  205. if(depth>1) depth = depth/2;
  206. }
  207. }
  208. _createSurfaceList();
  209. // Get final internal format
  210. mFormat = getBuffer(0,0)->getFormat();
  211. }
  212. void GLTexture::createRenderTexture(void)
  213. {
  214. // Create the GL texture
  215. // This already does everything neccessary
  216. createInternalResources();
  217. }
  218. // TODO PORT - Not supported in port. Not sure what its used for
  219. // static inline void do_image_io(const String &name, const String &group,
  220. // const String &ext,
  221. // vector<Image>::type &images,
  222. // Resource *r)
  223. // {
  224. //size_t imgIdx = images.size();
  225. // images.push_back(Image());
  226. // DataStreamPtr dstream =
  227. // ResourceGroupManager::getSingleton().openResource(
  228. // name, group, true, r);
  229. // images[imgIdx].load(dstream, ext);
  230. // }
  231. void GLTexture::prepareImpl()
  232. {
  233. if( mUsage & TU_RENDERTARGET ) return;
  234. // TODO PORT - Image loading not supported
  235. //String baseName, ext;
  236. //size_t pos = mName.find_last_of(".");
  237. //baseName = mName.substr(0, pos);
  238. //if( pos != String::npos )
  239. // ext = mName.substr(pos+1);
  240. //LoadedImages loadedImages = LoadedImages(new vector<Image>::type());
  241. //if(mTextureType == TEX_TYPE_1D || mTextureType == TEX_TYPE_2D ||
  242. // mTextureType == TEX_TYPE_3D)
  243. //{
  244. // do_image_io(mName, mGroup, ext, *loadedImages, this);
  245. // // If this is a cube map, set the texture type flag accordingly.
  246. // if ((*loadedImages)[0].hasFlag(IF_CUBEMAP))
  247. // mTextureType = TEX_TYPE_CUBE_MAP;
  248. // // If this is a volumetric texture set the texture type flag accordingly.
  249. // if((*loadedImages)[0].getDepth() > 1)
  250. // mTextureType = TEX_TYPE_3D;
  251. //}
  252. //else if (mTextureType == TEX_TYPE_CUBE_MAP)
  253. //{
  254. // if(getSourceFileType() == "dds")
  255. // {
  256. // // XX HACK there should be a better way to specify whether
  257. // // all faces are in the same file or not
  258. // do_image_io(mName, mGroup, ext, *loadedImages, this);
  259. // }
  260. // else
  261. // {
  262. // vector<Image>::type images(6);
  263. // ConstImagePtrList imagePtrs;
  264. // static const String suffixes[6] = {"_rt", "_lf", "_up", "_dn", "_fr", "_bk"};
  265. // for(size_t i = 0; i < 6; i++)
  266. // {
  267. // String fullName = baseName + suffixes[i];
  268. // if (!ext.empty())
  269. // fullName = fullName + "." + ext;
  270. // // find & load resource data intro stream to allow resource
  271. // // group changes if required
  272. // do_image_io(fullName,mGroup,ext,*loadedImages,this);
  273. // }
  274. // }
  275. //}
  276. //else
  277. // OGRE_EXCEPT( Exception::ERR_NOT_IMPLEMENTED, "**** Unknown texture type ****", "GLTexture::prepare" );
  278. //mLoadedImages = loadedImages;
  279. }
  280. void GLTexture::unprepareImpl()
  281. {
  282. //mLoadedImages.setNull();
  283. }
  284. void GLTexture::loadImpl()
  285. {
  286. if( mUsage & TU_RENDERTARGET )
  287. {
  288. createRenderTexture();
  289. return;
  290. }
  291. // TODO PORT - Image loading not supported
  292. //// Now the only copy is on the stack and will be cleaned in case of
  293. //// exceptions being thrown from _loadImages
  294. //LoadedImages loadedImages = mLoadedImages;
  295. //mLoadedImages.setNull();
  296. //// Call internal _loadImages, not loadImage since that's external and
  297. //// will determine load status etc again
  298. //ConstImagePtrList imagePtrs;
  299. //for (size_t i=0 ; i<loadedImages->size() ; ++i) {
  300. // imagePtrs.push_back(&(*loadedImages)[i]);
  301. //}
  302. //_loadImages(imagePtrs);
  303. }
  304. //*************************************************************************
  305. void GLTexture::freeInternalResourcesImpl()
  306. {
  307. mSurfaceList.clear();
  308. glDeleteTextures( 1, &mTextureID );
  309. }
  310. //---------------------------------------------------------------------------------------------
  311. void GLTexture::_createSurfaceList()
  312. {
  313. mSurfaceList.clear();
  314. // For all faces and mipmaps, store surfaces as HardwarePixelBufferPtr
  315. bool wantGeneratedMips = (mUsage & TU_AUTOMIPMAP)!=0;
  316. // Do mipmapping in software? (uses GLU) For some cards, this is still needed. Of course,
  317. // only when mipmap generation is desired.
  318. bool doSoftware = wantGeneratedMips && !mMipmapsHardwareGenerated && getNumMipmaps();
  319. for(size_t face=0; face<getNumFaces(); face++)
  320. {
  321. for(size_t mip=0; mip<=getNumMipmaps(); mip++)
  322. {
  323. GLHardwarePixelBuffer *buf = new GLTextureBuffer("", getGLTextureTarget(), mTextureID, face, mip,
  324. static_cast<HardwareBuffer::Usage>(mUsage), doSoftware && mip==0, mHwGamma, mFSAA);
  325. mSurfaceList.push_back(HardwarePixelBufferPtr(buf));
  326. /// Check for error
  327. if(buf->getWidth()==0 || buf->getHeight()==0 || buf->getDepth()==0)
  328. {
  329. CM_EXCEPT(RenderingAPIException,
  330. "Zero sized texture surface on texture face "
  331. + toString(face)
  332. + " mipmap "+toString(mip)
  333. + ". Probably, the GL driver refused to create the texture.");
  334. }
  335. }
  336. }
  337. }
  338. //---------------------------------------------------------------------------------------------
  339. HardwarePixelBufferPtr GLTexture::getBuffer(size_t face, size_t mipmap)
  340. {
  341. if(face >= getNumFaces())
  342. CM_EXCEPT(InvalidParametersException, "Face index out of range");
  343. if(mipmap > mNumMipmaps)
  344. CM_EXCEPT(InvalidParametersException, "Mipmap index out of range");
  345. unsigned int idx = face*(mNumMipmaps+1) + mipmap;
  346. assert(idx < mSurfaceList.size());
  347. return mSurfaceList[idx];
  348. }
  349. //---------------------------------------------------------------------------------------------
  350. void GLTexture::getCustomAttribute(const String& name, void* pData)
  351. {
  352. if (name == "GLID")
  353. *static_cast<GLuint*>(pData) = mTextureID;
  354. }
  355. }