OGLGraphics.cpp 87 KB

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