OGLGraphics.cpp 76 KB

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