OGLGraphics.cpp 67 KB

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