OGLGraphics.cpp 65 KB

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