imgui_sdl.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. #include "imgui_sdl.h"
  2. #if defined(WIN32) || defined(WIN64) || defined(_WIN32) || defined(_WIN64)
  3. #include <SDL.h>
  4. #else
  5. #include <SDL2/SDL.h>
  6. #endif
  7. #include "imgui.h"
  8. #include <map>
  9. #include <list>
  10. #include <cmath>
  11. #include <array>
  12. #include <vector>
  13. #include <memory>
  14. #include <iostream>
  15. #include <algorithm>
  16. #include <functional>
  17. #include <unordered_map>
  18. namespace
  19. {
  20. struct Device* CurrentDevice = nullptr;
  21. namespace TupleHash
  22. {
  23. template <typename T> struct Hash
  24. {
  25. std::size_t operator()(const T& value) const
  26. {
  27. return std::hash<T>()(value);
  28. }
  29. };
  30. template <typename T> void CombineHash(std::size_t& seed, const T& value)
  31. {
  32. seed ^= TupleHash::Hash<T>()(value) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
  33. }
  34. template <typename Tuple, std::size_t Index = std::tuple_size<Tuple>::value - 1> struct Hasher
  35. {
  36. static void Hash(std::size_t& seed, const Tuple& tuple)
  37. {
  38. Hasher<Tuple, Index - 1>::Hash(seed, tuple);
  39. CombineHash(seed, std::get<Index>(tuple));
  40. }
  41. };
  42. template <typename Tuple> struct Hasher<Tuple, 0>
  43. {
  44. static void Hash(std::size_t& seed, const Tuple& tuple)
  45. {
  46. CombineHash(seed, std::get<0>(tuple));
  47. }
  48. };
  49. template <typename... T> struct Hash<std::tuple<T...>>
  50. {
  51. std::size_t operator()(const std::tuple<T...>& value) const
  52. {
  53. std::size_t seed = 0;
  54. Hasher<std::tuple<T...>>::Hash(seed, value);
  55. return seed;
  56. }
  57. };
  58. }
  59. template <typename Key, typename Value, std::size_t Size> class LRUCache
  60. {
  61. public:
  62. bool Contains(const Key& key) const
  63. {
  64. return Container.find(key) != Container.end();
  65. }
  66. const Value& At(const Key& key)
  67. {
  68. assert(Contains(key));
  69. const auto location = Container.find(key);
  70. Order.splice(Order.begin(), Order, location->second);
  71. return location->second->second;
  72. }
  73. void Insert(const Key& key, Value value)
  74. {
  75. const auto existingLocation = Container.find(key);
  76. if (existingLocation != Container.end())
  77. {
  78. Order.erase(existingLocation->second);
  79. Container.erase(existingLocation);
  80. }
  81. Order.push_front(std::make_pair(key, std::move(value)));
  82. Container.insert(std::make_pair(key, Order.begin()));
  83. Clean();
  84. }
  85. private:
  86. void Clean()
  87. {
  88. while (Container.size() > Size)
  89. {
  90. auto last = Order.end();
  91. last--;
  92. Container.erase(last->first);
  93. Order.pop_back();
  94. }
  95. }
  96. std::list<std::pair<Key, Value>> Order;
  97. std::unordered_map<Key, decltype(Order.begin()), TupleHash::Hash<Key>> Container;
  98. };
  99. struct Color
  100. {
  101. const float R, G, B, A;
  102. explicit Color(uint32_t color)
  103. : R(((color >> 0) & 0xff) / 255.0f), G(((color >> 8) & 0xff) / 255.0f), B(((color >> 16) & 0xff) / 255.0f), A(((color >> 24) & 0xff) / 255.0f) { }
  104. Color(float r, float g, float b, float a) : R(r), G(g), B(b), A(a) { }
  105. Color operator*(const Color& c) const { return Color(R * c.R, G * c.G, B * c.B, A * c.A); }
  106. Color operator*(float v) const { return Color(R * v, G * v, B * v, A * v); }
  107. Color operator+(const Color& c) const { return Color(R + c.R, G + c.G, B + c.B, A + c.A); }
  108. uint32_t ToInt() const
  109. {
  110. return ((static_cast<int>(R * 255) & 0xff) << 0)
  111. | ((static_cast<int>(G * 255) & 0xff) << 8)
  112. | ((static_cast<int>(B * 255) & 0xff) << 16)
  113. | ((static_cast<int>(A * 255) & 0xff) << 24);
  114. }
  115. void UseAsDrawColor(SDL_Renderer* renderer) const
  116. {
  117. SDL_SetRenderDrawColor(renderer,
  118. static_cast<uint8_t>(R * 255),
  119. static_cast<uint8_t>(G * 255),
  120. static_cast<uint8_t>(B * 255),
  121. static_cast<uint8_t>(A * 255));
  122. }
  123. };
  124. struct Device
  125. {
  126. SDL_Renderer* Renderer;
  127. struct ClipRect
  128. {
  129. int X, Y, Width, Height;
  130. } Clip;
  131. struct TriangleCacheItem
  132. {
  133. SDL_Texture* Texture = nullptr;
  134. int Width = 0, Height = 0;
  135. ~TriangleCacheItem() { if (Texture) SDL_DestroyTexture(Texture); }
  136. };
  137. // You can tweak these to values that you find that work the best.
  138. static constexpr std::size_t UniformColorTriangleCacheSize = 512;
  139. static constexpr std::size_t GenericTriangleCacheSize = 64;
  140. // Uniform color is identified by its color and the coordinates of the edges.
  141. using UniformColorTriangleKey = std::tuple<uint32_t, int, int, int, int, int, int>;
  142. // The generic triangle cache unfortunately has to be basically a full representation of the triangle.
  143. // This includes the (offset) vertex positions, texture coordinates and vertex colors.
  144. using GenericTriangleVertexKey = std::tuple<int, int, double, double, uint32_t>;
  145. using GenericTriangleKey = std::tuple<GenericTriangleVertexKey, GenericTriangleVertexKey, GenericTriangleVertexKey>;
  146. LRUCache<UniformColorTriangleKey, std::unique_ptr<TriangleCacheItem>, UniformColorTriangleCacheSize> UniformColorTriangleCache;
  147. LRUCache<GenericTriangleKey, std::unique_ptr<TriangleCacheItem>, GenericTriangleCacheSize> GenericTriangleCache;
  148. Device(SDL_Renderer* renderer) : Renderer(renderer) { }
  149. void SetClipRect(const ClipRect& rect)
  150. {
  151. Clip = rect;
  152. const SDL_Rect clip = { rect.X, rect.Y, rect.Width, rect.Height };
  153. SDL_RenderSetClipRect(Renderer, &clip);
  154. }
  155. void EnableClip() { SetClipRect(Clip); }
  156. void DisableClip() { SDL_RenderSetClipRect(Renderer, nullptr); }
  157. void SetAt(int x, int y, const Color& color)
  158. {
  159. color.UseAsDrawColor(Renderer);
  160. SDL_RenderDrawPoint(Renderer, x, y);
  161. }
  162. SDL_Texture* MakeTexture(int width, int height)
  163. {
  164. SDL_Texture* texture = SDL_CreateTexture(Renderer, SDL_PIXELFORMAT_RGBA32, SDL_TEXTUREACCESS_TARGET, width, height);
  165. SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND);
  166. return texture;
  167. }
  168. void UseAsRenderTarget(SDL_Texture* texture)
  169. {
  170. SDL_SetRenderTarget(Renderer, texture);
  171. if (texture)
  172. {
  173. SDL_SetRenderDrawColor(Renderer, 0, 0, 0, 0);
  174. SDL_RenderClear(Renderer);
  175. }
  176. }
  177. };
  178. struct Texture
  179. {
  180. SDL_Surface* Surface;
  181. SDL_Texture* Source;
  182. ~Texture()
  183. {
  184. SDL_FreeSurface(Surface);
  185. SDL_DestroyTexture(Source);
  186. }
  187. Color Sample(float u, float v) const
  188. {
  189. const int x = static_cast<int>(std::round(u * (Surface->w - 1) + 0.5f));
  190. const int y = static_cast<int>(std::round(v * (Surface->h - 1) + 0.5f));
  191. const int location = y * Surface->w + x;
  192. assert(location < Surface->w * Surface->h);
  193. return Color(static_cast<uint32_t*>(Surface->pixels)[location]);
  194. }
  195. };
  196. template <typename T> class InterpolatedFactorEquation
  197. {
  198. public:
  199. InterpolatedFactorEquation(const T& value0, const T& value1, const T& value2, const ImVec2& v0, const ImVec2& v1, const ImVec2& v2)
  200. : Value0(value0), Value1(value1), Value2(value2), V0(v0), V1(v1), V2(v2),
  201. Divisor((V1.y - V2.y) * (V0.x - V2.x) + (V2.x - V1.x) * (V0.y - V2.y)) { }
  202. T Evaluate(float x, float y) const
  203. {
  204. const float w1 = ((V1.y - V2.y) * (x - V2.x) + (V2.x - V1.x) * (y - V2.y)) / Divisor;
  205. const float w2 = ((V2.y - V0.y) * (x - V2.x) + (V0.x - V2.x) * (y - V2.y)) / Divisor;
  206. const float w3 = 1.0f - w1 - w2;
  207. return static_cast<T>((Value0 * w1) + (Value1 * w2) + (Value2 * w3));
  208. }
  209. private:
  210. const T Value0;
  211. const T Value1;
  212. const T Value2;
  213. const ImVec2& V0;
  214. const ImVec2& V1;
  215. const ImVec2& V2;
  216. const float Divisor;
  217. };
  218. struct Rect
  219. {
  220. float MinX, MinY, MaxX, MaxY;
  221. float MinU, MinV, MaxU, MaxV;
  222. bool IsOnExtreme(const ImVec2& point) const
  223. {
  224. return (point.x == MinX || point.x == MaxX) && (point.y == MinY || point.y == MaxY);
  225. }
  226. bool UsesOnlyColor() const
  227. {
  228. const ImVec2& whitePixel = ImGui::GetIO().Fonts->TexUvWhitePixel;
  229. return MinU == MaxU && MinU == whitePixel.x && MinV == MaxV && MaxV == whitePixel.y;
  230. }
  231. static Rect CalculateBoundingBox(const ImDrawVert& v0, const ImDrawVert& v1, const ImDrawVert& v2)
  232. {
  233. return Rect{
  234. std::min({ v0.pos.x, v1.pos.x, v2.pos.x }),
  235. std::min({ v0.pos.y, v1.pos.y, v2.pos.y }),
  236. std::max({ v0.pos.x, v1.pos.x, v2.pos.x }),
  237. std::max({ v0.pos.y, v1.pos.y, v2.pos.y }),
  238. std::min({ v0.uv.x, v1.uv.x, v2.uv.x }),
  239. std::min({ v0.uv.y, v1.uv.y, v2.uv.y }),
  240. std::max({ v0.uv.x, v1.uv.x, v2.uv.x }),
  241. std::max({ v0.uv.y, v1.uv.y, v2.uv.y })
  242. };
  243. }
  244. };
  245. struct FixedPointTriangleRenderInfo
  246. {
  247. int X1, X2, X3, Y1, Y2, Y3;
  248. int MinX, MaxX, MinY, MaxY;
  249. static FixedPointTriangleRenderInfo CalculateFixedPointTriangleInfo(const ImVec2& v1, const ImVec2& v2, const ImVec2& v3)
  250. {
  251. static constexpr float scale = 16.0f;
  252. const int x1 = static_cast<int>(std::round(v1.x * scale));
  253. const int x2 = static_cast<int>(std::round(v2.x * scale));
  254. const int x3 = static_cast<int>(std::round(v3.x * scale));
  255. const int y1 = static_cast<int>(std::round(v1.y * scale));
  256. const int y2 = static_cast<int>(std::round(v2.y * scale));
  257. const int y3 = static_cast<int>(std::round(v3.y * scale));
  258. int minX = (std::min({ x1, x2, x3 }) + 0xF) >> 4;
  259. int maxX = (std::max({ x1, x2, x3 }) + 0xF) >> 4;
  260. int minY = (std::min({ y1, y2, y3 }) + 0xF) >> 4;
  261. int maxY = (std::max({ y1, y2, y3 }) + 0xF) >> 4;
  262. return FixedPointTriangleRenderInfo{ x1, x2, x3, y1, y2, y3, minX, maxX, minY, maxY };
  263. }
  264. };
  265. void DrawTriangleWithColorFunction(const FixedPointTriangleRenderInfo& renderInfo, const std::function<Color(float x, float y)>& colorFunction, Device::TriangleCacheItem* cacheItem)
  266. {
  267. // Implementation source: https://web.archive.org/web/20171128164608/http://forum.devmaster.net/t/advanced-rasterization/6145.
  268. // This is a fixed point implementation that rounds to top-left.
  269. const int deltaX12 = renderInfo.X1 - renderInfo.X2;
  270. const int deltaX23 = renderInfo.X2 - renderInfo.X3;
  271. const int deltaX31 = renderInfo.X3 - renderInfo.X1;
  272. const int deltaY12 = renderInfo.Y1 - renderInfo.Y2;
  273. const int deltaY23 = renderInfo.Y2 - renderInfo.Y3;
  274. const int deltaY31 = renderInfo.Y3 - renderInfo.Y1;
  275. const int fixedDeltaX12 = deltaX12 << 4;
  276. const int fixedDeltaX23 = deltaX23 << 4;
  277. const int fixedDeltaX31 = deltaX31 << 4;
  278. const int fixedDeltaY12 = deltaY12 << 4;
  279. const int fixedDeltaY23 = deltaY23 << 4;
  280. const int fixedDeltaY31 = deltaY31 << 4;
  281. const int width = renderInfo.MaxX - renderInfo.MinX;
  282. const int height = renderInfo.MaxY - renderInfo.MinY;
  283. if (width == 0 || height == 0) return;
  284. int c1 = deltaY12 * renderInfo.X1 - deltaX12 * renderInfo.Y1;
  285. int c2 = deltaY23 * renderInfo.X2 - deltaX23 * renderInfo.Y2;
  286. int c3 = deltaY31 * renderInfo.X3 - deltaX31 * renderInfo.Y3;
  287. if (deltaY12 < 0 || (deltaY12 == 0 && deltaX12 > 0)) c1++;
  288. if (deltaY23 < 0 || (deltaY23 == 0 && deltaX23 > 0)) c2++;
  289. if (deltaY31 < 0 || (deltaY31 == 0 && deltaX31 > 0)) c3++;
  290. int edgeStart1 = c1 + deltaX12 * (renderInfo.MinY << 4) - deltaY12 * (renderInfo.MinX << 4);
  291. int edgeStart2 = c2 + deltaX23 * (renderInfo.MinY << 4) - deltaY23 * (renderInfo.MinX << 4);
  292. int edgeStart3 = c3 + deltaX31 * (renderInfo.MinY << 4) - deltaY31 * (renderInfo.MinX << 4);
  293. SDL_Texture* cache = CurrentDevice->MakeTexture(width, height);
  294. CurrentDevice->DisableClip();
  295. CurrentDevice->UseAsRenderTarget(cache);
  296. for (int y = renderInfo.MinY; y < renderInfo.MaxY; y++)
  297. {
  298. int edge1 = edgeStart1;
  299. int edge2 = edgeStart2;
  300. int edge3 = edgeStart3;
  301. for (int x = renderInfo.MinX; x < renderInfo.MaxX; x++)
  302. {
  303. if (edge1 > 0 && edge2 > 0 && edge3 > 0)
  304. {
  305. CurrentDevice->SetAt(x - renderInfo.MinX, y - renderInfo.MinY, colorFunction(x + 0.5f, y + 0.5f));
  306. }
  307. edge1 -= fixedDeltaY12;
  308. edge2 -= fixedDeltaY23;
  309. edge3 -= fixedDeltaY31;
  310. }
  311. edgeStart1 += fixedDeltaX12;
  312. edgeStart2 += fixedDeltaX23;
  313. edgeStart3 += fixedDeltaX31;
  314. }
  315. CurrentDevice->UseAsRenderTarget(nullptr);
  316. CurrentDevice->EnableClip();
  317. cacheItem->Texture = cache;
  318. cacheItem->Width = width;
  319. cacheItem->Height = height;
  320. }
  321. void DrawCachedTriangle(const Device::TriangleCacheItem& triangle, const FixedPointTriangleRenderInfo& renderInfo)
  322. {
  323. const SDL_Rect destination = { renderInfo.MinX, renderInfo.MinY, triangle.Width, triangle.Height };
  324. SDL_RenderCopy(CurrentDevice->Renderer, triangle.Texture, nullptr, &destination);
  325. }
  326. void DrawTriangle(const ImDrawVert& v1, const ImDrawVert& v2, const ImDrawVert& v3, const Texture* texture)
  327. {
  328. // The naming inconsistency in the parameters is intentional. The fixed point algorithm wants the vertices in a counter clockwise order.
  329. const auto& renderInfo = FixedPointTriangleRenderInfo::CalculateFixedPointTriangleInfo(v3.pos, v2.pos, v1.pos);
  330. // First we check if there is a cached version of this triangle already waiting for us. If so, we can just do a super fast texture copy.
  331. const auto key = std::make_tuple(
  332. std::make_tuple(static_cast<int>(std::round(v1.pos.x)) - renderInfo.MinX, static_cast<int>(std::round(v1.pos.y)) - renderInfo.MinY, v1.uv.x, v1.uv.y, v1.col),
  333. std::make_tuple(static_cast<int>(std::round(v2.pos.x)) - renderInfo.MinX, static_cast<int>(std::round(v2.pos.y)) - renderInfo.MinY, v2.uv.x, v2.uv.y, v2.col),
  334. std::make_tuple(static_cast<int>(std::round(v3.pos.x)) - renderInfo.MinX, static_cast<int>(std::round(v3.pos.y)) - renderInfo.MinY, v3.uv.x, v3.uv.y, v3.col));
  335. if (CurrentDevice->GenericTriangleCache.Contains(key))
  336. {
  337. const auto& cached = CurrentDevice->GenericTriangleCache.At(key);
  338. DrawCachedTriangle(*cached, renderInfo);
  339. return;
  340. }
  341. const InterpolatedFactorEquation<float> textureU(v1.uv.x, v2.uv.x, v3.uv.x, v1.pos, v2.pos, v3.pos);
  342. const InterpolatedFactorEquation<float> textureV(v1.uv.y, v2.uv.y, v3.uv.y, v1.pos, v2.pos, v3.pos);
  343. const InterpolatedFactorEquation<Color> shadeColor(Color(v1.col), Color(v2.col), Color(v3.col), v1.pos, v2.pos, v3.pos);
  344. auto cached = std::make_unique<Device::TriangleCacheItem>();
  345. DrawTriangleWithColorFunction(renderInfo, [&](float x, float y) {
  346. const float u = textureU.Evaluate(x, y);
  347. const float v = textureV.Evaluate(x, y);
  348. const Color sampled = texture->Sample(u, v);
  349. const Color shade = shadeColor.Evaluate(x, y);
  350. return sampled * shade;
  351. }, cached.get());
  352. if (!cached->Texture) return;
  353. const SDL_Rect destination = { renderInfo.MinX, renderInfo.MinY, cached->Width, cached->Height };
  354. SDL_RenderCopy(CurrentDevice->Renderer, cached->Texture, nullptr, &destination);
  355. CurrentDevice->GenericTriangleCache.Insert(key, std::move(cached));
  356. }
  357. void DrawUniformColorTriangle(const ImDrawVert& v1, const ImDrawVert& v2, const ImDrawVert& v3)
  358. {
  359. const Color color(v1.col);
  360. // The naming inconsistency in the parameters is intentional. The fixed point algorithm wants the vertices in a counter clockwise order.
  361. const auto& renderInfo = FixedPointTriangleRenderInfo::CalculateFixedPointTriangleInfo(v3.pos, v2.pos, v1.pos);
  362. const auto key =std::make_tuple(v1.col,
  363. static_cast<int>(std::round(v1.pos.x)) - renderInfo.MinX, static_cast<int>(std::round(v1.pos.y)) - renderInfo.MinY,
  364. static_cast<int>(std::round(v2.pos.x)) - renderInfo.MinX, static_cast<int>(std::round(v2.pos.y)) - renderInfo.MinY,
  365. static_cast<int>(std::round(v3.pos.x)) - renderInfo.MinX, static_cast<int>(std::round(v3.pos.y)) - renderInfo.MinY);
  366. if (CurrentDevice->UniformColorTriangleCache.Contains(key))
  367. {
  368. const auto& cached = CurrentDevice->UniformColorTriangleCache.At(key);
  369. DrawCachedTriangle(*cached, renderInfo);
  370. return;
  371. }
  372. auto cached = std::make_unique<Device::TriangleCacheItem>();
  373. DrawTriangleWithColorFunction(renderInfo, [&color](float, float) { return color; }, cached.get());
  374. if (!cached->Texture) return;
  375. const SDL_Rect destination = { renderInfo.MinX, renderInfo.MinY, cached->Width, cached->Height };
  376. SDL_RenderCopy(CurrentDevice->Renderer, cached->Texture, nullptr, &destination);
  377. CurrentDevice->UniformColorTriangleCache.Insert(key, std::move(cached));
  378. }
  379. void DrawRectangle(const Rect& bounding, SDL_Texture* texture, int textureWidth, int textureHeight, const Color& color, bool doHorizontalFlip, bool doVerticalFlip)
  380. {
  381. // We are safe to assume uniform color here, because the caller checks it and and uses the triangle renderer to render those.
  382. const SDL_Rect destination = {
  383. static_cast<int>(bounding.MinX),
  384. static_cast<int>(bounding.MinY),
  385. static_cast<int>(bounding.MaxX - bounding.MinX),
  386. static_cast<int>(bounding.MaxY - bounding.MinY)
  387. };
  388. // If the area isn't textured, we can just draw a rectangle with the correct color.
  389. if (bounding.UsesOnlyColor())
  390. {
  391. color.UseAsDrawColor(CurrentDevice->Renderer);
  392. SDL_RenderFillRect(CurrentDevice->Renderer, &destination);
  393. }
  394. else
  395. {
  396. // We can now just calculate the correct source rectangle and draw it.
  397. const SDL_Rect source = {
  398. static_cast<int>(bounding.MinU * textureWidth),
  399. static_cast<int>(bounding.MinV * textureHeight),
  400. static_cast<int>((bounding.MaxU - bounding.MinU) * textureWidth),
  401. static_cast<int>((bounding.MaxV - bounding.MinV) * textureHeight)
  402. };
  403. const SDL_RendererFlip flip = static_cast<SDL_RendererFlip>((doHorizontalFlip ? SDL_FLIP_HORIZONTAL : 0) | (doVerticalFlip ? SDL_FLIP_VERTICAL : 0));
  404. SDL_SetTextureColorMod(texture, static_cast<uint8_t>(color.R * 255), static_cast<uint8_t>(color.G * 255), static_cast<uint8_t>(color.B * 255));
  405. SDL_RenderCopyEx(CurrentDevice->Renderer, texture, &source, &destination, 0.0, nullptr, flip);
  406. }
  407. }
  408. void DrawRectangle(const Rect& bounding, const Texture* texture, const Color& color, bool doHorizontalFlip, bool doVerticalFlip)
  409. {
  410. DrawRectangle(bounding, texture->Source, texture->Surface->w, texture->Surface->h, color, doHorizontalFlip, doVerticalFlip);
  411. }
  412. void DrawRectangle(const Rect& bounding, SDL_Texture* texture, const Color& color, bool doHorizontalFlip, bool doVerticalFlip)
  413. {
  414. int width, height;
  415. SDL_QueryTexture(texture, nullptr, nullptr, &width, &height);
  416. DrawRectangle(bounding, texture, width, height, color, doHorizontalFlip, doVerticalFlip);
  417. }
  418. }
  419. namespace ImGuiSDL
  420. {
  421. void Initialize(SDL_Renderer* renderer, int windowWidth, int windowHeight)
  422. {
  423. ImGuiIO& io = ImGui::GetIO();
  424. io.DisplaySize.x = static_cast<float>(windowWidth);
  425. io.DisplaySize.y = static_cast<float>(windowHeight);
  426. ImGui::GetStyle().WindowRounding = 0.0f;
  427. ImGui::GetStyle().AntiAliasedFill = false;
  428. ImGui::GetStyle().AntiAliasedLines = false;
  429. // Loads the font texture.
  430. unsigned char* pixels;
  431. int width, height;
  432. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  433. static constexpr uint32_t rmask = 0x000000ff, gmask = 0x0000ff00, bmask = 0x00ff0000, amask = 0xff000000;
  434. SDL_Surface* surface = SDL_CreateRGBSurfaceFrom(pixels, width, height, 32, 4 * width, rmask, gmask, bmask, amask);
  435. Texture* texture = new Texture();
  436. texture->Surface = surface;
  437. texture->Source = SDL_CreateTextureFromSurface(renderer, surface);
  438. io.Fonts->TexID = (void*)texture;
  439. CurrentDevice = new Device(renderer);
  440. }
  441. void Deinitialize()
  442. {
  443. // Frees up the memory of the font texture.
  444. ImGuiIO& io = ImGui::GetIO();
  445. Texture* texture = static_cast<Texture*>(io.Fonts->TexID);
  446. delete texture;
  447. delete CurrentDevice;
  448. }
  449. void Render(ImDrawData* drawData)
  450. {
  451. SDL_BlendMode blendMode;
  452. SDL_GetRenderDrawBlendMode(CurrentDevice->Renderer, &blendMode);
  453. SDL_SetRenderDrawBlendMode(CurrentDevice->Renderer, SDL_BLENDMODE_BLEND);
  454. Uint8 initialR, initialG, initialB, initialA;
  455. SDL_GetRenderDrawColor(CurrentDevice->Renderer, &initialR, &initialG, &initialB, &initialA);
  456. SDL_bool initialClipEnabled = SDL_RenderIsClipEnabled(CurrentDevice->Renderer);
  457. SDL_Rect initialClipRect;
  458. SDL_RenderGetClipRect(CurrentDevice->Renderer, &initialClipRect);
  459. SDL_Texture* initialRenderTarget = SDL_GetRenderTarget(CurrentDevice->Renderer);
  460. ImGuiIO& io = ImGui::GetIO();
  461. for (int n = 0; n < drawData->CmdListsCount; n++)
  462. {
  463. auto commandList = drawData->CmdLists[n];
  464. auto vertexBuffer = commandList->VtxBuffer;
  465. auto indexBuffer = commandList->IdxBuffer.Data;
  466. for (int cmd_i = 0; cmd_i < commandList->CmdBuffer.Size; cmd_i++)
  467. {
  468. const ImDrawCmd* drawCommand = &commandList->CmdBuffer[cmd_i];
  469. const Device::ClipRect clipRect = {
  470. static_cast<int>(drawCommand->ClipRect.x),
  471. static_cast<int>(drawCommand->ClipRect.y),
  472. static_cast<int>(drawCommand->ClipRect.z - drawCommand->ClipRect.x),
  473. static_cast<int>(drawCommand->ClipRect.w - drawCommand->ClipRect.y)
  474. };
  475. CurrentDevice->SetClipRect(clipRect);
  476. if (drawCommand->UserCallback)
  477. {
  478. drawCommand->UserCallback(commandList, drawCommand);
  479. }
  480. else
  481. {
  482. const bool isWrappedTexture = drawCommand->TextureId == io.Fonts->TexID;
  483. // Loops over triangles.
  484. for (unsigned int i = 0; i + 3 <= drawCommand->ElemCount; i += 3)
  485. {
  486. const ImDrawVert& v0 = vertexBuffer[indexBuffer[i + 0]];
  487. const ImDrawVert& v1 = vertexBuffer[indexBuffer[i + 1]];
  488. const ImDrawVert& v2 = vertexBuffer[indexBuffer[i + 2]];
  489. const Rect& bounding = Rect::CalculateBoundingBox(v0, v1, v2);
  490. const bool isTriangleUniformColor = v0.col == v1.col && v1.col == v2.col;
  491. const bool doesTriangleUseOnlyColor = bounding.UsesOnlyColor();
  492. // Actually, since we render a whole bunch of rectangles, we try to first detect those, and render them more efficiently.
  493. // How are rectangles detected? It's actually pretty simple: If all 6 vertices lie on the extremes of the bounding box,
  494. // it's a rectangle.
  495. if (i + 6 <= drawCommand->ElemCount)
  496. {
  497. const ImDrawVert& v3 = vertexBuffer[indexBuffer[i + 3]];
  498. const ImDrawVert& v4 = vertexBuffer[indexBuffer[i + 4]];
  499. const ImDrawVert& v5 = vertexBuffer[indexBuffer[i + 5]];
  500. const bool isUniformColor = isTriangleUniformColor && v2.col == v3.col && v3.col == v4.col && v4.col == v5.col;
  501. if (isUniformColor
  502. && bounding.IsOnExtreme(v0.pos)
  503. && bounding.IsOnExtreme(v1.pos)
  504. && bounding.IsOnExtreme(v2.pos)
  505. && bounding.IsOnExtreme(v3.pos)
  506. && bounding.IsOnExtreme(v4.pos)
  507. && bounding.IsOnExtreme(v5.pos))
  508. {
  509. // ImGui gives the triangles in a nice order: the first vertex happens to be the topleft corner of our rectangle.
  510. // We need to check for the orientation of the texture, as I believe in theory ImGui could feed us a flipped texture,
  511. // so that the larger texture coordinates are at topleft instead of bottomright.
  512. // We don't consider equal texture coordinates to require a flip, as then the rectangle is mostlikely simply a colored rectangle.
  513. const bool doHorizontalFlip = v2.uv.x < v0.uv.x;
  514. const bool doVerticalFlip = v2.uv.x < v0.uv.x;
  515. if (isWrappedTexture)
  516. {
  517. DrawRectangle(bounding, static_cast<const Texture*>(drawCommand->TextureId), Color(v0.col), doHorizontalFlip, doVerticalFlip);
  518. }
  519. else
  520. {
  521. DrawRectangle(bounding, static_cast<SDL_Texture*>(drawCommand->TextureId), Color(v0.col), doHorizontalFlip, doVerticalFlip);
  522. }
  523. i += 3; // Additional increment to account for the extra 3 vertices we consumed.
  524. continue;
  525. }
  526. }
  527. if (isTriangleUniformColor && doesTriangleUseOnlyColor)
  528. {
  529. DrawUniformColorTriangle(v0, v1, v2);
  530. }
  531. else
  532. {
  533. // Currently we assume that any non rectangular texture samples the font texture. Dunno if that's what actually happens, but it seems to work.
  534. assert(isWrappedTexture);
  535. DrawTriangle(v0, v1, v2, static_cast<const Texture*>(drawCommand->TextureId));
  536. }
  537. }
  538. }
  539. indexBuffer += drawCommand->ElemCount;
  540. }
  541. }
  542. CurrentDevice->DisableClip();
  543. SDL_SetRenderTarget(CurrentDevice->Renderer, initialRenderTarget);
  544. SDL_RenderSetClipRect(CurrentDevice->Renderer, initialClipEnabled ? &initialClipRect : nullptr);
  545. SDL_SetRenderDrawColor(CurrentDevice->Renderer,
  546. initialR, initialG, initialB, initialA);
  547. SDL_SetRenderDrawBlendMode(CurrentDevice->Renderer, blendMode);
  548. }
  549. }