Texture.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. /**
  2. * Copyright (c) 2006-2022 LOVE Development Team
  3. *
  4. * This software is provided 'as-is', without any express or implied
  5. * warranty. In no event will the authors be held liable for any damages
  6. * arising from the use of this software.
  7. *
  8. * Permission is granted to anyone to use this software for any purpose,
  9. * including commercial applications, and to alter it and redistribute it
  10. * freely, subject to the following restrictions:
  11. *
  12. * 1. The origin of this software must not be misrepresented; you must not
  13. * claim that you wrote the original software. If you use this software
  14. * in a product, an acknowledgment in the product documentation would be
  15. * appreciated but is not required.
  16. * 2. Altered source versions must be plainly marked as such, and must not be
  17. * misrepresented as being the original software.
  18. * 3. This notice may not be removed or altered from any source distribution.
  19. **/
  20. #include "Texture.h"
  21. #include "graphics/Graphics.h"
  22. #include "Graphics.h"
  23. #include "Buffer.h"
  24. #include "common/int.h"
  25. // STD
  26. #include <algorithm> // for min/max
  27. namespace love
  28. {
  29. namespace graphics
  30. {
  31. namespace opengl
  32. {
  33. static GLenum createFBO(GLuint &framebuffer, TextureType texType, PixelFormat format, GLuint texture, int mips, int layers, bool clear)
  34. {
  35. // get currently bound fbo to reset to it later
  36. GLuint current_fbo = gl.getFramebuffer(OpenGL::FRAMEBUFFER_ALL);
  37. glGenFramebuffers(1, &framebuffer);
  38. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, framebuffer);
  39. if (texture != 0)
  40. {
  41. if (isPixelFormatDepthStencil(format) && (GLAD_ES_VERSION_3_0 || !GLAD_ES_VERSION_2_0))
  42. {
  43. // glDrawBuffers is an ext in GL2. glDrawBuffer doesn't exist in ES3.
  44. GLenum none = GL_NONE;
  45. if (GLAD_ES_VERSION_3_0)
  46. glDrawBuffers(1, &none);
  47. else
  48. glDrawBuffer(GL_NONE);
  49. glReadBuffer(GL_NONE);
  50. }
  51. bool unusedSRGB = false;
  52. OpenGL::TextureFormat fmt = OpenGL::convertPixelFormat(format, false, unusedSRGB);
  53. int faces = texType == TEXTURE_CUBE ? 6 : 1;
  54. // Make sure all faces and layers of the texture are initialized to
  55. // transparent black. This is unfortunately probably pretty slow for
  56. // 2D-array and 3D textures with a lot of layers...
  57. for (int mip = mips - 1; mip >= 0; mip--)
  58. {
  59. for (int layer = layers - 1; layer >= 0; layer--)
  60. {
  61. for (int face = faces - 1; face >= 0; face--)
  62. {
  63. for (GLenum attachment : fmt.framebufferAttachments)
  64. {
  65. if (attachment == GL_NONE)
  66. continue;
  67. gl.framebufferTexture(attachment, texType, texture, mip, layer, face);
  68. }
  69. if (clear)
  70. {
  71. if (isPixelFormatDepthStencil(format))
  72. {
  73. bool hadDepthWrites = gl.hasDepthWrites();
  74. if (!hadDepthWrites) // glDepthMask also affects glClear.
  75. gl.setDepthWrites(true);
  76. uint32 stencilwrite = gl.getStencilWriteMask();
  77. if (stencilwrite != LOVE_UINT32_MAX)
  78. gl.setStencilWriteMask(LOVE_UINT32_MAX);
  79. gl.clearDepth(1.0);
  80. glClearStencil(0);
  81. glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
  82. if (!hadDepthWrites)
  83. gl.setDepthWrites(hadDepthWrites);
  84. if (stencilwrite != LOVE_UINT32_MAX)
  85. gl.setStencilWriteMask(stencilwrite);
  86. }
  87. else
  88. {
  89. glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
  90. glClear(GL_COLOR_BUFFER_BIT);
  91. }
  92. }
  93. }
  94. }
  95. }
  96. }
  97. GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  98. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, current_fbo);
  99. return status;
  100. }
  101. static GLenum newRenderbuffer(int width, int height, int &samples, PixelFormat pixelformat, GLuint &buffer)
  102. {
  103. bool unusedSRGB = false;
  104. OpenGL::TextureFormat fmt = OpenGL::convertPixelFormat(pixelformat, true, unusedSRGB);
  105. GLuint current_fbo = gl.getFramebuffer(OpenGL::FRAMEBUFFER_ALL);
  106. // Temporary FBO used to clear the renderbuffer.
  107. GLuint fbo = 0;
  108. glGenFramebuffers(1, &fbo);
  109. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, fbo);
  110. if (isPixelFormatDepthStencil(pixelformat) && (GLAD_ES_VERSION_3_0 || !GLAD_ES_VERSION_2_0))
  111. {
  112. // glDrawBuffers is an ext in GL2. glDrawBuffer doesn't exist in ES3.
  113. GLenum none = GL_NONE;
  114. if (GLAD_ES_VERSION_3_0)
  115. glDrawBuffers(1, &none);
  116. else
  117. glDrawBuffer(GL_NONE);
  118. glReadBuffer(GL_NONE);
  119. }
  120. glGenRenderbuffers(1, &buffer);
  121. glBindRenderbuffer(GL_RENDERBUFFER, buffer);
  122. if (samples > 1)
  123. glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples, fmt.internalformat, width, height);
  124. else
  125. glRenderbufferStorage(GL_RENDERBUFFER, fmt.internalformat, width, height);
  126. for (GLenum attachment : fmt.framebufferAttachments)
  127. {
  128. if (attachment != GL_NONE)
  129. glFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, buffer);
  130. }
  131. if (samples > 1)
  132. {
  133. glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
  134. samples = std::max(1, samples);
  135. }
  136. glBindRenderbuffer(GL_RENDERBUFFER, 0);
  137. GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  138. if (status == GL_FRAMEBUFFER_COMPLETE)
  139. {
  140. if (isPixelFormatDepthStencil(pixelformat))
  141. {
  142. bool hadDepthWrites = gl.hasDepthWrites();
  143. if (!hadDepthWrites) // glDepthMask also affects glClear.
  144. gl.setDepthWrites(true);
  145. gl.clearDepth(1.0);
  146. glClearStencil(0);
  147. glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
  148. if (!hadDepthWrites)
  149. gl.setDepthWrites(hadDepthWrites);
  150. }
  151. else
  152. {
  153. // Initialize the buffer to transparent black.
  154. glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
  155. glClear(GL_COLOR_BUFFER_BIT);
  156. }
  157. }
  158. else
  159. {
  160. glDeleteRenderbuffers(1, &buffer);
  161. buffer = 0;
  162. samples = 1;
  163. }
  164. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, current_fbo);
  165. gl.deleteFramebuffer(fbo);
  166. return status;
  167. }
  168. Texture::Texture(love::graphics::Graphics *gfx, const Settings &settings, const Slices *data)
  169. : love::graphics::Texture(gfx, settings, data)
  170. , slices(settings.type)
  171. , fbo(0)
  172. , texture(0)
  173. , renderbuffer(0)
  174. , framebufferStatus(GL_FRAMEBUFFER_COMPLETE)
  175. , textureGLError(GL_NO_ERROR)
  176. , actualSamples(1)
  177. {
  178. if (data != nullptr)
  179. slices = *data;
  180. if (!loadVolatile())
  181. {
  182. if (framebufferStatus != GL_FRAMEBUFFER_COMPLETE)
  183. throw love::Exception("Cannot create Texture (OpenGL framebuffer error: %s)", OpenGL::framebufferStatusString(framebufferStatus));
  184. if (textureGLError != GL_NO_ERROR)
  185. throw love::Exception("Cannot create Texture (OpenGL error: %s)", OpenGL::errorString(textureGLError));
  186. }
  187. // ImageData is referenced by the first loadVolatile call, but we don't
  188. // hang on to it after that so we can save memory.
  189. slices.clear();
  190. }
  191. Texture::~Texture()
  192. {
  193. unloadVolatile();
  194. }
  195. void Texture::createTexture()
  196. {
  197. // The base class handles some validation. For example, if ImageData is
  198. // given then it must exist for all mip levels, a render target can't use
  199. // a compressed format, etc.
  200. glGenTextures(1, &texture);
  201. gl.bindTextureToUnit(this, 0, false);
  202. // Use a default texture if the size is too big for the system.
  203. // validateDimensions is also called in the base class for RTs and
  204. // non-readable textures.
  205. if (!renderTarget && !validateDimensions(false))
  206. {
  207. usingDefaultTexture = true;
  208. setSamplerState(samplerState);
  209. bool isSRGB = false;
  210. gl.rawTexStorage(texType, 1, PIXELFORMAT_RGBA8_UNORM, isSRGB, 2, 2, 1);
  211. // A nice friendly checkerboard to signify invalid textures...
  212. GLubyte px[] = {0xFF,0xFF,0xFF,0xFF, 0xFF,0xA0,0xA0,0xFF,
  213. 0xFF,0xA0,0xA0,0xFF, 0xFF,0xFF,0xFF,0xFF};
  214. int slices = texType == TEXTURE_CUBE ? 6 : 1;
  215. Rect rect = {0, 0, 2, 2};
  216. for (int slice = 0; slice < slices; slice++)
  217. uploadByteData(PIXELFORMAT_RGBA8_UNORM, px, sizeof(px), 0, slice, rect);
  218. return;
  219. }
  220. GLenum gltype = OpenGL::getGLTextureType(texType);
  221. if (renderTarget && GLAD_ANGLE_texture_usage)
  222. glTexParameteri(gltype, GL_TEXTURE_USAGE_ANGLE, GL_FRAMEBUFFER_ATTACHMENT_ANGLE);
  223. setSamplerState(samplerState);
  224. int mipcount = getMipmapCount();
  225. int slicecount = 1;
  226. if (texType == TEXTURE_VOLUME)
  227. slicecount = getDepth();
  228. else if (texType == TEXTURE_2D_ARRAY)
  229. slicecount = getLayerCount();
  230. else if (texType == TEXTURE_CUBE)
  231. slicecount = 6;
  232. // For a couple flimsy reasons, we don't initialize the texture here if it's
  233. // compressed. I need to verify that getPixelFormatSliceSize will return the
  234. // correct value for all compressed texture formats, and I also vaguely
  235. // remember some driver issues on some old Android systems, maybe...
  236. // For now, the base class enforces data on init for compressed textures.
  237. if (!isCompressed())
  238. gl.rawTexStorage(texType, mipcount, format, sRGB, pixelWidth, pixelHeight, texType == TEXTURE_VOLUME ? depth : layers);
  239. int w = pixelWidth;
  240. int h = pixelHeight;
  241. int d = depth;
  242. OpenGL::TextureFormat fmt = gl.convertPixelFormat(format, false, sRGB);
  243. for (int mip = 0; mip < mipcount; mip++)
  244. {
  245. if (isCompressed() && (texType == TEXTURE_2D_ARRAY || texType == TEXTURE_VOLUME))
  246. {
  247. size_t mipsize = 0;
  248. if (texType == TEXTURE_2D_ARRAY || texType == TEXTURE_VOLUME)
  249. {
  250. for (int slice = 0; slice < slices.getSliceCount(mip); slice++)
  251. {
  252. auto id = slices.get(slice, mip);
  253. if (id != nullptr)
  254. mipsize += id->getSize();
  255. }
  256. }
  257. if (mipsize > 0)
  258. glCompressedTexImage3D(gltype, mip, fmt.internalformat, w, h, d, 0, mipsize, nullptr);
  259. }
  260. for (int slice = 0; slice < slicecount; slice++)
  261. {
  262. love::image::ImageDataBase *id = slices.get(slice, mip);
  263. if (id != nullptr)
  264. uploadImageData(id, mip, slice, 0, 0);
  265. }
  266. w = std::max(w / 2, 1);
  267. h = std::max(h / 2, 1);
  268. if (texType == TEXTURE_VOLUME)
  269. d = std::max(d / 2, 1);
  270. }
  271. bool hasdata = slices.get(0, 0) != nullptr;
  272. // All mipmap levels need to be initialized - for color formats we can clear
  273. // the base mip and use glGenerateMipmap after that's done. Depth and
  274. // stencil formats don't always support glGenerateMipmap so we need to
  275. // individually clear each mip level in that case. We avoid doing that for
  276. // color formats because of an Intel driver bug:
  277. // https://github.com/love2d/love/issues/1585
  278. int clearmips = 1;
  279. if (isPixelFormatDepthStencil(format))
  280. clearmips = mipmapCount;
  281. // Create a local FBO used for glReadPixels as well as MSAA blitting.
  282. if (isRenderTarget())
  283. {
  284. bool clear = !hasdata;
  285. int slices = texType == TEXTURE_VOLUME ? depth : layers;
  286. framebufferStatus = createFBO(fbo, texType, format, texture, clearmips, slices, clear);
  287. }
  288. else if (!hasdata)
  289. {
  290. // Initialize all slices to transparent black.
  291. for (int mip = 0; mip < clearmips; mip++)
  292. {
  293. int mipw = getPixelWidth(mip);
  294. int miph = getPixelHeight(mip);
  295. std::vector<uint8> emptydata(getPixelFormatSliceSize(format, mipw, miph));
  296. Rect r = {0, 0, mipw, miph};
  297. int slices = texType == TEXTURE_VOLUME ? getDepth(mip) : layers;
  298. slices = texType == TEXTURE_CUBE ? 6 : slices;
  299. for (int i = 0; i < slices; i++)
  300. uploadByteData(format, emptydata.data(), emptydata.size(), mip, i, r);
  301. }
  302. }
  303. // Non-readable textures can't have mipmaps (enforced in the base class),
  304. // so generateMipmaps here is fine - when they aren't already initialized.
  305. if (clearmips < mipmapCount && slices.getMipmapCount() <= 1 && getMipmapsMode() != MIPMAPS_NONE)
  306. generateMipmaps();
  307. }
  308. bool Texture::loadVolatile()
  309. {
  310. if (texture != 0 || renderbuffer != 0)
  311. return true;
  312. OpenGL::TempDebugGroup debuggroup("Texture load");
  313. // NPOT textures don't support mipmapping without full NPOT support.
  314. if ((GLAD_ES_VERSION_2_0 && !(GLAD_ES_VERSION_3_0 || GLAD_OES_texture_npot))
  315. && (pixelWidth != nextP2(pixelWidth) || pixelHeight != nextP2(pixelHeight)))
  316. {
  317. mipmapCount = 1;
  318. samplerState.mipmapFilter = SamplerState::MIPMAP_FILTER_NONE;
  319. }
  320. actualSamples = std::max(1, std::min(getRequestedMSAA(), gl.getMaxSamples()));
  321. while (glGetError() != GL_NO_ERROR); // Clear errors.
  322. framebufferStatus = GL_FRAMEBUFFER_COMPLETE;
  323. textureGLError = GL_NO_ERROR;
  324. if (isReadable())
  325. createTexture();
  326. if (!usingDefaultTexture && framebufferStatus == GL_FRAMEBUFFER_COMPLETE
  327. && (!isReadable() || actualSamples > 1))
  328. {
  329. framebufferStatus = newRenderbuffer(pixelWidth, pixelHeight, actualSamples, format, renderbuffer);
  330. }
  331. textureGLError = glGetError();
  332. if (framebufferStatus != GL_FRAMEBUFFER_COMPLETE || textureGLError != GL_NO_ERROR)
  333. {
  334. unloadVolatile();
  335. return false;
  336. }
  337. int64 memsize = 0;
  338. for (int mip = 0; mip < getMipmapCount(); mip++)
  339. {
  340. int w = getPixelWidth(mip);
  341. int h = getPixelHeight(mip);
  342. int slices = getDepth(mip) * layers * (texType == TEXTURE_CUBE ? 6 : 1);
  343. memsize += getPixelFormatSliceSize(format, w, h) * slices;
  344. }
  345. if (actualSamples > 1 && isReadable())
  346. {
  347. int slices = depth * layers * (texType == TEXTURE_CUBE ? 6 : 1);
  348. memsize += getPixelFormatSliceSize(format, pixelWidth, pixelHeight) * slices * actualSamples;
  349. }
  350. else if (actualSamples > 1)
  351. memsize *= actualSamples;
  352. setGraphicsMemorySize(memsize);
  353. usingDefaultTexture = false;
  354. return true;
  355. }
  356. void Texture::unloadVolatile()
  357. {
  358. if (isRenderTarget() && (fbo != 0 || renderbuffer != 0 || texture != 0))
  359. {
  360. // This is a bit ugly, but we need some way to destroy the cached FBO
  361. // when this texture's GL object is destroyed.
  362. auto gfx = Module::getInstance<Graphics>(Module::M_GRAPHICS);
  363. if (gfx != nullptr)
  364. gfx->cleanupRenderTexture(this);
  365. }
  366. if (fbo != 0)
  367. gl.deleteFramebuffer(fbo);
  368. if (renderbuffer != 0)
  369. glDeleteRenderbuffers(1, &renderbuffer);
  370. if (texture != 0)
  371. gl.deleteTexture(texture);
  372. fbo = 0;
  373. renderbuffer = 0;
  374. texture = 0;
  375. setGraphicsMemorySize(0);
  376. }
  377. void Texture::uploadByteData(PixelFormat pixelformat, const void *data, size_t size, int level, int slice, const Rect &r)
  378. {
  379. OpenGL::TempDebugGroup debuggroup("Texture data upload");
  380. gl.bindTextureToUnit(this, 0, false);
  381. OpenGL::TextureFormat fmt = OpenGL::convertPixelFormat(pixelformat, false, sRGB);
  382. GLenum gltarget = OpenGL::getGLTextureType(texType);
  383. if (texType == TEXTURE_CUBE)
  384. gltarget = GL_TEXTURE_CUBE_MAP_POSITIVE_X + slice;
  385. if (isPixelFormatCompressed(pixelformat))
  386. {
  387. if (texType == TEXTURE_2D || texType == TEXTURE_CUBE)
  388. {
  389. // Possible issues on some very old drivers if TexSubImage is used.
  390. if (r.x != 0 || r.y != 0 || r.w != getPixelWidth(level) || r.h != getPixelHeight(level))
  391. glCompressedTexSubImage2D(gltarget, level, r.x, r.y, r.w, r.h, fmt.internalformat, size, data);
  392. else
  393. glCompressedTexImage2D(gltarget, level, fmt.internalformat, r.w, r.h, 0, size, data);
  394. }
  395. else if (texType == TEXTURE_2D_ARRAY || texType == TEXTURE_VOLUME)
  396. glCompressedTexSubImage3D(gltarget, level, r.x, r.y, slice, r.w, r.h, 1, fmt.internalformat, size, data);
  397. }
  398. else
  399. {
  400. if (texType == TEXTURE_2D || texType == TEXTURE_CUBE)
  401. glTexSubImage2D(gltarget, level, r.x, r.y, r.w, r.h, fmt.externalformat, fmt.type, data);
  402. else if (texType == TEXTURE_2D_ARRAY || texType == TEXTURE_VOLUME)
  403. glTexSubImage3D(gltarget, level, r.x, r.y, slice, r.w, r.h, 1, fmt.externalformat, fmt.type, data);
  404. }
  405. }
  406. void Texture::generateMipmapsInternal()
  407. {
  408. gl.bindTextureToUnit(this, 0, false);
  409. GLenum gltextype = OpenGL::getGLTextureType(texType);
  410. if (gl.bugs.generateMipmapsRequiresTexture2DEnable)
  411. glEnable(gltextype);
  412. glGenerateMipmap(gltextype);
  413. }
  414. void Texture::readbackImageData(love::image::ImageData *data, int slice, int mipmap, const Rect &r)
  415. {
  416. if (fbo == 0) // Should never be reached.
  417. return;
  418. bool isSRGB = false;
  419. OpenGL::TextureFormat fmt = gl.convertPixelFormat(data->getFormat(), false, isSRGB);
  420. GLuint current_fbo = gl.getFramebuffer(OpenGL::FRAMEBUFFER_ALL);
  421. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, getFBO());
  422. if (slice > 0 || mipmap > 0)
  423. {
  424. int layer = texType == TEXTURE_CUBE ? 0 : slice;
  425. int face = texType == TEXTURE_CUBE ? slice : 0;
  426. gl.framebufferTexture(GL_COLOR_ATTACHMENT0, texType, texture, mipmap, layer, face);
  427. }
  428. glReadPixels(r.x, r.y, r.w, r.h, fmt.externalformat, fmt.type, data->getData());
  429. if (slice > 0 || mipmap > 0)
  430. gl.framebufferTexture(GL_COLOR_ATTACHMENT0, texType, texture, 0, 0, 0);
  431. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, current_fbo);
  432. }
  433. void Texture::copyFromBuffer(love::graphics::Buffer *source, size_t sourceoffset, int sourcewidth, size_t size, int slice, int mipmap, const Rect &rect)
  434. {
  435. // Higher level code does validation.
  436. GLuint glbuffer = (GLuint) source->getHandle();
  437. glBindBuffer(GL_PIXEL_UNPACK_BUFFER, glbuffer);
  438. if (!isCompressed()) // Not supported in GL with compressed textures...
  439. glPixelStorei(GL_UNPACK_ROW_LENGTH, sourcewidth);
  440. // glTexSubImage and friends copy from the active pixel_unpack_buffer by
  441. // treating the pointer as a byte offset.
  442. const uint8 *byteoffset = (const uint8 *)(ptrdiff_t)sourceoffset;
  443. uploadByteData(format, byteoffset, size, mipmap, slice, rect);
  444. glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
  445. glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
  446. }
  447. void Texture::copyToBuffer(love::graphics::Buffer *dest, int slice, int mipmap, const Rect &rect, size_t destoffset, int destwidth, size_t size)
  448. {
  449. // Higher level code does validation.
  450. GLuint glbuffer = (GLuint) dest->getHandle();
  451. glBindBuffer(GL_PIXEL_PACK_BUFFER, glbuffer);
  452. if (!isCompressed()) // Not supported in GL with compressed textures...
  453. glPixelStorei(GL_PACK_ROW_LENGTH, destwidth);
  454. gl.bindTextureToUnit(this, 0, false);
  455. bool isSRGB = false;
  456. OpenGL::TextureFormat fmt = gl.convertPixelFormat(format, false, isSRGB);
  457. // glTexSubImage and friends copy from the active pixel_unpack_buffer by
  458. // treating the pointer as a byte offset.
  459. uint8 *byteoffset = (uint8 *)(ptrdiff_t)destoffset;
  460. if (gl.isCopyTextureToBufferSupported())
  461. {
  462. if (isCompressed())
  463. glGetCompressedTextureSubImage(texture, mipmap, rect.x, rect.y, slice, rect.w, rect.h, 1, size, byteoffset);
  464. else
  465. glGetTextureSubImage(texture, mipmap, rect.x, rect.y, slice, rect.w, rect.h, 1, fmt.externalformat, fmt.type, size, byteoffset);
  466. }
  467. else if (fbo)
  468. {
  469. GLuint current_fbo = gl.getFramebuffer(OpenGL::FRAMEBUFFER_ALL);
  470. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, getFBO());
  471. if (slice > 0 || mipmap > 0)
  472. {
  473. int layer = texType == TEXTURE_CUBE ? 0 : slice;
  474. int face = texType == TEXTURE_CUBE ? slice : 0;
  475. gl.framebufferTexture(GL_COLOR_ATTACHMENT0, texType, texture, mipmap, layer, face);
  476. }
  477. glReadPixels(rect.x, rect.y, rect.w, rect.h, fmt.externalformat, fmt.type, byteoffset);
  478. if (slice > 0 || mipmap > 0)
  479. gl.framebufferTexture(GL_COLOR_ATTACHMENT0, texType, texture, 0, 0, 0);
  480. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, current_fbo);
  481. }
  482. glPixelStorei(GL_PACK_ROW_LENGTH, 0);
  483. glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
  484. }
  485. void Texture::setSamplerState(const SamplerState &s)
  486. {
  487. if (s.depthSampleMode.hasValue && !gl.isDepthCompareSampleSupported())
  488. throw love::Exception("Depth comparison sampling in shaders is not supported on this system.");
  489. // Base class does common validation and assigns samplerState.
  490. love::graphics::Texture::setSamplerState(s);
  491. auto supportedflags = OpenGL::getPixelFormatUsageFlags(getPixelFormat());
  492. if ((supportedflags & PIXELFORMATUSAGEFLAGS_LINEAR) == 0)
  493. {
  494. samplerState.magFilter = samplerState.minFilter = SamplerState::FILTER_NEAREST;
  495. if (samplerState.mipmapFilter == SamplerState::MIPMAP_FILTER_LINEAR)
  496. samplerState.mipmapFilter = SamplerState::MIPMAP_FILTER_NEAREST;
  497. }
  498. // We don't want filtering or (attempted) mipmaps on the default texture.
  499. if (usingDefaultTexture)
  500. {
  501. samplerState.mipmapFilter = SamplerState::MIPMAP_FILTER_NONE;
  502. samplerState.minFilter = samplerState.magFilter = SamplerState::FILTER_NEAREST;
  503. }
  504. // If we only have limited NPOT support then the wrap mode must be CLAMP.
  505. if ((GLAD_ES_VERSION_2_0 && !(GLAD_ES_VERSION_3_0 || GLAD_OES_texture_npot))
  506. && (pixelWidth != nextP2(pixelWidth) || pixelHeight != nextP2(pixelHeight) || depth != nextP2(depth)))
  507. {
  508. samplerState.wrapU = samplerState.wrapV = samplerState.wrapW = SamplerState::WRAP_CLAMP;
  509. }
  510. gl.bindTextureToUnit(this, 0, false);
  511. gl.setSamplerState(texType, samplerState);
  512. }
  513. ptrdiff_t Texture::getHandle() const
  514. {
  515. return texture;
  516. }
  517. ptrdiff_t Texture::getRenderTargetHandle() const
  518. {
  519. return renderTarget ? (renderbuffer != 0 ? renderbuffer : texture) : 0;
  520. }
  521. } // opengl
  522. } // graphics
  523. } // love