OGLGraphics.cpp 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../../Graphics/Camera.h"
  23. #include "../../Graphics/ConstantBuffer.h"
  24. #include "../../Core/Context.h"
  25. #include "../../Graphics/DebugRenderer.h"
  26. #include "../../IO/File.h"
  27. #include "../../Graphics/Graphics.h"
  28. #include "../../Graphics/GraphicsEvents.h"
  29. #include "../../Graphics/GraphicsImpl.h"
  30. #include "../../Graphics/IndexBuffer.h"
  31. #include "../../IO/Log.h"
  32. #include "../../Graphics/Material.h"
  33. #include "../../Core/Mutex.h"
  34. #include "../../Graphics/Octree.h"
  35. #include "../../Core/ProcessUtils.h"
  36. #include "../../Core/Profiler.h"
  37. #include "../../Graphics/RenderSurface.h"
  38. #include "../../Resource/ResourceCache.h"
  39. #include "../../Graphics/Shader.h"
  40. #include "../../Graphics/ShaderPrecache.h"
  41. #include "../../Graphics/ShaderProgram.h"
  42. #include "../../Graphics/ShaderVariation.h"
  43. #include "../../Graphics/Technique.h"
  44. #include "../../Graphics/Texture2D.h"
  45. #include "../../Graphics/Texture3D.h"
  46. #include "../../Graphics/TextureCube.h"
  47. #include "../../Graphics/VertexBuffer.h"
  48. #include "../../Graphics/Zone.h"
  49. #include <stdio.h>
  50. #include "../../DebugNew.h"
  51. #ifdef GL_ES_VERSION_2_0
  52. #define GL_DEPTH_COMPONENT24 GL_DEPTH_COMPONENT24_OES
  53. #define glClearDepth glClearDepthf
  54. #endif
  55. #ifdef WIN32
  56. // On Intel / NVIDIA setups prefer the NVIDIA GPU
  57. #include <windows.h>
  58. extern "C" {
  59. __declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
  60. }
  61. #endif
  62. namespace Atomic
  63. {
  64. static const unsigned glCmpFunc[] =
  65. {
  66. GL_ALWAYS,
  67. GL_EQUAL,
  68. GL_NOTEQUAL,
  69. GL_LESS,
  70. GL_LEQUAL,
  71. GL_GREATER,
  72. GL_GEQUAL
  73. };
  74. static const unsigned glSrcBlend[] =
  75. {
  76. GL_ONE,
  77. GL_ONE,
  78. GL_DST_COLOR,
  79. GL_SRC_ALPHA,
  80. GL_SRC_ALPHA,
  81. GL_ONE,
  82. GL_ONE_MINUS_DST_ALPHA,
  83. GL_ONE,
  84. GL_SRC_ALPHA
  85. };
  86. static const unsigned glDestBlend[] =
  87. {
  88. GL_ZERO,
  89. GL_ONE,
  90. GL_ZERO,
  91. GL_ONE_MINUS_SRC_ALPHA,
  92. GL_ONE,
  93. GL_ONE_MINUS_SRC_ALPHA,
  94. GL_DST_ALPHA,
  95. GL_ONE,
  96. GL_ONE
  97. };
  98. static const unsigned glBlendOp[] =
  99. {
  100. GL_FUNC_ADD,
  101. GL_FUNC_ADD,
  102. GL_FUNC_ADD,
  103. GL_FUNC_ADD,
  104. GL_FUNC_ADD,
  105. GL_FUNC_ADD,
  106. GL_FUNC_ADD,
  107. GL_FUNC_REVERSE_SUBTRACT,
  108. GL_FUNC_REVERSE_SUBTRACT
  109. };
  110. #ifndef GL_ES_VERSION_2_0
  111. static const unsigned glFillMode[] =
  112. {
  113. GL_FILL,
  114. GL_LINE,
  115. GL_POINT
  116. };
  117. static const unsigned glStencilOps[] =
  118. {
  119. GL_KEEP,
  120. GL_ZERO,
  121. GL_REPLACE,
  122. GL_INCR_WRAP,
  123. GL_DECR_WRAP
  124. };
  125. #endif
  126. // Remap vertex attributes on OpenGL so that all usually needed attributes including skinning fit to the first 8.
  127. // This avoids a skinning bug on GLES2 devices which only support 8.
  128. static const unsigned glVertexAttrIndex[] =
  129. {
  130. 0, 1, 2, 3, 4, 8, 9, 5, 6, 7, 10, 11, 12
  131. };
  132. #ifdef GL_ES_VERSION_2_0
  133. static unsigned glesDepthStencilFormat = GL_DEPTH_COMPONENT16;
  134. static unsigned glesReadableDepthFormat = GL_DEPTH_COMPONENT;
  135. #endif
  136. static String extensions;
  137. bool CheckExtension(const String& name)
  138. {
  139. if (extensions.Empty())
  140. extensions = (const char*)glGetString(GL_EXTENSIONS);
  141. return extensions.Contains(name);
  142. }
  143. static void GetGLPrimitiveType(unsigned elementCount, PrimitiveType type, unsigned& primitiveCount, GLenum& glPrimitiveType)
  144. {
  145. switch (type)
  146. {
  147. case TRIANGLE_LIST:
  148. primitiveCount = elementCount / 3;
  149. glPrimitiveType = GL_TRIANGLES;
  150. break;
  151. case LINE_LIST:
  152. primitiveCount = elementCount / 2;
  153. glPrimitiveType = GL_LINES;
  154. break;
  155. case POINT_LIST:
  156. primitiveCount = elementCount;
  157. glPrimitiveType = GL_POINTS;
  158. break;
  159. case TRIANGLE_STRIP:
  160. primitiveCount = elementCount - 2;
  161. glPrimitiveType = GL_TRIANGLE_STRIP;
  162. break;
  163. case LINE_STRIP:
  164. primitiveCount = elementCount - 1;
  165. glPrimitiveType = GL_LINE_STRIP;
  166. break;
  167. case TRIANGLE_FAN:
  168. primitiveCount = elementCount - 2;
  169. glPrimitiveType = GL_TRIANGLE_FAN;
  170. break;
  171. }
  172. }
  173. const Vector2 Graphics::pixelUVOffset(0.0f, 0.0f);
  174. bool Graphics::gl3Support = false;
  175. Graphics::Graphics(Context* context_) :
  176. Object(context_),
  177. impl_(new GraphicsImpl()),
  178. windowIcon_(0),
  179. externalWindow_(0),
  180. width_(0),
  181. height_(0),
  182. position_(SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED),
  183. multiSample_(1),
  184. fullscreen_(false),
  185. borderless_(false),
  186. resizable_(false),
  187. vsync_(false),
  188. tripleBuffer_(false),
  189. sRGB_(false),
  190. forceGL2_(false),
  191. instancingSupport_(false),
  192. lightPrepassSupport_(false),
  193. deferredSupport_(false),
  194. anisotropySupport_(false),
  195. dxtTextureSupport_(false),
  196. etcTextureSupport_(false),
  197. pvrtcTextureSupport_(false),
  198. sRGBSupport_(false),
  199. sRGBWriteSupport_(false),
  200. numPrimitives_(0),
  201. numBatches_(0),
  202. maxScratchBufferRequest_(0),
  203. dummyColorFormat_(0),
  204. shadowMapFormat_(GL_DEPTH_COMPONENT16),
  205. hiresShadowMapFormat_(GL_DEPTH_COMPONENT24),
  206. defaultTextureFilterMode_(FILTER_TRILINEAR),
  207. shaderPath_("Shaders/GLSL/"),
  208. shaderExtension_(".glsl"),
  209. orientations_("LandscapeLeft LandscapeRight"),
  210. #ifndef GL_ES_VERSION_2_0
  211. apiName_("GL2")
  212. #else
  213. apiName_("GLES2")
  214. #endif
  215. {
  216. SetTextureUnitMappings();
  217. ResetCachedState();
  218. // Initialize SDL now. Graphics should be the first SDL-using subsystem to be created
  219. SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER | SDL_INIT_NOPARACHUTE);
  220. // Register Graphics library object factories
  221. RegisterGraphicsLibrary(context_);
  222. }
  223. Graphics::~Graphics()
  224. {
  225. Close();
  226. delete impl_;
  227. impl_ = 0;
  228. // Shut down SDL now. Graphics should be the last SDL-using subsystem to be destroyed
  229. SDL_Quit();
  230. }
  231. void Graphics::SetExternalWindow(void* window)
  232. {
  233. if (!impl_->window_)
  234. externalWindow_ = window;
  235. else
  236. LOGERROR("Window already opened, can not set external window");
  237. }
  238. void Graphics::SetWindowTitle(const String& windowTitle)
  239. {
  240. windowTitle_ = windowTitle;
  241. if (impl_->window_)
  242. SDL_SetWindowTitle(impl_->window_, windowTitle_.CString());
  243. }
  244. void Graphics::SetWindowIcon(Image* windowIcon)
  245. {
  246. windowIcon_ = windowIcon;
  247. if (impl_->window_)
  248. CreateWindowIcon();
  249. }
  250. void Graphics::SetWindowPosition(const IntVector2& position)
  251. {
  252. if (impl_->window_)
  253. SDL_SetWindowPosition(impl_->window_, position.x_, position.y_);
  254. else
  255. position_ = position; // Sets as initial position for future window creation
  256. }
  257. void Graphics::SetWindowPosition(int x, int y)
  258. {
  259. SetWindowPosition(IntVector2(x, y));
  260. }
  261. void Graphics::SetWindowSize(int width, int height)
  262. {
  263. if (impl_->window_)
  264. {
  265. SDL_SetWindowSize(impl_->window_, width, height);
  266. WindowResized();
  267. }
  268. }
  269. void Graphics::CenterWindow()
  270. {
  271. if (impl_->window_)
  272. {
  273. SDL_DisplayMode mode;
  274. SDL_GetDesktopDisplayMode(0, &mode);
  275. int width, height;
  276. SDL_GetWindowSize(impl_->window_, &width, &height);
  277. int x = mode.w/2 - width/2;
  278. int y = mode.h/2 - height/2;
  279. SetWindowPosition(x, y);
  280. }
  281. }
  282. void Graphics::RaiseWindow()
  283. {
  284. if (impl_->window_)
  285. SDL_RaiseWindow(impl_->window_);
  286. }
  287. bool Graphics::SetMode(int width, int height, bool fullscreen, bool borderless, bool resizable, bool vsync, bool tripleBuffer, int multiSample)
  288. {
  289. PROFILE(SetScreenMode);
  290. bool maximize = false;
  291. // Fullscreen or Borderless can not be resizable
  292. if (fullscreen || borderless)
  293. resizable = false;
  294. // Borderless cannot be fullscreen, they are mutually exclusive
  295. if (borderless)
  296. fullscreen = false;
  297. multiSample = Clamp(multiSample, 1, 16);
  298. if (IsInitialized() && width == width_ && height == height_ && fullscreen == fullscreen_ && borderless == borderless_ &&
  299. resizable == resizable_ && vsync == vsync_ && tripleBuffer == tripleBuffer_ && multiSample == multiSample_)
  300. return true;
  301. // If only vsync changes, do not destroy/recreate the context
  302. if (IsInitialized() && width == width_ && height == height_ && fullscreen == fullscreen_ && borderless == borderless_ &&
  303. resizable == resizable_ && tripleBuffer == tripleBuffer_ && multiSample == multiSample_ && vsync != vsync_)
  304. {
  305. SDL_GL_SetSwapInterval(vsync ? 1 : 0);
  306. vsync_ = vsync;
  307. return true;
  308. }
  309. // If zero dimensions in windowed mode, set windowed mode to maximize and set a predefined default restored window size.
  310. // If zero in fullscreen, use desktop mode
  311. if (!width || !height)
  312. {
  313. if (fullscreen || borderless)
  314. {
  315. SDL_DisplayMode mode;
  316. SDL_GetDesktopDisplayMode(0, &mode);
  317. width = mode.w;
  318. height = mode.h;
  319. }
  320. else
  321. {
  322. maximize = resizable;
  323. width = 1024;
  324. height = 768;
  325. }
  326. }
  327. // Check fullscreen mode validity (desktop only). Use a closest match if not found
  328. #ifdef DESKTOP_GRAPHICS
  329. if (fullscreen)
  330. {
  331. PODVector<IntVector2> resolutions = GetResolutions();
  332. if (resolutions.Empty())
  333. fullscreen = false;
  334. else
  335. {
  336. unsigned best = 0;
  337. unsigned bestError = M_MAX_UNSIGNED;
  338. for (unsigned i = 0; i < resolutions.Size(); ++i)
  339. {
  340. unsigned error = Abs(resolutions[i].x_ - width) + Abs(resolutions[i].y_ - height);
  341. if (error < bestError)
  342. {
  343. best = i;
  344. bestError = error;
  345. }
  346. }
  347. width = resolutions[best].x_;
  348. height = resolutions[best].y_;
  349. }
  350. }
  351. #endif
  352. String extensions;
  353. // With an external window, only the size can change after initial setup, so do not recreate context
  354. if (!externalWindow_ || !impl_->context_)
  355. {
  356. // Close the existing window and OpenGL context, mark GPU objects as lost
  357. Release(false, true);
  358. #ifdef IOS
  359. // On iOS window needs to be resizable to handle orientation changes properly
  360. resizable = true;
  361. #endif
  362. SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
  363. #ifndef GL_ES_VERSION_2_0
  364. SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
  365. SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
  366. SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
  367. SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
  368. if (externalWindow_)
  369. SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
  370. else
  371. SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 0);
  372. SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
  373. if (!forceGL2_)
  374. {
  375. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
  376. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
  377. SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
  378. }
  379. else
  380. {
  381. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
  382. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
  383. SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, 0);
  384. }
  385. #else
  386. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
  387. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
  388. #endif
  389. if (multiSample > 1)
  390. {
  391. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
  392. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, multiSample);
  393. }
  394. else
  395. {
  396. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);
  397. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);
  398. }
  399. int x = fullscreen ? 0 : position_.x_;
  400. int y = fullscreen ? 0 : position_.y_;
  401. unsigned flags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
  402. if (fullscreen)
  403. flags |= SDL_WINDOW_FULLSCREEN;
  404. if (resizable)
  405. flags |= SDL_WINDOW_RESIZABLE;
  406. if (borderless)
  407. flags |= SDL_WINDOW_BORDERLESS;
  408. SDL_SetHint(SDL_HINT_ORIENTATIONS, orientations_.CString());
  409. for (;;)
  410. {
  411. if (!externalWindow_)
  412. impl_->window_ = SDL_CreateWindow(windowTitle_.CString(), x, y, width, height, flags);
  413. else
  414. {
  415. #ifndef EMSCRIPTEN
  416. if (!impl_->window_)
  417. impl_->window_ = SDL_CreateWindowFrom(externalWindow_, SDL_WINDOW_OPENGL);
  418. fullscreen = false;
  419. #endif
  420. }
  421. if (impl_->window_)
  422. break;
  423. else
  424. {
  425. if (multiSample > 1)
  426. {
  427. // If failed with multisampling, retry first without
  428. multiSample = 1;
  429. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);
  430. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);
  431. }
  432. else
  433. {
  434. LOGERROR("Could not open window");
  435. return false;
  436. }
  437. }
  438. }
  439. CreateWindowIcon();
  440. if (maximize)
  441. {
  442. Maximize();
  443. SDL_GetWindowSize(impl_->window_, &width, &height);
  444. }
  445. // Create/restore context and GPU objects and set initial renderstate
  446. Restore();
  447. // Specific error message is already logged by Restore() when context creation or OpenGL extensions check fails
  448. if (!impl_->context_)
  449. return false;
  450. }
  451. // Set vsync
  452. SDL_GL_SetSwapInterval(vsync ? 1 : 0);
  453. // Store the system FBO on IOS now
  454. #ifdef IOS
  455. glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&impl_->systemFBO_);
  456. #endif
  457. fullscreen_ = fullscreen;
  458. resizable_ = resizable;
  459. borderless_ = borderless;
  460. vsync_ = vsync;
  461. tripleBuffer_ = tripleBuffer;
  462. multiSample_ = multiSample;
  463. SDL_GetWindowSize(impl_->window_, &width_, &height_);
  464. if (!fullscreen)
  465. SDL_GetWindowPosition(impl_->window_, &position_.x_, &position_.y_);
  466. // Reset rendertargets and viewport for the new screen mode
  467. ResetRenderTargets();
  468. // Clear the initial window contents to black
  469. Clear(CLEAR_COLOR);
  470. SDL_GL_SwapWindow(impl_->window_);
  471. CheckFeatureSupport();
  472. #ifdef ATOMIC_LOGGING
  473. String msg;
  474. msg.AppendWithFormat("Set screen mode %dx%d %s", width_, height_, (fullscreen_ ? "fullscreen" : "windowed"));
  475. if (borderless_)
  476. msg.Append(" borderless");
  477. if (resizable_)
  478. msg.Append(" resizable");
  479. if (multiSample > 1)
  480. msg.AppendWithFormat(" multisample %d", multiSample);
  481. LOGINFO(msg);
  482. #endif
  483. using namespace ScreenMode;
  484. VariantMap& eventData = GetEventDataMap();
  485. eventData[P_WIDTH] = width_;
  486. eventData[P_HEIGHT] = height_;
  487. eventData[P_FULLSCREEN] = fullscreen_;
  488. eventData[P_RESIZABLE] = resizable_;
  489. eventData[P_BORDERLESS] = borderless_;
  490. SendEvent(E_SCREENMODE, eventData);
  491. return true;
  492. }
  493. bool Graphics::SetMode(int width, int height)
  494. {
  495. return SetMode(width, height, fullscreen_, borderless_, resizable_, vsync_, tripleBuffer_, multiSample_);
  496. }
  497. void Graphics::SetSRGB(bool enable)
  498. {
  499. enable &= sRGBWriteSupport_;
  500. if (enable != sRGB_)
  501. {
  502. sRGB_ = enable;
  503. impl_->fboDirty_ = true;
  504. }
  505. }
  506. void Graphics::SetFlushGPU(bool enable)
  507. {
  508. }
  509. void Graphics::SetForceGL2(bool enable)
  510. {
  511. if (IsInitialized())
  512. {
  513. LOGERROR("OpenGL 2 can only be forced before setting the initial screen mode");
  514. return;
  515. }
  516. forceGL2_ = enable;
  517. }
  518. void Graphics::SetOrientations(const String& orientations)
  519. {
  520. orientations_ = orientations.Trimmed();
  521. SDL_SetHint(SDL_HINT_ORIENTATIONS, orientations_.CString());
  522. }
  523. bool Graphics::ToggleFullscreen()
  524. {
  525. return SetMode(width_, height_, !fullscreen_, borderless_, resizable_, vsync_, tripleBuffer_, multiSample_);
  526. }
  527. void Graphics::Close()
  528. {
  529. if (!IsInitialized())
  530. return;
  531. // Actually close the window
  532. Release(true, true);
  533. }
  534. bool Graphics::TakeScreenShot(Image* destImage)
  535. {
  536. PROFILE(TakeScreenShot);
  537. ResetRenderTargets();
  538. destImage->SetSize(width_, height_, 3);
  539. glReadPixels(0, 0, width_, height_, GL_RGB, GL_UNSIGNED_BYTE, destImage->GetData());
  540. // On OpenGL we need to flip the image vertically after reading
  541. destImage->FlipVertical();
  542. return true;
  543. }
  544. bool Graphics::BeginFrame()
  545. {
  546. if (!IsInitialized() || IsDeviceLost())
  547. return false;
  548. // If using an external window, check it for size changes, and reset screen mode if necessary
  549. if (externalWindow_)
  550. {
  551. int width, height;
  552. SDL_GetWindowSize(impl_->window_, &width, &height);
  553. if (width != width_ || height != height_)
  554. SetMode(width, height);
  555. }
  556. // Set default rendertarget and depth buffer
  557. ResetRenderTargets();
  558. // Cleanup textures from previous frame
  559. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  560. SetTexture(i, 0);
  561. // Enable color and depth write
  562. SetColorWrite(true);
  563. SetDepthWrite(true);
  564. numPrimitives_ = 0;
  565. numBatches_ = 0;
  566. SendEvent(E_BEGINRENDERING);
  567. return true;
  568. }
  569. void Graphics::EndFrame()
  570. {
  571. if (!IsInitialized())
  572. return;
  573. PROFILE(Present);
  574. SendEvent(E_ENDRENDERING);
  575. SDL_GL_SwapWindow(impl_->window_);
  576. // Clean up too large scratch buffers
  577. CleanupScratchBuffers();
  578. }
  579. void Graphics::Clear(unsigned flags, const Color& color, float depth, unsigned stencil)
  580. {
  581. PrepareDraw();
  582. #ifdef GL_ES_VERSION_2_0
  583. flags &= ~CLEAR_STENCIL;
  584. #endif
  585. bool oldColorWrite = colorWrite_;
  586. bool oldDepthWrite = depthWrite_;
  587. if (flags & CLEAR_COLOR && !oldColorWrite)
  588. SetColorWrite(true);
  589. if (flags & CLEAR_DEPTH && !oldDepthWrite)
  590. SetDepthWrite(true);
  591. if (flags & CLEAR_STENCIL && stencilWriteMask_ != M_MAX_UNSIGNED)
  592. glStencilMask(M_MAX_UNSIGNED);
  593. unsigned glFlags = 0;
  594. if (flags & CLEAR_COLOR)
  595. {
  596. glFlags |= GL_COLOR_BUFFER_BIT;
  597. glClearColor(color.r_, color.g_, color.b_, color.a_);
  598. }
  599. if (flags & CLEAR_DEPTH)
  600. {
  601. glFlags |= GL_DEPTH_BUFFER_BIT;
  602. glClearDepth(depth);
  603. }
  604. if (flags & CLEAR_STENCIL)
  605. {
  606. glFlags |= GL_STENCIL_BUFFER_BIT;
  607. glClearStencil(stencil);
  608. }
  609. // If viewport is less than full screen, set a scissor to limit the clear
  610. /// \todo Any user-set scissor test will be lost
  611. IntVector2 viewSize = GetRenderTargetDimensions();
  612. if (viewport_.left_ != 0 || viewport_.top_ != 0 || viewport_.right_ != viewSize.x_ || viewport_.bottom_ != viewSize.y_)
  613. SetScissorTest(true, IntRect(0, 0, viewport_.Width(), viewport_.Height()));
  614. else
  615. SetScissorTest(false);
  616. glClear(glFlags);
  617. SetScissorTest(false);
  618. SetColorWrite(oldColorWrite);
  619. SetDepthWrite(oldDepthWrite);
  620. if (flags & CLEAR_STENCIL && stencilWriteMask_ != M_MAX_UNSIGNED)
  621. glStencilMask(stencilWriteMask_);
  622. }
  623. bool Graphics::ResolveToTexture(Texture2D* destination, const IntRect& viewport)
  624. {
  625. if (!destination || !destination->GetRenderSurface())
  626. return false;
  627. PROFILE(ResolveToTexture);
  628. IntRect vpCopy = viewport;
  629. if (vpCopy.right_ <= vpCopy.left_)
  630. vpCopy.right_ = vpCopy.left_ + 1;
  631. if (vpCopy.bottom_ <= vpCopy.top_)
  632. vpCopy.bottom_ = vpCopy.top_ + 1;
  633. vpCopy.left_ = Clamp(vpCopy.left_, 0, width_);
  634. vpCopy.top_ = Clamp(vpCopy.top_, 0, height_);
  635. vpCopy.right_ = Clamp(vpCopy.right_, 0, width_);
  636. vpCopy.bottom_ = Clamp(vpCopy.bottom_, 0, height_);
  637. // Make sure the FBO is not in use
  638. ResetRenderTargets();
  639. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  640. SetTextureForUpdate(destination);
  641. glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, vpCopy.left_, height_ - vpCopy.bottom_, vpCopy.Width(), vpCopy.Height());
  642. SetTexture(0, 0);
  643. return true;
  644. }
  645. void Graphics::Draw(PrimitiveType type, unsigned vertexStart, unsigned vertexCount)
  646. {
  647. if (!vertexCount)
  648. return;
  649. PrepareDraw();
  650. unsigned primitiveCount;
  651. GLenum glPrimitiveType;
  652. GetGLPrimitiveType(vertexCount, type, primitiveCount, glPrimitiveType);
  653. glDrawArrays(glPrimitiveType, vertexStart, vertexCount);
  654. numPrimitives_ += primitiveCount;
  655. ++numBatches_;
  656. }
  657. void Graphics::Draw(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount)
  658. {
  659. if (!indexCount || !indexBuffer_ || !indexBuffer_->GetGPUObject())
  660. return;
  661. PrepareDraw();
  662. unsigned indexSize = indexBuffer_->GetIndexSize();
  663. unsigned primitiveCount;
  664. GLenum glPrimitiveType;
  665. GetGLPrimitiveType(indexCount, type, primitiveCount, glPrimitiveType);
  666. GLenum indexType = indexSize == sizeof(unsigned short) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
  667. glDrawElements(glPrimitiveType, indexCount, indexType, reinterpret_cast<const GLvoid*>(indexStart * indexSize));
  668. numPrimitives_ += primitiveCount;
  669. ++numBatches_;
  670. }
  671. void Graphics::DrawInstanced(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount, unsigned instanceCount)
  672. {
  673. #ifndef GL_ES_VERSION_2_0
  674. if (!indexCount || !indexBuffer_ || !indexBuffer_->GetGPUObject() || !instancingSupport_)
  675. return;
  676. PrepareDraw();
  677. unsigned indexSize = indexBuffer_->GetIndexSize();
  678. unsigned primitiveCount;
  679. GLenum glPrimitiveType;
  680. GetGLPrimitiveType(indexCount, type, primitiveCount, glPrimitiveType);
  681. GLenum indexType = indexSize == sizeof(unsigned short) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
  682. if (gl3Support)
  683. {
  684. glDrawElementsInstanced(glPrimitiveType, indexCount, indexType, reinterpret_cast<const GLvoid*>(indexStart * indexSize),
  685. instanceCount);
  686. }
  687. else
  688. {
  689. glDrawElementsInstancedARB(glPrimitiveType, indexCount, indexType, reinterpret_cast<const GLvoid*>(indexStart *
  690. indexSize), instanceCount);
  691. }
  692. numPrimitives_ += instanceCount * primitiveCount;
  693. ++numBatches_;
  694. #endif
  695. }
  696. void Graphics::SetVertexBuffer(VertexBuffer* buffer)
  697. {
  698. // Note: this is not multi-instance safe
  699. static PODVector<VertexBuffer*> vertexBuffers(1);
  700. static PODVector<unsigned> elementMasks(1);
  701. vertexBuffers[0] = buffer;
  702. elementMasks[0] = MASK_DEFAULT;
  703. SetVertexBuffers(vertexBuffers, elementMasks);
  704. }
  705. bool Graphics::SetVertexBuffers(const PODVector<VertexBuffer*>& buffers, const PODVector<unsigned>& elementMasks,
  706. unsigned instanceOffset)
  707. {
  708. if (buffers.Size() > MAX_VERTEX_STREAMS)
  709. {
  710. LOGERROR("Too many vertex buffers");
  711. return false;
  712. }
  713. if (buffers.Size() != elementMasks.Size())
  714. {
  715. LOGERROR("Amount of element masks and vertex buffers does not match");
  716. return false;
  717. }
  718. bool changed = false;
  719. unsigned newAttributes = 0;
  720. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  721. {
  722. VertexBuffer* buffer = 0;
  723. unsigned elementMask = 0;
  724. if (i < buffers.Size() && buffers[i])
  725. {
  726. buffer = buffers[i];
  727. if (elementMasks[i] == MASK_DEFAULT)
  728. elementMask = buffer->GetElementMask();
  729. else
  730. elementMask = buffer->GetElementMask() & elementMasks[i];
  731. }
  732. // If buffer and element mask have stayed the same, skip to the next buffer
  733. if (buffer == vertexBuffers_[i] && elementMask == elementMasks_[i] && instanceOffset == lastInstanceOffset_ && !changed)
  734. {
  735. newAttributes |= elementMask;
  736. continue;
  737. }
  738. vertexBuffers_[i] = buffer;
  739. elementMasks_[i] = elementMask;
  740. changed = true;
  741. // Beware buffers with missing OpenGL objects, as binding a zero buffer object means accessing CPU memory for vertex data,
  742. // in which case the pointer will be invalid and cause a crash
  743. if (!buffer || !buffer->GetGPUObject())
  744. continue;
  745. SetVBO(buffer->GetGPUObject());
  746. unsigned vertexSize = buffer->GetVertexSize();
  747. for (unsigned j = 0; j < MAX_VERTEX_ELEMENTS; ++j)
  748. {
  749. unsigned attrIndex = glVertexAttrIndex[j];
  750. unsigned elementBit = 1 << j;
  751. if (elementMask & elementBit)
  752. {
  753. newAttributes |= elementBit;
  754. // Enable attribute if not enabled yet
  755. if ((impl_->enabledAttributes_ & elementBit) == 0)
  756. {
  757. glEnableVertexAttribArray(attrIndex);
  758. impl_->enabledAttributes_ |= elementBit;
  759. }
  760. // Set the attribute pointer. Add instance offset for the instance matrix pointers
  761. unsigned offset = j >= ELEMENT_INSTANCEMATRIX1 ? instanceOffset * vertexSize : 0;
  762. glVertexAttribPointer(attrIndex, VertexBuffer::elementComponents[j], VertexBuffer::elementType[j],
  763. VertexBuffer::elementNormalize[j], vertexSize, reinterpret_cast<const GLvoid*>(buffer->GetElementOffset((VertexElement)j)
  764. + offset));
  765. }
  766. }
  767. }
  768. if (!changed)
  769. return true;
  770. lastInstanceOffset_ = instanceOffset;
  771. // Now check which vertex attributes should be disabled
  772. unsigned disableAttributes = impl_->enabledAttributes_ & (~newAttributes);
  773. unsigned disableIndex = 0;
  774. while (disableAttributes)
  775. {
  776. if (disableAttributes & 1)
  777. {
  778. glDisableVertexAttribArray(glVertexAttrIndex[disableIndex]);
  779. impl_->enabledAttributes_ &= ~(1 << disableIndex);
  780. }
  781. disableAttributes >>= 1;
  782. ++disableIndex;
  783. }
  784. return true;
  785. }
  786. bool Graphics::SetVertexBuffers(const Vector<SharedPtr<VertexBuffer> >& buffers, const PODVector<unsigned>&
  787. elementMasks, unsigned instanceOffset)
  788. {
  789. return SetVertexBuffers(reinterpret_cast<const PODVector<VertexBuffer*>&>(buffers), elementMasks, instanceOffset);
  790. }
  791. void Graphics::SetIndexBuffer(IndexBuffer* buffer)
  792. {
  793. if (indexBuffer_ == buffer)
  794. return;
  795. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer ? buffer->GetGPUObject() : 0);
  796. indexBuffer_ = buffer;
  797. }
  798. void Graphics::SetShaders(ShaderVariation* vs, ShaderVariation* ps)
  799. {
  800. if (vs == vertexShader_ && ps == pixelShader_)
  801. return;
  802. // Compile the shaders now if not yet compiled. If already attempted, do not retry
  803. if (vs && !vs->GetGPUObject())
  804. {
  805. if (vs->GetCompilerOutput().Empty())
  806. {
  807. PROFILE(CompileVertexShader);
  808. bool success = vs->Create();
  809. if (success)
  810. LOGDEBUG("Compiled vertex shader " + vs->GetFullName());
  811. else
  812. {
  813. LOGERROR("Failed to compile vertex shader " + vs->GetFullName() + ":\n" + vs->GetCompilerOutput());
  814. vs = 0;
  815. }
  816. }
  817. else
  818. vs = 0;
  819. }
  820. if (ps && !ps->GetGPUObject())
  821. {
  822. if (ps->GetCompilerOutput().Empty())
  823. {
  824. PROFILE(CompilePixelShader);
  825. bool success = ps->Create();
  826. if (success)
  827. LOGDEBUG("Compiled pixel shader " + ps->GetFullName());
  828. else
  829. {
  830. LOGERROR("Failed to compile pixel shader " + ps->GetFullName() + ":\n" + ps->GetCompilerOutput());
  831. ps = 0;
  832. }
  833. }
  834. else
  835. ps = 0;
  836. }
  837. if (!vs || !ps)
  838. {
  839. glUseProgram(0);
  840. vertexShader_ = 0;
  841. pixelShader_ = 0;
  842. shaderProgram_ = 0;
  843. }
  844. else
  845. {
  846. vertexShader_ = vs;
  847. pixelShader_ = ps;
  848. Pair<ShaderVariation*, ShaderVariation*> combination(vs, ps);
  849. ShaderProgramMap::Iterator i = shaderPrograms_.Find(combination);
  850. if (i != shaderPrograms_.End())
  851. {
  852. // Use the existing linked program
  853. if (i->second_->GetGPUObject())
  854. {
  855. glUseProgram(i->second_->GetGPUObject());
  856. shaderProgram_ = i->second_;
  857. }
  858. else
  859. {
  860. glUseProgram(0);
  861. shaderProgram_ = 0;
  862. }
  863. }
  864. else
  865. {
  866. // Link a new combination
  867. PROFILE(LinkShaders);
  868. SharedPtr<ShaderProgram> newProgram(new ShaderProgram(this, vs, ps));
  869. if (newProgram->Link())
  870. {
  871. LOGDEBUG("Linked vertex shader " + vs->GetFullName() + " and pixel shader " + ps->GetFullName());
  872. // Note: Link() calls glUseProgram() to set the texture sampler uniforms,
  873. // so it is not necessary to call it again
  874. shaderProgram_ = newProgram;
  875. }
  876. else
  877. {
  878. LOGERROR("Failed to link vertex shader " + vs->GetFullName() + " and pixel shader " + ps->GetFullName() + ":\n" +
  879. newProgram->GetLinkerOutput());
  880. glUseProgram(0);
  881. shaderProgram_ = 0;
  882. }
  883. shaderPrograms_[combination] = newProgram;
  884. }
  885. }
  886. // Update the clip plane uniform on GL3, and set constant buffers
  887. #ifndef GL_ES_VERSION_2_0
  888. if (gl3Support && shaderProgram_)
  889. {
  890. const SharedPtr<ConstantBuffer>* constantBuffers = shaderProgram_->GetConstantBuffers();
  891. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS * 2; ++i)
  892. {
  893. ConstantBuffer* buffer = constantBuffers[i].Get();
  894. if (buffer != currentConstantBuffers_[i])
  895. {
  896. unsigned object = buffer ? buffer->GetGPUObject() : 0;
  897. glBindBufferBase(GL_UNIFORM_BUFFER, i, object);
  898. // Calling glBindBufferBase also affects the generic buffer binding point
  899. impl_->boundUBO_ = object;
  900. currentConstantBuffers_[i] = buffer;
  901. ShaderProgram::ClearGlobalParameterSource((ShaderParameterGroup)(i % MAX_SHADER_PARAMETER_GROUPS));
  902. }
  903. }
  904. SetShaderParameter(VSP_CLIPPLANE, useClipPlane_ ? clipPlane_ : Vector4(0.0f, 0.0f, 0.0f, 1.0f));
  905. }
  906. #endif
  907. // Store shader combination if shader dumping in progress
  908. if (shaderPrecache_)
  909. shaderPrecache_->StoreShaders(vertexShader_, pixelShader_);
  910. }
  911. void Graphics::SetShaderParameter(StringHash param, const float* data, unsigned count)
  912. {
  913. if (shaderProgram_)
  914. {
  915. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  916. if (info)
  917. {
  918. if (info->bufferPtr_)
  919. {
  920. ConstantBuffer* buffer = info->bufferPtr_;
  921. if (!buffer->IsDirty())
  922. dirtyConstantBuffers_.Push(buffer);
  923. buffer->SetParameter(info->location_, count * sizeof(float), data);
  924. return;
  925. }
  926. switch (info->type_)
  927. {
  928. case GL_FLOAT:
  929. glUniform1fv(info->location_, count, data);
  930. break;
  931. case GL_FLOAT_VEC2:
  932. glUniform2fv(info->location_, count / 2, data);
  933. break;
  934. case GL_FLOAT_VEC3:
  935. glUniform3fv(info->location_, count / 3, data);
  936. break;
  937. case GL_FLOAT_VEC4:
  938. glUniform4fv(info->location_, count / 4, data);
  939. break;
  940. case GL_FLOAT_MAT3:
  941. glUniformMatrix3fv(info->location_, count / 9, GL_FALSE, data);
  942. break;
  943. case GL_FLOAT_MAT4:
  944. glUniformMatrix4fv(info->location_, count / 16, GL_FALSE, data);
  945. break;
  946. }
  947. }
  948. }
  949. }
  950. void Graphics::SetShaderParameter(StringHash param, float value)
  951. {
  952. if (shaderProgram_)
  953. {
  954. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  955. if (info)
  956. {
  957. if (info->bufferPtr_)
  958. {
  959. ConstantBuffer* buffer = info->bufferPtr_;
  960. if (!buffer->IsDirty())
  961. dirtyConstantBuffers_.Push(buffer);
  962. buffer->SetParameter(info->location_, sizeof(float), &value);
  963. return;
  964. }
  965. glUniform1fv(info->location_, 1, &value);
  966. }
  967. }
  968. }
  969. void Graphics::SetShaderParameter(StringHash param, const Color& color)
  970. {
  971. SetShaderParameter(param, color.Data(), 4);
  972. }
  973. void Graphics::SetShaderParameter(StringHash param, const Vector2& vector)
  974. {
  975. if (shaderProgram_)
  976. {
  977. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  978. if (info)
  979. {
  980. if (info->bufferPtr_)
  981. {
  982. ConstantBuffer* buffer = info->bufferPtr_;
  983. if (!buffer->IsDirty())
  984. dirtyConstantBuffers_.Push(buffer);
  985. buffer->SetParameter(info->location_, sizeof(Vector2), &vector);
  986. return;
  987. }
  988. // Check the uniform type to avoid mismatch
  989. switch (info->type_)
  990. {
  991. case GL_FLOAT:
  992. glUniform1fv(info->location_, 1, vector.Data());
  993. break;
  994. case GL_FLOAT_VEC2:
  995. glUniform2fv(info->location_, 1, vector.Data());
  996. break;
  997. }
  998. }
  999. }
  1000. }
  1001. void Graphics::SetShaderParameter(StringHash param, const Matrix3& matrix)
  1002. {
  1003. if (shaderProgram_)
  1004. {
  1005. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  1006. if (info)
  1007. {
  1008. if (info->bufferPtr_)
  1009. {
  1010. ConstantBuffer* buffer = info->bufferPtr_;
  1011. if (!buffer->IsDirty())
  1012. dirtyConstantBuffers_.Push(buffer);
  1013. buffer->SetVector3ArrayParameter(info->location_, 3, &matrix);
  1014. return;
  1015. }
  1016. glUniformMatrix3fv(info->location_, 1, GL_FALSE, matrix.Data());
  1017. }
  1018. }
  1019. }
  1020. void Graphics::SetShaderParameter(StringHash param, const Vector3& vector)
  1021. {
  1022. if (shaderProgram_)
  1023. {
  1024. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  1025. if (info)
  1026. {
  1027. if (info->bufferPtr_)
  1028. {
  1029. ConstantBuffer* buffer = info->bufferPtr_;
  1030. if (!buffer->IsDirty())
  1031. dirtyConstantBuffers_.Push(buffer);
  1032. buffer->SetParameter(info->location_, sizeof(Vector3), &vector);
  1033. return;
  1034. }
  1035. // Check the uniform type to avoid mismatch
  1036. switch (info->type_)
  1037. {
  1038. case GL_FLOAT:
  1039. glUniform1fv(info->location_, 1, vector.Data());
  1040. break;
  1041. case GL_FLOAT_VEC2:
  1042. glUniform2fv(info->location_, 1, vector.Data());
  1043. break;
  1044. case GL_FLOAT_VEC3:
  1045. glUniform3fv(info->location_, 1, vector.Data());
  1046. break;
  1047. }
  1048. }
  1049. }
  1050. }
  1051. void Graphics::SetShaderParameter(StringHash param, const Matrix4& matrix)
  1052. {
  1053. if (shaderProgram_)
  1054. {
  1055. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  1056. if (info)
  1057. {
  1058. if (info->bufferPtr_)
  1059. {
  1060. ConstantBuffer* buffer = info->bufferPtr_;
  1061. if (!buffer->IsDirty())
  1062. dirtyConstantBuffers_.Push(buffer);
  1063. buffer->SetParameter(info->location_, sizeof(Matrix4), &matrix);
  1064. return;
  1065. }
  1066. glUniformMatrix4fv(info->location_, 1, GL_FALSE, matrix.Data());
  1067. }
  1068. }
  1069. }
  1070. void Graphics::SetShaderParameter(StringHash param, const Vector4& vector)
  1071. {
  1072. if (shaderProgram_)
  1073. {
  1074. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  1075. if (info)
  1076. {
  1077. if (info->bufferPtr_)
  1078. {
  1079. ConstantBuffer* buffer = info->bufferPtr_;
  1080. if (!buffer->IsDirty())
  1081. dirtyConstantBuffers_.Push(buffer);
  1082. buffer->SetParameter(info->location_, sizeof(Vector4), &vector);
  1083. return;
  1084. }
  1085. // Check the uniform type to avoid mismatch
  1086. switch (info->type_)
  1087. {
  1088. case GL_FLOAT:
  1089. glUniform1fv(info->location_, 1, vector.Data());
  1090. break;
  1091. case GL_FLOAT_VEC2:
  1092. glUniform2fv(info->location_, 1, vector.Data());
  1093. break;
  1094. case GL_FLOAT_VEC3:
  1095. glUniform3fv(info->location_, 1, vector.Data());
  1096. break;
  1097. case GL_FLOAT_VEC4:
  1098. glUniform4fv(info->location_, 1, vector.Data());
  1099. break;
  1100. }
  1101. }
  1102. }
  1103. }
  1104. void Graphics::SetShaderParameter(StringHash param, const Matrix3x4& matrix)
  1105. {
  1106. if (shaderProgram_)
  1107. {
  1108. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  1109. if (info)
  1110. {
  1111. // Expand to a full Matrix4
  1112. static Matrix4 fullMatrix;
  1113. fullMatrix.m00_ = matrix.m00_;
  1114. fullMatrix.m01_ = matrix.m01_;
  1115. fullMatrix.m02_ = matrix.m02_;
  1116. fullMatrix.m03_ = matrix.m03_;
  1117. fullMatrix.m10_ = matrix.m10_;
  1118. fullMatrix.m11_ = matrix.m11_;
  1119. fullMatrix.m12_ = matrix.m12_;
  1120. fullMatrix.m13_ = matrix.m13_;
  1121. fullMatrix.m20_ = matrix.m20_;
  1122. fullMatrix.m21_ = matrix.m21_;
  1123. fullMatrix.m22_ = matrix.m22_;
  1124. fullMatrix.m23_ = matrix.m23_;
  1125. if (info->bufferPtr_)
  1126. {
  1127. ConstantBuffer* buffer = info->bufferPtr_;
  1128. if (!buffer->IsDirty())
  1129. dirtyConstantBuffers_.Push(buffer);
  1130. buffer->SetParameter(info->location_, sizeof(Matrix4), &fullMatrix);
  1131. return;
  1132. }
  1133. glUniformMatrix4fv(info->location_, 1, GL_FALSE, fullMatrix.Data());
  1134. }
  1135. }
  1136. }
  1137. void Graphics::SetShaderParameter(StringHash param, const Variant& value)
  1138. {
  1139. switch (value.GetType())
  1140. {
  1141. case VAR_BOOL:
  1142. SetShaderParameter(param, value.GetBool());
  1143. break;
  1144. case VAR_FLOAT:
  1145. SetShaderParameter(param, value.GetFloat());
  1146. break;
  1147. case VAR_VECTOR2:
  1148. SetShaderParameter(param, value.GetVector2());
  1149. break;
  1150. case VAR_VECTOR3:
  1151. SetShaderParameter(param, value.GetVector3());
  1152. break;
  1153. case VAR_VECTOR4:
  1154. SetShaderParameter(param, value.GetVector4());
  1155. break;
  1156. case VAR_COLOR:
  1157. SetShaderParameter(param, value.GetColor());
  1158. break;
  1159. case VAR_MATRIX3:
  1160. SetShaderParameter(param, value.GetMatrix3());
  1161. break;
  1162. case VAR_MATRIX3X4:
  1163. SetShaderParameter(param, value.GetMatrix3x4());
  1164. break;
  1165. case VAR_MATRIX4:
  1166. SetShaderParameter(param, value.GetMatrix4());
  1167. break;
  1168. default:
  1169. // Unsupported parameter type, do nothing
  1170. break;
  1171. }
  1172. }
  1173. bool Graphics::NeedParameterUpdate(ShaderParameterGroup group, const void* source)
  1174. {
  1175. return shaderProgram_ ? shaderProgram_->NeedParameterUpdate(group, source) : false;
  1176. }
  1177. bool Graphics::HasShaderParameter(StringHash param)
  1178. {
  1179. return shaderProgram_ && shaderProgram_->HasParameter(param);
  1180. }
  1181. bool Graphics::HasTextureUnit(TextureUnit unit)
  1182. {
  1183. return shaderProgram_ && shaderProgram_->HasTextureUnit(unit);
  1184. }
  1185. void Graphics::ClearParameterSource(ShaderParameterGroup group)
  1186. {
  1187. if (shaderProgram_)
  1188. shaderProgram_->ClearParameterSource(group);
  1189. }
  1190. void Graphics::ClearParameterSources()
  1191. {
  1192. ShaderProgram::ClearParameterSources();
  1193. }
  1194. void Graphics::ClearTransformSources()
  1195. {
  1196. if (shaderProgram_)
  1197. {
  1198. shaderProgram_->ClearParameterSource(SP_CAMERA);
  1199. shaderProgram_->ClearParameterSource(SP_OBJECT);
  1200. }
  1201. }
  1202. void Graphics::SetTexture(unsigned index, Texture* texture)
  1203. {
  1204. if (index >= MAX_TEXTURE_UNITS)
  1205. return;
  1206. // Check if texture is currently bound as a rendertarget. In that case, use its backup texture, or blank if not defined
  1207. if (texture)
  1208. {
  1209. if (renderTargets_[0] && renderTargets_[0]->GetParentTexture() == texture)
  1210. texture = texture->GetBackupTexture();
  1211. }
  1212. if (textures_[index] != texture)
  1213. {
  1214. if (impl_->activeTexture_ != index)
  1215. {
  1216. glActiveTexture(GL_TEXTURE0 + index);
  1217. impl_->activeTexture_ = index;
  1218. }
  1219. if (texture)
  1220. {
  1221. unsigned glType = texture->GetTarget();
  1222. if (glType != textureTypes_[index])
  1223. {
  1224. if (textureTypes_[index])
  1225. {
  1226. if (textures_[index])
  1227. glBindTexture(textureTypes_[index], 0);
  1228. if (!gl3Support)
  1229. glDisable(textureTypes_[index]);
  1230. }
  1231. if (!gl3Support)
  1232. glEnable(glType);
  1233. textureTypes_[index] = glType;
  1234. }
  1235. glBindTexture(glType, texture->GetGPUObject());
  1236. if (texture->GetParametersDirty())
  1237. texture->UpdateParameters();
  1238. }
  1239. else
  1240. {
  1241. if (textureTypes_[index])
  1242. glBindTexture(textureTypes_[index], 0);
  1243. }
  1244. textures_[index] = texture;
  1245. }
  1246. else
  1247. {
  1248. if (texture && texture->GetParametersDirty())
  1249. {
  1250. if (impl_->activeTexture_ != index)
  1251. {
  1252. glActiveTexture(GL_TEXTURE0 + index);
  1253. impl_->activeTexture_ = index;
  1254. }
  1255. glBindTexture(texture->GetTarget(), texture->GetGPUObject());
  1256. texture->UpdateParameters();
  1257. }
  1258. }
  1259. }
  1260. void Graphics::SetTextureForUpdate(Texture* texture)
  1261. {
  1262. if (impl_->activeTexture_ != 0)
  1263. {
  1264. glActiveTexture(GL_TEXTURE0);
  1265. impl_->activeTexture_ = 0;
  1266. }
  1267. glBindTexture(texture->GetTarget(), texture->GetGPUObject());
  1268. textures_[0] = texture;
  1269. }
  1270. void Graphics::SetDefaultTextureFilterMode(TextureFilterMode mode)
  1271. {
  1272. if (mode != defaultTextureFilterMode_)
  1273. {
  1274. defaultTextureFilterMode_ = mode;
  1275. SetTextureParametersDirty();
  1276. }
  1277. }
  1278. void Graphics::SetTextureAnisotropy(unsigned level)
  1279. {
  1280. if (level != textureAnisotropy_)
  1281. {
  1282. textureAnisotropy_ = level;
  1283. SetTextureParametersDirty();
  1284. }
  1285. }
  1286. void Graphics::SetTextureParametersDirty()
  1287. {
  1288. MutexLock lock(gpuObjectMutex_);
  1289. for (PODVector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1290. {
  1291. Texture* texture = dynamic_cast<Texture*>(*i);
  1292. if (texture)
  1293. texture->SetParametersDirty();
  1294. }
  1295. }
  1296. void Graphics::ResetRenderTargets()
  1297. {
  1298. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1299. SetRenderTarget(i, (RenderSurface*)0);
  1300. SetDepthStencil((RenderSurface*)0);
  1301. SetViewport(IntRect(0, 0, width_, height_));
  1302. }
  1303. void Graphics::ResetRenderTarget(unsigned index)
  1304. {
  1305. SetRenderTarget(index, (RenderSurface*)0);
  1306. }
  1307. void Graphics::ResetDepthStencil()
  1308. {
  1309. SetDepthStencil((RenderSurface*)0);
  1310. }
  1311. void Graphics::SetRenderTarget(unsigned index, RenderSurface* renderTarget)
  1312. {
  1313. if (index >= MAX_RENDERTARGETS)
  1314. return;
  1315. if (renderTarget != renderTargets_[index])
  1316. {
  1317. renderTargets_[index] = renderTarget;
  1318. // If the rendertarget is also bound as a texture, replace with backup texture or null
  1319. if (renderTarget)
  1320. {
  1321. Texture* parentTexture = renderTarget->GetParentTexture();
  1322. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1323. {
  1324. if (textures_[i] == parentTexture)
  1325. SetTexture(i, textures_[i]->GetBackupTexture());
  1326. }
  1327. }
  1328. impl_->fboDirty_ = true;
  1329. }
  1330. }
  1331. void Graphics::SetRenderTarget(unsigned index, Texture2D* texture)
  1332. {
  1333. RenderSurface* renderTarget = 0;
  1334. if (texture)
  1335. renderTarget = texture->GetRenderSurface();
  1336. SetRenderTarget(index, renderTarget);
  1337. }
  1338. void Graphics::SetDepthStencil(RenderSurface* depthStencil)
  1339. {
  1340. // If we are using a rendertarget texture, it is required in OpenGL to also have an own depth-stencil
  1341. // Create a new depth-stencil texture as necessary to be able to provide similar behaviour as Direct3D9
  1342. if (renderTargets_[0] && !depthStencil)
  1343. {
  1344. int width = renderTargets_[0]->GetWidth();
  1345. int height = renderTargets_[0]->GetHeight();
  1346. // Direct3D9 default depth-stencil can not be used when rendertarget is larger than the window.
  1347. // Check size similarly
  1348. if (width <= width_ && height <= height_)
  1349. {
  1350. int searchKey = (width << 16) | height;
  1351. HashMap<int, SharedPtr<Texture2D> >::Iterator i = depthTextures_.Find(searchKey);
  1352. if (i != depthTextures_.End())
  1353. depthStencil = i->second_->GetRenderSurface();
  1354. else
  1355. {
  1356. SharedPtr<Texture2D> newDepthTexture(new Texture2D(context_));
  1357. newDepthTexture->SetSize(width, height, GetDepthStencilFormat(), TEXTURE_DEPTHSTENCIL);
  1358. depthTextures_[searchKey] = newDepthTexture;
  1359. depthStencil = newDepthTexture->GetRenderSurface();
  1360. }
  1361. }
  1362. }
  1363. if (depthStencil != depthStencil_)
  1364. {
  1365. depthStencil_ = depthStencil;
  1366. impl_->fboDirty_ = true;
  1367. }
  1368. }
  1369. void Graphics::SetDepthStencil(Texture2D* texture)
  1370. {
  1371. RenderSurface* depthStencil = 0;
  1372. if (texture)
  1373. depthStencil = texture->GetRenderSurface();
  1374. SetDepthStencil(depthStencil);
  1375. }
  1376. void Graphics::SetViewport(const IntRect& rect)
  1377. {
  1378. PrepareDraw();
  1379. IntVector2 rtSize = GetRenderTargetDimensions();
  1380. IntRect rectCopy = rect;
  1381. if (rectCopy.right_ <= rectCopy.left_)
  1382. rectCopy.right_ = rectCopy.left_ + 1;
  1383. if (rectCopy.bottom_ <= rectCopy.top_)
  1384. rectCopy.bottom_ = rectCopy.top_ + 1;
  1385. rectCopy.left_ = Clamp(rectCopy.left_, 0, rtSize.x_);
  1386. rectCopy.top_ = Clamp(rectCopy.top_, 0, rtSize.y_);
  1387. rectCopy.right_ = Clamp(rectCopy.right_, 0, rtSize.x_);
  1388. rectCopy.bottom_ = Clamp(rectCopy.bottom_, 0, rtSize.y_);
  1389. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1390. glViewport(rectCopy.left_, rtSize.y_ - rectCopy.bottom_, rectCopy.Width(), rectCopy.Height());
  1391. viewport_ = rectCopy;
  1392. // Disable scissor test, needs to be re-enabled by the user
  1393. SetScissorTest(false);
  1394. }
  1395. void Graphics::SetBlendMode(BlendMode mode)
  1396. {
  1397. if (mode != blendMode_)
  1398. {
  1399. if (mode == BLEND_REPLACE)
  1400. glDisable(GL_BLEND);
  1401. else
  1402. {
  1403. glEnable(GL_BLEND);
  1404. glBlendFunc(glSrcBlend[mode], glDestBlend[mode]);
  1405. glBlendEquation(glBlendOp[mode]);
  1406. }
  1407. blendMode_ = mode;
  1408. }
  1409. }
  1410. void Graphics::SetColorWrite(bool enable)
  1411. {
  1412. if (enable != colorWrite_)
  1413. {
  1414. if (enable)
  1415. glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  1416. else
  1417. glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  1418. colorWrite_ = enable;
  1419. }
  1420. }
  1421. void Graphics::SetCullMode(CullMode mode)
  1422. {
  1423. if (mode != cullMode_)
  1424. {
  1425. if (mode == CULL_NONE)
  1426. glDisable(GL_CULL_FACE);
  1427. else
  1428. {
  1429. // Use Direct3D convention, ie. clockwise vertices define a front face
  1430. glEnable(GL_CULL_FACE);
  1431. glCullFace(mode == CULL_CCW ? GL_FRONT : GL_BACK);
  1432. }
  1433. cullMode_ = mode;
  1434. }
  1435. }
  1436. void Graphics::SetDepthBias(float constantBias, float slopeScaledBias)
  1437. {
  1438. if (constantBias != constantDepthBias_ || slopeScaledBias != slopeScaledDepthBias_)
  1439. {
  1440. #ifndef GL_ES_VERSION_2_0
  1441. if (slopeScaledBias != 0.0f)
  1442. {
  1443. // OpenGL constant bias is unreliable and dependant on depth buffer bitdepth, apply in the projection matrix instead
  1444. float adjustedSlopeScaledBias = slopeScaledBias + 1.0f;
  1445. glEnable(GL_POLYGON_OFFSET_FILL);
  1446. glPolygonOffset(adjustedSlopeScaledBias, 0.0f);
  1447. }
  1448. else
  1449. glDisable(GL_POLYGON_OFFSET_FILL);
  1450. #endif
  1451. constantDepthBias_ = constantBias;
  1452. slopeScaledDepthBias_ = slopeScaledBias;
  1453. // Force update of the projection matrix shader parameter
  1454. ClearParameterSource(SP_CAMERA);
  1455. }
  1456. }
  1457. void Graphics::SetDepthTest(CompareMode mode)
  1458. {
  1459. if (mode != depthTestMode_)
  1460. {
  1461. glDepthFunc(glCmpFunc[mode]);
  1462. depthTestMode_ = mode;
  1463. }
  1464. }
  1465. void Graphics::SetDepthWrite(bool enable)
  1466. {
  1467. if (enable != depthWrite_)
  1468. {
  1469. glDepthMask(enable ? GL_TRUE : GL_FALSE);
  1470. depthWrite_ = enable;
  1471. }
  1472. }
  1473. void Graphics::SetFillMode(FillMode mode)
  1474. {
  1475. #ifndef GL_ES_VERSION_2_0
  1476. if (mode != fillMode_)
  1477. {
  1478. glPolygonMode(GL_FRONT_AND_BACK, glFillMode[mode]);
  1479. fillMode_ = mode;
  1480. }
  1481. #endif
  1482. }
  1483. void Graphics::SetScissorTest(bool enable, const Rect& rect, bool borderInclusive)
  1484. {
  1485. // During some light rendering loops, a full rect is toggled on/off repeatedly.
  1486. // Disable scissor in that case to reduce state changes
  1487. if (rect.min_.x_ <= 0.0f && rect.min_.y_ <= 0.0f && rect.max_.x_ >= 1.0f && rect.max_.y_ >= 1.0f)
  1488. enable = false;
  1489. if (enable)
  1490. {
  1491. IntVector2 rtSize(GetRenderTargetDimensions());
  1492. IntVector2 viewSize(viewport_.Size());
  1493. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1494. IntRect intRect;
  1495. int expand = borderInclusive ? 1 : 0;
  1496. intRect.left_ = Clamp((int)((rect.min_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_, 0, rtSize.x_ - 1);
  1497. intRect.top_ = Clamp((int)((-rect.max_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_, 0, rtSize.y_ - 1);
  1498. intRect.right_ = Clamp((int)((rect.max_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_ + expand, 0, rtSize.x_);
  1499. intRect.bottom_ = Clamp((int)((-rect.min_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_ + expand, 0, rtSize.y_);
  1500. if (intRect.right_ == intRect.left_)
  1501. intRect.right_++;
  1502. if (intRect.bottom_ == intRect.top_)
  1503. intRect.bottom_++;
  1504. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1505. enable = false;
  1506. if (enable && scissorRect_ != intRect)
  1507. {
  1508. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1509. glScissor(intRect.left_, rtSize.y_ - intRect.bottom_, intRect.Width(), intRect.Height());
  1510. scissorRect_ = intRect;
  1511. }
  1512. }
  1513. else
  1514. scissorRect_ = IntRect::ZERO;
  1515. if (enable != scissorTest_)
  1516. {
  1517. if (enable)
  1518. glEnable(GL_SCISSOR_TEST);
  1519. else
  1520. glDisable(GL_SCISSOR_TEST);
  1521. scissorTest_ = enable;
  1522. }
  1523. }
  1524. void Graphics::SetScissorTest(bool enable, const IntRect& rect)
  1525. {
  1526. IntVector2 rtSize(GetRenderTargetDimensions());
  1527. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1528. if (enable)
  1529. {
  1530. IntRect intRect;
  1531. intRect.left_ = Clamp(rect.left_ + viewPos.x_, 0, rtSize.x_ - 1);
  1532. intRect.top_ = Clamp(rect.top_ + viewPos.y_, 0, rtSize.y_ - 1);
  1533. intRect.right_ = Clamp(rect.right_ + viewPos.x_, 0, rtSize.x_);
  1534. intRect.bottom_ = Clamp(rect.bottom_ + viewPos.y_, 0, rtSize.y_);
  1535. if (intRect.right_ == intRect.left_)
  1536. intRect.right_++;
  1537. if (intRect.bottom_ == intRect.top_)
  1538. intRect.bottom_++;
  1539. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1540. enable = false;
  1541. if (enable && scissorRect_ != intRect)
  1542. {
  1543. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1544. glScissor(intRect.left_, rtSize.y_ - intRect.bottom_, intRect.Width(), intRect.Height());
  1545. scissorRect_ = intRect;
  1546. }
  1547. }
  1548. else
  1549. scissorRect_ = IntRect::ZERO;
  1550. if (enable != scissorTest_)
  1551. {
  1552. if (enable)
  1553. glEnable(GL_SCISSOR_TEST);
  1554. else
  1555. glDisable(GL_SCISSOR_TEST);
  1556. scissorTest_ = enable;
  1557. }
  1558. }
  1559. void Graphics::SetClipPlane(bool enable, const Plane& clipPlane, const Matrix3x4& view, const Matrix4& projection)
  1560. {
  1561. #ifndef GL_ES_VERSION_2_0
  1562. if (enable != useClipPlane_)
  1563. {
  1564. if (enable)
  1565. glEnable(GL_CLIP_PLANE0);
  1566. else
  1567. glDisable(GL_CLIP_PLANE0);
  1568. useClipPlane_ = enable;
  1569. }
  1570. if (enable)
  1571. {
  1572. Matrix4 viewProj = projection * view;
  1573. clipPlane_ = clipPlane.Transformed(viewProj).ToVector4();
  1574. if (!gl3Support)
  1575. {
  1576. GLdouble planeData[4];
  1577. planeData[0] = clipPlane_.x_;
  1578. planeData[1] = clipPlane_.y_;
  1579. planeData[2] = clipPlane_.z_;
  1580. planeData[3] = clipPlane_.w_;
  1581. glClipPlane(GL_CLIP_PLANE0, &planeData[0]);
  1582. }
  1583. }
  1584. #endif
  1585. }
  1586. void Graphics::SetStencilTest(bool enable, CompareMode mode, StencilOp pass, StencilOp fail, StencilOp zFail, unsigned stencilRef, unsigned compareMask, unsigned writeMask)
  1587. {
  1588. #ifndef GL_ES_VERSION_2_0
  1589. if (enable != stencilTest_)
  1590. {
  1591. if (enable)
  1592. glEnable(GL_STENCIL_TEST);
  1593. else
  1594. glDisable(GL_STENCIL_TEST);
  1595. stencilTest_ = enable;
  1596. }
  1597. if (enable)
  1598. {
  1599. if (mode != stencilTestMode_ || stencilRef != stencilRef_ || compareMask != stencilCompareMask_)
  1600. {
  1601. glStencilFunc(glCmpFunc[mode], stencilRef, compareMask);
  1602. stencilTestMode_ = mode;
  1603. stencilRef_ = stencilRef;
  1604. stencilCompareMask_ = compareMask;
  1605. }
  1606. if (writeMask != stencilWriteMask_)
  1607. {
  1608. glStencilMask(writeMask);
  1609. stencilWriteMask_ = writeMask;
  1610. }
  1611. if (pass != stencilPass_ || fail != stencilFail_ || zFail != stencilZFail_)
  1612. {
  1613. glStencilOp(glStencilOps[fail], glStencilOps[zFail], glStencilOps[pass]);
  1614. stencilPass_ = pass;
  1615. stencilFail_ = fail;
  1616. stencilZFail_ = zFail;
  1617. }
  1618. }
  1619. #endif
  1620. }
  1621. void Graphics::BeginDumpShaders(const String& fileName)
  1622. {
  1623. shaderPrecache_ = new ShaderPrecache(context_, fileName);
  1624. }
  1625. void Graphics::EndDumpShaders()
  1626. {
  1627. shaderPrecache_.Reset();
  1628. }
  1629. void Graphics::PrecacheShaders(Deserializer& source)
  1630. {
  1631. PROFILE(PrecacheShaders);
  1632. ShaderPrecache::LoadShaders(this, source);
  1633. }
  1634. bool Graphics::IsInitialized() const
  1635. {
  1636. return impl_->window_ != 0;
  1637. }
  1638. bool Graphics::IsDeviceLost() const
  1639. {
  1640. // On iOS treat window minimization as device loss, as it is forbidden to access OpenGL when minimized
  1641. #ifdef IOS
  1642. if (impl_->window_ && (SDL_GetWindowFlags(impl_->window_) & SDL_WINDOW_MINIMIZED) != 0)
  1643. return true;
  1644. #endif
  1645. return impl_->context_ == 0;
  1646. }
  1647. IntVector2 Graphics::GetWindowPosition() const
  1648. {
  1649. if (impl_->window_)
  1650. return position_;
  1651. return IntVector2::ZERO;
  1652. }
  1653. PODVector<IntVector2> Graphics::GetResolutions() const
  1654. {
  1655. PODVector<IntVector2> ret;
  1656. unsigned numModes = SDL_GetNumDisplayModes(0);
  1657. for (unsigned i = 0; i < numModes; ++i)
  1658. {
  1659. SDL_DisplayMode mode;
  1660. SDL_GetDisplayMode(0, i, &mode);
  1661. int width = mode.w;
  1662. int height = mode.h;
  1663. // Store mode if unique
  1664. bool unique = true;
  1665. for (unsigned j = 0; j < ret.Size(); ++j)
  1666. {
  1667. if (ret[j].x_ == width && ret[j].y_ == height)
  1668. {
  1669. unique = false;
  1670. break;
  1671. }
  1672. }
  1673. if (unique)
  1674. ret.Push(IntVector2(width, height));
  1675. }
  1676. return ret;
  1677. }
  1678. PODVector<int> Graphics::GetMultiSampleLevels() const
  1679. {
  1680. PODVector<int> ret;
  1681. // No multisampling always supported
  1682. ret.Push(1);
  1683. /// \todo Implement properly, if possible
  1684. return ret;
  1685. }
  1686. IntVector2 Graphics::GetDesktopResolution() const
  1687. {
  1688. #if !defined(ANDROID) && !defined(IOS)
  1689. SDL_DisplayMode mode;
  1690. SDL_GetDesktopDisplayMode(0, &mode);
  1691. return IntVector2(mode.w, mode.h);
  1692. #else
  1693. // SDL_GetDesktopDisplayMode() may not work correctly on mobile platforms. Rather return the window size
  1694. return IntVector2(width_, height_);
  1695. #endif
  1696. }
  1697. unsigned Graphics::GetFormat(CompressedFormat format) const
  1698. {
  1699. switch (format)
  1700. {
  1701. case CF_RGBA:
  1702. return GL_RGBA;
  1703. case CF_DXT1:
  1704. return dxtTextureSupport_ ? GL_COMPRESSED_RGBA_S3TC_DXT1_EXT : 0;
  1705. #if !defined(GL_ES_VERSION_2_0) || defined(EMSCRIPTEN)
  1706. case CF_DXT3:
  1707. return dxtTextureSupport_ ? GL_COMPRESSED_RGBA_S3TC_DXT3_EXT : 0;
  1708. case CF_DXT5:
  1709. return dxtTextureSupport_ ? GL_COMPRESSED_RGBA_S3TC_DXT5_EXT : 0;
  1710. #endif
  1711. #ifdef GL_ES_VERSION_2_0
  1712. case CF_ETC1:
  1713. return etcTextureSupport_ ? GL_ETC1_RGB8_OES : 0;
  1714. case CF_PVRTC_RGB_2BPP:
  1715. return pvrtcTextureSupport_ ? COMPRESSED_RGB_PVRTC_2BPPV1_IMG : 0;
  1716. case CF_PVRTC_RGB_4BPP:
  1717. return pvrtcTextureSupport_ ? COMPRESSED_RGB_PVRTC_4BPPV1_IMG : 0;
  1718. case CF_PVRTC_RGBA_2BPP:
  1719. return pvrtcTextureSupport_ ? COMPRESSED_RGBA_PVRTC_2BPPV1_IMG : 0;
  1720. case CF_PVRTC_RGBA_4BPP:
  1721. return pvrtcTextureSupport_ ? COMPRESSED_RGBA_PVRTC_4BPPV1_IMG : 0;
  1722. #endif
  1723. default:
  1724. return 0;
  1725. }
  1726. }
  1727. unsigned Graphics::GetMaxBones()
  1728. {
  1729. #ifdef RPI
  1730. return 32;
  1731. #else
  1732. return gl3Support ? 128 : 64;
  1733. #endif
  1734. }
  1735. ShaderVariation* Graphics::GetShader(ShaderType type, const String& name, const String& defines) const
  1736. {
  1737. return GetShader(type, name.CString(), defines.CString());
  1738. }
  1739. ShaderVariation* Graphics::GetShader(ShaderType type, const char* name, const char* defines) const
  1740. {
  1741. if (lastShaderName_ != name || !lastShader_)
  1742. {
  1743. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1744. String fullShaderName = shaderPath_ + name + shaderExtension_;
  1745. // Try to reduce repeated error log prints because of missing shaders
  1746. if (lastShaderName_ == name && !cache->Exists(fullShaderName))
  1747. return 0;
  1748. lastShader_ = cache->GetResource<Shader>(fullShaderName);
  1749. lastShaderName_ = name;
  1750. }
  1751. return lastShader_ ? lastShader_->GetVariation(type, defines) : (ShaderVariation*)0;
  1752. }
  1753. VertexBuffer* Graphics::GetVertexBuffer(unsigned index) const
  1754. {
  1755. return index < MAX_VERTEX_STREAMS ? vertexBuffers_[index] : 0;
  1756. }
  1757. TextureUnit Graphics::GetTextureUnit(const String& name)
  1758. {
  1759. HashMap<String, TextureUnit>::Iterator i = textureUnits_.Find(name);
  1760. if (i != textureUnits_.End())
  1761. return i->second_;
  1762. else
  1763. return MAX_TEXTURE_UNITS;
  1764. }
  1765. const String& Graphics::GetTextureUnitName(TextureUnit unit)
  1766. {
  1767. for (HashMap<String, TextureUnit>::Iterator i = textureUnits_.Begin(); i != textureUnits_.End(); ++i)
  1768. {
  1769. if (i->second_ == unit)
  1770. return i->first_;
  1771. }
  1772. return String::EMPTY;
  1773. }
  1774. Texture* Graphics::GetTexture(unsigned index) const
  1775. {
  1776. return index < MAX_TEXTURE_UNITS ? textures_[index] : 0;
  1777. }
  1778. RenderSurface* Graphics::GetRenderTarget(unsigned index) const
  1779. {
  1780. return index < MAX_RENDERTARGETS ? renderTargets_[index] : 0;
  1781. }
  1782. IntVector2 Graphics::GetRenderTargetDimensions() const
  1783. {
  1784. int width, height;
  1785. if (renderTargets_[0])
  1786. {
  1787. width = renderTargets_[0]->GetWidth();
  1788. height = renderTargets_[0]->GetHeight();
  1789. }
  1790. else if (depthStencil_)
  1791. {
  1792. width = depthStencil_->GetWidth();
  1793. height = depthStencil_->GetHeight();
  1794. }
  1795. else
  1796. {
  1797. width = width_;
  1798. height = height_;
  1799. }
  1800. return IntVector2(width, height);
  1801. }
  1802. void Graphics::WindowResized()
  1803. {
  1804. if (!impl_->window_)
  1805. return;
  1806. int newWidth, newHeight;
  1807. SDL_GetWindowSize(impl_->window_, &newWidth, &newHeight);
  1808. if (newWidth == width_ && newHeight == height_)
  1809. return;
  1810. width_ = newWidth;
  1811. height_ = newHeight;
  1812. // Reset rendertargets and viewport for the new screen size. Also clean up any FBO's, as they may be screen size dependent
  1813. CleanupFramebuffers();
  1814. ResetRenderTargets();
  1815. LOGDEBUGF("Window was resized to %dx%d", width_, height_);
  1816. using namespace ScreenMode;
  1817. VariantMap& eventData = GetEventDataMap();
  1818. eventData[P_WIDTH] = width_;
  1819. eventData[P_HEIGHT] = height_;
  1820. eventData[P_FULLSCREEN] = fullscreen_;
  1821. eventData[P_RESIZABLE] = resizable_;
  1822. eventData[P_BORDERLESS] = borderless_;
  1823. SendEvent(E_SCREENMODE, eventData);
  1824. }
  1825. void Graphics::WindowMoved()
  1826. {
  1827. if (!impl_->window_ || fullscreen_)
  1828. return;
  1829. int newX, newY;
  1830. SDL_GetWindowPosition(impl_->window_, &newX, &newY);
  1831. if (newX == position_.x_ && newY == position_.y_)
  1832. return;
  1833. position_.x_ = newX;
  1834. position_.y_ = newY;
  1835. LOGDEBUGF("Window was moved to %d,%d", position_.x_, position_.y_);
  1836. using namespace WindowPos;
  1837. VariantMap& eventData = GetEventDataMap();
  1838. eventData[P_X] = position_.x_;
  1839. eventData[P_Y] = position_.y_;
  1840. SendEvent(E_WINDOWPOS, eventData);
  1841. }
  1842. void Graphics::AddGPUObject(GPUObject* object)
  1843. {
  1844. MutexLock lock(gpuObjectMutex_);
  1845. gpuObjects_.Push(object);
  1846. }
  1847. void Graphics::RemoveGPUObject(GPUObject* object)
  1848. {
  1849. MutexLock lock(gpuObjectMutex_);
  1850. gpuObjects_.Remove(object);
  1851. }
  1852. void* Graphics::ReserveScratchBuffer(unsigned size)
  1853. {
  1854. if (!size)
  1855. return 0;
  1856. if (size > maxScratchBufferRequest_)
  1857. maxScratchBufferRequest_ = size;
  1858. // First check for a free buffer that is large enough
  1859. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1860. {
  1861. if (!i->reserved_ && i->size_ >= size)
  1862. {
  1863. i->reserved_ = true;
  1864. return i->data_.Get();
  1865. }
  1866. }
  1867. // Then check if a free buffer can be resized
  1868. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1869. {
  1870. if (!i->reserved_)
  1871. {
  1872. i->data_ = new unsigned char[size];
  1873. i->size_ = size;
  1874. i->reserved_ = true;
  1875. return i->data_.Get();
  1876. }
  1877. }
  1878. // Finally allocate a new buffer
  1879. ScratchBuffer newBuffer;
  1880. newBuffer.data_ = new unsigned char[size];
  1881. newBuffer.size_ = size;
  1882. newBuffer.reserved_ = true;
  1883. scratchBuffers_.Push(newBuffer);
  1884. return newBuffer.data_.Get();
  1885. }
  1886. void Graphics::FreeScratchBuffer(void* buffer)
  1887. {
  1888. if (!buffer)
  1889. return;
  1890. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1891. {
  1892. if (i->reserved_ && i->data_.Get() == buffer)
  1893. {
  1894. i->reserved_ = false;
  1895. return;
  1896. }
  1897. }
  1898. LOGWARNING("Reserved scratch buffer " + ToStringHex((unsigned)(size_t)buffer) + " not found");
  1899. }
  1900. void Graphics::CleanupScratchBuffers()
  1901. {
  1902. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1903. {
  1904. if (!i->reserved_ && i->size_ > maxScratchBufferRequest_ * 2)
  1905. {
  1906. i->data_ = maxScratchBufferRequest_ > 0 ? new unsigned char[maxScratchBufferRequest_] : 0;
  1907. i->size_ = maxScratchBufferRequest_;
  1908. }
  1909. }
  1910. maxScratchBufferRequest_ = 0;
  1911. }
  1912. void Graphics::CleanupRenderSurface(RenderSurface* surface)
  1913. {
  1914. if (!surface)
  1915. return;
  1916. // Flush pending FBO changes first if any
  1917. PrepareDraw();
  1918. unsigned currentFBO = impl_->boundFBO_;
  1919. // Go through all FBOs and clean up the surface from them
  1920. for (HashMap<unsigned long long, FrameBufferObject>::Iterator i = impl_->frameBuffers_.Begin();
  1921. i != impl_->frameBuffers_.End(); ++i)
  1922. {
  1923. for (unsigned j = 0; j < MAX_RENDERTARGETS; ++j)
  1924. {
  1925. if (i->second_.colorAttachments_[j] == surface)
  1926. {
  1927. if (currentFBO != i->second_.fbo_)
  1928. {
  1929. BindFramebuffer(i->second_.fbo_);
  1930. currentFBO = i->second_.fbo_;
  1931. }
  1932. BindColorAttachment(j, GL_TEXTURE_2D, 0);
  1933. i->second_.colorAttachments_[j] = 0;
  1934. // Mark drawbuffer bits to need recalculation
  1935. i->second_.drawBuffers_ = M_MAX_UNSIGNED;
  1936. }
  1937. }
  1938. if (i->second_.depthAttachment_ == surface)
  1939. {
  1940. if (currentFBO != i->second_.fbo_)
  1941. {
  1942. BindFramebuffer(i->second_.fbo_);
  1943. currentFBO = i->second_.fbo_;
  1944. }
  1945. BindDepthAttachment(0, false);
  1946. BindStencilAttachment(0, false);
  1947. i->second_.depthAttachment_ = 0;
  1948. }
  1949. }
  1950. // Restore previously bound FBO now if needed
  1951. if (currentFBO != impl_->boundFBO_)
  1952. BindFramebuffer(impl_->boundFBO_);
  1953. }
  1954. void Graphics::CleanupShaderPrograms(ShaderVariation* variation)
  1955. {
  1956. for (ShaderProgramMap::Iterator i = shaderPrograms_.Begin(); i != shaderPrograms_.End();)
  1957. {
  1958. if (i->second_->GetVertexShader() == variation || i->second_->GetPixelShader() == variation)
  1959. i = shaderPrograms_.Erase(i);
  1960. else
  1961. ++i;
  1962. }
  1963. if (vertexShader_ == variation || pixelShader_ == variation)
  1964. shaderProgram_ = 0;
  1965. }
  1966. ConstantBuffer* Graphics::GetOrCreateConstantBuffer(unsigned bindingIndex, unsigned size)
  1967. {
  1968. unsigned key = (bindingIndex << 16) | size;
  1969. HashMap<unsigned, SharedPtr<ConstantBuffer> >::Iterator i = constantBuffers_.Find(key);
  1970. if (i == constantBuffers_.End())
  1971. {
  1972. i = constantBuffers_.Insert(MakePair(key, SharedPtr<ConstantBuffer>(new ConstantBuffer(context_))));
  1973. i->second_->SetSize(size);
  1974. }
  1975. return i->second_.Get();
  1976. }
  1977. void Graphics::Release(bool clearGPUObjects, bool closeWindow)
  1978. {
  1979. if (!impl_->window_)
  1980. return;
  1981. {
  1982. MutexLock lock(gpuObjectMutex_);
  1983. if (clearGPUObjects)
  1984. {
  1985. // Shutting down: release all GPU objects that still exist
  1986. // Shader programs are also GPU objects; clear them first to avoid list modification during iteration
  1987. shaderPrograms_.Clear();
  1988. for (PODVector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1989. (*i)->Release();
  1990. gpuObjects_.Clear();
  1991. }
  1992. else
  1993. {
  1994. // We are not shutting down, but recreating the context: mark GPU objects lost
  1995. for (PODVector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1996. (*i)->OnDeviceLost();
  1997. // In this case clear shader programs last so that they do not attempt to delete their OpenGL program
  1998. // from a context that may no longer exist
  1999. shaderPrograms_.Clear();
  2000. SendEvent(E_DEVICELOST);
  2001. }
  2002. }
  2003. CleanupFramebuffers();
  2004. depthTextures_.Clear();
  2005. // End fullscreen mode first to counteract transition and getting stuck problems on OS X
  2006. #if defined(__APPLE__) && !defined(IOS)
  2007. if (closeWindow && fullscreen_ && !externalWindow_)
  2008. SDL_SetWindowFullscreen(impl_->window_, SDL_FALSE);
  2009. #endif
  2010. if (impl_->context_)
  2011. {
  2012. // Do not log this message if we are exiting
  2013. if (!clearGPUObjects)
  2014. LOGINFO("OpenGL context lost");
  2015. SDL_GL_DeleteContext(impl_->context_);
  2016. impl_->context_ = 0;
  2017. }
  2018. if (closeWindow)
  2019. {
  2020. SDL_ShowCursor(SDL_TRUE);
  2021. // Do not destroy external window except when shutting down
  2022. if (!externalWindow_ || clearGPUObjects)
  2023. {
  2024. SDL_DestroyWindow(impl_->window_);
  2025. impl_->window_ = 0;
  2026. }
  2027. }
  2028. }
  2029. void Graphics::Restore()
  2030. {
  2031. if (!impl_->window_)
  2032. return;
  2033. #ifdef ANDROID
  2034. // On Android the context may be lost behind the scenes as the application is minimized
  2035. if (impl_->context_ && !SDL_GL_GetCurrentContext())
  2036. {
  2037. impl_->context_ = 0;
  2038. // Mark GPU objects lost without a current context. In this case they just mark their internal state lost
  2039. // but do not perform OpenGL commands to delete the GL objects
  2040. Release(false, false);
  2041. }
  2042. #endif
  2043. // Ensure first that the context exists
  2044. if (!impl_->context_)
  2045. {
  2046. impl_->context_ = SDL_GL_CreateContext(impl_->window_);
  2047. #ifndef GL_ES_VERSION_2_0
  2048. // If we're trying to use OpenGL 3, but context creation fails, retry with 2
  2049. if (!forceGL2_ && !impl_->context_)
  2050. {
  2051. forceGL2_ = true;
  2052. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
  2053. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
  2054. SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, 0);
  2055. impl_->context_ = SDL_GL_CreateContext(impl_->window_);
  2056. }
  2057. #endif
  2058. #ifdef IOS
  2059. glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&impl_->systemFBO_);
  2060. #endif
  2061. if (!impl_->context_)
  2062. {
  2063. LOGERROR("Could not create OpenGL context");
  2064. return;
  2065. }
  2066. // Clear cached extensions string from the previous context
  2067. extensions.Clear();
  2068. // Initialize OpenGL extensions library (desktop only)
  2069. #ifndef GL_ES_VERSION_2_0
  2070. GLenum err = glewInit();
  2071. if (GLEW_OK != err)
  2072. {
  2073. LOGERROR("Could not initialize OpenGL extensions");
  2074. return;
  2075. }
  2076. if (!forceGL2_ && GLEW_VERSION_3_2)
  2077. {
  2078. gl3Support = true;
  2079. apiName_ = "GL3";
  2080. // Create and bind a vertex array object that will stay in use throughout
  2081. unsigned vertexArrayObject;
  2082. glGenVertexArrays(1, &vertexArrayObject);
  2083. glBindVertexArray(vertexArrayObject);
  2084. }
  2085. else if (GLEW_VERSION_2_0)
  2086. {
  2087. if (!GLEW_EXT_framebuffer_object || !GLEW_EXT_packed_depth_stencil)
  2088. {
  2089. LOGERROR("EXT_framebuffer_object and EXT_packed_depth_stencil OpenGL extensions are required");
  2090. return;
  2091. }
  2092. gl3Support = false;
  2093. apiName_ = "GL2";
  2094. }
  2095. else
  2096. {
  2097. LOGERROR("OpenGL 2.0 is required");
  2098. return;
  2099. }
  2100. #endif
  2101. // Set up texture data read/write alignment. It is important that this is done before uploading any texture data
  2102. glPixelStorei(GL_PACK_ALIGNMENT, 1);
  2103. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  2104. ResetCachedState();
  2105. }
  2106. {
  2107. MutexLock lock(gpuObjectMutex_);
  2108. for (PODVector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  2109. (*i)->OnDeviceReset();
  2110. }
  2111. SendEvent(E_DEVICERESET);
  2112. }
  2113. void Graphics::Maximize()
  2114. {
  2115. if (!impl_->window_)
  2116. return;
  2117. SDL_MaximizeWindow(impl_->window_);
  2118. }
  2119. void Graphics::Minimize()
  2120. {
  2121. if (!impl_->window_)
  2122. return;
  2123. SDL_MinimizeWindow(impl_->window_);
  2124. }
  2125. void Graphics::MarkFBODirty()
  2126. {
  2127. impl_->fboDirty_ = true;
  2128. }
  2129. void Graphics::SetVBO(unsigned object)
  2130. {
  2131. if (impl_->boundVBO_ != object)
  2132. {
  2133. if (object)
  2134. glBindBuffer(GL_ARRAY_BUFFER, object);
  2135. impl_->boundVBO_ = object;
  2136. }
  2137. }
  2138. void Graphics::SetUBO(unsigned object)
  2139. {
  2140. #ifndef GL_ES_VERSION_2_0
  2141. if (impl_->boundUBO_ != object)
  2142. {
  2143. if (object)
  2144. glBindBuffer(GL_UNIFORM_BUFFER, object);
  2145. impl_->boundUBO_ = object;
  2146. }
  2147. #endif
  2148. }
  2149. unsigned Graphics::GetAlphaFormat()
  2150. {
  2151. #ifndef GL_ES_VERSION_2_0
  2152. // Alpha format is deprecated on OpenGL 3+
  2153. if (gl3Support)
  2154. return GL_R8;
  2155. #endif
  2156. return GL_ALPHA;
  2157. }
  2158. unsigned Graphics::GetLuminanceFormat()
  2159. {
  2160. #ifndef GL_ES_VERSION_2_0
  2161. // Luminance format is deprecated on OpenGL 3+
  2162. if (gl3Support)
  2163. return GL_R8;
  2164. #endif
  2165. return GL_LUMINANCE;
  2166. }
  2167. unsigned Graphics::GetLuminanceAlphaFormat()
  2168. {
  2169. #ifndef GL_ES_VERSION_2_0
  2170. // Luminance alpha format is deprecated on OpenGL 3+
  2171. if (gl3Support)
  2172. return GL_RG8;
  2173. #endif
  2174. return GL_LUMINANCE_ALPHA;
  2175. }
  2176. unsigned Graphics::GetRGBFormat()
  2177. {
  2178. return GL_RGB;
  2179. }
  2180. unsigned Graphics::GetRGBAFormat()
  2181. {
  2182. return GL_RGBA;
  2183. }
  2184. unsigned Graphics::GetRGBA16Format()
  2185. {
  2186. #ifndef GL_ES_VERSION_2_0
  2187. return GL_RGBA16;
  2188. #else
  2189. return GL_RGBA;
  2190. #endif
  2191. }
  2192. unsigned Graphics::GetRGBAFloat16Format()
  2193. {
  2194. #ifndef GL_ES_VERSION_2_0
  2195. return GL_RGBA16F_ARB;
  2196. #else
  2197. return GL_RGBA;
  2198. #endif
  2199. }
  2200. unsigned Graphics::GetRGBAFloat32Format()
  2201. {
  2202. #ifndef GL_ES_VERSION_2_0
  2203. return GL_RGBA32F_ARB;
  2204. #else
  2205. return GL_RGBA;
  2206. #endif
  2207. }
  2208. unsigned Graphics::GetRG16Format()
  2209. {
  2210. #ifndef GL_ES_VERSION_2_0
  2211. return GL_RG16;
  2212. #else
  2213. return GL_RGBA;
  2214. #endif
  2215. }
  2216. unsigned Graphics::GetRGFloat16Format()
  2217. {
  2218. #ifndef GL_ES_VERSION_2_0
  2219. return GL_RG16F;
  2220. #else
  2221. return GL_RGBA;
  2222. #endif
  2223. }
  2224. unsigned Graphics::GetRGFloat32Format()
  2225. {
  2226. #ifndef GL_ES_VERSION_2_0
  2227. return GL_RG32F;
  2228. #else
  2229. return GL_RGBA;
  2230. #endif
  2231. }
  2232. unsigned Graphics::GetFloat16Format()
  2233. {
  2234. #ifndef GL_ES_VERSION_2_0
  2235. return GL_R16F;
  2236. #else
  2237. return GL_LUMINANCE;
  2238. #endif
  2239. }
  2240. unsigned Graphics::GetFloat32Format()
  2241. {
  2242. #ifndef GL_ES_VERSION_2_0
  2243. return GL_R32F;
  2244. #else
  2245. return GL_LUMINANCE;
  2246. #endif
  2247. }
  2248. unsigned Graphics::GetLinearDepthFormat()
  2249. {
  2250. #ifndef GL_ES_VERSION_2_0
  2251. // OpenGL 3 can use different color attachment formats
  2252. if (gl3Support)
  2253. return GL_R32F;
  2254. #endif
  2255. // OpenGL 2 requires color attachments to have the same format, therefore encode deferred depth to RGBA manually
  2256. // if not using a readable hardware depth texture
  2257. return GL_RGBA;
  2258. }
  2259. unsigned Graphics::GetDepthStencilFormat()
  2260. {
  2261. #ifndef GL_ES_VERSION_2_0
  2262. return GL_DEPTH24_STENCIL8_EXT;
  2263. #else
  2264. return glesDepthStencilFormat;
  2265. #endif
  2266. }
  2267. unsigned Graphics::GetReadableDepthFormat()
  2268. {
  2269. #ifndef GL_ES_VERSION_2_0
  2270. return GL_DEPTH_COMPONENT24;
  2271. #else
  2272. return glesReadableDepthFormat;
  2273. #endif
  2274. }
  2275. unsigned Graphics::GetFormat(const String& formatName)
  2276. {
  2277. String nameLower = formatName.ToLower().Trimmed();
  2278. if (nameLower == "a")
  2279. return GetAlphaFormat();
  2280. if (nameLower == "l")
  2281. return GetLuminanceFormat();
  2282. if (nameLower == "la")
  2283. return GetLuminanceAlphaFormat();
  2284. if (nameLower == "rgb")
  2285. return GetRGBFormat();
  2286. if (nameLower == "rgba")
  2287. return GetRGBAFormat();
  2288. if (nameLower == "rgba16")
  2289. return GetRGBA16Format();
  2290. if (nameLower == "rgba16f")
  2291. return GetRGBAFloat16Format();
  2292. if (nameLower == "rgba32f")
  2293. return GetRGBAFloat32Format();
  2294. if (nameLower == "rg16")
  2295. return GetRG16Format();
  2296. if (nameLower == "rg16f")
  2297. return GetRGFloat16Format();
  2298. if (nameLower == "rg32f")
  2299. return GetRGFloat32Format();
  2300. if (nameLower == "r16f")
  2301. return GetFloat16Format();
  2302. if (nameLower == "r32f" || nameLower == "float")
  2303. return GetFloat32Format();
  2304. if (nameLower == "lineardepth" || nameLower == "depth")
  2305. return GetLinearDepthFormat();
  2306. if (nameLower == "d24s8")
  2307. return GetDepthStencilFormat();
  2308. if (nameLower == "readabledepth" || nameLower == "hwdepth")
  2309. return GetReadableDepthFormat();
  2310. return GetRGBFormat();
  2311. }
  2312. void Graphics::CreateWindowIcon()
  2313. {
  2314. if (windowIcon_)
  2315. {
  2316. SDL_Surface* surface = windowIcon_->GetSDLSurface();
  2317. if (surface)
  2318. {
  2319. SDL_SetWindowIcon(impl_->window_, surface);
  2320. SDL_FreeSurface(surface);
  2321. }
  2322. }
  2323. }
  2324. void Graphics::CheckFeatureSupport()
  2325. {
  2326. // Check supported features: light pre-pass, deferred rendering and hardware depth texture
  2327. lightPrepassSupport_ = false;
  2328. deferredSupport_ = false;
  2329. #ifndef GL_ES_VERSION_2_0
  2330. int numSupportedRTs = 1;
  2331. if (gl3Support)
  2332. {
  2333. // Work around GLEW failure to check extensions properly from a GL3 context
  2334. instancingSupport_ = true;
  2335. dxtTextureSupport_ = true;
  2336. anisotropySupport_ = true;
  2337. sRGBSupport_ = true;
  2338. sRGBWriteSupport_ = true;
  2339. glVertexAttribDivisor(ELEMENT_INSTANCEMATRIX1, 1);
  2340. glVertexAttribDivisor(ELEMENT_INSTANCEMATRIX2, 1);
  2341. glVertexAttribDivisor(ELEMENT_INSTANCEMATRIX3, 1);
  2342. glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &numSupportedRTs);
  2343. }
  2344. else
  2345. {
  2346. instancingSupport_ = GLEW_ARB_instanced_arrays != 0;
  2347. dxtTextureSupport_ = GLEW_EXT_texture_compression_s3tc != 0;
  2348. anisotropySupport_ = GLEW_EXT_texture_filter_anisotropic != 0;
  2349. sRGBSupport_ = GLEW_EXT_texture_sRGB != 0;
  2350. sRGBWriteSupport_ = GLEW_EXT_framebuffer_sRGB != 0;
  2351. // Set up instancing divisors if supported
  2352. if (instancingSupport_)
  2353. {
  2354. glVertexAttribDivisorARB(ELEMENT_INSTANCEMATRIX1, 1);
  2355. glVertexAttribDivisorARB(ELEMENT_INSTANCEMATRIX2, 1);
  2356. glVertexAttribDivisorARB(ELEMENT_INSTANCEMATRIX3, 1);
  2357. }
  2358. glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS_EXT, &numSupportedRTs);
  2359. }
  2360. // Must support 2 rendertargets for light pre-pass, and 4 for deferred
  2361. if (numSupportedRTs >= 2)
  2362. lightPrepassSupport_ = true;
  2363. if (numSupportedRTs >= 4)
  2364. deferredSupport_ = true;
  2365. #if defined(__APPLE__) && !defined(IOS)
  2366. // On OS X check for an Intel driver and use shadow map RGBA dummy color textures, because mixing
  2367. // depth-only FBO rendering and backbuffer rendering will bug, resulting in a black screen in full
  2368. // screen mode, and incomplete shadow maps in windowed mode
  2369. String renderer((const char*)glGetString(GL_RENDERER));
  2370. if (renderer.Contains("Intel", false))
  2371. dummyColorFormat_ = GetRGBAFormat();
  2372. #endif
  2373. #else
  2374. // Check for supported compressed texture formats
  2375. #ifdef EMSCRIPTEN
  2376. dxtTextureSupport_ = CheckExtension("WEBGL_compressed_texture_s3tc");
  2377. #else
  2378. dxtTextureSupport_ = CheckExtension("EXT_texture_compression_dxt1");
  2379. etcTextureSupport_ = CheckExtension("OES_compressed_ETC1_RGB8_texture");
  2380. pvrtcTextureSupport_ = CheckExtension("IMG_texture_compression_pvrtc");
  2381. #endif
  2382. // Check for best supported depth renderbuffer format for GLES2
  2383. if (CheckExtension("GL_OES_depth24"))
  2384. glesDepthStencilFormat = GL_DEPTH_COMPONENT24_OES;
  2385. if (CheckExtension("GL_OES_packed_depth_stencil"))
  2386. glesDepthStencilFormat = GL_DEPTH24_STENCIL8_OES;
  2387. #ifdef EMSCRIPTEN
  2388. if (!CheckExtension("WEBGL_depth_texture"))
  2389. #else
  2390. if (!CheckExtension("GL_OES_depth_texture"))
  2391. #endif
  2392. {
  2393. shadowMapFormat_ = 0;
  2394. hiresShadowMapFormat_ = 0;
  2395. glesReadableDepthFormat = 0;
  2396. }
  2397. else
  2398. {
  2399. #ifdef IOS
  2400. // iOS hack: depth renderbuffer seems to fail, so use depth textures for everything
  2401. // if supported
  2402. glesDepthStencilFormat = GL_DEPTH_COMPONENT;
  2403. #endif
  2404. shadowMapFormat_ = GL_DEPTH_COMPONENT;
  2405. hiresShadowMapFormat_ = 0;
  2406. // WebGL shadow map rendering seems to be extremely slow without an attached dummy color texture
  2407. #ifdef EMSCRIPTEN
  2408. dummyColorFormat_ = GetRGBAFormat();
  2409. #endif
  2410. }
  2411. #endif
  2412. }
  2413. void Graphics::PrepareDraw()
  2414. {
  2415. #ifndef GL_ES_VERSION_2_0
  2416. if (gl3Support)
  2417. {
  2418. for (PODVector<ConstantBuffer*>::Iterator i = dirtyConstantBuffers_.Begin(); i != dirtyConstantBuffers_.End(); ++i)
  2419. (*i)->Apply();
  2420. dirtyConstantBuffers_.Clear();
  2421. }
  2422. #endif
  2423. if (impl_->fboDirty_)
  2424. {
  2425. impl_->fboDirty_ = false;
  2426. // First check if no framebuffer is needed. In that case simply return to backbuffer rendering
  2427. bool noFbo = !depthStencil_;
  2428. if (noFbo)
  2429. {
  2430. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  2431. {
  2432. if (renderTargets_[i])
  2433. {
  2434. noFbo = false;
  2435. break;
  2436. }
  2437. }
  2438. }
  2439. if (noFbo)
  2440. {
  2441. if (impl_->boundFBO_ != impl_->systemFBO_)
  2442. {
  2443. BindFramebuffer(impl_->systemFBO_);
  2444. impl_->boundFBO_ = impl_->systemFBO_;
  2445. }
  2446. #ifndef GL_ES_VERSION_2_0
  2447. // Disable/enable sRGB write
  2448. if (sRGBWriteSupport_)
  2449. {
  2450. bool sRGBWrite = sRGB_;
  2451. if (sRGBWrite != impl_->sRGBWrite_)
  2452. {
  2453. if (sRGBWrite)
  2454. glEnable(GL_FRAMEBUFFER_SRGB_EXT);
  2455. else
  2456. glDisable(GL_FRAMEBUFFER_SRGB_EXT);
  2457. impl_->sRGBWrite_ = sRGBWrite;
  2458. }
  2459. }
  2460. #endif
  2461. return;
  2462. }
  2463. // Search for a new framebuffer based on format & size, or create new
  2464. IntVector2 rtSize = Graphics::GetRenderTargetDimensions();
  2465. unsigned format = 0;
  2466. if (renderTargets_[0])
  2467. format = renderTargets_[0]->GetParentTexture()->GetFormat();
  2468. else if (depthStencil_)
  2469. format = depthStencil_->GetParentTexture()->GetFormat();
  2470. unsigned long long fboKey = (rtSize.x_ << 16 | rtSize.y_) | (((unsigned long long)format) << 32);
  2471. HashMap<unsigned long long, FrameBufferObject>::Iterator i = impl_->frameBuffers_.Find(fboKey);
  2472. if (i == impl_->frameBuffers_.End())
  2473. {
  2474. FrameBufferObject newFbo;
  2475. newFbo.fbo_ = CreateFramebuffer();
  2476. i = impl_->frameBuffers_.Insert(MakePair(fboKey, newFbo));
  2477. }
  2478. if (impl_->boundFBO_ != i->second_.fbo_)
  2479. {
  2480. BindFramebuffer(i->second_.fbo_);
  2481. impl_->boundFBO_ = i->second_.fbo_;
  2482. }
  2483. #ifndef GL_ES_VERSION_2_0
  2484. // Setup readbuffers & drawbuffers if needed
  2485. if (i->second_.readBuffers_ != GL_NONE)
  2486. {
  2487. glReadBuffer(GL_NONE);
  2488. i->second_.readBuffers_ = GL_NONE;
  2489. }
  2490. // Calculate the bit combination of non-zero color rendertargets to first check if the combination changed
  2491. unsigned newDrawBuffers = 0;
  2492. for (unsigned j = 0; j < MAX_RENDERTARGETS; ++j)
  2493. {
  2494. if (renderTargets_[j])
  2495. newDrawBuffers |= 1 << j;
  2496. }
  2497. if (newDrawBuffers != i->second_.drawBuffers_)
  2498. {
  2499. // Check for no color rendertargets (depth rendering only)
  2500. if (!newDrawBuffers)
  2501. glDrawBuffer(GL_NONE);
  2502. else
  2503. {
  2504. int drawBufferIds[MAX_RENDERTARGETS];
  2505. unsigned drawBufferCount = 0;
  2506. for (unsigned j = 0; j < MAX_RENDERTARGETS; ++j)
  2507. {
  2508. if (renderTargets_[j])
  2509. {
  2510. if (!gl3Support)
  2511. drawBufferIds[drawBufferCount++] = GL_COLOR_ATTACHMENT0_EXT + j;
  2512. else
  2513. drawBufferIds[drawBufferCount++] = GL_COLOR_ATTACHMENT0 + j;
  2514. }
  2515. }
  2516. glDrawBuffers(drawBufferCount, (const GLenum*)drawBufferIds);
  2517. }
  2518. i->second_.drawBuffers_ = newDrawBuffers;
  2519. }
  2520. #endif
  2521. for (unsigned j = 0; j < MAX_RENDERTARGETS; ++j)
  2522. {
  2523. if (renderTargets_[j])
  2524. {
  2525. Texture* texture = renderTargets_[j]->GetParentTexture();
  2526. // If texture's parameters are dirty, update before attaching
  2527. if (texture->GetParametersDirty())
  2528. {
  2529. SetTextureForUpdate(texture);
  2530. texture->UpdateParameters();
  2531. SetTexture(0, 0);
  2532. }
  2533. if (i->second_.colorAttachments_[j] != renderTargets_[j])
  2534. {
  2535. BindColorAttachment(j, renderTargets_[j]->GetTarget(), texture->GetGPUObject());
  2536. i->second_.colorAttachments_[j] = renderTargets_[j];
  2537. }
  2538. }
  2539. else
  2540. {
  2541. if (i->second_.colorAttachments_[j])
  2542. {
  2543. BindColorAttachment(j, GL_TEXTURE_2D, 0);
  2544. i->second_.colorAttachments_[j] = 0;
  2545. }
  2546. }
  2547. }
  2548. if (depthStencil_)
  2549. {
  2550. // Bind either a renderbuffer or a depth texture, depending on what is available
  2551. Texture* texture = depthStencil_->GetParentTexture();
  2552. #ifndef GL_ES_VERSION_2_0
  2553. bool hasStencil = texture->GetFormat() == GL_DEPTH24_STENCIL8_EXT;
  2554. #else
  2555. bool hasStencil = texture->GetFormat() == GL_DEPTH24_STENCIL8_OES;
  2556. #endif
  2557. unsigned renderBufferID = depthStencil_->GetRenderBuffer();
  2558. if (!renderBufferID)
  2559. {
  2560. // If texture's parameters are dirty, update before attaching
  2561. if (texture->GetParametersDirty())
  2562. {
  2563. SetTextureForUpdate(texture);
  2564. texture->UpdateParameters();
  2565. SetTexture(0, 0);
  2566. }
  2567. if (i->second_.depthAttachment_ != depthStencil_)
  2568. {
  2569. BindDepthAttachment(texture->GetGPUObject(), false);
  2570. BindStencilAttachment(hasStencil ? texture->GetGPUObject() : 0, false);
  2571. i->second_.depthAttachment_ = depthStencil_;
  2572. }
  2573. }
  2574. else
  2575. {
  2576. if (i->second_.depthAttachment_ != depthStencil_)
  2577. {
  2578. BindDepthAttachment(renderBufferID, true);
  2579. BindStencilAttachment(hasStencil ? renderBufferID : 0, true);
  2580. i->second_.depthAttachment_ = depthStencil_;
  2581. }
  2582. }
  2583. }
  2584. else
  2585. {
  2586. if (i->second_.depthAttachment_)
  2587. {
  2588. BindDepthAttachment(0, false);
  2589. BindStencilAttachment(0, false);
  2590. i->second_.depthAttachment_ = 0;
  2591. }
  2592. }
  2593. #ifndef GL_ES_VERSION_2_0
  2594. // Disable/enable sRGB write
  2595. if (sRGBWriteSupport_)
  2596. {
  2597. bool sRGBWrite = renderTargets_[0] ? renderTargets_[0]->GetParentTexture()->GetSRGB() : sRGB_;
  2598. if (sRGBWrite != impl_->sRGBWrite_)
  2599. {
  2600. if (sRGBWrite)
  2601. glEnable(GL_FRAMEBUFFER_SRGB_EXT);
  2602. else
  2603. glDisable(GL_FRAMEBUFFER_SRGB_EXT);
  2604. impl_->sRGBWrite_ = sRGBWrite;
  2605. }
  2606. }
  2607. #endif
  2608. }
  2609. }
  2610. void Graphics::CleanupFramebuffers()
  2611. {
  2612. if (!IsDeviceLost())
  2613. {
  2614. BindFramebuffer(impl_->systemFBO_);
  2615. impl_->boundFBO_ = impl_->systemFBO_;
  2616. impl_->fboDirty_ = true;
  2617. for (HashMap<unsigned long long, FrameBufferObject>::Iterator i = impl_->frameBuffers_.Begin(); i !=
  2618. impl_->frameBuffers_.End(); ++i)
  2619. DeleteFramebuffer(i->second_.fbo_);
  2620. }
  2621. else
  2622. impl_->boundFBO_ = 0;
  2623. impl_->frameBuffers_.Clear();
  2624. }
  2625. void Graphics::ResetCachedState()
  2626. {
  2627. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  2628. {
  2629. vertexBuffers_[i] = 0;
  2630. elementMasks_[i] = 0;
  2631. }
  2632. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  2633. {
  2634. textures_[i] = 0;
  2635. textureTypes_[i] = 0;
  2636. }
  2637. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  2638. renderTargets_[i] = 0;
  2639. depthStencil_ = 0;
  2640. viewport_ = IntRect(0, 0, 0, 0);
  2641. indexBuffer_ = 0;
  2642. vertexShader_ = 0;
  2643. pixelShader_ = 0;
  2644. shaderProgram_ = 0;
  2645. blendMode_ = BLEND_REPLACE;
  2646. textureAnisotropy_ = 1;
  2647. colorWrite_ = true;
  2648. cullMode_ = CULL_NONE;
  2649. constantDepthBias_ = 0.0f;
  2650. slopeScaledDepthBias_ = 0.0f;
  2651. depthTestMode_ = CMP_ALWAYS;
  2652. depthWrite_ = false;
  2653. fillMode_ = FILL_SOLID;
  2654. scissorTest_ = false;
  2655. scissorRect_ = IntRect::ZERO;
  2656. stencilTest_ = false;
  2657. stencilTestMode_ = CMP_ALWAYS;
  2658. stencilPass_ = OP_KEEP;
  2659. stencilFail_ = OP_KEEP;
  2660. stencilZFail_ = OP_KEEP;
  2661. stencilRef_ = 0;
  2662. stencilCompareMask_ = M_MAX_UNSIGNED;
  2663. stencilWriteMask_ = M_MAX_UNSIGNED;
  2664. useClipPlane_ = false;
  2665. lastInstanceOffset_ = 0;
  2666. impl_->activeTexture_ = 0;
  2667. impl_->enabledAttributes_ = 0;
  2668. impl_->boundFBO_ = impl_->systemFBO_;
  2669. impl_->boundVBO_ = 0;
  2670. impl_->boundUBO_ = 0;
  2671. impl_->sRGBWrite_ = false;
  2672. // Set initial state to match Direct3D
  2673. if (impl_->context_)
  2674. {
  2675. glEnable(GL_DEPTH_TEST);
  2676. SetCullMode(CULL_CCW);
  2677. SetDepthTest(CMP_LESSEQUAL);
  2678. SetDepthWrite(true);
  2679. }
  2680. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS * 2; ++i)
  2681. currentConstantBuffers_[i] = 0;
  2682. dirtyConstantBuffers_.Clear();
  2683. }
  2684. void Graphics::SetTextureUnitMappings()
  2685. {
  2686. textureUnits_["DiffMap"] = TU_DIFFUSE;
  2687. textureUnits_["DiffCubeMap"] = TU_DIFFUSE;
  2688. textureUnits_["AlbedoBuffer"] = TU_ALBEDOBUFFER;
  2689. textureUnits_["NormalMap"] = TU_NORMAL;
  2690. textureUnits_["NormalBuffer"] = TU_NORMALBUFFER;
  2691. textureUnits_["SpecMap"] = TU_SPECULAR;
  2692. textureUnits_["EmissiveMap"] = TU_EMISSIVE;
  2693. textureUnits_["EnvMap"] = TU_ENVIRONMENT;
  2694. textureUnits_["EnvCubeMap"] = TU_ENVIRONMENT;
  2695. textureUnits_["LightRampMap"] = TU_LIGHTRAMP;
  2696. textureUnits_["LightSpotMap"] = TU_LIGHTSHAPE;
  2697. textureUnits_["LightCubeMap"] = TU_LIGHTSHAPE;
  2698. textureUnits_["ShadowMap"] = TU_SHADOWMAP;
  2699. #ifdef DESKTOP_GRAPHICS
  2700. textureUnits_["VolumeMap"] = TU_VOLUMEMAP;
  2701. textureUnits_["FaceSelectCubeMap"] = TU_FACESELECT;
  2702. textureUnits_["IndirectionCubeMap"] = TU_INDIRECTION;
  2703. textureUnits_["DepthBuffer"] = TU_DEPTHBUFFER;
  2704. textureUnits_["LightBuffer"] = TU_LIGHTBUFFER;
  2705. textureUnits_["ZoneCubeMap"] = TU_ZONE;
  2706. textureUnits_["ZoneVolumeMap"] = TU_ZONE;
  2707. #endif
  2708. }
  2709. unsigned Graphics::CreateFramebuffer()
  2710. {
  2711. unsigned newFbo = 0;
  2712. #ifndef GL_ES_VERSION_2_0
  2713. if (!gl3Support)
  2714. glGenFramebuffersEXT(1, &newFbo);
  2715. else
  2716. #endif
  2717. glGenFramebuffers(1, &newFbo);
  2718. return newFbo;
  2719. }
  2720. void Graphics::DeleteFramebuffer(unsigned fbo)
  2721. {
  2722. #ifndef GL_ES_VERSION_2_0
  2723. if (!gl3Support)
  2724. glDeleteFramebuffersEXT(1, &fbo);
  2725. else
  2726. #endif
  2727. glDeleteFramebuffers(1, &fbo);
  2728. }
  2729. void Graphics::BindFramebuffer(unsigned fbo)
  2730. {
  2731. #ifndef GL_ES_VERSION_2_0
  2732. if (!gl3Support)
  2733. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo);
  2734. else
  2735. #endif
  2736. glBindFramebuffer(GL_FRAMEBUFFER, fbo);
  2737. }
  2738. void Graphics::BindColorAttachment(unsigned index, unsigned target, unsigned object)
  2739. {
  2740. #ifndef GL_ES_VERSION_2_0
  2741. if (!gl3Support)
  2742. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + index, target, object, 0);
  2743. else
  2744. #endif
  2745. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + index, target, object, 0);
  2746. }
  2747. void Graphics::BindDepthAttachment(unsigned object, bool isRenderBuffer)
  2748. {
  2749. if (!object)
  2750. isRenderBuffer = false;
  2751. #ifndef GL_ES_VERSION_2_0
  2752. if (!gl3Support)
  2753. {
  2754. if (!isRenderBuffer)
  2755. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, object, 0);
  2756. else
  2757. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, object);
  2758. }
  2759. else
  2760. #endif
  2761. {
  2762. if (!isRenderBuffer)
  2763. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, object, 0);
  2764. else
  2765. glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, object);
  2766. }
  2767. }
  2768. void Graphics::BindStencilAttachment(unsigned object, bool isRenderBuffer)
  2769. {
  2770. if (!object)
  2771. isRenderBuffer = false;
  2772. #ifndef GL_ES_VERSION_2_0
  2773. if (!gl3Support)
  2774. {
  2775. if (!isRenderBuffer)
  2776. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, object, 0);
  2777. else
  2778. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, object);
  2779. }
  2780. else
  2781. #endif
  2782. {
  2783. if (!isRenderBuffer)
  2784. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, object, 0);
  2785. else
  2786. glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, object);
  2787. }
  2788. }
  2789. bool Graphics::CheckFramebuffer()
  2790. {
  2791. #ifndef GL_ES_VERSION_2_0
  2792. if (!gl3Support)
  2793. return glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT) == GL_FRAMEBUFFER_COMPLETE_EXT;
  2794. else
  2795. #endif
  2796. return glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE;
  2797. }
  2798. void RegisterGraphicsLibrary(Context* context)
  2799. {
  2800. Material::RegisterObject(context);
  2801. Shader::RegisterObject(context);
  2802. Technique::RegisterObject(context);
  2803. Texture2D::RegisterObject(context);
  2804. Texture3D::RegisterObject(context);
  2805. TextureCube::RegisterObject(context);
  2806. Camera::RegisterObject(context);
  2807. Drawable::RegisterObject(context);
  2808. Light::RegisterObject(context);
  2809. DebugRenderer::RegisterObject(context);
  2810. Octree::RegisterObject(context);
  2811. Zone::RegisterObject(context);
  2812. }
  2813. }