Texture.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176
  1. /**
  2. * Copyright (c) 2006-2024 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. // LOVE
  21. #include "common/config.h"
  22. #include "Texture.h"
  23. #include "Graphics.h"
  24. // C
  25. #include <cmath>
  26. #include <algorithm>
  27. namespace love
  28. {
  29. namespace graphics
  30. {
  31. uint64 SamplerState::toKey() const
  32. {
  33. union { float f; uint32 i; } conv;
  34. conv.f = lodBias;
  35. const uint32 BITS_4 = 0xF;
  36. return (minFilter << 0) | (magFilter << 1) | (mipmapFilter << 2)
  37. | (wrapU << 4) | (wrapV << 7) | (wrapW << 10)
  38. | (maxAnisotropy << 13) | ((BITS_4 & minLod) << 17) | ((BITS_4 & maxLod) << 21)
  39. | (depthSampleMode.hasValue << 25) | (depthSampleMode.value << 26)
  40. | ((uint64)conv.i << 32);
  41. }
  42. SamplerState SamplerState::fromKey(uint64 key)
  43. {
  44. const uint32 BITS_1 = 0x1;
  45. const uint32 BITS_2 = 0x3;
  46. const uint32 BITS_3 = 0x7;
  47. const uint32 BITS_4 = 0xF;
  48. SamplerState s;
  49. s.minFilter = (FilterMode) ((key >> 0) & BITS_1);
  50. s.magFilter = (FilterMode) ((key >> 1) & BITS_1);
  51. s.mipmapFilter = (MipmapFilterMode) ((key >> 2) & BITS_2);
  52. s.wrapU = (WrapMode) ((key >> 4 ) & BITS_3);
  53. s.wrapV = (WrapMode) ((key >> 7 ) & BITS_3);
  54. s.wrapW = (WrapMode) ((key >> 10) & BITS_3);
  55. s.maxAnisotropy = (key >> 13) & BITS_4;
  56. s.minLod = (key >> 17) & BITS_4;
  57. s.maxLod = (key >> 21) & BITS_4;
  58. s.depthSampleMode.hasValue = ((key >> 25) & BITS_1) != 0;
  59. s.depthSampleMode.value = (CompareMode) ((key >> 26) & BITS_4);
  60. union { float f; uint32 i; } conv;
  61. conv.i = (uint32) (key >> 32);
  62. s.lodBias = conv.f;
  63. return s;
  64. }
  65. bool SamplerState::isClampZeroOrOne(WrapMode w)
  66. {
  67. return w == WRAP_CLAMP_ONE || w == WRAP_CLAMP_ZERO;
  68. }
  69. static StringMap<SamplerState::FilterMode, SamplerState::FILTER_MAX_ENUM>::Entry filterModeEntries[] =
  70. {
  71. { "linear", SamplerState::FILTER_LINEAR },
  72. { "nearest", SamplerState::FILTER_NEAREST },
  73. };
  74. static StringMap<SamplerState::FilterMode, SamplerState::FILTER_MAX_ENUM> filterModes(filterModeEntries, sizeof(filterModeEntries));
  75. static StringMap<SamplerState::MipmapFilterMode, SamplerState::MIPMAP_FILTER_MAX_ENUM>::Entry mipmapFilterModeEntries[] =
  76. {
  77. { "none", SamplerState::MIPMAP_FILTER_NONE },
  78. { "linear", SamplerState::MIPMAP_FILTER_LINEAR },
  79. { "nearest", SamplerState::MIPMAP_FILTER_NEAREST },
  80. };
  81. static StringMap<SamplerState::MipmapFilterMode, SamplerState::MIPMAP_FILTER_MAX_ENUM> mipmapFilterModes(mipmapFilterModeEntries, sizeof(mipmapFilterModeEntries));
  82. static StringMap<SamplerState::WrapMode, SamplerState::WRAP_MAX_ENUM>::Entry wrapModeEntries[] =
  83. {
  84. { "clamp", SamplerState::WRAP_CLAMP },
  85. { "clampzero", SamplerState::WRAP_CLAMP_ZERO },
  86. { "clampone", SamplerState::WRAP_CLAMP_ONE },
  87. { "repeat", SamplerState::WRAP_REPEAT },
  88. { "mirroredrepeat", SamplerState::WRAP_MIRRORED_REPEAT },
  89. };
  90. static StringMap<SamplerState::WrapMode, SamplerState::WRAP_MAX_ENUM> wrapModes(wrapModeEntries, sizeof(wrapModeEntries));
  91. bool SamplerState::getConstant(const char *in, FilterMode &out)
  92. {
  93. return filterModes.find(in, out);
  94. }
  95. bool SamplerState::getConstant(FilterMode in, const char *&out)
  96. {
  97. return filterModes.find(in, out);
  98. }
  99. std::vector<std::string> SamplerState::getConstants(FilterMode)
  100. {
  101. return filterModes.getNames();
  102. }
  103. bool SamplerState::getConstant(const char *in, MipmapFilterMode &out)
  104. {
  105. return mipmapFilterModes.find(in, out);
  106. }
  107. bool SamplerState::getConstant(MipmapFilterMode in, const char *&out)
  108. {
  109. return mipmapFilterModes.find(in, out);
  110. }
  111. std::vector<std::string> SamplerState::getConstants(MipmapFilterMode)
  112. {
  113. return mipmapFilterModes.getNames();
  114. }
  115. bool SamplerState::getConstant(const char *in, WrapMode &out)
  116. {
  117. return wrapModes.find(in, out);
  118. }
  119. bool SamplerState::getConstant(WrapMode in, const char *&out)
  120. {
  121. return wrapModes.find(in, out);
  122. }
  123. std::vector<std::string> SamplerState::getConstants(WrapMode)
  124. {
  125. return wrapModes.getNames();
  126. }
  127. love::Type Texture::type("Texture", &Drawable::type);
  128. int Texture::textureCount = 0;
  129. int64 Texture::totalGraphicsMemory = 0;
  130. Texture::Texture(Graphics *gfx, const Settings &settings, const Slices *slices)
  131. : texType(settings.type)
  132. , format(settings.format)
  133. , renderTarget(settings.renderTarget)
  134. , computeWrite(settings.computeWrite)
  135. , readable(true)
  136. , viewFormats(settings.viewFormats)
  137. , mipmapsMode(settings.mipmaps)
  138. , width(settings.width)
  139. , height(settings.height)
  140. , depth(settings.type == TEXTURE_VOLUME ? settings.layers : 1)
  141. , layers(settings.type == TEXTURE_2D_ARRAY ? settings.layers : 1)
  142. , mipmapCount(1)
  143. , pixelWidth(0)
  144. , pixelHeight(0)
  145. , requestedMSAA(settings.msaa > 1 ? settings.msaa : 0)
  146. , samplerState()
  147. , graphicsMemorySize(0)
  148. , debugName(settings.debugName)
  149. , rootView({this, 0, 0})
  150. , parentView({this, 0, 0})
  151. {
  152. const auto &caps = gfx->getCapabilities();
  153. int requestedMipmapCount = settings.mipmapCount;
  154. if (slices != nullptr && slices->getMipmapCount() > 0 && slices->getSliceCount() > 0)
  155. {
  156. texType = slices->getTextureType();
  157. if (requestedMSAA > 1)
  158. throw love::Exception("MSAA textures cannot be created from image data.");
  159. int dataMipmaps = 1;
  160. if (slices->validate() && slices->getMipmapCount() > 1)
  161. {
  162. dataMipmaps = slices->getMipmapCount();
  163. if (requestedMipmapCount > 0)
  164. requestedMipmapCount = std::min(requestedMipmapCount, dataMipmaps);
  165. else
  166. requestedMipmapCount = dataMipmaps;
  167. }
  168. love::image::ImageDataBase *slice = slices->get(0, 0);
  169. format = slice->getFormat();
  170. if (isGammaCorrect() && !slice->isLinear())
  171. format = getSRGBPixelFormat(format);
  172. pixelWidth = slice->getWidth();
  173. pixelHeight = slice->getHeight();
  174. if (texType == TEXTURE_2D_ARRAY)
  175. layers = slices->getSliceCount();
  176. else if (texType == TEXTURE_VOLUME)
  177. depth = slices->getSliceCount();
  178. width = (int) (pixelWidth / settings.dpiScale + 0.5);
  179. height = (int) (pixelHeight / settings.dpiScale + 0.5);
  180. if (isCompressed() && dataMipmaps <= 1)
  181. mipmapsMode = MIPMAPS_NONE;
  182. }
  183. else
  184. {
  185. if (isCompressed())
  186. throw love::Exception("Compressed textures must be created with initial data.");
  187. pixelWidth = (int) ((width * settings.dpiScale) + 0.5);
  188. pixelHeight = (int) ((height * settings.dpiScale) + 0.5);
  189. }
  190. if (settings.readable.hasValue)
  191. readable = settings.readable.value;
  192. else
  193. readable = !renderTarget || !isPixelFormatDepthStencil(format);
  194. format = gfx->getSizedFormat(format);
  195. if (!isGammaCorrect() || settings.linear)
  196. format = getLinearPixelFormat(format);
  197. if (mipmapsMode == MIPMAPS_AUTO && isCompressed())
  198. mipmapsMode = MIPMAPS_MANUAL;
  199. if (mipmapsMode != MIPMAPS_NONE)
  200. {
  201. int totalMipmapCount = getTotalMipmapCount(pixelWidth, pixelHeight, depth);
  202. if (requestedMipmapCount > 0)
  203. mipmapCount = std::min(totalMipmapCount, requestedMipmapCount);
  204. else
  205. mipmapCount = totalMipmapCount;
  206. }
  207. const char *miperr = nullptr;
  208. if (mipmapsMode == MIPMAPS_AUTO && !supportsGenerateMipmaps(miperr))
  209. {
  210. const char *fstr = "unknown";
  211. love::getConstant(format, fstr);
  212. throw love::Exception("Automatic mipmap generation is not supported for textures with the %s pixel format.", fstr);
  213. }
  214. if (pixelWidth <= 0 || pixelHeight <= 0 || layers <= 0 || depth <= 0)
  215. throw love::Exception("Texture dimensions must be greater than 0.");
  216. if (texType != TEXTURE_2D && requestedMSAA > 1)
  217. throw love::Exception("MSAA is only supported for textures with the 2D texture type.");
  218. if (!renderTarget && requestedMSAA > 1)
  219. throw love::Exception("MSAA is only supported with render target textures.");
  220. if (readable && isPixelFormatDepthStencil(format) && settings.msaa > 1)
  221. throw love::Exception("Readable depth/stencil textures with MSAA are not currently supported.");
  222. if ((!readable || settings.msaa > 1) && mipmapsMode != MIPMAPS_NONE)
  223. throw love::Exception("Non-readable and MSAA textures cannot have mipmaps.");
  224. if (!readable && texType != TEXTURE_2D)
  225. throw love::Exception("Non-readable pixel formats are only supported for 2D texture types.");
  226. if (isCompressed() && renderTarget)
  227. throw love::Exception("Compressed textures cannot be render targets.");
  228. if (isPixelFormatDepthStencil(format) && !renderTarget)
  229. throw love::Exception("Depth or stencil pixel formats are only supported with render target textures.");
  230. if (isPixelFormatDepthStencil(format) && texType == TEXTURE_VOLUME)
  231. throw love::Exception("Volume texture types are not supported with depth or stencil pixel formats.");
  232. for (PixelFormat viewformat : viewFormats)
  233. {
  234. if (getLinearPixelFormat(viewformat) == getLinearPixelFormat(format))
  235. continue;
  236. if (isPixelFormatCompressed(format) || isPixelFormatCompressed(viewformat))
  237. throw love::Exception("Compressed textures cannot use different pixel formats for texture views, aside from sRGB versus linear variants of the same pixel format.");
  238. if (isPixelFormatColor(viewformat) != isPixelFormatColor(format))
  239. throw love::Exception("Color-format textures cannot use depth/stencil pixel formats and vice versa, in texture views.");
  240. // TODO: depth[24|32f]_stencil8 -> stencil8 can work.
  241. if (isPixelFormatDepthStencil(viewformat))
  242. throw love::Exception("Using different pixel formats for texture views is not currently supported for depth or stencil formats.");
  243. size_t viewbytes = getPixelFormatBlockSize(viewformat);
  244. size_t basebytes = getPixelFormatBlockSize(format);
  245. if (viewbytes != basebytes)
  246. throw love::Exception("Texture view pixel formats must have the same bits per pixel as the base texture's pixel format.");
  247. }
  248. validatePixelFormat(gfx);
  249. if (!caps.textureTypes[texType])
  250. {
  251. const char *textypestr = "unknown";
  252. Texture::getConstant(texType, textypestr);
  253. throw love::Exception("%s textures are not supported on this system.", textypestr);
  254. }
  255. validateDimensions(true);
  256. samplerState = gfx->getDefaultSamplerState();
  257. if (getMipmapCount() == 1)
  258. samplerState.mipmapFilter = SamplerState::MIPMAP_FILTER_NONE;
  259. Quad::Viewport v = {0, 0, (double) width, (double) height};
  260. quad.set(new Quad(v, width, height), Acquire::NORETAIN);
  261. ++textureCount;
  262. }
  263. Texture::Texture(Graphics *gfx, Texture *base, const ViewSettings &viewsettings)
  264. : texType(viewsettings.type.get(base->getTextureType()))
  265. , format(viewsettings.format.get(base->getPixelFormat()))
  266. , renderTarget(base->renderTarget)
  267. , computeWrite(base->computeWrite)
  268. , readable(base->readable)
  269. , viewFormats(base->viewFormats)
  270. , mipmapsMode(base->mipmapsMode)
  271. , width(1)
  272. , height(1)
  273. , depth(1)
  274. , layers(1)
  275. , mipmapCount(1)
  276. , pixelWidth(1)
  277. , pixelHeight(1)
  278. , requestedMSAA(base->requestedMSAA)
  279. , samplerState(base->samplerState)
  280. , quad(base->quad)
  281. , graphicsMemorySize(0)
  282. , debugName(viewsettings.debugName)
  283. , rootView({base->rootView.texture, 0, 0})
  284. , parentView({base, viewsettings.mipmapStart.get(0), viewsettings.layerStart.get(0)})
  285. {
  286. width = base->getWidth(parentView.startMipmap);
  287. height = base->getHeight(parentView.startMipmap);
  288. if (texType == TEXTURE_VOLUME)
  289. depth = base->getDepth(parentView.startMipmap);
  290. if (texType == TEXTURE_2D_ARRAY)
  291. {
  292. int baselayers = base->getTextureType() == TEXTURE_CUBE ? 6 : base->getLayerCount();
  293. layers = viewsettings.layerCount.get(baselayers - parentView.startLayer);
  294. }
  295. mipmapCount = viewsettings.mipmapCount.get(base->getMipmapCount() - parentView.startMipmap);
  296. pixelWidth = base->getPixelWidth(parentView.startMipmap);
  297. pixelHeight = base->getPixelHeight(parentView.startMipmap);
  298. if (parentView.startMipmap < 0)
  299. throw love::Exception("Invalid mipmap start value for texture view (out of range).");
  300. if (mipmapCount < 0 || parentView.startMipmap + mipmapCount > base->getMipmapCount())
  301. throw love::Exception("Invalid mipmap start or count value for texture view (out of range).");
  302. if (parentView.startLayer < 0)
  303. throw love::Exception("Invalid layer start value for texture view (out of range).");
  304. int baseLayerCount = base->getTextureType() == TEXTURE_CUBE ? 6 : base->getLayerCount();
  305. if (layers < 0 || parentView.startLayer + layers > baseLayerCount)
  306. throw love::Exception("Invalid layer start or count value for texture view (out of range).");
  307. if (texType == TEXTURE_CUBE && parentView.startLayer + 6 > baseLayerCount)
  308. throw love::Exception("Cube texture view cannot fit in the base texture's layers with the given start layer.");
  309. ViewInfo nextView = { this, 0, 0 };
  310. while (nextView.texture != rootView.texture)
  311. {
  312. nextView = nextView.texture->parentView;
  313. rootView.startMipmap += nextView.startMipmap;
  314. rootView.startLayer += nextView.startLayer;
  315. }
  316. const auto &caps = gfx->getCapabilities();
  317. if (!caps.features[Graphics::FEATURE_GLSL4])
  318. throw love::Exception("Texture views are not supported on this system (GLSL 4 support is necessary.)");
  319. validatePixelFormat(gfx);
  320. if (!caps.textureTypes[texType])
  321. {
  322. const char *textypestr = "unknown";
  323. Texture::getConstant(texType, textypestr);
  324. throw love::Exception("%s textures are not supported on this system.", textypestr);
  325. }
  326. if (!readable)
  327. throw love::Exception("Texture views are not supported for non-readable textures.");
  328. if (base->getTextureType() == TEXTURE_2D)
  329. {
  330. if (texType != TEXTURE_2D && texType != TEXTURE_2D_ARRAY)
  331. throw love::Exception("Texture views created from a 2D texture must use the 2d or array texture type.");
  332. }
  333. else if (base->getTextureType() == TEXTURE_2D_ARRAY || base->getTextureType() == TEXTURE_CUBE)
  334. {
  335. if (texType != TEXTURE_2D && texType != TEXTURE_2D_ARRAY && texType != TEXTURE_CUBE)
  336. throw love::Exception("Texture views created from an array or cube texture must use the 2d, array, or cube texture type.");
  337. }
  338. else if (base->getTextureType() == TEXTURE_VOLUME)
  339. {
  340. if (texType != TEXTURE_VOLUME)
  341. throw love::Exception("Texture views created from a volume texture must use the volume texture type.");
  342. }
  343. else
  344. {
  345. throw love::Exception("Unknown texture type.");
  346. }
  347. if (format != base->getPixelFormat())
  348. {
  349. if (std::find(viewFormats.begin(), viewFormats.end(), format) == viewFormats.end())
  350. throw love::Exception("Using a different pixel format in a texture view requires the original texture to be created with a 'viewformats' setting that includes the given format in its list.");
  351. }
  352. const char *miperr = nullptr;
  353. if (mipmapsMode == MIPMAPS_AUTO && !supportsGenerateMipmaps(miperr))
  354. mipmapsMode = MIPMAPS_MANUAL;
  355. rootView.texture->retain();
  356. parentView.texture->retain();
  357. }
  358. Texture::~Texture()
  359. {
  360. setGraphicsMemorySize(0);
  361. if (this == rootView.texture)
  362. --textureCount;
  363. if (rootView.texture != this && rootView.texture != nullptr)
  364. rootView.texture->release();
  365. if (parentView.texture != this && parentView.texture != nullptr)
  366. parentView.texture->release();
  367. }
  368. void Texture::setGraphicsMemorySize(int64 bytes)
  369. {
  370. totalGraphicsMemory = std::max(totalGraphicsMemory - graphicsMemorySize, (int64) 0);
  371. bytes = std::max(bytes, (int64) 0);
  372. graphicsMemorySize = bytes;
  373. totalGraphicsMemory += bytes;
  374. }
  375. void Texture::draw(Graphics *gfx, const Matrix4 &m)
  376. {
  377. draw(gfx, quad, m);
  378. }
  379. void Texture::draw(Graphics *gfx, Quad *q, const Matrix4 &localTransform)
  380. {
  381. if (texType == TEXTURE_2D_ARRAY)
  382. {
  383. drawLayer(gfx, q->getLayer(), q, localTransform);
  384. return;
  385. }
  386. if (!readable)
  387. throw love::Exception("Textures with non-readable formats cannot be drawn.");
  388. if (renderTarget && gfx->isRenderTargetActive(this))
  389. throw love::Exception("Cannot render a Texture to itself.");
  390. const Matrix4 &tm = gfx->getTransform();
  391. bool is2D = tm.isAffine2DTransform();
  392. Graphics::BatchedDrawCommand cmd;
  393. cmd.formats[0] = getSinglePositionFormat(is2D);
  394. cmd.formats[1] = CommonFormat::STf_RGBAub;
  395. cmd.indexMode = TRIANGLEINDEX_QUADS;
  396. cmd.vertexCount = 4;
  397. cmd.texture = this;
  398. Graphics::BatchedVertexData data = gfx->requestBatchedDraw(cmd);
  399. Matrix4 t(tm, localTransform);
  400. if (is2D)
  401. t.transformXY((Vector2 *) data.stream[0], q->getVertexPositions(), 4);
  402. else
  403. t.transformXY0((Vector3 *) data.stream[0], q->getVertexPositions(), 4);
  404. const Vector2 *texcoords = q->getVertexTexCoords();
  405. STf_RGBAub *vertexdata = (STf_RGBAub *) data.stream[1];
  406. Color32 c = toColor32(gfx->getColor());
  407. for (int i = 0; i < 4; i++)
  408. {
  409. vertexdata[i].s = texcoords[i].x;
  410. vertexdata[i].t = texcoords[i].y;
  411. vertexdata[i].color = c;
  412. }
  413. }
  414. void Texture::drawLayer(Graphics *gfx, int layer, const Matrix4 &m)
  415. {
  416. drawLayer(gfx, layer, quad, m);
  417. }
  418. void Texture::drawLayer(Graphics *gfx, int layer, Quad *q, const Matrix4 &m)
  419. {
  420. if (!readable)
  421. throw love::Exception("Textures with non-readable formats cannot be drawn.");
  422. if (renderTarget && gfx->isRenderTargetActive(this, layer))
  423. throw love::Exception("Cannot render a Texture to itself.");
  424. if (texType != TEXTURE_2D_ARRAY)
  425. throw love::Exception("drawLayer can only be used with Array Textures.");
  426. if (layer < 0 || layer >= layers)
  427. throw love::Exception("Invalid layer: %d (Texture has %d layers)", layer + 1, layers);
  428. Color32 c = toColor32(gfx->getColor());
  429. const Matrix4 &tm = gfx->getTransform();
  430. bool is2D = tm.isAffine2DTransform();
  431. Matrix4 t(tm, m);
  432. Graphics::BatchedDrawCommand cmd;
  433. cmd.formats[0] = getSinglePositionFormat(is2D);
  434. cmd.formats[1] = CommonFormat::STPf_RGBAub;
  435. cmd.indexMode = TRIANGLEINDEX_QUADS;
  436. cmd.vertexCount = 4;
  437. cmd.texture = this;
  438. cmd.standardShaderType = Shader::STANDARD_ARRAY;
  439. Graphics::BatchedVertexData data = gfx->requestBatchedDraw(cmd);
  440. if (is2D)
  441. t.transformXY((Vector2 *) data.stream[0], q->getVertexPositions(), 4);
  442. else
  443. t.transformXY0((Vector3 *) data.stream[0], q->getVertexPositions(), 4);
  444. const Vector2 *texcoords = q->getVertexTexCoords();
  445. STPf_RGBAub *vertexdata = (STPf_RGBAub *) data.stream[1];
  446. for (int i = 0; i < 4; i++)
  447. {
  448. vertexdata[i].s = texcoords[i].x;
  449. vertexdata[i].t = texcoords[i].y;
  450. vertexdata[i].p = (float) layer;
  451. vertexdata[i].color = c;
  452. }
  453. }
  454. void Texture::uploadImageData(love::image::ImageDataBase *d, int level, int slice, int x, int y)
  455. {
  456. Rect rect = {x, y, d->getWidth(), d->getHeight()};
  457. uploadByteData(d->getData(), d->getSize(), level, slice, rect);
  458. }
  459. void Texture::replacePixels(love::image::ImageDataBase *d, int slice, int mipmap, int x, int y, bool reloadmipmaps)
  460. {
  461. if (!isReadable())
  462. throw love::Exception("replacePixels can only be called on readable Textures.");
  463. if (getMSAA() > 1)
  464. throw love::Exception("replacePixels cannot be called on a MSAA Texture.");
  465. if (isPixelFormatDepthStencil(format))
  466. throw love::Exception("replacePixels cannot be called on depth or stencil Textures.");
  467. auto gfx = Module::getInstance<Graphics>(Module::M_GRAPHICS);
  468. if (gfx != nullptr && gfx->isRenderTargetActive(this))
  469. throw love::Exception("replacePixels cannot be called on this Texture while it's an active render target.");
  470. // No effect if the texture hasn't been created yet.
  471. if (getHandle() == 0)
  472. return;
  473. // ImageData format might be linear but intended to be used as sRGB, so we
  474. // don't error if only the sRGBness is different.
  475. if (getLinearPixelFormat(d->getFormat()) != getLinearPixelFormat(getPixelFormat()))
  476. throw love::Exception("Pixel formats must match.");
  477. if (mipmap < 0 || mipmap >= getMipmapCount())
  478. throw love::Exception("Invalid texture mipmap index %d.", mipmap + 1);
  479. if (slice < 0 || (texType == TEXTURE_CUBE && slice >= 6)
  480. || (texType == TEXTURE_VOLUME && slice >= getDepth(mipmap))
  481. || (texType == TEXTURE_2D_ARRAY && slice >= getLayerCount()))
  482. {
  483. throw love::Exception("Invalid texture slice index %d.", slice + 1);
  484. }
  485. Rect rect = {x, y, d->getWidth(), d->getHeight()};
  486. int mipw = getPixelWidth(mipmap);
  487. int miph = getPixelHeight(mipmap);
  488. if (rect.x < 0 || rect.y < 0 || rect.w <= 0 || rect.h <= 0
  489. || (rect.x + rect.w) > mipw || (rect.y + rect.h) > miph)
  490. {
  491. throw love::Exception("Invalid rectangle dimensions (x=%d, y=%d, w=%d, h=%d) for %dx%d Texture.", rect.x, rect.y, rect.w, rect.h, mipw, miph);
  492. }
  493. if (isPixelFormatCompressed(d->getFormat()) && (rect.x != 0 || rect.y != 0 || rect.w != mipw || rect.h != miph))
  494. {
  495. const PixelFormatInfo &info = getPixelFormatInfo(d->getFormat());
  496. int bw = (int) info.blockWidth;
  497. int bh = (int) info.blockHeight;
  498. if (rect.x % bw != 0 || rect.y % bh != 0 || rect.w % bw != 0 || rect.h % bh != 0)
  499. {
  500. const char *name = nullptr;
  501. love::getConstant(d->getFormat(), name);
  502. throw love::Exception("Compressed texture format %s only supports replacing a sub-rectangle with offset and dimensions that are a multiple of %d x %d.", name, bw, bh);
  503. }
  504. }
  505. Graphics::flushBatchedDrawsGlobal();
  506. uploadImageData(d, mipmap, slice, x, y);
  507. if (reloadmipmaps && mipmap == 0 && getMipmapCount() > 1)
  508. generateMipmaps();
  509. }
  510. void Texture::replacePixels(const void *data, size_t size, int slice, int mipmap, const Rect &rect, bool reloadmipmaps)
  511. {
  512. if (!isReadable() || getMSAA() > 1)
  513. return;
  514. auto gfx = Module::getInstance<Graphics>(Module::M_GRAPHICS);
  515. if (gfx != nullptr && gfx->isRenderTargetActive(this))
  516. return;
  517. Graphics::flushBatchedDrawsGlobal();
  518. uploadByteData(data, size, mipmap, slice, rect);
  519. if (reloadmipmaps && mipmap == 0 && getMipmapCount() > 1)
  520. generateMipmaps();
  521. }
  522. bool Texture::supportsGenerateMipmaps(const char *&outReason) const
  523. {
  524. if (getMipmapsMode() == MIPMAPS_NONE)
  525. {
  526. outReason = "generateMipmaps can only be called on a Texture which was created with mipmaps enabled.";
  527. return false;
  528. }
  529. if (isPixelFormatCompressed(format))
  530. {
  531. outReason = "generateMipmaps cannot be called on a compressed Texture.";
  532. return false;
  533. }
  534. if (isPixelFormatDepthStencil(format))
  535. {
  536. outReason = "generateMipmaps cannot be called on a depth/stencil Texture.";
  537. return false;
  538. }
  539. if (isPixelFormatInteger(format))
  540. {
  541. outReason = "generateMipmaps cannot be called on an integer Texture.";
  542. return false;
  543. }
  544. // This should be linear | rt because that's what metal needs, but the above
  545. // code handles textures can't be used as RTs in metal.
  546. auto gfx = Module::getInstance<Graphics>(Module::M_GRAPHICS);
  547. if (gfx != nullptr && !gfx->isPixelFormatSupported(format, PIXELFORMATUSAGEFLAGS_LINEAR))
  548. {
  549. outReason = "generateMipmaps cannot be called on textures with formats that don't support linear filtering on this system.";
  550. return false;
  551. }
  552. return true;
  553. }
  554. void Texture::generateMipmaps()
  555. {
  556. const char *err = nullptr;
  557. if (!supportsGenerateMipmaps(err))
  558. throw love::Exception("%s", err);
  559. auto gfx = Module::getInstance<Graphics>(Module::M_GRAPHICS);
  560. if (gfx != nullptr && gfx->isRenderTargetActive(this))
  561. throw love::Exception("generateMipmaps cannot be called on this Texture while it's an active render target.");
  562. generateMipmapsInternal();
  563. }
  564. bool Texture::isCompressed() const
  565. {
  566. return isPixelFormatCompressed(format);
  567. }
  568. bool Texture::isFormatLinear() const
  569. {
  570. return isGammaCorrect() && !isPixelFormatSRGB(format);
  571. }
  572. bool Texture::isValidSlice(int slice, int mip) const
  573. {
  574. return slice >= 0 && slice < getSliceCount(mip);
  575. }
  576. int Texture::getSliceCount(int mip) const
  577. {
  578. if (texType == TEXTURE_2D)
  579. return 1;
  580. else if (texType == TEXTURE_CUBE)
  581. return 6;
  582. else if (texType == TEXTURE_2D_ARRAY)
  583. return layers;
  584. else if (texType == TEXTURE_VOLUME)
  585. return getDepth(mip);
  586. return 1;
  587. }
  588. int Texture::getWidth(int mip) const
  589. {
  590. return std::max(width >> mip, 1);
  591. }
  592. int Texture::getHeight(int mip) const
  593. {
  594. return std::max(height >> mip, 1);
  595. }
  596. int Texture::getDepth(int mip) const
  597. {
  598. return std::max(depth >> mip, 1);
  599. }
  600. int Texture::getLayerCount() const
  601. {
  602. return layers;
  603. }
  604. int Texture::getMipmapCount() const
  605. {
  606. return mipmapCount;
  607. }
  608. int Texture::getPixelWidth(int mip) const
  609. {
  610. return std::max(pixelWidth >> mip, 1);
  611. }
  612. int Texture::getPixelHeight(int mip) const
  613. {
  614. return std::max(pixelHeight >> mip, 1);
  615. }
  616. float Texture::getDPIScale() const
  617. {
  618. return (float) pixelHeight / (float) height;
  619. }
  620. int Texture::getRequestedMSAA() const
  621. {
  622. return requestedMSAA;
  623. }
  624. const SamplerState &Texture::getSamplerState() const
  625. {
  626. return samplerState;
  627. }
  628. SamplerState Texture::validateSamplerState(SamplerState s) const
  629. {
  630. if (!readable)
  631. return s;
  632. if (s.depthSampleMode.hasValue && !isPixelFormatDepth(format))
  633. throw love::Exception("Only depth textures can have a depth sample compare mode.");
  634. if (s.mipmapFilter != SamplerState::MIPMAP_FILTER_NONE && getMipmapCount() == 1)
  635. s.mipmapFilter = SamplerState::MIPMAP_FILTER_NONE;
  636. if (texType == TEXTURE_CUBE)
  637. s.wrapU = s.wrapV = s.wrapW = SamplerState::WRAP_CLAMP;
  638. if (s.minFilter == SamplerState::FILTER_LINEAR || s.magFilter == SamplerState::FILTER_LINEAR || s.mipmapFilter == SamplerState::MIPMAP_FILTER_LINEAR)
  639. {
  640. auto gfx = Module::getInstance<Graphics>(Module::M_GRAPHICS);
  641. if (!gfx->isPixelFormatSupported(format, PIXELFORMATUSAGEFLAGS_LINEAR))
  642. {
  643. s.minFilter = s.magFilter = SamplerState::FILTER_NEAREST;
  644. if (s.mipmapFilter == SamplerState::MIPMAP_FILTER_LINEAR)
  645. s.mipmapFilter = SamplerState::MIPMAP_FILTER_NEAREST;
  646. }
  647. }
  648. Graphics::flushBatchedDrawsGlobal();
  649. return s;
  650. }
  651. Quad *Texture::getQuad() const
  652. {
  653. return quad;
  654. }
  655. int Texture::getTotalMipmapCount(int w, int h)
  656. {
  657. return (int) log2(std::max(w, h)) + 1;
  658. }
  659. int Texture::getTotalMipmapCount(int w, int h, int d)
  660. {
  661. return (int) log2(std::max(std::max(w, h), d)) + 1;
  662. }
  663. bool Texture::validateDimensions(bool throwException) const
  664. {
  665. bool success = true;
  666. auto gfx = Module::getInstance<Graphics>(Module::M_GRAPHICS);
  667. if (gfx == nullptr)
  668. return false;
  669. const Graphics::Capabilities &caps = gfx->getCapabilities();
  670. int max2Dsize = (int) caps.limits[Graphics::LIMIT_TEXTURE_SIZE];
  671. int max3Dsize = (int) caps.limits[Graphics::LIMIT_VOLUME_TEXTURE_SIZE];
  672. int maxcubesize = (int) caps.limits[Graphics::LIMIT_CUBE_TEXTURE_SIZE];
  673. int maxlayers = (int) caps.limits[Graphics::LIMIT_TEXTURE_LAYERS];
  674. int largestdim = 0;
  675. const char *largestname = nullptr;
  676. if ((texType == TEXTURE_2D || texType == TEXTURE_2D_ARRAY) && (pixelWidth > max2Dsize || pixelHeight > max2Dsize))
  677. {
  678. success = false;
  679. largestdim = std::max(pixelWidth, pixelHeight);
  680. largestname = pixelWidth > pixelHeight ? "pixel width" : "pixel height";
  681. }
  682. else if (texType == TEXTURE_2D_ARRAY && layers > maxlayers)
  683. {
  684. success = false;
  685. largestdim = layers;
  686. largestname = "array layer count";
  687. }
  688. else if (texType == TEXTURE_CUBE && (pixelWidth > maxcubesize || pixelWidth != pixelHeight))
  689. {
  690. success = false;
  691. largestdim = std::max(pixelWidth, pixelHeight);
  692. largestname = pixelWidth > pixelHeight ? "pixel width" : "pixel height";
  693. if (throwException && pixelWidth != pixelHeight)
  694. throw love::Exception("Cubemap textures must have equal width and height.");
  695. }
  696. else if (texType == TEXTURE_VOLUME && (pixelWidth > max3Dsize || pixelHeight > max3Dsize || depth > max3Dsize))
  697. {
  698. success = false;
  699. largestdim = std::max(std::max(pixelWidth, pixelHeight), depth);
  700. if (largestdim == pixelWidth)
  701. largestname = "pixel width";
  702. else if (largestdim == pixelHeight)
  703. largestname = "pixel height";
  704. else
  705. largestname = "pixel depth";
  706. }
  707. if (throwException && largestname != nullptr)
  708. throw love::Exception("Cannot create texture: %s of %d is too large for this system.", largestname, largestdim);
  709. return success;
  710. }
  711. void Texture::validatePixelFormat(Graphics *gfx) const
  712. {
  713. uint32 usage = PIXELFORMATUSAGEFLAGS_NONE;
  714. if (renderTarget)
  715. usage |= PIXELFORMATUSAGEFLAGS_RENDERTARGET;
  716. if (readable)
  717. usage |= PIXELFORMATUSAGEFLAGS_SAMPLE;
  718. if (computeWrite)
  719. usage |= PIXELFORMATUSAGEFLAGS_COMPUTEWRITE;
  720. if (!gfx->isPixelFormatSupported(format, (PixelFormatUsageFlags) usage))
  721. {
  722. const char *fstr = "unknown";
  723. love::getConstant(format, fstr);
  724. const char *readablestr = "";
  725. if (readable != !isPixelFormatDepthStencil(format))
  726. readablestr = readable ? " readable" : " non-readable";
  727. const char *rtstr = "";
  728. if (computeWrite)
  729. rtstr = " as a compute shader-writable texture";
  730. else if (renderTarget)
  731. rtstr = " as a render target";
  732. throw love::Exception("The %s%s pixel format is not supported%s on this system.", fstr, readablestr, rtstr);
  733. }
  734. }
  735. Texture::Slices::Slices(TextureType textype)
  736. : textureType(textype)
  737. {
  738. }
  739. void Texture::Slices::clear()
  740. {
  741. data.clear();
  742. }
  743. void Texture::Slices::set(int slice, int mipmap, love::image::ImageDataBase *d)
  744. {
  745. if (textureType == TEXTURE_VOLUME)
  746. {
  747. if (mipmap >= (int) data.size())
  748. data.resize(mipmap + 1);
  749. if (slice >= (int) data[mipmap].size())
  750. data[mipmap].resize(slice + 1);
  751. data[mipmap][slice].set(d);
  752. }
  753. else
  754. {
  755. if (slice >= (int) data.size())
  756. data.resize(slice + 1);
  757. if (mipmap >= (int) data[slice].size())
  758. data[slice].resize(mipmap + 1);
  759. data[slice][mipmap].set(d);
  760. }
  761. }
  762. love::image::ImageDataBase *Texture::Slices::get(int slice, int mipmap) const
  763. {
  764. if (slice < 0 || slice >= getSliceCount(mipmap))
  765. return nullptr;
  766. if (mipmap < 0 || mipmap >= getMipmapCount(slice))
  767. return nullptr;
  768. if (textureType == TEXTURE_VOLUME)
  769. return data[mipmap][slice].get();
  770. else
  771. return data[slice][mipmap].get();
  772. }
  773. void Texture::Slices::add(love::image::CompressedImageData *cdata, int startslice, int startmip, bool addallslices, bool addallmips)
  774. {
  775. int slicecount = addallslices ? cdata->getSliceCount() : 1;
  776. int mipcount = addallmips ? cdata->getMipmapCount() : 1;
  777. for (int mip = 0; mip < mipcount; mip++)
  778. {
  779. for (int slice = 0; slice < slicecount; slice++)
  780. set(startslice + slice, startmip + mip, cdata->getSlice(slice, mip));
  781. }
  782. }
  783. int Texture::Slices::getSliceCount(int mip) const
  784. {
  785. if (textureType == TEXTURE_VOLUME)
  786. {
  787. if (mip < 0 || mip >= (int) data.size())
  788. return 0;
  789. return (int) data[mip].size();
  790. }
  791. else
  792. return (int) data.size();
  793. }
  794. int Texture::Slices::getMipmapCount(int slice) const
  795. {
  796. if (textureType == TEXTURE_VOLUME)
  797. return (int) data.size();
  798. else
  799. {
  800. if (slice < 0 || slice >= (int) data.size())
  801. return 0;
  802. return data[slice].size();
  803. }
  804. }
  805. bool Texture::Slices::validate() const
  806. {
  807. int slicecount = getSliceCount();
  808. int mipcount = getMipmapCount(0);
  809. if (slicecount == 0 || mipcount == 0)
  810. throw love::Exception("At least one ImageData or CompressedImageData is required.");
  811. if (textureType == TEXTURE_CUBE && slicecount != 6)
  812. throw love::Exception("Cube textures must have exactly 6 sides.");
  813. image::ImageDataBase *firstdata = get(0, 0);
  814. int w = firstdata->getWidth();
  815. int h = firstdata->getHeight();
  816. PixelFormat format = firstdata->getFormat();
  817. bool linear = firstdata->isLinear();
  818. if (textureType == TEXTURE_CUBE && w != h)
  819. throw love::Exception("Cube textures must have equal widths and heights for each cube face.");
  820. int mipw = w;
  821. int miph = h;
  822. int mipslices = slicecount;
  823. for (int mip = 0; mip < mipcount; mip++)
  824. {
  825. if (textureType == TEXTURE_VOLUME)
  826. {
  827. slicecount = getSliceCount(mip);
  828. if (slicecount != mipslices)
  829. throw love::Exception("Invalid number of image data layers in mipmap level %d (expected %d, got %d)", mip+1, mipslices, slicecount);
  830. }
  831. for (int slice = 0; slice < slicecount; slice++)
  832. {
  833. auto slicedata = get(slice, mip);
  834. if (slicedata == nullptr)
  835. throw love::Exception("Missing image data (slice %d, mipmap level %d)", slice+1, mip+1);
  836. int realw = slicedata->getWidth();
  837. int realh = slicedata->getHeight();
  838. if (getMipmapCount(slice) != mipcount)
  839. throw love::Exception("All texture layers must have the same mipmap count.");
  840. if (mipw != realw)
  841. throw love::Exception("Width of image data (slice %d, mipmap level %d) is incorrect (expected %d, got %d)", slice+1, mip+1, mipw, realw);
  842. if (miph != realh)
  843. throw love::Exception("Height of image data (slice %d, mipmap level %d) is incorrect (expected %d, got %d)", slice+1, mip+1, miph, realh);
  844. if (format != slicedata->getFormat())
  845. throw love::Exception("All texture slices and mipmaps must have the same pixel format.");
  846. if (linear != slicedata->isLinear())
  847. throw love::Exception("All texture slices and mipmaps must have the same linear setting.");
  848. }
  849. mipw = std::max(mipw / 2, 1);
  850. miph = std::max(miph / 2, 1);
  851. if (textureType == TEXTURE_VOLUME)
  852. mipslices = std::max(mipslices / 2, 1);
  853. }
  854. return true;
  855. }
  856. static StringMap<TextureType, TEXTURE_MAX_ENUM>::Entry texTypeEntries[] =
  857. {
  858. { "2d", TEXTURE_2D },
  859. { "volume", TEXTURE_VOLUME },
  860. { "array", TEXTURE_2D_ARRAY },
  861. { "cube", TEXTURE_CUBE },
  862. };
  863. static StringMap<TextureType, TEXTURE_MAX_ENUM> texTypes(texTypeEntries, sizeof(texTypeEntries));
  864. static StringMap<Texture::MipmapsMode, Texture::MIPMAPS_MAX_ENUM>::Entry mipmapEntries[] =
  865. {
  866. { "none", Texture::MIPMAPS_NONE },
  867. { "manual", Texture::MIPMAPS_MANUAL },
  868. { "auto", Texture::MIPMAPS_AUTO },
  869. };
  870. static StringMap<Texture::MipmapsMode, Texture::MIPMAPS_MAX_ENUM> mipmapModes(mipmapEntries, sizeof(mipmapEntries));
  871. static StringMap<Texture::SettingType, Texture::SETTING_MAX_ENUM>::Entry settingTypeEntries[] =
  872. {
  873. { "width", Texture::SETTING_WIDTH },
  874. { "height", Texture::SETTING_HEIGHT },
  875. { "layers", Texture::SETTING_LAYERS },
  876. { "mipmaps", Texture::SETTING_MIPMAPS },
  877. { "mipmapcount", Texture::SETTING_MIPMAP_COUNT },
  878. { "format", Texture::SETTING_FORMAT },
  879. { "linear", Texture::SETTING_LINEAR },
  880. { "type", Texture::SETTING_TYPE },
  881. { "dpiscale", Texture::SETTING_DPI_SCALE },
  882. { "msaa", Texture::SETTING_MSAA },
  883. { "canvas", Texture::SETTING_RENDER_TARGET },
  884. { "computewrite", Texture::SETTING_COMPUTE_WRITE },
  885. { "viewformats", Texture::SETTING_VIEW_FORMATS },
  886. { "readable", Texture::SETTING_READABLE },
  887. { "debugname", Texture::SETTING_DEBUGNAME },
  888. };
  889. static StringMap<Texture::SettingType, Texture::SETTING_MAX_ENUM> settingTypes(settingTypeEntries, sizeof(settingTypeEntries));
  890. bool Texture::getConstant(const char *in, TextureType &out)
  891. {
  892. return texTypes.find(in, out);
  893. }
  894. bool Texture::getConstant(TextureType in, const char *&out)
  895. {
  896. return texTypes.find(in, out);
  897. }
  898. std::vector<std::string> Texture::getConstants(TextureType)
  899. {
  900. return texTypes.getNames();
  901. }
  902. bool Texture::getConstant(const char *in, MipmapsMode &out)
  903. {
  904. return mipmapModes.find(in, out);
  905. }
  906. bool Texture::getConstant(MipmapsMode in, const char *&out)
  907. {
  908. return mipmapModes.find(in, out);
  909. }
  910. std::vector<std::string> Texture::getConstants(MipmapsMode)
  911. {
  912. return mipmapModes.getNames();
  913. }
  914. bool Texture::getConstant(const char *in, SettingType &out)
  915. {
  916. return settingTypes.find(in, out);
  917. }
  918. bool Texture::getConstant(SettingType in, const char *&out)
  919. {
  920. return settingTypes.find(in, out);
  921. }
  922. const char *Texture::getConstant(SettingType in)
  923. {
  924. const char *name = nullptr;
  925. getConstant(in, name);
  926. return name;
  927. }
  928. std::vector<std::string> Texture::getConstants(SettingType)
  929. {
  930. return settingTypes.getNames();
  931. }
  932. } // graphics
  933. } // love