OGLGraphics.cpp 81 KB

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