Texture.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968
  1. /**
  2. * Copyright (c) 2006-2020 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. return (minFilter << 0) | (magFilter << 1) | (mipmapFilter << 2)
  36. | (wrapU << 4) | (wrapV << 7) | (wrapW << 10)
  37. | (maxAnisotropy << 12) | (minLod << 16) | (maxLod << 20)
  38. | (depthSampleMode.hasValue << 24) | (depthSampleMode.value << 25)
  39. | ((uint64)conv.i << 32);
  40. }
  41. SamplerState SamplerState::fromKey(uint64 key)
  42. {
  43. const uint32 BITS_1 = 0x1;
  44. const uint32 BITS_2 = 0x3;
  45. const uint32 BITS_3 = 0x7;
  46. const uint32 BITS_4 = 0xF;
  47. SamplerState s;
  48. s.minFilter = (FilterMode) ((key >> 0) & BITS_1);
  49. s.magFilter = (FilterMode) ((key >> 1) & BITS_1);
  50. s.mipmapFilter = (MipmapFilterMode) ((key >> 2) & BITS_2);
  51. s.wrapU = (WrapMode) ((key >> 4 ) & BITS_3);
  52. s.wrapV = (WrapMode) ((key >> 7 ) & BITS_3);
  53. s.wrapW = (WrapMode) ((key >> 10) & BITS_3);
  54. s.maxAnisotropy = (key >> 12) & BITS_4;
  55. s.minLod = (key >> 16) & BITS_4;
  56. s.maxLod = (key >> 20) & BITS_4;
  57. s.depthSampleMode.hasValue = ((key >> 24) & BITS_1) != 0;
  58. s.depthSampleMode.value = (CompareMode) ((key >> 25) & BITS_4);
  59. union { float f; uint32 i; } conv;
  60. conv.i = (uint32) (key >> 32);
  61. s.lodBias = conv.f;
  62. return s;
  63. }
  64. bool SamplerState::isClampZeroOrOne(WrapMode w)
  65. {
  66. return w == WRAP_CLAMP_ONE || w == WRAP_CLAMP_ZERO;
  67. }
  68. static StringMap<SamplerState::FilterMode, SamplerState::FILTER_MAX_ENUM>::Entry filterModeEntries[] =
  69. {
  70. { "linear", SamplerState::FILTER_LINEAR },
  71. { "nearest", SamplerState::FILTER_NEAREST },
  72. };
  73. static StringMap<SamplerState::FilterMode, SamplerState::FILTER_MAX_ENUM> filterModes(filterModeEntries, sizeof(filterModeEntries));
  74. static StringMap<SamplerState::MipmapFilterMode, SamplerState::MIPMAP_FILTER_MAX_ENUM>::Entry mipmapFilterModeEntries[] =
  75. {
  76. { "none", SamplerState::MIPMAP_FILTER_NONE },
  77. { "linear", SamplerState::MIPMAP_FILTER_LINEAR },
  78. { "nearest", SamplerState::MIPMAP_FILTER_NEAREST },
  79. };
  80. static StringMap<SamplerState::MipmapFilterMode, SamplerState::MIPMAP_FILTER_MAX_ENUM> mipmapFilterModes(mipmapFilterModeEntries, sizeof(mipmapFilterModeEntries));
  81. static StringMap<SamplerState::WrapMode, SamplerState::WRAP_MAX_ENUM>::Entry wrapModeEntries[] =
  82. {
  83. { "clamp", SamplerState::WRAP_CLAMP },
  84. { "clampzero", SamplerState::WRAP_CLAMP_ZERO },
  85. { "clampone", SamplerState::WRAP_CLAMP_ONE },
  86. { "repeat", SamplerState::WRAP_REPEAT },
  87. { "mirroredrepeat", SamplerState::WRAP_MIRRORED_REPEAT },
  88. };
  89. static StringMap<SamplerState::WrapMode, SamplerState::WRAP_MAX_ENUM> wrapModes(wrapModeEntries, sizeof(wrapModeEntries));
  90. bool SamplerState::getConstant(const char *in, FilterMode &out)
  91. {
  92. return filterModes.find(in, out);
  93. }
  94. bool SamplerState::getConstant(FilterMode in, const char *&out)
  95. {
  96. return filterModes.find(in, out);
  97. }
  98. std::vector<std::string> SamplerState::getConstants(FilterMode)
  99. {
  100. return filterModes.getNames();
  101. }
  102. bool SamplerState::getConstant(const char *in, MipmapFilterMode &out)
  103. {
  104. return mipmapFilterModes.find(in, out);
  105. }
  106. bool SamplerState::getConstant(MipmapFilterMode in, const char *&out)
  107. {
  108. return mipmapFilterModes.find(in, out);
  109. }
  110. std::vector<std::string> SamplerState::getConstants(MipmapFilterMode)
  111. {
  112. return mipmapFilterModes.getNames();
  113. }
  114. bool SamplerState::getConstant(const char *in, WrapMode &out)
  115. {
  116. return wrapModes.find(in, out);
  117. }
  118. bool SamplerState::getConstant(WrapMode in, const char *&out)
  119. {
  120. return wrapModes.find(in, out);
  121. }
  122. std::vector<std::string> SamplerState::getConstants(WrapMode)
  123. {
  124. return wrapModes.getNames();
  125. }
  126. love::Type Texture::type("Texture", &Drawable::type);
  127. int Texture::textureCount = 0;
  128. int64 Texture::totalGraphicsMemory = 0;
  129. Texture::Texture(Graphics *gfx, const Settings &settings, const Slices *slices)
  130. : texType(settings.type)
  131. , format(settings.format)
  132. , renderTarget(settings.renderTarget)
  133. , readable(true)
  134. , mipmapsMode(settings.mipmaps)
  135. , sRGB(isGammaCorrect() && !settings.linear)
  136. , width(settings.width)
  137. , height(settings.height)
  138. , depth(settings.type == TEXTURE_VOLUME ? settings.layers : 1)
  139. , layers(settings.type == TEXTURE_2D_ARRAY ? settings.layers : 1)
  140. , mipmapCount(1)
  141. , pixelWidth(0)
  142. , pixelHeight(0)
  143. , requestedMSAA(settings.msaa)
  144. , samplerState()
  145. , graphicsMemorySize(0)
  146. , usingDefaultTexture(false)
  147. {
  148. if (slices != nullptr && slices->getMipmapCount() > 0 && slices->getSliceCount() > 0)
  149. {
  150. texType = slices->getTextureType();
  151. if (requestedMSAA > 1)
  152. throw love::Exception("MSAA textures cannot be created from image data.");
  153. int dataMipmaps = 1;
  154. if (slices->validate() && slices->getMipmapCount() > 1)
  155. dataMipmaps = slices->getMipmapCount();
  156. love::image::ImageDataBase *slice = slices->get(0, 0);
  157. format = slice->getFormat();
  158. pixelWidth = slice->getWidth();
  159. pixelHeight = slice->getHeight();
  160. if (texType == TEXTURE_2D_ARRAY)
  161. layers = slices->getSliceCount();
  162. else if (texType == TEXTURE_VOLUME)
  163. depth = slices->getSliceCount();
  164. width = (int) (pixelWidth / settings.dpiScale + 0.5);
  165. height = (int) (pixelHeight / settings.dpiScale + 0.5);
  166. if (isCompressed() && dataMipmaps <= 1)
  167. mipmapsMode = MIPMAPS_NONE;
  168. }
  169. else
  170. {
  171. if (isCompressed())
  172. throw love::Exception("Compressed textures must be created with initial data.");
  173. pixelWidth = (int) ((width * settings.dpiScale) + 0.5);
  174. pixelHeight = (int) ((height * settings.dpiScale) + 0.5);
  175. }
  176. if (settings.readable.hasValue)
  177. readable = settings.readable.value;
  178. else
  179. readable = !renderTarget || !isPixelFormatDepthStencil(format);
  180. format = gfx->getSizedFormat(format, renderTarget, readable, sRGB);
  181. if (mipmapsMode == MIPMAPS_AUTO && isCompressed())
  182. mipmapsMode = MIPMAPS_MANUAL;
  183. if (mipmapsMode != MIPMAPS_NONE)
  184. mipmapCount = getTotalMipmapCount(pixelWidth, pixelHeight, depth);
  185. if (pixelWidth <= 0 || pixelHeight <= 0 || layers <= 0 || depth <= 0)
  186. throw love::Exception("Texture dimensions must be greater than 0.");
  187. if (texType != TEXTURE_2D && requestedMSAA > 1)
  188. throw love::Exception("MSAA is only supported for textures with the 2D texture type.");
  189. if (!renderTarget && requestedMSAA > 1)
  190. throw love::Exception("MSAA is only supported with render target textures.");
  191. if (readable && isPixelFormatDepthStencil(format) && settings.msaa > 1)
  192. throw love::Exception("Readable depth/stencil textures with MSAA are not currently supported.");
  193. if ((!readable || settings.msaa > 1) && mipmapsMode != MIPMAPS_NONE)
  194. throw love::Exception("Non-readable and MSAA textures cannot have mipmaps.");
  195. if (!readable && texType != TEXTURE_2D)
  196. throw love::Exception("Non-readable pixel formats are only supported for 2D texture types.");
  197. if (isCompressed() && renderTarget)
  198. throw love::Exception("Compressed textures cannot be render targets.");
  199. if (!gfx->isPixelFormatSupported(format, renderTarget, readable, sRGB))
  200. {
  201. const char *fstr = "unknown";
  202. love::getConstant(format, fstr);
  203. const char *readablestr = "";
  204. if (readable != !isPixelFormatDepthStencil(format))
  205. readablestr = readable ? " readable" : " non-readable";
  206. const char *rtstr = "";
  207. if (renderTarget)
  208. rtstr = " as a render target";
  209. throw love::Exception("The %s%s pixel format is not supported%s on this system.", fstr, readablestr, rtstr);
  210. }
  211. if (!gfx->getCapabilities().textureTypes[texType])
  212. {
  213. const char *textypestr = "unknown";
  214. Texture::getConstant(texType, textypestr);
  215. throw love::Exception("%s textures are not supported on this system.", textypestr);
  216. }
  217. validateDimensions(renderTarget || !readable);
  218. samplerState = gfx->getDefaultSamplerState();
  219. Quad::Viewport v = {0, 0, (double) width, (double) height};
  220. quad.set(new Quad(v, width, height), Acquire::NORETAIN);
  221. ++textureCount;
  222. }
  223. Texture::~Texture()
  224. {
  225. --textureCount;
  226. setGraphicsMemorySize(0);
  227. }
  228. void Texture::setGraphicsMemorySize(int64 bytes)
  229. {
  230. totalGraphicsMemory = std::max(totalGraphicsMemory - graphicsMemorySize, (int64) 0);
  231. bytes = std::max(bytes, (int64) 0);
  232. graphicsMemorySize = bytes;
  233. totalGraphicsMemory += bytes;
  234. }
  235. void Texture::draw(Graphics *gfx, const Matrix4 &m)
  236. {
  237. draw(gfx, quad, m);
  238. }
  239. void Texture::draw(Graphics *gfx, Quad *q, const Matrix4 &localTransform)
  240. {
  241. using namespace vertex;
  242. if (!readable)
  243. throw love::Exception("Textures with non-readable formats cannot be drawn.");
  244. if (renderTarget && gfx->isRenderTargetActive(this))
  245. throw love::Exception("Cannot render a Texture to itself.");
  246. if (texType == TEXTURE_2D_ARRAY)
  247. {
  248. drawLayer(gfx, q->getLayer(), q, localTransform);
  249. return;
  250. }
  251. const Matrix4 &tm = gfx->getTransform();
  252. bool is2D = tm.isAffine2DTransform();
  253. Graphics::BatchedDrawCommand cmd;
  254. cmd.formats[0] = vertex::getSinglePositionFormat(is2D);
  255. cmd.formats[1] = CommonFormat::STf_RGBAub;
  256. cmd.indexMode = TriangleIndexMode::QUADS;
  257. cmd.vertexCount = 4;
  258. cmd.texture = this;
  259. Graphics::BatchedVertexData data = gfx->requestBatchedDraw(cmd);
  260. Matrix4 t(tm, localTransform);
  261. if (is2D)
  262. t.transformXY((Vector2 *) data.stream[0], q->getVertexPositions(), 4);
  263. else
  264. t.transformXY0((Vector3 *) data.stream[0], q->getVertexPositions(), 4);
  265. const Vector2 *texcoords = q->getVertexTexCoords();
  266. vertex::STf_RGBAub *vertexdata = (vertex::STf_RGBAub *) data.stream[1];
  267. Color32 c = toColor32(gfx->getColor());
  268. for (int i = 0; i < 4; i++)
  269. {
  270. vertexdata[i].s = texcoords[i].x;
  271. vertexdata[i].t = texcoords[i].y;
  272. vertexdata[i].color = c;
  273. }
  274. }
  275. void Texture::drawLayer(Graphics *gfx, int layer, const Matrix4 &m)
  276. {
  277. drawLayer(gfx, layer, quad, m);
  278. }
  279. void Texture::drawLayer(Graphics *gfx, int layer, Quad *q, const Matrix4 &m)
  280. {
  281. using namespace vertex;
  282. if (!readable)
  283. throw love::Exception("Textures with non-readable formats cannot be drawn.");
  284. if (renderTarget && gfx->isRenderTargetActive(this, layer))
  285. throw love::Exception("Cannot render a Texture to itself.");
  286. if (texType != TEXTURE_2D_ARRAY)
  287. throw love::Exception("drawLayer can only be used with Array Textures.");
  288. if (layer < 0 || layer >= layers)
  289. throw love::Exception("Invalid layer: %d (Texture has %d layers)", layer + 1, layers);
  290. Color32 c = toColor32(gfx->getColor());
  291. const Matrix4 &tm = gfx->getTransform();
  292. bool is2D = tm.isAffine2DTransform();
  293. Matrix4 t(tm, m);
  294. Graphics::BatchedDrawCommand cmd;
  295. cmd.formats[0] = vertex::getSinglePositionFormat(is2D);
  296. cmd.formats[1] = CommonFormat::STPf_RGBAub;
  297. cmd.indexMode = TriangleIndexMode::QUADS;
  298. cmd.vertexCount = 4;
  299. cmd.texture = this;
  300. cmd.standardShaderType = Shader::STANDARD_ARRAY;
  301. Graphics::BatchedVertexData data = gfx->requestBatchedDraw(cmd);
  302. if (is2D)
  303. t.transformXY((Vector2 *) data.stream[0], q->getVertexPositions(), 4);
  304. else
  305. t.transformXY0((Vector3 *) data.stream[0], q->getVertexPositions(), 4);
  306. const Vector2 *texcoords = q->getVertexTexCoords();
  307. vertex::STPf_RGBAub *vertexdata = (vertex::STPf_RGBAub *) data.stream[1];
  308. for (int i = 0; i < 4; i++)
  309. {
  310. vertexdata[i].s = texcoords[i].x;
  311. vertexdata[i].t = texcoords[i].y;
  312. vertexdata[i].p = (float) layer;
  313. vertexdata[i].color = c;
  314. }
  315. }
  316. void Texture::uploadImageData(love::image::ImageDataBase *d, int level, int slice, int x, int y)
  317. {
  318. love::image::ImageData *id = dynamic_cast<love::image::ImageData *>(d);
  319. love::thread::EmptyLock lock;
  320. if (id != nullptr)
  321. lock.setLock(id->getMutex());
  322. Rect rect = {x, y, d->getWidth(), d->getHeight()};
  323. uploadByteData(d->getFormat(), d->getData(), d->getSize(), level, slice, rect, d);
  324. }
  325. void Texture::replacePixels(love::image::ImageDataBase *d, int slice, int mipmap, int x, int y, bool reloadmipmaps)
  326. {
  327. if (!isReadable())
  328. throw love::Exception("replacePixels can only be called on readable Textures.");
  329. if (getMSAA() > 1)
  330. throw love::Exception("replacePixels cannot be called on a MSAA Texture.");
  331. auto gfx = Module::getInstance<Graphics>(Module::M_GRAPHICS);
  332. if (gfx != nullptr && gfx->isRenderTargetActive(this))
  333. throw love::Exception("replacePixels cannot be called on this Texture while it's an active render target.");
  334. // No effect if the texture hasn't been created yet.
  335. if (getHandle() == 0 || usingDefaultTexture)
  336. return;
  337. if (d->getFormat() != getPixelFormat())
  338. throw love::Exception("Pixel formats must match.");
  339. if (mipmap < 0 || mipmap >= getMipmapCount())
  340. throw love::Exception("Invalid texture mipmap index %d.", mipmap + 1);
  341. if (slice < 0 || (texType == TEXTURE_CUBE && slice >= 6)
  342. || (texType == TEXTURE_VOLUME && slice >= getDepth(mipmap))
  343. || (texType == TEXTURE_2D_ARRAY && slice >= getLayerCount()))
  344. {
  345. throw love::Exception("Invalid texture slice index %d.", slice + 1);
  346. }
  347. Rect rect = {x, y, d->getWidth(), d->getHeight()};
  348. int mipw = getPixelWidth(mipmap);
  349. int miph = getPixelHeight(mipmap);
  350. if (rect.x < 0 || rect.y < 0 || rect.w <= 0 || rect.h <= 0
  351. || (rect.x + rect.w) > mipw || (rect.y + rect.h) > miph)
  352. {
  353. 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);
  354. }
  355. // We don't currently support partial updates of compressed textures.
  356. if (isPixelFormatCompressed(d->getFormat()) && (rect.x != 0 || rect.y != 0 || rect.w != mipw || rect.h != miph))
  357. throw love::Exception("Compressed textures only support replacing the entire Texture.");
  358. Graphics::flushBatchedDrawsGlobal();
  359. uploadImageData(d, mipmap, slice, x, y);
  360. if (reloadmipmaps && mipmap == 0 && getMipmapCount() > 1)
  361. generateMipmaps();
  362. }
  363. void Texture::replacePixels(const void *data, size_t size, int slice, int mipmap, const Rect &rect, bool reloadmipmaps)
  364. {
  365. if (!isReadable() || getMSAA() > 1)
  366. return;
  367. auto gfx = Module::getInstance<Graphics>(Module::M_GRAPHICS);
  368. if (gfx != nullptr && gfx->isRenderTargetActive(this))
  369. return;
  370. Graphics::flushBatchedDrawsGlobal();
  371. uploadByteData(format, data, size, mipmap, slice, rect, nullptr);
  372. if (reloadmipmaps && mipmap == 0 && getMipmapCount() > 1)
  373. generateMipmaps();
  374. }
  375. love::image::ImageData *Texture::newImageData(love::image::Image *module, int slice, int mipmap, const Rect &r)
  376. {
  377. if (!isReadable())
  378. throw love::Exception("Texture:newImageData cannot be called on non-readable Textures.");
  379. if (!isRenderTarget())
  380. throw love::Exception("Texture:newImageData can only be called on render target Textures.");
  381. if (isPixelFormatDepthStencil(getPixelFormat()))
  382. throw love::Exception("Texture:newImageData cannot be called on Textures with depth/stencil pixel formats.");
  383. if (r.x < 0 || r.y < 0 || r.w <= 0 || r.h <= 0 || (r.x + r.w) > getPixelWidth(mipmap) || (r.y + r.h) > getPixelHeight(mipmap))
  384. throw love::Exception("Invalid rectangle dimensions.");
  385. if (slice < 0 || (texType == TEXTURE_VOLUME && slice >= getDepth(mipmap))
  386. || (texType == TEXTURE_2D_ARRAY && slice >= layers)
  387. || (texType == TEXTURE_CUBE && slice >= 6))
  388. {
  389. throw love::Exception("Invalid slice index.");
  390. }
  391. Graphics *gfx = Module::getInstance<Graphics>(Module::M_GRAPHICS);
  392. if (gfx != nullptr && gfx->isRenderTargetActive(this))
  393. throw love::Exception("Texture:newImageData cannot be called while that Texture is an active render target.");
  394. PixelFormat dataformat = getLinearPixelFormat(getPixelFormat());
  395. if (!image::ImageData::validPixelFormat(dataformat))
  396. {
  397. const char *formatname = "unknown";
  398. love::getConstant(dataformat, formatname);
  399. throw love::Exception("ImageData with the '%s' pixel format is not supported.", formatname);
  400. }
  401. return module->newImageData(r.w, r.h, dataformat);
  402. }
  403. TextureType Texture::getTextureType() const
  404. {
  405. return texType;
  406. }
  407. PixelFormat Texture::getPixelFormat() const
  408. {
  409. return format;
  410. }
  411. Texture::MipmapsMode Texture::getMipmapsMode() const
  412. {
  413. return mipmapsMode;
  414. }
  415. bool Texture::isRenderTarget() const
  416. {
  417. return renderTarget;
  418. }
  419. bool Texture::isReadable() const
  420. {
  421. return readable;
  422. }
  423. bool Texture::isCompressed() const
  424. {
  425. return isPixelFormatCompressed(format);
  426. }
  427. bool Texture::isFormatLinear() const
  428. {
  429. return isGammaCorrect() && !sRGB && !isPixelFormatSRGB(format);
  430. }
  431. bool Texture::isValidSlice(int slice) const
  432. {
  433. if (slice < 0)
  434. return false;
  435. if (texType == TEXTURE_CUBE)
  436. return slice < 6;
  437. else if (texType == TEXTURE_VOLUME)
  438. return slice < depth;
  439. else if (texType == TEXTURE_2D_ARRAY)
  440. return slice < layers;
  441. else if (slice > 0)
  442. return false;
  443. return true;
  444. }
  445. int Texture::getWidth(int mip) const
  446. {
  447. return std::max(width >> mip, 1);
  448. }
  449. int Texture::getHeight(int mip) const
  450. {
  451. return std::max(height >> mip, 1);
  452. }
  453. int Texture::getDepth(int mip) const
  454. {
  455. return std::max(depth >> mip, 1);
  456. }
  457. int Texture::getLayerCount() const
  458. {
  459. return layers;
  460. }
  461. int Texture::getMipmapCount() const
  462. {
  463. return mipmapCount;
  464. }
  465. int Texture::getPixelWidth(int mip) const
  466. {
  467. return std::max(pixelWidth >> mip, 1);
  468. }
  469. int Texture::getPixelHeight(int mip) const
  470. {
  471. return std::max(pixelHeight >> mip, 1);
  472. }
  473. float Texture::getDPIScale() const
  474. {
  475. return (float) pixelHeight / (float) height;
  476. }
  477. int Texture::getRequestedMSAA() const
  478. {
  479. return requestedMSAA;
  480. }
  481. void Texture::setSamplerState(const SamplerState &s)
  482. {
  483. if (!readable)
  484. return;
  485. if (s.depthSampleMode.hasValue && !isPixelFormatDepth(format))
  486. throw love::Exception("Only depth textures can have a depth sample compare mode.");
  487. Graphics::flushBatchedDrawsGlobal();
  488. samplerState = s;
  489. if (samplerState.mipmapFilter != SamplerState::MIPMAP_FILTER_NONE && getMipmapCount() == 1)
  490. samplerState.mipmapFilter = SamplerState::MIPMAP_FILTER_NONE;
  491. if (texType == TEXTURE_CUBE)
  492. samplerState.wrapU = samplerState.wrapV = samplerState.wrapW = SamplerState::WRAP_CLAMP;
  493. }
  494. const SamplerState &Texture::getSamplerState() const
  495. {
  496. return samplerState;
  497. }
  498. Quad *Texture::getQuad() const
  499. {
  500. return quad;
  501. }
  502. int Texture::getTotalMipmapCount(int w, int h)
  503. {
  504. return (int) log2(std::max(w, h)) + 1;
  505. }
  506. int Texture::getTotalMipmapCount(int w, int h, int d)
  507. {
  508. return (int) log2(std::max(std::max(w, h), d)) + 1;
  509. }
  510. bool Texture::validateDimensions(bool throwException) const
  511. {
  512. bool success = true;
  513. auto gfx = Module::getInstance<Graphics>(Module::M_GRAPHICS);
  514. if (gfx == nullptr)
  515. return false;
  516. const Graphics::Capabilities &caps = gfx->getCapabilities();
  517. int max2Dsize = (int) caps.limits[Graphics::LIMIT_TEXTURE_SIZE];
  518. int max3Dsize = (int) caps.limits[Graphics::LIMIT_VOLUME_TEXTURE_SIZE];
  519. int maxcubesize = (int) caps.limits[Graphics::LIMIT_CUBE_TEXTURE_SIZE];
  520. int maxlayers = (int) caps.limits[Graphics::LIMIT_TEXTURE_LAYERS];
  521. int largestdim = 0;
  522. const char *largestname = nullptr;
  523. if ((texType == TEXTURE_2D || texType == TEXTURE_2D_ARRAY) && (pixelWidth > max2Dsize || pixelHeight > max2Dsize))
  524. {
  525. success = false;
  526. largestdim = std::max(pixelWidth, pixelHeight);
  527. largestname = pixelWidth > pixelHeight ? "pixel width" : "pixel height";
  528. }
  529. else if (texType == TEXTURE_2D_ARRAY && layers > maxlayers)
  530. {
  531. success = false;
  532. largestdim = layers;
  533. largestname = "array layer count";
  534. }
  535. else if (texType == TEXTURE_CUBE && (pixelWidth > maxcubesize || pixelWidth != pixelHeight))
  536. {
  537. success = false;
  538. largestdim = std::max(pixelWidth, pixelHeight);
  539. largestname = pixelWidth > pixelHeight ? "pixel width" : "pixel height";
  540. if (throwException && pixelWidth != pixelHeight)
  541. throw love::Exception("Cubemap textures must have equal width and height.");
  542. }
  543. else if (texType == TEXTURE_VOLUME && (pixelWidth > max3Dsize || pixelHeight > max3Dsize || depth > max3Dsize))
  544. {
  545. success = false;
  546. largestdim = std::max(std::max(pixelWidth, pixelHeight), depth);
  547. if (largestdim == pixelWidth)
  548. largestname = "pixel width";
  549. else if (largestdim == pixelHeight)
  550. largestname = "pixel height";
  551. else
  552. largestname = "pixel depth";
  553. }
  554. if (throwException && largestname != nullptr)
  555. throw love::Exception("Cannot create texture: %s of %d is too large for this system.", largestname, largestdim);
  556. return success;
  557. }
  558. Texture::Slices::Slices(TextureType textype)
  559. : textureType(textype)
  560. {
  561. }
  562. void Texture::Slices::clear()
  563. {
  564. data.clear();
  565. }
  566. void Texture::Slices::set(int slice, int mipmap, love::image::ImageDataBase *d)
  567. {
  568. if (textureType == TEXTURE_VOLUME)
  569. {
  570. if (mipmap >= (int) data.size())
  571. data.resize(mipmap + 1);
  572. if (slice >= (int) data[mipmap].size())
  573. data[mipmap].resize(slice + 1);
  574. data[mipmap][slice].set(d);
  575. }
  576. else
  577. {
  578. if (slice >= (int) data.size())
  579. data.resize(slice + 1);
  580. if (mipmap >= (int) data[slice].size())
  581. data[slice].resize(mipmap + 1);
  582. data[slice][mipmap].set(d);
  583. }
  584. }
  585. love::image::ImageDataBase *Texture::Slices::get(int slice, int mipmap) const
  586. {
  587. if (slice < 0 || slice >= getSliceCount(mipmap))
  588. return nullptr;
  589. if (mipmap < 0 || mipmap >= getMipmapCount(slice))
  590. return nullptr;
  591. if (textureType == TEXTURE_VOLUME)
  592. return data[mipmap][slice].get();
  593. else
  594. return data[slice][mipmap].get();
  595. }
  596. void Texture::Slices::add(love::image::CompressedImageData *cdata, int startslice, int startmip, bool addallslices, bool addallmips)
  597. {
  598. int slicecount = addallslices ? cdata->getSliceCount() : 1;
  599. int mipcount = addallmips ? cdata->getMipmapCount() : 1;
  600. for (int mip = 0; mip < mipcount; mip++)
  601. {
  602. for (int slice = 0; slice < slicecount; slice++)
  603. set(startslice + slice, startmip + mip, cdata->getSlice(slice, mip));
  604. }
  605. }
  606. int Texture::Slices::getSliceCount(int mip) const
  607. {
  608. if (textureType == TEXTURE_VOLUME)
  609. {
  610. if (mip < 0 || mip >= (int) data.size())
  611. return 0;
  612. return (int) data[mip].size();
  613. }
  614. else
  615. return (int) data.size();
  616. }
  617. int Texture::Slices::getMipmapCount(int slice) const
  618. {
  619. if (textureType == TEXTURE_VOLUME)
  620. return (int) data.size();
  621. else
  622. {
  623. if (slice < 0 || slice >= (int) data.size())
  624. return 0;
  625. return data[slice].size();
  626. }
  627. }
  628. bool Texture::Slices::validate() const
  629. {
  630. int slicecount = getSliceCount();
  631. int mipcount = getMipmapCount(0);
  632. if (slicecount == 0 || mipcount == 0)
  633. throw love::Exception("At least one ImageData or CompressedImageData is required.");
  634. if (textureType == TEXTURE_CUBE && slicecount != 6)
  635. throw love::Exception("Cube textures must have exactly 6 sides.");
  636. image::ImageDataBase *firstdata = get(0, 0);
  637. int w = firstdata->getWidth();
  638. int h = firstdata->getHeight();
  639. int depth = textureType == TEXTURE_VOLUME ? slicecount : 1;
  640. PixelFormat format = firstdata->getFormat();
  641. int expectedmips = Texture::getTotalMipmapCount(w, h, depth);
  642. if (mipcount != expectedmips && mipcount != 1)
  643. throw love::Exception("Texture does not have all required mipmap levels (expected %d, got %d)", expectedmips, mipcount);
  644. if (textureType == TEXTURE_CUBE && w != h)
  645. throw love::Exception("Cube textures must have equal widths and heights for each cube face.");
  646. int mipw = w;
  647. int miph = h;
  648. int mipslices = slicecount;
  649. for (int mip = 0; mip < mipcount; mip++)
  650. {
  651. if (textureType == TEXTURE_VOLUME)
  652. {
  653. slicecount = getSliceCount(mip);
  654. if (slicecount != mipslices)
  655. throw love::Exception("Invalid number of image data layers in mipmap level %d (expected %d, got %d)", mip+1, mipslices, slicecount);
  656. }
  657. for (int slice = 0; slice < slicecount; slice++)
  658. {
  659. auto slicedata = get(slice, mip);
  660. if (slicedata == nullptr)
  661. throw love::Exception("Missing image data (slice %d, mipmap level %d)", slice+1, mip+1);
  662. int realw = slicedata->getWidth();
  663. int realh = slicedata->getHeight();
  664. if (getMipmapCount(slice) != mipcount)
  665. throw love::Exception("All texture layers must have the same mipmap count.");
  666. if (mipw != realw)
  667. throw love::Exception("Width of image data (slice %d, mipmap level %d) is incorrect (expected %d, got %d)", slice+1, mip+1, mipw, realw);
  668. if (miph != realh)
  669. throw love::Exception("Height of image data (slice %d, mipmap level %d) is incorrect (expected %d, got %d)", slice+1, mip+1, miph, realh);
  670. if (format != slicedata->getFormat())
  671. throw love::Exception("All texture slices and mipmaps must have the same pixel format.");
  672. }
  673. mipw = std::max(mipw / 2, 1);
  674. miph = std::max(miph / 2, 1);
  675. if (textureType == TEXTURE_VOLUME)
  676. mipslices = std::max(mipslices / 2, 1);
  677. }
  678. return true;
  679. }
  680. static StringMap<TextureType, TEXTURE_MAX_ENUM>::Entry texTypeEntries[] =
  681. {
  682. { "2d", TEXTURE_2D },
  683. { "volume", TEXTURE_VOLUME },
  684. { "array", TEXTURE_2D_ARRAY },
  685. { "cube", TEXTURE_CUBE },
  686. };
  687. static StringMap<TextureType, TEXTURE_MAX_ENUM> texTypes(texTypeEntries, sizeof(texTypeEntries));
  688. static StringMap<Texture::MipmapsMode, Texture::MIPMAPS_MAX_ENUM>::Entry mipmapEntries[] =
  689. {
  690. { "none", Texture::MIPMAPS_NONE },
  691. { "manual", Texture::MIPMAPS_MANUAL },
  692. { "auto", Texture::MIPMAPS_AUTO },
  693. };
  694. static StringMap<Texture::MipmapsMode, Texture::MIPMAPS_MAX_ENUM> mipmapModes(mipmapEntries, sizeof(mipmapEntries));
  695. static StringMap<Texture::SettingType, Texture::SETTING_MAX_ENUM>::Entry settingTypeEntries[] =
  696. {
  697. { "width", Texture::SETTING_WIDTH },
  698. { "height", Texture::SETTING_HEIGHT },
  699. { "layers", Texture::SETTING_LAYERS },
  700. { "mipmaps", Texture::SETTING_MIPMAPS },
  701. { "format", Texture::SETTING_FORMAT },
  702. { "linear", Texture::SETTING_LINEAR },
  703. { "type", Texture::SETTING_TYPE },
  704. { "dpiscale", Texture::SETTING_DPI_SCALE },
  705. { "msaa", Texture::SETTING_MSAA },
  706. { "canvas", Texture::SETTING_RENDER_TARGET },
  707. { "readable", Texture::SETTING_READABLE },
  708. };
  709. static StringMap<Texture::SettingType, Texture::SETTING_MAX_ENUM> settingTypes(settingTypeEntries, sizeof(settingTypeEntries));
  710. bool Texture::getConstant(const char *in, TextureType &out)
  711. {
  712. return texTypes.find(in, out);
  713. }
  714. bool Texture::getConstant(TextureType in, const char *&out)
  715. {
  716. return texTypes.find(in, out);
  717. }
  718. std::vector<std::string> Texture::getConstants(TextureType)
  719. {
  720. return texTypes.getNames();
  721. }
  722. bool Texture::getConstant(const char *in, MipmapsMode &out)
  723. {
  724. return mipmapModes.find(in, out);
  725. }
  726. bool Texture::getConstant(MipmapsMode in, const char *&out)
  727. {
  728. return mipmapModes.find(in, out);
  729. }
  730. std::vector<std::string> Texture::getConstants(MipmapsMode)
  731. {
  732. return mipmapModes.getNames();
  733. }
  734. bool Texture::getConstant(const char *in, SettingType &out)
  735. {
  736. return settingTypes.find(in, out);
  737. }
  738. bool Texture::getConstant(SettingType in, const char *&out)
  739. {
  740. return settingTypes.find(in, out);
  741. }
  742. const char *Texture::getConstant(SettingType in)
  743. {
  744. const char *name = nullptr;
  745. getConstant(in, name);
  746. return name;
  747. }
  748. std::vector<std::string> Texture::getConstants(SettingType)
  749. {
  750. return settingTypes.getNames();
  751. }
  752. } // graphics
  753. } // love