2
0

OGLGraphics.cpp 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257
  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. int depthBits = Min(impl_->depthBits_, 23);
  1201. if (!depthBits)
  1202. depthBits = 23;
  1203. float adjustedConstantBias = constantBias * (float)(1 << (depthBits - 1));
  1204. float adjustedSlopeScaledBias = slopeScaledBias + 1.0f;
  1205. glEnable(GL_POLYGON_OFFSET_FILL);
  1206. glPolygonOffset(adjustedSlopeScaledBias, adjustedConstantBias);
  1207. }
  1208. else
  1209. glDisable(GL_POLYGON_OFFSET_FILL);
  1210. constantDepthBias_ = constantBias;
  1211. slopeScaledDepthBias_ = slopeScaledBias;
  1212. }
  1213. }
  1214. void Graphics::SetDepthTest(CompareMode mode)
  1215. {
  1216. if (mode != depthTestMode_)
  1217. {
  1218. glDepthFunc(glCmpFunc[mode]);
  1219. depthTestMode_ = mode;
  1220. }
  1221. }
  1222. void Graphics::SetDepthWrite(bool enable)
  1223. {
  1224. if (enable != depthWrite_)
  1225. {
  1226. glDepthMask(enable ? GL_TRUE : GL_FALSE);
  1227. depthWrite_ = enable;
  1228. }
  1229. }
  1230. void Graphics::SetScissorTest(bool enable, const Rect& rect, bool borderInclusive)
  1231. {
  1232. // During some light rendering loops, a full rect is toggled on/off repeatedly.
  1233. // Disable scissor in that case to reduce state changes
  1234. if (rect.min_.x_ <= 0.0f && rect.min_.y_ <= 0.0f && rect.max_.x_ >= 1.0f && rect.max_.y_ >= 1.0f)
  1235. enable = false;
  1236. if (enable)
  1237. {
  1238. IntVector2 rtSize(GetRenderTargetDimensions());
  1239. IntVector2 viewSize(viewport_.right_ - viewport_.left_, viewport_.bottom_ - viewport_.top_);
  1240. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1241. IntRect intRect;
  1242. int expand = borderInclusive ? 1 : 0;
  1243. intRect.left_ = Clamp((int)((rect.min_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_, 0, rtSize.x_ - 1);
  1244. intRect.top_ = Clamp((int)((-rect.max_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_, 0, rtSize.y_ - 1);
  1245. intRect.right_ = Clamp((int)((rect.max_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_ + expand, 0, rtSize.x_);
  1246. intRect.bottom_ = Clamp((int)((-rect.min_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_ + expand, 0, rtSize.y_);
  1247. if (intRect.right_ == intRect.left_)
  1248. intRect.right_++;
  1249. if (intRect.bottom_ == intRect.top_)
  1250. intRect.bottom_++;
  1251. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1252. enable = false;
  1253. if (enable && scissorRect_ != intRect)
  1254. {
  1255. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1256. glScissor(intRect.left_, rtSize.y_ - intRect.bottom_, intRect.right_ - intRect.left_, intRect.bottom_ - intRect.top_);
  1257. scissorRect_ = intRect;
  1258. }
  1259. }
  1260. else
  1261. scissorRect_ = IntRect::ZERO;
  1262. if (enable != scissorTest_)
  1263. {
  1264. if (enable)
  1265. glEnable(GL_SCISSOR_TEST);
  1266. else
  1267. glDisable(GL_SCISSOR_TEST);
  1268. scissorTest_ = enable;
  1269. }
  1270. }
  1271. void Graphics::SetScissorTest(bool enable, const IntRect& rect)
  1272. {
  1273. IntVector2 rtSize(GetRenderTargetDimensions());
  1274. IntVector2 viewSize(viewport_.right_ - viewport_.left_, viewport_.bottom_ - viewport_.top_);
  1275. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1276. if (enable)
  1277. {
  1278. IntRect intRect;
  1279. intRect.left_ = Clamp(rect.left_ + viewPos.x_, 0, rtSize.x_ - 1);
  1280. intRect.top_ = Clamp(rect.top_ + viewPos.y_, 0, rtSize.y_ - 1);
  1281. intRect.right_ = Clamp(rect.right_ + viewPos.x_, 0, rtSize.x_);
  1282. intRect.bottom_ = Clamp(rect.bottom_ + viewPos.y_, 0, rtSize.y_);
  1283. if (intRect.right_ == intRect.left_)
  1284. intRect.right_++;
  1285. if (intRect.bottom_ == intRect.top_)
  1286. intRect.bottom_++;
  1287. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1288. enable = false;
  1289. if (enable && scissorRect_ != intRect)
  1290. {
  1291. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1292. glScissor(intRect.left_, rtSize.y_ - intRect.bottom_, intRect.right_ - intRect.left_, intRect.bottom_ - intRect.top_);
  1293. scissorRect_ = intRect;
  1294. }
  1295. }
  1296. else
  1297. scissorRect_ = IntRect::ZERO;
  1298. if (enable != scissorTest_)
  1299. {
  1300. if (enable)
  1301. glEnable(GL_SCISSOR_TEST);
  1302. else
  1303. glDisable(GL_SCISSOR_TEST);
  1304. scissorTest_ = enable;
  1305. }
  1306. }
  1307. void Graphics::SetStreamFrequency(unsigned index, unsigned frequency)
  1308. {
  1309. }
  1310. void Graphics::ResetStreamFrequencies()
  1311. {
  1312. }
  1313. void Graphics::SetStencilTest(bool enable, CompareMode mode, StencilOp pass, StencilOp fail, StencilOp zFail, unsigned stencilRef, unsigned compareMask, unsigned writeMask)
  1314. {
  1315. if (enable != stencilTest_)
  1316. {
  1317. if (enable)
  1318. glEnable(GL_STENCIL_TEST);
  1319. else
  1320. glDisable(GL_STENCIL_TEST);
  1321. stencilTest_ = enable;
  1322. }
  1323. if (enable)
  1324. {
  1325. if (mode != stencilTestMode_ || stencilRef != stencilRef_ || compareMask != stencilCompareMask_)
  1326. {
  1327. glStencilFunc(glCmpFunc[mode], stencilRef, compareMask);
  1328. stencilTestMode_ = mode;
  1329. stencilRef_ = stencilRef;
  1330. stencilCompareMask_ = compareMask;
  1331. }
  1332. if (writeMask != stencilWriteMask_)
  1333. {
  1334. glStencilMask(writeMask);
  1335. stencilWriteMask_ = writeMask;
  1336. }
  1337. if (pass != stencilPass_ || fail != stencilFail_ || zFail != stencilZFail_)
  1338. {
  1339. glStencilOp(glStencilOps[fail], glStencilOps[zFail], glStencilOps[pass]);
  1340. stencilPass_ = pass;
  1341. stencilFail_ = fail;
  1342. stencilZFail_ = zFail;
  1343. }
  1344. }
  1345. }
  1346. void Graphics::SetForceSM2(bool enable)
  1347. {
  1348. }
  1349. bool Graphics::IsInitialized() const
  1350. {
  1351. return impl_->window_ != 0;
  1352. }
  1353. void* Graphics::GetWindowHandle() const
  1354. {
  1355. return impl_->window_;
  1356. }
  1357. PODVector<IntVector2> Graphics::GetResolutions() const
  1358. {
  1359. PODVector<IntVector2> ret;
  1360. unsigned numModes = SDL_GetNumDisplayModes(0);
  1361. for (unsigned i = 0; i < numModes; ++i)
  1362. {
  1363. SDL_DisplayMode mode;
  1364. SDL_GetDisplayMode(0, i, &mode);
  1365. int width = mode.w;
  1366. int height = mode.h;
  1367. // Store mode if unique
  1368. bool unique = true;
  1369. for (unsigned j = 0; j < ret.Size(); ++i)
  1370. {
  1371. if (ret[j].x_ == width && ret[j].y_ == height)
  1372. {
  1373. unique = false;
  1374. break;
  1375. }
  1376. }
  1377. if (unique)
  1378. ret.Push(IntVector2(width, height));
  1379. }
  1380. return ret;
  1381. }
  1382. PODVector<int> Graphics::GetMultiSampleLevels() const
  1383. {
  1384. PODVector<int> ret;
  1385. // No multisampling always supported
  1386. ret.Push(1);
  1387. /// \todo Implement properly, if possible
  1388. return ret;
  1389. }
  1390. VertexBuffer* Graphics::GetVertexBuffer(unsigned index) const
  1391. {
  1392. return index < MAX_VERTEX_STREAMS ? vertexBuffers_[index] : 0;
  1393. }
  1394. TextureUnit Graphics::GetTextureUnit(const String& name)
  1395. {
  1396. Map<String, TextureUnit>::Iterator i = textureUnits_.Find(name);
  1397. if (i != textureUnits_.End())
  1398. return i->second_;
  1399. else
  1400. return MAX_TEXTURE_UNITS;
  1401. }
  1402. const String& Graphics::GetTextureUnitName(TextureUnit unit)
  1403. {
  1404. for (Map<String, TextureUnit>::Iterator i = textureUnits_.Begin(); i != textureUnits_.End(); ++i)
  1405. {
  1406. if (i->second_ == unit)
  1407. return i->first_;
  1408. }
  1409. return noParameter;
  1410. }
  1411. Texture* Graphics::GetTexture(unsigned index) const
  1412. {
  1413. return index < MAX_TEXTURE_UNITS ? textures_[index] : 0;
  1414. }
  1415. RenderSurface* Graphics::GetRenderTarget(unsigned index) const
  1416. {
  1417. return index < MAX_RENDERTARGETS ? renderTargets_[index] : 0;
  1418. }
  1419. IntVector2 Graphics::GetRenderTargetDimensions() const
  1420. {
  1421. int width, height;
  1422. if (renderTargets_[0])
  1423. {
  1424. width = renderTargets_[0]->GetWidth();
  1425. height = renderTargets_[0]->GetHeight();
  1426. }
  1427. else if (depthStencil_)
  1428. {
  1429. width = depthStencil_->GetWidth();
  1430. height = depthStencil_->GetHeight();
  1431. }
  1432. else
  1433. {
  1434. width = width_;
  1435. height = height_;
  1436. }
  1437. return IntVector2(width, height);
  1438. }
  1439. void Graphics::AddGPUObject(GPUObject* object)
  1440. {
  1441. gpuObjects_.Push(object);
  1442. }
  1443. void Graphics::RemoveGPUObject(GPUObject* object)
  1444. {
  1445. gpuObjects_.Erase(gpuObjects_.Find(object));
  1446. }
  1447. void* Graphics::ReserveDiscardLockBuffer(unsigned size)
  1448. {
  1449. // First check for a free buffer that is large enough
  1450. for (Vector<DiscardLockBuffer>::Iterator i = discardLockBuffers_.Begin(); i != discardLockBuffers_.End(); ++i)
  1451. {
  1452. if (!i->reserved_ && i->size_ >= size)
  1453. {
  1454. i->reserved_ = true;
  1455. return i->data_.Get();
  1456. }
  1457. }
  1458. // Then check if a free buffer can be resized
  1459. for (Vector<DiscardLockBuffer>::Iterator i = discardLockBuffers_.Begin(); i != discardLockBuffers_.End(); ++i)
  1460. {
  1461. if (!i->reserved_)
  1462. {
  1463. i->data_ = new unsigned char[size];
  1464. i->size_ = size;
  1465. i->reserved_ = true;
  1466. return i->data_.Get();
  1467. }
  1468. }
  1469. // Finally allocate a new buffer
  1470. DiscardLockBuffer newBuffer;
  1471. newBuffer.data_ = new unsigned char[size];
  1472. newBuffer.size_ = size;
  1473. newBuffer.reserved_ = true;
  1474. discardLockBuffers_.Push(newBuffer);
  1475. return newBuffer.data_.Get();
  1476. }
  1477. void Graphics::FreeDiscardLockBuffer(void* buffer)
  1478. {
  1479. for (Vector<DiscardLockBuffer>::Iterator i = discardLockBuffers_.Begin(); i != discardLockBuffers_.End(); ++i)
  1480. {
  1481. if (i->reserved_ && i->data_.Get() == buffer)
  1482. {
  1483. i->reserved_ = false;
  1484. return;
  1485. }
  1486. }
  1487. LOGWARNING("Reserved discard lock buffer " + ToStringHex((unsigned)buffer) + " not found");
  1488. }
  1489. void Graphics::Release(bool clearGPUObjects, bool closeWindow)
  1490. {
  1491. if (!impl_->window_)
  1492. return;
  1493. CleanupFramebuffers(true);
  1494. depthTextures_.Clear();
  1495. if (clearGPUObjects)
  1496. {
  1497. // Shutting down: release all GPU objects that still exist
  1498. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1499. (*i)->Release();
  1500. gpuObjects_.Clear();
  1501. }
  1502. else
  1503. {
  1504. // We are not shutting down, but recreating the context: mark GPU objects lost
  1505. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1506. (*i)->OnDeviceLost();
  1507. }
  1508. // When the new context is initialized, it will have default state again
  1509. ResetCachedState();
  1510. ClearParameterSources();
  1511. {
  1512. MutexLock lock(GetStaticMutex());
  1513. if (impl_->context_)
  1514. {
  1515. SDL_GL_DeleteContext(impl_->context_);
  1516. impl_->context_ = 0;
  1517. }
  1518. if (closeWindow)
  1519. {
  1520. SDL_ShowCursor(SDL_TRUE);
  1521. SDL_DestroyWindow(impl_->window_);
  1522. impl_->window_ = 0;
  1523. }
  1524. }
  1525. }
  1526. void Graphics::CleanupRenderSurface(RenderSurface* surface)
  1527. {
  1528. if (!surface)
  1529. return;
  1530. // Flush pending FBO changes first if any
  1531. CommitFramebuffer();
  1532. unsigned currentFbo = impl_->boundFbo_;
  1533. // Go through all FBOs and clean up the surface from them
  1534. for (Map<unsigned long long, FrameBufferObject>::Iterator i = impl_->frameBuffers_.Begin(); i != impl_->frameBuffers_.End();
  1535. ++i)
  1536. {
  1537. for (unsigned j = 0; j < MAX_RENDERTARGETS; ++j)
  1538. {
  1539. if (i->second_.colorAttachments_[j] == surface)
  1540. {
  1541. if (currentFbo != i->second_.fbo_)
  1542. {
  1543. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, i->second_.fbo_);
  1544. currentFbo = i->second_.fbo_;
  1545. }
  1546. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + j, GL_TEXTURE_2D, 0, 0);
  1547. i->second_.colorAttachments_[j] = 0;
  1548. // Mark drawbuffer bits to need recalculation
  1549. i->second_.drawBuffers_ = M_MAX_UNSIGNED;
  1550. }
  1551. }
  1552. if (i->second_.depthAttachment_ == surface)
  1553. {
  1554. if (currentFbo != i->second_.fbo_)
  1555. {
  1556. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, i->second_.fbo_);
  1557. currentFbo = i->second_.fbo_;
  1558. }
  1559. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1560. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1561. i->second_.depthAttachment_ = 0;
  1562. }
  1563. }
  1564. // Restore previously bound FBO now if needed
  1565. if (currentFbo != impl_->boundFbo_)
  1566. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, impl_->boundFbo_);
  1567. }
  1568. unsigned Graphics::GetAlphaFormat()
  1569. {
  1570. return GL_ALPHA;
  1571. }
  1572. unsigned Graphics::GetLuminanceFormat()
  1573. {
  1574. return GL_LUMINANCE;
  1575. }
  1576. unsigned Graphics::GetLuminanceAlphaFormat()
  1577. {
  1578. return GL_LUMINANCE_ALPHA;
  1579. }
  1580. unsigned Graphics::GetRGBFormat()
  1581. {
  1582. return GL_RGB;
  1583. }
  1584. unsigned Graphics::GetRGBAFormat()
  1585. {
  1586. return GL_RGBA;
  1587. }
  1588. unsigned Graphics::GetFloatFormat()
  1589. {
  1590. #ifndef GL_ES_VERSION_2_0
  1591. return GL_LUMINANCE32F_ARB;
  1592. #else
  1593. return GL_LUMINANCE;
  1594. #endif
  1595. }
  1596. unsigned Graphics::GetLinearDepthFormat()
  1597. {
  1598. // OpenGL FBO specs state that color attachments must have the same format; therefore must encode linear depth to RGBA
  1599. // manually if not using a readable hardware depth texture
  1600. return GL_RGBA;
  1601. }
  1602. unsigned Graphics::GetDepthStencilFormat()
  1603. {
  1604. #ifndef GL_ES_VERSION_2_0
  1605. return GL_DEPTH24_STENCIL8_EXT;
  1606. #else
  1607. return GL_DEPTH_COMPONENT;
  1608. #endif
  1609. }
  1610. void Graphics::CheckFeatureSupport()
  1611. {
  1612. // Check supported features: light pre-pass, deferred rendering and hardware depth texture
  1613. lightPrepassSupport_ = false;
  1614. deferredSupport_ = false;
  1615. hardwareDepthSupport_ = false;
  1616. int numSupportedRTs = 1;
  1617. #ifndef GL_ES_VERSION_2_0
  1618. glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS_EXT, &numSupportedRTs);
  1619. // For now hardware depth texture is only tested for on NVIDIA hardware because of visual artifacts and slowdown on ATI
  1620. String vendorString = String((const char*)glGetString(GL_VENDOR)).ToUpper();
  1621. if (vendorString.Find("NVIDIA") != String::NPOS)
  1622. {
  1623. SharedPtr<Texture2D> depthTexture(new Texture2D(context_));
  1624. hardwareDepthSupport_ = true;
  1625. // Note: Texture2D::SetSize() requires hardwareDepthSupport_ == true to create a texture instead of a renderbuffer
  1626. depthTexture->SetSize(256, 256, GetDepthStencilFormat(), TEXTURE_DEPTHSTENCIL);
  1627. SetDepthStencil(depthTexture);
  1628. // If hardware depth textures work, this means also light pre-pass is automatically supported
  1629. if (CheckFramebuffer())
  1630. {
  1631. lightPrepassSupport_ = true;
  1632. if (numSupportedRTs >= 3)
  1633. deferredSupport_ = true;
  1634. }
  1635. else
  1636. hardwareDepthSupport_ = false;
  1637. ResetDepthStencil();
  1638. }
  1639. if (!hardwareDepthSupport_)
  1640. {
  1641. // If hardware depth is not supported, must support 2 rendertargets for light pre-pass, and 4 for deferred
  1642. if (numSupportedRTs >= 2)
  1643. lightPrepassSupport_ = true;
  1644. if (numSupportedRTs >= 4)
  1645. deferredSupport_ = true;
  1646. }
  1647. #else
  1648. if (!CheckExtension("GL_OES_depth_texture"))
  1649. {
  1650. shadowMapFormat_ = 0;
  1651. hiresShadowMapFormat_ = 0;
  1652. }
  1653. else
  1654. {
  1655. shadowMapFormat_ = GL_DEPTH_COMPONENT;
  1656. hiresShadowMapFormat_ = GL_DEPTH_COMPONENT;
  1657. hardwareDepthSupport_ = true;
  1658. }
  1659. #endif
  1660. }
  1661. void Graphics::CommitFramebuffer()
  1662. {
  1663. if (!impl_->fboDirty_)
  1664. return;
  1665. impl_->fboDirty_ = false;
  1666. // First check if no framebuffer is needed. In that case simply return to backbuffer rendering
  1667. bool noFbo = !depthStencil_;
  1668. if (noFbo)
  1669. {
  1670. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1671. {
  1672. if (renderTargets_[i])
  1673. {
  1674. noFbo = false;
  1675. break;
  1676. }
  1677. }
  1678. }
  1679. if (noFbo)
  1680. {
  1681. if (impl_->boundFbo_)
  1682. {
  1683. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
  1684. impl_->boundFbo_ = 0;
  1685. }
  1686. return;
  1687. }
  1688. // Search for a new framebuffer based on format & size, or create new
  1689. IntVector2 rtSize = Graphics::GetRenderTargetDimensions();
  1690. unsigned format = 0;
  1691. if (renderTargets_[0])
  1692. format = renderTargets_[0]->GetParentTexture()->GetFormat();
  1693. else if (depthStencil_)
  1694. format = depthStencil_->GetParentTexture()->GetFormat();
  1695. unsigned long long fboKey = (rtSize.x_ << 16 | rtSize.y_) | (((unsigned long long)format) << 32);
  1696. Map<unsigned long long, FrameBufferObject>::Iterator i = impl_->frameBuffers_.Find(fboKey);
  1697. if (i == impl_->frameBuffers_.End())
  1698. {
  1699. FrameBufferObject newFbo;
  1700. glGenFramebuffersEXT(1, &newFbo.fbo_);
  1701. i = impl_->frameBuffers_.Insert(MakePair(fboKey, newFbo));
  1702. }
  1703. i->second_.useTimer_.Reset();
  1704. if (impl_->boundFbo_ != i->second_.fbo_)
  1705. {
  1706. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, i->second_.fbo_);
  1707. impl_->boundFbo_ = i->second_.fbo_;
  1708. }
  1709. #ifndef GL_ES_VERSION_2_0
  1710. // Setup readbuffers & drawbuffers if needed
  1711. if (i->second_.readBuffers_ != GL_NONE)
  1712. {
  1713. glReadBuffer(GL_NONE);
  1714. i->second_.readBuffers_ = GL_NONE;
  1715. }
  1716. // Calculate the bit combination of non-zero color rendertargets to first check if the combination changed
  1717. unsigned newDrawBuffers = 0;
  1718. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1719. {
  1720. if (renderTargets_[i])
  1721. newDrawBuffers |= 1 << i;
  1722. }
  1723. if (newDrawBuffers != i->second_.drawBuffers_)
  1724. {
  1725. // Check for no color rendertargets (depth rendering only)
  1726. if (!newDrawBuffers)
  1727. glDrawBuffer(GL_NONE);
  1728. else
  1729. {
  1730. int drawBufferIds[4];
  1731. unsigned drawBufferCount = 0;
  1732. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1733. {
  1734. if (renderTargets_[i])
  1735. drawBufferIds[drawBufferCount++] = GL_COLOR_ATTACHMENT0_EXT + i;
  1736. }
  1737. glDrawBuffers(drawBufferCount, (const GLenum*)drawBufferIds);
  1738. }
  1739. i->second_.drawBuffers_ = newDrawBuffers;
  1740. }
  1741. #endif
  1742. for (unsigned j = 0; j < MAX_RENDERTARGETS; ++j)
  1743. {
  1744. if (renderTargets_[j])
  1745. {
  1746. Texture* texture = renderTargets_[j]->GetParentTexture();
  1747. // If texture's parameters are dirty, update before attaching
  1748. if (texture->GetParametersDirty())
  1749. {
  1750. SetTextureForUpdate(texture);
  1751. texture->UpdateParameters();
  1752. SetTexture(0, 0);
  1753. }
  1754. if (i->second_.colorAttachments_[j] != renderTargets_[j])
  1755. {
  1756. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + j, renderTargets_[j]->GetTarget(),
  1757. texture->GetGPUObject(), 0);
  1758. i->second_.colorAttachments_[j] = renderTargets_[j];
  1759. }
  1760. }
  1761. else
  1762. {
  1763. if (i->second_.colorAttachments_[j])
  1764. {
  1765. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + j, GL_TEXTURE_2D, 0, 0);
  1766. i->second_.colorAttachments_[j] = 0;
  1767. }
  1768. }
  1769. }
  1770. if (depthStencil_)
  1771. {
  1772. // Bind either a renderbuffer or a depth texture, depending on what is available
  1773. Texture* texture = depthStencil_->GetParentTexture();
  1774. #ifndef GL_ES_VERSION_2_0
  1775. bool hasStencil = texture->GetFormat() == GetDepthStencilFormat();
  1776. #else
  1777. bool hasStencil = false;
  1778. #endif
  1779. unsigned renderBufferID = depthStencil_->GetRenderBuffer();
  1780. if (!renderBufferID)
  1781. {
  1782. // If texture's parameters are dirty, update before attaching
  1783. if (texture->GetParametersDirty())
  1784. {
  1785. SetTextureForUpdate(texture);
  1786. texture->UpdateParameters();
  1787. SetTexture(0, 0);
  1788. }
  1789. if (i->second_.depthAttachment_ != depthStencil_)
  1790. {
  1791. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, texture->GetGPUObject(), 0);
  1792. if (hasStencil)
  1793. {
  1794. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D,
  1795. texture->GetGPUObject(), 0);
  1796. }
  1797. else
  1798. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1799. i->second_.depthAttachment_ = depthStencil_;
  1800. }
  1801. }
  1802. else
  1803. {
  1804. if (i->second_.depthAttachment_ != depthStencil_)
  1805. {
  1806. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, renderBufferID);
  1807. if (hasStencil)
  1808. {
  1809. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT,
  1810. renderBufferID);
  1811. }
  1812. else
  1813. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1814. i->second_.depthAttachment_ = depthStencil_;
  1815. }
  1816. }
  1817. impl_->depthBits_ = texture->GetDepthBits();
  1818. }
  1819. else
  1820. {
  1821. if (i->second_.depthAttachment_)
  1822. {
  1823. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1824. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1825. i->second_.depthAttachment_ = 0;
  1826. impl_->depthBits_ = impl_->windowDepthBits_;
  1827. }
  1828. }
  1829. }
  1830. bool Graphics::CheckFramebuffer()
  1831. {
  1832. return glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT) == GL_FRAMEBUFFER_COMPLETE_EXT;
  1833. }
  1834. void Graphics::CleanupFramebuffers(bool deleteAll)
  1835. {
  1836. if (deleteAll && impl_->boundFbo_)
  1837. {
  1838. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
  1839. impl_->boundFbo_ = 0;
  1840. }
  1841. for (Map<unsigned long long, FrameBufferObject>::Iterator i = impl_->frameBuffers_.Begin(); i != impl_->frameBuffers_.End();)
  1842. {
  1843. Map<unsigned long long, FrameBufferObject>::Iterator current = i++;
  1844. if (deleteAll || (current->second_.fbo_ != impl_->boundFbo_ && current->second_.useTimer_.GetMSec(false) > MAX_FRAMEBUFFER_AGE))
  1845. {
  1846. glDeleteFramebuffersEXT(1, &current->second_.fbo_);
  1847. impl_->frameBuffers_.Erase(current);
  1848. }
  1849. }
  1850. }
  1851. void Graphics::ResetCachedState()
  1852. {
  1853. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  1854. {
  1855. vertexBuffers_[i] = 0;
  1856. elementMasks_[i] = 0;
  1857. }
  1858. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1859. {
  1860. textures_[i] = 0;
  1861. textureTypes_[i] = 0;
  1862. }
  1863. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1864. renderTargets_[i] = 0;
  1865. depthStencil_ = 0;
  1866. viewTexture_ = 0;
  1867. viewport_ = IntRect(0, 0, 0, 0);
  1868. indexBuffer_ = 0;
  1869. vertexShader_ = 0;
  1870. pixelShader_ = 0;
  1871. shaderProgram_ = 0;
  1872. blendMode_ = BLEND_REPLACE;
  1873. textureAnisotropy_ = 1;
  1874. colorWrite_ = true;
  1875. cullMode_ = CULL_NONE;
  1876. constantDepthBias_ = 0.0f;
  1877. slopeScaledDepthBias_ = 0.0f;
  1878. depthTestMode_ = CMP_ALWAYS;
  1879. depthWrite_ = true;
  1880. scissorTest_ = false;
  1881. scissorRect_ = IntRect::ZERO;
  1882. stencilTest_ = false;
  1883. stencilTestMode_ = CMP_ALWAYS;
  1884. stencilPass_ = OP_KEEP;
  1885. stencilFail_ = OP_KEEP;
  1886. stencilZFail_ = OP_KEEP;
  1887. stencilRef_ = 0;
  1888. stencilCompareMask_ = M_MAX_UNSIGNED;
  1889. stencilWriteMask_ = M_MAX_UNSIGNED;
  1890. impl_->activeTexture_ = 0;
  1891. impl_->enabledAttributes_ = 0;
  1892. }
  1893. void Graphics::SetTextureUnitMappings()
  1894. {
  1895. textureUnits_["DiffMap"] = TU_DIFFUSE;
  1896. textureUnits_["DiffCubeMap"] = TU_DIFFUSE;
  1897. textureUnits_["NormalMap"] = TU_NORMAL;
  1898. textureUnits_["EmissiveMap"] = TU_EMISSIVE;
  1899. textureUnits_["EnvironmentMap"] = TU_ENVIRONMENT;
  1900. textureUnits_["EnvironmentCubeMap"] = TU_ENVIRONMENT;
  1901. textureUnits_["LightRampMap"] = TU_LIGHTRAMP;
  1902. textureUnits_["LightSpotMap"] = TU_LIGHTSHAPE;
  1903. textureUnits_["LightCubeMap"] = TU_LIGHTSHAPE;
  1904. textureUnits_["ShadowMap"] = TU_SHADOWMAP;
  1905. textureUnits_["FaceSelectCubeMap"] = TU_FACESELECT;
  1906. textureUnits_["IndirectionCubeMap"] = TU_INDIRECTION;
  1907. textureUnits_["AlbedoBuffer"] = TU_ALBEDOBUFFER;
  1908. textureUnits_["NormalBuffer"] = TU_NORMALBUFFER;
  1909. textureUnits_["DepthBuffer"] = TU_DEPTHBUFFER;
  1910. textureUnits_["LightBuffer"] = TU_LIGHTBUFFER;
  1911. }
  1912. void RegisterGraphicsLibrary(Context* context)
  1913. {
  1914. Animation::RegisterObject(context);
  1915. Material::RegisterObject(context);
  1916. Model::RegisterObject(context);
  1917. Shader::RegisterObject(context);
  1918. Technique::RegisterObject(context);
  1919. Texture2D::RegisterObject(context);
  1920. TextureCube::RegisterObject(context);
  1921. Camera::RegisterObject(context);
  1922. Drawable::RegisterObject(context);
  1923. Light::RegisterObject(context);
  1924. StaticModel::RegisterObject(context);
  1925. Skybox::RegisterObject(context);
  1926. AnimatedModel::RegisterObject(context);
  1927. AnimationController::RegisterObject(context);
  1928. BillboardSet::RegisterObject(context);
  1929. ParticleEmitter::RegisterObject(context);
  1930. DebugRenderer::RegisterObject(context);
  1931. Octree::RegisterObject(context);
  1932. Zone::RegisterObject(context);
  1933. }