OGLGraphics.cpp 100 KB

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