OGLGraphics.cpp 69 KB

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