OGLGraphics.cpp 67 KB

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