OGLGraphics.cpp 86 KB

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