OGLGraphics.cpp 87 KB

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