OGLGraphics.cpp 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233
  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. glUniformMatrix3fv(info->location_, count / 9, GL_TRUE, data);
  762. break;
  763. case GL_FLOAT_MAT4:
  764. glUniformMatrix4fv(info->location_, count / 16, GL_TRUE, data);
  765. break;
  766. }
  767. }
  768. }
  769. }
  770. void Graphics::SetShaderParameter(StringHash param, float value)
  771. {
  772. if (shaderProgram_)
  773. {
  774. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  775. if (info)
  776. glUniform1fv(info->location_, 1, &value);
  777. }
  778. }
  779. void Graphics::SetShaderParameter(StringHash param, const Color& color)
  780. {
  781. SetShaderParameter(param, color.Data(), 4);
  782. }
  783. void Graphics::SetShaderParameter(StringHash param, const Matrix3& matrix)
  784. {
  785. if (shaderProgram_)
  786. {
  787. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  788. if (info)
  789. glUniformMatrix3fv(info->location_, 1, GL_TRUE, matrix.Data());
  790. }
  791. }
  792. void Graphics::SetShaderParameter(StringHash param, const Vector3& vector)
  793. {
  794. if (shaderProgram_)
  795. {
  796. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  797. if (info)
  798. {
  799. // Check the uniform type to avoid mismatch
  800. switch (info->type_)
  801. {
  802. case GL_FLOAT:
  803. glUniform1fv(info->location_, 1, vector.Data());
  804. break;
  805. case GL_FLOAT_VEC2:
  806. glUniform2fv(info->location_, 1, vector.Data());
  807. break;
  808. case GL_FLOAT_VEC3:
  809. glUniform3fv(info->location_, 1, vector.Data());
  810. break;
  811. }
  812. }
  813. }
  814. }
  815. void Graphics::SetShaderParameter(StringHash param, const Matrix4& matrix)
  816. {
  817. if (shaderProgram_)
  818. {
  819. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  820. if (info)
  821. glUniformMatrix4fv(info->location_, 1, GL_TRUE, matrix.Data());
  822. }
  823. }
  824. void Graphics::SetShaderParameter(StringHash param, const Vector4& vector)
  825. {
  826. if (shaderProgram_)
  827. {
  828. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  829. if (info)
  830. {
  831. // Check the uniform type to avoid mismatch
  832. switch (info->type_)
  833. {
  834. case GL_FLOAT:
  835. glUniform1fv(info->location_, 1, vector.Data());
  836. break;
  837. case GL_FLOAT_VEC2:
  838. glUniform2fv(info->location_, 1, vector.Data());
  839. break;
  840. case GL_FLOAT_VEC3:
  841. glUniform3fv(info->location_, 1, vector.Data());
  842. break;
  843. case GL_FLOAT_VEC4:
  844. glUniform4fv(info->location_, 1, vector.Data());
  845. break;
  846. }
  847. }
  848. }
  849. }
  850. void Graphics::SetShaderParameter(StringHash param, const Matrix3x4& matrix)
  851. {
  852. if (shaderProgram_)
  853. {
  854. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  855. if (info)
  856. {
  857. float data[16];
  858. data[0] = matrix.m00_;
  859. data[1] = matrix.m01_;
  860. data[2] = matrix.m02_;
  861. data[3] = matrix.m03_;
  862. data[4] = matrix.m10_;
  863. data[5] = matrix.m11_;
  864. data[6] = matrix.m12_;
  865. data[7] = matrix.m13_;
  866. data[8] = matrix.m20_;
  867. data[9] = matrix.m21_;
  868. data[10] = matrix.m22_;
  869. data[11] = matrix.m23_;
  870. data[12] = 0.0f;
  871. data[13] = 0.0f;
  872. data[14] = 0.0f;
  873. data[15] = 1.0f;
  874. glUniformMatrix4fv(info->location_, 1, GL_TRUE, data);
  875. }
  876. }
  877. }
  878. bool Graphics::NeedParameterUpdate(ShaderParameterGroup group, const void* source)
  879. {
  880. if ((unsigned)shaderParameterSources_[group] == M_MAX_UNSIGNED || shaderParameterSources_[group] != source)
  881. {
  882. shaderParameterSources_[group] = source;
  883. return true;
  884. }
  885. else
  886. return false;
  887. }
  888. bool Graphics::HasShaderParameter(ShaderType type, StringHash param)
  889. {
  890. return shaderProgram_ && shaderProgram_->HasParameter(param);
  891. }
  892. bool Graphics::HasTextureUnit(TextureUnit unit)
  893. {
  894. return shaderProgram_ && shaderProgram_->HasTextureUnit(unit);
  895. }
  896. void Graphics::ClearParameterSource(ShaderParameterGroup group)
  897. {
  898. shaderParameterSources_[group] = (const void*)M_MAX_UNSIGNED;
  899. }
  900. void Graphics::ClearParameterSources()
  901. {
  902. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  903. shaderParameterSources_[i] = (const void*)M_MAX_UNSIGNED;
  904. }
  905. void Graphics::ClearTransformSources()
  906. {
  907. shaderParameterSources_[SP_CAMERA] = (const void*)M_MAX_UNSIGNED;
  908. shaderParameterSources_[SP_OBJECTTRANSFORM] = (const void*)M_MAX_UNSIGNED;
  909. }
  910. void Graphics::CleanupShaderPrograms()
  911. {
  912. for (ShaderProgramMap::Iterator i = shaderPrograms_.Begin(); i != shaderPrograms_.End();)
  913. {
  914. ShaderProgramMap::Iterator current = i++;
  915. ShaderVariation* vs = current->second_->GetVertexShader();
  916. ShaderVariation* ps = current->second_->GetPixelShader();
  917. if (!vs || !ps || !vs->GetGPUObject() || !ps->GetGPUObject())
  918. shaderPrograms_.Erase(current);
  919. }
  920. }
  921. void Graphics::SetTexture(unsigned index, Texture* texture)
  922. {
  923. if (index >= MAX_TEXTURE_UNITS)
  924. return;
  925. // Check if texture is currently bound as a rendertarget. In that case, use its backup texture, or blank if not defined
  926. if (texture)
  927. {
  928. if (texture == viewTexture_ || (renderTargets_[0] && renderTargets_[0]->GetParentTexture() == texture))
  929. texture = texture->GetBackupTexture();
  930. }
  931. if (textures_[index] != texture)
  932. {
  933. if (impl_->activeTexture_ != index)
  934. {
  935. glActiveTexture(GL_TEXTURE0 + index);
  936. impl_->activeTexture_ = index;
  937. }
  938. if (texture)
  939. {
  940. unsigned glType = texture->GetTarget();
  941. if (glType != textureTypes_[index])
  942. {
  943. if (textureTypes_[index])
  944. glDisable(textureTypes_[index]);
  945. glEnable(glType);
  946. textureTypes_[index] = glType;
  947. }
  948. glBindTexture(glType, texture->GetGPUObject());
  949. if (texture->GetParametersDirty())
  950. texture->UpdateParameters();
  951. }
  952. else
  953. {
  954. if (textureTypes_[index])
  955. glBindTexture(textureTypes_[index], 0);
  956. }
  957. textures_[index] = texture;
  958. }
  959. else
  960. {
  961. if (texture && texture->GetParametersDirty())
  962. {
  963. if (impl_->activeTexture_ != index)
  964. {
  965. glActiveTexture(GL_TEXTURE0 + index);
  966. impl_->activeTexture_ = index;
  967. }
  968. glBindTexture(texture->GetTarget(), texture->GetGPUObject());
  969. texture->UpdateParameters();
  970. }
  971. }
  972. }
  973. void Graphics::SetTextureForUpdate(Texture* texture)
  974. {
  975. if (impl_->activeTexture_ != 0)
  976. {
  977. glActiveTexture(GL_TEXTURE0);
  978. impl_->activeTexture_ = 0;
  979. }
  980. glBindTexture(texture->GetTarget(), texture->GetGPUObject());
  981. textures_[0] = texture;
  982. }
  983. void Graphics::SetDefaultTextureFilterMode(TextureFilterMode mode)
  984. {
  985. if (mode != defaultTextureFilterMode_)
  986. {
  987. defaultTextureFilterMode_ = mode;
  988. SetTextureParametersDirty();
  989. }
  990. }
  991. void Graphics::SetTextureAnisotropy(unsigned level)
  992. {
  993. if (level != textureAnisotropy_)
  994. {
  995. textureAnisotropy_ = level;
  996. SetTextureParametersDirty();
  997. }
  998. }
  999. void Graphics::SetTextureParametersDirty()
  1000. {
  1001. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1002. {
  1003. Texture* texture = dynamic_cast<Texture*>(*i);
  1004. if (texture)
  1005. texture->SetParametersDirty();
  1006. }
  1007. }
  1008. void Graphics::ResetRenderTargets()
  1009. {
  1010. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1011. SetRenderTarget(i, (RenderSurface*)0);
  1012. SetDepthStencil((RenderSurface*)0);
  1013. SetViewport(IntRect(0, 0, width_, height_));
  1014. }
  1015. void Graphics::ResetRenderTarget(unsigned index)
  1016. {
  1017. SetRenderTarget(index, (RenderSurface*)0);
  1018. }
  1019. void Graphics::ResetDepthStencil()
  1020. {
  1021. SetDepthStencil((RenderSurface*)0);
  1022. }
  1023. void Graphics::SetRenderTarget(unsigned index, RenderSurface* renderTarget)
  1024. {
  1025. if (index >= MAX_RENDERTARGETS)
  1026. return;
  1027. if (renderTarget != renderTargets_[index])
  1028. {
  1029. renderTargets_[index] = renderTarget;
  1030. // If the rendertarget is also bound as a texture, replace with backup texture or null
  1031. if (renderTarget)
  1032. {
  1033. Texture* parentTexture = renderTarget->GetParentTexture();
  1034. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1035. {
  1036. if (textures_[i] == parentTexture)
  1037. SetTexture(i, textures_[i]->GetBackupTexture());
  1038. }
  1039. }
  1040. impl_->fboDirty_ = true;
  1041. }
  1042. }
  1043. void Graphics::SetRenderTarget(unsigned index, Texture2D* texture)
  1044. {
  1045. RenderSurface* renderTarget = 0;
  1046. if (texture)
  1047. renderTarget = texture->GetRenderSurface();
  1048. SetRenderTarget(index, renderTarget);
  1049. }
  1050. void Graphics::SetDepthStencil(RenderSurface* depthStencil)
  1051. {
  1052. // If we are using a rendertarget texture, it is required in OpenGL to also have an own depth-stencil
  1053. // Create a new depth-stencil texture as necessary to be able to provide similar behaviour as Direct3D9
  1054. if (renderTargets_[0] && !depthStencil)
  1055. {
  1056. int width = renderTargets_[0]->GetWidth();
  1057. int height = renderTargets_[0]->GetHeight();
  1058. // Direct3D9 default depth-stencil can not be used when rendertarget is larger than the window.
  1059. // Check size similarly
  1060. if (width <= width_ && height <= height_)
  1061. {
  1062. int searchKey = (width << 16) | height;
  1063. HashMap<int, SharedPtr<Texture2D> >::Iterator i = depthTextures_.Find(searchKey);
  1064. if (i != depthTextures_.End())
  1065. depthStencil = i->second_->GetRenderSurface();
  1066. else
  1067. {
  1068. SharedPtr<Texture2D> newDepthTexture(new Texture2D(context_));
  1069. newDepthTexture->SetSize(width, height, GetDepthStencilFormat(), TEXTURE_DEPTHSTENCIL);
  1070. depthTextures_[searchKey] = newDepthTexture;
  1071. depthStencil = newDepthTexture->GetRenderSurface();
  1072. }
  1073. }
  1074. }
  1075. if (depthStencil != depthStencil_)
  1076. {
  1077. depthStencil_ = depthStencil;
  1078. impl_->fboDirty_ = true;
  1079. }
  1080. }
  1081. void Graphics::SetDepthStencil(Texture2D* texture)
  1082. {
  1083. RenderSurface* depthStencil = 0;
  1084. if (texture)
  1085. depthStencil = texture->GetRenderSurface();
  1086. SetDepthStencil(depthStencil);
  1087. }
  1088. void Graphics::SetViewTexture(Texture* texture)
  1089. {
  1090. viewTexture_ = texture;
  1091. if (viewTexture_)
  1092. {
  1093. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1094. {
  1095. if (textures_[i] == viewTexture_)
  1096. SetTexture(i, textures_[i]->GetBackupTexture());
  1097. }
  1098. }
  1099. }
  1100. void Graphics::SetViewport(const IntRect& rect)
  1101. {
  1102. if (impl_->fboDirty_)
  1103. CommitFramebuffer();
  1104. IntVector2 rtSize = GetRenderTargetDimensions();
  1105. IntRect rectCopy = rect;
  1106. if (rectCopy.right_ <= rectCopy.left_)
  1107. rectCopy.right_ = rectCopy.left_ + 1;
  1108. if (rectCopy.bottom_ <= rectCopy.top_)
  1109. rectCopy.bottom_ = rectCopy.top_ + 1;
  1110. rectCopy.left_ = Clamp(rectCopy.left_, 0, rtSize.x_);
  1111. rectCopy.top_ = Clamp(rectCopy.top_, 0, rtSize.y_);
  1112. rectCopy.right_ = Clamp(rectCopy.right_, 0, rtSize.x_);
  1113. rectCopy.bottom_ = Clamp(rectCopy.bottom_, 0, rtSize.y_);
  1114. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1115. glViewport(rectCopy.left_, rtSize.y_ - rectCopy.bottom_, rectCopy.right_ - rectCopy.left_, rectCopy.bottom_ - rectCopy.top_);
  1116. viewport_ = rectCopy;
  1117. // Disable scissor test, needs to be re-enabled by the user
  1118. SetScissorTest(false);
  1119. }
  1120. void Graphics::SetBlendMode(BlendMode mode)
  1121. {
  1122. if (mode != blendMode_)
  1123. {
  1124. if (mode == BLEND_REPLACE)
  1125. glDisable(GL_BLEND);
  1126. else
  1127. {
  1128. glEnable(GL_BLEND);
  1129. glBlendFunc(glSrcBlend[mode], glDestBlend[mode]);
  1130. }
  1131. blendMode_ = mode;
  1132. }
  1133. }
  1134. void Graphics::SetColorWrite(bool enable)
  1135. {
  1136. if (enable != colorWrite_)
  1137. {
  1138. if (enable)
  1139. glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  1140. else
  1141. glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  1142. colorWrite_ = enable;
  1143. }
  1144. }
  1145. void Graphics::SetCullMode(CullMode mode)
  1146. {
  1147. if (mode != cullMode_)
  1148. {
  1149. if (mode == CULL_NONE)
  1150. glDisable(GL_CULL_FACE);
  1151. else
  1152. {
  1153. // Use Direct3D convention, ie. clockwise vertices define a front face
  1154. glEnable(GL_CULL_FACE);
  1155. glCullFace(mode == CULL_CCW ? GL_FRONT : GL_BACK);
  1156. }
  1157. cullMode_ = mode;
  1158. }
  1159. }
  1160. void Graphics::SetDepthBias(float constantBias, float slopeScaledBias)
  1161. {
  1162. if (constantBias != constantDepthBias_ || slopeScaledBias != slopeScaledDepthBias_)
  1163. {
  1164. if (constantBias != 0.0f || slopeScaledBias != 0.0f)
  1165. {
  1166. // Bring the constant bias from Direct3D9 scale to OpenGL (depends on depth buffer bitdepth)
  1167. // Zero depth bits may be returned if using the packed depth-stencil format. Assume 24bit in that case
  1168. int depthBits = Min(impl_->depthBits_, 23);
  1169. if (!depthBits)
  1170. depthBits = 23;
  1171. float adjustedConstantBias = constantBias * (float)(1 << (depthBits - 1));
  1172. float adjustedSlopeScaledBias = slopeScaledBias + 1.0f;
  1173. glEnable(GL_POLYGON_OFFSET_FILL);
  1174. #ifndef GL_ES_VERSION_2_0
  1175. glEnable(GL_POLYGON_OFFSET_LINE);
  1176. #endif
  1177. glPolygonOffset(adjustedSlopeScaledBias, adjustedConstantBias);
  1178. }
  1179. else
  1180. {
  1181. glDisable(GL_POLYGON_OFFSET_FILL);
  1182. #ifndef GL_ES_VERSION_2_0
  1183. glDisable(GL_POLYGON_OFFSET_LINE);
  1184. #endif
  1185. }
  1186. constantDepthBias_ = constantBias;
  1187. slopeScaledDepthBias_ = slopeScaledBias;
  1188. }
  1189. }
  1190. void Graphics::SetDepthTest(CompareMode mode)
  1191. {
  1192. if (mode != depthTestMode_)
  1193. {
  1194. glDepthFunc(glCmpFunc[mode]);
  1195. depthTestMode_ = mode;
  1196. }
  1197. }
  1198. void Graphics::SetDepthWrite(bool enable)
  1199. {
  1200. if (enable != depthWrite_)
  1201. {
  1202. glDepthMask(enable ? GL_TRUE : GL_FALSE);
  1203. depthWrite_ = enable;
  1204. }
  1205. }
  1206. void Graphics::SetFillMode(FillMode mode)
  1207. {
  1208. if (mode != fillMode_)
  1209. {
  1210. #ifndef GL_ES_VERSION_2_0
  1211. glPolygonMode(GL_FRONT_AND_BACK, mode == FILL_SOLID ? GL_FILL : GL_LINE);
  1212. #endif
  1213. fillMode_ = mode;
  1214. }
  1215. }
  1216. void Graphics::SetScissorTest(bool enable, const Rect& rect, bool borderInclusive)
  1217. {
  1218. // During some light rendering loops, a full rect is toggled on/off repeatedly.
  1219. // Disable scissor in that case to reduce state changes
  1220. if (rect.min_.x_ <= 0.0f && rect.min_.y_ <= 0.0f && rect.max_.x_ >= 1.0f && rect.max_.y_ >= 1.0f)
  1221. enable = false;
  1222. if (enable)
  1223. {
  1224. IntVector2 rtSize(GetRenderTargetDimensions());
  1225. IntVector2 viewSize(viewport_.right_ - viewport_.left_, viewport_.bottom_ - viewport_.top_);
  1226. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1227. IntRect intRect;
  1228. int expand = borderInclusive ? 1 : 0;
  1229. intRect.left_ = Clamp((int)((rect.min_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_, 0, rtSize.x_ - 1);
  1230. intRect.top_ = Clamp((int)((-rect.max_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_, 0, rtSize.y_ - 1);
  1231. intRect.right_ = Clamp((int)((rect.max_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_ + expand, 0, rtSize.x_);
  1232. intRect.bottom_ = Clamp((int)((-rect.min_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_ + expand, 0, rtSize.y_);
  1233. if (intRect.right_ == intRect.left_)
  1234. intRect.right_++;
  1235. if (intRect.bottom_ == intRect.top_)
  1236. intRect.bottom_++;
  1237. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1238. enable = false;
  1239. if (enable && scissorRect_ != intRect)
  1240. {
  1241. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1242. glScissor(intRect.left_, rtSize.y_ - intRect.bottom_, intRect.right_ - intRect.left_, intRect.bottom_ - intRect.top_);
  1243. scissorRect_ = intRect;
  1244. }
  1245. }
  1246. else
  1247. scissorRect_ = IntRect::ZERO;
  1248. if (enable != scissorTest_)
  1249. {
  1250. if (enable)
  1251. glEnable(GL_SCISSOR_TEST);
  1252. else
  1253. glDisable(GL_SCISSOR_TEST);
  1254. scissorTest_ = enable;
  1255. }
  1256. }
  1257. void Graphics::SetScissorTest(bool enable, const IntRect& rect)
  1258. {
  1259. IntVector2 rtSize(GetRenderTargetDimensions());
  1260. IntVector2 viewSize(viewport_.right_ - viewport_.left_, viewport_.bottom_ - viewport_.top_);
  1261. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1262. if (enable)
  1263. {
  1264. IntRect intRect;
  1265. intRect.left_ = Clamp(rect.left_ + viewPos.x_, 0, rtSize.x_ - 1);
  1266. intRect.top_ = Clamp(rect.top_ + viewPos.y_, 0, rtSize.y_ - 1);
  1267. intRect.right_ = Clamp(rect.right_ + viewPos.x_, 0, rtSize.x_);
  1268. intRect.bottom_ = Clamp(rect.bottom_ + viewPos.y_, 0, rtSize.y_);
  1269. if (intRect.right_ == intRect.left_)
  1270. intRect.right_++;
  1271. if (intRect.bottom_ == intRect.top_)
  1272. intRect.bottom_++;
  1273. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1274. enable = false;
  1275. if (enable && scissorRect_ != intRect)
  1276. {
  1277. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1278. glScissor(intRect.left_, rtSize.y_ - intRect.bottom_, intRect.right_ - intRect.left_, intRect.bottom_ - intRect.top_);
  1279. scissorRect_ = intRect;
  1280. }
  1281. }
  1282. else
  1283. scissorRect_ = IntRect::ZERO;
  1284. if (enable != scissorTest_)
  1285. {
  1286. if (enable)
  1287. glEnable(GL_SCISSOR_TEST);
  1288. else
  1289. glDisable(GL_SCISSOR_TEST);
  1290. scissorTest_ = enable;
  1291. }
  1292. }
  1293. void Graphics::SetStreamFrequency(unsigned index, unsigned frequency)
  1294. {
  1295. }
  1296. void Graphics::ResetStreamFrequencies()
  1297. {
  1298. }
  1299. void Graphics::SetStencilTest(bool enable, CompareMode mode, StencilOp pass, StencilOp fail, StencilOp zFail, unsigned stencilRef, unsigned compareMask, unsigned writeMask)
  1300. {
  1301. if (enable != stencilTest_)
  1302. {
  1303. if (enable)
  1304. glEnable(GL_STENCIL_TEST);
  1305. else
  1306. glDisable(GL_STENCIL_TEST);
  1307. stencilTest_ = enable;
  1308. }
  1309. if (enable)
  1310. {
  1311. if (mode != stencilTestMode_ || stencilRef != stencilRef_ || compareMask != stencilCompareMask_)
  1312. {
  1313. glStencilFunc(glCmpFunc[mode], stencilRef, compareMask);
  1314. stencilTestMode_ = mode;
  1315. stencilRef_ = stencilRef;
  1316. stencilCompareMask_ = compareMask;
  1317. }
  1318. if (writeMask != stencilWriteMask_)
  1319. {
  1320. glStencilMask(writeMask);
  1321. stencilWriteMask_ = writeMask;
  1322. }
  1323. if (pass != stencilPass_ || fail != stencilFail_ || zFail != stencilZFail_)
  1324. {
  1325. glStencilOp(glStencilOps[fail], glStencilOps[zFail], glStencilOps[pass]);
  1326. stencilPass_ = pass;
  1327. stencilFail_ = fail;
  1328. stencilZFail_ = zFail;
  1329. }
  1330. }
  1331. }
  1332. void Graphics::SetForceSM2(bool enable)
  1333. {
  1334. }
  1335. bool Graphics::IsInitialized() const
  1336. {
  1337. return impl_->window_ != 0;
  1338. }
  1339. void* Graphics::GetWindowHandle() const
  1340. {
  1341. return impl_->window_;
  1342. }
  1343. PODVector<IntVector2> Graphics::GetResolutions() const
  1344. {
  1345. PODVector<IntVector2> ret;
  1346. unsigned numModes = SDL_GetNumDisplayModes(0);
  1347. for (unsigned i = 0; i < numModes; ++i)
  1348. {
  1349. SDL_DisplayMode mode;
  1350. SDL_GetDisplayMode(0, i, &mode);
  1351. int width = mode.w;
  1352. int height = mode.h;
  1353. // Store mode if unique
  1354. bool unique = true;
  1355. for (unsigned j = 0; j < ret.Size(); ++i)
  1356. {
  1357. if (ret[j].x_ == width && ret[j].y_ == height)
  1358. {
  1359. unique = false;
  1360. break;
  1361. }
  1362. }
  1363. if (unique)
  1364. ret.Push(IntVector2(width, height));
  1365. }
  1366. return ret;
  1367. }
  1368. PODVector<int> Graphics::GetMultiSampleLevels() const
  1369. {
  1370. PODVector<int> ret;
  1371. // No multisampling always supported
  1372. ret.Push(1);
  1373. /// \todo Implement properly, if possible
  1374. return ret;
  1375. }
  1376. VertexBuffer* Graphics::GetVertexBuffer(unsigned index) const
  1377. {
  1378. return index < MAX_VERTEX_STREAMS ? vertexBuffers_[index] : 0;
  1379. }
  1380. TextureUnit Graphics::GetTextureUnit(const String& name)
  1381. {
  1382. Map<String, TextureUnit>::Iterator i = textureUnits_.Find(name);
  1383. if (i != textureUnits_.End())
  1384. return i->second_;
  1385. else
  1386. return MAX_TEXTURE_UNITS;
  1387. }
  1388. const String& Graphics::GetTextureUnitName(TextureUnit unit)
  1389. {
  1390. for (Map<String, TextureUnit>::Iterator i = textureUnits_.Begin(); i != textureUnits_.End(); ++i)
  1391. {
  1392. if (i->second_ == unit)
  1393. return i->first_;
  1394. }
  1395. return noParameter;
  1396. }
  1397. Texture* Graphics::GetTexture(unsigned index) const
  1398. {
  1399. return index < MAX_TEXTURE_UNITS ? textures_[index] : 0;
  1400. }
  1401. RenderSurface* Graphics::GetRenderTarget(unsigned index) const
  1402. {
  1403. return index < MAX_RENDERTARGETS ? renderTargets_[index] : 0;
  1404. }
  1405. IntVector2 Graphics::GetRenderTargetDimensions() const
  1406. {
  1407. int width, height;
  1408. if (renderTargets_[0])
  1409. {
  1410. width = renderTargets_[0]->GetWidth();
  1411. height = renderTargets_[0]->GetHeight();
  1412. }
  1413. else if (depthStencil_)
  1414. {
  1415. width = depthStencil_->GetWidth();
  1416. height = depthStencil_->GetHeight();
  1417. }
  1418. else
  1419. {
  1420. width = width_;
  1421. height = height_;
  1422. }
  1423. return IntVector2(width, height);
  1424. }
  1425. void Graphics::AddGPUObject(GPUObject* object)
  1426. {
  1427. gpuObjects_.Push(object);
  1428. }
  1429. void Graphics::RemoveGPUObject(GPUObject* object)
  1430. {
  1431. gpuObjects_.Erase(gpuObjects_.Find(object));
  1432. }
  1433. void* Graphics::ReserveDiscardLockBuffer(unsigned size)
  1434. {
  1435. // First check for a free buffer that is large enough
  1436. for (Vector<DiscardLockBuffer>::Iterator i = discardLockBuffers_.Begin(); i != discardLockBuffers_.End(); ++i)
  1437. {
  1438. if (!i->reserved_ && i->size_ >= size)
  1439. {
  1440. i->reserved_ = true;
  1441. return i->data_.Get();
  1442. }
  1443. }
  1444. // Then check if a free buffer can be resized
  1445. for (Vector<DiscardLockBuffer>::Iterator i = discardLockBuffers_.Begin(); i != discardLockBuffers_.End(); ++i)
  1446. {
  1447. if (!i->reserved_)
  1448. {
  1449. i->data_ = new unsigned char[size];
  1450. i->size_ = size;
  1451. i->reserved_ = true;
  1452. return i->data_.Get();
  1453. }
  1454. }
  1455. // Finally allocate a new buffer
  1456. DiscardLockBuffer newBuffer;
  1457. newBuffer.data_ = new unsigned char[size];
  1458. newBuffer.size_ = size;
  1459. newBuffer.reserved_ = true;
  1460. discardLockBuffers_.Push(newBuffer);
  1461. return newBuffer.data_.Get();
  1462. }
  1463. void Graphics::FreeDiscardLockBuffer(void* buffer)
  1464. {
  1465. for (Vector<DiscardLockBuffer>::Iterator i = discardLockBuffers_.Begin(); i != discardLockBuffers_.End(); ++i)
  1466. {
  1467. if (i->reserved_ && i->data_.Get() == buffer)
  1468. {
  1469. i->reserved_ = false;
  1470. return;
  1471. }
  1472. }
  1473. LOGWARNING("Reserved discard lock buffer " + ToStringHex((unsigned)buffer) + " not found");
  1474. }
  1475. void Graphics::Release(bool clearGPUObjects, bool closeWindow)
  1476. {
  1477. if (!impl_->window_)
  1478. return;
  1479. CleanupFramebuffers(true);
  1480. depthTextures_.Clear();
  1481. if (clearGPUObjects)
  1482. {
  1483. // Shutting down: release all GPU objects that still exist
  1484. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1485. (*i)->Release();
  1486. gpuObjects_.Clear();
  1487. }
  1488. else
  1489. {
  1490. // We are not shutting down, but recreating the context: mark GPU objects lost
  1491. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1492. (*i)->OnDeviceLost();
  1493. }
  1494. // When the new context is initialized, it will have default state again
  1495. ResetCachedState();
  1496. ClearParameterSources();
  1497. {
  1498. MutexLock lock(GetStaticMutex());
  1499. if (impl_->context_)
  1500. {
  1501. SDL_GL_DeleteContext(impl_->context_);
  1502. impl_->context_ = 0;
  1503. }
  1504. if (closeWindow)
  1505. {
  1506. SDL_ShowCursor(SDL_TRUE);
  1507. SDL_DestroyWindow(impl_->window_);
  1508. impl_->window_ = 0;
  1509. }
  1510. }
  1511. }
  1512. void Graphics::CleanupRenderSurface(RenderSurface* surface)
  1513. {
  1514. if (!surface)
  1515. return;
  1516. // Flush pending FBO changes first if any
  1517. CommitFramebuffer();
  1518. unsigned currentFbo = impl_->boundFbo_;
  1519. // Go through all FBOs and clean up the surface from them
  1520. for (Map<unsigned long long, FrameBufferObject>::Iterator i = impl_->frameBuffers_.Begin(); i != impl_->frameBuffers_.End();
  1521. ++i)
  1522. {
  1523. for (unsigned j = 0; j < MAX_RENDERTARGETS; ++j)
  1524. {
  1525. if (i->second_.colorAttachments_[j] == surface)
  1526. {
  1527. if (currentFbo != i->second_.fbo_)
  1528. {
  1529. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, i->second_.fbo_);
  1530. currentFbo = i->second_.fbo_;
  1531. }
  1532. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + j, GL_TEXTURE_2D, 0, 0);
  1533. i->second_.colorAttachments_[j] = 0;
  1534. // Mark drawbuffer bits to need recalculation
  1535. i->second_.drawBuffers_ = M_MAX_UNSIGNED;
  1536. }
  1537. }
  1538. if (i->second_.depthAttachment_ == surface)
  1539. {
  1540. if (currentFbo != i->second_.fbo_)
  1541. {
  1542. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, i->second_.fbo_);
  1543. currentFbo = i->second_.fbo_;
  1544. }
  1545. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1546. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1547. i->second_.depthAttachment_ = 0;
  1548. }
  1549. }
  1550. // Restore previously bound FBO now if needed
  1551. if (currentFbo != impl_->boundFbo_)
  1552. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, impl_->boundFbo_);
  1553. }
  1554. unsigned Graphics::GetAlphaFormat()
  1555. {
  1556. return GL_ALPHA;
  1557. }
  1558. unsigned Graphics::GetLuminanceFormat()
  1559. {
  1560. return GL_LUMINANCE;
  1561. }
  1562. unsigned Graphics::GetLuminanceAlphaFormat()
  1563. {
  1564. return GL_LUMINANCE_ALPHA;
  1565. }
  1566. unsigned Graphics::GetRGBFormat()
  1567. {
  1568. return GL_RGB;
  1569. }
  1570. unsigned Graphics::GetRGBAFormat()
  1571. {
  1572. return GL_RGBA;
  1573. }
  1574. unsigned Graphics::GetFloatFormat()
  1575. {
  1576. #ifndef GL_ES_VERSION_2_0
  1577. return GL_LUMINANCE32F_ARB;
  1578. #else
  1579. return GL_LUMINANCE;
  1580. #endif
  1581. }
  1582. unsigned Graphics::GetLinearDepthFormat()
  1583. {
  1584. // OpenGL FBO specs state that color attachments must have the same format; therefore must encode linear depth to RGBA
  1585. // manually if not using a readable hardware depth texture
  1586. return GL_RGBA;
  1587. }
  1588. unsigned Graphics::GetDepthStencilFormat()
  1589. {
  1590. #ifndef GL_ES_VERSION_2_0
  1591. return GL_DEPTH24_STENCIL8_EXT;
  1592. #else
  1593. return 0;
  1594. #endif
  1595. }
  1596. void Graphics::CheckFeatureSupport()
  1597. {
  1598. // Check supported features: light pre-pass, deferred rendering and hardware depth texture
  1599. lightPrepassSupport_ = false;
  1600. deferredSupport_ = false;
  1601. hardwareDepthSupport_ = false;
  1602. int numSupportedRTs = 1;
  1603. #ifndef GL_ES_VERSION_2_0
  1604. glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS_EXT, &numSupportedRTs);
  1605. #else
  1606. // For now disable shadow mapping on OpenGL ES
  1607. shadowMapFormat_ = 0;
  1608. hiresShadowMapFormat_ = 0;
  1609. #endif
  1610. // For now hardware depth texture is only tested for on NVIDIA hardware because of visual artifacts and slowdown on ATI
  1611. String vendorString = String((const char*)glGetString(GL_VENDOR)).ToUpper();
  1612. if (vendorString.Find("NVIDIA") != String::NPOS)
  1613. {
  1614. SharedPtr<Texture2D> depthTexture(new Texture2D(context_));
  1615. hardwareDepthSupport_ = true;
  1616. // Note: Texture2D::SetSize() requires hardwareDepthSupport_ == true to create a texture instead of a renderbuffer
  1617. depthTexture->SetSize(256, 256, GetDepthStencilFormat(), TEXTURE_DEPTHSTENCIL);
  1618. SetDepthStencil(depthTexture);
  1619. // If hardware depth textures work, this means also light pre-pass is automatically supported
  1620. if (CheckFramebuffer())
  1621. {
  1622. lightPrepassSupport_ = true;
  1623. if (numSupportedRTs >= 3)
  1624. deferredSupport_ = true;
  1625. }
  1626. else
  1627. hardwareDepthSupport_ = false;
  1628. ResetDepthStencil();
  1629. }
  1630. if (!hardwareDepthSupport_)
  1631. {
  1632. // If hardware depth is not supported, must support 2 rendertargets for light pre-pass, and 4 for deferred
  1633. if (numSupportedRTs >= 2)
  1634. lightPrepassSupport_ = true;
  1635. if (numSupportedRTs >= 4)
  1636. deferredSupport_ = true;
  1637. }
  1638. }
  1639. void Graphics::CommitFramebuffer()
  1640. {
  1641. if (!impl_->fboDirty_)
  1642. return;
  1643. impl_->fboDirty_ = false;
  1644. // First check if no framebuffer is needed. In that case simply return to backbuffer rendering
  1645. bool noFbo = !depthStencil_;
  1646. if (noFbo)
  1647. {
  1648. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1649. {
  1650. if (renderTargets_[i])
  1651. {
  1652. noFbo = false;
  1653. break;
  1654. }
  1655. }
  1656. }
  1657. if (noFbo)
  1658. {
  1659. if (impl_->boundFbo_)
  1660. {
  1661. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
  1662. impl_->boundFbo_ = 0;
  1663. }
  1664. return;
  1665. }
  1666. // Search for a new framebuffer based on format & size, or create new
  1667. IntVector2 rtSize = Graphics::GetRenderTargetDimensions();
  1668. unsigned format = 0;
  1669. if (renderTargets_[0])
  1670. format = renderTargets_[0]->GetParentTexture()->GetFormat();
  1671. else if (depthStencil_)
  1672. format = depthStencil_->GetParentTexture()->GetFormat();
  1673. unsigned long long fboKey = (rtSize.x_ << 16 | rtSize.y_) | (((unsigned long long)format) << 32);
  1674. Map<unsigned long long, FrameBufferObject>::Iterator i = impl_->frameBuffers_.Find(fboKey);
  1675. if (i == impl_->frameBuffers_.End())
  1676. {
  1677. FrameBufferObject newFbo;
  1678. glGenFramebuffersEXT(1, &newFbo.fbo_);
  1679. i = impl_->frameBuffers_.Insert(MakePair(fboKey, newFbo));
  1680. }
  1681. i->second_.useTimer_.Reset();
  1682. if (impl_->boundFbo_ != i->second_.fbo_)
  1683. {
  1684. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, i->second_.fbo_);
  1685. impl_->boundFbo_ = i->second_.fbo_;
  1686. }
  1687. #ifndef GL_ES_VERSION_2_0
  1688. // Setup readbuffers & drawbuffers if needed
  1689. if (i->second_.readBuffers_ != GL_NONE)
  1690. {
  1691. glReadBuffer(GL_NONE);
  1692. i->second_.readBuffers_ = GL_NONE;
  1693. }
  1694. // Calculate the bit combination of non-zero color rendertargets to first check if the combination changed
  1695. unsigned newDrawBuffers = 0;
  1696. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1697. {
  1698. if (renderTargets_[i])
  1699. newDrawBuffers |= 1 << i;
  1700. }
  1701. if (newDrawBuffers != i->second_.drawBuffers_)
  1702. {
  1703. // Check for no color rendertargets (depth rendering only)
  1704. if (!newDrawBuffers)
  1705. glDrawBuffer(GL_NONE);
  1706. else
  1707. {
  1708. int drawBufferIds[4];
  1709. unsigned drawBufferCount = 0;
  1710. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1711. {
  1712. if (renderTargets_[i])
  1713. drawBufferIds[drawBufferCount++] = GL_COLOR_ATTACHMENT0_EXT + i;
  1714. }
  1715. glDrawBuffers(drawBufferCount, (const GLenum*)drawBufferIds);
  1716. }
  1717. i->second_.drawBuffers_ = newDrawBuffers;
  1718. }
  1719. #endif
  1720. for (unsigned j = 0; j < MAX_RENDERTARGETS; ++j)
  1721. {
  1722. if (renderTargets_[j])
  1723. {
  1724. Texture* texture = renderTargets_[j]->GetParentTexture();
  1725. // If texture's parameters are dirty, update before attaching
  1726. if (texture->GetParametersDirty())
  1727. {
  1728. SetTextureForUpdate(texture);
  1729. texture->UpdateParameters();
  1730. SetTexture(0, 0);
  1731. }
  1732. if (i->second_.colorAttachments_[j] != renderTargets_[j])
  1733. {
  1734. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + j, renderTargets_[j]->GetTarget(),
  1735. texture->GetGPUObject(), 0);
  1736. i->second_.colorAttachments_[j] = renderTargets_[j];
  1737. }
  1738. }
  1739. else
  1740. {
  1741. if (i->second_.colorAttachments_[j])
  1742. {
  1743. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + j, GL_TEXTURE_2D, 0, 0);
  1744. i->second_.colorAttachments_[j] = 0;
  1745. }
  1746. }
  1747. }
  1748. if (depthStencil_)
  1749. {
  1750. // Bind either a renderbuffer or a depth texture, depending on what is available
  1751. Texture* texture = depthStencil_->GetParentTexture();
  1752. bool hasStencil = texture->GetFormat() == GetDepthStencilFormat();
  1753. unsigned renderBufferID = depthStencil_->GetRenderBuffer();
  1754. if (!renderBufferID)
  1755. {
  1756. // If texture's parameters are dirty, update before attaching
  1757. if (texture->GetParametersDirty())
  1758. {
  1759. SetTextureForUpdate(texture);
  1760. texture->UpdateParameters();
  1761. SetTexture(0, 0);
  1762. }
  1763. if (i->second_.depthAttachment_ != depthStencil_)
  1764. {
  1765. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, texture->GetGPUObject(), 0);
  1766. if (hasStencil)
  1767. {
  1768. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D,
  1769. texture->GetGPUObject(), 0);
  1770. }
  1771. else
  1772. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1773. i->second_.depthAttachment_ = depthStencil_;
  1774. }
  1775. }
  1776. else
  1777. {
  1778. if (i->second_.depthAttachment_ != depthStencil_)
  1779. {
  1780. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, renderBufferID);
  1781. if (hasStencil)
  1782. {
  1783. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT,
  1784. renderBufferID);
  1785. }
  1786. else
  1787. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1788. i->second_.depthAttachment_ = depthStencil_;
  1789. }
  1790. }
  1791. impl_->depthBits_ = texture->GetDepthBits();
  1792. }
  1793. else
  1794. {
  1795. if (i->second_.depthAttachment_)
  1796. {
  1797. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1798. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1799. i->second_.depthAttachment_ = 0;
  1800. impl_->depthBits_ = impl_->windowDepthBits_;
  1801. }
  1802. }
  1803. }
  1804. bool Graphics::CheckFramebuffer()
  1805. {
  1806. return glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT) == GL_FRAMEBUFFER_COMPLETE_EXT;
  1807. }
  1808. void Graphics::CleanupFramebuffers(bool deleteAll)
  1809. {
  1810. if (deleteAll && impl_->boundFbo_)
  1811. {
  1812. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
  1813. impl_->boundFbo_ = 0;
  1814. }
  1815. for (Map<unsigned long long, FrameBufferObject>::Iterator i = impl_->frameBuffers_.Begin(); i != impl_->frameBuffers_.End();)
  1816. {
  1817. Map<unsigned long long, FrameBufferObject>::Iterator current = i++;
  1818. if (deleteAll || (current->second_.fbo_ != impl_->boundFbo_ && current->second_.useTimer_.GetMSec(false) > MAX_FRAMEBUFFER_AGE))
  1819. {
  1820. glDeleteFramebuffersEXT(1, &current->second_.fbo_);
  1821. impl_->frameBuffers_.Erase(current);
  1822. }
  1823. }
  1824. }
  1825. void Graphics::ResetCachedState()
  1826. {
  1827. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  1828. {
  1829. vertexBuffers_[i] = 0;
  1830. elementMasks_[i] = 0;
  1831. }
  1832. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1833. {
  1834. textures_[i] = 0;
  1835. textureTypes_[i] = 0;
  1836. }
  1837. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1838. renderTargets_[i] = 0;
  1839. depthStencil_ = 0;
  1840. viewTexture_ = 0;
  1841. viewport_ = IntRect(0, 0, 0, 0);
  1842. indexBuffer_ = 0;
  1843. vertexShader_ = 0;
  1844. pixelShader_ = 0;
  1845. shaderProgram_ = 0;
  1846. blendMode_ = BLEND_REPLACE;
  1847. textureAnisotropy_ = 1;
  1848. colorWrite_ = true;
  1849. cullMode_ = CULL_NONE;
  1850. constantDepthBias_ = 0.0f;
  1851. slopeScaledDepthBias_ = 0.0f;
  1852. depthTestMode_ = CMP_ALWAYS;
  1853. depthWrite_ = true;
  1854. fillMode_ = FILL_SOLID;
  1855. scissorTest_ = false;
  1856. scissorRect_ = IntRect::ZERO;
  1857. stencilTest_ = false;
  1858. stencilTestMode_ = CMP_ALWAYS;
  1859. stencilPass_ = OP_KEEP;
  1860. stencilFail_ = OP_KEEP;
  1861. stencilZFail_ = OP_KEEP;
  1862. stencilRef_ = 0;
  1863. stencilCompareMask_ = M_MAX_UNSIGNED;
  1864. stencilWriteMask_ = M_MAX_UNSIGNED;
  1865. impl_->activeTexture_ = 0;
  1866. impl_->enabledAttributes_ = 0;
  1867. }
  1868. void Graphics::SetTextureUnitMappings()
  1869. {
  1870. textureUnits_["DiffMap"] = TU_DIFFUSE;
  1871. textureUnits_["DiffCubeMap"] = TU_DIFFUSE;
  1872. textureUnits_["NormalMap"] = TU_NORMAL;
  1873. textureUnits_["EmissiveMap"] = TU_EMISSIVE;
  1874. textureUnits_["DetailMap"] = TU_DETAIL;
  1875. textureUnits_["EnvironmentMap"] = TU_ENVIRONMENT;
  1876. textureUnits_["EnvironmentCubeMap"] = TU_ENVIRONMENT;
  1877. textureUnits_["LightRampMap"] = TU_LIGHTRAMP;
  1878. textureUnits_["LightSpotMap"] = TU_LIGHTSHAPE;
  1879. textureUnits_["LightCubeMap"] = TU_LIGHTSHAPE;
  1880. textureUnits_["ShadowMap"] = TU_SHADOWMAP;
  1881. textureUnits_["FaceSelectCubeMap"] = TU_FACESELECT;
  1882. textureUnits_["IndirectionCubeMap"] = TU_INDIRECTION;
  1883. textureUnits_["AlbedoBuffer"] = TU_ALBEDOBUFFER;
  1884. textureUnits_["NormalBuffer"] = TU_NORMALBUFFER;
  1885. textureUnits_["DepthBuffer"] = TU_DEPTHBUFFER;
  1886. textureUnits_["LightBuffer"] = TU_LIGHTBUFFER;
  1887. }
  1888. void RegisterGraphicsLibrary(Context* context)
  1889. {
  1890. Animation::RegisterObject(context);
  1891. Material::RegisterObject(context);
  1892. Model::RegisterObject(context);
  1893. Shader::RegisterObject(context);
  1894. Technique::RegisterObject(context);
  1895. Texture2D::RegisterObject(context);
  1896. TextureCube::RegisterObject(context);
  1897. Camera::RegisterObject(context);
  1898. Drawable::RegisterObject(context);
  1899. Light::RegisterObject(context);
  1900. StaticModel::RegisterObject(context);
  1901. Skybox::RegisterObject(context);
  1902. AnimatedModel::RegisterObject(context);
  1903. AnimationController::RegisterObject(context);
  1904. BillboardSet::RegisterObject(context);
  1905. ParticleEmitter::RegisterObject(context);
  1906. DebugRenderer::RegisterObject(context);
  1907. Octree::RegisterObject(context);
  1908. Zone::RegisterObject(context);
  1909. }