CmGLRenderSystem.cpp 92 KB

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