OGLGraphics.cpp 87 KB

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