CmGLRenderSystem.cpp 92 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162
  1. /*
  2. -----------------------------------------------------------------------------
  3. This source file is part of OGRE
  4. (Object-oriented Graphics Rendering Engine)
  5. For the latest info, see http://www.ogre3d.org
  6. Copyright (c) 2000-2011 Torus Knot Software Ltd
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in
  14. all copies or substantial portions of the Software.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. THE SOFTWARE.s
  22. -----------------------------------------------------------------------------
  23. */
  24. #include "CmGLRenderSystem.h"
  25. #include "CmRenderSystem.h"
  26. #include "CmCamera.h"
  27. #include "CmGLTextureManager.h"
  28. #include "CmGLHardwareVertexBuffer.h"
  29. #include "CmGLHardwareIndexBuffer.h"
  30. #include "CmGLDefaultHardwareBufferManager.h"
  31. #include "CmGLUtil.h"
  32. #include "CmGLGpuProgram.h"
  33. #include "ATI_FS_GLGpuProgram.h"
  34. #include "CmGLGpuProgramManager.h"
  35. #include "CmException.h"
  36. #include "CmGLSLExtSupport.h"
  37. #include "CmGLHardwareOcclusionQuery.h"
  38. #include "CmGLContext.h"
  39. #include "CmGLFBORenderTexture.h"
  40. #include "CmGLPBRenderTexture.h"
  41. // Convenience macro from ARB_vertex_buffer_object spec
  42. #define VBO_BUFFER_OFFSET(i) ((char *)NULL + (i))
  43. #if CM_THREAD_SUPPORT != 1
  44. GLenum glewContextInit (CamelotEngine::GLSupport *glSupport);
  45. #endif
  46. namespace CamelotEngine {
  47. // Callback function used when registering GLGpuPrograms
  48. GpuProgram* createGLArbGpuProgram(GpuProgramType gptype, const String& syntaxCode)
  49. {
  50. GLArbGpuProgram* ret = new GLArbGpuProgram();
  51. ret->setType(gptype);
  52. ret->setSyntaxCode(syntaxCode);
  53. return ret;
  54. }
  55. GpuProgram* createGL_ATI_FS_GpuProgram(GpuProgramType gptype, const String& syntaxCode)
  56. {
  57. ATI_FS_GLGpuProgram* ret = new ATI_FS_GLGpuProgram();
  58. ret->setType(gptype);
  59. ret->setSyntaxCode(syntaxCode);
  60. return ret;
  61. }
  62. GLRenderSystem::GLRenderSystem()
  63. : mDepthWrite(true), mStencilMask(0xFFFFFFFF),
  64. mGLSLProgramFactory(0),
  65. mActiveTextureUnit(0)
  66. {
  67. size_t i;
  68. // Get our GLSupport
  69. mGLSupport = getGLSupport();
  70. mWorldMatrix = Matrix4::IDENTITY;
  71. mViewMatrix = Matrix4::IDENTITY;
  72. initConfigOptions();
  73. mColourWrite[0] = mColourWrite[1] = mColourWrite[2] = mColourWrite[3] = true;
  74. for (i = 0; i < CM_MAX_TEXTURE_LAYERS; i++)
  75. {
  76. // Dummy value
  77. mTextureCoordIndex[i] = 99;
  78. mTextureTypes[i] = 0;
  79. }
  80. mActiveRenderTarget = 0;
  81. mCurrentContext = 0;
  82. mMainContext = 0;
  83. mGLInitialised = false;
  84. mCurrentLights = 0;
  85. mMinFilter = FO_LINEAR;
  86. mMipFilter = FO_POINT;
  87. mCurrentVertexProgram = 0;
  88. mCurrentGeometryProgram = 0;
  89. mCurrentFragmentProgram = 0;
  90. }
  91. GLRenderSystem::~GLRenderSystem()
  92. {
  93. shutdown();
  94. // Destroy render windows
  95. RenderTargetMap::iterator i;
  96. for (i = mRenderTargets.begin(); i != mRenderTargets.end(); ++i)
  97. {
  98. delete i->second;
  99. }
  100. mRenderTargets.clear();
  101. if(mGLSupport)
  102. delete mGLSupport;
  103. }
  104. const String& GLRenderSystem::getName(void) const
  105. {
  106. static String strName("OpenGL Rendering Subsystem");
  107. return strName;
  108. }
  109. void GLRenderSystem::initConfigOptions(void)
  110. {
  111. mGLSupport->addConfig();
  112. }
  113. ConfigOptionMap& GLRenderSystem::getConfigOptions(void)
  114. {
  115. return mGLSupport->getConfigOptions();
  116. }
  117. void GLRenderSystem::setConfigOption(const String &name, const String &value)
  118. {
  119. mGLSupport->setConfigOption(name, value);
  120. }
  121. String GLRenderSystem::validateConfigOptions(void)
  122. {
  123. // XXX Return an error string if something is invalid
  124. return mGLSupport->validateConfig();
  125. }
  126. RenderWindow* GLRenderSystem::_initialise(bool autoCreateWindow, const String& windowTitle)
  127. {
  128. mGLSupport->start();
  129. RenderWindow* autoWindow = mGLSupport->createWindow(autoCreateWindow, this, windowTitle);
  130. RenderSystem::_initialise(autoCreateWindow, windowTitle);
  131. return autoWindow;
  132. }
  133. RenderSystemCapabilities* GLRenderSystem::createRenderSystemCapabilities() const
  134. {
  135. RenderSystemCapabilities* rsc = new RenderSystemCapabilities();
  136. rsc->setCategoryRelevant(CAPS_CATEGORY_GL, true);
  137. rsc->setDriverVersion(mDriverVersion);
  138. const char* deviceName = (const char*)glGetString(GL_RENDERER);
  139. const char* vendorName = (const char*)glGetString(GL_VENDOR);
  140. rsc->setDeviceName(deviceName);
  141. rsc->setRenderSystemName(getName());
  142. // determine vendor
  143. if (strstr(vendorName, "NVIDIA"))
  144. rsc->setVendor(GPU_NVIDIA);
  145. else if (strstr(vendorName, "ATI"))
  146. rsc->setVendor(GPU_ATI);
  147. else if (strstr(vendorName, "Intel"))
  148. rsc->setVendor(GPU_INTEL);
  149. else if (strstr(vendorName, "S3"))
  150. rsc->setVendor(GPU_S3);
  151. else if (strstr(vendorName, "Matrox"))
  152. rsc->setVendor(GPU_MATROX);
  153. else if (strstr(vendorName, "3DLabs"))
  154. rsc->setVendor(GPU_3DLABS);
  155. else if (strstr(vendorName, "SiS"))
  156. rsc->setVendor(GPU_SIS);
  157. else
  158. rsc->setVendor(GPU_UNKNOWN);
  159. // Supports fixed-function
  160. rsc->setCapability(RSC_FIXED_FUNCTION);
  161. // Check for hardware mipmapping support.
  162. if(GLEW_VERSION_1_4 || GLEW_SGIS_generate_mipmap)
  163. {
  164. bool disableAutoMip = false;
  165. #if CM_PLATFORM == CM_PLATFORM_APPLE || CM_PLATFORM == CM_PLATFORM_LINUX
  166. // Apple & Linux ATI drivers have faults in hardware mipmap generation
  167. if (rsc->getVendor() == GPU_ATI)
  168. disableAutoMip = true;
  169. #endif
  170. // The Intel 915G frequently corrupts textures when using hardware mip generation
  171. // I'm not currently sure how many generations of hardware this affects,
  172. // so for now, be safe.
  173. if (rsc->getVendor() == GPU_INTEL)
  174. disableAutoMip = true;
  175. // SiS chipsets also seem to have problems with this
  176. if (rsc->getVendor() == GPU_SIS)
  177. disableAutoMip = true;
  178. if (!disableAutoMip)
  179. rsc->setCapability(RSC_AUTOMIPMAP);
  180. }
  181. // Check for blending support
  182. if(GLEW_VERSION_1_3 ||
  183. GLEW_ARB_texture_env_combine ||
  184. GLEW_EXT_texture_env_combine)
  185. {
  186. rsc->setCapability(RSC_BLENDING);
  187. }
  188. // Check for Multitexturing support and set number of texture units
  189. if(GLEW_VERSION_1_3 ||
  190. GLEW_ARB_multitexture)
  191. {
  192. GLint units;
  193. glGetIntegerv( GL_MAX_TEXTURE_UNITS, &units );
  194. if (GLEW_ARB_fragment_program)
  195. {
  196. // Also check GL_MAX_TEXTURE_IMAGE_UNITS_ARB since NV at least
  197. // only increased this on the FX/6x00 series
  198. GLint arbUnits;
  199. glGetIntegerv( GL_MAX_TEXTURE_IMAGE_UNITS_ARB, &arbUnits );
  200. if (arbUnits > units)
  201. units = arbUnits;
  202. }
  203. rsc->setNumTextureUnits(units);
  204. }
  205. else
  206. {
  207. // If no multitexture support then set one texture unit
  208. rsc->setNumTextureUnits(1);
  209. }
  210. // Check for Anisotropy support
  211. if(GLEW_EXT_texture_filter_anisotropic)
  212. {
  213. rsc->setCapability(RSC_ANISOTROPY);
  214. }
  215. // Check for DOT3 support
  216. if(GLEW_VERSION_1_3 ||
  217. GLEW_ARB_texture_env_dot3 ||
  218. GLEW_EXT_texture_env_dot3)
  219. {
  220. rsc->setCapability(RSC_DOT3);
  221. }
  222. // Check for cube mapping
  223. if(GLEW_VERSION_1_3 ||
  224. GLEW_ARB_texture_cube_map ||
  225. GLEW_EXT_texture_cube_map)
  226. {
  227. rsc->setCapability(RSC_CUBEMAPPING);
  228. }
  229. // Point sprites
  230. if (GLEW_VERSION_2_0 || GLEW_ARB_point_sprite)
  231. {
  232. rsc->setCapability(RSC_POINT_SPRITES);
  233. }
  234. // Check for point parameters
  235. if (GLEW_VERSION_1_4)
  236. {
  237. rsc->setCapability(RSC_POINT_EXTENDED_PARAMETERS);
  238. }
  239. if (GLEW_ARB_point_parameters)
  240. {
  241. rsc->setCapability(RSC_POINT_EXTENDED_PARAMETERS_ARB);
  242. }
  243. if (GLEW_EXT_point_parameters)
  244. {
  245. rsc->setCapability(RSC_POINT_EXTENDED_PARAMETERS_EXT);
  246. }
  247. // Check for hardware stencil support and set bit depth
  248. GLint stencil;
  249. glGetIntegerv(GL_STENCIL_BITS,&stencil);
  250. if(stencil)
  251. {
  252. rsc->setCapability(RSC_HWSTENCIL);
  253. rsc->setStencilBufferBitDepth(stencil);
  254. }
  255. if(GLEW_VERSION_1_5 || GLEW_ARB_vertex_buffer_object)
  256. {
  257. if (!GLEW_ARB_vertex_buffer_object)
  258. {
  259. rsc->setCapability(RSC_GL1_5_NOVBO);
  260. }
  261. rsc->setCapability(RSC_VBO);
  262. }
  263. if(GLEW_ARB_vertex_program)
  264. {
  265. rsc->setCapability(RSC_VERTEX_PROGRAM);
  266. // Vertex Program Properties
  267. rsc->setVertexProgramConstantBoolCount(0);
  268. rsc->setVertexProgramConstantIntCount(0);
  269. GLint floatConstantCount;
  270. glGetProgramivARB(GL_VERTEX_PROGRAM_ARB, GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB, &floatConstantCount);
  271. rsc->setVertexProgramConstantFloatCount(floatConstantCount);
  272. rsc->addShaderProfile("arbvp1");
  273. if (GLEW_NV_vertex_program2_option)
  274. {
  275. rsc->addShaderProfile("vp30");
  276. }
  277. if (GLEW_NV_vertex_program3)
  278. {
  279. rsc->addShaderProfile("vp40");
  280. }
  281. if (GLEW_NV_vertex_program4)
  282. {
  283. rsc->addShaderProfile("gp4vp");
  284. rsc->addShaderProfile("gpu_vp");
  285. }
  286. }
  287. if (GLEW_NV_register_combiners2 &&
  288. GLEW_NV_texture_shader)
  289. {
  290. rsc->setCapability(RSC_FRAGMENT_PROGRAM);
  291. }
  292. // NFZ - check for ATI fragment shader support
  293. if (GLEW_ATI_fragment_shader)
  294. {
  295. rsc->setCapability(RSC_FRAGMENT_PROGRAM);
  296. // no boolean params allowed
  297. rsc->setFragmentProgramConstantBoolCount(0);
  298. // no integer params allowed
  299. rsc->setFragmentProgramConstantIntCount(0);
  300. // only 8 Vector4 constant floats supported
  301. rsc->setFragmentProgramConstantFloatCount(8);
  302. rsc->addShaderProfile("ps_1_4");
  303. rsc->addShaderProfile("ps_1_3");
  304. rsc->addShaderProfile("ps_1_2");
  305. rsc->addShaderProfile("ps_1_1");
  306. }
  307. if (GLEW_ARB_fragment_program)
  308. {
  309. rsc->setCapability(RSC_FRAGMENT_PROGRAM);
  310. // Fragment Program Properties
  311. rsc->setFragmentProgramConstantBoolCount(0);
  312. rsc->setFragmentProgramConstantIntCount(0);
  313. GLint floatConstantCount;
  314. glGetProgramivARB(GL_FRAGMENT_PROGRAM_ARB, GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB, &floatConstantCount);
  315. rsc->setFragmentProgramConstantFloatCount(floatConstantCount);
  316. rsc->addShaderProfile("arbfp1");
  317. if (GLEW_NV_fragment_program_option)
  318. {
  319. rsc->addShaderProfile("fp30");
  320. }
  321. if (GLEW_NV_fragment_program2)
  322. {
  323. rsc->addShaderProfile("fp40");
  324. }
  325. }
  326. // NFZ - Check if GLSL is supported
  327. if ( GLEW_VERSION_2_0 ||
  328. (GLEW_ARB_shading_language_100 &&
  329. GLEW_ARB_shader_objects &&
  330. GLEW_ARB_fragment_shader &&
  331. GLEW_ARB_vertex_shader) )
  332. {
  333. rsc->addShaderProfile("glsl");
  334. }
  335. // Check if geometry shaders are supported
  336. if (GLEW_VERSION_2_0 &&
  337. GLEW_EXT_geometry_shader4)
  338. {
  339. rsc->setCapability(RSC_GEOMETRY_PROGRAM);
  340. rsc->addShaderProfile("nvgp4");
  341. //Also add the CG profiles
  342. rsc->addShaderProfile("gpu_gp");
  343. rsc->addShaderProfile("gp4gp");
  344. rsc->setGeometryProgramConstantBoolCount(0);
  345. rsc->setGeometryProgramConstantIntCount(0);
  346. GLint floatConstantCount = 0;
  347. glGetIntegerv(GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_EXT, &floatConstantCount);
  348. rsc->setGeometryProgramConstantFloatCount(floatConstantCount);
  349. GLint maxOutputVertices;
  350. glGetIntegerv(GL_MAX_GEOMETRY_OUTPUT_VERTICES_EXT,&maxOutputVertices);
  351. rsc->setGeometryProgramNumOutputVertices(maxOutputVertices);
  352. }
  353. //Check if render to vertex buffer (transform feedback in OpenGL)
  354. if (GLEW_VERSION_2_0 &&
  355. GLEW_NV_transform_feedback)
  356. {
  357. rsc->setCapability(RSC_HWRENDER_TO_VERTEX_BUFFER);
  358. }
  359. // Check for texture compression
  360. if(GLEW_VERSION_1_3 || GLEW_ARB_texture_compression)
  361. {
  362. rsc->setCapability(RSC_TEXTURE_COMPRESSION);
  363. // Check for dxt compression
  364. if(GLEW_EXT_texture_compression_s3tc)
  365. {
  366. #if defined(__APPLE__) && defined(__PPC__)
  367. // Apple on ATI & PPC has errors in DXT
  368. if (mGLSupport->getGLVendor().find("ATI") == std::string::npos)
  369. #endif
  370. rsc->setCapability(RSC_TEXTURE_COMPRESSION_DXT);
  371. }
  372. // Check for vtc compression
  373. if(GLEW_NV_texture_compression_vtc)
  374. {
  375. rsc->setCapability(RSC_TEXTURE_COMPRESSION_VTC);
  376. }
  377. }
  378. // Scissor test is standard in GL 1.2 (is it emulated on some cards though?)
  379. rsc->setCapability(RSC_SCISSOR_TEST);
  380. // As are user clipping planes
  381. rsc->setCapability(RSC_USER_CLIP_PLANES);
  382. // 2-sided stencil?
  383. if (GLEW_VERSION_2_0 || GLEW_EXT_stencil_two_side)
  384. {
  385. rsc->setCapability(RSC_TWO_SIDED_STENCIL);
  386. }
  387. // stencil wrapping?
  388. if (GLEW_VERSION_1_4 || GLEW_EXT_stencil_wrap)
  389. {
  390. rsc->setCapability(RSC_STENCIL_WRAP);
  391. }
  392. // Check for hardware occlusion support
  393. if(GLEW_VERSION_1_5 || GLEW_ARB_occlusion_query)
  394. {
  395. // Some buggy driver claim that it is GL 1.5 compliant and
  396. // not support ARB_occlusion_query
  397. if (!GLEW_ARB_occlusion_query)
  398. {
  399. rsc->setCapability(RSC_GL1_5_NOHWOCCLUSION);
  400. }
  401. rsc->setCapability(RSC_HWOCCLUSION);
  402. }
  403. else if (GLEW_NV_occlusion_query)
  404. {
  405. // Support NV extension too for old hardware
  406. rsc->setCapability(RSC_HWOCCLUSION);
  407. }
  408. // UBYTE4 always supported
  409. rsc->setCapability(RSC_VERTEX_FORMAT_UBYTE4);
  410. // Infinite far plane always supported
  411. rsc->setCapability(RSC_INFINITE_FAR_PLANE);
  412. // Check for non-power-of-2 texture support
  413. if(GLEW_ARB_texture_non_power_of_two)
  414. {
  415. rsc->setCapability(RSC_NON_POWER_OF_2_TEXTURES);
  416. }
  417. // Check for Float textures
  418. if(GLEW_ATI_texture_float || GLEW_ARB_texture_float)
  419. {
  420. rsc->setCapability(RSC_TEXTURE_FLOAT);
  421. }
  422. // 3D textures should be supported by GL 1.2, which is our minimum version
  423. rsc->setCapability(RSC_TEXTURE_3D);
  424. // Check for framebuffer object extension
  425. if(GLEW_EXT_framebuffer_object)
  426. {
  427. // Probe number of draw buffers
  428. // Only makes sense with FBO support, so probe here
  429. if(GLEW_VERSION_2_0 ||
  430. GLEW_ARB_draw_buffers ||
  431. GLEW_ATI_draw_buffers)
  432. {
  433. GLint buffers;
  434. glGetIntegerv(GL_MAX_DRAW_BUFFERS_ARB, &buffers);
  435. rsc->setNumMultiRenderTargets(std::min<int>(buffers, (GLint)CM_MAX_MULTIPLE_RENDER_TARGETS));
  436. rsc->setCapability(RSC_MRT_DIFFERENT_BIT_DEPTHS);
  437. if(!GLEW_VERSION_2_0)
  438. {
  439. // Before GL version 2.0, we need to get one of the extensions
  440. if(GLEW_ARB_draw_buffers)
  441. rsc->setCapability(RSC_FBO_ARB);
  442. if(GLEW_ATI_draw_buffers)
  443. rsc->setCapability(RSC_FBO_ATI);
  444. }
  445. // Set FBO flag for all 3 'subtypes'
  446. rsc->setCapability(RSC_FBO);
  447. }
  448. rsc->setCapability(RSC_HWRENDER_TO_TEXTURE);
  449. }
  450. // Check GLSupport for PBuffer support
  451. if(mGLSupport->supportsPBuffers())
  452. {
  453. // Use PBuffers
  454. rsc->setCapability(RSC_HWRENDER_TO_TEXTURE);
  455. rsc->setCapability(RSC_PBUFFER);
  456. }
  457. // Point size
  458. if (GLEW_VERSION_1_4)
  459. {
  460. float ps;
  461. glGetFloatv(GL_POINT_SIZE_MAX, &ps);
  462. rsc->setMaxPointSize(ps);
  463. }
  464. else
  465. {
  466. GLint vSize[2];
  467. glGetIntegerv(GL_POINT_SIZE_RANGE,vSize);
  468. rsc->setMaxPointSize((float)vSize[1]);
  469. }
  470. // Vertex texture fetching
  471. if (mGLSupport->checkExtension("GL_ARB_vertex_shader"))
  472. {
  473. GLint vUnits;
  474. glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB, &vUnits);
  475. rsc->setNumVertexTextureUnits(static_cast<UINT16>(vUnits));
  476. if (vUnits > 0)
  477. {
  478. rsc->setCapability(RSC_VERTEX_TEXTURE_FETCH);
  479. }
  480. // GL always shares vertex and fragment texture units (for now?)
  481. rsc->setVertexTextureUnitsShared(true);
  482. }
  483. // Mipmap LOD biasing?
  484. if (GLEW_VERSION_1_4 || GLEW_EXT_texture_lod_bias)
  485. {
  486. rsc->setCapability(RSC_MIPMAP_LOD_BIAS);
  487. }
  488. // Alpha to coverage?
  489. if (mGLSupport->checkExtension("GL_ARB_multisample"))
  490. {
  491. // Alpha to coverage always 'supported' when MSAA is available
  492. // although card may ignore it if it doesn't specifically support A2C
  493. rsc->setCapability(RSC_ALPHA_TO_COVERAGE);
  494. }
  495. // Advanced blending operations
  496. if(GLEW_VERSION_2_0)
  497. {
  498. rsc->setCapability(RSC_ADVANCED_BLEND_OPERATIONS);
  499. }
  500. return rsc;
  501. }
  502. void GLRenderSystem::initialiseFromRenderSystemCapabilities(RenderSystemCapabilities* caps, RenderTarget* primary)
  503. {
  504. if(caps->getRenderSystemName() != getName())
  505. {
  506. CM_EXCEPT(InvalidParametersException,
  507. "Trying to initialize GLRenderSystem from RenderSystemCapabilities that do not support OpenGL");
  508. }
  509. // set texture the number of texture units
  510. mFixedFunctionTextureUnits = caps->getNumTextureUnits();
  511. //In GL there can be less fixed function texture units than general
  512. //texture units. Get the minimum of the two.
  513. if (caps->hasCapability(RSC_FRAGMENT_PROGRAM))
  514. {
  515. GLint maxTexCoords = 0;
  516. glGetIntegerv(GL_MAX_TEXTURE_COORDS_ARB, &maxTexCoords);
  517. if (mFixedFunctionTextureUnits > maxTexCoords)
  518. {
  519. mFixedFunctionTextureUnits = maxTexCoords;
  520. }
  521. }
  522. if(caps->hasCapability(RSC_GL1_5_NOVBO))
  523. {
  524. // Assign ARB functions same to GL 1.5 version since
  525. // interface identical
  526. glBindBufferARB = glBindBuffer;
  527. glBufferDataARB = glBufferData;
  528. glBufferSubDataARB = glBufferSubData;
  529. glDeleteBuffersARB = glDeleteBuffers;
  530. glGenBuffersARB = glGenBuffers;
  531. glGetBufferParameterivARB = glGetBufferParameteriv;
  532. glGetBufferPointervARB = glGetBufferPointerv;
  533. glGetBufferSubDataARB = glGetBufferSubData;
  534. glIsBufferARB = glIsBuffer;
  535. glMapBufferARB = glMapBuffer;
  536. glUnmapBufferARB = glUnmapBuffer;
  537. }
  538. if(caps->hasCapability(RSC_VBO))
  539. {
  540. HardwareBufferManager::startUp(new GLHardwareBufferManager);
  541. }
  542. else
  543. {
  544. HardwareBufferManager::startUp(new GLDefaultHardwareBufferManager);
  545. }
  546. // GPU Program Manager setup
  547. GpuProgramManager::startUp(new GLGpuProgramManager());
  548. GLGpuProgramManager* gpuProgramManager = static_cast<GLGpuProgramManager*>(GpuProgramManager::instancePtr());
  549. if(caps->hasCapability(RSC_VERTEX_PROGRAM))
  550. {
  551. if(caps->isShaderProfileSupported("arbvp1"))
  552. {
  553. gpuProgramManager->registerProgramFactory("arbvp1", createGLArbGpuProgram);
  554. }
  555. if(caps->isShaderProfileSupported("vp30"))
  556. {
  557. gpuProgramManager->registerProgramFactory("vp30", createGLArbGpuProgram);
  558. }
  559. if(caps->isShaderProfileSupported("vp40"))
  560. {
  561. gpuProgramManager->registerProgramFactory("vp40", createGLArbGpuProgram);
  562. }
  563. if(caps->isShaderProfileSupported("gp4vp"))
  564. {
  565. gpuProgramManager->registerProgramFactory("gp4vp", createGLArbGpuProgram);
  566. }
  567. if(caps->isShaderProfileSupported("gpu_vp"))
  568. {
  569. gpuProgramManager->registerProgramFactory("gpu_vp", createGLArbGpuProgram);
  570. }
  571. }
  572. if(caps->hasCapability(RSC_GEOMETRY_PROGRAM))
  573. {
  574. //TODO : Should these be createGLArbGpuProgram or createGLGpuNVparseProgram?
  575. if(caps->isShaderProfileSupported("nvgp4"))
  576. {
  577. gpuProgramManager->registerProgramFactory("nvgp4", createGLArbGpuProgram);
  578. }
  579. if(caps->isShaderProfileSupported("gp4gp"))
  580. {
  581. gpuProgramManager->registerProgramFactory("gp4gp", createGLArbGpuProgram);
  582. }
  583. if(caps->isShaderProfileSupported("gpu_gp"))
  584. {
  585. gpuProgramManager->registerProgramFactory("gpu_gp", createGLArbGpuProgram);
  586. }
  587. }
  588. if(caps->hasCapability(RSC_FRAGMENT_PROGRAM))
  589. {
  590. if(caps->isShaderProfileSupported("ps_1_4"))
  591. {
  592. gpuProgramManager->registerProgramFactory("ps_1_4", createGL_ATI_FS_GpuProgram);
  593. }
  594. if(caps->isShaderProfileSupported("ps_1_3"))
  595. {
  596. gpuProgramManager->registerProgramFactory("ps_1_3", createGL_ATI_FS_GpuProgram);
  597. }
  598. if(caps->isShaderProfileSupported("ps_1_2"))
  599. {
  600. gpuProgramManager->registerProgramFactory("ps_1_2", createGL_ATI_FS_GpuProgram);
  601. }
  602. if(caps->isShaderProfileSupported("ps_1_1"))
  603. {
  604. gpuProgramManager->registerProgramFactory("ps_1_1", createGL_ATI_FS_GpuProgram);
  605. }
  606. if(caps->isShaderProfileSupported("arbfp1"))
  607. {
  608. gpuProgramManager->registerProgramFactory("arbfp1", createGLArbGpuProgram);
  609. }
  610. if(caps->isShaderProfileSupported("fp40"))
  611. {
  612. gpuProgramManager->registerProgramFactory("fp40", createGLArbGpuProgram);
  613. }
  614. if(caps->isShaderProfileSupported("fp30"))
  615. {
  616. gpuProgramManager->registerProgramFactory("fp30", createGLArbGpuProgram);
  617. }
  618. }
  619. if(caps->isShaderProfileSupported("glsl"))
  620. {
  621. // NFZ - check for GLSL vertex and fragment shader support successful
  622. mGLSLProgramFactory = new GLSLProgramFactory();
  623. HighLevelGpuProgramManager::instance().addFactory(mGLSLProgramFactory);
  624. }
  625. if(caps->hasCapability(RSC_HWOCCLUSION))
  626. {
  627. if(caps->hasCapability(RSC_GL1_5_NOHWOCCLUSION))
  628. {
  629. // Assign ARB functions same to GL 1.5 version since
  630. // interface identical
  631. glBeginQueryARB = glBeginQuery;
  632. glDeleteQueriesARB = glDeleteQueries;
  633. glEndQueryARB = glEndQuery;
  634. glGenQueriesARB = glGenQueries;
  635. glGetQueryObjectivARB = glGetQueryObjectiv;
  636. glGetQueryObjectuivARB = glGetQueryObjectuiv;
  637. glGetQueryivARB = glGetQueryiv;
  638. glIsQueryARB = glIsQuery;
  639. }
  640. }
  641. /// Do this after extension function pointers are initialised as the extension
  642. /// is used to probe further capabilities.
  643. ConfigOptionMap::iterator cfi = getConfigOptions().find("RTT Preferred Mode");
  644. // RTT Mode: 0 use whatever available, 1 use PBuffers, 2 force use copying
  645. int rttMode = 0;
  646. if (cfi != getConfigOptions().end())
  647. {
  648. if (cfi->second.currentValue == "PBuffer")
  649. {
  650. rttMode = 1;
  651. }
  652. else if (cfi->second.currentValue == "Copy")
  653. {
  654. rttMode = 2;
  655. }
  656. }
  657. // Check for framebuffer object extension
  658. if(caps->hasCapability(RSC_FBO) && rttMode < 1)
  659. {
  660. // Before GL version 2.0, we need to get one of the extensions
  661. if(caps->hasCapability(RSC_FBO_ARB))
  662. GLEW_GET_FUN(__glewDrawBuffers) = glDrawBuffersARB;
  663. else if(caps->hasCapability(RSC_FBO_ATI))
  664. GLEW_GET_FUN(__glewDrawBuffers) = glDrawBuffersATI;
  665. if(caps->hasCapability(RSC_HWRENDER_TO_TEXTURE))
  666. {
  667. // Create FBO manager
  668. // TODO LOG PORT - Log this somewhere?
  669. //LogManager::getSingleton().logMessage("GL: Using GL_EXT_framebuffer_object for rendering to textures (best)");
  670. GLRTTManager::startUp(new GLFBOManager(false));
  671. }
  672. }
  673. else
  674. {
  675. // Check GLSupport for PBuffer support
  676. if(caps->hasCapability(RSC_PBUFFER) && rttMode < 2)
  677. {
  678. if(caps->hasCapability(RSC_HWRENDER_TO_TEXTURE))
  679. {
  680. // Use PBuffers
  681. GLRTTManager::startUp(new GLPBRTTManager(mGLSupport, primary));
  682. // TODO LOG PORT - Log this somewhere?
  683. //LogManager::getSingleton().logMessage("GL: Using PBuffers for rendering to textures");
  684. }
  685. }
  686. else
  687. {
  688. // No pbuffer support either -- fallback to simplest copying from framebuffer
  689. GLRTTManager::startUp(new GLCopyingRTTManager());
  690. // TODO LOG PORT - Log this somewhere?
  691. //LogManager::getSingleton().logMessage("GL: Using framebuffer copy for rendering to textures (worst)");
  692. //LogManager::getSingleton().logMessage("GL: Warning: RenderTexture size is restricted to size of framebuffer. If you are on Linux, consider using GLX instead of SDL.");
  693. }
  694. // Downgrade number of simultaneous targets
  695. caps->setNumMultiRenderTargets(1);
  696. }
  697. /// Create the texture manager
  698. TextureManager::startUp(new GLTextureManager(*mGLSupport));
  699. mGLInitialised = true;
  700. }
  701. void GLRenderSystem::reinitialise(void)
  702. {
  703. this->shutdown();
  704. this->_initialise(true);
  705. }
  706. void GLRenderSystem::shutdown(void)
  707. {
  708. RenderSystem::shutdown();
  709. // Deleting the GLSL program factory
  710. if (mGLSLProgramFactory)
  711. {
  712. // Remove from manager safely
  713. HighLevelGpuProgramManager::instance().removeFactory(mGLSLProgramFactory);
  714. delete mGLSLProgramFactory;
  715. mGLSLProgramFactory = 0;
  716. }
  717. // Deleting the GPU program manager and hardware buffer manager. Has to be done before the mGLSupport->stop().
  718. GpuProgramManager::shutDown();
  719. HardwareBufferManager::shutDown();
  720. GLRTTManager::shutDown();
  721. // Delete extra threads contexts
  722. for (GLContextList::iterator i = mBackgroundContextList.begin();
  723. i != mBackgroundContextList.end(); ++i)
  724. {
  725. GLContext* pCurContext = *i;
  726. pCurContext->releaseContext();
  727. delete pCurContext;
  728. }
  729. mBackgroundContextList.clear();
  730. mGLSupport->stop();
  731. mStopRendering = true;
  732. TextureManager::shutDown();
  733. // There will be a new initial window and so forth, thus any call to test
  734. // some params will access an invalid pointer, so it is best to reset
  735. // the whole state.
  736. mGLInitialised = 0;
  737. }
  738. void GLRenderSystem::setAmbientLight(float r, float g, float b)
  739. {
  740. GLfloat lmodel_ambient[] = {r, g, b, 1.0};
  741. glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
  742. }
  743. void GLRenderSystem::setShadingType(ShadeOptions so)
  744. {
  745. switch(so)
  746. {
  747. case SO_FLAT:
  748. glShadeModel(GL_FLAT);
  749. break;
  750. default:
  751. glShadeModel(GL_SMOOTH);
  752. break;
  753. }
  754. }
  755. //---------------------------------------------------------------------
  756. bool GLRenderSystem::_createRenderWindows(const RenderWindowDescriptionList& renderWindowDescriptions,
  757. RenderWindowList& createdWindows)
  758. {
  759. // Call base render system method.
  760. if (false == RenderSystem::_createRenderWindows(renderWindowDescriptions, createdWindows))
  761. return false;
  762. // Simply call _createRenderWindow in a loop.
  763. for (size_t i = 0; i < renderWindowDescriptions.size(); ++i)
  764. {
  765. const RenderWindowDescription& curRenderWindowDescription = renderWindowDescriptions[i];
  766. RenderWindow* curWindow = NULL;
  767. curWindow = _createRenderWindow(curRenderWindowDescription.name,
  768. curRenderWindowDescription.width,
  769. curRenderWindowDescription.height,
  770. curRenderWindowDescription.useFullScreen,
  771. &curRenderWindowDescription.miscParams);
  772. createdWindows.push_back(curWindow);
  773. }
  774. return true;
  775. }
  776. //---------------------------------------------------------------------
  777. RenderWindow* GLRenderSystem::_createRenderWindow(const String &name,
  778. unsigned int width, unsigned int height, bool fullScreen,
  779. const NameValuePairList *miscParams)
  780. {
  781. if (mRenderTargets.find(name) != mRenderTargets.end())
  782. {
  783. CM_EXCEPT(InvalidParametersException,
  784. "Window with name '" + name + "' already exists");
  785. }
  786. // Create the window
  787. RenderWindow* win = mGLSupport->newWindow(name, width, height,
  788. fullScreen, miscParams);
  789. attachRenderTarget( *win );
  790. if (!mGLInitialised)
  791. {
  792. // set up glew and GLSupport
  793. initialiseContext(win);
  794. std::vector<CamelotEngine::String> tokens = StringUtil::split(mGLSupport->getGLVersion(), ".");
  795. if (!tokens.empty())
  796. {
  797. mDriverVersion.major = parseInt(tokens[0]);
  798. if (tokens.size() > 1)
  799. mDriverVersion.minor = parseInt(tokens[1]);
  800. if (tokens.size() > 2)
  801. mDriverVersion.release = parseInt(tokens[2]);
  802. }
  803. mDriverVersion.build = 0;
  804. // Initialise GL after the first window has been created
  805. // TODO: fire this from emulation options, and don't duplicate float and Current capabilities
  806. mRealCapabilities = createRenderSystemCapabilities();
  807. // use real capabilities if custom capabilities are not available
  808. if(!mUseCustomCapabilities)
  809. mCurrentCapabilities = mRealCapabilities;
  810. initialiseFromRenderSystemCapabilities(mCurrentCapabilities, win);
  811. // Initialise the main context
  812. _oneTimeContextInitialization();
  813. if(mCurrentContext)
  814. mCurrentContext->setInitialized();
  815. }
  816. return win;
  817. }
  818. void GLRenderSystem::initialiseContext(RenderWindow* primary)
  819. {
  820. // Set main and current context
  821. mMainContext = 0;
  822. primary->getCustomAttribute("GLCONTEXT", &mMainContext);
  823. mCurrentContext = mMainContext;
  824. // Set primary context as active
  825. if(mCurrentContext)
  826. mCurrentContext->setCurrent();
  827. // Setup GLSupport
  828. mGLSupport->initialiseExtensions();
  829. // Get extension function pointers
  830. #if CM_THREAD_SUPPORT != 1
  831. glewContextInit(mGLSupport);
  832. #endif
  833. }
  834. //-----------------------------------------------------------------------
  835. MultiRenderTarget * GLRenderSystem::createMultiRenderTarget(const String & name)
  836. {
  837. MultiRenderTarget *retval = GLRTTManager::instancePtr()->createMultiRenderTarget(name);
  838. attachRenderTarget( *retval );
  839. return retval;
  840. }
  841. //-----------------------------------------------------------------------
  842. void GLRenderSystem::destroyRenderWindow(RenderWindow* pWin)
  843. {
  844. // Find it to remove from list
  845. RenderTargetMap::iterator i = mRenderTargets.begin();
  846. while (i != mRenderTargets.end())
  847. {
  848. if (i->second == pWin)
  849. {
  850. mRenderTargets.erase(i);
  851. delete pWin;
  852. break;
  853. }
  854. }
  855. }
  856. //-----------------------------------------------------------------------------
  857. void GLRenderSystem::makeGLMatrix(GLfloat gl_matrix[16], const Matrix4& m)
  858. {
  859. size_t x = 0;
  860. for (size_t i = 0; i < 4; i++)
  861. {
  862. for (size_t j = 0; j < 4; j++)
  863. {
  864. gl_matrix[x] = m[j][i];
  865. x++;
  866. }
  867. }
  868. }
  869. //-----------------------------------------------------------------------------
  870. void GLRenderSystem::_setWorldMatrix( const Matrix4 &m )
  871. {
  872. GLfloat mat[16];
  873. mWorldMatrix = m;
  874. makeGLMatrix( mat, mViewMatrix * mWorldMatrix );
  875. glMatrixMode(GL_MODELVIEW);
  876. glLoadMatrixf(mat);
  877. }
  878. //-----------------------------------------------------------------------------
  879. void GLRenderSystem::_setViewMatrix( const Matrix4 &m )
  880. {
  881. mViewMatrix = m;
  882. GLfloat mat[16];
  883. makeGLMatrix( mat, mViewMatrix * mWorldMatrix );
  884. glMatrixMode(GL_MODELVIEW);
  885. glLoadMatrixf(mat);
  886. // also mark clip planes dirty
  887. if (!mClipPlanes.empty())
  888. mClipPlanesDirty = true;
  889. }
  890. //-----------------------------------------------------------------------------
  891. void GLRenderSystem::_setProjectionMatrix(const Matrix4 &m)
  892. {
  893. GLfloat mat[16];
  894. makeGLMatrix(mat, m);
  895. if (mActiveRenderTarget->requiresTextureFlipping())
  896. {
  897. // Invert transformed y
  898. mat[1] = -mat[1];
  899. mat[5] = -mat[5];
  900. mat[9] = -mat[9];
  901. mat[13] = -mat[13];
  902. }
  903. glMatrixMode(GL_PROJECTION);
  904. glLoadMatrixf(mat);
  905. glMatrixMode(GL_MODELVIEW);
  906. // also mark clip planes dirty
  907. if (!mClipPlanes.empty())
  908. mClipPlanesDirty = true;
  909. }
  910. //-----------------------------------------------------------------------------
  911. void GLRenderSystem::_setSurfaceParams(const Color &ambient,
  912. const Color &diffuse, const Color &specular,
  913. const Color &emissive, float shininess,
  914. TrackVertexColourType tracking)
  915. {
  916. // Track vertex colour
  917. if(tracking != TVC_NONE)
  918. {
  919. GLenum gt = GL_DIFFUSE;
  920. // There are actually 15 different combinations for tracking, of which
  921. // GL only supports the most used 5. This means that we have to do some
  922. // magic to find the best match. NOTE:
  923. // GL_AMBIENT_AND_DIFFUSE != GL_AMBIENT | GL__DIFFUSE
  924. if(tracking & TVC_AMBIENT)
  925. {
  926. if(tracking & TVC_DIFFUSE)
  927. {
  928. gt = GL_AMBIENT_AND_DIFFUSE;
  929. }
  930. else
  931. {
  932. gt = GL_AMBIENT;
  933. }
  934. }
  935. else if(tracking & TVC_DIFFUSE)
  936. {
  937. gt = GL_DIFFUSE;
  938. }
  939. else if(tracking & TVC_SPECULAR)
  940. {
  941. gt = GL_SPECULAR;
  942. }
  943. else if(tracking & TVC_EMISSIVE)
  944. {
  945. gt = GL_EMISSION;
  946. }
  947. glColorMaterial(GL_FRONT_AND_BACK, gt);
  948. glEnable(GL_COLOR_MATERIAL);
  949. }
  950. else
  951. {
  952. glDisable(GL_COLOR_MATERIAL);
  953. }
  954. // XXX Cache previous values?
  955. // XXX Front or Front and Back?
  956. GLfloat f4val[4] = {diffuse.r, diffuse.g, diffuse.b, diffuse.a};
  957. glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, f4val);
  958. f4val[0] = ambient.r;
  959. f4val[1] = ambient.g;
  960. f4val[2] = ambient.b;
  961. f4val[3] = ambient.a;
  962. glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, f4val);
  963. f4val[0] = specular.r;
  964. f4val[1] = specular.g;
  965. f4val[2] = specular.b;
  966. f4val[3] = specular.a;
  967. glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, f4val);
  968. f4val[0] = emissive.r;
  969. f4val[1] = emissive.g;
  970. f4val[2] = emissive.b;
  971. f4val[3] = emissive.a;
  972. glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, f4val);
  973. glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, shininess);
  974. }
  975. //-----------------------------------------------------------------------------
  976. void GLRenderSystem::_setPointParameters(float size,
  977. bool attenuationEnabled, float constant, float linear, float quadratic,
  978. float minSize, float maxSize)
  979. {
  980. float val[4] = {1, 0, 0, 1};
  981. if(attenuationEnabled)
  982. {
  983. // Point size is still calculated in pixels even when attenuation is
  984. // enabled, which is pretty awkward, since you typically want a viewport
  985. // independent size if you're looking for attenuation.
  986. // So, scale the point size up by viewport size (this is equivalent to
  987. // what D3D does as standard)
  988. size = size * mActiveViewport->getActualHeight();
  989. minSize = minSize * mActiveViewport->getActualHeight();
  990. if (maxSize == 0.0f)
  991. maxSize = mCurrentCapabilities->getMaxPointSize(); // pixels
  992. else
  993. maxSize = maxSize * mActiveViewport->getActualHeight();
  994. // XXX: why do I need this for results to be consistent with D3D?
  995. // Equations are supposedly the same once you factor in vp height
  996. float correction = 0.005f;
  997. // scaling required
  998. val[0] = constant;
  999. val[1] = linear * correction;
  1000. val[2] = quadratic * correction;
  1001. val[3] = 1;
  1002. if (mCurrentCapabilities->hasCapability(RSC_VERTEX_PROGRAM))
  1003. glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
  1004. }
  1005. else
  1006. {
  1007. if (maxSize == 0.0f)
  1008. maxSize = mCurrentCapabilities->getMaxPointSize();
  1009. if (mCurrentCapabilities->hasCapability(RSC_VERTEX_PROGRAM))
  1010. glDisable(GL_VERTEX_PROGRAM_POINT_SIZE);
  1011. }
  1012. // no scaling required
  1013. // GL has no disabled flag for this so just set to constant
  1014. glPointSize(size);
  1015. if (mCurrentCapabilities->hasCapability(RSC_POINT_EXTENDED_PARAMETERS))
  1016. {
  1017. glPointParameterfv(GL_POINT_DISTANCE_ATTENUATION, val);
  1018. glPointParameterf(GL_POINT_SIZE_MIN, minSize);
  1019. glPointParameterf(GL_POINT_SIZE_MAX, maxSize);
  1020. }
  1021. else if (mCurrentCapabilities->hasCapability(RSC_POINT_EXTENDED_PARAMETERS_ARB))
  1022. {
  1023. glPointParameterfvARB(GL_POINT_DISTANCE_ATTENUATION, val);
  1024. glPointParameterfARB(GL_POINT_SIZE_MIN, minSize);
  1025. glPointParameterfARB(GL_POINT_SIZE_MAX, maxSize);
  1026. }
  1027. else if (mCurrentCapabilities->hasCapability(RSC_POINT_EXTENDED_PARAMETERS_EXT))
  1028. {
  1029. glPointParameterfvEXT(GL_POINT_DISTANCE_ATTENUATION, val);
  1030. glPointParameterfEXT(GL_POINT_SIZE_MIN, minSize);
  1031. glPointParameterfEXT(GL_POINT_SIZE_MAX, maxSize);
  1032. }
  1033. }
  1034. //---------------------------------------------------------------------
  1035. void GLRenderSystem::_setPointSpritesEnabled(bool enabled)
  1036. {
  1037. if (!getCapabilities()->hasCapability(RSC_POINT_SPRITES))
  1038. return;
  1039. if (enabled)
  1040. {
  1041. glEnable(GL_POINT_SPRITE);
  1042. }
  1043. else
  1044. {
  1045. glDisable(GL_POINT_SPRITE);
  1046. }
  1047. // Set sprite texture coord generation
  1048. // Don't offer this as an option since D3D links it to sprite enabled
  1049. for (UINT16 i = 0; i < mFixedFunctionTextureUnits; ++i)
  1050. {
  1051. activateGLTextureUnit(i);
  1052. glTexEnvi(GL_POINT_SPRITE, GL_COORD_REPLACE,
  1053. enabled ? GL_TRUE : GL_FALSE);
  1054. }
  1055. activateGLTextureUnit(0);
  1056. }
  1057. //-----------------------------------------------------------------------------
  1058. void GLRenderSystem::_setTexture(size_t stage, bool enabled, const TexturePtr &texPtr)
  1059. {
  1060. GLTexturePtr tex = std::static_pointer_cast<GLTexture>(texPtr);
  1061. GLenum lastTextureType = mTextureTypes[stage];
  1062. if (!activateGLTextureUnit(stage))
  1063. return;
  1064. if (enabled)
  1065. {
  1066. if (tex)
  1067. {
  1068. // note used
  1069. mTextureTypes[stage] = tex->getGLTextureTarget();
  1070. }
  1071. else
  1072. // assume 2D
  1073. mTextureTypes[stage] = GL_TEXTURE_2D;
  1074. if(lastTextureType != mTextureTypes[stage] && lastTextureType != 0)
  1075. {
  1076. if (stage < mFixedFunctionTextureUnits)
  1077. {
  1078. glDisable( lastTextureType );
  1079. }
  1080. }
  1081. if (stage < mFixedFunctionTextureUnits)
  1082. {
  1083. glEnable( mTextureTypes[stage] );
  1084. }
  1085. if(tex)
  1086. glBindTexture( mTextureTypes[stage], tex->getGLID() );
  1087. else
  1088. {
  1089. glBindTexture( mTextureTypes[stage], static_cast<GLTextureManager*>(&TextureManager::instance())->getWarningTextureID() );
  1090. }
  1091. }
  1092. else
  1093. {
  1094. if (stage < mFixedFunctionTextureUnits)
  1095. {
  1096. if (lastTextureType != 0)
  1097. {
  1098. glDisable( mTextureTypes[stage] );
  1099. }
  1100. glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
  1101. }
  1102. // bind zero texture
  1103. glBindTexture(GL_TEXTURE_2D, 0);
  1104. }
  1105. activateGLTextureUnit(0);
  1106. }
  1107. //-----------------------------------------------------------------------------
  1108. void GLRenderSystem::_setTextureCoordSet(size_t stage, size_t index)
  1109. {
  1110. mTextureCoordIndex[stage] = index;
  1111. }
  1112. //-----------------------------------------------------------------------------
  1113. void GLRenderSystem::_setTextureCoordCalculation(size_t stage, TexCoordCalcMethod m,
  1114. const Frustum* frustum)
  1115. {
  1116. if (stage >= mFixedFunctionTextureUnits)
  1117. {
  1118. // Can't do this
  1119. return;
  1120. }
  1121. GLfloat M[16];
  1122. Matrix4 projectionBias;
  1123. // Default to no extra auto texture matrix
  1124. mUseAutoTextureMatrix = false;
  1125. GLfloat eyePlaneS[] = {1.0, 0.0, 0.0, 0.0};
  1126. GLfloat eyePlaneT[] = {0.0, 1.0, 0.0, 0.0};
  1127. GLfloat eyePlaneR[] = {0.0, 0.0, 1.0, 0.0};
  1128. GLfloat eyePlaneQ[] = {0.0, 0.0, 0.0, 1.0};
  1129. if (!activateGLTextureUnit(stage))
  1130. return;
  1131. switch( m )
  1132. {
  1133. case TEXCALC_NONE:
  1134. glDisable( GL_TEXTURE_GEN_S );
  1135. glDisable( GL_TEXTURE_GEN_T );
  1136. glDisable( GL_TEXTURE_GEN_R );
  1137. glDisable( GL_TEXTURE_GEN_Q );
  1138. break;
  1139. case TEXCALC_ENVIRONMENT_MAP:
  1140. glTexGeni( GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP );
  1141. glTexGeni( GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP );
  1142. glEnable( GL_TEXTURE_GEN_S );
  1143. glEnable( GL_TEXTURE_GEN_T );
  1144. glDisable( GL_TEXTURE_GEN_R );
  1145. glDisable( GL_TEXTURE_GEN_Q );
  1146. // Need to use a texture matrix to flip the spheremap
  1147. mUseAutoTextureMatrix = true;
  1148. memset(mAutoTextureMatrix, 0, sizeof(GLfloat)*16);
  1149. mAutoTextureMatrix[0] = mAutoTextureMatrix[10] = mAutoTextureMatrix[15] = 1.0f;
  1150. mAutoTextureMatrix[5] = -1.0f;
  1151. break;
  1152. case TEXCALC_ENVIRONMENT_MAP_PLANAR:
  1153. // XXX This doesn't seem right?!
  1154. #ifdef GL_VERSION_1_3
  1155. glTexGeni( GL_S, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP );
  1156. glTexGeni( GL_T, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP );
  1157. glTexGeni( GL_R, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP );
  1158. glEnable( GL_TEXTURE_GEN_S );
  1159. glEnable( GL_TEXTURE_GEN_T );
  1160. glEnable( GL_TEXTURE_GEN_R );
  1161. glDisable( GL_TEXTURE_GEN_Q );
  1162. #else
  1163. glTexGeni( GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP );
  1164. glTexGeni( GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP );
  1165. glEnable( GL_TEXTURE_GEN_S );
  1166. glEnable( GL_TEXTURE_GEN_T );
  1167. glDisable( GL_TEXTURE_GEN_R );
  1168. glDisable( GL_TEXTURE_GEN_Q );
  1169. #endif
  1170. break;
  1171. case TEXCALC_ENVIRONMENT_MAP_REFLECTION:
  1172. glTexGeni( GL_S, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP );
  1173. glTexGeni( GL_T, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP );
  1174. glTexGeni( GL_R, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP );
  1175. glEnable( GL_TEXTURE_GEN_S );
  1176. glEnable( GL_TEXTURE_GEN_T );
  1177. glEnable( GL_TEXTURE_GEN_R );
  1178. glDisable( GL_TEXTURE_GEN_Q );
  1179. // We need an extra texture matrix here
  1180. // This sets the texture matrix to be the inverse of the view matrix
  1181. mUseAutoTextureMatrix = true;
  1182. makeGLMatrix( M, mViewMatrix);
  1183. // Transpose 3x3 in order to invert matrix (rotation)
  1184. // Note that we need to invert the Z _before_ the rotation
  1185. // No idea why we have to invert the Z at all, but reflection is wrong without it
  1186. mAutoTextureMatrix[0] = M[0]; mAutoTextureMatrix[1] = M[4]; mAutoTextureMatrix[2] = -M[8];
  1187. mAutoTextureMatrix[4] = M[1]; mAutoTextureMatrix[5] = M[5]; mAutoTextureMatrix[6] = -M[9];
  1188. mAutoTextureMatrix[8] = M[2]; mAutoTextureMatrix[9] = M[6]; mAutoTextureMatrix[10] = -M[10];
  1189. mAutoTextureMatrix[3] = mAutoTextureMatrix[7] = mAutoTextureMatrix[11] = 0.0f;
  1190. mAutoTextureMatrix[12] = mAutoTextureMatrix[13] = mAutoTextureMatrix[14] = 0.0f;
  1191. mAutoTextureMatrix[15] = 1.0f;
  1192. break;
  1193. case TEXCALC_ENVIRONMENT_MAP_NORMAL:
  1194. glTexGeni( GL_S, GL_TEXTURE_GEN_MODE, GL_NORMAL_MAP );
  1195. glTexGeni( GL_T, GL_TEXTURE_GEN_MODE, GL_NORMAL_MAP );
  1196. glTexGeni( GL_R, GL_TEXTURE_GEN_MODE, GL_NORMAL_MAP );
  1197. glEnable( GL_TEXTURE_GEN_S );
  1198. glEnable( GL_TEXTURE_GEN_T );
  1199. glEnable( GL_TEXTURE_GEN_R );
  1200. glDisable( GL_TEXTURE_GEN_Q );
  1201. break;
  1202. case TEXCALC_PROJECTIVE_TEXTURE:
  1203. glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
  1204. glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
  1205. glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
  1206. glTexGeni(GL_Q, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
  1207. glTexGenfv(GL_S, GL_EYE_PLANE, eyePlaneS);
  1208. glTexGenfv(GL_T, GL_EYE_PLANE, eyePlaneT);
  1209. glTexGenfv(GL_R, GL_EYE_PLANE, eyePlaneR);
  1210. glTexGenfv(GL_Q, GL_EYE_PLANE, eyePlaneQ);
  1211. glEnable(GL_TEXTURE_GEN_S);
  1212. glEnable(GL_TEXTURE_GEN_T);
  1213. glEnable(GL_TEXTURE_GEN_R);
  1214. glEnable(GL_TEXTURE_GEN_Q);
  1215. mUseAutoTextureMatrix = true;
  1216. // Set scale and translation matrix for projective textures
  1217. projectionBias = Matrix4::CLIPSPACE2DTOIMAGESPACE;
  1218. projectionBias = projectionBias * frustum->getProjectionMatrix();
  1219. if(mTexProjRelative)
  1220. {
  1221. Matrix4 viewMatrix;
  1222. frustum->calcViewMatrixRelative(mTexProjRelativeOrigin, viewMatrix);
  1223. projectionBias = projectionBias * viewMatrix;
  1224. }
  1225. else
  1226. {
  1227. projectionBias = projectionBias * frustum->getViewMatrix();
  1228. }
  1229. projectionBias = projectionBias * mWorldMatrix;
  1230. makeGLMatrix(mAutoTextureMatrix, projectionBias);
  1231. break;
  1232. default:
  1233. break;
  1234. }
  1235. activateGLTextureUnit(0);
  1236. }
  1237. //-----------------------------------------------------------------------------
  1238. GLint GLRenderSystem::getTextureAddressingMode(
  1239. TextureState::TextureAddressingMode tam) const
  1240. {
  1241. switch(tam)
  1242. {
  1243. default:
  1244. case TextureState::TAM_WRAP:
  1245. return GL_REPEAT;
  1246. case TextureState::TAM_MIRROR:
  1247. return GL_MIRRORED_REPEAT;
  1248. case TextureState::TAM_CLAMP:
  1249. return GL_CLAMP_TO_EDGE;
  1250. case TextureState::TAM_BORDER:
  1251. return GL_CLAMP_TO_BORDER;
  1252. }
  1253. }
  1254. //-----------------------------------------------------------------------------
  1255. void GLRenderSystem::_setTextureAddressingMode(size_t stage, const TextureState::UVWAddressingMode& uvw)
  1256. {
  1257. if (!activateGLTextureUnit(stage))
  1258. return;
  1259. glTexParameteri( mTextureTypes[stage], GL_TEXTURE_WRAP_S,
  1260. getTextureAddressingMode(uvw.u));
  1261. glTexParameteri( mTextureTypes[stage], GL_TEXTURE_WRAP_T,
  1262. getTextureAddressingMode(uvw.v));
  1263. glTexParameteri( mTextureTypes[stage], GL_TEXTURE_WRAP_R,
  1264. getTextureAddressingMode(uvw.w));
  1265. activateGLTextureUnit(0);
  1266. }
  1267. //-----------------------------------------------------------------------------
  1268. void GLRenderSystem::_setTextureBorderColour(size_t stage, const Color& colour)
  1269. {
  1270. GLfloat border[4] = { colour.r, colour.g, colour.b, colour.a };
  1271. if (activateGLTextureUnit(stage))
  1272. {
  1273. glTexParameterfv( mTextureTypes[stage], GL_TEXTURE_BORDER_COLOR, border);
  1274. activateGLTextureUnit(0);
  1275. }
  1276. }
  1277. //-----------------------------------------------------------------------------
  1278. void GLRenderSystem::_setTextureMipmapBias(size_t stage, float bias)
  1279. {
  1280. if (mCurrentCapabilities->hasCapability(RSC_MIPMAP_LOD_BIAS))
  1281. {
  1282. if (activateGLTextureUnit(stage))
  1283. {
  1284. glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, bias);
  1285. activateGLTextureUnit(0);
  1286. }
  1287. }
  1288. }
  1289. //-----------------------------------------------------------------------------
  1290. void GLRenderSystem::_setTextureMatrix(size_t stage, const Matrix4& xform)
  1291. {
  1292. if (stage >= mFixedFunctionTextureUnits)
  1293. {
  1294. // Can't do this
  1295. return;
  1296. }
  1297. GLfloat mat[16];
  1298. makeGLMatrix(mat, xform);
  1299. if (!activateGLTextureUnit(stage))
  1300. return;
  1301. glMatrixMode(GL_TEXTURE);
  1302. // Load this matrix in
  1303. glLoadMatrixf(mat);
  1304. if (mUseAutoTextureMatrix)
  1305. {
  1306. // Concat auto matrix
  1307. glMultMatrixf(mAutoTextureMatrix);
  1308. }
  1309. glMatrixMode(GL_MODELVIEW);
  1310. activateGLTextureUnit(0);
  1311. }
  1312. //-----------------------------------------------------------------------------
  1313. GLint GLRenderSystem::getBlendMode(SceneBlendFactor ogreBlend) const
  1314. {
  1315. switch(ogreBlend)
  1316. {
  1317. case SBF_ONE:
  1318. return GL_ONE;
  1319. case SBF_ZERO:
  1320. return GL_ZERO;
  1321. case SBF_DEST_COLOUR:
  1322. return GL_DST_COLOR;
  1323. case SBF_SOURCE_COLOUR:
  1324. return GL_SRC_COLOR;
  1325. case SBF_ONE_MINUS_DEST_COLOUR:
  1326. return GL_ONE_MINUS_DST_COLOR;
  1327. case SBF_ONE_MINUS_SOURCE_COLOUR:
  1328. return GL_ONE_MINUS_SRC_COLOR;
  1329. case SBF_DEST_ALPHA:
  1330. return GL_DST_ALPHA;
  1331. case SBF_SOURCE_ALPHA:
  1332. return GL_SRC_ALPHA;
  1333. case SBF_ONE_MINUS_DEST_ALPHA:
  1334. return GL_ONE_MINUS_DST_ALPHA;
  1335. case SBF_ONE_MINUS_SOURCE_ALPHA:
  1336. return GL_ONE_MINUS_SRC_ALPHA;
  1337. };
  1338. // to keep compiler happy
  1339. return GL_ONE;
  1340. }
  1341. void GLRenderSystem::_setSceneBlending(SceneBlendFactor sourceFactor, SceneBlendFactor destFactor, SceneBlendOperation op )
  1342. {
  1343. GLint sourceBlend = getBlendMode(sourceFactor);
  1344. GLint destBlend = getBlendMode(destFactor);
  1345. if(sourceFactor == SBF_ONE && destFactor == SBF_ZERO)
  1346. {
  1347. glDisable(GL_BLEND);
  1348. }
  1349. else
  1350. {
  1351. glEnable(GL_BLEND);
  1352. glBlendFunc(sourceBlend, destBlend);
  1353. }
  1354. GLint func = GL_FUNC_ADD;
  1355. switch(op)
  1356. {
  1357. case SBO_ADD:
  1358. func = GL_FUNC_ADD;
  1359. break;
  1360. case SBO_SUBTRACT:
  1361. func = GL_FUNC_SUBTRACT;
  1362. break;
  1363. case SBO_REVERSE_SUBTRACT:
  1364. func = GL_FUNC_REVERSE_SUBTRACT;
  1365. break;
  1366. case SBO_MIN:
  1367. func = GL_MIN;
  1368. break;
  1369. case SBO_MAX:
  1370. func = GL_MAX;
  1371. break;
  1372. }
  1373. if(GLEW_VERSION_1_4 || GLEW_ARB_imaging)
  1374. {
  1375. glBlendEquation(func);
  1376. }
  1377. else if(GLEW_EXT_blend_minmax && (func == GL_MIN || func == GL_MAX))
  1378. {
  1379. glBlendEquationEXT(func);
  1380. }
  1381. }
  1382. //-----------------------------------------------------------------------------
  1383. void GLRenderSystem::_setSeparateSceneBlending(
  1384. SceneBlendFactor sourceFactor, SceneBlendFactor destFactor,
  1385. SceneBlendFactor sourceFactorAlpha, SceneBlendFactor destFactorAlpha,
  1386. SceneBlendOperation op, SceneBlendOperation alphaOp )
  1387. {
  1388. GLint sourceBlend = getBlendMode(sourceFactor);
  1389. GLint destBlend = getBlendMode(destFactor);
  1390. GLint sourceBlendAlpha = getBlendMode(sourceFactorAlpha);
  1391. GLint destBlendAlpha = getBlendMode(destFactorAlpha);
  1392. if(sourceFactor == SBF_ONE && destFactor == SBF_ZERO &&
  1393. sourceFactorAlpha == SBF_ONE && destFactorAlpha == SBF_ZERO)
  1394. {
  1395. glDisable(GL_BLEND);
  1396. }
  1397. else
  1398. {
  1399. glEnable(GL_BLEND);
  1400. glBlendFuncSeparate(sourceBlend, destBlend, sourceBlendAlpha, destBlendAlpha);
  1401. }
  1402. GLint func = GL_FUNC_ADD, alphaFunc = GL_FUNC_ADD;
  1403. switch(op)
  1404. {
  1405. case SBO_ADD:
  1406. func = GL_FUNC_ADD;
  1407. break;
  1408. case SBO_SUBTRACT:
  1409. func = GL_FUNC_SUBTRACT;
  1410. break;
  1411. case SBO_REVERSE_SUBTRACT:
  1412. func = GL_FUNC_REVERSE_SUBTRACT;
  1413. break;
  1414. case SBO_MIN:
  1415. func = GL_MIN;
  1416. break;
  1417. case SBO_MAX:
  1418. func = GL_MAX;
  1419. break;
  1420. }
  1421. switch(alphaOp)
  1422. {
  1423. case SBO_ADD:
  1424. alphaFunc = GL_FUNC_ADD;
  1425. break;
  1426. case SBO_SUBTRACT:
  1427. alphaFunc = GL_FUNC_SUBTRACT;
  1428. break;
  1429. case SBO_REVERSE_SUBTRACT:
  1430. alphaFunc = GL_FUNC_REVERSE_SUBTRACT;
  1431. break;
  1432. case SBO_MIN:
  1433. alphaFunc = GL_MIN;
  1434. break;
  1435. case SBO_MAX:
  1436. alphaFunc = GL_MAX;
  1437. break;
  1438. }
  1439. if(GLEW_VERSION_2_0) {
  1440. glBlendEquationSeparate(func, alphaFunc);
  1441. }
  1442. else if(GLEW_EXT_blend_equation_separate) {
  1443. glBlendEquationSeparateEXT(func, alphaFunc);
  1444. }
  1445. }
  1446. //-----------------------------------------------------------------------------
  1447. void GLRenderSystem::_setAlphaRejectSettings(CompareFunction func, unsigned char value, bool alphaToCoverage)
  1448. {
  1449. bool a2c = false;
  1450. static bool lasta2c = false;
  1451. if(func == CMPF_ALWAYS_PASS)
  1452. {
  1453. glDisable(GL_ALPHA_TEST);
  1454. }
  1455. else
  1456. {
  1457. glEnable(GL_ALPHA_TEST);
  1458. a2c = alphaToCoverage;
  1459. glAlphaFunc(convertCompareFunction(func), value / 255.0f);
  1460. }
  1461. if (a2c != lasta2c && getCapabilities()->hasCapability(RSC_ALPHA_TO_COVERAGE))
  1462. {
  1463. if (a2c)
  1464. glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  1465. else
  1466. glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  1467. lasta2c = a2c;
  1468. }
  1469. }
  1470. //-----------------------------------------------------------------------------
  1471. void GLRenderSystem::_setViewport(Viewport *vp)
  1472. {
  1473. // Check if viewport is different
  1474. if (vp != mActiveViewport)
  1475. {
  1476. RenderTarget* target;
  1477. target = vp->getTarget();
  1478. _setRenderTarget(target);
  1479. mActiveViewport = vp;
  1480. GLsizei x, y, w, h;
  1481. // Calculate the "lower-left" corner of the viewport
  1482. w = vp->getActualWidth();
  1483. h = vp->getActualHeight();
  1484. x = vp->getActualLeft();
  1485. y = vp->getActualTop();
  1486. if (!target->requiresTextureFlipping())
  1487. {
  1488. // Convert "upper-left" corner to "lower-left"
  1489. y = target->getHeight() - h - y;
  1490. }
  1491. glViewport(x, y, w, h);
  1492. // Configure the viewport clipping
  1493. glScissor(x, y, w, h);
  1494. }
  1495. }
  1496. void GLRenderSystem::setLights()
  1497. {
  1498. // TODO PORT - I'm not using fixed pipeline lights. Remove this later
  1499. //for (size_t i = 0; i < MAX_LIGHTS; ++i)
  1500. //{
  1501. // if (mLights[i] != NULL)
  1502. // {
  1503. // Light* lt = mLights[i];
  1504. // setGLLightPositionDirection(lt, GL_LIGHT0 + i);
  1505. // }
  1506. //}
  1507. }
  1508. //-----------------------------------------------------------------------------
  1509. void GLRenderSystem::_beginFrame(void)
  1510. {
  1511. if (!mActiveViewport)
  1512. CM_EXCEPT(InvalidStateException,
  1513. "Cannot begin frame - no viewport selected.");
  1514. // Activate the viewport clipping
  1515. glEnable(GL_SCISSOR_TEST);
  1516. }
  1517. //-----------------------------------------------------------------------------
  1518. void GLRenderSystem::_endFrame(void)
  1519. {
  1520. // Deactivate the viewport clipping.
  1521. glDisable(GL_SCISSOR_TEST);
  1522. // unbind GPU programs at end of frame
  1523. // this is mostly to avoid holding bound programs that might get deleted
  1524. // outside via the resource manager
  1525. unbindGpuProgram(GPT_VERTEX_PROGRAM);
  1526. unbindGpuProgram(GPT_FRAGMENT_PROGRAM);
  1527. }
  1528. //-----------------------------------------------------------------------------
  1529. void GLRenderSystem::_setCullingMode(CullingMode mode)
  1530. {
  1531. mCullingMode = mode;
  1532. // NB: Because two-sided stencil API dependence of the front face, we must
  1533. // use the same 'winding' for the front face everywhere. As the OGRE default
  1534. // culling mode is clockwise, we also treat anticlockwise winding as front
  1535. // face for consistently. On the assumption that, we can't change the front
  1536. // face by glFrontFace anywhere.
  1537. GLenum cullMode;
  1538. switch( mode )
  1539. {
  1540. case CULL_NONE:
  1541. glDisable( GL_CULL_FACE );
  1542. return;
  1543. default:
  1544. case CULL_CLOCKWISE:
  1545. if (mActiveRenderTarget &&
  1546. ((mActiveRenderTarget->requiresTextureFlipping() && !mInvertVertexWinding) ||
  1547. (!mActiveRenderTarget->requiresTextureFlipping() && mInvertVertexWinding)))
  1548. {
  1549. cullMode = GL_FRONT;
  1550. }
  1551. else
  1552. {
  1553. cullMode = GL_BACK;
  1554. }
  1555. break;
  1556. case CULL_ANTICLOCKWISE:
  1557. if (mActiveRenderTarget &&
  1558. ((mActiveRenderTarget->requiresTextureFlipping() && !mInvertVertexWinding) ||
  1559. (!mActiveRenderTarget->requiresTextureFlipping() && mInvertVertexWinding)))
  1560. {
  1561. cullMode = GL_BACK;
  1562. }
  1563. else
  1564. {
  1565. cullMode = GL_FRONT;
  1566. }
  1567. break;
  1568. }
  1569. glEnable( GL_CULL_FACE );
  1570. glCullFace( cullMode );
  1571. }
  1572. //-----------------------------------------------------------------------------
  1573. void GLRenderSystem::_setDepthBufferParams(bool depthTest, bool depthWrite, CompareFunction depthFunction)
  1574. {
  1575. _setDepthBufferCheckEnabled(depthTest);
  1576. _setDepthBufferWriteEnabled(depthWrite);
  1577. _setDepthBufferFunction(depthFunction);
  1578. }
  1579. //-----------------------------------------------------------------------------
  1580. void GLRenderSystem::_setDepthBufferCheckEnabled(bool enabled)
  1581. {
  1582. if (enabled)
  1583. {
  1584. glClearDepth(1.0f);
  1585. glEnable(GL_DEPTH_TEST);
  1586. }
  1587. else
  1588. {
  1589. glDisable(GL_DEPTH_TEST);
  1590. }
  1591. }
  1592. //-----------------------------------------------------------------------------
  1593. void GLRenderSystem::_setDepthBufferWriteEnabled(bool enabled)
  1594. {
  1595. GLboolean flag = enabled ? GL_TRUE : GL_FALSE;
  1596. glDepthMask( flag );
  1597. // Store for reference in _beginFrame
  1598. mDepthWrite = enabled;
  1599. }
  1600. //-----------------------------------------------------------------------------
  1601. void GLRenderSystem::_setDepthBufferFunction(CompareFunction func)
  1602. {
  1603. glDepthFunc(convertCompareFunction(func));
  1604. }
  1605. //-----------------------------------------------------------------------------
  1606. void GLRenderSystem::_setDepthBias(float constantBias, float slopeScaleBias)
  1607. {
  1608. if (constantBias != 0 || slopeScaleBias != 0)
  1609. {
  1610. glEnable(GL_POLYGON_OFFSET_FILL);
  1611. glEnable(GL_POLYGON_OFFSET_POINT);
  1612. glEnable(GL_POLYGON_OFFSET_LINE);
  1613. glPolygonOffset(-slopeScaleBias, -constantBias);
  1614. }
  1615. else
  1616. {
  1617. glDisable(GL_POLYGON_OFFSET_FILL);
  1618. glDisable(GL_POLYGON_OFFSET_POINT);
  1619. glDisable(GL_POLYGON_OFFSET_LINE);
  1620. }
  1621. }
  1622. //-----------------------------------------------------------------------------
  1623. void GLRenderSystem::_setColourBufferWriteEnabled(bool red, bool green, bool blue, bool alpha)
  1624. {
  1625. glColorMask(red, green, blue, alpha);
  1626. // record this
  1627. mColourWrite[0] = red;
  1628. mColourWrite[1] = blue;
  1629. mColourWrite[2] = green;
  1630. mColourWrite[3] = alpha;
  1631. }
  1632. //-----------------------------------------------------------------------------
  1633. String GLRenderSystem::getErrorDescription(long errCode) const
  1634. {
  1635. const GLubyte *errString = gluErrorString (errCode);
  1636. return (errString != 0) ? String((const char*) errString) : StringUtil::BLANK;
  1637. }
  1638. //-----------------------------------------------------------------------------
  1639. void GLRenderSystem::setLightingEnabled(bool enabled)
  1640. {
  1641. if (enabled)
  1642. {
  1643. glEnable(GL_LIGHTING);
  1644. }
  1645. else
  1646. {
  1647. glDisable(GL_LIGHTING);
  1648. }
  1649. }
  1650. //-----------------------------------------------------------------------------
  1651. void GLRenderSystem::_setFog(FogMode mode, const Color& colour, float density, float start, float end)
  1652. {
  1653. GLint fogMode;
  1654. switch (mode)
  1655. {
  1656. case FOG_EXP:
  1657. fogMode = GL_EXP;
  1658. break;
  1659. case FOG_EXP2:
  1660. fogMode = GL_EXP2;
  1661. break;
  1662. case FOG_LINEAR:
  1663. fogMode = GL_LINEAR;
  1664. break;
  1665. default:
  1666. // Give up on it
  1667. glDisable(GL_FOG);
  1668. return;
  1669. }
  1670. glEnable(GL_FOG);
  1671. glFogi(GL_FOG_MODE, fogMode);
  1672. GLfloat fogColor[4] = {colour.r, colour.g, colour.b, colour.a};
  1673. glFogfv(GL_FOG_COLOR, fogColor);
  1674. glFogf(GL_FOG_DENSITY, density);
  1675. glFogf(GL_FOG_START, start);
  1676. glFogf(GL_FOG_END, end);
  1677. // XXX Hint here?
  1678. }
  1679. VertexElementType GLRenderSystem::getColourVertexElementType(void) const
  1680. {
  1681. return VET_COLOUR_ABGR;
  1682. }
  1683. void GLRenderSystem::_convertProjectionMatrix(const Matrix4& matrix,
  1684. Matrix4& dest, bool forGpuProgram)
  1685. {
  1686. // no any conversion request for OpenGL
  1687. dest = matrix;
  1688. }
  1689. void GLRenderSystem::_makeProjectionMatrix(const Radian& fovy, float aspect, float nearPlane,
  1690. float farPlane, Matrix4& dest, bool forGpuProgram)
  1691. {
  1692. Radian thetaY ( fovy / 2.0f );
  1693. float tanThetaY = Math::Tan(thetaY);
  1694. //float thetaX = thetaY * aspect;
  1695. //float tanThetaX = Math::Tan(thetaX);
  1696. // Calc matrix elements
  1697. float w = (1.0f / tanThetaY) / aspect;
  1698. float h = 1.0f / tanThetaY;
  1699. float q, qn;
  1700. if (farPlane == 0)
  1701. {
  1702. // Infinite far plane
  1703. q = Frustum::INFINITE_FAR_PLANE_ADJUST - 1;
  1704. qn = nearPlane * (Frustum::INFINITE_FAR_PLANE_ADJUST - 2);
  1705. }
  1706. else
  1707. {
  1708. q = -(farPlane + nearPlane) / (farPlane - nearPlane);
  1709. qn = -2 * (farPlane * nearPlane) / (farPlane - nearPlane);
  1710. }
  1711. // NB This creates Z in range [-1,1]
  1712. //
  1713. // [ w 0 0 0 ]
  1714. // [ 0 h 0 0 ]
  1715. // [ 0 0 q qn ]
  1716. // [ 0 0 -1 0 ]
  1717. dest = Matrix4::ZERO;
  1718. dest[0][0] = w;
  1719. dest[1][1] = h;
  1720. dest[2][2] = q;
  1721. dest[2][3] = qn;
  1722. dest[3][2] = -1;
  1723. }
  1724. void GLRenderSystem::_makeOrthoMatrix(const Radian& fovy, float aspect, float nearPlane,
  1725. float farPlane, Matrix4& dest, bool forGpuProgram)
  1726. {
  1727. Radian thetaY (fovy / 2.0f);
  1728. float tanThetaY = Math::Tan(thetaY);
  1729. //float thetaX = thetaY * aspect;
  1730. float tanThetaX = tanThetaY * aspect; //Math::Tan(thetaX);
  1731. float half_w = tanThetaX * nearPlane;
  1732. float half_h = tanThetaY * nearPlane;
  1733. float iw = 1.0f / half_w;
  1734. float ih = 1.0f / half_h;
  1735. float q;
  1736. if (farPlane == 0)
  1737. {
  1738. q = 0;
  1739. }
  1740. else
  1741. {
  1742. q = 2.0f / (farPlane - nearPlane);
  1743. }
  1744. dest = Matrix4::ZERO;
  1745. dest[0][0] = iw;
  1746. dest[1][1] = ih;
  1747. dest[2][2] = -q;
  1748. dest[2][3] = - (farPlane + nearPlane)/(farPlane - nearPlane);
  1749. dest[3][3] = 1;
  1750. }
  1751. void GLRenderSystem::_setPolygonMode(PolygonMode level)
  1752. {
  1753. GLenum glmode;
  1754. switch(level)
  1755. {
  1756. case PM_POINTS:
  1757. glmode = GL_POINT;
  1758. break;
  1759. case PM_WIREFRAME:
  1760. glmode = GL_LINE;
  1761. break;
  1762. default:
  1763. case PM_SOLID:
  1764. glmode = GL_FILL;
  1765. break;
  1766. }
  1767. glPolygonMode(GL_FRONT_AND_BACK, glmode);
  1768. }
  1769. //---------------------------------------------------------------------
  1770. void GLRenderSystem::setStencilCheckEnabled(bool enabled)
  1771. {
  1772. if (enabled)
  1773. {
  1774. glEnable(GL_STENCIL_TEST);
  1775. }
  1776. else
  1777. {
  1778. glDisable(GL_STENCIL_TEST);
  1779. }
  1780. }
  1781. //---------------------------------------------------------------------
  1782. void GLRenderSystem::setStencilBufferParams(CompareFunction func,
  1783. UINT32 refValue, UINT32 mask, StencilOperation stencilFailOp,
  1784. StencilOperation depthFailOp, StencilOperation passOp,
  1785. bool twoSidedOperation)
  1786. {
  1787. bool flip;
  1788. mStencilMask = mask;
  1789. if (twoSidedOperation)
  1790. {
  1791. if (!mCurrentCapabilities->hasCapability(RSC_TWO_SIDED_STENCIL))
  1792. CM_EXCEPT(InvalidParametersException, "2-sided stencils are not supported");
  1793. // NB: We should always treat CCW as front face for consistent with default
  1794. // culling mode. Therefore, we must take care with two-sided stencil settings.
  1795. flip = (mInvertVertexWinding && !mActiveRenderTarget->requiresTextureFlipping()) ||
  1796. (!mInvertVertexWinding && mActiveRenderTarget->requiresTextureFlipping());
  1797. if(GLEW_VERSION_2_0) // New GL2 commands
  1798. {
  1799. // Back
  1800. glStencilMaskSeparate(GL_BACK, mask);
  1801. glStencilFuncSeparate(GL_BACK, convertCompareFunction(func), refValue, mask);
  1802. glStencilOpSeparate(GL_BACK,
  1803. convertStencilOp(stencilFailOp, !flip),
  1804. convertStencilOp(depthFailOp, !flip),
  1805. convertStencilOp(passOp, !flip));
  1806. // Front
  1807. glStencilMaskSeparate(GL_FRONT, mask);
  1808. glStencilFuncSeparate(GL_FRONT, convertCompareFunction(func), refValue, mask);
  1809. glStencilOpSeparate(GL_FRONT,
  1810. convertStencilOp(stencilFailOp, flip),
  1811. convertStencilOp(depthFailOp, flip),
  1812. convertStencilOp(passOp, flip));
  1813. }
  1814. else // EXT_stencil_two_side
  1815. {
  1816. glEnable(GL_STENCIL_TEST_TWO_SIDE_EXT);
  1817. // Back
  1818. glActiveStencilFaceEXT(GL_BACK);
  1819. glStencilMask(mask);
  1820. glStencilFunc(convertCompareFunction(func), refValue, mask);
  1821. glStencilOp(
  1822. convertStencilOp(stencilFailOp, !flip),
  1823. convertStencilOp(depthFailOp, !flip),
  1824. convertStencilOp(passOp, !flip));
  1825. // Front
  1826. glActiveStencilFaceEXT(GL_FRONT);
  1827. glStencilMask(mask);
  1828. glStencilFunc(convertCompareFunction(func), refValue, mask);
  1829. glStencilOp(
  1830. convertStencilOp(stencilFailOp, flip),
  1831. convertStencilOp(depthFailOp, flip),
  1832. convertStencilOp(passOp, flip));
  1833. }
  1834. }
  1835. else
  1836. {
  1837. if(!GLEW_VERSION_2_0)
  1838. glDisable(GL_STENCIL_TEST_TWO_SIDE_EXT);
  1839. flip = false;
  1840. glStencilMask(mask);
  1841. glStencilFunc(convertCompareFunction(func), refValue, mask);
  1842. glStencilOp(
  1843. convertStencilOp(stencilFailOp, flip),
  1844. convertStencilOp(depthFailOp, flip),
  1845. convertStencilOp(passOp, flip));
  1846. }
  1847. }
  1848. //---------------------------------------------------------------------
  1849. GLint GLRenderSystem::convertCompareFunction(CompareFunction func) const
  1850. {
  1851. switch(func)
  1852. {
  1853. case CMPF_ALWAYS_FAIL:
  1854. return GL_NEVER;
  1855. case CMPF_ALWAYS_PASS:
  1856. return GL_ALWAYS;
  1857. case CMPF_LESS:
  1858. return GL_LESS;
  1859. case CMPF_LESS_EQUAL:
  1860. return GL_LEQUAL;
  1861. case CMPF_EQUAL:
  1862. return GL_EQUAL;
  1863. case CMPF_NOT_EQUAL:
  1864. return GL_NOTEQUAL;
  1865. case CMPF_GREATER_EQUAL:
  1866. return GL_GEQUAL;
  1867. case CMPF_GREATER:
  1868. return GL_GREATER;
  1869. };
  1870. // to keep compiler happy
  1871. return GL_ALWAYS;
  1872. }
  1873. //---------------------------------------------------------------------
  1874. GLint GLRenderSystem::convertStencilOp(StencilOperation op, bool invert) const
  1875. {
  1876. switch(op)
  1877. {
  1878. case SOP_KEEP:
  1879. return GL_KEEP;
  1880. case SOP_ZERO:
  1881. return GL_ZERO;
  1882. case SOP_REPLACE:
  1883. return GL_REPLACE;
  1884. case SOP_INCREMENT:
  1885. return invert ? GL_DECR : GL_INCR;
  1886. case SOP_DECREMENT:
  1887. return invert ? GL_INCR : GL_DECR;
  1888. case SOP_INCREMENT_WRAP:
  1889. return invert ? GL_DECR_WRAP_EXT : GL_INCR_WRAP_EXT;
  1890. case SOP_DECREMENT_WRAP:
  1891. return invert ? GL_INCR_WRAP_EXT : GL_DECR_WRAP_EXT;
  1892. case SOP_INVERT:
  1893. return GL_INVERT;
  1894. };
  1895. // to keep compiler happy
  1896. return SOP_KEEP;
  1897. }
  1898. //---------------------------------------------------------------------
  1899. GLuint GLRenderSystem::getCombinedMinMipFilter(void) const
  1900. {
  1901. switch(mMinFilter)
  1902. {
  1903. case FO_ANISOTROPIC:
  1904. case FO_LINEAR:
  1905. switch(mMipFilter)
  1906. {
  1907. case FO_ANISOTROPIC:
  1908. case FO_LINEAR:
  1909. // linear min, linear mip
  1910. return GL_LINEAR_MIPMAP_LINEAR;
  1911. case FO_POINT:
  1912. // linear min, point mip
  1913. return GL_LINEAR_MIPMAP_NEAREST;
  1914. case FO_NONE:
  1915. // linear min, no mip
  1916. return GL_LINEAR;
  1917. }
  1918. break;
  1919. case FO_POINT:
  1920. case FO_NONE:
  1921. switch(mMipFilter)
  1922. {
  1923. case FO_ANISOTROPIC:
  1924. case FO_LINEAR:
  1925. // nearest min, linear mip
  1926. return GL_NEAREST_MIPMAP_LINEAR;
  1927. case FO_POINT:
  1928. // nearest min, point mip
  1929. return GL_NEAREST_MIPMAP_NEAREST;
  1930. case FO_NONE:
  1931. // nearest min, no mip
  1932. return GL_NEAREST;
  1933. }
  1934. break;
  1935. }
  1936. // should never get here
  1937. return 0;
  1938. }
  1939. //---------------------------------------------------------------------
  1940. void GLRenderSystem::_setTextureUnitFiltering(size_t unit,
  1941. FilterType ftype, FilterOptions fo)
  1942. {
  1943. if (!activateGLTextureUnit(unit))
  1944. return;
  1945. switch(ftype)
  1946. {
  1947. case FT_MIN:
  1948. mMinFilter = fo;
  1949. // Combine with existing mip filter
  1950. glTexParameteri(
  1951. mTextureTypes[unit],
  1952. GL_TEXTURE_MIN_FILTER,
  1953. getCombinedMinMipFilter());
  1954. break;
  1955. case FT_MAG:
  1956. switch (fo)
  1957. {
  1958. case FO_ANISOTROPIC: // GL treats linear and aniso the same
  1959. case FO_LINEAR:
  1960. glTexParameteri(
  1961. mTextureTypes[unit],
  1962. GL_TEXTURE_MAG_FILTER,
  1963. GL_LINEAR);
  1964. break;
  1965. case FO_POINT:
  1966. case FO_NONE:
  1967. glTexParameteri(
  1968. mTextureTypes[unit],
  1969. GL_TEXTURE_MAG_FILTER,
  1970. GL_NEAREST);
  1971. break;
  1972. }
  1973. break;
  1974. case FT_MIP:
  1975. mMipFilter = fo;
  1976. // Combine with existing min filter
  1977. glTexParameteri(
  1978. mTextureTypes[unit],
  1979. GL_TEXTURE_MIN_FILTER,
  1980. getCombinedMinMipFilter());
  1981. break;
  1982. }
  1983. activateGLTextureUnit(0);
  1984. }
  1985. //---------------------------------------------------------------------
  1986. GLfloat GLRenderSystem::_getCurrentAnisotropy(size_t unit)
  1987. {
  1988. GLfloat curAniso = 0;
  1989. glGetTexParameterfv(mTextureTypes[unit],
  1990. GL_TEXTURE_MAX_ANISOTROPY_EXT, &curAniso);
  1991. return curAniso ? curAniso : 1;
  1992. }
  1993. //---------------------------------------------------------------------
  1994. void GLRenderSystem::_setTextureLayerAnisotropy(size_t unit, unsigned int maxAnisotropy)
  1995. {
  1996. if (!mCurrentCapabilities->hasCapability(RSC_ANISOTROPY))
  1997. return;
  1998. if (!activateGLTextureUnit(unit))
  1999. return;
  2000. GLfloat largest_supported_anisotropy = 0;
  2001. glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &largest_supported_anisotropy);
  2002. if (maxAnisotropy > largest_supported_anisotropy)
  2003. maxAnisotropy = largest_supported_anisotropy ?
  2004. static_cast<UINT32>(largest_supported_anisotropy) : 1;
  2005. if (_getCurrentAnisotropy(unit) != maxAnisotropy)
  2006. glTexParameterf(mTextureTypes[unit], GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)maxAnisotropy);
  2007. activateGLTextureUnit(0);
  2008. }
  2009. //---------------------------------------------------------------------
  2010. void GLRenderSystem::setVertexDeclaration(VertexDeclaration* decl)
  2011. {
  2012. }
  2013. //---------------------------------------------------------------------
  2014. void GLRenderSystem::setVertexBufferBinding(VertexBufferBinding* binding)
  2015. {
  2016. }
  2017. //---------------------------------------------------------------------
  2018. void GLRenderSystem::_render(const RenderOperation& op)
  2019. {
  2020. // Call super class
  2021. RenderSystem::_render(op);
  2022. void* pBufferData = 0;
  2023. bool multitexturing = (getCapabilities()->getNumTextureUnits() > 1);
  2024. const VertexDeclaration::VertexElementList& decl =
  2025. op.vertexData->vertexDeclaration->getElements();
  2026. VertexDeclaration::VertexElementList::const_iterator elem, elemEnd;
  2027. elemEnd = decl.end();
  2028. vector<GLuint>::type attribsBound;
  2029. for (elem = decl.begin(); elem != elemEnd; ++elem)
  2030. {
  2031. if (!op.vertexData->vertexBufferBinding->isBufferBound(elem->getSource()))
  2032. continue; // skip unbound elements
  2033. HardwareVertexBufferPtr vertexBuffer =
  2034. op.vertexData->vertexBufferBinding->getBuffer(elem->getSource());
  2035. if(mCurrentCapabilities->hasCapability(RSC_VBO))
  2036. {
  2037. glBindBufferARB(GL_ARRAY_BUFFER_ARB,
  2038. static_cast<const GLHardwareVertexBuffer*>(vertexBuffer.get())->getGLBufferId());
  2039. pBufferData = VBO_BUFFER_OFFSET(elem->getOffset());
  2040. }
  2041. else
  2042. {
  2043. pBufferData = static_cast<const GLDefaultHardwareVertexBuffer*>(vertexBuffer.get())->getDataPtr(elem->getOffset());
  2044. }
  2045. if (op.vertexData->vertexStart)
  2046. {
  2047. pBufferData = static_cast<char*>(pBufferData) + op.vertexData->vertexStart * vertexBuffer->getVertexSize();
  2048. }
  2049. unsigned int i = 0;
  2050. VertexElementSemantic sem = elem->getSemantic();
  2051. bool isCustomAttrib = false;
  2052. if (mCurrentVertexProgram)
  2053. isCustomAttrib = mCurrentVertexProgram->isAttributeValid(sem, elem->getIndex());
  2054. // Custom attribute support
  2055. // tangents, binormals, blendweights etc always via this route
  2056. // builtins may be done this way too
  2057. if (isCustomAttrib)
  2058. {
  2059. GLint attrib = mCurrentVertexProgram->getAttributeIndex(sem, elem->getIndex());
  2060. unsigned short typeCount = VertexElement::getTypeCount(elem->getType());
  2061. GLboolean normalised = GL_FALSE;
  2062. switch(elem->getType())
  2063. {
  2064. case VET_COLOUR:
  2065. case VET_COLOUR_ABGR:
  2066. case VET_COLOUR_ARGB:
  2067. // Because GL takes these as a sequence of single unsigned bytes, count needs to be 4
  2068. // VertexElement::getTypeCount treats them as 1 (RGBA)
  2069. // Also need to normalise the fixed-point data
  2070. typeCount = 4;
  2071. normalised = GL_TRUE;
  2072. break;
  2073. default:
  2074. break;
  2075. };
  2076. glVertexAttribPointerARB(
  2077. attrib,
  2078. typeCount,
  2079. GLHardwareBufferManager::getGLType(elem->getType()),
  2080. normalised,
  2081. static_cast<GLsizei>(vertexBuffer->getVertexSize()),
  2082. pBufferData);
  2083. glEnableVertexAttribArrayARB(attrib);
  2084. attribsBound.push_back(attrib);
  2085. }
  2086. else
  2087. {
  2088. // fixed-function & builtin attribute support
  2089. switch(sem)
  2090. {
  2091. case VES_POSITION:
  2092. glVertexPointer(VertexElement::getTypeCount(
  2093. elem->getType()),
  2094. GLHardwareBufferManager::getGLType(elem->getType()),
  2095. static_cast<GLsizei>(vertexBuffer->getVertexSize()),
  2096. pBufferData);
  2097. glEnableClientState( GL_VERTEX_ARRAY );
  2098. break;
  2099. case VES_NORMAL:
  2100. glNormalPointer(
  2101. GLHardwareBufferManager::getGLType(elem->getType()),
  2102. static_cast<GLsizei>(vertexBuffer->getVertexSize()),
  2103. pBufferData);
  2104. glEnableClientState( GL_NORMAL_ARRAY );
  2105. break;
  2106. case VES_DIFFUSE:
  2107. glColorPointer(4,
  2108. GLHardwareBufferManager::getGLType(elem->getType()),
  2109. static_cast<GLsizei>(vertexBuffer->getVertexSize()),
  2110. pBufferData);
  2111. glEnableClientState( GL_COLOR_ARRAY );
  2112. break;
  2113. case VES_SPECULAR:
  2114. if (GLEW_EXT_secondary_color)
  2115. {
  2116. glSecondaryColorPointerEXT(4,
  2117. GLHardwareBufferManager::getGLType(elem->getType()),
  2118. static_cast<GLsizei>(vertexBuffer->getVertexSize()),
  2119. pBufferData);
  2120. glEnableClientState( GL_SECONDARY_COLOR_ARRAY );
  2121. }
  2122. break;
  2123. case VES_TEXTURE_COORDINATES:
  2124. if (mCurrentVertexProgram)
  2125. {
  2126. // Programmable pipeline - direct UV assignment
  2127. glClientActiveTextureARB(GL_TEXTURE0 + elem->getIndex());
  2128. glTexCoordPointer(
  2129. VertexElement::getTypeCount(elem->getType()),
  2130. GLHardwareBufferManager::getGLType(elem->getType()),
  2131. static_cast<GLsizei>(vertexBuffer->getVertexSize()),
  2132. pBufferData);
  2133. glEnableClientState( GL_TEXTURE_COORD_ARRAY );
  2134. }
  2135. else
  2136. {
  2137. // fixed function matching to units based on tex_coord_set
  2138. for (i = 0; i < mDisabledTexUnitsFrom; i++)
  2139. {
  2140. // Only set this texture unit's texcoord pointer if it
  2141. // is supposed to be using this element's index
  2142. if (mTextureCoordIndex[i] == elem->getIndex() && i < mFixedFunctionTextureUnits)
  2143. {
  2144. if (multitexturing)
  2145. glClientActiveTextureARB(GL_TEXTURE0 + i);
  2146. glTexCoordPointer(
  2147. VertexElement::getTypeCount(elem->getType()),
  2148. GLHardwareBufferManager::getGLType(elem->getType()),
  2149. static_cast<GLsizei>(vertexBuffer->getVertexSize()),
  2150. pBufferData);
  2151. glEnableClientState( GL_TEXTURE_COORD_ARRAY );
  2152. }
  2153. }
  2154. }
  2155. break;
  2156. default:
  2157. break;
  2158. };
  2159. } // isCustomAttrib
  2160. }
  2161. if (multitexturing)
  2162. glClientActiveTextureARB(GL_TEXTURE0);
  2163. // Find the correct type to render
  2164. GLint primType;
  2165. //Use adjacency if there is a geometry program and it requested adjacency info
  2166. bool useAdjacency = (mGeometryProgramBound && mCurrentGeometryProgram->isAdjacencyInfoRequired());
  2167. switch (op.operationType)
  2168. {
  2169. case RenderOperation::OT_POINT_LIST:
  2170. primType = GL_POINTS;
  2171. break;
  2172. case RenderOperation::OT_LINE_LIST:
  2173. primType = useAdjacency ? GL_LINES_ADJACENCY_EXT : GL_LINES;
  2174. break;
  2175. case RenderOperation::OT_LINE_STRIP:
  2176. primType = useAdjacency ? GL_LINE_STRIP_ADJACENCY_EXT : GL_LINE_STRIP;
  2177. break;
  2178. default:
  2179. case RenderOperation::OT_TRIANGLE_LIST:
  2180. primType = useAdjacency ? GL_TRIANGLES_ADJACENCY_EXT : GL_TRIANGLES;
  2181. break;
  2182. case RenderOperation::OT_TRIANGLE_STRIP:
  2183. primType = useAdjacency ? GL_TRIANGLE_STRIP_ADJACENCY_EXT : GL_TRIANGLE_STRIP;
  2184. break;
  2185. case RenderOperation::OT_TRIANGLE_FAN:
  2186. primType = GL_TRIANGLE_FAN;
  2187. break;
  2188. }
  2189. if (op.useIndexes)
  2190. {
  2191. if(mCurrentCapabilities->hasCapability(RSC_VBO))
  2192. {
  2193. glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB,
  2194. static_cast<GLHardwareIndexBuffer*>(
  2195. op.indexData->indexBuffer.get())->getGLBufferId());
  2196. pBufferData = VBO_BUFFER_OFFSET(
  2197. op.indexData->indexStart * op.indexData->indexBuffer->getIndexSize());
  2198. }
  2199. else
  2200. {
  2201. pBufferData = static_cast<GLDefaultHardwareIndexBuffer*>(
  2202. op.indexData->indexBuffer.get())->getDataPtr(
  2203. op.indexData->indexStart * op.indexData->indexBuffer->getIndexSize());
  2204. }
  2205. GLenum indexType = (op.indexData->indexBuffer->getType() == HardwareIndexBuffer::IT_16BIT) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
  2206. do
  2207. {
  2208. // Update derived depth bias
  2209. if (mDerivedDepthBias && mCurrentPassIterationNum > 0)
  2210. {
  2211. _setDepthBias(mDerivedDepthBiasBase +
  2212. mDerivedDepthBiasMultiplier * mCurrentPassIterationNum,
  2213. mDerivedDepthBiasSlopeScale);
  2214. }
  2215. glDrawElements(primType, op.indexData->indexCount, indexType, pBufferData);
  2216. } while (updatePassIterationRenderState());
  2217. }
  2218. else
  2219. {
  2220. do
  2221. {
  2222. // Update derived depth bias
  2223. if (mDerivedDepthBias && mCurrentPassIterationNum > 0)
  2224. {
  2225. _setDepthBias(mDerivedDepthBiasBase +
  2226. mDerivedDepthBiasMultiplier * mCurrentPassIterationNum,
  2227. mDerivedDepthBiasSlopeScale);
  2228. }
  2229. glDrawArrays(primType, 0, op.vertexData->vertexCount);
  2230. } while (updatePassIterationRenderState());
  2231. }
  2232. glDisableClientState( GL_VERTEX_ARRAY );
  2233. // only valid up to GL_MAX_TEXTURE_UNITS, which is recorded in mFixedFunctionTextureUnits
  2234. if (multitexturing)
  2235. {
  2236. for (int i = 0; i < mFixedFunctionTextureUnits; i++)
  2237. {
  2238. glClientActiveTextureARB(GL_TEXTURE0 + i);
  2239. glDisableClientState( GL_TEXTURE_COORD_ARRAY );
  2240. }
  2241. glClientActiveTextureARB(GL_TEXTURE0);
  2242. }
  2243. else
  2244. {
  2245. glDisableClientState( GL_TEXTURE_COORD_ARRAY );
  2246. }
  2247. glDisableClientState( GL_NORMAL_ARRAY );
  2248. glDisableClientState( GL_COLOR_ARRAY );
  2249. if (GLEW_EXT_secondary_color)
  2250. {
  2251. glDisableClientState( GL_SECONDARY_COLOR_ARRAY );
  2252. }
  2253. // unbind any custom attributes
  2254. for (vector<GLuint>::type::iterator ai = attribsBound.begin(); ai != attribsBound.end(); ++ai)
  2255. {
  2256. glDisableVertexAttribArrayARB(*ai);
  2257. }
  2258. glColor4f(1,1,1,1);
  2259. if (GLEW_EXT_secondary_color)
  2260. {
  2261. glSecondaryColor3fEXT(0.0f, 0.0f, 0.0f);
  2262. }
  2263. }
  2264. //---------------------------------------------------------------------
  2265. void GLRenderSystem::setNormaliseNormals(bool normalise)
  2266. {
  2267. if (normalise)
  2268. glEnable(GL_NORMALIZE);
  2269. else
  2270. glDisable(GL_NORMALIZE);
  2271. }
  2272. //---------------------------------------------------------------------
  2273. void GLRenderSystem::bindGpuProgram(GpuProgram* prg)
  2274. {
  2275. GLGpuProgram* glprg = static_cast<GLGpuProgram*>(prg);
  2276. // Unbind previous gpu program first.
  2277. //
  2278. // Note:
  2279. // 1. Even if both previous and current are the same object, we can't
  2280. // bypass re-bind completely since the object itself maybe modified.
  2281. // But we can bypass unbind based on the assumption that object
  2282. // internally GL program type shouldn't be changed after it has
  2283. // been created. The behavior of bind to a GL program type twice
  2284. // should be same as unbind and rebind that GL program type, even
  2285. // for difference objects.
  2286. // 2. We also assumed that the program's type (vertex or fragment) should
  2287. // not be changed during it's in using. If not, the following switch
  2288. // statement will confuse GL state completely, and we can't fix it
  2289. // here. To fix this case, we must coding the program implementation
  2290. // itself, if type is changing (during load/unload, etc), and it's inuse,
  2291. // unbind and notify render system to correct for its state.
  2292. //
  2293. switch (glprg->getType())
  2294. {
  2295. case GPT_VERTEX_PROGRAM:
  2296. if (mCurrentVertexProgram != glprg)
  2297. {
  2298. if (mCurrentVertexProgram)
  2299. mCurrentVertexProgram->unbindProgram();
  2300. mCurrentVertexProgram = glprg;
  2301. }
  2302. break;
  2303. case GPT_FRAGMENT_PROGRAM:
  2304. if (mCurrentFragmentProgram != glprg)
  2305. {
  2306. if (mCurrentFragmentProgram)
  2307. mCurrentFragmentProgram->unbindProgram();
  2308. mCurrentFragmentProgram = glprg;
  2309. }
  2310. break;
  2311. case GPT_GEOMETRY_PROGRAM:
  2312. if (mCurrentGeometryProgram != glprg)
  2313. {
  2314. if (mCurrentGeometryProgram)
  2315. mCurrentGeometryProgram->unbindProgram();
  2316. mCurrentGeometryProgram = glprg;
  2317. }
  2318. break;
  2319. }
  2320. // Bind the program
  2321. glprg->bindProgram();
  2322. RenderSystem::bindGpuProgram(prg);
  2323. }
  2324. //---------------------------------------------------------------------
  2325. void GLRenderSystem::unbindGpuProgram(GpuProgramType gptype)
  2326. {
  2327. if (gptype == GPT_VERTEX_PROGRAM && mCurrentVertexProgram)
  2328. {
  2329. mActiveVertexGpuProgramParameters = nullptr;
  2330. mCurrentVertexProgram->unbindProgram();
  2331. mCurrentVertexProgram = 0;
  2332. }
  2333. else if (gptype == GPT_GEOMETRY_PROGRAM && mCurrentGeometryProgram)
  2334. {
  2335. mActiveGeometryGpuProgramParameters = nullptr;
  2336. mCurrentGeometryProgram->unbindProgram();
  2337. mCurrentGeometryProgram = 0;
  2338. }
  2339. else if (gptype == GPT_FRAGMENT_PROGRAM && mCurrentFragmentProgram)
  2340. {
  2341. mActiveFragmentGpuProgramParameters = nullptr;
  2342. mCurrentFragmentProgram->unbindProgram();
  2343. mCurrentFragmentProgram = 0;
  2344. }
  2345. RenderSystem::unbindGpuProgram(gptype);
  2346. }
  2347. //---------------------------------------------------------------------
  2348. void GLRenderSystem::bindGpuProgramParameters(GpuProgramType gptype, GpuProgramParametersSharedPtr params, UINT16 mask)
  2349. {
  2350. if (mask & (UINT16)GPV_GLOBAL)
  2351. {
  2352. // We could maybe use GL_EXT_bindable_uniform here to produce Dx10-style
  2353. // shared constant buffers, but GPU support seems fairly weak?
  2354. // for now, just copy
  2355. params->_copySharedParams();
  2356. }
  2357. switch (gptype)
  2358. {
  2359. case GPT_VERTEX_PROGRAM:
  2360. mActiveVertexGpuProgramParameters = params;
  2361. mCurrentVertexProgram->bindProgramParameters(params, mask);
  2362. break;
  2363. case GPT_GEOMETRY_PROGRAM:
  2364. mActiveGeometryGpuProgramParameters = params;
  2365. mCurrentGeometryProgram->bindProgramParameters(params, mask);
  2366. break;
  2367. case GPT_FRAGMENT_PROGRAM:
  2368. mActiveFragmentGpuProgramParameters = params;
  2369. mCurrentFragmentProgram->bindProgramParameters(params, mask);
  2370. break;
  2371. }
  2372. }
  2373. //---------------------------------------------------------------------
  2374. void GLRenderSystem::bindGpuProgramPassIterationParameters(GpuProgramType gptype)
  2375. {
  2376. switch (gptype)
  2377. {
  2378. case GPT_VERTEX_PROGRAM:
  2379. mCurrentVertexProgram->bindProgramPassIterationParameters(mActiveVertexGpuProgramParameters);
  2380. break;
  2381. case GPT_GEOMETRY_PROGRAM:
  2382. mCurrentGeometryProgram->bindProgramPassIterationParameters(mActiveGeometryGpuProgramParameters);
  2383. break;
  2384. case GPT_FRAGMENT_PROGRAM:
  2385. mCurrentFragmentProgram->bindProgramPassIterationParameters(mActiveFragmentGpuProgramParameters);
  2386. break;
  2387. }
  2388. }
  2389. //---------------------------------------------------------------------
  2390. void GLRenderSystem::setClipPlanesImpl(const PlaneList& clipPlanes)
  2391. {
  2392. // A note on GL user clipping:
  2393. // When an ARB vertex program is enabled in GL, user clipping is completely
  2394. // disabled. There is no way around this, it's just turned off.
  2395. // When using GLSL, user clipping can work but you have to include a
  2396. // glClipVertex command in your vertex shader.
  2397. // Thus the planes set here may not actually be respected.
  2398. size_t i = 0;
  2399. size_t numClipPlanes;
  2400. GLdouble clipPlane[4];
  2401. // Save previous modelview
  2402. glMatrixMode(GL_MODELVIEW);
  2403. glPushMatrix();
  2404. // just load view matrix (identity world)
  2405. GLfloat mat[16];
  2406. makeGLMatrix(mat, mViewMatrix);
  2407. glLoadMatrixf(mat);
  2408. numClipPlanes = clipPlanes.size();
  2409. for (i = 0; i < numClipPlanes; ++i)
  2410. {
  2411. GLenum clipPlaneId = static_cast<GLenum>(GL_CLIP_PLANE0 + i);
  2412. const Plane& plane = clipPlanes[i];
  2413. if (i >= 6/*GL_MAX_CLIP_PLANES*/)
  2414. {
  2415. CM_EXCEPT(RenderingAPIException, "Unable to set clip plane");
  2416. }
  2417. clipPlane[0] = plane.normal.x;
  2418. clipPlane[1] = plane.normal.y;
  2419. clipPlane[2] = plane.normal.z;
  2420. clipPlane[3] = plane.d;
  2421. glClipPlane(clipPlaneId, clipPlane);
  2422. glEnable(clipPlaneId);
  2423. }
  2424. // disable remaining clip planes
  2425. for ( ; i < 6/*GL_MAX_CLIP_PLANES*/; ++i)
  2426. {
  2427. glDisable(static_cast<GLenum>(GL_CLIP_PLANE0 + i));
  2428. }
  2429. // restore matrices
  2430. glPopMatrix();
  2431. }
  2432. //---------------------------------------------------------------------
  2433. void GLRenderSystem::setScissorTest(bool enabled, size_t left,
  2434. size_t top, size_t right, size_t bottom)
  2435. {
  2436. // If request texture flipping, use "upper-left", otherwise use "lower-left"
  2437. bool flipping = mActiveRenderTarget->requiresTextureFlipping();
  2438. // GL measures from the bottom, not the top
  2439. size_t targetHeight = mActiveRenderTarget->getHeight();
  2440. // Calculate the "lower-left" corner of the viewport
  2441. GLsizei x = 0, y = 0, w = 0, h = 0;
  2442. if (enabled)
  2443. {
  2444. glEnable(GL_SCISSOR_TEST);
  2445. // NB GL uses width / height rather than right / bottom
  2446. x = left;
  2447. if (flipping)
  2448. y = top;
  2449. else
  2450. y = targetHeight - bottom;
  2451. w = right - left;
  2452. h = bottom - top;
  2453. glScissor(x, y, w, h);
  2454. }
  2455. else
  2456. {
  2457. glDisable(GL_SCISSOR_TEST);
  2458. // GL requires you to reset the scissor when disabling
  2459. w = mActiveViewport->getActualWidth();
  2460. h = mActiveViewport->getActualHeight();
  2461. x = mActiveViewport->getActualLeft();
  2462. if (flipping)
  2463. y = mActiveViewport->getActualTop();
  2464. else
  2465. y = targetHeight - mActiveViewport->getActualTop() - h;
  2466. glScissor(x, y, w, h);
  2467. }
  2468. }
  2469. //---------------------------------------------------------------------
  2470. void GLRenderSystem::clearFrameBuffer(unsigned int buffers,
  2471. const Color& colour, float depth, unsigned short stencil)
  2472. {
  2473. bool colourMask = !mColourWrite[0] || !mColourWrite[1]
  2474. || !mColourWrite[2] || !mColourWrite[3];
  2475. GLbitfield flags = 0;
  2476. if (buffers & FBT_COLOUR)
  2477. {
  2478. flags |= GL_COLOR_BUFFER_BIT;
  2479. // Enable buffer for writing if it isn't
  2480. if (colourMask)
  2481. {
  2482. glColorMask(true, true, true, true);
  2483. }
  2484. glClearColor(colour.r, colour.g, colour.b, colour.a);
  2485. }
  2486. if (buffers & FBT_DEPTH)
  2487. {
  2488. flags |= GL_DEPTH_BUFFER_BIT;
  2489. // Enable buffer for writing if it isn't
  2490. if (!mDepthWrite)
  2491. {
  2492. glDepthMask( GL_TRUE );
  2493. }
  2494. glClearDepth(depth);
  2495. }
  2496. if (buffers & FBT_STENCIL)
  2497. {
  2498. flags |= GL_STENCIL_BUFFER_BIT;
  2499. // Enable buffer for writing if it isn't
  2500. glStencilMask(0xFFFFFFFF);
  2501. glClearStencil(stencil);
  2502. }
  2503. // Should be enable scissor test due the clear region is
  2504. // relied on scissor box bounds.
  2505. GLboolean scissorTestEnabled = glIsEnabled(GL_SCISSOR_TEST);
  2506. if (!scissorTestEnabled)
  2507. {
  2508. glEnable(GL_SCISSOR_TEST);
  2509. }
  2510. // Sets the scissor box as same as viewport
  2511. GLint viewport[4] = { 0, 0, 0, 0 };
  2512. GLint scissor[4] = { 0, 0, 0, 0 };
  2513. glGetIntegerv(GL_VIEWPORT, viewport);
  2514. glGetIntegerv(GL_SCISSOR_BOX, scissor);
  2515. bool scissorBoxDifference =
  2516. viewport[0] != scissor[0] || viewport[1] != scissor[1] ||
  2517. viewport[2] != scissor[2] || viewport[3] != scissor[3];
  2518. if (scissorBoxDifference)
  2519. {
  2520. glScissor(viewport[0], viewport[1], viewport[2], viewport[3]);
  2521. }
  2522. // Clear buffers
  2523. glClear(flags);
  2524. // Restore scissor box
  2525. if (scissorBoxDifference)
  2526. {
  2527. glScissor(scissor[0], scissor[1], scissor[2], scissor[3]);
  2528. }
  2529. // Restore scissor test
  2530. if (!scissorTestEnabled)
  2531. {
  2532. glDisable(GL_SCISSOR_TEST);
  2533. }
  2534. // Reset buffer write state
  2535. if (!mDepthWrite && (buffers & FBT_DEPTH))
  2536. {
  2537. glDepthMask( GL_FALSE );
  2538. }
  2539. if (colourMask && (buffers & FBT_COLOUR))
  2540. {
  2541. glColorMask(mColourWrite[0], mColourWrite[1], mColourWrite[2], mColourWrite[3]);
  2542. }
  2543. if (buffers & FBT_STENCIL)
  2544. {
  2545. glStencilMask(mStencilMask);
  2546. }
  2547. }
  2548. // ------------------------------------------------------------------
  2549. void GLRenderSystem::_makeProjectionMatrix(float left, float right,
  2550. float bottom, float top, float nearPlane, float farPlane, Matrix4& dest,
  2551. bool forGpuProgram)
  2552. {
  2553. float width = right - left;
  2554. float height = top - bottom;
  2555. float q, qn;
  2556. if (farPlane == 0)
  2557. {
  2558. // Infinite far plane
  2559. q = Frustum::INFINITE_FAR_PLANE_ADJUST - 1;
  2560. qn = nearPlane * (Frustum::INFINITE_FAR_PLANE_ADJUST - 2);
  2561. }
  2562. else
  2563. {
  2564. q = -(farPlane + nearPlane) / (farPlane - nearPlane);
  2565. qn = -2 * (farPlane * nearPlane) / (farPlane - nearPlane);
  2566. }
  2567. dest = Matrix4::ZERO;
  2568. dest[0][0] = 2 * nearPlane / width;
  2569. dest[0][2] = (right+left) / width;
  2570. dest[1][1] = 2 * nearPlane / height;
  2571. dest[1][2] = (top+bottom) / height;
  2572. dest[2][2] = q;
  2573. dest[2][3] = qn;
  2574. dest[3][2] = -1;
  2575. }
  2576. //---------------------------------------------------------------------
  2577. HardwareOcclusionQuery* GLRenderSystem::createHardwareOcclusionQuery(void)
  2578. {
  2579. GLHardwareOcclusionQuery* ret = new GLHardwareOcclusionQuery();
  2580. mHwOcclusionQueries.push_back(ret);
  2581. return ret;
  2582. }
  2583. //---------------------------------------------------------------------
  2584. float GLRenderSystem::getHorizontalTexelOffset(void)
  2585. {
  2586. // No offset in GL
  2587. return 0.0f;
  2588. }
  2589. //---------------------------------------------------------------------
  2590. float GLRenderSystem::getVerticalTexelOffset(void)
  2591. {
  2592. // No offset in GL
  2593. return 0.0f;
  2594. }
  2595. //---------------------------------------------------------------------
  2596. void GLRenderSystem::_applyObliqueDepthProjection(Matrix4& matrix, const Plane& plane,
  2597. bool forGpuProgram)
  2598. {
  2599. // Thanks to Eric Lenyel for posting this calculation at www.terathon.com
  2600. // Calculate the clip-space corner point opposite the clipping plane
  2601. // as (sgn(clipPlane.x), sgn(clipPlane.y), 1, 1) and
  2602. // transform it into camera space by multiplying it
  2603. // by the inverse of the projection matrix
  2604. Vector4 q;
  2605. q.x = (Math::Sign(plane.normal.x) + matrix[0][2]) / matrix[0][0];
  2606. q.y = (Math::Sign(plane.normal.y) + matrix[1][2]) / matrix[1][1];
  2607. q.z = -1.0F;
  2608. q.w = (1.0F + matrix[2][2]) / matrix[2][3];
  2609. // Calculate the scaled plane vector
  2610. Vector4 clipPlane4d(plane.normal.x, plane.normal.y, plane.normal.z, plane.d);
  2611. Vector4 c = clipPlane4d * (2.0F / (clipPlane4d.dotProduct(q)));
  2612. // Replace the third row of the projection matrix
  2613. matrix[2][0] = c.x;
  2614. matrix[2][1] = c.y;
  2615. matrix[2][2] = c.z + 1.0F;
  2616. matrix[2][3] = c.w;
  2617. }
  2618. //---------------------------------------------------------------------
  2619. void GLRenderSystem::_oneTimeContextInitialization()
  2620. {
  2621. if (GLEW_VERSION_1_2)
  2622. {
  2623. // Set nicer lighting model -- d3d9 has this by default
  2624. glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
  2625. glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, 1);
  2626. }
  2627. if (GLEW_VERSION_1_4)
  2628. {
  2629. glEnable(GL_COLOR_SUM);
  2630. glDisable(GL_DITHER);
  2631. }
  2632. // Check for FSAA
  2633. // Enable the extension if it was enabled by the GLSupport
  2634. if (mGLSupport->checkExtension("GL_ARB_multisample"))
  2635. {
  2636. int fsaa_active = false;
  2637. glGetIntegerv(GL_SAMPLE_BUFFERS_ARB,(GLint*)&fsaa_active);
  2638. if(fsaa_active)
  2639. {
  2640. glEnable(GL_MULTISAMPLE_ARB);
  2641. }
  2642. }
  2643. }
  2644. //---------------------------------------------------------------------
  2645. void GLRenderSystem::_switchContext(GLContext *context)
  2646. {
  2647. // Unbind GPU programs and rebind to new context later, because
  2648. // scene manager treat render system as ONE 'context' ONLY, and it
  2649. // cached the GPU programs using state.
  2650. if (mCurrentVertexProgram)
  2651. mCurrentVertexProgram->unbindProgram();
  2652. if (mCurrentGeometryProgram)
  2653. mCurrentGeometryProgram->unbindProgram();
  2654. if (mCurrentFragmentProgram)
  2655. mCurrentFragmentProgram->unbindProgram();
  2656. // Disable lights
  2657. mCurrentLights = 0;
  2658. // Disable textures
  2659. _disableTextureUnitsFrom(0);
  2660. // It's ready for switching
  2661. if (mCurrentContext)
  2662. mCurrentContext->endCurrent();
  2663. mCurrentContext = context;
  2664. mCurrentContext->setCurrent();
  2665. // Check if the context has already done one-time initialisation
  2666. if(!mCurrentContext->getInitialized())
  2667. {
  2668. _oneTimeContextInitialization();
  2669. mCurrentContext->setInitialized();
  2670. }
  2671. // Rebind GPU programs to new context
  2672. if (mCurrentVertexProgram)
  2673. mCurrentVertexProgram->bindProgram();
  2674. if (mCurrentGeometryProgram)
  2675. mCurrentGeometryProgram->bindProgram();
  2676. if (mCurrentFragmentProgram)
  2677. mCurrentFragmentProgram->bindProgram();
  2678. // Must reset depth/colour write mask to according with user desired, otherwise,
  2679. // clearFrameBuffer would be wrong because the value we are recorded may be
  2680. // difference with the really state stored in GL context.
  2681. glDepthMask(mDepthWrite);
  2682. glColorMask(mColourWrite[0], mColourWrite[1], mColourWrite[2], mColourWrite[3]);
  2683. glStencilMask(mStencilMask);
  2684. }
  2685. //---------------------------------------------------------------------
  2686. void GLRenderSystem::_setRenderTarget(RenderTarget *target)
  2687. {
  2688. // Unbind frame buffer object
  2689. if(mActiveRenderTarget)
  2690. GLRTTManager::instancePtr()->unbind(mActiveRenderTarget);
  2691. mActiveRenderTarget = target;
  2692. // Switch context if different from current one
  2693. GLContext *newContext = 0;
  2694. target->getCustomAttribute("GLCONTEXT", &newContext);
  2695. if(newContext && mCurrentContext != newContext)
  2696. {
  2697. _switchContext(newContext);
  2698. }
  2699. // Bind frame buffer object
  2700. GLRTTManager::instancePtr()->bind(target);
  2701. if (GLEW_EXT_framebuffer_sRGB)
  2702. {
  2703. // Enable / disable sRGB states
  2704. if (target->isHardwareGammaEnabled())
  2705. {
  2706. glEnable(GL_FRAMEBUFFER_SRGB_EXT);
  2707. // Note: could test GL_FRAMEBUFFER_SRGB_CAPABLE_EXT here before
  2708. // enabling, but GL spec says incapable surfaces ignore the setting
  2709. // anyway. We test the capability to enable isHardwareGammaEnabled.
  2710. }
  2711. else
  2712. {
  2713. glDisable(GL_FRAMEBUFFER_SRGB_EXT);
  2714. }
  2715. }
  2716. }
  2717. //---------------------------------------------------------------------
  2718. void GLRenderSystem::_unregisterContext(GLContext *context)
  2719. {
  2720. if(mCurrentContext == context) {
  2721. // Change the context to something else so that a valid context
  2722. // remains active. When this is the main context being unregistered,
  2723. // we set the main context to 0.
  2724. if(mCurrentContext != mMainContext) {
  2725. _switchContext(mMainContext);
  2726. } else {
  2727. /// No contexts remain
  2728. mCurrentContext->endCurrent();
  2729. mCurrentContext = 0;
  2730. mMainContext = 0;
  2731. }
  2732. }
  2733. }
  2734. //---------------------------------------------------------------------
  2735. float GLRenderSystem::getMinimumDepthInputValue(void)
  2736. {
  2737. // Range [-1.0f, 1.0f]
  2738. return -1.0f;
  2739. }
  2740. //---------------------------------------------------------------------
  2741. float GLRenderSystem::getMaximumDepthInputValue(void)
  2742. {
  2743. // Range [-1.0f, 1.0f]
  2744. return 1.0f;
  2745. }
  2746. //---------------------------------------------------------------------
  2747. void GLRenderSystem::registerThread()
  2748. {
  2749. CM_LOCK_MUTEX(mThreadInitMutex)
  2750. // This is only valid once we've created the main context
  2751. if (!mMainContext)
  2752. {
  2753. CM_EXCEPT(InvalidParametersException,
  2754. "Cannot register a background thread before the main context has been created.");
  2755. }
  2756. // Create a new context for this thread. Cloning from the main context
  2757. // will ensure that resources are shared with the main context
  2758. // We want a separate context so that we can safely create GL
  2759. // objects in parallel with the main thread
  2760. GLContext* newContext = mMainContext->clone();
  2761. mBackgroundContextList.push_back(newContext);
  2762. // Bind this new context to this thread.
  2763. newContext->setCurrent();
  2764. _oneTimeContextInitialization();
  2765. newContext->setInitialized();
  2766. }
  2767. //---------------------------------------------------------------------
  2768. void GLRenderSystem::unregisterThread()
  2769. {
  2770. // nothing to do here?
  2771. // Don't need to worry about active context, just make sure we delete
  2772. // on shutdown.
  2773. }
  2774. //---------------------------------------------------------------------
  2775. void GLRenderSystem::preExtraThreadsStarted()
  2776. {
  2777. CM_LOCK_MUTEX(mThreadInitMutex)
  2778. // free context, we'll need this to share lists
  2779. mCurrentContext->endCurrent();
  2780. }
  2781. //---------------------------------------------------------------------
  2782. void GLRenderSystem::postExtraThreadsStarted()
  2783. {
  2784. CM_LOCK_MUTEX(mThreadInitMutex)
  2785. // reacquire context
  2786. mCurrentContext->setCurrent();
  2787. }
  2788. //---------------------------------------------------------------------
  2789. bool GLRenderSystem::activateGLTextureUnit(size_t unit)
  2790. {
  2791. if (mActiveTextureUnit != unit)
  2792. {
  2793. if (GLEW_VERSION_1_2 && unit < getCapabilities()->getNumTextureUnits())
  2794. {
  2795. glActiveTextureARB(GL_TEXTURE0 + unit);
  2796. mActiveTextureUnit = unit;
  2797. return true;
  2798. }
  2799. else if (!unit)
  2800. {
  2801. // always ok to use the first unit
  2802. return true;
  2803. }
  2804. else
  2805. {
  2806. return false;
  2807. }
  2808. }
  2809. else
  2810. {
  2811. return true;
  2812. }
  2813. }
  2814. //---------------------------------------------------------------------
  2815. unsigned int GLRenderSystem::getDisplayMonitorCount() const
  2816. {
  2817. return mGLSupport->getDisplayMonitorCount();
  2818. }
  2819. }