OGLGraphics.cpp 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "AnimatedModel.h"
  24. #include "Animation.h"
  25. #include "AnimationController.h"
  26. #include "BillboardSet.h"
  27. #include "Camera.h"
  28. #include "Context.h"
  29. #include "CustomGeometry.h"
  30. #include "DebugRenderer.h"
  31. #include "DecalSet.h"
  32. #include "File.h"
  33. #include "Graphics.h"
  34. #include "GraphicsEvents.h"
  35. #include "GraphicsImpl.h"
  36. #include "IndexBuffer.h"
  37. #include "Log.h"
  38. #include "Material.h"
  39. #include "Mutex.h"
  40. #include "Octree.h"
  41. #include "ParticleEmitter.h"
  42. #include "ProcessUtils.h"
  43. #include "Profiler.h"
  44. #include "RenderSurface.h"
  45. #include "ResourceCache.h"
  46. #include "Shader.h"
  47. #include "ShaderPrecache.h"
  48. #include "ShaderProgram.h"
  49. #include "ShaderVariation.h"
  50. #include "Skybox.h"
  51. #include "StaticModelGroup.h"
  52. #include "Technique.h"
  53. #include "Terrain.h"
  54. #include "TerrainPatch.h"
  55. #include "Texture2D.h"
  56. #include "Texture3D.h"
  57. #include "TextureCube.h"
  58. #include "VertexBuffer.h"
  59. #include "Zone.h"
  60. #include <stdio.h>
  61. #include "DebugNew.h"
  62. #ifdef GL_ES_VERSION_2_0
  63. #define GL_DEPTH_COMPONENT24 GL_DEPTH_COMPONENT24_OES
  64. #define GL_FRAMEBUFFER_EXT GL_FRAMEBUFFER
  65. #define GL_RENDERBUFFER_EXT GL_RENDERBUFFER
  66. #define GL_COLOR_ATTACHMENT0_EXT GL_COLOR_ATTACHMENT0
  67. #define GL_DEPTH_ATTACHMENT_EXT GL_DEPTH_ATTACHMENT
  68. #define GL_STENCIL_ATTACHMENT_EXT GL_STENCIL_ATTACHMENT
  69. #define GL_FRAMEBUFFER_COMPLETE_EXT GL_FRAMEBUFFER_COMPLETE
  70. #define glClearDepth glClearDepthf
  71. #define glBindFramebufferEXT glBindFramebuffer
  72. #define glFramebufferTexture2DEXT glFramebufferTexture2D
  73. #define glFramebufferRenderbufferEXT glFramebufferRenderbuffer
  74. #define glGenFramebuffersEXT glGenFramebuffers
  75. #define glDeleteFramebuffersEXT glDeleteFramebuffers
  76. #define glCheckFramebufferStatusEXT glCheckFramebufferStatus
  77. #endif
  78. #ifdef WIN32
  79. // On Intel / NVIDIA setups prefer the NVIDIA GPU
  80. #include <windows.h>
  81. extern "C" {
  82. __declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
  83. }
  84. #endif
  85. namespace Urho3D
  86. {
  87. static const unsigned glCmpFunc[] =
  88. {
  89. GL_ALWAYS,
  90. GL_EQUAL,
  91. GL_NOTEQUAL,
  92. GL_LESS,
  93. GL_LEQUAL,
  94. GL_GREATER,
  95. GL_GEQUAL
  96. };
  97. static const unsigned glSrcBlend[] =
  98. {
  99. GL_ONE,
  100. GL_ONE,
  101. GL_DST_COLOR,
  102. GL_SRC_ALPHA,
  103. GL_SRC_ALPHA,
  104. GL_ONE,
  105. GL_ONE_MINUS_DST_ALPHA,
  106. GL_ONE,
  107. GL_SRC_ALPHA
  108. };
  109. static const unsigned glDestBlend[] =
  110. {
  111. GL_ZERO,
  112. GL_ONE,
  113. GL_ZERO,
  114. GL_ONE_MINUS_SRC_ALPHA,
  115. GL_ONE,
  116. GL_ONE_MINUS_SRC_ALPHA,
  117. GL_DST_ALPHA,
  118. GL_ONE,
  119. GL_ONE
  120. };
  121. static const unsigned glBlendOp[] =
  122. {
  123. GL_FUNC_ADD,
  124. GL_FUNC_ADD,
  125. GL_FUNC_ADD,
  126. GL_FUNC_ADD,
  127. GL_FUNC_ADD,
  128. GL_FUNC_ADD,
  129. GL_FUNC_ADD,
  130. GL_FUNC_REVERSE_SUBTRACT,
  131. GL_FUNC_REVERSE_SUBTRACT
  132. };
  133. #ifndef GL_ES_VERSION_2_0
  134. static const unsigned glFillMode[] =
  135. {
  136. GL_FILL,
  137. GL_LINE,
  138. GL_POINT
  139. };
  140. #endif
  141. static const unsigned glStencilOps[] =
  142. {
  143. GL_KEEP,
  144. GL_ZERO,
  145. GL_REPLACE,
  146. GL_INCR_WRAP,
  147. GL_DECR_WRAP
  148. };
  149. // Remap vertex attributes on OpenGL so that all usually needed attributes including skinning fit to the first 8.
  150. // This avoids a skinning bug on GLES2 devices which only support 8.
  151. static const unsigned glVertexAttrIndex[] =
  152. {
  153. 0, 1, 2, 3, 4, 8, 9, 5, 6, 7, 10, 11, 12
  154. };
  155. static const unsigned MAX_FRAMEBUFFER_AGE = 2000;
  156. #ifdef GL_ES_VERSION_2_0
  157. static unsigned glesDepthStencilFormat = GL_DEPTH_COMPONENT16;
  158. #endif
  159. bool CheckExtension(String& extensions, const String& name)
  160. {
  161. if (extensions.Empty())
  162. extensions = (const char*)glGetString(GL_EXTENSIONS);
  163. return extensions.Contains(name);
  164. }
  165. Graphics::Graphics(Context* context_) :
  166. Object(context_),
  167. impl_(new GraphicsImpl()),
  168. windowIcon_(0),
  169. externalWindow_(0),
  170. width_(0),
  171. height_(0),
  172. multiSample_(1),
  173. fullscreen_(false),
  174. borderless_(false),
  175. resizable_(false),
  176. vsync_(false),
  177. tripleBuffer_(false),
  178. sRGB_(false),
  179. instancingSupport_(false),
  180. lightPrepassSupport_(false),
  181. deferredSupport_(false),
  182. anisotropySupport_(false),
  183. dxtTextureSupport_(false),
  184. etcTextureSupport_(false),
  185. pvrtcTextureSupport_(false),
  186. sRGBSupport_(false),
  187. sRGBWriteSupport_(false),
  188. numPrimitives_(0),
  189. numBatches_(0),
  190. maxScratchBufferRequest_(0),
  191. dummyColorFormat_(0),
  192. shadowMapFormat_(GL_DEPTH_COMPONENT16),
  193. hiresShadowMapFormat_(GL_DEPTH_COMPONENT24),
  194. defaultTextureFilterMode_(FILTER_BILINEAR),
  195. releasingGPUObjects_(false),
  196. shaderPath_("Shaders/GLSL/"),
  197. shaderExtension_(".glsl"),
  198. orientations_("LandscapeLeft LandscapeRight")
  199. {
  200. SetTextureUnitMappings();
  201. ResetCachedState();
  202. // Initialize SDL now. Graphics should be the first SDL-using subsystem to be created
  203. SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER | SDL_INIT_NOPARACHUTE);
  204. // Register Graphics library object factories
  205. RegisterGraphicsLibrary(context_);
  206. }
  207. Graphics::~Graphics()
  208. {
  209. Close();
  210. delete impl_;
  211. impl_ = 0;
  212. // Shut down SDL now. Graphics should be the last SDL-using subsystem to be destroyed
  213. SDL_Quit();
  214. }
  215. void Graphics::SetExternalWindow(void* window)
  216. {
  217. if (!impl_->window_)
  218. externalWindow_ = window;
  219. else
  220. LOGERROR("Window already opened, can not set external window");
  221. }
  222. void Graphics::SetWindowTitle(const String& windowTitle)
  223. {
  224. windowTitle_ = windowTitle;
  225. if (impl_->window_)
  226. SDL_SetWindowTitle(impl_->window_, windowTitle_.CString());
  227. }
  228. void Graphics::SetWindowIcon(Image* windowIcon)
  229. {
  230. windowIcon_ = windowIcon;
  231. if (impl_->window_)
  232. CreateWindowIcon();
  233. }
  234. void Graphics::SetWindowPosition(const IntVector2& position)
  235. {
  236. if (impl_->window_)
  237. SDL_SetWindowPosition(impl_->window_, position.x_, position.y_);
  238. }
  239. void Graphics::SetWindowPosition(int x, int y)
  240. {
  241. SetWindowPosition(IntVector2(x, y));
  242. }
  243. bool Graphics::SetMode(int width, int height, bool fullscreen, bool borderless, bool resizable, bool vsync, bool tripleBuffer, int multiSample)
  244. {
  245. PROFILE(SetScreenMode);
  246. bool maximize = false;
  247. // Fullscreen or Borderless can not be resizable
  248. if (fullscreen || borderless)
  249. resizable = false;
  250. // Borderless cannot be fullscreen, they are mutually exclusive
  251. if (borderless)
  252. fullscreen = false;
  253. multiSample = Clamp(multiSample, 1, 16);
  254. if (IsInitialized() && width == width_ && height == height_ && fullscreen == fullscreen_ && borderless == borderless_ && resizable == resizable_ &&
  255. vsync == vsync_ && tripleBuffer == tripleBuffer_ && multiSample == multiSample_)
  256. return true;
  257. // If only vsync changes, do not destroy/recreate the context
  258. if (IsInitialized() && width == width_ && height == height_ && fullscreen == fullscreen_ && borderless == borderless_ && resizable == resizable_ &&
  259. tripleBuffer == tripleBuffer_ && multiSample == multiSample_ && vsync != vsync_)
  260. {
  261. SDL_GL_SetSwapInterval(vsync ? 1 : 0);
  262. vsync_ = vsync;
  263. return true;
  264. }
  265. // If zero dimensions in windowed mode, set windowed mode to maximize and set a predefined default restored window size. If zero in fullscreen, use desktop mode
  266. if (!width || !height)
  267. {
  268. if (fullscreen || borderless)
  269. {
  270. SDL_DisplayMode mode;
  271. SDL_GetDesktopDisplayMode(0, &mode);
  272. width = mode.w;
  273. height = mode.h;
  274. }
  275. else
  276. {
  277. maximize = resizable;
  278. width = 1024;
  279. height = 768;
  280. }
  281. }
  282. // Check fullscreen mode validity (desktop only). If not valid, revert to windowed
  283. #if !defined(ANDROID) && !defined(IOS) && !defined(RASPI)
  284. if (fullscreen)
  285. {
  286. PODVector<IntVector2> resolutions = GetResolutions();
  287. fullscreen = false;
  288. for (unsigned i = 0; i < resolutions.Size(); ++i)
  289. {
  290. if (width == resolutions[i].x_ && height == resolutions[i].y_)
  291. {
  292. fullscreen = true;
  293. break;
  294. }
  295. }
  296. }
  297. #endif
  298. String extensions;
  299. // With an external window, only the size can change after initial setup, so do not recreate context
  300. if (!externalWindow_ || !impl_->context_)
  301. {
  302. // Close the existing window and OpenGL context, mark GPU objects as lost
  303. Release(false, true);
  304. #ifdef IOS
  305. // On iOS window needs to be resizable to handle orientation changes properly
  306. resizable = true;
  307. #endif
  308. SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
  309. #ifndef GL_ES_VERSION_2_0
  310. SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
  311. SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
  312. SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
  313. SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
  314. if (externalWindow_)
  315. SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
  316. else
  317. SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 0);
  318. SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
  319. #endif
  320. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
  321. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
  322. if (multiSample > 1)
  323. {
  324. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
  325. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, multiSample);
  326. }
  327. else
  328. {
  329. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);
  330. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);
  331. }
  332. int x = fullscreen ? 0 : SDL_WINDOWPOS_UNDEFINED;
  333. int y = fullscreen ? 0 : SDL_WINDOWPOS_UNDEFINED;
  334. unsigned flags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
  335. if (fullscreen)
  336. flags |= SDL_WINDOW_FULLSCREEN;
  337. if (resizable)
  338. flags |= SDL_WINDOW_RESIZABLE;
  339. if (borderless)
  340. flags |= SDL_WINDOW_BORDERLESS;
  341. SDL_SetHint(SDL_HINT_ORIENTATIONS, orientations_.CString());
  342. for (;;)
  343. {
  344. if (!externalWindow_)
  345. impl_->window_ = SDL_CreateWindow(windowTitle_.CString(), x, y, width, height, flags);
  346. else
  347. {
  348. if (!impl_->window_)
  349. impl_->window_ = SDL_CreateWindowFrom(externalWindow_, SDL_WINDOW_OPENGL);
  350. fullscreen = false;
  351. }
  352. if (impl_->window_)
  353. break;
  354. else
  355. {
  356. if (multiSample > 1)
  357. {
  358. // If failed with multisampling, retry first without
  359. multiSample = 1;
  360. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);
  361. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);
  362. }
  363. else
  364. {
  365. LOGERROR("Could not open window");
  366. return false;
  367. }
  368. }
  369. }
  370. CreateWindowIcon();
  371. if (maximize)
  372. {
  373. Maximize();
  374. SDL_GetWindowSize(impl_->window_, &width, &height);
  375. }
  376. // Create/restore context and GPU objects and set initial renderstate
  377. Restore();
  378. if (!impl_->context_)
  379. {
  380. LOGERROR("Could not create OpenGL context");
  381. return false;
  382. }
  383. // If OpenGL extensions not yet initialized, initialize now
  384. #ifndef GL_ES_VERSION_2_0
  385. GLenum err = glewInit();
  386. if (GLEW_OK != err)
  387. {
  388. LOGERROR("Cannot initialize OpenGL");
  389. Release(true, true);
  390. return false;
  391. }
  392. if (!GLEW_VERSION_2_0)
  393. {
  394. LOGERROR("OpenGL 2.0 is required");
  395. Release(true, true);
  396. return false;
  397. }
  398. if (!GLEW_EXT_framebuffer_object || !GLEW_EXT_packed_depth_stencil)
  399. {
  400. LOGERROR("EXT_framebuffer_object and EXT_packed_depth_stencil OpenGL extensions are required");
  401. Release(true, true);
  402. return false;
  403. }
  404. instancingSupport_ = GLEW_ARB_instanced_arrays != 0;
  405. dxtTextureSupport_ = GLEW_EXT_texture_compression_s3tc != 0;
  406. anisotropySupport_ = GLEW_EXT_texture_filter_anisotropic != 0;
  407. sRGBSupport_ = GLEW_EXT_texture_sRGB != 0;
  408. sRGBWriteSupport_ = GLEW_EXT_framebuffer_sRGB != 0;
  409. // Set up instancing divisors if supported
  410. if (instancingSupport_)
  411. {
  412. glVertexAttribDivisorARB(ELEMENT_INSTANCEMATRIX1, 1);
  413. glVertexAttribDivisorARB(ELEMENT_INSTANCEMATRIX2, 1);
  414. glVertexAttribDivisorARB(ELEMENT_INSTANCEMATRIX3, 1);
  415. }
  416. #else
  417. dxtTextureSupport_ = CheckExtension(extensions, "EXT_texture_compression_dxt1");
  418. etcTextureSupport_ = CheckExtension(extensions, "OES_compressed_ETC1_RGB8_texture");
  419. pvrtcTextureSupport_ = CheckExtension(extensions, "IMG_texture_compression_pvrtc");
  420. #endif
  421. // Set up texture data read/write alignment
  422. glPixelStorei(GL_PACK_ALIGNMENT, 1);
  423. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  424. }
  425. // Set vsync
  426. SDL_GL_SetSwapInterval(vsync ? 1 : 0);
  427. // Store the system FBO on IOS now
  428. #ifdef IOS
  429. glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&impl_->systemFbo_);
  430. #endif
  431. fullscreen_ = fullscreen;
  432. resizable_ = resizable;
  433. borderless_ = borderless;
  434. vsync_ = vsync;
  435. tripleBuffer_ = tripleBuffer;
  436. multiSample_ = multiSample;
  437. SDL_GetWindowSize(impl_->window_, &width_, &height_);
  438. // Reset rendertargets and viewport for the new screen mode
  439. ResetRenderTargets();
  440. // Clear the initial window contents to black
  441. Clear(CLEAR_COLOR);
  442. SDL_GL_SwapWindow(impl_->window_);
  443. CheckFeatureSupport(extensions);
  444. #ifdef URHO3D_LOGGING
  445. String msg;
  446. msg.AppendWithFormat("Set screen mode %dx%d %s", width_, height_, (fullscreen_ ? "fullscreen" : "windowed"));
  447. if (borderless_)
  448. msg.Append(" borderless");
  449. if (resizable_)
  450. msg.Append(" resizable");
  451. if (multiSample > 1)
  452. msg.AppendWithFormat(" multisample %d", multiSample);
  453. LOGINFO(msg);
  454. #endif
  455. using namespace ScreenMode;
  456. VariantMap& eventData = GetEventDataMap();
  457. eventData[P_WIDTH] = width_;
  458. eventData[P_HEIGHT] = height_;
  459. eventData[P_FULLSCREEN] = fullscreen_;
  460. eventData[P_RESIZABLE] = resizable_;
  461. eventData[P_BORDERLESS] = borderless_;
  462. SendEvent(E_SCREENMODE, eventData);
  463. return true;
  464. }
  465. bool Graphics::SetMode(int width, int height)
  466. {
  467. return SetMode(width, height, fullscreen_, borderless_, resizable_, vsync_, tripleBuffer_, multiSample_);
  468. }
  469. void Graphics::SetSRGB(bool enable)
  470. {
  471. enable &= sRGBWriteSupport_;
  472. if (enable != sRGB_)
  473. {
  474. sRGB_ = enable;
  475. impl_->fboDirty_ = true;
  476. }
  477. }
  478. void Graphics::SetOrientations(const String& orientations)
  479. {
  480. orientations_ = orientations.Trimmed();
  481. SDL_SetHint(SDL_HINT_ORIENTATIONS, orientations_.CString());
  482. }
  483. bool Graphics::ToggleFullscreen()
  484. {
  485. return SetMode(width_, height_, !fullscreen_, borderless_, resizable_, vsync_, tripleBuffer_, multiSample_);
  486. }
  487. void Graphics::Close()
  488. {
  489. if (!IsInitialized())
  490. return;
  491. // Actually close the window
  492. Release(true, true);
  493. }
  494. bool Graphics::TakeScreenShot(Image& destImage)
  495. {
  496. PROFILE(TakeScreenShot);
  497. ResetRenderTargets();
  498. destImage.SetSize(width_, height_, 3);
  499. glReadPixels(0, 0, width_, height_, GL_RGB, GL_UNSIGNED_BYTE, destImage.GetData());
  500. // On OpenGL we need to flip the image vertically after reading
  501. destImage.FlipVertical();
  502. return true;
  503. }
  504. bool Graphics::BeginFrame()
  505. {
  506. if (!IsInitialized() || IsDeviceLost())
  507. return false;
  508. // If using an external window, check it for size changes, and reset screen mode if necessary
  509. if (externalWindow_)
  510. {
  511. int width, height;
  512. SDL_GetWindowSize(impl_->window_, &width, &height);
  513. if (width != width_ || height != height_)
  514. SetMode(width, height);
  515. }
  516. // Set default rendertarget and depth buffer
  517. ResetRenderTargets();
  518. // Cleanup textures from previous frame
  519. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  520. SetTexture(i, 0);
  521. // Enable color and depth write
  522. SetColorWrite(true);
  523. SetDepthWrite(true);
  524. numPrimitives_ = 0;
  525. numBatches_ = 0;
  526. SendEvent(E_BEGINRENDERING);
  527. return true;
  528. }
  529. void Graphics::EndFrame()
  530. {
  531. if (!IsInitialized())
  532. return;
  533. PROFILE(Present);
  534. SendEvent(E_ENDRENDERING);
  535. SDL_GL_SwapWindow(impl_->window_);
  536. // Clean up FBO's that have not been used for a long time, and too large scratch buffers
  537. CleanupFramebuffers();
  538. CleanupScratchBuffers();
  539. }
  540. void Graphics::Clear(unsigned flags, const Color& color, float depth, unsigned stencil)
  541. {
  542. if (impl_->fboDirty_)
  543. CommitFramebuffer();
  544. #ifdef GL_ES_VERSION_2_0
  545. flags &= ~CLEAR_STENCIL;
  546. #endif
  547. bool oldColorWrite = colorWrite_;
  548. bool oldDepthWrite = depthWrite_;
  549. if (flags & CLEAR_COLOR && !oldColorWrite)
  550. SetColorWrite(true);
  551. if (flags & CLEAR_DEPTH && !oldDepthWrite)
  552. SetDepthWrite(true);
  553. if (flags & CLEAR_STENCIL && stencilWriteMask_ != M_MAX_UNSIGNED)
  554. glStencilMask(M_MAX_UNSIGNED);
  555. unsigned glFlags = 0;
  556. if (flags & CLEAR_COLOR)
  557. {
  558. glFlags |= GL_COLOR_BUFFER_BIT;
  559. glClearColor(color.r_, color.g_, color.b_, color.a_);
  560. }
  561. if (flags & CLEAR_DEPTH)
  562. {
  563. glFlags |= GL_DEPTH_BUFFER_BIT;
  564. glClearDepth(depth);
  565. }
  566. if (flags & CLEAR_STENCIL)
  567. {
  568. glFlags |= GL_STENCIL_BUFFER_BIT;
  569. glClearStencil(stencil);
  570. }
  571. // If viewport is less than full screen, set a scissor to limit the clear
  572. /// \todo Any user-set scissor test will be lost
  573. IntVector2 viewSize = GetRenderTargetDimensions();
  574. if (viewport_.left_ != 0 || viewport_.top_ != 0 || viewport_.right_ != viewSize.x_ || viewport_.bottom_ != viewSize.y_)
  575. SetScissorTest(true, IntRect(0, 0, viewport_.Width(), viewport_.Height()));
  576. else
  577. SetScissorTest(false);
  578. glClear(glFlags);
  579. SetScissorTest(false);
  580. SetColorWrite(oldColorWrite);
  581. SetDepthWrite(oldDepthWrite);
  582. if (flags & CLEAR_STENCIL && stencilWriteMask_ != M_MAX_UNSIGNED)
  583. glStencilMask(stencilWriteMask_);
  584. }
  585. bool Graphics::ResolveToTexture(Texture2D* destination, const IntRect& viewport)
  586. {
  587. if (!destination || !destination->GetRenderSurface())
  588. return false;
  589. PROFILE(ResolveToTexture);
  590. IntRect vpCopy = viewport;
  591. if (vpCopy.right_ <= vpCopy.left_)
  592. vpCopy.right_ = vpCopy.left_ + 1;
  593. if (vpCopy.bottom_ <= vpCopy.top_)
  594. vpCopy.bottom_ = vpCopy.top_ + 1;
  595. vpCopy.left_ = Clamp(vpCopy.left_, 0, width_);
  596. vpCopy.top_ = Clamp(vpCopy.top_, 0, height_);
  597. vpCopy.right_ = Clamp(vpCopy.right_, 0, width_);
  598. vpCopy.bottom_ = Clamp(vpCopy.bottom_, 0, height_);
  599. // Make sure the FBO is not in use
  600. ResetRenderTargets();
  601. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  602. SetTextureForUpdate(destination);
  603. glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, vpCopy.left_, height_ - vpCopy.bottom_, vpCopy.Width(), vpCopy.Height());
  604. SetTexture(0, 0);
  605. return true;
  606. }
  607. void Graphics::Draw(PrimitiveType type, unsigned vertexStart, unsigned vertexCount)
  608. {
  609. if (!vertexCount)
  610. return;
  611. if (impl_->fboDirty_)
  612. CommitFramebuffer();
  613. unsigned primitiveCount = 0;
  614. switch (type)
  615. {
  616. case TRIANGLE_LIST:
  617. primitiveCount = vertexCount / 3;
  618. glDrawArrays(GL_TRIANGLES, vertexStart, vertexCount);
  619. break;
  620. case LINE_LIST:
  621. primitiveCount = vertexCount / 2;
  622. glDrawArrays(GL_LINES, vertexStart, vertexCount);
  623. break;
  624. }
  625. numPrimitives_ += primitiveCount;
  626. ++numBatches_;
  627. }
  628. void Graphics::Draw(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount)
  629. {
  630. if (!indexCount || !indexBuffer_ || !indexBuffer_->GetGPUObject())
  631. return;
  632. if (impl_->fboDirty_)
  633. CommitFramebuffer();
  634. unsigned primitiveCount = 0;
  635. unsigned indexSize = indexBuffer_->GetIndexSize();
  636. switch (type)
  637. {
  638. case TRIANGLE_LIST:
  639. primitiveCount = indexCount / 3;
  640. if (indexSize == sizeof(unsigned short))
  641. glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_SHORT, reinterpret_cast<const GLvoid*>(indexStart * indexSize));
  642. else
  643. glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, reinterpret_cast<const GLvoid*>(indexStart * indexSize));
  644. break;
  645. case LINE_LIST:
  646. primitiveCount = indexCount / 2;
  647. if (indexSize == sizeof(unsigned short))
  648. glDrawElements(GL_LINES, indexCount, GL_UNSIGNED_SHORT, reinterpret_cast<const GLvoid*>(indexStart * indexSize));
  649. else
  650. glDrawElements(GL_LINES, indexCount, GL_UNSIGNED_INT, reinterpret_cast<const GLvoid*>(indexStart * indexSize));
  651. break;
  652. }
  653. numPrimitives_ += primitiveCount;
  654. ++numBatches_;
  655. }
  656. void Graphics::DrawInstanced(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount, unsigned instanceCount)
  657. {
  658. #ifndef GL_ES_VERSION_2_0
  659. if (!indexCount || !indexBuffer_ || !indexBuffer_->GetGPUObject() || !instancingSupport_)
  660. return;
  661. if (impl_->fboDirty_)
  662. CommitFramebuffer();
  663. unsigned primitiveCount = 0;
  664. unsigned indexSize = indexBuffer_->GetIndexSize();
  665. switch (type)
  666. {
  667. case TRIANGLE_LIST:
  668. primitiveCount = indexCount / 3;
  669. if (indexSize == sizeof(unsigned short))
  670. {
  671. glDrawElementsInstancedARB(GL_TRIANGLES, indexCount, GL_UNSIGNED_SHORT, reinterpret_cast<const GLvoid*>(indexStart * indexSize),
  672. instanceCount);
  673. }
  674. else
  675. {
  676. glDrawElementsInstancedARB(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, reinterpret_cast<const GLvoid*>(indexStart * indexSize),
  677. instanceCount);
  678. }
  679. break;
  680. case LINE_LIST:
  681. primitiveCount = indexCount / 2;
  682. if (indexSize == sizeof(unsigned short))
  683. {
  684. glDrawElementsInstancedARB(GL_LINES, indexCount, GL_UNSIGNED_SHORT, reinterpret_cast<const GLvoid*>(indexStart * indexSize),
  685. instanceCount);
  686. }
  687. else
  688. {
  689. glDrawElementsInstancedARB(GL_LINES, indexCount, GL_UNSIGNED_INT, reinterpret_cast<const GLvoid*>(indexStart * indexSize),
  690. instanceCount);
  691. }
  692. break;
  693. }
  694. numPrimitives_ += instanceCount * primitiveCount;
  695. ++numBatches_;
  696. #endif
  697. }
  698. void Graphics::SetVertexBuffer(VertexBuffer* buffer)
  699. {
  700. // Note: this is not multi-instance safe
  701. static PODVector<VertexBuffer*> vertexBuffers(1);
  702. static PODVector<unsigned> elementMasks(1);
  703. vertexBuffers[0] = buffer;
  704. elementMasks[0] = MASK_DEFAULT;
  705. SetVertexBuffers(vertexBuffers, elementMasks);
  706. }
  707. bool Graphics::SetVertexBuffers(const PODVector<VertexBuffer*>& buffers, const PODVector<unsigned>& elementMasks,
  708. unsigned instanceOffset)
  709. {
  710. if (buffers.Size() > MAX_VERTEX_STREAMS)
  711. {
  712. LOGERROR("Too many vertex buffers");
  713. return false;
  714. }
  715. if (buffers.Size() != elementMasks.Size())
  716. {
  717. LOGERROR("Amount of element masks and vertex buffers does not match");
  718. return false;
  719. }
  720. bool changed = false;
  721. unsigned newAttributes = 0;
  722. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  723. {
  724. VertexBuffer* buffer = 0;
  725. unsigned elementMask = 0;
  726. if (i < buffers.Size() && buffers[i])
  727. {
  728. buffer = buffers[i];
  729. if (elementMasks[i] == MASK_DEFAULT)
  730. elementMask = buffer->GetElementMask();
  731. else
  732. elementMask = buffer->GetElementMask() & elementMasks[i];
  733. }
  734. // If buffer and element mask have stayed the same, skip to the next buffer
  735. if (buffer == vertexBuffers_[i] && elementMask == elementMasks_[i] && instanceOffset == lastInstanceOffset_ && !changed)
  736. {
  737. newAttributes |= elementMask;
  738. continue;
  739. }
  740. vertexBuffers_[i] = buffer;
  741. elementMasks_[i] = elementMask;
  742. changed = true;
  743. // Beware buffers with missing OpenGL objects, as binding a zero buffer object means accessing CPU memory for vertex data,
  744. // in which case the pointer will be invalid and cause a crash
  745. if (!buffer || !buffer->GetGPUObject())
  746. continue;
  747. glBindBuffer(GL_ARRAY_BUFFER, buffer->GetGPUObject());
  748. unsigned vertexSize = buffer->GetVertexSize();
  749. for (unsigned j = 0; j < MAX_VERTEX_ELEMENTS; ++j)
  750. {
  751. unsigned attrIndex = glVertexAttrIndex[j];
  752. unsigned elementBit = 1 << j;
  753. if (elementMask & elementBit)
  754. {
  755. newAttributes |= elementBit;
  756. // Enable attribute if not enabled yet
  757. if ((impl_->enabledAttributes_ & elementBit) == 0)
  758. {
  759. glEnableVertexAttribArray(attrIndex);
  760. impl_->enabledAttributes_ |= elementBit;
  761. }
  762. // Set the attribute pointer. Add instance offset for the instance matrix pointers
  763. unsigned offset = j >= ELEMENT_INSTANCEMATRIX1 ? instanceOffset * vertexSize : 0;
  764. glVertexAttribPointer(attrIndex, VertexBuffer::elementComponents[j], VertexBuffer::elementType[j],
  765. VertexBuffer::elementNormalize[j], vertexSize, reinterpret_cast<const GLvoid*>(buffer->GetElementOffset((VertexElement)j)
  766. + offset));
  767. }
  768. }
  769. }
  770. if (!changed)
  771. return true;
  772. lastInstanceOffset_ = instanceOffset;
  773. // Now check which vertex attributes should be disabled
  774. unsigned disableAttributes = impl_->enabledAttributes_ & (~newAttributes);
  775. unsigned disableIndex = 0;
  776. while (disableAttributes)
  777. {
  778. if (disableAttributes & 1)
  779. {
  780. glDisableVertexAttribArray(glVertexAttrIndex[disableIndex]);
  781. impl_->enabledAttributes_ &= ~(1 << disableIndex);
  782. }
  783. disableAttributes >>= 1;
  784. ++disableIndex;
  785. }
  786. return true;
  787. }
  788. bool Graphics::SetVertexBuffers(const Vector<SharedPtr<VertexBuffer> >& buffers, const PODVector<unsigned>&
  789. elementMasks, unsigned instanceOffset)
  790. {
  791. if (buffers.Size() > MAX_VERTEX_STREAMS)
  792. {
  793. LOGERROR("Too many vertex buffers");
  794. return false;
  795. }
  796. if (buffers.Size() != elementMasks.Size())
  797. {
  798. LOGERROR("Amount of element masks and vertex buffers does not match");
  799. return false;
  800. }
  801. bool changed = false;
  802. unsigned newAttributes = 0;
  803. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  804. {
  805. VertexBuffer* buffer = 0;
  806. unsigned elementMask = 0;
  807. if (i < buffers.Size() && buffers[i])
  808. {
  809. buffer = buffers[i];
  810. if (elementMasks[i] == MASK_DEFAULT)
  811. elementMask = buffer->GetElementMask();
  812. else
  813. elementMask = buffer->GetElementMask() & elementMasks[i];
  814. }
  815. // If buffer and element mask have stayed the same, skip to the next buffer
  816. if (buffer == vertexBuffers_[i] && elementMask == elementMasks_[i] && instanceOffset == lastInstanceOffset_ && !changed)
  817. {
  818. newAttributes |= elementMask;
  819. continue;
  820. }
  821. vertexBuffers_[i] = buffer;
  822. elementMasks_[i] = elementMask;
  823. changed = true;
  824. // Beware buffers with missing OpenGL objects, as binding a zero buffer object means accessing CPU memory for vertex data,
  825. // in which case the pointer will be invalid and cause a crash
  826. if (!buffer || !buffer->GetGPUObject())
  827. continue;
  828. glBindBuffer(GL_ARRAY_BUFFER, buffer->GetGPUObject());
  829. unsigned vertexSize = buffer->GetVertexSize();
  830. for (unsigned j = 0; j < MAX_VERTEX_ELEMENTS; ++j)
  831. {
  832. unsigned attrIndex = glVertexAttrIndex[j];
  833. unsigned elementBit = 1 << j;
  834. if (elementMask & elementBit)
  835. {
  836. newAttributes |= elementBit;
  837. // Enable attribute if not enabled yet
  838. if ((impl_->enabledAttributes_ & elementBit) == 0)
  839. {
  840. glEnableVertexAttribArray(attrIndex);
  841. impl_->enabledAttributes_ |= elementBit;
  842. }
  843. // Set the attribute pointer. Add instance offset for the instance matrix pointers
  844. unsigned offset = j >= ELEMENT_INSTANCEMATRIX1 ? instanceOffset * vertexSize : 0;
  845. glVertexAttribPointer(attrIndex, VertexBuffer::elementComponents[j], VertexBuffer::elementType[j],
  846. VertexBuffer::elementNormalize[j], vertexSize, reinterpret_cast<const GLvoid*>(buffer->GetElementOffset((VertexElement)j)
  847. + offset));
  848. }
  849. }
  850. }
  851. if (!changed)
  852. return true;
  853. lastInstanceOffset_ = instanceOffset;
  854. // Now check which vertex attributes should be disabled
  855. unsigned disableAttributes = impl_->enabledAttributes_ & (~newAttributes);
  856. unsigned disableIndex = 0;
  857. while (disableAttributes)
  858. {
  859. if (disableAttributes & 1)
  860. {
  861. glDisableVertexAttribArray(glVertexAttrIndex[disableIndex]);
  862. impl_->enabledAttributes_ &= ~(1 << disableIndex);
  863. }
  864. disableAttributes >>= 1;
  865. ++disableIndex;
  866. }
  867. return true;
  868. }
  869. void Graphics::SetIndexBuffer(IndexBuffer* buffer)
  870. {
  871. if (indexBuffer_ == buffer)
  872. return;
  873. if (buffer)
  874. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer->GetGPUObject());
  875. else
  876. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
  877. indexBuffer_ = buffer;
  878. }
  879. void Graphics::SetShaders(ShaderVariation* vs, ShaderVariation* ps)
  880. {
  881. if (vs == vertexShader_ && ps == pixelShader_)
  882. return;
  883. ClearParameterSources();
  884. // Compile the shaders now if not yet compiled. If already attempted, do not retry
  885. if (vs && !vs->GetGPUObject())
  886. {
  887. if (vs->GetCompilerOutput().Empty())
  888. {
  889. PROFILE(CompileVertexShader);
  890. bool success = vs->Create();
  891. if (success)
  892. LOGDEBUG("Compiled vertex shader " + vs->GetFullName());
  893. else
  894. {
  895. LOGERROR("Failed to compile vertex shader " + vs->GetFullName() + ":\n" + vs->GetCompilerOutput());
  896. vs = 0;
  897. }
  898. }
  899. else
  900. vs = 0;
  901. }
  902. if (ps && !ps->GetGPUObject())
  903. {
  904. if (ps->GetCompilerOutput().Empty())
  905. {
  906. PROFILE(CompilePixelShader);
  907. bool success = ps->Create();
  908. if (success)
  909. LOGDEBUG("Compiled pixel shader " + ps->GetFullName());
  910. else
  911. {
  912. LOGERROR("Failed to compile pixel shader " + ps->GetFullName() + ":\n" + ps->GetCompilerOutput());
  913. ps = 0;
  914. }
  915. }
  916. else
  917. ps = 0;
  918. }
  919. if (!vs || !ps)
  920. {
  921. glUseProgram(0);
  922. vertexShader_ = 0;
  923. pixelShader_ = 0;
  924. shaderProgram_ = 0;
  925. }
  926. else
  927. {
  928. vertexShader_ = vs;
  929. pixelShader_ = ps;
  930. Pair<ShaderVariation*, ShaderVariation*> combination(vs, ps);
  931. ShaderProgramMap::Iterator i = shaderPrograms_.Find(combination);
  932. if (i != shaderPrograms_.End())
  933. {
  934. // Use the existing linked program
  935. if (i->second_->GetGPUObject())
  936. {
  937. glUseProgram(i->second_->GetGPUObject());
  938. shaderProgram_ = i->second_;
  939. }
  940. else
  941. {
  942. glUseProgram(0);
  943. shaderProgram_ = 0;
  944. }
  945. }
  946. else
  947. {
  948. // Link a new combination
  949. PROFILE(LinkShaders);
  950. SharedPtr<ShaderProgram> newProgram(new ShaderProgram(this, vs, ps));
  951. if (newProgram->Link())
  952. {
  953. LOGDEBUG("Linked vertex shader " + vs->GetFullName() + " and pixel shader " + ps->GetFullName());
  954. // Note: Link() calls glUseProgram() to set the texture sampler uniforms,
  955. // so it is not necessary to call it again
  956. shaderProgram_ = newProgram;
  957. }
  958. else
  959. {
  960. LOGERROR("Failed to link vertex shader " + vs->GetFullName() + " and pixel shader " + ps->GetFullName() + ":\n" +
  961. newProgram->GetLinkerOutput());
  962. glUseProgram(0);
  963. shaderProgram_ = 0;
  964. }
  965. shaderPrograms_[combination] = newProgram;
  966. }
  967. }
  968. // Store shader combination if shader dumping in progress
  969. if (shaderPrecache_)
  970. shaderPrecache_->StoreShaders(vertexShader_, pixelShader_);
  971. }
  972. void Graphics::SetShaderParameter(StringHash param, const float* data, unsigned count)
  973. {
  974. if (shaderProgram_)
  975. {
  976. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  977. if (info)
  978. {
  979. switch (info->type_)
  980. {
  981. case GL_FLOAT:
  982. glUniform1fv(info->location_, count, data);
  983. break;
  984. case GL_FLOAT_VEC2:
  985. glUniform2fv(info->location_, count / 2, data);
  986. break;
  987. case GL_FLOAT_VEC3:
  988. glUniform3fv(info->location_, count / 3, data);
  989. break;
  990. case GL_FLOAT_VEC4:
  991. glUniform4fv(info->location_, count / 4, data);
  992. break;
  993. case GL_FLOAT_MAT3:
  994. count = Min((int)count, (int)NUM_TEMP_MATRICES * 9);
  995. Matrix3::BulkTranspose(&tempMatrices3_[0].m00_, data, count / 9);
  996. glUniformMatrix3fv(info->location_, count / 9, GL_FALSE, tempMatrices3_[0].Data());
  997. break;
  998. case GL_FLOAT_MAT4:
  999. count = Min((int)count, (int)NUM_TEMP_MATRICES * 16);
  1000. Matrix4::BulkTranspose(&tempMatrices4_[0].m00_, data, count / 16);
  1001. glUniformMatrix4fv(info->location_, count / 16, GL_FALSE, tempMatrices4_[0].Data());
  1002. break;
  1003. }
  1004. }
  1005. }
  1006. }
  1007. void Graphics::SetShaderParameter(StringHash param, float value)
  1008. {
  1009. if (shaderProgram_)
  1010. {
  1011. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  1012. if (info)
  1013. glUniform1fv(info->location_, 1, &value);
  1014. }
  1015. }
  1016. void Graphics::SetShaderParameter(StringHash param, const Color& color)
  1017. {
  1018. SetShaderParameter(param, color.Data(), 4);
  1019. }
  1020. void Graphics::SetShaderParameter(StringHash param, const Vector2& vector)
  1021. {
  1022. if (shaderProgram_)
  1023. {
  1024. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  1025. if (info)
  1026. {
  1027. // Check the uniform type to avoid mismatch
  1028. switch (info->type_)
  1029. {
  1030. case GL_FLOAT:
  1031. glUniform1fv(info->location_, 1, vector.Data());
  1032. break;
  1033. case GL_FLOAT_VEC2:
  1034. glUniform2fv(info->location_, 1, vector.Data());
  1035. break;
  1036. }
  1037. }
  1038. }
  1039. }
  1040. void Graphics::SetShaderParameter(StringHash param, const Matrix3& matrix)
  1041. {
  1042. if (shaderProgram_)
  1043. {
  1044. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  1045. if (info)
  1046. glUniformMatrix3fv(info->location_, 1, GL_FALSE, matrix.Transpose().Data());
  1047. }
  1048. }
  1049. void Graphics::SetShaderParameter(StringHash param, const Vector3& vector)
  1050. {
  1051. if (shaderProgram_)
  1052. {
  1053. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  1054. if (info)
  1055. {
  1056. // Check the uniform type to avoid mismatch
  1057. switch (info->type_)
  1058. {
  1059. case GL_FLOAT:
  1060. glUniform1fv(info->location_, 1, vector.Data());
  1061. break;
  1062. case GL_FLOAT_VEC2:
  1063. glUniform2fv(info->location_, 1, vector.Data());
  1064. break;
  1065. case GL_FLOAT_VEC3:
  1066. glUniform3fv(info->location_, 1, vector.Data());
  1067. break;
  1068. }
  1069. }
  1070. }
  1071. }
  1072. void Graphics::SetShaderParameter(StringHash param, const Matrix4& matrix)
  1073. {
  1074. if (shaderProgram_)
  1075. {
  1076. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  1077. if (info)
  1078. glUniformMatrix4fv(info->location_, 1, GL_FALSE, matrix.Transpose().Data());
  1079. }
  1080. }
  1081. void Graphics::SetShaderParameter(StringHash param, const Vector4& vector)
  1082. {
  1083. if (shaderProgram_)
  1084. {
  1085. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  1086. if (info)
  1087. {
  1088. // Check the uniform type to avoid mismatch
  1089. switch (info->type_)
  1090. {
  1091. case GL_FLOAT:
  1092. glUniform1fv(info->location_, 1, vector.Data());
  1093. break;
  1094. case GL_FLOAT_VEC2:
  1095. glUniform2fv(info->location_, 1, vector.Data());
  1096. break;
  1097. case GL_FLOAT_VEC3:
  1098. glUniform3fv(info->location_, 1, vector.Data());
  1099. break;
  1100. case GL_FLOAT_VEC4:
  1101. glUniform4fv(info->location_, 1, vector.Data());
  1102. break;
  1103. }
  1104. }
  1105. }
  1106. }
  1107. void Graphics::SetShaderParameter(StringHash param, const Matrix3x4& matrix)
  1108. {
  1109. if (shaderProgram_)
  1110. {
  1111. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  1112. if (info)
  1113. {
  1114. float data[16];
  1115. data[0] = matrix.m00_;
  1116. data[1] = matrix.m10_;
  1117. data[2] = matrix.m20_;
  1118. data[3] = 0.0f;
  1119. data[4] = matrix.m01_;
  1120. data[5] = matrix.m11_;
  1121. data[6] = matrix.m21_;
  1122. data[7] = 0.0f;
  1123. data[8] = matrix.m02_;
  1124. data[9] = matrix.m12_;
  1125. data[10] = matrix.m22_;
  1126. data[11] = 0.0f;
  1127. data[12] = matrix.m03_;
  1128. data[13] = matrix.m13_;
  1129. data[14] = matrix.m23_;
  1130. data[15] = 1.0f;
  1131. glUniformMatrix4fv(info->location_, 1, GL_FALSE, data);
  1132. }
  1133. }
  1134. }
  1135. void Graphics::SetShaderParameter(StringHash param, const Variant& value)
  1136. {
  1137. switch (value.GetType())
  1138. {
  1139. case VAR_BOOL:
  1140. SetShaderParameter(param, value.GetBool());
  1141. break;
  1142. case VAR_FLOAT:
  1143. SetShaderParameter(param, value.GetFloat());
  1144. break;
  1145. case VAR_VECTOR2:
  1146. SetShaderParameter(param, value.GetVector2());
  1147. break;
  1148. case VAR_VECTOR3:
  1149. SetShaderParameter(param, value.GetVector3());
  1150. break;
  1151. case VAR_VECTOR4:
  1152. SetShaderParameter(param, value.GetVector4());
  1153. break;
  1154. case VAR_COLOR:
  1155. SetShaderParameter(param, value.GetColor());
  1156. break;
  1157. case VAR_MATRIX3:
  1158. SetShaderParameter(param, value.GetMatrix3());
  1159. break;
  1160. case VAR_MATRIX3X4:
  1161. SetShaderParameter(param, value.GetMatrix3x4());
  1162. break;
  1163. case VAR_MATRIX4:
  1164. SetShaderParameter(param, value.GetMatrix4());
  1165. break;
  1166. default:
  1167. // Unsupported parameter type, do nothing
  1168. break;
  1169. }
  1170. }
  1171. bool Graphics::NeedParameterUpdate(ShaderParameterGroup group, const void* source)
  1172. {
  1173. if ((unsigned)(size_t)shaderParameterSources_[group] == M_MAX_UNSIGNED || shaderParameterSources_[group] != source)
  1174. {
  1175. shaderParameterSources_[group] = source;
  1176. return true;
  1177. }
  1178. else
  1179. return false;
  1180. }
  1181. bool Graphics::HasShaderParameter(ShaderType type, StringHash param)
  1182. {
  1183. return shaderProgram_ && shaderProgram_->HasParameter(param);
  1184. }
  1185. bool Graphics::HasTextureUnit(TextureUnit unit)
  1186. {
  1187. return shaderProgram_ && shaderProgram_->HasTextureUnit(unit);
  1188. }
  1189. void Graphics::ClearParameterSource(ShaderParameterGroup group)
  1190. {
  1191. shaderParameterSources_[group] = (const void*)M_MAX_UNSIGNED;
  1192. }
  1193. void Graphics::ClearParameterSources()
  1194. {
  1195. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  1196. shaderParameterSources_[i] = (const void*)M_MAX_UNSIGNED;
  1197. }
  1198. void Graphics::ClearTransformSources()
  1199. {
  1200. shaderParameterSources_[SP_CAMERA] = (const void*)M_MAX_UNSIGNED;
  1201. shaderParameterSources_[SP_OBJECTTRANSFORM] = (const void*)M_MAX_UNSIGNED;
  1202. }
  1203. void Graphics::CleanupShaderPrograms()
  1204. {
  1205. // Ignore individual call from ShaderVariation instance when Graphics subsystem is in process of
  1206. // releasing all GPU objects or recreating GPU objects due device lost, because the Graphics subsystem
  1207. // will eventually erase all the shader programs afterward as part of the release process.
  1208. if (releasingGPUObjects_)
  1209. return;
  1210. for (ShaderProgramMap::Iterator i = shaderPrograms_.Begin(); i != shaderPrograms_.End();)
  1211. {
  1212. ShaderVariation* vs = i->second_->GetVertexShader();
  1213. ShaderVariation* ps = i->second_->GetPixelShader();
  1214. if (!vs || !ps || !vs->GetGPUObject() || !ps->GetGPUObject())
  1215. i = shaderPrograms_.Erase(i);
  1216. else
  1217. ++i;
  1218. }
  1219. }
  1220. void Graphics::SetTexture(unsigned index, Texture* texture)
  1221. {
  1222. if (index >= MAX_TEXTURE_UNITS)
  1223. return;
  1224. // Check if texture is currently bound as a rendertarget. In that case, use its backup texture, or blank if not defined
  1225. if (texture)
  1226. {
  1227. if (renderTargets_[0] && renderTargets_[0]->GetParentTexture() == texture)
  1228. texture = texture->GetBackupTexture();
  1229. }
  1230. if (textures_[index] != texture)
  1231. {
  1232. if (impl_->activeTexture_ != index)
  1233. {
  1234. glActiveTexture(GL_TEXTURE0 + index);
  1235. impl_->activeTexture_ = index;
  1236. }
  1237. if (texture)
  1238. {
  1239. unsigned glType = texture->GetTarget();
  1240. if (glType != textureTypes_[index])
  1241. {
  1242. if (textureTypes_[index])
  1243. glDisable(textureTypes_[index]);
  1244. glEnable(glType);
  1245. textureTypes_[index] = glType;
  1246. }
  1247. glBindTexture(glType, texture->GetGPUObject());
  1248. if (texture->GetParametersDirty())
  1249. texture->UpdateParameters();
  1250. }
  1251. else
  1252. {
  1253. if (textureTypes_[index])
  1254. glBindTexture(textureTypes_[index], 0);
  1255. }
  1256. textures_[index] = texture;
  1257. }
  1258. else
  1259. {
  1260. if (texture && texture->GetParametersDirty())
  1261. {
  1262. if (impl_->activeTexture_ != index)
  1263. {
  1264. glActiveTexture(GL_TEXTURE0 + index);
  1265. impl_->activeTexture_ = index;
  1266. }
  1267. glBindTexture(texture->GetTarget(), texture->GetGPUObject());
  1268. texture->UpdateParameters();
  1269. }
  1270. }
  1271. }
  1272. void Graphics::SetTextureForUpdate(Texture* texture)
  1273. {
  1274. if (impl_->activeTexture_ != 0)
  1275. {
  1276. glActiveTexture(GL_TEXTURE0);
  1277. impl_->activeTexture_ = 0;
  1278. }
  1279. glBindTexture(texture->GetTarget(), texture->GetGPUObject());
  1280. textures_[0] = texture;
  1281. }
  1282. void Graphics::SetDefaultTextureFilterMode(TextureFilterMode mode)
  1283. {
  1284. if (mode != defaultTextureFilterMode_)
  1285. {
  1286. defaultTextureFilterMode_ = mode;
  1287. SetTextureParametersDirty();
  1288. }
  1289. }
  1290. void Graphics::SetTextureAnisotropy(unsigned level)
  1291. {
  1292. if (level != textureAnisotropy_)
  1293. {
  1294. textureAnisotropy_ = level;
  1295. SetTextureParametersDirty();
  1296. }
  1297. }
  1298. void Graphics::SetTextureParametersDirty()
  1299. {
  1300. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1301. {
  1302. Texture* texture = dynamic_cast<Texture*>(*i);
  1303. if (texture)
  1304. texture->SetParametersDirty();
  1305. }
  1306. }
  1307. void Graphics::ResetRenderTargets()
  1308. {
  1309. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1310. SetRenderTarget(i, (RenderSurface*)0);
  1311. SetDepthStencil((RenderSurface*)0);
  1312. SetViewport(IntRect(0, 0, width_, height_));
  1313. }
  1314. void Graphics::ResetRenderTarget(unsigned index)
  1315. {
  1316. SetRenderTarget(index, (RenderSurface*)0);
  1317. }
  1318. void Graphics::ResetDepthStencil()
  1319. {
  1320. SetDepthStencil((RenderSurface*)0);
  1321. }
  1322. void Graphics::SetRenderTarget(unsigned index, RenderSurface* renderTarget)
  1323. {
  1324. if (index >= MAX_RENDERTARGETS)
  1325. return;
  1326. if (renderTarget != renderTargets_[index])
  1327. {
  1328. renderTargets_[index] = renderTarget;
  1329. // If the rendertarget is also bound as a texture, replace with backup texture or null
  1330. if (renderTarget)
  1331. {
  1332. Texture* parentTexture = renderTarget->GetParentTexture();
  1333. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1334. {
  1335. if (textures_[i] == parentTexture)
  1336. SetTexture(i, textures_[i]->GetBackupTexture());
  1337. }
  1338. }
  1339. impl_->fboDirty_ = true;
  1340. }
  1341. }
  1342. void Graphics::SetRenderTarget(unsigned index, Texture2D* texture)
  1343. {
  1344. RenderSurface* renderTarget = 0;
  1345. if (texture)
  1346. renderTarget = texture->GetRenderSurface();
  1347. SetRenderTarget(index, renderTarget);
  1348. }
  1349. void Graphics::SetDepthStencil(RenderSurface* depthStencil)
  1350. {
  1351. // If we are using a rendertarget texture, it is required in OpenGL to also have an own depth-stencil
  1352. // Create a new depth-stencil texture as necessary to be able to provide similar behaviour as Direct3D9
  1353. if (renderTargets_[0] && !depthStencil)
  1354. {
  1355. int width = renderTargets_[0]->GetWidth();
  1356. int height = renderTargets_[0]->GetHeight();
  1357. // Direct3D9 default depth-stencil can not be used when rendertarget is larger than the window.
  1358. // Check size similarly
  1359. if (width <= width_ && height <= height_)
  1360. {
  1361. int searchKey = (width << 16) | height;
  1362. HashMap<int, SharedPtr<Texture2D> >::Iterator i = depthTextures_.Find(searchKey);
  1363. if (i != depthTextures_.End())
  1364. depthStencil = i->second_->GetRenderSurface();
  1365. else
  1366. {
  1367. SharedPtr<Texture2D> newDepthTexture(new Texture2D(context_));
  1368. newDepthTexture->SetSize(width, height, GetDepthStencilFormat(), TEXTURE_DEPTHSTENCIL);
  1369. depthTextures_[searchKey] = newDepthTexture;
  1370. depthStencil = newDepthTexture->GetRenderSurface();
  1371. }
  1372. }
  1373. }
  1374. if (depthStencil != depthStencil_)
  1375. {
  1376. depthStencil_ = depthStencil;
  1377. impl_->fboDirty_ = true;
  1378. }
  1379. }
  1380. void Graphics::SetDepthStencil(Texture2D* texture)
  1381. {
  1382. RenderSurface* depthStencil = 0;
  1383. if (texture)
  1384. depthStencil = texture->GetRenderSurface();
  1385. SetDepthStencil(depthStencil);
  1386. }
  1387. void Graphics::SetViewport(const IntRect& rect)
  1388. {
  1389. if (impl_->fboDirty_)
  1390. CommitFramebuffer();
  1391. IntVector2 rtSize = GetRenderTargetDimensions();
  1392. IntRect rectCopy = rect;
  1393. if (rectCopy.right_ <= rectCopy.left_)
  1394. rectCopy.right_ = rectCopy.left_ + 1;
  1395. if (rectCopy.bottom_ <= rectCopy.top_)
  1396. rectCopy.bottom_ = rectCopy.top_ + 1;
  1397. rectCopy.left_ = Clamp(rectCopy.left_, 0, rtSize.x_);
  1398. rectCopy.top_ = Clamp(rectCopy.top_, 0, rtSize.y_);
  1399. rectCopy.right_ = Clamp(rectCopy.right_, 0, rtSize.x_);
  1400. rectCopy.bottom_ = Clamp(rectCopy.bottom_, 0, rtSize.y_);
  1401. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1402. glViewport(rectCopy.left_, rtSize.y_ - rectCopy.bottom_, rectCopy.Width(), rectCopy.Height());
  1403. viewport_ = rectCopy;
  1404. // Disable scissor test, needs to be re-enabled by the user
  1405. SetScissorTest(false);
  1406. }
  1407. void Graphics::SetBlendMode(BlendMode mode)
  1408. {
  1409. if (mode != blendMode_)
  1410. {
  1411. if (mode == BLEND_REPLACE)
  1412. glDisable(GL_BLEND);
  1413. else
  1414. {
  1415. glEnable(GL_BLEND);
  1416. glBlendFunc(glSrcBlend[mode], glDestBlend[mode]);
  1417. glBlendEquation(glBlendOp[mode]);
  1418. }
  1419. blendMode_ = mode;
  1420. }
  1421. }
  1422. void Graphics::SetColorWrite(bool enable)
  1423. {
  1424. if (enable != colorWrite_)
  1425. {
  1426. if (enable)
  1427. glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  1428. else
  1429. glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  1430. colorWrite_ = enable;
  1431. }
  1432. }
  1433. void Graphics::SetCullMode(CullMode mode)
  1434. {
  1435. if (mode != cullMode_)
  1436. {
  1437. if (mode == CULL_NONE)
  1438. glDisable(GL_CULL_FACE);
  1439. else
  1440. {
  1441. // Use Direct3D convention, ie. clockwise vertices define a front face
  1442. glEnable(GL_CULL_FACE);
  1443. glCullFace(mode == CULL_CCW ? GL_FRONT : GL_BACK);
  1444. }
  1445. cullMode_ = mode;
  1446. }
  1447. }
  1448. void Graphics::SetDepthBias(float constantBias, float slopeScaledBias)
  1449. {
  1450. if (constantBias != constantDepthBias_ || slopeScaledBias != slopeScaledDepthBias_)
  1451. {
  1452. #ifndef GL_ES_VERSION_2_0
  1453. if (slopeScaledBias != 0.0f)
  1454. {
  1455. // OpenGL constant bias is unreliable and dependant on depth buffer bitdepth, apply in the projection matrix instead
  1456. float adjustedSlopeScaledBias = slopeScaledBias + 1.0f;
  1457. glEnable(GL_POLYGON_OFFSET_FILL);
  1458. glPolygonOffset(adjustedSlopeScaledBias, 0.0f);
  1459. }
  1460. else
  1461. glDisable(GL_POLYGON_OFFSET_FILL);
  1462. #endif
  1463. constantDepthBias_ = constantBias;
  1464. slopeScaledDepthBias_ = slopeScaledBias;
  1465. shaderParameterSources_[SP_CAMERA] = (const void*)M_MAX_UNSIGNED;
  1466. }
  1467. }
  1468. void Graphics::SetDepthTest(CompareMode mode)
  1469. {
  1470. if (mode != depthTestMode_)
  1471. {
  1472. glDepthFunc(glCmpFunc[mode]);
  1473. depthTestMode_ = mode;
  1474. }
  1475. }
  1476. void Graphics::SetDepthWrite(bool enable)
  1477. {
  1478. if (enable != depthWrite_)
  1479. {
  1480. glDepthMask(enable ? GL_TRUE : GL_FALSE);
  1481. depthWrite_ = enable;
  1482. }
  1483. }
  1484. void Graphics::SetFillMode(FillMode mode)
  1485. {
  1486. #ifndef GL_ES_VERSION_2_0
  1487. if (mode != fillMode_)
  1488. {
  1489. glPolygonMode(GL_FRONT_AND_BACK, glFillMode[mode]);
  1490. fillMode_ = mode;
  1491. }
  1492. #endif
  1493. }
  1494. void Graphics::SetScissorTest(bool enable, const Rect& rect, bool borderInclusive)
  1495. {
  1496. // During some light rendering loops, a full rect is toggled on/off repeatedly.
  1497. // Disable scissor in that case to reduce state changes
  1498. if (rect.min_.x_ <= 0.0f && rect.min_.y_ <= 0.0f && rect.max_.x_ >= 1.0f && rect.max_.y_ >= 1.0f)
  1499. enable = false;
  1500. if (enable)
  1501. {
  1502. IntVector2 rtSize(GetRenderTargetDimensions());
  1503. IntVector2 viewSize(viewport_.Size());
  1504. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1505. IntRect intRect;
  1506. int expand = borderInclusive ? 1 : 0;
  1507. intRect.left_ = Clamp((int)((rect.min_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_, 0, rtSize.x_ - 1);
  1508. intRect.top_ = Clamp((int)((-rect.max_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_, 0, rtSize.y_ - 1);
  1509. intRect.right_ = Clamp((int)((rect.max_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_ + expand, 0, rtSize.x_);
  1510. intRect.bottom_ = Clamp((int)((-rect.min_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_ + expand, 0, rtSize.y_);
  1511. if (intRect.right_ == intRect.left_)
  1512. intRect.right_++;
  1513. if (intRect.bottom_ == intRect.top_)
  1514. intRect.bottom_++;
  1515. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1516. enable = false;
  1517. if (enable && scissorRect_ != intRect)
  1518. {
  1519. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1520. glScissor(intRect.left_, rtSize.y_ - intRect.bottom_, intRect.Width(), intRect.Height());
  1521. scissorRect_ = intRect;
  1522. }
  1523. }
  1524. else
  1525. scissorRect_ = IntRect::ZERO;
  1526. if (enable != scissorTest_)
  1527. {
  1528. if (enable)
  1529. glEnable(GL_SCISSOR_TEST);
  1530. else
  1531. glDisable(GL_SCISSOR_TEST);
  1532. scissorTest_ = enable;
  1533. }
  1534. }
  1535. void Graphics::SetScissorTest(bool enable, const IntRect& rect)
  1536. {
  1537. IntVector2 rtSize(GetRenderTargetDimensions());
  1538. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1539. if (enable)
  1540. {
  1541. IntRect intRect;
  1542. intRect.left_ = Clamp(rect.left_ + viewPos.x_, 0, rtSize.x_ - 1);
  1543. intRect.top_ = Clamp(rect.top_ + viewPos.y_, 0, rtSize.y_ - 1);
  1544. intRect.right_ = Clamp(rect.right_ + viewPos.x_, 0, rtSize.x_);
  1545. intRect.bottom_ = Clamp(rect.bottom_ + viewPos.y_, 0, rtSize.y_);
  1546. if (intRect.right_ == intRect.left_)
  1547. intRect.right_++;
  1548. if (intRect.bottom_ == intRect.top_)
  1549. intRect.bottom_++;
  1550. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1551. enable = false;
  1552. if (enable && scissorRect_ != intRect)
  1553. {
  1554. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1555. glScissor(intRect.left_, rtSize.y_ - intRect.bottom_, intRect.Width(), intRect.Height());
  1556. scissorRect_ = intRect;
  1557. }
  1558. }
  1559. else
  1560. scissorRect_ = IntRect::ZERO;
  1561. if (enable != scissorTest_)
  1562. {
  1563. if (enable)
  1564. glEnable(GL_SCISSOR_TEST);
  1565. else
  1566. glDisable(GL_SCISSOR_TEST);
  1567. scissorTest_ = enable;
  1568. }
  1569. }
  1570. void Graphics::SetClipPlane(bool enable, const Plane& clipPlane, const Matrix3x4& view, const Matrix4& projection)
  1571. {
  1572. #ifndef GL_ES_VERSION_2_0
  1573. if (enable != useClipPlane_)
  1574. {
  1575. if (enable)
  1576. glEnable(GL_CLIP_PLANE0);
  1577. else
  1578. glDisable(GL_CLIP_PLANE0);
  1579. useClipPlane_ = enable;
  1580. }
  1581. if (enable)
  1582. {
  1583. Matrix4 viewProj = projection * view;
  1584. Vector4 planeVec = clipPlane.Transformed(viewProj).ToVector4();
  1585. GLdouble planeData[4];
  1586. planeData[0] = planeVec.x_;
  1587. planeData[1] = planeVec.y_;
  1588. planeData[2] = planeVec.z_;
  1589. planeData[3] = planeVec.w_;
  1590. glClipPlane(GL_CLIP_PLANE0, &planeData[0]);
  1591. }
  1592. #endif
  1593. }
  1594. void Graphics::SetStreamFrequency(unsigned index, unsigned frequency)
  1595. {
  1596. }
  1597. void Graphics::ResetStreamFrequencies()
  1598. {
  1599. }
  1600. void Graphics::SetStencilTest(bool enable, CompareMode mode, StencilOp pass, StencilOp fail, StencilOp zFail, unsigned stencilRef, unsigned compareMask, unsigned writeMask)
  1601. {
  1602. #ifndef GL_ES_VERSION_2_0
  1603. if (enable != stencilTest_)
  1604. {
  1605. if (enable)
  1606. glEnable(GL_STENCIL_TEST);
  1607. else
  1608. glDisable(GL_STENCIL_TEST);
  1609. stencilTest_ = enable;
  1610. }
  1611. if (enable)
  1612. {
  1613. if (mode != stencilTestMode_ || stencilRef != stencilRef_ || compareMask != stencilCompareMask_)
  1614. {
  1615. glStencilFunc(glCmpFunc[mode], stencilRef, compareMask);
  1616. stencilTestMode_ = mode;
  1617. stencilRef_ = stencilRef;
  1618. stencilCompareMask_ = compareMask;
  1619. }
  1620. if (writeMask != stencilWriteMask_)
  1621. {
  1622. glStencilMask(writeMask);
  1623. stencilWriteMask_ = writeMask;
  1624. }
  1625. if (pass != stencilPass_ || fail != stencilFail_ || zFail != stencilZFail_)
  1626. {
  1627. glStencilOp(glStencilOps[fail], glStencilOps[zFail], glStencilOps[pass]);
  1628. stencilPass_ = pass;
  1629. stencilFail_ = fail;
  1630. stencilZFail_ = zFail;
  1631. }
  1632. }
  1633. #endif
  1634. }
  1635. void Graphics::SetForceSM2(bool enable)
  1636. {
  1637. }
  1638. void Graphics::BeginDumpShaders(const String& fileName)
  1639. {
  1640. shaderPrecache_ = new ShaderPrecache(context_, fileName);
  1641. }
  1642. void Graphics::EndDumpShaders()
  1643. {
  1644. shaderPrecache_.Reset();
  1645. }
  1646. void Graphics::PrecacheShaders(Deserializer& source)
  1647. {
  1648. PROFILE(PrecacheShaders);
  1649. ShaderPrecache::LoadShaders(this, source);
  1650. }
  1651. bool Graphics::IsInitialized() const
  1652. {
  1653. return impl_->window_ != 0;
  1654. }
  1655. bool Graphics::IsDeviceLost() const
  1656. {
  1657. // On iOS treat window minimization as device loss, as it is forbidden to access OpenGL when minimized
  1658. #ifdef IOS
  1659. if (impl_->window_ && (SDL_GetWindowFlags(impl_->window_) & SDL_WINDOW_MINIMIZED) != 0)
  1660. return true;
  1661. #endif
  1662. return impl_->context_ == 0;
  1663. }
  1664. IntVector2 Graphics::GetWindowPosition() const
  1665. {
  1666. IntVector2 ret(IntVector2::ZERO);
  1667. if (impl_->window_)
  1668. SDL_GetWindowPosition(impl_->window_, &ret.x_, &ret.y_);
  1669. return ret;
  1670. }
  1671. PODVector<IntVector2> Graphics::GetResolutions() const
  1672. {
  1673. PODVector<IntVector2> ret;
  1674. unsigned numModes = SDL_GetNumDisplayModes(0);
  1675. for (unsigned i = 0; i < numModes; ++i)
  1676. {
  1677. SDL_DisplayMode mode;
  1678. SDL_GetDisplayMode(0, i, &mode);
  1679. int width = mode.w;
  1680. int height = mode.h;
  1681. // Store mode if unique
  1682. bool unique = true;
  1683. for (unsigned j = 0; j < ret.Size(); ++j)
  1684. {
  1685. if (ret[j].x_ == width && ret[j].y_ == height)
  1686. {
  1687. unique = false;
  1688. break;
  1689. }
  1690. }
  1691. if (unique)
  1692. ret.Push(IntVector2(width, height));
  1693. }
  1694. return ret;
  1695. }
  1696. PODVector<int> Graphics::GetMultiSampleLevels() const
  1697. {
  1698. PODVector<int> ret;
  1699. // No multisampling always supported
  1700. ret.Push(1);
  1701. /// \todo Implement properly, if possible
  1702. return ret;
  1703. }
  1704. IntVector2 Graphics::GetDesktopResolution() const
  1705. {
  1706. #if !defined(ANDROID) && !defined(IOS)
  1707. SDL_DisplayMode mode;
  1708. SDL_GetDesktopDisplayMode(0, &mode);
  1709. return IntVector2(mode.w, mode.h);
  1710. #else
  1711. // SDL_GetDesktopDisplayMode() may not work correctly on mobile platforms. Rather return the window size
  1712. return IntVector2(width_, height_);
  1713. #endif
  1714. }
  1715. unsigned Graphics::GetFormat(CompressedFormat format) const
  1716. {
  1717. switch (format)
  1718. {
  1719. case CF_DXT1:
  1720. return dxtTextureSupport_ ? GL_COMPRESSED_RGBA_S3TC_DXT1_EXT : 0;
  1721. #ifndef GL_ES_VERSION_2_0
  1722. case CF_DXT3:
  1723. return dxtTextureSupport_ ? GL_COMPRESSED_RGBA_S3TC_DXT3_EXT : 0;
  1724. case CF_DXT5:
  1725. return dxtTextureSupport_ ? GL_COMPRESSED_RGBA_S3TC_DXT5_EXT : 0;
  1726. #else
  1727. case CF_ETC1:
  1728. return etcTextureSupport_ ? GL_ETC1_RGB8_OES : 0;
  1729. case CF_PVRTC_RGB_2BPP:
  1730. return pvrtcTextureSupport_ ? COMPRESSED_RGB_PVRTC_2BPPV1_IMG : 0;
  1731. case CF_PVRTC_RGB_4BPP:
  1732. return pvrtcTextureSupport_ ? COMPRESSED_RGB_PVRTC_4BPPV1_IMG : 0;
  1733. case CF_PVRTC_RGBA_2BPP:
  1734. return pvrtcTextureSupport_ ? COMPRESSED_RGBA_PVRTC_2BPPV1_IMG : 0;
  1735. case CF_PVRTC_RGBA_4BPP:
  1736. return pvrtcTextureSupport_ ? COMPRESSED_RGBA_PVRTC_4BPPV1_IMG : 0;
  1737. #endif
  1738. default:
  1739. return 0;
  1740. }
  1741. }
  1742. ShaderVariation* Graphics::GetShader(ShaderType type, const String& name, const String& defines) const
  1743. {
  1744. return GetShader(type, name.CString(), defines.CString());
  1745. }
  1746. ShaderVariation* Graphics::GetShader(ShaderType type, const char* name, const char* defines) const
  1747. {
  1748. if (lastShaderName_ != name || !lastShader_)
  1749. {
  1750. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1751. String fullShaderName = shaderPath_ + name + shaderExtension_;
  1752. // Try to reduce repeated error log prints because of missing shaders
  1753. if (lastShaderName_ == name && !cache->Exists(fullShaderName))
  1754. return 0;
  1755. lastShader_ = cache->GetResource<Shader>(fullShaderName);
  1756. lastShaderName_ = name;
  1757. }
  1758. return lastShader_ ? lastShader_->GetVariation(type, defines) : (ShaderVariation*)0;
  1759. }
  1760. VertexBuffer* Graphics::GetVertexBuffer(unsigned index) const
  1761. {
  1762. return index < MAX_VERTEX_STREAMS ? vertexBuffers_[index] : 0;
  1763. }
  1764. TextureUnit Graphics::GetTextureUnit(const String& name)
  1765. {
  1766. HashMap<String, TextureUnit>::Iterator i = textureUnits_.Find(name);
  1767. if (i != textureUnits_.End())
  1768. return i->second_;
  1769. else
  1770. return MAX_TEXTURE_UNITS;
  1771. }
  1772. const String& Graphics::GetTextureUnitName(TextureUnit unit)
  1773. {
  1774. for (HashMap<String, TextureUnit>::Iterator i = textureUnits_.Begin(); i != textureUnits_.End(); ++i)
  1775. {
  1776. if (i->second_ == unit)
  1777. return i->first_;
  1778. }
  1779. return String::EMPTY;
  1780. }
  1781. Texture* Graphics::GetTexture(unsigned index) const
  1782. {
  1783. return index < MAX_TEXTURE_UNITS ? textures_[index] : 0;
  1784. }
  1785. RenderSurface* Graphics::GetRenderTarget(unsigned index) const
  1786. {
  1787. return index < MAX_RENDERTARGETS ? renderTargets_[index] : 0;
  1788. }
  1789. IntVector2 Graphics::GetRenderTargetDimensions() const
  1790. {
  1791. int width, height;
  1792. if (renderTargets_[0])
  1793. {
  1794. width = renderTargets_[0]->GetWidth();
  1795. height = renderTargets_[0]->GetHeight();
  1796. }
  1797. else if (depthStencil_)
  1798. {
  1799. width = depthStencil_->GetWidth();
  1800. height = depthStencil_->GetHeight();
  1801. }
  1802. else
  1803. {
  1804. width = width_;
  1805. height = height_;
  1806. }
  1807. return IntVector2(width, height);
  1808. }
  1809. void Graphics::WindowResized()
  1810. {
  1811. if (!impl_->window_)
  1812. return;
  1813. int newWidth, newHeight;
  1814. SDL_GetWindowSize(impl_->window_, &newWidth, &newHeight);
  1815. if (newWidth == width_ && newHeight == height_)
  1816. return;
  1817. width_ = newWidth;
  1818. height_ = newHeight;
  1819. // Reset rendertargets and viewport for the new screen size
  1820. ResetRenderTargets();
  1821. LOGDEBUGF("Window was resized to %dx%d", width_, height_);
  1822. using namespace ScreenMode;
  1823. VariantMap& eventData = GetEventDataMap();
  1824. eventData[P_WIDTH] = width_;
  1825. eventData[P_HEIGHT] = height_;
  1826. eventData[P_FULLSCREEN] = fullscreen_;
  1827. eventData[P_RESIZABLE] = resizable_;
  1828. eventData[P_BORDERLESS] = borderless_;
  1829. SendEvent(E_SCREENMODE, eventData);
  1830. }
  1831. void Graphics::AddGPUObject(GPUObject* object)
  1832. {
  1833. gpuObjects_.Push(object);
  1834. }
  1835. void Graphics::RemoveGPUObject(GPUObject* object)
  1836. {
  1837. gpuObjects_.Remove(object);
  1838. }
  1839. void* Graphics::ReserveScratchBuffer(unsigned size)
  1840. {
  1841. if (!size)
  1842. return 0;
  1843. if (size > maxScratchBufferRequest_)
  1844. maxScratchBufferRequest_ = size;
  1845. // First check for a free buffer that is large enough
  1846. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1847. {
  1848. if (!i->reserved_ && i->size_ >= size)
  1849. {
  1850. i->reserved_ = true;
  1851. return i->data_.Get();
  1852. }
  1853. }
  1854. // Then check if a free buffer can be resized
  1855. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1856. {
  1857. if (!i->reserved_)
  1858. {
  1859. i->data_ = new unsigned char[size];
  1860. i->size_ = size;
  1861. i->reserved_ = true;
  1862. return i->data_.Get();
  1863. }
  1864. }
  1865. // Finally allocate a new buffer
  1866. ScratchBuffer newBuffer;
  1867. newBuffer.data_ = new unsigned char[size];
  1868. newBuffer.size_ = size;
  1869. newBuffer.reserved_ = true;
  1870. scratchBuffers_.Push(newBuffer);
  1871. return newBuffer.data_.Get();
  1872. }
  1873. void Graphics::FreeScratchBuffer(void* buffer)
  1874. {
  1875. if (!buffer)
  1876. return;
  1877. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1878. {
  1879. if (i->reserved_ && i->data_.Get() == buffer)
  1880. {
  1881. i->reserved_ = false;
  1882. return;
  1883. }
  1884. }
  1885. LOGWARNING("Reserved scratch buffer " + ToStringHex((unsigned)(size_t)buffer) + " not found");
  1886. }
  1887. void Graphics::CleanupScratchBuffers()
  1888. {
  1889. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1890. {
  1891. if (!i->reserved_ && i->size_ > maxScratchBufferRequest_ * 2)
  1892. {
  1893. i->data_ = maxScratchBufferRequest_ > 0 ? new unsigned char[maxScratchBufferRequest_] : 0;
  1894. i->size_ = maxScratchBufferRequest_;
  1895. }
  1896. }
  1897. maxScratchBufferRequest_ = 0;
  1898. }
  1899. void Graphics::Release(bool clearGPUObjects, bool closeWindow)
  1900. {
  1901. if (!impl_->window_)
  1902. return;
  1903. releasingGPUObjects_ = true;
  1904. if (clearGPUObjects)
  1905. {
  1906. // Shutting down: release all GPU objects that still exist
  1907. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1908. (*i)->Release();
  1909. gpuObjects_.Clear();
  1910. }
  1911. else
  1912. {
  1913. // We are not shutting down, but recreating the context: mark GPU objects lost
  1914. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1915. (*i)->OnDeviceLost();
  1916. }
  1917. releasingGPUObjects_ = false;
  1918. CleanupFramebuffers(true);
  1919. depthTextures_.Clear();
  1920. shaderPrograms_.Clear();
  1921. // End fullscreen mode first to counteract transition and getting stuck problems on OS X
  1922. #if defined(__APPLE__) && !defined(IOS)
  1923. if (closeWindow && fullscreen_ && !externalWindow_)
  1924. SDL_SetWindowFullscreen(impl_->window_, SDL_FALSE);
  1925. #endif
  1926. if (impl_->context_)
  1927. {
  1928. // Do not log this message if we are exiting
  1929. if (!clearGPUObjects)
  1930. LOGINFO("OpenGL context lost");
  1931. SDL_GL_DeleteContext(impl_->context_);
  1932. impl_->context_ = 0;
  1933. }
  1934. if (closeWindow)
  1935. {
  1936. SDL_ShowCursor(SDL_TRUE);
  1937. // Do not destroy external window except when shutting down
  1938. if (!externalWindow_ || clearGPUObjects)
  1939. {
  1940. SDL_DestroyWindow(impl_->window_);
  1941. impl_->window_ = 0;
  1942. }
  1943. }
  1944. }
  1945. void Graphics::Restore()
  1946. {
  1947. if (!impl_->window_)
  1948. return;
  1949. #ifdef ANDROID
  1950. // On Android the context may be lost behind the scenes as the application is minimized
  1951. if (impl_->context_ && !SDL_GL_GetCurrentContext())
  1952. {
  1953. impl_->context_ = 0;
  1954. // Mark GPU objects lost without a current context. In this case they just mark their internal state lost
  1955. // but do not perform OpenGL commands to delete the GL objects
  1956. Release(false, false);
  1957. }
  1958. #endif
  1959. // Ensure first that the context exists
  1960. if (!impl_->context_)
  1961. {
  1962. impl_->context_ = SDL_GL_CreateContext(impl_->window_);
  1963. #ifdef IOS
  1964. glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&impl_->systemFbo_);
  1965. #endif
  1966. ResetCachedState();
  1967. }
  1968. if (!impl_->context_)
  1969. return;
  1970. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1971. (*i)->OnDeviceReset();
  1972. }
  1973. void Graphics::Maximize()
  1974. {
  1975. if (!impl_->window_)
  1976. return;
  1977. SDL_MaximizeWindow(impl_->window_);
  1978. }
  1979. void Graphics::Minimize()
  1980. {
  1981. if (!impl_->window_)
  1982. return;
  1983. SDL_MinimizeWindow(impl_->window_);
  1984. }
  1985. void Graphics::CleanupRenderSurface(RenderSurface* surface)
  1986. {
  1987. if (!surface)
  1988. return;
  1989. // Flush pending FBO changes first if any
  1990. CommitFramebuffer();
  1991. unsigned currentFbo = impl_->boundFbo_;
  1992. // Go through all FBOs and clean up the surface from them
  1993. for (HashMap<unsigned long long, FrameBufferObject>::Iterator i = impl_->frameBuffers_.Begin();
  1994. i != impl_->frameBuffers_.End(); ++i)
  1995. {
  1996. for (unsigned j = 0; j < MAX_RENDERTARGETS; ++j)
  1997. {
  1998. if (i->second_.colorAttachments_[j] == surface)
  1999. {
  2000. if (currentFbo != i->second_.fbo_)
  2001. {
  2002. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, i->second_.fbo_);
  2003. currentFbo = i->second_.fbo_;
  2004. }
  2005. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + j, GL_TEXTURE_2D, 0, 0);
  2006. i->second_.colorAttachments_[j] = 0;
  2007. // Mark drawbuffer bits to need recalculation
  2008. i->second_.drawBuffers_ = M_MAX_UNSIGNED;
  2009. }
  2010. }
  2011. if (i->second_.depthAttachment_ == surface)
  2012. {
  2013. if (currentFbo != i->second_.fbo_)
  2014. {
  2015. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, i->second_.fbo_);
  2016. currentFbo = i->second_.fbo_;
  2017. }
  2018. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  2019. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  2020. i->second_.depthAttachment_ = 0;
  2021. }
  2022. }
  2023. // Restore previously bound FBO now if needed
  2024. if (currentFbo != impl_->boundFbo_)
  2025. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, impl_->boundFbo_);
  2026. }
  2027. void Graphics::MarkFBODirty()
  2028. {
  2029. impl_->fboDirty_ = true;
  2030. }
  2031. unsigned Graphics::GetAlphaFormat()
  2032. {
  2033. return GL_ALPHA;
  2034. }
  2035. unsigned Graphics::GetLuminanceFormat()
  2036. {
  2037. return GL_LUMINANCE;
  2038. }
  2039. unsigned Graphics::GetLuminanceAlphaFormat()
  2040. {
  2041. return GL_LUMINANCE_ALPHA;
  2042. }
  2043. unsigned Graphics::GetRGBFormat()
  2044. {
  2045. return GL_RGB;
  2046. }
  2047. unsigned Graphics::GetRGBAFormat()
  2048. {
  2049. return GL_RGBA;
  2050. }
  2051. unsigned Graphics::GetRGBA16Format()
  2052. {
  2053. #ifndef GL_ES_VERSION_2_0
  2054. return GL_RGBA16;
  2055. #else
  2056. return GL_RGBA;
  2057. #endif
  2058. }
  2059. unsigned Graphics::GetRGBAFloat16Format()
  2060. {
  2061. #ifndef GL_ES_VERSION_2_0
  2062. return GL_RGBA16F_ARB;
  2063. #else
  2064. return GL_RGBA;
  2065. #endif
  2066. }
  2067. unsigned Graphics::GetRGBAFloat32Format()
  2068. {
  2069. #ifndef GL_ES_VERSION_2_0
  2070. return GL_RGBA32F_ARB;
  2071. #else
  2072. return GL_RGBA;
  2073. #endif
  2074. }
  2075. unsigned Graphics::GetRG16Format()
  2076. {
  2077. #ifndef GL_ES_VERSION_2_0
  2078. return GL_RG16;
  2079. #else
  2080. return GL_RGBA;
  2081. #endif
  2082. }
  2083. unsigned Graphics::GetRGFloat16Format()
  2084. {
  2085. #ifndef GL_ES_VERSION_2_0
  2086. return GL_RG16F;
  2087. #else
  2088. return GL_RGBA;
  2089. #endif
  2090. }
  2091. unsigned Graphics::GetRGFloat32Format()
  2092. {
  2093. #ifndef GL_ES_VERSION_2_0
  2094. return GL_RG32F;
  2095. #else
  2096. return GL_RGBA;
  2097. #endif
  2098. }
  2099. unsigned Graphics::GetFloat16Format()
  2100. {
  2101. #ifndef GL_ES_VERSION_2_0
  2102. return GL_LUMINANCE16F_ARB;
  2103. #else
  2104. return GL_LUMINANCE;
  2105. #endif
  2106. }
  2107. unsigned Graphics::GetFloat32Format()
  2108. {
  2109. #ifndef GL_ES_VERSION_2_0
  2110. return GL_LUMINANCE32F_ARB;
  2111. #else
  2112. return GL_LUMINANCE;
  2113. #endif
  2114. }
  2115. unsigned Graphics::GetLinearDepthFormat()
  2116. {
  2117. // OpenGL FBO specs state that color attachments must have the same format; therefore must encode linear depth to RGBA
  2118. // manually if not using a readable hardware depth texture
  2119. return GL_RGBA;
  2120. }
  2121. unsigned Graphics::GetDepthStencilFormat()
  2122. {
  2123. #ifndef GL_ES_VERSION_2_0
  2124. return GL_DEPTH24_STENCIL8_EXT;
  2125. #else
  2126. return glesDepthStencilFormat;
  2127. #endif
  2128. }
  2129. unsigned Graphics::GetFormat(const String& formatName)
  2130. {
  2131. String nameLower = formatName.ToLower().Trimmed();
  2132. if (nameLower == "a")
  2133. return GetAlphaFormat();
  2134. if (nameLower == "l")
  2135. return GetLuminanceFormat();
  2136. if (nameLower == "la")
  2137. return GetLuminanceAlphaFormat();
  2138. if (nameLower == "rgb")
  2139. return GetRGBFormat();
  2140. if (nameLower == "rgba")
  2141. return GetRGBAFormat();
  2142. if (nameLower == "rgba16")
  2143. return GetRGBA16Format();
  2144. if (nameLower == "rgba16f")
  2145. return GetRGBAFloat16Format();
  2146. if (nameLower == "rgba32f")
  2147. return GetRGBAFloat32Format();
  2148. if (nameLower == "rg16")
  2149. return GetRG16Format();
  2150. if (nameLower == "rg16f")
  2151. return GetRGFloat16Format();
  2152. if (nameLower == "rg32f")
  2153. return GetRGFloat32Format();
  2154. if (nameLower == "r16f")
  2155. return GetFloat16Format();
  2156. if (nameLower == "r32f" || nameLower == "float")
  2157. return GetFloat32Format();
  2158. if (nameLower == "lineardepth" || nameLower == "depth")
  2159. return GetLinearDepthFormat();
  2160. if (nameLower == "d24s8")
  2161. return GetDepthStencilFormat();
  2162. return GetRGBFormat();
  2163. }
  2164. void Graphics::CreateWindowIcon()
  2165. {
  2166. if (windowIcon_)
  2167. {
  2168. SDL_Surface* surface = windowIcon_->GetSDLSurface();
  2169. if (surface)
  2170. {
  2171. SDL_SetWindowIcon(impl_->window_, surface);
  2172. SDL_FreeSurface(surface);
  2173. }
  2174. }
  2175. }
  2176. void Graphics::CheckFeatureSupport(String& extensions)
  2177. {
  2178. // Check supported features: light pre-pass, deferred rendering and hardware depth texture
  2179. lightPrepassSupport_ = false;
  2180. deferredSupport_ = false;
  2181. int numSupportedRTs = 1;
  2182. #ifndef GL_ES_VERSION_2_0
  2183. glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS_EXT, &numSupportedRTs);
  2184. // If hardware depth is not supported, must support 2 rendertargets for light pre-pass, and 4 for deferred
  2185. if (numSupportedRTs >= 2)
  2186. lightPrepassSupport_ = true;
  2187. if (numSupportedRTs >= 4)
  2188. deferredSupport_ = true;
  2189. #if defined(__APPLE__) && !defined(IOS)
  2190. // On OS X check for an Intel driver and use shadow map RGBA dummy color textures, because mixing
  2191. // depth-only FBO rendering and backbuffer rendering will bug, resulting in a black screen in full
  2192. // screen mode, and incomplete shadow maps in windowed mode
  2193. String renderer((const char*)glGetString(GL_RENDERER));
  2194. if (renderer.Contains("Intel", false))
  2195. dummyColorFormat_ = GetRGBAFormat();
  2196. #endif
  2197. #else
  2198. // Check for best supported depth renderbuffer format for GLES2
  2199. if (CheckExtension(extensions, "GL_OES_depth24"))
  2200. glesDepthStencilFormat = GL_DEPTH_COMPONENT24_OES;
  2201. if (CheckExtension(extensions, "GL_OES_packed_depth_stencil"))
  2202. glesDepthStencilFormat = GL_DEPTH24_STENCIL8_OES;
  2203. if (!CheckExtension(extensions, "GL_OES_depth_texture"))
  2204. {
  2205. shadowMapFormat_ = 0;
  2206. hiresShadowMapFormat_ = 0;
  2207. }
  2208. else
  2209. {
  2210. #ifdef IOS
  2211. // iOS hack: depth renderbuffer seems to fail, so use depth textures for everything
  2212. // if supported
  2213. glesDepthStencilFormat = GL_DEPTH_COMPONENT;
  2214. #endif
  2215. shadowMapFormat_ = GL_DEPTH_COMPONENT;
  2216. hiresShadowMapFormat_ = 0;
  2217. }
  2218. #endif
  2219. }
  2220. void Graphics::CommitFramebuffer()
  2221. {
  2222. if (!impl_->fboDirty_)
  2223. return;
  2224. impl_->fboDirty_ = false;
  2225. // First check if no framebuffer is needed. In that case simply return to backbuffer rendering
  2226. bool noFbo = !depthStencil_;
  2227. if (noFbo)
  2228. {
  2229. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  2230. {
  2231. if (renderTargets_[i])
  2232. {
  2233. noFbo = false;
  2234. break;
  2235. }
  2236. }
  2237. }
  2238. if (noFbo)
  2239. {
  2240. if (impl_->boundFbo_ != impl_->systemFbo_)
  2241. {
  2242. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, impl_->systemFbo_);
  2243. impl_->boundFbo_ = impl_->systemFbo_;
  2244. }
  2245. #ifndef GL_ES_VERSION_2_0
  2246. // Disable/enable sRGB write
  2247. if (sRGBWriteSupport_)
  2248. {
  2249. bool sRGBWrite = sRGB_;
  2250. if (sRGBWrite != impl_->sRGBWrite_)
  2251. {
  2252. if (sRGBWrite)
  2253. glEnable(GL_FRAMEBUFFER_SRGB_EXT);
  2254. else
  2255. glDisable(GL_FRAMEBUFFER_SRGB_EXT);
  2256. impl_->sRGBWrite_ = sRGBWrite;
  2257. }
  2258. }
  2259. #endif
  2260. return;
  2261. }
  2262. // Search for a new framebuffer based on format & size, or create new
  2263. IntVector2 rtSize = Graphics::GetRenderTargetDimensions();
  2264. unsigned format = 0;
  2265. if (renderTargets_[0])
  2266. format = renderTargets_[0]->GetParentTexture()->GetFormat();
  2267. else if (depthStencil_)
  2268. format = depthStencil_->GetParentTexture()->GetFormat();
  2269. unsigned long long fboKey = (rtSize.x_ << 16 | rtSize.y_) | (((unsigned long long)format) << 32);
  2270. HashMap<unsigned long long, FrameBufferObject>::Iterator i = impl_->frameBuffers_.Find(fboKey);
  2271. if (i == impl_->frameBuffers_.End())
  2272. {
  2273. FrameBufferObject newFbo;
  2274. glGenFramebuffersEXT(1, &newFbo.fbo_);
  2275. i = impl_->frameBuffers_.Insert(MakePair(fboKey, newFbo));
  2276. }
  2277. i->second_.useTimer_.Reset();
  2278. if (impl_->boundFbo_ != i->second_.fbo_)
  2279. {
  2280. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, i->second_.fbo_);
  2281. impl_->boundFbo_ = i->second_.fbo_;
  2282. }
  2283. #ifndef GL_ES_VERSION_2_0
  2284. // Setup readbuffers & drawbuffers if needed
  2285. if (i->second_.readBuffers_ != GL_NONE)
  2286. {
  2287. glReadBuffer(GL_NONE);
  2288. i->second_.readBuffers_ = GL_NONE;
  2289. }
  2290. // Calculate the bit combination of non-zero color rendertargets to first check if the combination changed
  2291. unsigned newDrawBuffers = 0;
  2292. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  2293. {
  2294. if (renderTargets_[i])
  2295. newDrawBuffers |= 1 << i;
  2296. }
  2297. if (newDrawBuffers != i->second_.drawBuffers_)
  2298. {
  2299. // Check for no color rendertargets (depth rendering only)
  2300. if (!newDrawBuffers)
  2301. glDrawBuffer(GL_NONE);
  2302. else
  2303. {
  2304. int drawBufferIds[MAX_RENDERTARGETS];
  2305. unsigned drawBufferCount = 0;
  2306. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  2307. {
  2308. if (renderTargets_[i])
  2309. drawBufferIds[drawBufferCount++] = GL_COLOR_ATTACHMENT0_EXT + i;
  2310. }
  2311. glDrawBuffers(drawBufferCount, (const GLenum*)drawBufferIds);
  2312. }
  2313. i->second_.drawBuffers_ = newDrawBuffers;
  2314. }
  2315. #endif
  2316. for (unsigned j = 0; j < MAX_RENDERTARGETS; ++j)
  2317. {
  2318. if (renderTargets_[j])
  2319. {
  2320. Texture* texture = renderTargets_[j]->GetParentTexture();
  2321. // If texture's parameters are dirty, update before attaching
  2322. if (texture->GetParametersDirty())
  2323. {
  2324. SetTextureForUpdate(texture);
  2325. texture->UpdateParameters();
  2326. SetTexture(0, 0);
  2327. }
  2328. if (i->second_.colorAttachments_[j] != renderTargets_[j])
  2329. {
  2330. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + j, renderTargets_[j]->GetTarget(),
  2331. texture->GetGPUObject(), 0);
  2332. i->second_.colorAttachments_[j] = renderTargets_[j];
  2333. }
  2334. }
  2335. else
  2336. {
  2337. if (i->second_.colorAttachments_[j])
  2338. {
  2339. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + j, GL_TEXTURE_2D, 0, 0);
  2340. i->second_.colorAttachments_[j] = 0;
  2341. }
  2342. }
  2343. }
  2344. if (depthStencil_)
  2345. {
  2346. // Bind either a renderbuffer or a depth texture, depending on what is available
  2347. Texture* texture = depthStencil_->GetParentTexture();
  2348. #ifndef GL_ES_VERSION_2_0
  2349. bool hasStencil = texture->GetFormat() == GL_DEPTH24_STENCIL8_EXT;
  2350. #else
  2351. bool hasStencil = texture->GetFormat() == GL_DEPTH24_STENCIL8_OES;
  2352. #endif
  2353. unsigned renderBufferID = depthStencil_->GetRenderBuffer();
  2354. if (!renderBufferID)
  2355. {
  2356. // If texture's parameters are dirty, update before attaching
  2357. if (texture->GetParametersDirty())
  2358. {
  2359. SetTextureForUpdate(texture);
  2360. texture->UpdateParameters();
  2361. SetTexture(0, 0);
  2362. }
  2363. if (i->second_.depthAttachment_ != depthStencil_)
  2364. {
  2365. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, texture->GetGPUObject(), 0);
  2366. if (hasStencil)
  2367. {
  2368. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D,
  2369. texture->GetGPUObject(), 0);
  2370. }
  2371. else
  2372. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  2373. i->second_.depthAttachment_ = depthStencil_;
  2374. }
  2375. }
  2376. else
  2377. {
  2378. if (i->second_.depthAttachment_ != depthStencil_)
  2379. {
  2380. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, renderBufferID);
  2381. if (hasStencil)
  2382. {
  2383. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT,
  2384. renderBufferID);
  2385. }
  2386. else
  2387. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  2388. i->second_.depthAttachment_ = depthStencil_;
  2389. }
  2390. }
  2391. }
  2392. else
  2393. {
  2394. if (i->second_.depthAttachment_)
  2395. {
  2396. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  2397. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  2398. i->second_.depthAttachment_ = 0;
  2399. }
  2400. }
  2401. #ifndef GL_ES_VERSION_2_0
  2402. // Disable/enable sRGB write
  2403. if (sRGBWriteSupport_)
  2404. {
  2405. bool sRGBWrite = renderTargets_[0] ? renderTargets_[0]->GetParentTexture()->GetSRGB() : sRGB_;
  2406. if (sRGBWrite != impl_->sRGBWrite_)
  2407. {
  2408. if (sRGBWrite)
  2409. glEnable(GL_FRAMEBUFFER_SRGB_EXT);
  2410. else
  2411. glDisable(GL_FRAMEBUFFER_SRGB_EXT);
  2412. impl_->sRGBWrite_ = sRGBWrite;
  2413. }
  2414. }
  2415. #endif
  2416. }
  2417. bool Graphics::CheckFramebuffer()
  2418. {
  2419. return glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT) == GL_FRAMEBUFFER_COMPLETE_EXT;
  2420. }
  2421. void Graphics::CleanupFramebuffers(bool force)
  2422. {
  2423. if (!IsDeviceLost())
  2424. {
  2425. for (HashMap<unsigned long long, FrameBufferObject>::Iterator i = impl_->frameBuffers_.Begin();
  2426. i != impl_->frameBuffers_.End();)
  2427. {
  2428. if (i->second_.fbo_ != impl_->boundFbo_ && (force || i->second_.useTimer_.GetMSec(false) >
  2429. MAX_FRAMEBUFFER_AGE))
  2430. {
  2431. glDeleteFramebuffersEXT(1, &i->second_.fbo_);
  2432. i = impl_->frameBuffers_.Erase(i);
  2433. }
  2434. else
  2435. ++i;
  2436. }
  2437. }
  2438. else
  2439. {
  2440. impl_->boundFbo_ = 0;
  2441. impl_->frameBuffers_.Clear();
  2442. }
  2443. }
  2444. void Graphics::ResetCachedState()
  2445. {
  2446. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  2447. {
  2448. vertexBuffers_[i] = 0;
  2449. elementMasks_[i] = 0;
  2450. }
  2451. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  2452. {
  2453. textures_[i] = 0;
  2454. textureTypes_[i] = 0;
  2455. }
  2456. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  2457. renderTargets_[i] = 0;
  2458. depthStencil_ = 0;
  2459. viewport_ = IntRect(0, 0, 0, 0);
  2460. indexBuffer_ = 0;
  2461. vertexShader_ = 0;
  2462. pixelShader_ = 0;
  2463. shaderProgram_ = 0;
  2464. blendMode_ = BLEND_REPLACE;
  2465. textureAnisotropy_ = 1;
  2466. colorWrite_ = true;
  2467. cullMode_ = CULL_NONE;
  2468. constantDepthBias_ = 0.0f;
  2469. slopeScaledDepthBias_ = 0.0f;
  2470. depthTestMode_ = CMP_ALWAYS;
  2471. depthWrite_ = false;
  2472. fillMode_ = FILL_SOLID;
  2473. scissorTest_ = false;
  2474. scissorRect_ = IntRect::ZERO;
  2475. stencilTest_ = false;
  2476. stencilTestMode_ = CMP_ALWAYS;
  2477. stencilPass_ = OP_KEEP;
  2478. stencilFail_ = OP_KEEP;
  2479. stencilZFail_ = OP_KEEP;
  2480. stencilRef_ = 0;
  2481. stencilCompareMask_ = M_MAX_UNSIGNED;
  2482. stencilWriteMask_ = M_MAX_UNSIGNED;
  2483. lastInstanceOffset_ = 0;
  2484. useClipPlane_ = false;
  2485. impl_->activeTexture_ = 0;
  2486. impl_->enabledAttributes_ = 0;
  2487. impl_->boundFbo_ = impl_->systemFbo_;
  2488. impl_->sRGBWrite_ = false;
  2489. // Set initial state to match Direct3D
  2490. if (impl_->context_)
  2491. {
  2492. glEnable(GL_DEPTH_TEST);
  2493. SetCullMode(CULL_CCW);
  2494. SetDepthTest(CMP_LESSEQUAL);
  2495. SetDepthWrite(true);
  2496. }
  2497. }
  2498. void Graphics::SetTextureUnitMappings()
  2499. {
  2500. textureUnits_["DiffMap"] = TU_DIFFUSE;
  2501. textureUnits_["DiffCubeMap"] = TU_DIFFUSE;
  2502. textureUnits_["NormalMap"] = TU_NORMAL;
  2503. textureUnits_["SpecMap"] = TU_SPECULAR;
  2504. textureUnits_["EmissiveMap"] = TU_EMISSIVE;
  2505. textureUnits_["EnvMap"] = TU_ENVIRONMENT;
  2506. textureUnits_["EnvCubeMap"] = TU_ENVIRONMENT;
  2507. textureUnits_["LightRampMap"] = TU_LIGHTRAMP;
  2508. textureUnits_["LightSpotMap"] = TU_LIGHTSHAPE;
  2509. textureUnits_["LightCubeMap"] = TU_LIGHTSHAPE;
  2510. textureUnits_["ShadowMap"] = TU_SHADOWMAP;
  2511. textureUnits_["FaceSelectCubeMap"] = TU_FACESELECT;
  2512. textureUnits_["IndirectionCubeMap"] = TU_INDIRECTION;
  2513. textureUnits_["AlbedoBuffer"] = TU_ALBEDOBUFFER;
  2514. textureUnits_["NormalBuffer"] = TU_NORMALBUFFER;
  2515. textureUnits_["DepthBuffer"] = TU_DEPTHBUFFER;
  2516. textureUnits_["LightBuffer"] = TU_LIGHTBUFFER;
  2517. textureUnits_["VolumeMap"] = TU_VOLUMEMAP;
  2518. }
  2519. void RegisterGraphicsLibrary(Context* context)
  2520. {
  2521. Animation::RegisterObject(context);
  2522. Material::RegisterObject(context);
  2523. Model::RegisterObject(context);
  2524. Shader::RegisterObject(context);
  2525. Technique::RegisterObject(context);
  2526. Texture2D::RegisterObject(context);
  2527. Texture3D::RegisterObject(context);
  2528. TextureCube::RegisterObject(context);
  2529. Camera::RegisterObject(context);
  2530. Drawable::RegisterObject(context);
  2531. Light::RegisterObject(context);
  2532. StaticModel::RegisterObject(context);
  2533. StaticModelGroup::RegisterObject(context);
  2534. Skybox::RegisterObject(context);
  2535. AnimatedModel::RegisterObject(context);
  2536. AnimationController::RegisterObject(context);
  2537. BillboardSet::RegisterObject(context);
  2538. ParticleEmitter::RegisterObject(context);
  2539. CustomGeometry::RegisterObject(context);
  2540. DecalSet::RegisterObject(context);
  2541. Terrain::RegisterObject(context);
  2542. TerrainPatch::RegisterObject(context);
  2543. DebugRenderer::RegisterObject(context);
  2544. Octree::RegisterObject(context);
  2545. Zone::RegisterObject(context);
  2546. }
  2547. }