OGLGraphics.cpp 95 KB

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