OGLGraphics.cpp 98 KB

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