2
0

OGLGraphics.cpp 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368
  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 <GLee.h>
  54. #include "DebugNew.h"
  55. #ifdef _MSC_VER
  56. #pragma warning(disable:4355)
  57. #endif
  58. static const unsigned glCmpFunc[] =
  59. {
  60. GL_ALWAYS,
  61. GL_EQUAL,
  62. GL_NOTEQUAL,
  63. GL_LESS,
  64. GL_LEQUAL,
  65. GL_GREATER,
  66. GL_GEQUAL
  67. };
  68. static const unsigned glSrcBlend[] =
  69. {
  70. GL_ONE,
  71. GL_ONE,
  72. GL_DST_COLOR,
  73. GL_SRC_ALPHA,
  74. GL_SRC_ALPHA,
  75. GL_ONE,
  76. GL_ONE_MINUS_DST_ALPHA
  77. };
  78. static const unsigned glDestBlend[] =
  79. {
  80. GL_ZERO,
  81. GL_ONE,
  82. GL_ZERO,
  83. GL_ONE_MINUS_SRC_ALPHA,
  84. GL_ONE,
  85. GL_ONE_MINUS_SRC_ALPHA,
  86. GL_DST_ALPHA
  87. };
  88. static const unsigned glStencilOps[] =
  89. {
  90. GL_KEEP,
  91. GL_ZERO,
  92. GL_REPLACE,
  93. GL_INCR,
  94. GL_DECR
  95. };
  96. static const String noParameter;
  97. static const DWORD windowStyle = WS_OVERLAPPEDWINDOW & ~WS_THICKFRAME & ~WS_MAXIMIZEBOX;
  98. static LRESULT CALLBACK wndProc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam);
  99. OBJECTTYPESTATIC(Graphics);
  100. Graphics::Graphics(Context* context_) :
  101. Object(context_),
  102. impl_(new GraphicsImpl()),
  103. mode_(RENDER_FORWARD),
  104. width_(0),
  105. height_(0),
  106. multiSample_(0),
  107. windowPosX_(0),
  108. windowPosY_(0),
  109. fullscreen_(false),
  110. vsync_(false),
  111. flushGPU_(true),
  112. fullscreenModeSet_(false),
  113. inModeChange_(false),
  114. deferredSupport_(false),
  115. prepassSupport_(false),
  116. numPrimitives_(0),
  117. numBatches_(0),
  118. immediateBuffer_(0),
  119. defaultTextureFilterMode_(FILTER_BILINEAR),
  120. shadowMapFormat_(0),
  121. hiresShadowMapFormat_(0)
  122. {
  123. ResetCachedState();
  124. InitializeShaderParameters();
  125. SubscribeToEvent(E_WINDOWMESSAGE, HANDLER(Graphics, HandleWindowMessage));
  126. SubscribeToEvent(E_ACTIVATION, HANDLER(Graphics, HandleActivation));
  127. }
  128. Graphics::~Graphics()
  129. {
  130. Close();
  131. delete impl_;
  132. impl_ = 0;
  133. }
  134. void Graphics::MessagePump()
  135. {
  136. MSG msg;
  137. while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
  138. {
  139. TranslateMessage(&msg);
  140. DispatchMessage(&msg);
  141. }
  142. }
  143. void Graphics::SetWindowTitle(const String& windowTitle)
  144. {
  145. windowTitle_ = windowTitle;
  146. if (impl_->window_)
  147. SetWindowText(impl_->window_, windowTitle_.CString());
  148. }
  149. bool Graphics::SetMode(RenderMode mode, int width, int height, bool fullscreen, bool vsync, int multiSample)
  150. {
  151. PROFILE(SetScreenMode);
  152. /// \todo For now multisampling is not supported
  153. multiSample = 0;
  154. // If zero dimensions, use the desktop default
  155. if ((width <= 0) || (height <= 0))
  156. {
  157. if (fullscreen)
  158. {
  159. IntVector2 desktopResolution = impl_->GetDesktopResolution();
  160. width = desktopResolution.x_;
  161. height = desktopResolution.y_;
  162. }
  163. else
  164. {
  165. width = 800;
  166. height = 600;
  167. }
  168. }
  169. if ((mode == mode_) && (width == width_) && (height == height_) && (fullscreen == fullscreen_) && (vsync == vsync_)
  170. && (multiSample == multiSample_))
  171. return true;
  172. if (!impl_->window_)
  173. {
  174. if (!OpenWindow(width, height))
  175. return false;
  176. }
  177. // Save window placement if currently windowed
  178. if (!fullscreen_)
  179. {
  180. WINDOWPLACEMENT wndpl;
  181. wndpl.length = sizeof wndpl;
  182. if (SUCCEEDED(GetWindowPlacement(impl_->window_, &wndpl)))
  183. {
  184. windowPosX_ = wndpl.rcNormalPosition.left;
  185. windowPosY_ = wndpl.rcNormalPosition.top;
  186. }
  187. }
  188. // Create OpenGL context
  189. if (!impl_->renderContext_)
  190. {
  191. impl_->renderContext_ = wglCreateContext(impl_->deviceContext_);
  192. wglMakeCurrent(impl_->deviceContext_, impl_->renderContext_);
  193. // Query for extensions now. Needs to happen under lock as the function pointers are static
  194. {
  195. MutexLock lock(GetStaticMutex());
  196. GLeeInit();
  197. }
  198. if (!_GLEE_VERSION_2_0)
  199. {
  200. LOGERROR("OpenGL 2.0 is required");
  201. return false;
  202. }
  203. // Create the FBO if supported
  204. if (_GLEE_EXT_framebuffer_object)
  205. {
  206. glGenFramebuffersEXT(1, &impl_->fbo_);
  207. // If FBO is supported, shadows can be rendered
  208. shadowMapFormat_ = GL_DEPTH_COMPONENT16;
  209. hiresShadowMapFormat_ = GL_DEPTH_COMPONENT24;
  210. // Deferred and light prepass rendering require the ability to use a depth/stencil buffer with FBO,
  211. // for proper optimization and split point light masking
  212. if (_GLEE_EXT_packed_depth_stencil)
  213. {
  214. deferredSupport_ = true;
  215. prepassSupport_ = true;
  216. }
  217. }
  218. // Set initial state to match Direct3D
  219. glEnable(GL_DEPTH_TEST);
  220. SetCullMode(CULL_CCW);
  221. SetDepthTest(CMP_LESSEQUAL);
  222. }
  223. // Change/restore desktop resolution as necessary
  224. if (fullscreen)
  225. {
  226. if (!SetScreenMode(width, height))
  227. fullscreen = false;
  228. }
  229. else
  230. {
  231. if (fullscreen_)
  232. RestoreScreenMode();
  233. }
  234. AdjustWindow(width, height, fullscreen);
  235. #ifdef WIN32
  236. if (wglSwapIntervalEXT)
  237. wglSwapIntervalEXT(vsync ? 1 : 0);
  238. #endif
  239. glGetIntegerv(GL_DEPTH_BITS, &impl_->windowDepthBits_);
  240. impl_->depthBits_ = impl_->windowDepthBits_;
  241. // Clear all additional depth buffers now, as they are possibly not needed any more
  242. depthTextures_.Clear();
  243. width_ = width;
  244. height_ = height;
  245. fullscreen_ = fullscreen;
  246. vsync_ = vsync;
  247. mode_ = mode;
  248. // Reset rendertargets and viewport for the new screen mode
  249. ResetRenderTargets();
  250. viewTexture_ = 0;
  251. // Get the system depth buffer's bit depth
  252. glGetIntegerv(GL_DEPTH_BITS, &impl_->depthBits_);
  253. // Create rendering buffers
  254. CreateRenderTargets();
  255. // Let screen mode dependent GPU objects update themselves
  256. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  257. (*i)->OnDeviceReset();
  258. if (!multiSample)
  259. LOGINFO("Set screen mode " + String(width_) + "x" + String(height_) + " " + (fullscreen_ ? "fullscreen" : "windowed"));
  260. else
  261. LOGINFO("Set screen mode " + String(width_) + "x" + String(height_) + " " + (fullscreen_ ? "fullscreen" : "windowed") +
  262. " multisample " + String(multiSample));
  263. using namespace ScreenMode;
  264. VariantMap eventData;
  265. eventData[P_WIDTH] = width_;
  266. eventData[P_HEIGHT] = height_;
  267. eventData[P_FULLSCREEN] = fullscreen_;
  268. SendEvent(E_SCREENMODE, eventData);
  269. return true;
  270. }
  271. bool Graphics::SetMode(int width, int height)
  272. {
  273. return SetMode(mode_, width, height, fullscreen_, vsync_, multiSample_);
  274. }
  275. bool Graphics::SetMode(RenderMode mode)
  276. {
  277. return SetMode(mode, width_, height_, fullscreen_, vsync_, multiSample_);
  278. }
  279. bool Graphics::ToggleFullscreen()
  280. {
  281. return SetMode(mode_, width_, height_, !fullscreen_, vsync_, multiSample_);
  282. }
  283. void Graphics::Close()
  284. {
  285. // Release all GPU objects that still exist
  286. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  287. (*i)->Release();
  288. gpuObjects_.Clear();
  289. if (impl_->renderContext_)
  290. {
  291. if (impl_->fbo_)
  292. glDeleteFramebuffersEXT(1, &impl_->fbo_);
  293. wglMakeCurrent(NULL, NULL);
  294. wglDeleteContext(impl_->renderContext_);
  295. impl_->renderContext_ = 0;
  296. }
  297. if (impl_->deviceContext_)
  298. {
  299. ReleaseDC(impl_->window_, impl_->deviceContext_);
  300. impl_->deviceContext_ = 0;
  301. }
  302. if (impl_->window_)
  303. {
  304. RestoreScreenMode();
  305. DestroyWindow(impl_->window_);
  306. impl_->window_ = 0;
  307. }
  308. }
  309. bool Graphics::TakeScreenShot(Image& destImage)
  310. {
  311. PROFILE(TakeScreenShot);
  312. SetRenderTarget(0, (RenderSurface*)0);
  313. destImage.SetSize(width_, height_, 3);
  314. glReadPixels(0, 0, width_, height_, GL_RGB, GL_UNSIGNED_BYTE, destImage.GetData());
  315. return true;
  316. }
  317. void Graphics::SetFlushGPU(bool enable)
  318. {
  319. flushGPU_ = enable;
  320. }
  321. bool Graphics::BeginFrame()
  322. {
  323. PROFILE(BeginRendering);
  324. if (!IsInitialized())
  325. return false;
  326. // If we should be fullscreen, but the screen mode is not currently set, do not render
  327. if ((fullscreen_) && (!fullscreenModeSet_))
  328. return false;
  329. // Set default rendertarget and depth buffer
  330. ResetRenderTargets();
  331. viewTexture_ = 0;
  332. // Cleanup textures from previous frame
  333. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  334. SetTexture(i, 0);
  335. // Enable color and depth write
  336. SetColorWrite(true);
  337. SetDepthWrite(true);
  338. // Reset immediate mode vertex buffer positions
  339. for (Map<unsigned, unsigned>::Iterator i = immediateVertexBufferPos_.Begin(); i != immediateVertexBufferPos_.End(); ++i)
  340. i->second_ = 0;
  341. numPrimitives_ = 0;
  342. numBatches_ = 0;
  343. SendEvent(E_BEGINRENDER);
  344. return true;
  345. }
  346. void Graphics::EndFrame()
  347. {
  348. PROFILE(EndRendering);
  349. if (!IsInitialized())
  350. return;
  351. SendEvent(E_ENDRENDER);
  352. SwapBuffers(impl_->deviceContext_);
  353. }
  354. void Graphics::Clear(unsigned flags, const Color& color, float depth, unsigned stencil)
  355. {
  356. bool oldColorWrite = colorWrite_;
  357. bool oldDepthWrite = depthWrite_;
  358. if ((flags & CLEAR_COLOR) && (!oldColorWrite))
  359. SetColorWrite(true);
  360. if ((flags & CLEAR_DEPTH) && (!oldDepthWrite))
  361. SetDepthWrite(true);
  362. 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. glClear(glFlags);
  379. SetColorWrite(oldColorWrite);
  380. SetDepthWrite(oldDepthWrite);
  381. }
  382. void Graphics::Draw(PrimitiveType type, unsigned vertexStart, unsigned vertexCount)
  383. {
  384. if (!vertexCount)
  385. return;
  386. unsigned primitiveCount = 0;
  387. switch (type)
  388. {
  389. case TRIANGLE_LIST:
  390. primitiveCount = vertexCount / 3;
  391. glDrawArrays(GL_TRIANGLES, vertexStart, vertexCount);
  392. break;
  393. case LINE_LIST:
  394. primitiveCount = vertexCount / 2;
  395. glDrawArrays(GL_LINES, vertexStart, vertexCount);
  396. break;
  397. }
  398. numPrimitives_ += primitiveCount;
  399. ++numBatches_;
  400. }
  401. void Graphics::Draw(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount)
  402. {
  403. if ((!indexCount) || (!indexBuffer_))
  404. return;
  405. unsigned primitiveCount = 0;
  406. unsigned indexSize = indexBuffer_->GetIndexSize();
  407. switch (type)
  408. {
  409. case TRIANGLE_LIST:
  410. primitiveCount = indexCount / 3;
  411. if (indexSize == sizeof(unsigned short))
  412. glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_SHORT, (const GLvoid*)(indexStart * indexSize));
  413. else
  414. glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, (const GLvoid*)(indexStart * indexSize));
  415. break;
  416. case LINE_LIST:
  417. primitiveCount = indexCount / 2;
  418. if (indexSize == sizeof(unsigned short))
  419. glDrawElements(GL_LINES, indexCount, GL_UNSIGNED_SHORT, (const GLvoid*)(indexStart * indexSize));
  420. else
  421. glDrawElements(GL_LINES, indexCount, GL_UNSIGNED_INT, (const GLvoid*)(indexStart * indexSize));
  422. break;
  423. }
  424. numPrimitives_ += primitiveCount;
  425. ++numBatches_;
  426. }
  427. void Graphics::DrawInstanced(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount, unsigned instanceCount)
  428. {
  429. }
  430. void Graphics::SetVertexBuffer(VertexBuffer* buffer)
  431. {
  432. Vector<VertexBuffer*> vertexBuffers(1);
  433. PODVector<unsigned> elementMasks(1);
  434. vertexBuffers[0] = buffer;
  435. elementMasks[0] = MASK_DEFAULT;
  436. SetVertexBuffers(vertexBuffers, elementMasks);
  437. }
  438. bool Graphics::SetVertexBuffers(const Vector<VertexBuffer*>& buffers, const PODVector<unsigned>& elementMasks,
  439. unsigned instanceOffset)
  440. {
  441. if (buffers.Size() > MAX_VERTEX_STREAMS)
  442. {
  443. LOGERROR("Too many vertex buffers");
  444. return false;
  445. }
  446. if (buffers.Size() != elementMasks.Size())
  447. {
  448. LOGERROR("Amount of element masks and vertex buffers does not match");
  449. return false;
  450. }
  451. // If no valid shader to determine the attribute bindings, can not set vertex buffers
  452. if (!shaderProgram_)
  453. return false;
  454. const int* attributeLocations = shaderProgram_->GetAttributeLocations();
  455. bool changed = false;
  456. unsigned newAttributes = 0;
  457. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  458. {
  459. VertexBuffer* buffer = 0;
  460. unsigned elementMask = 0;
  461. if (i < buffers.Size())
  462. {
  463. buffer = buffers[i];
  464. elementMask = elementMasks[i];
  465. if ((elementMask == MASK_DEFAULT) && (buffer))
  466. elementMask = buffers[i]->GetElementMask();
  467. }
  468. // If buffer and element mask have stayed the same, skip to the next buffer
  469. if ((buffer == vertexBuffers_[i]) && (elementMask == elementMasks_[i]))
  470. continue;
  471. vertexBuffers_[i] = buffer;
  472. elementMasks_[i] = elementMask;
  473. changed = true;
  474. if (!buffer)
  475. continue;
  476. glBindBuffer(GL_ARRAY_BUFFER, buffer->GetGPUObject());
  477. unsigned vertexSize = buffer->GetVertexSize();
  478. for (unsigned j = 0; j < MAX_VERTEX_ELEMENTS; ++j)
  479. {
  480. // If shader does not use the attribute, do not bind it (bandwidth optimization)
  481. int attributeIndex = attributeLocations[j];
  482. if (attributeIndex < 0)
  483. continue;
  484. unsigned elementBit = 1 << j;
  485. unsigned attributeBit = 1 << attributeIndex;
  486. if (elementMask & elementBit)
  487. {
  488. newAttributes |= attributeBit;
  489. // Enable attribute if not enabled yet
  490. if ((impl_->enabledAttributes_ & attributeBit) == 0)
  491. {
  492. glEnableVertexAttribArray(attributeIndex);
  493. impl_->enabledAttributes_ |= attributeBit;
  494. }
  495. // Set the attribute pointer
  496. glVertexAttribPointer(attributeIndex, VertexBuffer::elementComponents[j], VertexBuffer::elementType[j],
  497. VertexBuffer::elementNormalize[j], vertexSize, (const GLvoid*)(buffer->GetElementOffset((VertexElement)j)));
  498. }
  499. }
  500. }
  501. if (!changed)
  502. return true;
  503. // Now check which vertex attributes should be disabled
  504. unsigned disableAttributes = impl_->enabledAttributes_ & (~newAttributes);
  505. int disableIndex = 0;
  506. while (disableAttributes)
  507. {
  508. if (disableAttributes & 1)
  509. {
  510. glDisableVertexAttribArray(disableIndex);
  511. impl_->enabledAttributes_ &= ~(1 << disableIndex);
  512. }
  513. disableAttributes >>= 1;
  514. ++disableIndex;
  515. }
  516. return true;
  517. }
  518. bool Graphics::SetVertexBuffers(const Vector<SharedPtr<VertexBuffer> >& buffers, const PODVector<unsigned>&
  519. elementMasks, unsigned instanceOffset)
  520. {
  521. if (buffers.Size() > MAX_VERTEX_STREAMS)
  522. {
  523. LOGERROR("Too many vertex buffers");
  524. return false;
  525. }
  526. if (buffers.Size() != elementMasks.Size())
  527. {
  528. LOGERROR("Amount of element masks and vertex buffers does not match");
  529. return false;
  530. }
  531. // If no valid shader to determine the attribute bindings, can not set vertex buffers
  532. if (!shaderProgram_)
  533. return false;
  534. const int* attributeLocations = shaderProgram_->GetAttributeLocations();
  535. bool changed = false;
  536. unsigned newAttributes = 0;
  537. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  538. {
  539. VertexBuffer* buffer = 0;
  540. unsigned elementMask = 0;
  541. if (i < buffers.Size())
  542. {
  543. buffer = buffers[i];
  544. elementMask = elementMasks[i];
  545. if ((elementMask == MASK_DEFAULT) && (buffer))
  546. elementMask = buffers[i]->GetElementMask();
  547. }
  548. // If buffer and element mask have stayed the same, skip to the next buffer
  549. if ((buffer == vertexBuffers_[i]) && (elementMask == elementMasks_[i]))
  550. continue;
  551. vertexBuffers_[i] = buffer;
  552. elementMasks_[i] = elementMask;
  553. changed = true;
  554. if (!buffer)
  555. continue;
  556. glBindBuffer(GL_ARRAY_BUFFER, buffer->GetGPUObject());
  557. unsigned vertexSize = buffer->GetVertexSize();
  558. for (unsigned j = 0; j < MAX_VERTEX_ELEMENTS; ++j)
  559. {
  560. // If shader does not use the attribute, do not bind it (bandwidth optimization)
  561. int attributeIndex = attributeLocations[j];
  562. if (attributeIndex < 0)
  563. continue;
  564. unsigned elementBit = 1 << j;
  565. unsigned attributeBit = 1 << attributeIndex;
  566. if (elementMask & elementBit)
  567. {
  568. newAttributes |= attributeBit;
  569. // Enable attribute if not enabled yet
  570. if ((impl_->enabledAttributes_ & attributeBit) == 0)
  571. {
  572. glEnableVertexAttribArray(attributeIndex);
  573. impl_->enabledAttributes_ |= attributeBit;
  574. }
  575. // Set the attribute pointer
  576. glVertexAttribPointer(attributeIndex, VertexBuffer::elementComponents[j], VertexBuffer::elementType[j],
  577. VertexBuffer::elementNormalize[j], vertexSize, (const GLvoid*)(buffer->GetElementOffset((VertexElement)j)));
  578. }
  579. }
  580. }
  581. if (!changed)
  582. return true;
  583. // Now check which vertex attributes should be disabled
  584. unsigned disableAttributes = impl_->enabledAttributes_ & (~newAttributes);
  585. int disableIndex = 0;
  586. while (disableAttributes)
  587. {
  588. if (disableAttributes & 1)
  589. {
  590. glDisableVertexAttribArray(disableIndex);
  591. impl_->enabledAttributes_ &= ~(1 << disableIndex);
  592. }
  593. disableAttributes >>= 1;
  594. ++disableIndex;
  595. }
  596. return true;
  597. }
  598. void Graphics::SetIndexBuffer(IndexBuffer* buffer)
  599. {
  600. if (indexBuffer_ == buffer)
  601. return;
  602. if (buffer)
  603. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer->GetGPUObject());
  604. else
  605. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
  606. indexBuffer_ = buffer;
  607. }
  608. void Graphics::SetShaders(ShaderVariation* vs, ShaderVariation* ps)
  609. {
  610. if ((vs == vertexShader_) && (ps == pixelShader_))
  611. return;
  612. // All vertex attributes must be re-bound after shader change, and uniforms need to be reassigned
  613. ClearLastParameterSources();
  614. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  615. {
  616. vertexBuffers_[i] = 0;
  617. elementMasks_[i] = 0;
  618. }
  619. if ((!vs) || (!ps))
  620. {
  621. glUseProgram(0);
  622. vertexShader_ = 0;
  623. pixelShader_ = 0;
  624. shaderProgram_ = 0;
  625. }
  626. else
  627. {
  628. vertexShader_ = vs;
  629. pixelShader_ = ps;
  630. Pair<ShaderVariation*, ShaderVariation*> combination(vs, ps);
  631. ShaderProgramMap::Iterator i = shaderPrograms_.Find(combination);
  632. if (i != shaderPrograms_.End())
  633. {
  634. // Use the existing linked program
  635. if (i->second_->IsLinked())
  636. {
  637. glUseProgram(i->second_->GetGPUObject());
  638. shaderProgram_ = i->second_;
  639. }
  640. else
  641. {
  642. glUseProgram(0);
  643. shaderProgram_ = 0;
  644. }
  645. }
  646. else
  647. {
  648. // Link a new combination
  649. SharedPtr<ShaderProgram> newProgram(new ShaderProgram(this, vs, ps));
  650. if (!newProgram->Link())
  651. {
  652. LOGERROR("Failed to link shader " + vs->GetShader()->GetName() + ":\n" +
  653. newProgram->GetLinkerOutput());
  654. glUseProgram(0);
  655. shaderProgram_ = 0;
  656. }
  657. else
  658. {
  659. // Note: Link() calls glUseProgram() to set the texture sampler uniforms,
  660. // so it is not necessary to call it again
  661. shaderProgram_ = newProgram;
  662. }
  663. shaderPrograms_[combination] = newProgram;
  664. }
  665. }
  666. }
  667. void Graphics::SetShaderParameter(ShaderParameter param, const bool* data, unsigned count)
  668. {
  669. // Not supported
  670. }
  671. void Graphics::SetShaderParameter(ShaderParameter param, const float* data, unsigned count)
  672. {
  673. if (shaderProgram_)
  674. {
  675. const UniformInfo* info = shaderProgram_->GetUniformInfo(param);
  676. if (info)
  677. {
  678. switch (info->type_)
  679. {
  680. case GL_FLOAT:
  681. glUniform1fv(info->location_, count, data);
  682. break;
  683. case GL_FLOAT_VEC2:
  684. glUniform2fv(info->location_, count / 2, data);
  685. break;
  686. case GL_FLOAT_VEC3:
  687. glUniform3fv(info->location_, count / 3, data);
  688. break;
  689. case GL_FLOAT_VEC4:
  690. glUniform4fv(info->location_, count / 4, data);
  691. break;
  692. case GL_FLOAT_MAT3:
  693. glUniformMatrix3fv(info->location_, count / 9, GL_TRUE, data);
  694. break;
  695. case GL_FLOAT_MAT4:
  696. glUniformMatrix4fv(info->location_, count / 16, GL_TRUE, data);
  697. break;
  698. }
  699. }
  700. }
  701. }
  702. void Graphics::SetShaderParameter(ShaderParameter param, const int* data, unsigned count)
  703. {
  704. if (shaderProgram_)
  705. {
  706. const UniformInfo* info = shaderProgram_->GetUniformInfo(param);
  707. if (info)
  708. {
  709. switch (info->type_)
  710. {
  711. case GL_INT:
  712. glUniform1iv(info->location_, count, data);
  713. break;
  714. case GL_INT_VEC2:
  715. glUniform2iv(info->location_, count / 2, data);
  716. break;
  717. case GL_INT_VEC3:
  718. glUniform3iv(info->location_, count / 3, data);
  719. break;
  720. case GL_INT_VEC4:
  721. glUniform4iv(info->location_, count / 4, data);
  722. break;
  723. }
  724. }
  725. }
  726. }
  727. void Graphics::SetShaderParameter(ShaderParameter param, float value)
  728. {
  729. if (shaderProgram_)
  730. {
  731. const UniformInfo* info = shaderProgram_->GetUniformInfo(param);
  732. if (info)
  733. glUniform1fv(info->location_, 1, &value);
  734. }
  735. }
  736. void Graphics::SetShaderParameter(ShaderParameter param, const Color& color)
  737. {
  738. SetShaderParameter(param, color.GetData(), 4);
  739. }
  740. void Graphics::SetShaderParameter(ShaderParameter param, const Matrix3& matrix)
  741. {
  742. if (shaderProgram_)
  743. {
  744. const UniformInfo* info = shaderProgram_->GetUniformInfo(param);
  745. if (info)
  746. glUniformMatrix3fv(info->location_, 1, GL_TRUE, matrix.GetData());
  747. }
  748. }
  749. void Graphics::SetShaderParameter(ShaderParameter param, const Vector3& vector)
  750. {
  751. if (shaderProgram_)
  752. {
  753. const UniformInfo* info = shaderProgram_->GetUniformInfo(param);
  754. if (info)
  755. {
  756. // Check the uniform type to avoid mismatch
  757. switch (info->type_)
  758. {
  759. case GL_FLOAT:
  760. glUniform1fv(info->location_, 1, vector.GetData());
  761. break;
  762. case GL_FLOAT_VEC2:
  763. glUniform2fv(info->location_, 1, vector.GetData());
  764. break;
  765. case GL_FLOAT_VEC3:
  766. glUniform3fv(info->location_, 1, vector.GetData());
  767. break;
  768. }
  769. }
  770. }
  771. }
  772. void Graphics::SetShaderParameter(ShaderParameter param, const Matrix4& matrix)
  773. {
  774. if (shaderProgram_)
  775. {
  776. const UniformInfo* info = shaderProgram_->GetUniformInfo(param);
  777. if (info)
  778. glUniformMatrix4fv(info->location_, 1, GL_TRUE, matrix.GetData());
  779. }
  780. }
  781. void Graphics::SetShaderParameter(ShaderParameter param, const Vector4& vector)
  782. {
  783. if (shaderProgram_)
  784. {
  785. const UniformInfo* info = shaderProgram_->GetUniformInfo(param);
  786. if (info)
  787. {
  788. // Check the uniform type to avoid mismatch
  789. switch (info->type_)
  790. {
  791. case GL_FLOAT:
  792. glUniform1fv(info->location_, 1, vector.GetData());
  793. break;
  794. case GL_FLOAT_VEC2:
  795. glUniform2fv(info->location_, 1, vector.GetData());
  796. break;
  797. case GL_FLOAT_VEC3:
  798. glUniform3fv(info->location_, 1, vector.GetData());
  799. break;
  800. case GL_FLOAT_VEC4:
  801. glUniform4fv(info->location_, 1, vector.GetData());
  802. break;
  803. }
  804. }
  805. }
  806. }
  807. void Graphics::SetShaderParameter(ShaderParameter param, const Matrix3x4& matrix)
  808. {
  809. if (shaderProgram_)
  810. {
  811. const UniformInfo* info = shaderProgram_->GetUniformInfo(param);
  812. if (info)
  813. {
  814. float data[16];
  815. data[0] = matrix.m00_;
  816. data[1] = matrix.m01_;
  817. data[2] = matrix.m02_;
  818. data[3] = matrix.m03_;
  819. data[4] = matrix.m10_;
  820. data[5] = matrix.m11_;
  821. data[6] = matrix.m12_;
  822. data[7] = matrix.m13_;
  823. data[8] = matrix.m20_;
  824. data[9] = matrix.m21_;
  825. data[10] = matrix.m22_;
  826. data[11] = matrix.m23_;
  827. data[12] = 0.0f;
  828. data[13] = 0.0f;
  829. data[14] = 0.0f;
  830. data[15] = 1.0f;
  831. glUniformMatrix4fv(info->location_, 1, GL_TRUE, data);
  832. }
  833. }
  834. }
  835. bool Graphics::NeedParameterUpdate(ShaderParameter param, const void* source)
  836. {
  837. if ((shaderProgram_) && (shaderProgram_->HasParameter(param)) && (lastShaderParameterSources_[param] != source))
  838. {
  839. lastShaderParameterSources_[param] = source;
  840. return true;
  841. }
  842. return false;
  843. }
  844. bool Graphics::NeedTextureUnit(TextureUnit unit)
  845. {
  846. if ((shaderProgram_) && (shaderProgram_->HasTextureUnit(unit)))
  847. return true;
  848. return false;
  849. }
  850. void Graphics::ClearLastParameterSources()
  851. {
  852. for (unsigned i = 0; i < MAX_SHADER_PARAMETERS; ++i)
  853. lastShaderParameterSources_[i] = (const void*)M_MAX_UNSIGNED;
  854. }
  855. void Graphics::ClearTransformSources()
  856. {
  857. lastShaderParameterSources_[VSP_MODEL] = (const void*)M_MAX_UNSIGNED;
  858. lastShaderParameterSources_[VSP_VIEWPROJ] = (const void*)M_MAX_UNSIGNED;
  859. }
  860. void Graphics::CleanupShaderPrograms()
  861. {
  862. for (ShaderProgramMap::Iterator i = shaderPrograms_.Begin(); i != shaderPrograms_.End();)
  863. {
  864. ShaderProgramMap::Iterator current = i++;
  865. if (!current->second_->GetGPUObject())
  866. {
  867. if (shaderProgram_ == current->second_)
  868. shaderProgram_ = 0;
  869. shaderPrograms_.Erase(current);
  870. }
  871. }
  872. }
  873. void Graphics::SetTexture(unsigned index, Texture* texture)
  874. {
  875. if (index >= MAX_TEXTURE_UNITS)
  876. return;
  877. // Check if texture is currently bound as a render target. In that case, use its backup texture, or blank if not defined
  878. if (texture)
  879. {
  880. if (((renderTargets_[0]) && (renderTargets_[0]->GetParentTexture() == texture)) ||
  881. ((depthStencil_) && (depthStencil_->GetParentTexture() == texture)))
  882. texture = texture->GetBackupTexture();
  883. // Check also for the view texture, in case a specific rendering pass does not bind the destination render target,
  884. // but should still not sample it either
  885. else if (texture == viewTexture_)
  886. texture = texture->GetBackupTexture();
  887. }
  888. if (textures_[index] != texture)
  889. {
  890. if (impl_->activeTexture_ != index)
  891. {
  892. glActiveTexture(GL_TEXTURE0 + index);
  893. impl_->activeTexture_ = index;
  894. }
  895. if (texture)
  896. {
  897. unsigned glType = texture->GetTextureType();
  898. if (glType != textureTypes_[index])
  899. {
  900. if (textureTypes_[index])
  901. glDisable(textureTypes_[index]);
  902. glEnable(glType);
  903. textureTypes_[index] = glType;
  904. }
  905. glBindTexture(glType, texture->GetGPUObject());
  906. if (texture->GetParametersDirty())
  907. texture->UpdateParameters();
  908. }
  909. else
  910. {
  911. if (textureTypes_[index])
  912. glBindTexture(textureTypes_[index], 0);
  913. }
  914. textures_[index] = texture;
  915. }
  916. else
  917. {
  918. if ((texture) && (texture->GetParametersDirty()))
  919. {
  920. if (impl_->activeTexture_ != index)
  921. {
  922. glActiveTexture(GL_TEXTURE0 + index);
  923. impl_->activeTexture_ = index;
  924. }
  925. glBindTexture(texture->GetTextureType(), texture->GetGPUObject());
  926. texture->UpdateParameters();
  927. }
  928. }
  929. }
  930. void Graphics::SetTextureForUpdate(Texture* texture)
  931. {
  932. if (impl_->activeTexture_ != 0)
  933. {
  934. glActiveTexture(GL_TEXTURE0);
  935. impl_->activeTexture_ = 0;
  936. }
  937. glBindTexture(texture->GetTextureType(), texture->GetGPUObject());
  938. textures_[0] = texture;
  939. }
  940. void Graphics::SetDefaultTextureFilterMode(TextureFilterMode mode)
  941. {
  942. if (mode != defaultTextureFilterMode_)
  943. {
  944. defaultTextureFilterMode_ = mode;
  945. SetTextureParametersDirty();
  946. }
  947. }
  948. void Graphics::SetTextureAnisotropy(unsigned level)
  949. {
  950. if (level != textureAnisotropy_)
  951. {
  952. textureAnisotropy_ = level;
  953. SetTextureParametersDirty();
  954. }
  955. }
  956. void Graphics::SetTextureParametersDirty()
  957. {
  958. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  959. {
  960. Texture* texture = dynamic_cast<Texture*>(*i);
  961. if (texture)
  962. texture->SetParametersDirty();
  963. }
  964. }
  965. void Graphics::ResetRenderTargets()
  966. {
  967. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  968. SetRenderTarget(i, (RenderSurface*)0);
  969. SetDepthStencil((RenderSurface*)0);
  970. }
  971. void Graphics::ResetRenderTarget(unsigned index)
  972. {
  973. SetRenderTarget(index, (RenderSurface*)0);
  974. }
  975. void Graphics::ResetDepthStencil()
  976. {
  977. SetDepthStencil((RenderSurface*)0);
  978. }
  979. void Graphics::SetRenderTarget(unsigned index, RenderSurface* renderTarget)
  980. {
  981. if ((index >= MAX_RENDERTARGETS) || (!impl_->fbo_))
  982. return;
  983. if (renderTarget != renderTargets_[index])
  984. {
  985. renderTargets_[index] = renderTarget;
  986. // If the rendertarget is also bound as a texture, replace with backup texture or null
  987. if (renderTarget)
  988. {
  989. Texture* parentTexture = renderTarget->GetParentTexture();
  990. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  991. {
  992. if (textures_[i] == parentTexture)
  993. SetTexture(i, textures_[i]->GetBackupTexture());
  994. }
  995. }
  996. // Bind the FBO to be able to make changes to it
  997. if (!impl_->fboBound_)
  998. {
  999. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, impl_->fbo_);
  1000. impl_->fboBound_ = true;
  1001. }
  1002. if (renderTarget)
  1003. {
  1004. Texture* texture = renderTarget->GetParentTexture();
  1005. // If texture's parameters are dirty, update before attaching
  1006. if (texture->GetParametersDirty())
  1007. {
  1008. SetTextureForUpdate(texture);
  1009. texture->UpdateParameters();
  1010. SetTexture(0, 0);
  1011. }
  1012. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + index, GL_TEXTURE_2D, texture->GetGPUObject(), 0);
  1013. }
  1014. else
  1015. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + index, GL_TEXTURE_2D, 0, 0);
  1016. // Disable color buffer writing/reading if only a depth texture is to be used:
  1017. // otherwise it is an OpenGL error (incomplete framebuffer)
  1018. SetDrawBuffers();
  1019. // If all rendertargets and the depth buffer are not textures, revert to backbuffer rendering
  1020. bool noFBO = (depthStencil_ == 0);
  1021. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1022. {
  1023. if (renderTargets_[i])
  1024. {
  1025. noFBO = false;
  1026. break;
  1027. }
  1028. }
  1029. if ((noFBO) && (impl_->fboBound_))
  1030. {
  1031. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
  1032. impl_->fboBound_ = false;
  1033. }
  1034. }
  1035. }
  1036. void Graphics::SetRenderTarget(unsigned index, Texture2D* renderTexture)
  1037. {
  1038. RenderSurface* renderTarget = 0;
  1039. if (renderTexture)
  1040. renderTarget = renderTexture->GetRenderSurface();
  1041. SetRenderTarget(index, renderTarget);
  1042. }
  1043. void Graphics::SetDepthStencil(RenderSurface* depthStencil)
  1044. {
  1045. if ((impl_->fbo_) && (depthStencil != depthStencil_))
  1046. {
  1047. // If we are using a rendertarget texture, it is required in OpenGL to also have an own depth stencil
  1048. // Create a new depth stencil texture as necessary to be able to provide similar behaviour.
  1049. if ((renderTargets_[0]) && (!depthStencil))
  1050. {
  1051. int width = renderTargets_[0]->GetWidth();
  1052. int height = renderTargets_[0]->GetHeight();
  1053. // Reuse the deferred depth buffer if possible
  1054. if ((depthBuffer_) && (width == width_) && (height == height_))
  1055. depthStencil = depthBuffer_->GetRenderSurface();
  1056. else
  1057. {
  1058. int searchKey = (width << 16) | height;
  1059. Map<int, SharedPtr<Texture2D> >::Iterator i = depthTextures_.Find(searchKey);
  1060. if (i != depthTextures_.End())
  1061. depthStencil = i->second_->GetRenderSurface();
  1062. else
  1063. {
  1064. SharedPtr<Texture2D> newDepthTexture(new Texture2D(context_));
  1065. newDepthTexture->SetSize(width, height, GetDepthFormat(), TEXTURE_DEPTHSTENCIL);
  1066. depthTextures_[searchKey] = newDepthTexture;
  1067. depthStencil = newDepthTexture->GetRenderSurface();
  1068. }
  1069. }
  1070. }
  1071. /// \todo Should check if the texture actually is in depth format
  1072. depthStencil_ = depthStencil;
  1073. // Bind the FBO to be able to make changes to it
  1074. if (!impl_->fboBound_)
  1075. {
  1076. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, impl_->fbo_);
  1077. impl_->fboBound_ = true;
  1078. }
  1079. if (depthStencil)
  1080. {
  1081. Texture* texture = depthStencil->GetParentTexture();
  1082. // If texture's parameters are dirty, update before attaching
  1083. if (texture->GetParametersDirty())
  1084. {
  1085. SetTextureForUpdate(texture);
  1086. texture->UpdateParameters();
  1087. SetTexture(0, 0);
  1088. }
  1089. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, texture->GetGPUObject(), 0);
  1090. impl_->depthBits_ = texture->GetDepthBits();
  1091. }
  1092. else
  1093. {
  1094. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1095. impl_->depthBits_ = impl_->windowDepthBits_;
  1096. }
  1097. // Disable color buffer writing/reading if only a depth texture is to be used:
  1098. // otherwise it is an OpenGL error (incomplete framebuffer)
  1099. SetDrawBuffers();
  1100. // If all rendertargets and the depth buffer are not textures, revert to backbuffer rendering
  1101. bool noFBO = (depthStencil_ == 0);
  1102. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1103. {
  1104. if (renderTargets_[i])
  1105. {
  1106. noFBO = false;
  1107. break;
  1108. }
  1109. }
  1110. if ((noFBO) && (impl_->fboBound_))
  1111. {
  1112. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
  1113. impl_->fboBound_ = false;
  1114. }
  1115. }
  1116. // Reset viewport and scissor test
  1117. IntVector2 viewSize = GetRenderTargetDimensions();
  1118. SetViewport(IntRect(0, 0, viewSize.x_, viewSize.y_));
  1119. SetScissorTest(false);
  1120. }
  1121. void Graphics::SetDepthStencil(Texture2D* depthTexture)
  1122. {
  1123. RenderSurface* depthStencil = 0;
  1124. if (depthTexture)
  1125. depthStencil = depthTexture->GetRenderSurface();
  1126. SetDepthStencil(depthStencil);
  1127. }
  1128. void Graphics::SetViewport(const IntRect& rect)
  1129. {
  1130. IntVector2 rtSize = GetRenderTargetDimensions();
  1131. IntRect rectCopy = rect;
  1132. if (rectCopy.right_ <= rectCopy.left_)
  1133. rectCopy.right_ = rectCopy.left_ + 1;
  1134. if (rectCopy.bottom_ <= rectCopy.top_)
  1135. rectCopy.bottom_ = rectCopy.top_ + 1;
  1136. rectCopy.left_ = Clamp(rectCopy.left_, 0, rtSize.x_);
  1137. rectCopy.top_ = Clamp(rectCopy.top_, 0, rtSize.y_);
  1138. rectCopy.right_ = Clamp(rectCopy.right_, 0, rtSize.x_);
  1139. rectCopy.bottom_ = Clamp(rectCopy.bottom_, 0, rtSize.y_);
  1140. if (rectCopy != viewport_)
  1141. {
  1142. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1143. glViewport(rectCopy.left_, rtSize.y_ - rectCopy.bottom_, rectCopy.right_ - rectCopy.left_, rectCopy.bottom_ - rectCopy.top_);
  1144. viewport_ = rectCopy;
  1145. }
  1146. // Disable scissor test, needs to be re-enabled by the user
  1147. SetScissorTest(false);
  1148. }
  1149. void Graphics::SetViewTexture(Texture* texture)
  1150. {
  1151. viewTexture_ = texture;
  1152. // Check for the view texture being currently bound
  1153. if (texture)
  1154. {
  1155. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1156. {
  1157. if (textures_[i] == texture)
  1158. SetTexture(i, textures_[i]->GetBackupTexture());
  1159. }
  1160. }
  1161. }
  1162. void Graphics::SetAlphaTest(bool enable, CompareMode mode, float alphaRef)
  1163. {
  1164. if (enable != alphaTest_)
  1165. {
  1166. if (enable)
  1167. glEnable(GL_ALPHA_TEST);
  1168. else
  1169. glDisable(GL_ALPHA_TEST);
  1170. alphaTest_ = enable;
  1171. }
  1172. if (enable)
  1173. {
  1174. alphaRef = Clamp(alphaRef, 0.0f, 1.0f);
  1175. if ((mode != alphaTestMode_) || (alphaRef != alphaRef_))
  1176. {
  1177. glAlphaFunc(glCmpFunc[mode], alphaRef);
  1178. alphaTestMode_ = mode;
  1179. alphaRef_ = alphaRef;
  1180. }
  1181. }
  1182. }
  1183. void Graphics::SetBlendMode(BlendMode mode)
  1184. {
  1185. if (mode != blendMode_)
  1186. {
  1187. if (mode == BLEND_REPLACE)
  1188. glDisable(GL_BLEND);
  1189. else
  1190. {
  1191. glEnable(GL_BLEND);
  1192. glBlendFunc(glSrcBlend[mode], glDestBlend[mode]);
  1193. }
  1194. blendMode_ = mode;
  1195. }
  1196. }
  1197. void Graphics::SetColorWrite(bool enable)
  1198. {
  1199. if (enable != colorWrite_)
  1200. {
  1201. if (enable)
  1202. glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  1203. else
  1204. glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  1205. colorWrite_ = enable;
  1206. }
  1207. }
  1208. void Graphics::SetCullMode(CullMode mode)
  1209. {
  1210. if (mode != cullMode_)
  1211. {
  1212. if (mode == CULL_NONE)
  1213. glDisable(GL_CULL_FACE);
  1214. else
  1215. {
  1216. // Use Direct3D convention, ie. clockwise vertices define a front face
  1217. glEnable(GL_CULL_FACE);
  1218. glCullFace(mode == CULL_CCW ? GL_FRONT : GL_BACK);
  1219. }
  1220. cullMode_ = mode;
  1221. }
  1222. }
  1223. void Graphics::SetDepthBias(float constantBias, float slopeScaledBias)
  1224. {
  1225. if ((constantBias != constantDepthBias_) || (slopeScaledBias != slopeScaledDepthBias_))
  1226. {
  1227. if ((constantBias != 0.0f) || (slopeScaledBias != 0.0f))
  1228. {
  1229. // Bring the constant bias from Direct3D9 scale to OpenGL (depends on depth buffer bitdepth)
  1230. // Zero depth bits may be returned if using the packed depth stencil format. Assume 24bit in that case
  1231. int depthBits = min(impl_->depthBits_, 23);
  1232. if (!depthBits)
  1233. depthBits = 23;
  1234. float adjustedConstantBias = constantBias * (float)(1 << (depthBits - 1));
  1235. float adjustedSlopeScaledBias = slopeScaledBias + 1.0f;
  1236. glEnable(GL_POLYGON_OFFSET_FILL);
  1237. glEnable(GL_POLYGON_OFFSET_LINE);
  1238. glPolygonOffset(adjustedSlopeScaledBias, adjustedConstantBias);
  1239. }
  1240. else
  1241. {
  1242. glDisable(GL_POLYGON_OFFSET_FILL);
  1243. glDisable(GL_POLYGON_OFFSET_LINE);
  1244. }
  1245. constantDepthBias_ = constantBias;
  1246. slopeScaledDepthBias_ = slopeScaledBias;
  1247. }
  1248. }
  1249. void Graphics::SetDepthTest(CompareMode mode)
  1250. {
  1251. if (mode != depthTestMode_)
  1252. {
  1253. glDepthFunc(glCmpFunc[mode]);
  1254. depthTestMode_ = mode;
  1255. }
  1256. }
  1257. void Graphics::SetDepthWrite(bool enable)
  1258. {
  1259. if (enable != depthWrite_)
  1260. {
  1261. glDepthMask(enable ? GL_TRUE : GL_FALSE);
  1262. depthWrite_ = enable;
  1263. }
  1264. }
  1265. void Graphics::SetFillMode(FillMode mode)
  1266. {
  1267. if (mode != fillMode_)
  1268. {
  1269. glPolygonMode(GL_FRONT_AND_BACK, mode == FILL_SOLID ? GL_FILL : GL_LINE);
  1270. fillMode_ = mode;
  1271. }
  1272. }
  1273. void Graphics::SetScissorTest(bool enable, const Rect& rect, bool borderInclusive)
  1274. {
  1275. // During some light rendering loops, a full rect is toggled on/off repeatedly.
  1276. // Disable scissor in that case to reduce state changes
  1277. if ((rect.min_.x_ <= 0.0f) && (rect.min_.y_ <= 0.0f) && (rect.max_.y_ >= 1.0f) && (rect.max_.y_ >= 1.0f))
  1278. enable = false;
  1279. // Check for illegal rect, disable in that case
  1280. if ((rect.max_.x_ < rect.min_.x_) || (rect.max_.y_ < rect.min_.y_))
  1281. enable = false;
  1282. if (enable)
  1283. {
  1284. IntVector2 rtSize(GetRenderTargetDimensions());
  1285. IntVector2 viewSize(viewport_.right_ - viewport_.left_, viewport_.bottom_ - viewport_.top_);
  1286. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1287. IntRect intRect;
  1288. int expand = borderInclusive ? 1 : 0;
  1289. intRect.left_ = Clamp((int)((rect.min_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_, 0, rtSize.x_ - 1);
  1290. intRect.top_ = Clamp((int)((-rect.max_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_, 0, rtSize.y_ - 1);
  1291. intRect.right_ = Clamp((int)((rect.max_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_ + expand, 0, rtSize.x_);
  1292. intRect.bottom_ = Clamp((int)((-rect.min_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_ + expand, 0, rtSize.y_);
  1293. if (intRect.right_ == intRect.left_)
  1294. intRect.right_++;
  1295. if (intRect.bottom_ == intRect.top_)
  1296. intRect.bottom_++;
  1297. if ((intRect.right_ < intRect.left_) || (intRect.bottom_ < intRect.top_))
  1298. enable = false;
  1299. if ((enable) && (scissorRect_ != intRect))
  1300. {
  1301. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1302. glScissor(intRect.left_, rtSize.y_ - intRect.bottom_, intRect.right_ - intRect.left_, intRect.bottom_ - intRect.top_);
  1303. scissorRect_ = intRect;
  1304. }
  1305. }
  1306. else
  1307. scissorRect_ = IntRect::ZERO;
  1308. if (enable != scissorTest_)
  1309. {
  1310. if (enable)
  1311. glEnable(GL_SCISSOR_TEST);
  1312. else
  1313. glDisable(GL_SCISSOR_TEST);
  1314. scissorTest_ = enable;
  1315. }
  1316. }
  1317. void Graphics::SetScissorTest(bool enable, const IntRect& rect)
  1318. {
  1319. IntVector2 rtSize(GetRenderTargetDimensions());
  1320. IntVector2 viewSize(viewport_.right_ - viewport_.left_, viewport_.bottom_ - viewport_.top_);
  1321. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1322. // Full scissor is same as disabling the test
  1323. if ((rect.left_ <= 0) && (rect.right_ >= viewSize.x_) && (rect.top_ <= 0) && (rect.bottom_ >= viewSize.y_))
  1324. enable = false;
  1325. // Check for illegal rect, disable in that case
  1326. if ((rect.right_ < rect.left_) || (rect.bottom_ < rect.top_))
  1327. enable = false;
  1328. if (enable)
  1329. {
  1330. IntRect intRect;
  1331. intRect.left_ = Clamp(rect.left_ + viewPos.x_, 0, rtSize.x_ - 1);
  1332. intRect.top_ = Clamp(rect.top_ + viewPos.y_, 0, rtSize.y_ - 1);
  1333. intRect.right_ = Clamp(rect.right_ + viewPos.x_, 0, rtSize.x_);
  1334. intRect.bottom_ = Clamp(rect.bottom_ + viewPos.y_, 0, rtSize.y_);
  1335. if (intRect.right_ == intRect.left_)
  1336. intRect.right_++;
  1337. if (intRect.bottom_ == intRect.top_)
  1338. intRect.bottom_++;
  1339. if ((intRect.right_ < intRect.left_) || (intRect.bottom_ < intRect.top_))
  1340. enable = false;
  1341. if ((enable) && (scissorRect_ != intRect))
  1342. {
  1343. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1344. glScissor(intRect.left_, rtSize.y_ - intRect.bottom_, intRect.right_ - intRect.left_, intRect.bottom_ - intRect.top_);
  1345. scissorRect_ = intRect;
  1346. }
  1347. }
  1348. else
  1349. scissorRect_ = IntRect::ZERO;
  1350. if (enable != scissorTest_)
  1351. {
  1352. if (enable)
  1353. glEnable(GL_SCISSOR_TEST);
  1354. else
  1355. glDisable(GL_SCISSOR_TEST);
  1356. scissorTest_ = enable;
  1357. }
  1358. }
  1359. void Graphics::SetStreamFrequency(unsigned index, unsigned frequency)
  1360. {
  1361. }
  1362. void Graphics::ResetStreamFrequencies()
  1363. {
  1364. }
  1365. void Graphics::SetStencilTest(bool enable, CompareMode mode, StencilOp pass, StencilOp fail, StencilOp zFail, unsigned stencilRef, unsigned stencilMask)
  1366. {
  1367. if (enable != stencilTest_)
  1368. {
  1369. if (enable)
  1370. glEnable(GL_STENCIL_TEST);
  1371. else
  1372. glDisable(GL_STENCIL_TEST);
  1373. stencilTest_ = enable;
  1374. }
  1375. if (enable)
  1376. {
  1377. if ((mode != stencilTestMode_) || (stencilRef != stencilRef_) || (stencilMask != stencilMask_))
  1378. {
  1379. glStencilFunc(glCmpFunc[mode], stencilRef, stencilMask);
  1380. stencilTestMode_ = mode;
  1381. stencilRef_ = stencilRef;
  1382. stencilMask_ = stencilMask;
  1383. }
  1384. if ((pass != stencilPass_) || (fail != stencilFail_) || (!zFail != stencilZFail_))
  1385. {
  1386. glStencilOp(glStencilOps[fail], glStencilOps[zFail], glStencilOps[pass]);
  1387. stencilPass_ = pass;
  1388. stencilFail_ = fail;
  1389. stencilZFail_ = zFail;
  1390. }
  1391. }
  1392. }
  1393. bool Graphics::BeginImmediate(PrimitiveType type, unsigned vertexCount, unsigned elementMask)
  1394. {
  1395. if (immediateBuffer_)
  1396. {
  1397. LOGERROR("New immediate draw operation started before ending the last one");
  1398. return false;
  1399. }
  1400. if (!(elementMask & MASK_POSITION))
  1401. {
  1402. LOGERROR("Immediate draw operation must contain vertex positions");
  1403. return false;
  1404. }
  1405. if (!vertexCount)
  1406. return true;
  1407. // Start from default size, ensure that buffer is big enough to hold the immediate draw operation
  1408. unsigned newSize = IMMEDIATE_BUFFER_DEFAULT_SIZE;
  1409. while (newSize < vertexCount)
  1410. newSize <<= 1;
  1411. // See if buffer exists for this vertex format. If not, create new
  1412. if (immediateVertexBuffers_.Find(elementMask) == immediateVertexBuffers_.End())
  1413. {
  1414. LOGDEBUG("Created immediate vertex buffer");
  1415. VertexBuffer* newBuffer = new VertexBuffer(context_);
  1416. newBuffer->SetSize(newSize, elementMask, true);
  1417. immediateVertexBuffers_[elementMask] = newBuffer;
  1418. immediateVertexBufferPos_[elementMask] = 0;
  1419. }
  1420. // Resize buffer if it is too small
  1421. VertexBuffer* buffer = immediateVertexBuffers_[elementMask];
  1422. if (buffer->GetVertexCount() < newSize)
  1423. {
  1424. LOGDEBUG("Resized immediate vertex buffer to " + String(newSize));
  1425. buffer->SetSize(newSize, elementMask);
  1426. immediateVertexBufferPos_[elementMask] = 0;
  1427. }
  1428. // Get the current lock position for the buffer
  1429. unsigned bufferPos = immediateVertexBufferPos_[elementMask];
  1430. if (bufferPos + vertexCount >= buffer->GetVertexCount())
  1431. bufferPos = 0;
  1432. LockMode lockMode = LOCK_DISCARD;
  1433. if (bufferPos != 0)
  1434. lockMode = LOCK_NOOVERWRITE;
  1435. // Note: the data pointer gets pre-decremented here, because the first call to DefineVertex() will increment it
  1436. immediateDataPtr_ = ((unsigned char*)buffer->Lock(bufferPos, vertexCount, lockMode)) - buffer->GetVertexSize();
  1437. immediateBuffer_ = buffer;
  1438. immediateType_= type;
  1439. immediateStartPos_ = bufferPos;
  1440. immediateVertexCount_ = vertexCount;
  1441. immediateCurrentVertex_ = 0;
  1442. // Store new buffer position for next lock into the same buffer
  1443. bufferPos += vertexCount;
  1444. if (bufferPos >= buffer->GetVertexCount())
  1445. bufferPos = 0;
  1446. immediateVertexBufferPos_[elementMask] = bufferPos;
  1447. return true;
  1448. }
  1449. bool Graphics::DefineVertex(const Vector3& vertex)
  1450. {
  1451. if ((!immediateBuffer_) || (immediateCurrentVertex_ >= immediateVertexCount_))
  1452. return false;
  1453. immediateDataPtr_ += immediateBuffer_->GetVertexSize();
  1454. ++immediateCurrentVertex_;
  1455. float* dest = (float*)(immediateDataPtr_ + immediateBuffer_->GetElementOffset(ELEMENT_POSITION));
  1456. const float* src = vertex.GetData();
  1457. dest[0] = src[0];
  1458. dest[1] = src[1];
  1459. dest[2] = src[2];
  1460. return true;
  1461. }
  1462. bool Graphics::DefineNormal(const Vector3& normal)
  1463. {
  1464. if ((!immediateBuffer_) ||(!(immediateBuffer_->GetElementMask() & MASK_NORMAL)) || (!immediateCurrentVertex_))
  1465. return false;
  1466. float* dest = (float*)(immediateDataPtr_ + immediateBuffer_->GetElementOffset(ELEMENT_NORMAL));
  1467. const float* src = normal.GetData();
  1468. dest[0] = src[0];
  1469. dest[1] = src[1];
  1470. dest[2] = src[2];
  1471. return true;
  1472. }
  1473. bool Graphics::DefineTexCoord(const Vector2& texCoord)
  1474. {
  1475. if ((!immediateBuffer_) || (!(immediateBuffer_->GetElementMask() & MASK_TEXCOORD1)) || (!immediateCurrentVertex_))
  1476. return false;
  1477. float* dest = (float*)(immediateDataPtr_ + immediateBuffer_->GetElementOffset(ELEMENT_TEXCOORD1));
  1478. const float* src = texCoord.GetData();
  1479. dest[0] = src[0];
  1480. dest[1] = src[1];
  1481. return true;
  1482. }
  1483. bool Graphics::DefineColor(const Color& color)
  1484. {
  1485. if ((!immediateBuffer_) || (!(immediateBuffer_->GetElementMask() & MASK_COLOR)) || (!immediateCurrentVertex_))
  1486. return false;
  1487. unsigned* dest = (unsigned*)(immediateDataPtr_ + immediateBuffer_->GetElementOffset(ELEMENT_COLOR));
  1488. *dest = color.ToUInt();
  1489. return true;
  1490. }
  1491. bool Graphics::DefineColor(unsigned color)
  1492. {
  1493. if ((!immediateBuffer_) || (!(immediateBuffer_->GetElementMask() & MASK_COLOR)) || (!immediateCurrentVertex_))
  1494. return false;
  1495. unsigned* dest = (unsigned*)(immediateDataPtr_ + immediateBuffer_->GetElementOffset(ELEMENT_COLOR));
  1496. *dest = color;
  1497. return true;
  1498. }
  1499. void Graphics::EndImmediate()
  1500. {
  1501. if (immediateBuffer_)
  1502. {
  1503. immediateBuffer_->Unlock();
  1504. SetVertexBuffer(immediateBuffer_);
  1505. Draw(immediateType_, immediateStartPos_, immediateVertexCount_);
  1506. immediateBuffer_ = 0;
  1507. }
  1508. }
  1509. void Graphics::SetForceSM2(bool enable)
  1510. {
  1511. }
  1512. unsigned char* Graphics::GetImmediateDataPtr() const
  1513. {
  1514. if (!immediateBuffer_)
  1515. {
  1516. LOGERROR("Immediate draw operation not started");
  1517. return 0;
  1518. }
  1519. // Pointer was pre-decremented in BeginImmediate(). Undo that now
  1520. return immediateDataPtr_ + immediateBuffer_->GetVertexSize();
  1521. }
  1522. PODVector<IntVector2> Graphics::GetResolutions() const
  1523. {
  1524. PODVector<IntVector2> ret;
  1525. return ret;
  1526. }
  1527. PODVector<int> Graphics::GetMultiSampleLevels() const
  1528. {
  1529. PODVector<int> ret;
  1530. // No multisampling always supported
  1531. ret.Push(0);
  1532. return ret;
  1533. }
  1534. VertexBuffer* Graphics::GetVertexBuffer(unsigned index) const
  1535. {
  1536. return index < MAX_VERTEX_STREAMS ? vertexBuffers_[index] : 0;
  1537. }
  1538. ShaderParameter Graphics::GetShaderParameter(const String& name)
  1539. {
  1540. Map<String, ShaderParameter>::Iterator i = shaderParameters_.Find(name);
  1541. if (i != shaderParameters_.End())
  1542. return i->second_;
  1543. else
  1544. return MAX_SHADER_PARAMETERS;
  1545. }
  1546. TextureUnit Graphics::GetTextureUnit(const String& name)
  1547. {
  1548. Map<String, TextureUnit>::Iterator i = textureUnits_.Find(name);
  1549. if (i != textureUnits_.End())
  1550. return i->second_;
  1551. else
  1552. return MAX_TEXTURE_UNITS;
  1553. }
  1554. const String& Graphics::GetShaderParameterName(ShaderParameter parameter)
  1555. {
  1556. for (Map<String, ShaderParameter>::Iterator i = shaderParameters_.Begin(); i != shaderParameters_.End(); ++i)
  1557. {
  1558. if (i->second_ == parameter)
  1559. return i->first_;
  1560. }
  1561. return noParameter;
  1562. }
  1563. const String& Graphics::GetTextureUnitName(TextureUnit unit)
  1564. {
  1565. for (Map<String, TextureUnit>::Iterator i = textureUnits_.Begin(); i != textureUnits_.End(); ++i)
  1566. {
  1567. if (i->second_ == unit)
  1568. return i->first_;
  1569. }
  1570. return noParameter;
  1571. }
  1572. Texture* Graphics::GetTexture(unsigned index) const
  1573. {
  1574. return index < MAX_TEXTURE_UNITS ? textures_[index] : 0;
  1575. }
  1576. RenderSurface* Graphics::GetRenderTarget(unsigned index) const
  1577. {
  1578. return index < MAX_RENDERTARGETS ? renderTargets_[index] : 0;
  1579. }
  1580. IntVector2 Graphics::GetRenderTargetDimensions() const
  1581. {
  1582. int width, height;
  1583. if (renderTargets_[0])
  1584. {
  1585. width = renderTargets_[0]->GetWidth();
  1586. height = renderTargets_[0]->GetHeight();
  1587. }
  1588. else if (depthStencil_)
  1589. {
  1590. width = depthStencil_->GetWidth();
  1591. height = depthStencil_->GetHeight();
  1592. }
  1593. else
  1594. {
  1595. width = width_;
  1596. height = height_;
  1597. }
  1598. return IntVector2(width, height);
  1599. }
  1600. void Graphics::AddGPUObject(GPUObject* object)
  1601. {
  1602. gpuObjects_.Push(object);
  1603. }
  1604. void Graphics::RemoveGPUObject(GPUObject* object)
  1605. {
  1606. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1607. {
  1608. if ((*i) == object)
  1609. {
  1610. gpuObjects_.Erase(i);
  1611. return;
  1612. }
  1613. }
  1614. }
  1615. unsigned Graphics::GetAlphaFormat()
  1616. {
  1617. return GL_ALPHA;
  1618. }
  1619. unsigned Graphics::GetLuminanceFormat()
  1620. {
  1621. return GL_LUMINANCE;
  1622. }
  1623. unsigned Graphics::GetLuminanceAlphaFormat()
  1624. {
  1625. return GL_LUMINANCE_ALPHA;
  1626. }
  1627. unsigned Graphics::GetRGBFormat()
  1628. {
  1629. return GL_RGB;
  1630. }
  1631. unsigned Graphics::GetRGBAFormat()
  1632. {
  1633. return GL_RGBA;
  1634. }
  1635. unsigned Graphics::GetDepthFormat()
  1636. {
  1637. // Note: this requires GLee static initialization to have completed to return the proper result
  1638. if (_GLEE_EXT_packed_depth_stencil)
  1639. return GL_DEPTH24_STENCIL8_EXT;
  1640. else
  1641. return GL_DEPTH_COMPONENT24;
  1642. }
  1643. bool Graphics::IsInitialized() const
  1644. {
  1645. return ((impl_->window_ != 0) && (impl_->renderContext_ != 0));
  1646. }
  1647. unsigned Graphics::GetWindowHandle() const
  1648. {
  1649. return (unsigned)impl_->window_;
  1650. }
  1651. bool Graphics::GetRenderTextureSupport() const
  1652. {
  1653. return impl_->fbo_ != 0;
  1654. }
  1655. bool Graphics::OpenWindow(int width, int height)
  1656. {
  1657. WNDCLASS wc;
  1658. wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
  1659. wc.lpfnWndProc = wndProc;
  1660. wc.cbClsExtra = 0;
  1661. wc.cbWndExtra = 0;
  1662. wc.hInstance = impl_->instance_;
  1663. wc.hIcon = LoadIcon(0, IDI_APPLICATION);
  1664. wc.hCursor = LoadCursor(0, IDC_ARROW);
  1665. wc.hbrBackground = 0;
  1666. wc.lpszMenuName = 0;
  1667. wc.lpszClassName = "OpenGL";
  1668. RegisterClass(&wc);
  1669. RECT rect = {0, 0, width, height};
  1670. AdjustWindowRect(&rect, windowStyle, false);
  1671. impl_->window_ = CreateWindow("OpenGL", windowTitle_.CString(), windowStyle, CW_USEDEFAULT, CW_USEDEFAULT,
  1672. rect.right, rect.bottom, 0, 0, impl_->instance_, 0);
  1673. if (!impl_->window_)
  1674. {
  1675. LOGERROR("Could not create window");
  1676. return false;
  1677. }
  1678. SetWindowLongPtr(impl_->window_, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(this));
  1679. // Save window placement
  1680. WINDOWPLACEMENT wndpl;
  1681. wndpl.length = sizeof wndpl;
  1682. if (SUCCEEDED(GetWindowPlacement(impl_->window_, &wndpl)))
  1683. {
  1684. windowPosX_ = wndpl.rcNormalPosition.left;
  1685. windowPosY_ = wndpl.rcNormalPosition.top;
  1686. }
  1687. // Save the device context, then set the pixel format
  1688. impl_->deviceContext_ = GetDC(impl_->window_);
  1689. PIXELFORMATDESCRIPTOR pfd;
  1690. ZeroMemory(&pfd, sizeof(pfd));
  1691. pfd.nSize = sizeof(pfd);
  1692. pfd.nVersion = 1;
  1693. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_GENERIC_ACCELERATED | PFD_DOUBLEBUFFER;
  1694. pfd.iPixelType = PFD_TYPE_RGBA;
  1695. pfd.cColorBits = 24;
  1696. pfd.cDepthBits = 24;
  1697. pfd.cStencilBits = 8;
  1698. int iFormat = ChoosePixelFormat(impl_->deviceContext_, &pfd);
  1699. if (!iFormat)
  1700. {
  1701. LOGERROR("Failed to choose pixel format");
  1702. return false;
  1703. }
  1704. if (SetPixelFormat(impl_->deviceContext_, iFormat, &pfd) == FALSE)
  1705. {
  1706. LOGERROR("Failed to set pixel format");
  1707. return false;
  1708. }
  1709. LOGINFO("Created application window");
  1710. return true;
  1711. }
  1712. bool Graphics::SetScreenMode(int newWidth, int newHeight)
  1713. {
  1714. inModeChange_ = true;
  1715. bool success = true;
  1716. IntVector2 desktopResolution = impl_->GetDesktopResolution();
  1717. unsigned bitsPerPixel = impl_->GetDesktopBitsPerPixel();
  1718. // Switch resolution only if necessary
  1719. if ((desktopResolution.x_ != newWidth) || (desktopResolution.y_ != newHeight) || (bitsPerPixel != 32))
  1720. {
  1721. DEVMODE dmScreenSettings;
  1722. ZeroMemory(&dmScreenSettings, sizeof(dmScreenSettings));
  1723. dmScreenSettings.dmSize = sizeof(dmScreenSettings);
  1724. dmScreenSettings.dmPelsWidth = newWidth;
  1725. dmScreenSettings.dmPelsHeight = newHeight;
  1726. dmScreenSettings.dmBitsPerPel = 32;
  1727. dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
  1728. success = ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN) == DISP_CHANGE_SUCCESSFUL;
  1729. if (success)
  1730. fullscreenModeSet_ = true;
  1731. }
  1732. else
  1733. fullscreenModeSet_ = true;
  1734. inModeChange_ = false;
  1735. return success;
  1736. }
  1737. void Graphics::RestoreScreenMode()
  1738. {
  1739. if (fullscreenModeSet_)
  1740. {
  1741. inModeChange_ = true;
  1742. ChangeDisplaySettings(NULL, 0);
  1743. fullscreenModeSet_ = false;
  1744. inModeChange_ = false;
  1745. }
  1746. }
  1747. void Graphics::AdjustWindow(int newWidth, int newHeight, bool newFullscreen)
  1748. {
  1749. inModeChange_ = true;
  1750. if (newFullscreen)
  1751. {
  1752. SetWindowLongPtr(impl_->window_, GWL_STYLE, WS_POPUP);
  1753. SetWindowPos(impl_->window_, HWND_TOP, 0, 0, newWidth, newHeight, SWP_NOZORDER | SWP_SHOWWINDOW);
  1754. }
  1755. else
  1756. {
  1757. RECT rect = {0, 0, newWidth, newHeight};
  1758. AdjustWindowRect(&rect, windowStyle, false);
  1759. SetWindowLongPtr(impl_->window_, GWL_STYLE, windowStyle);
  1760. SetWindowPos(impl_->window_, HWND_TOP, windowPosX_, windowPosY_, rect.right - rect.left, rect.bottom - rect.top,
  1761. SWP_NOZORDER | SWP_SHOWWINDOW);
  1762. // Clean up the desktop of the old window contents
  1763. InvalidateRect(0, 0, true);
  1764. }
  1765. inModeChange_ = false;
  1766. }
  1767. void Graphics::CreateRenderTargets()
  1768. {
  1769. if (mode_ != RENDER_FORWARD)
  1770. {
  1771. // In deferred rendering, the diffuse buffer stores diffuse albedo. In light prepass, it is used for light accumulation
  1772. if (!diffBuffer_)
  1773. {
  1774. diffBuffer_ = new Texture2D(context_);
  1775. diffBuffer_->SetSize(0, 0, GetRGBAFormat(), TEXTURE_RENDERTARGET);
  1776. }
  1777. if (!normalBuffer_)
  1778. {
  1779. normalBuffer_ = new Texture2D(context_);
  1780. normalBuffer_->SetSize(0, 0, GetRGBAFormat(), TEXTURE_RENDERTARGET);
  1781. }
  1782. if (!depthBuffer_)
  1783. {
  1784. depthBuffer_ = new Texture2D(context_);
  1785. depthBuffer_->SetSize(0, 0, GetDepthFormat(), TEXTURE_DEPTHSTENCIL);
  1786. }
  1787. // If deferred mode temporal AA is used, reserve screen buffers
  1788. // (later we will probably want the screen buffer reserved in any case, to do for example distortion effects,
  1789. // which will also be useful in forward rendering)
  1790. if (multiSample_)
  1791. {
  1792. for (unsigned i = 0; i < NUM_SCREEN_BUFFERS; ++i)
  1793. {
  1794. screenBuffers_[i] = new Texture2D(context_);
  1795. screenBuffers_[i]->SetSize(0, 0, GetRGBAFormat(), TEXTURE_RENDERTARGET);
  1796. }
  1797. }
  1798. else
  1799. {
  1800. for (unsigned i = 0; i < NUM_SCREEN_BUFFERS; ++i)
  1801. screenBuffers_[i].Reset();
  1802. }
  1803. }
  1804. else
  1805. {
  1806. diffBuffer_.Reset();
  1807. normalBuffer_.Reset();
  1808. depthBuffer_.Reset();
  1809. for (unsigned i = 0; i < NUM_SCREEN_BUFFERS; ++i)
  1810. screenBuffers_[i].Reset();
  1811. }
  1812. }
  1813. void Graphics::ResetCachedState()
  1814. {
  1815. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  1816. {
  1817. vertexBuffers_[i] = 0;
  1818. elementMasks_[i] = 0;
  1819. }
  1820. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1821. {
  1822. textures_[i] = 0;
  1823. textureTypes_[i] = 0;
  1824. }
  1825. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1826. renderTargets_[i] = 0;
  1827. depthStencil_ = 0;
  1828. viewport_ = IntRect(0, 0, 0, 0);
  1829. viewTexture_ = 0;
  1830. indexBuffer_ = 0;
  1831. vertexShader_ = 0;
  1832. pixelShader_ = 0;
  1833. shaderProgram_ = 0;
  1834. blendMode_ = BLEND_REPLACE;
  1835. alphaTest_ = false;
  1836. alphaTestMode_ = CMP_ALWAYS;
  1837. alphaRef_ = 0.0f;
  1838. textureAnisotropy_ = 1;
  1839. colorWrite_ = true;
  1840. cullMode_ = CULL_NONE;
  1841. constantDepthBias_ = 0.0f;
  1842. slopeScaledDepthBias_ = 0.0f;
  1843. depthTestMode_ = CMP_ALWAYS;
  1844. depthWrite_ = true;
  1845. fillMode_ = FILL_SOLID;
  1846. scissorTest_ = false;
  1847. scissorRect_ = IntRect::ZERO;
  1848. stencilTest_ = false;
  1849. stencilTestMode_ = CMP_ALWAYS;
  1850. stencilPass_ = OP_KEEP;
  1851. stencilFail_ = OP_KEEP;
  1852. stencilZFail_ = OP_KEEP;
  1853. stencilRef_ = 0;
  1854. stencilMask_ = M_MAX_UNSIGNED;
  1855. }
  1856. void Graphics::SetDrawBuffers()
  1857. {
  1858. // Calculate the bit combination of non-zero color rendertargets to first check if the combination changed
  1859. unsigned newDrawBuffers = 0;
  1860. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1861. {
  1862. if (renderTargets_[i])
  1863. newDrawBuffers |= 1 << i;
  1864. }
  1865. if (newDrawBuffers == impl_->drawBuffers_)
  1866. return;
  1867. // Check for no color rendertargets (depth rendering only)
  1868. if (!newDrawBuffers)
  1869. glDrawBuffer(GL_NONE);
  1870. else
  1871. {
  1872. int drawBufferIds[4];
  1873. unsigned drawBufferCount = 0;
  1874. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1875. {
  1876. if (renderTargets_[i])
  1877. drawBufferIds[drawBufferCount++] = GL_COLOR_ATTACHMENT0_EXT + i;
  1878. }
  1879. glDrawBuffers(drawBufferCount, (const GLenum*)drawBufferIds);
  1880. }
  1881. glReadBuffer(GL_NONE);
  1882. }
  1883. void Graphics::InitializeShaderParameters()
  1884. {
  1885. // Map parameter names
  1886. shaderParameters_["CameraPos"] = VSP_CAMERAPOS;
  1887. shaderParameters_["CameraRot"] = VSP_CAMERAROT;
  1888. shaderParameters_["DepthMode"] = VSP_DEPTHMODE;
  1889. shaderParameters_["ElapsedTime"] = VSP_ELAPSEDTIME;
  1890. shaderParameters_["FrustumSize"] = VSP_FRUSTUMSIZE;
  1891. shaderParameters_["GBufferOffsets"] = VSP_GBUFFEROFFSETS;
  1892. shaderParameters_["Model"] = VSP_MODEL;
  1893. shaderParameters_["ShadowProj"] = VSP_SHADOWPROJ;
  1894. shaderParameters_["SpotProj"] = VSP_SPOTPROJ;
  1895. shaderParameters_["ViewProj"] = VSP_VIEWPROJ;
  1896. shaderParameters_["UOffset"] = VSP_UOFFSET;
  1897. shaderParameters_["VOffset"] = VSP_VOFFSET;
  1898. shaderParameters_["ViewRightVector"] = VSP_VIEWRIGHTVECTOR;
  1899. shaderParameters_["ViewUpVector"] = VSP_VIEWUPVECTOR;
  1900. shaderParameters_["SkinMatrices"] = VSP_SKINMATRICES;
  1901. shaderParameters_["AmbientColor"] = PSP_AMBIENTCOLOR;
  1902. shaderParameters_["AntiAliasWeights"] = PSP_ANTIALIASWEIGHTS;
  1903. shaderParameters_["CameraPosPS"] = PSP_CAMERAPOS;
  1904. shaderParameters_["DepthReconstruct"] = PSP_DEPTHRECONSTRUCT;
  1905. shaderParameters_["ElapsedTimePS"] = PSP_ELAPSEDTIME;
  1906. shaderParameters_["FogColor"] = PSP_FOGCOLOR;
  1907. shaderParameters_["FogParams"] = PSP_FOGPARAMS;
  1908. shaderParameters_["GBufferOffsetsPS"] = PSP_GBUFFEROFFSETS;
  1909. shaderParameters_["GBufferViewport"] = PSP_GBUFFERVIEWPORT;
  1910. shaderParameters_["LightAtten"] = PSP_LIGHTATTEN;
  1911. shaderParameters_["LightColor"] = PSP_LIGHTCOLOR;
  1912. shaderParameters_["LightDir"] = PSP_LIGHTDIR;
  1913. shaderParameters_["LightPos"] = PSP_LIGHTPOS;
  1914. shaderParameters_["LightSplits"] = PSP_LIGHTSPLITS;
  1915. shaderParameters_["LightVecRot"] = PSP_LIGHTVECROT;
  1916. shaderParameters_["MatDiffColor"] = PSP_MATDIFFCOLOR;
  1917. shaderParameters_["MatEmissiveColor"] = PSP_MATEMISSIVECOLOR;
  1918. shaderParameters_["MatSpecProperties"] = PSP_MATSPECPROPERTIES;
  1919. shaderParameters_["SampleOffsets"] = PSP_SAMPLEOFFSETS;
  1920. shaderParameters_["ShadowIntensity"] = PSP_SHADOWINTENSITY;
  1921. shaderParameters_["ShadowProjPS"] = PSP_SHADOWPROJ;
  1922. shaderParameters_["SpotProjPS"] = PSP_SPOTPROJ;
  1923. shaderParameters_["ViewProjPS"] = PSP_VIEWPROJ;
  1924. // Map texture units
  1925. textureUnits_["NormalMap"] = TU_NORMAL;
  1926. textureUnits_["DiffMap"] = TU_DIFFUSE;
  1927. textureUnits_["DiffCubeMap"] = TU_DIFFUSE;
  1928. textureUnits_["SpecMap"] = TU_SPECULAR;
  1929. textureUnits_["EmissiveMap"] = TU_EMISSIVE;
  1930. textureUnits_["DetailMap"] = TU_DETAIL;
  1931. textureUnits_["EnvironmentMap"] = TU_ENVIRONMENT;
  1932. textureUnits_["EnvironmentCubeMap"] = TU_ENVIRONMENT;
  1933. textureUnits_["LightRampMap"] = TU_LIGHTRAMP;
  1934. textureUnits_["LightSpotMap"] = TU_LIGHTSPOT;
  1935. textureUnits_["LightCubeMap"] = TU_LIGHTSPOT;
  1936. textureUnits_["ShadowMap"] = TU_SHADOWMAP;
  1937. textureUnits_["DiffBuffer"] = TU_DIFFBUFFER;
  1938. textureUnits_["NormalBuffer"] = TU_NORMALBUFFER;
  1939. textureUnits_["DepthBuffer"] = TU_DEPTHBUFFER;
  1940. textureUnits_["LightBuffer"] = TU_LIGHTBUFFER;
  1941. }
  1942. void Graphics::HandleWindowMessage(StringHash eventType, VariantMap& eventData)
  1943. {
  1944. using namespace WindowMessage;
  1945. if (eventData[P_WINDOW].GetInt() != (int)impl_->window_)
  1946. return;
  1947. switch (eventData[P_MSG].GetInt())
  1948. {
  1949. case WM_CLOSE:
  1950. Close();
  1951. eventData[P_HANDLED] = true;
  1952. break;
  1953. case WM_DESTROY:
  1954. eventData[P_HANDLED] = true;
  1955. break;
  1956. }
  1957. }
  1958. void Graphics::HandleActivation(StringHash eventType, VariantMap& eventData)
  1959. {
  1960. if ((inModeChange_) || (!impl_->window_) || (!fullscreen_))
  1961. return;
  1962. using namespace Activation;
  1963. if (eventData[P_ACTIVE].GetBool())
  1964. {
  1965. // If we were activated and are not minimized, change back to the custom mode
  1966. if ((!eventData[P_MINIMIZED].GetBool()) && (!fullscreenModeSet_))
  1967. {
  1968. if (!SetScreenMode(width_, height_))
  1969. fullscreen_ = false;
  1970. AdjustWindow(width_, height_, fullscreen_);
  1971. }
  1972. }
  1973. else
  1974. {
  1975. // Reset to desktop resolution on inactivation
  1976. inModeChange_ = true;
  1977. ShowWindow(impl_->window_, SW_MINIMIZE);
  1978. inModeChange_ = false;
  1979. RestoreScreenMode();
  1980. }
  1981. }
  1982. LRESULT CALLBACK wndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  1983. {
  1984. using namespace WindowMessage;
  1985. Graphics* graphics = reinterpret_cast<Graphics*>(GetWindowLongPtr(hwnd, GWLP_USERDATA));
  1986. if ((graphics) && (graphics->IsInitialized()))
  1987. {
  1988. VariantMap eventData;
  1989. eventData[P_WINDOW] = (int)hwnd;
  1990. eventData[P_MSG] = (int)msg;
  1991. eventData[P_WPARAM] = (int)wParam;
  1992. eventData[P_LPARAM] = (int)lParam;
  1993. eventData[P_HANDLED] = false;
  1994. graphics->SendEvent(E_WINDOWMESSAGE, eventData);
  1995. if (eventData[P_HANDLED].GetBool())
  1996. return 0;
  1997. }
  1998. return DefWindowProc(hwnd, msg, wParam, lParam);
  1999. }
  2000. void RegisterGraphicsLibrary(Context* context)
  2001. {
  2002. Animation::RegisterObject(context);
  2003. Material::RegisterObject(context);
  2004. Model::RegisterObject(context);
  2005. Shader::RegisterObject(context);
  2006. Technique::RegisterObject(context);
  2007. Texture2D::RegisterObject(context);
  2008. TextureCube::RegisterObject(context);
  2009. Camera::RegisterObject(context);
  2010. Drawable::RegisterObject(context);
  2011. Light::RegisterObject(context);
  2012. StaticModel::RegisterObject(context);
  2013. Skybox::RegisterObject(context);
  2014. AnimatedModel::RegisterObject(context);
  2015. AnimationController::RegisterObject(context);
  2016. BillboardSet::RegisterObject(context);
  2017. ParticleEmitter::RegisterObject(context);
  2018. DebugRenderer::RegisterObject(context);
  2019. Octree::RegisterObject(context);
  2020. Zone::RegisterObject(context);
  2021. }