CmGLRenderSystem.cpp 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595
  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 "CmAsyncOp.h"
  40. #include "CmGLFBORenderTexture.h"
  41. #include "CmGLPBRenderTexture.h"
  42. // Convenience macro from ARB_vertex_buffer_object spec
  43. #define VBO_BUFFER_OFFSET(i) ((char *)NULL + (i))
  44. #if CM_THREAD_SUPPORT != 1
  45. GLenum glewContextInit (CamelotEngine::GLSupport *glSupport);
  46. #endif
  47. namespace CamelotEngine {
  48. // Callback function used when registering GLGpuPrograms
  49. GpuProgram* createGLArbGpuProgram(GpuProgramType gptype, const String& syntaxCode)
  50. {
  51. GLArbGpuProgram* ret = new GLArbGpuProgram();
  52. ret->setType(gptype);
  53. ret->setSyntaxCode(syntaxCode);
  54. return ret;
  55. }
  56. GpuProgram* createGL_ATI_FS_GpuProgram(GpuProgramType gptype, const String& syntaxCode)
  57. {
  58. ATI_FS_GLGpuProgram* ret = new ATI_FS_GLGpuProgram();
  59. ret->setType(gptype);
  60. ret->setSyntaxCode(syntaxCode);
  61. return ret;
  62. }
  63. GLRenderSystem::GLRenderSystem()
  64. : mDepthWrite(true), mStencilMask(0xFFFFFFFF),
  65. mGLSLProgramFactory(0),
  66. mCgProgramFactory(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("GLRenderSystem");
  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. RenderSystemCapabilities* GLRenderSystem::createRenderSystemCapabilities() const
  129. {
  130. RenderSystemCapabilities* rsc = new RenderSystemCapabilities();
  131. rsc->setCategoryRelevant(CAPS_CATEGORY_GL, true);
  132. rsc->setDriverVersion(mDriverVersion);
  133. const char* deviceName = (const char*)glGetString(GL_RENDERER);
  134. const char* vendorName = (const char*)glGetString(GL_VENDOR);
  135. rsc->setDeviceName(deviceName);
  136. rsc->setRenderSystemName(getName());
  137. // determine vendor
  138. if (strstr(vendorName, "NVIDIA"))
  139. rsc->setVendor(GPU_NVIDIA);
  140. else if (strstr(vendorName, "ATI"))
  141. rsc->setVendor(GPU_ATI);
  142. else if (strstr(vendorName, "Intel"))
  143. rsc->setVendor(GPU_INTEL);
  144. else if (strstr(vendorName, "S3"))
  145. rsc->setVendor(GPU_S3);
  146. else if (strstr(vendorName, "Matrox"))
  147. rsc->setVendor(GPU_MATROX);
  148. else if (strstr(vendorName, "3DLabs"))
  149. rsc->setVendor(GPU_3DLABS);
  150. else if (strstr(vendorName, "SiS"))
  151. rsc->setVendor(GPU_SIS);
  152. else
  153. rsc->setVendor(GPU_UNKNOWN);
  154. // Supports fixed-function
  155. rsc->setCapability(RSC_FIXED_FUNCTION);
  156. // Check for hardware mipmapping support.
  157. if(GLEW_VERSION_1_4 || GLEW_SGIS_generate_mipmap)
  158. {
  159. bool disableAutoMip = false;
  160. #if CM_PLATFORM == CM_PLATFORM_APPLE || CM_PLATFORM == CM_PLATFORM_LINUX
  161. // Apple & Linux ATI drivers have faults in hardware mipmap generation
  162. if (rsc->getVendor() == GPU_ATI)
  163. disableAutoMip = true;
  164. #endif
  165. // The Intel 915G frequently corrupts textures when using hardware mip generation
  166. // I'm not currently sure how many generations of hardware this affects,
  167. // so for now, be safe.
  168. if (rsc->getVendor() == GPU_INTEL)
  169. disableAutoMip = true;
  170. // SiS chipsets also seem to have problems with this
  171. if (rsc->getVendor() == GPU_SIS)
  172. disableAutoMip = true;
  173. if (!disableAutoMip)
  174. rsc->setCapability(RSC_AUTOMIPMAP);
  175. }
  176. // Check for blending support
  177. if(GLEW_VERSION_1_3 ||
  178. GLEW_ARB_texture_env_combine ||
  179. GLEW_EXT_texture_env_combine)
  180. {
  181. rsc->setCapability(RSC_BLENDING);
  182. }
  183. // Check for Multitexturing support and set number of texture units
  184. if(GLEW_VERSION_1_3 ||
  185. GLEW_ARB_multitexture)
  186. {
  187. GLint units;
  188. glGetIntegerv( GL_MAX_TEXTURE_UNITS, &units );
  189. if (GLEW_ARB_fragment_program)
  190. {
  191. // Also check GL_MAX_TEXTURE_IMAGE_UNITS_ARB since NV at least
  192. // only increased this on the FX/6x00 series
  193. GLint arbUnits;
  194. glGetIntegerv( GL_MAX_TEXTURE_IMAGE_UNITS_ARB, &arbUnits );
  195. if (arbUnits > units)
  196. units = arbUnits;
  197. }
  198. rsc->setNumTextureUnits(units);
  199. }
  200. else
  201. {
  202. // If no multitexture support then set one texture unit
  203. rsc->setNumTextureUnits(1);
  204. }
  205. // Check for Anisotropy support
  206. if(GLEW_EXT_texture_filter_anisotropic)
  207. {
  208. rsc->setCapability(RSC_ANISOTROPY);
  209. }
  210. // Check for DOT3 support
  211. if(GLEW_VERSION_1_3 ||
  212. GLEW_ARB_texture_env_dot3 ||
  213. GLEW_EXT_texture_env_dot3)
  214. {
  215. rsc->setCapability(RSC_DOT3);
  216. }
  217. // Check for cube mapping
  218. if(GLEW_VERSION_1_3 ||
  219. GLEW_ARB_texture_cube_map ||
  220. GLEW_EXT_texture_cube_map)
  221. {
  222. rsc->setCapability(RSC_CUBEMAPPING);
  223. }
  224. // Point sprites
  225. if (GLEW_VERSION_2_0 || GLEW_ARB_point_sprite)
  226. {
  227. rsc->setCapability(RSC_POINT_SPRITES);
  228. }
  229. // Check for point parameters
  230. if (GLEW_VERSION_1_4)
  231. {
  232. rsc->setCapability(RSC_POINT_EXTENDED_PARAMETERS);
  233. }
  234. if (GLEW_ARB_point_parameters)
  235. {
  236. rsc->setCapability(RSC_POINT_EXTENDED_PARAMETERS_ARB);
  237. }
  238. if (GLEW_EXT_point_parameters)
  239. {
  240. rsc->setCapability(RSC_POINT_EXTENDED_PARAMETERS_EXT);
  241. }
  242. // Check for hardware stencil support and set bit depth
  243. GLint stencil;
  244. glGetIntegerv(GL_STENCIL_BITS,&stencil);
  245. if(stencil)
  246. {
  247. rsc->setCapability(RSC_HWSTENCIL);
  248. rsc->setStencilBufferBitDepth(stencil);
  249. }
  250. if(GLEW_VERSION_1_5 || GLEW_ARB_vertex_buffer_object)
  251. {
  252. if (!GLEW_ARB_vertex_buffer_object)
  253. {
  254. rsc->setCapability(RSC_GL1_5_NOVBO);
  255. }
  256. rsc->setCapability(RSC_VBO);
  257. }
  258. if(GLEW_ARB_vertex_program)
  259. {
  260. rsc->setCapability(RSC_VERTEX_PROGRAM);
  261. // Vertex Program Properties
  262. rsc->setVertexProgramConstantBoolCount(0);
  263. rsc->setVertexProgramConstantIntCount(0);
  264. GLint floatConstantCount;
  265. glGetProgramivARB(GL_VERTEX_PROGRAM_ARB, GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB, &floatConstantCount);
  266. rsc->setVertexProgramConstantFloatCount(floatConstantCount);
  267. rsc->addShaderProfile("arbvp1");
  268. rsc->addGpuProgramProfile(GPP_VS_1_1, "arbvp1"); // TODO - I don't know if any of these GpuProgramProfile mappings are correct!
  269. rsc->addGpuProgramProfile(GPP_VS_2_0, "arbvp1");
  270. rsc->addGpuProgramProfile(GPP_VS_2_a, "arbvp1");
  271. rsc->addGpuProgramProfile(GPP_VS_2_x, "arbvp1");
  272. if (GLEW_NV_vertex_program2_option)
  273. {
  274. rsc->addShaderProfile("vp30");
  275. rsc->addGpuProgramProfile(GPP_VS_3_0, "vp30"); // TODO - I don't know if any of these GpuProgramProfile mappings are correct!
  276. rsc->addGpuProgramProfile(GPP_VS_4_0, "vp30");
  277. }
  278. if (GLEW_NV_vertex_program3)
  279. {
  280. rsc->addShaderProfile("vp40");
  281. rsc->addGpuProgramProfile(GPP_VS_3_0, "vp40"); // TODO - I don't know if any of these GpuProgramProfile mappings are correct!
  282. rsc->addGpuProgramProfile(GPP_VS_4_0, "vp40");
  283. }
  284. if (GLEW_NV_vertex_program4)
  285. {
  286. rsc->addShaderProfile("gp4vp");
  287. rsc->addShaderProfile("gpu_vp");
  288. }
  289. }
  290. if (GLEW_NV_register_combiners2 &&
  291. GLEW_NV_texture_shader)
  292. {
  293. rsc->setCapability(RSC_FRAGMENT_PROGRAM);
  294. }
  295. // NFZ - check for ATI fragment shader support
  296. if (GLEW_ATI_fragment_shader)
  297. {
  298. rsc->setCapability(RSC_FRAGMENT_PROGRAM);
  299. // no boolean params allowed
  300. rsc->setFragmentProgramConstantBoolCount(0);
  301. // no integer params allowed
  302. rsc->setFragmentProgramConstantIntCount(0);
  303. // only 8 Vector4 constant floats supported
  304. rsc->setFragmentProgramConstantFloatCount(8);
  305. rsc->addShaderProfile("ps_1_4");
  306. rsc->addShaderProfile("ps_1_3");
  307. rsc->addShaderProfile("ps_1_2");
  308. rsc->addShaderProfile("ps_1_1");
  309. rsc->addGpuProgramProfile(GPP_PS_1_1, "ps_1_1"); // TODO - I don't know if any of these GpuProgramProfile mappings are correct!
  310. rsc->addGpuProgramProfile(GPP_PS_1_2, "ps_1_2");
  311. rsc->addGpuProgramProfile(GPP_PS_1_3, "ps_1_3");
  312. rsc->addGpuProgramProfile(GPP_PS_1_4, "ps_1_4");
  313. }
  314. if (GLEW_ARB_fragment_program)
  315. {
  316. rsc->setCapability(RSC_FRAGMENT_PROGRAM);
  317. // Fragment Program Properties
  318. rsc->setFragmentProgramConstantBoolCount(0);
  319. rsc->setFragmentProgramConstantIntCount(0);
  320. GLint floatConstantCount;
  321. glGetProgramivARB(GL_FRAGMENT_PROGRAM_ARB, GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB, &floatConstantCount);
  322. rsc->setFragmentProgramConstantFloatCount(floatConstantCount);
  323. rsc->addShaderProfile("arbfp1");
  324. rsc->addGpuProgramProfile(GPP_PS_1_1, "arbfp1"); // TODO - I don't know if any of these GpuProgramProfile mappings are correct!
  325. rsc->addGpuProgramProfile(GPP_PS_1_2, "arbfp1");
  326. rsc->addGpuProgramProfile(GPP_PS_1_3, "arbfp1");
  327. rsc->addGpuProgramProfile(GPP_PS_1_4, "arbfp1");
  328. rsc->addGpuProgramProfile(GPP_PS_2_0, "arbfp1");
  329. rsc->addGpuProgramProfile(GPP_PS_2_a, "arbfp1");
  330. rsc->addGpuProgramProfile(GPP_PS_2_b, "arbfp1");
  331. rsc->addGpuProgramProfile(GPP_PS_2_x, "arbfp1");
  332. if (GLEW_NV_fragment_program_option)
  333. {
  334. rsc->addShaderProfile("fp30");
  335. rsc->addGpuProgramProfile(GPP_PS_3_0, "fp30"); // TODO - I don't know if any of these GpuProgramProfile mappings are correct!
  336. rsc->addGpuProgramProfile(GPP_PS_3_x, "fp30");
  337. rsc->addGpuProgramProfile(GPP_PS_4_0, "fp30");
  338. }
  339. if (GLEW_NV_fragment_program2)
  340. {
  341. rsc->addShaderProfile("fp40");
  342. rsc->addGpuProgramProfile(GPP_PS_3_0, "fp40"); // TODO - I don't know if any of these GpuProgramProfile mappings are correct!
  343. rsc->addGpuProgramProfile(GPP_PS_3_x, "fp40");
  344. rsc->addGpuProgramProfile(GPP_PS_4_0, "fp40");
  345. }
  346. }
  347. rsc->addShaderProfile("cg");
  348. // NFZ - Check if GLSL is supported
  349. if ( GLEW_VERSION_2_0 ||
  350. (GLEW_ARB_shading_language_100 &&
  351. GLEW_ARB_shader_objects &&
  352. GLEW_ARB_fragment_shader &&
  353. GLEW_ARB_vertex_shader) )
  354. {
  355. rsc->addShaderProfile("glsl");
  356. }
  357. // Check if geometry shaders are supported
  358. if (GLEW_VERSION_2_0 &&
  359. GLEW_EXT_geometry_shader4)
  360. {
  361. rsc->setCapability(RSC_GEOMETRY_PROGRAM);
  362. rsc->addShaderProfile("nvgp4");
  363. //Also add the CG profiles
  364. rsc->addShaderProfile("gpu_gp");
  365. rsc->addShaderProfile("gp4gp");
  366. rsc->setGeometryProgramConstantBoolCount(0);
  367. rsc->setGeometryProgramConstantIntCount(0);
  368. GLint floatConstantCount = 0;
  369. glGetIntegerv(GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_EXT, &floatConstantCount);
  370. rsc->setGeometryProgramConstantFloatCount(floatConstantCount);
  371. GLint maxOutputVertices;
  372. glGetIntegerv(GL_MAX_GEOMETRY_OUTPUT_VERTICES_EXT,&maxOutputVertices);
  373. rsc->setGeometryProgramNumOutputVertices(maxOutputVertices);
  374. }
  375. //Check if render to vertex buffer (transform feedback in OpenGL)
  376. if (GLEW_VERSION_2_0 &&
  377. GLEW_NV_transform_feedback)
  378. {
  379. rsc->setCapability(RSC_HWRENDER_TO_VERTEX_BUFFER);
  380. }
  381. // Check for texture compression
  382. if(GLEW_VERSION_1_3 || GLEW_ARB_texture_compression)
  383. {
  384. rsc->setCapability(RSC_TEXTURE_COMPRESSION);
  385. // Check for dxt compression
  386. if(GLEW_EXT_texture_compression_s3tc)
  387. {
  388. #if defined(__APPLE__) && defined(__PPC__)
  389. // Apple on ATI & PPC has errors in DXT
  390. if (mGLSupport->getGLVendor().find("ATI") == std::string::npos)
  391. #endif
  392. rsc->setCapability(RSC_TEXTURE_COMPRESSION_DXT);
  393. }
  394. // Check for vtc compression
  395. if(GLEW_NV_texture_compression_vtc)
  396. {
  397. rsc->setCapability(RSC_TEXTURE_COMPRESSION_VTC);
  398. }
  399. }
  400. // Scissor test is standard in GL 1.2 (is it emulated on some cards though?)
  401. rsc->setCapability(RSC_SCISSOR_TEST);
  402. // As are user clipping planes
  403. rsc->setCapability(RSC_USER_CLIP_PLANES);
  404. // 2-sided stencil?
  405. if (GLEW_VERSION_2_0 || GLEW_EXT_stencil_two_side)
  406. {
  407. rsc->setCapability(RSC_TWO_SIDED_STENCIL);
  408. }
  409. // stencil wrapping?
  410. if (GLEW_VERSION_1_4 || GLEW_EXT_stencil_wrap)
  411. {
  412. rsc->setCapability(RSC_STENCIL_WRAP);
  413. }
  414. // Check for hardware occlusion support
  415. if(GLEW_VERSION_1_5 || GLEW_ARB_occlusion_query)
  416. {
  417. // Some buggy driver claim that it is GL 1.5 compliant and
  418. // not support ARB_occlusion_query
  419. if (!GLEW_ARB_occlusion_query)
  420. {
  421. rsc->setCapability(RSC_GL1_5_NOHWOCCLUSION);
  422. }
  423. rsc->setCapability(RSC_HWOCCLUSION);
  424. }
  425. else if (GLEW_NV_occlusion_query)
  426. {
  427. // Support NV extension too for old hardware
  428. rsc->setCapability(RSC_HWOCCLUSION);
  429. }
  430. // UBYTE4 always supported
  431. rsc->setCapability(RSC_VERTEX_FORMAT_UBYTE4);
  432. // Infinite far plane always supported
  433. rsc->setCapability(RSC_INFINITE_FAR_PLANE);
  434. // Check for non-power-of-2 texture support
  435. if(GLEW_ARB_texture_non_power_of_two)
  436. {
  437. rsc->setCapability(RSC_NON_POWER_OF_2_TEXTURES);
  438. }
  439. // Check for Float textures
  440. if(GLEW_ATI_texture_float || GLEW_ARB_texture_float)
  441. {
  442. rsc->setCapability(RSC_TEXTURE_FLOAT);
  443. }
  444. // 3D textures should be supported by GL 1.2, which is our minimum version
  445. rsc->setCapability(RSC_TEXTURE_3D);
  446. // Check for framebuffer object extension
  447. if(GLEW_EXT_framebuffer_object)
  448. {
  449. // Probe number of draw buffers
  450. // Only makes sense with FBO support, so probe here
  451. if(GLEW_VERSION_2_0 ||
  452. GLEW_ARB_draw_buffers ||
  453. GLEW_ATI_draw_buffers)
  454. {
  455. GLint buffers;
  456. glGetIntegerv(GL_MAX_DRAW_BUFFERS_ARB, &buffers);
  457. rsc->setNumMultiRenderTargets(std::min<int>(buffers, (GLint)CM_MAX_MULTIPLE_RENDER_TARGETS));
  458. rsc->setCapability(RSC_MRT_DIFFERENT_BIT_DEPTHS);
  459. if(!GLEW_VERSION_2_0)
  460. {
  461. // Before GL version 2.0, we need to get one of the extensions
  462. if(GLEW_ARB_draw_buffers)
  463. rsc->setCapability(RSC_FBO_ARB);
  464. if(GLEW_ATI_draw_buffers)
  465. rsc->setCapability(RSC_FBO_ATI);
  466. }
  467. // Set FBO flag for all 3 'subtypes'
  468. rsc->setCapability(RSC_FBO);
  469. }
  470. rsc->setCapability(RSC_HWRENDER_TO_TEXTURE);
  471. }
  472. // Check GLSupport for PBuffer support
  473. if(mGLSupport->supportsPBuffers())
  474. {
  475. // Use PBuffers
  476. rsc->setCapability(RSC_HWRENDER_TO_TEXTURE);
  477. rsc->setCapability(RSC_PBUFFER);
  478. }
  479. // Point size
  480. if (GLEW_VERSION_1_4)
  481. {
  482. float ps;
  483. glGetFloatv(GL_POINT_SIZE_MAX, &ps);
  484. rsc->setMaxPointSize(ps);
  485. }
  486. else
  487. {
  488. GLint vSize[2];
  489. glGetIntegerv(GL_POINT_SIZE_RANGE,vSize);
  490. rsc->setMaxPointSize((float)vSize[1]);
  491. }
  492. // Vertex texture fetching
  493. if (mGLSupport->checkExtension("GL_ARB_vertex_shader"))
  494. {
  495. GLint vUnits;
  496. glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB, &vUnits);
  497. rsc->setNumVertexTextureUnits(static_cast<UINT16>(vUnits));
  498. if (vUnits > 0)
  499. {
  500. rsc->setCapability(RSC_VERTEX_TEXTURE_FETCH);
  501. }
  502. // GL always shares vertex and fragment texture units (for now?)
  503. rsc->setVertexTextureUnitsShared(true);
  504. }
  505. // Mipmap LOD biasing?
  506. if (GLEW_VERSION_1_4 || GLEW_EXT_texture_lod_bias)
  507. {
  508. rsc->setCapability(RSC_MIPMAP_LOD_BIAS);
  509. }
  510. // Alpha to coverage?
  511. if (mGLSupport->checkExtension("GL_ARB_multisample"))
  512. {
  513. // Alpha to coverage always 'supported' when MSAA is available
  514. // although card may ignore it if it doesn't specifically support A2C
  515. rsc->setCapability(RSC_ALPHA_TO_COVERAGE);
  516. }
  517. // Advanced blending operations
  518. if(GLEW_VERSION_2_0)
  519. {
  520. rsc->setCapability(RSC_ADVANCED_BLEND_OPERATIONS);
  521. }
  522. return rsc;
  523. }
  524. void GLRenderSystem::initialiseFromRenderSystemCapabilities(RenderSystemCapabilities* caps, RenderTarget* primary)
  525. {
  526. if(caps->getRenderSystemName() != getName())
  527. {
  528. CM_EXCEPT(InvalidParametersException,
  529. "Trying to initialize GLRenderSystem from RenderSystemCapabilities that do not support OpenGL");
  530. }
  531. // set texture the number of texture units
  532. mFixedFunctionTextureUnits = caps->getNumTextureUnits();
  533. //In GL there can be less fixed function texture units than general
  534. //texture units. Get the minimum of the two.
  535. if (caps->hasCapability(RSC_FRAGMENT_PROGRAM))
  536. {
  537. GLint maxTexCoords = 0;
  538. glGetIntegerv(GL_MAX_TEXTURE_COORDS_ARB, &maxTexCoords);
  539. if (mFixedFunctionTextureUnits > maxTexCoords)
  540. {
  541. mFixedFunctionTextureUnits = maxTexCoords;
  542. }
  543. }
  544. if(caps->hasCapability(RSC_GL1_5_NOVBO))
  545. {
  546. // Assign ARB functions same to GL 1.5 version since
  547. // interface identical
  548. glBindBufferARB = glBindBuffer;
  549. glBufferDataARB = glBufferData;
  550. glBufferSubDataARB = glBufferSubData;
  551. glDeleteBuffersARB = glDeleteBuffers;
  552. glGenBuffersARB = glGenBuffers;
  553. glGetBufferParameterivARB = glGetBufferParameteriv;
  554. glGetBufferPointervARB = glGetBufferPointerv;
  555. glGetBufferSubDataARB = glGetBufferSubData;
  556. glIsBufferARB = glIsBuffer;
  557. glMapBufferARB = glMapBuffer;
  558. glUnmapBufferARB = glUnmapBuffer;
  559. }
  560. if(caps->hasCapability(RSC_VBO))
  561. {
  562. HardwareBufferManager::startUp(new GLHardwareBufferManager);
  563. }
  564. else
  565. {
  566. HardwareBufferManager::startUp(new GLDefaultHardwareBufferManager);
  567. }
  568. // GPU Program Manager setup
  569. GpuProgramManager::startUp(new GLGpuProgramManager());
  570. GLGpuProgramManager* gpuProgramManager = static_cast<GLGpuProgramManager*>(GpuProgramManager::instancePtr());
  571. if(caps->hasCapability(RSC_VERTEX_PROGRAM))
  572. {
  573. if(caps->isShaderProfileSupported("arbvp1"))
  574. {
  575. gpuProgramManager->registerProgramFactory("arbvp1", createGLArbGpuProgram);
  576. }
  577. if(caps->isShaderProfileSupported("vp30"))
  578. {
  579. gpuProgramManager->registerProgramFactory("vp30", createGLArbGpuProgram);
  580. }
  581. if(caps->isShaderProfileSupported("vp40"))
  582. {
  583. gpuProgramManager->registerProgramFactory("vp40", createGLArbGpuProgram);
  584. }
  585. if(caps->isShaderProfileSupported("gp4vp"))
  586. {
  587. gpuProgramManager->registerProgramFactory("gp4vp", createGLArbGpuProgram);
  588. }
  589. if(caps->isShaderProfileSupported("gpu_vp"))
  590. {
  591. gpuProgramManager->registerProgramFactory("gpu_vp", createGLArbGpuProgram);
  592. }
  593. }
  594. if(caps->hasCapability(RSC_GEOMETRY_PROGRAM))
  595. {
  596. //TODO : Should these be createGLArbGpuProgram or createGLGpuNVparseProgram?
  597. if(caps->isShaderProfileSupported("nvgp4"))
  598. {
  599. gpuProgramManager->registerProgramFactory("nvgp4", createGLArbGpuProgram);
  600. }
  601. if(caps->isShaderProfileSupported("gp4gp"))
  602. {
  603. gpuProgramManager->registerProgramFactory("gp4gp", createGLArbGpuProgram);
  604. }
  605. if(caps->isShaderProfileSupported("gpu_gp"))
  606. {
  607. gpuProgramManager->registerProgramFactory("gpu_gp", createGLArbGpuProgram);
  608. }
  609. }
  610. if(caps->hasCapability(RSC_FRAGMENT_PROGRAM))
  611. {
  612. if(caps->isShaderProfileSupported("ps_1_4"))
  613. {
  614. gpuProgramManager->registerProgramFactory("ps_1_4", createGL_ATI_FS_GpuProgram);
  615. }
  616. if(caps->isShaderProfileSupported("ps_1_3"))
  617. {
  618. gpuProgramManager->registerProgramFactory("ps_1_3", createGL_ATI_FS_GpuProgram);
  619. }
  620. if(caps->isShaderProfileSupported("ps_1_2"))
  621. {
  622. gpuProgramManager->registerProgramFactory("ps_1_2", createGL_ATI_FS_GpuProgram);
  623. }
  624. if(caps->isShaderProfileSupported("ps_1_1"))
  625. {
  626. gpuProgramManager->registerProgramFactory("ps_1_1", createGL_ATI_FS_GpuProgram);
  627. }
  628. if(caps->isShaderProfileSupported("arbfp1"))
  629. {
  630. gpuProgramManager->registerProgramFactory("arbfp1", createGLArbGpuProgram);
  631. }
  632. if(caps->isShaderProfileSupported("fp40"))
  633. {
  634. gpuProgramManager->registerProgramFactory("fp40", createGLArbGpuProgram);
  635. }
  636. if(caps->isShaderProfileSupported("fp30"))
  637. {
  638. gpuProgramManager->registerProgramFactory("fp30", createGLArbGpuProgram);
  639. }
  640. }
  641. if(caps->isShaderProfileSupported("glsl"))
  642. {
  643. // NFZ - check for GLSL vertex and fragment shader support successful
  644. mGLSLProgramFactory = new GLSLProgramFactory();
  645. HighLevelGpuProgramManager::instance().addFactory(mGLSLProgramFactory);
  646. }
  647. if(caps->isShaderProfileSupported("cg"))
  648. {
  649. // NFZ - check for GLSL vertex and fragment shader support successful
  650. mCgProgramFactory = new CgProgramFactory();
  651. HighLevelGpuProgramManager::instance().addFactory(mCgProgramFactory);
  652. }
  653. if(caps->hasCapability(RSC_HWOCCLUSION))
  654. {
  655. if(caps->hasCapability(RSC_GL1_5_NOHWOCCLUSION))
  656. {
  657. // Assign ARB functions same to GL 1.5 version since
  658. // interface identical
  659. glBeginQueryARB = glBeginQuery;
  660. glDeleteQueriesARB = glDeleteQueries;
  661. glEndQueryARB = glEndQuery;
  662. glGenQueriesARB = glGenQueries;
  663. glGetQueryObjectivARB = glGetQueryObjectiv;
  664. glGetQueryObjectuivARB = glGetQueryObjectuiv;
  665. glGetQueryivARB = glGetQueryiv;
  666. glIsQueryARB = glIsQuery;
  667. }
  668. }
  669. /// Do this after extension function pointers are initialised as the extension
  670. /// is used to probe further capabilities.
  671. ConfigOptionMap::iterator cfi = getConfigOptions().find("RTT Preferred Mode");
  672. // RTT Mode: 0 use whatever available, 1 use PBuffers, 2 force use copying
  673. int rttMode = 0;
  674. if (cfi != getConfigOptions().end())
  675. {
  676. if (cfi->second.currentValue == "PBuffer")
  677. {
  678. rttMode = 1;
  679. }
  680. else if (cfi->second.currentValue == "Copy")
  681. {
  682. rttMode = 2;
  683. }
  684. }
  685. // Check for framebuffer object extension
  686. if(caps->hasCapability(RSC_FBO) && rttMode < 1)
  687. {
  688. // Before GL version 2.0, we need to get one of the extensions
  689. if(caps->hasCapability(RSC_FBO_ARB))
  690. GLEW_GET_FUN(__glewDrawBuffers) = glDrawBuffersARB;
  691. else if(caps->hasCapability(RSC_FBO_ATI))
  692. GLEW_GET_FUN(__glewDrawBuffers) = glDrawBuffersATI;
  693. if(caps->hasCapability(RSC_HWRENDER_TO_TEXTURE))
  694. {
  695. // Create FBO manager
  696. // TODO LOG PORT - Log this somewhere?
  697. //LogManager::getSingleton().logMessage("GL: Using GL_EXT_framebuffer_object for rendering to textures (best)");
  698. GLRTTManager::startUp(new GLFBOManager(false));
  699. }
  700. }
  701. else
  702. {
  703. // Check GLSupport for PBuffer support
  704. if(caps->hasCapability(RSC_PBUFFER) && rttMode < 2)
  705. {
  706. if(caps->hasCapability(RSC_HWRENDER_TO_TEXTURE))
  707. {
  708. // Use PBuffers
  709. GLRTTManager::startUp(new GLPBRTTManager(mGLSupport, primary));
  710. // TODO LOG PORT - Log this somewhere?
  711. //LogManager::getSingleton().logMessage("GL: Using PBuffers for rendering to textures");
  712. }
  713. }
  714. else
  715. {
  716. // No pbuffer support either -- fallback to simplest copying from framebuffer
  717. GLRTTManager::startUp(new GLCopyingRTTManager());
  718. // TODO LOG PORT - Log this somewhere?
  719. //LogManager::getSingleton().logMessage("GL: Using framebuffer copy for rendering to textures (worst)");
  720. //LogManager::getSingleton().logMessage("GL: Warning: RenderTexture size is restricted to size of framebuffer. If you are on Linux, consider using GLX instead of SDL.");
  721. }
  722. // Downgrade number of simultaneous targets
  723. caps->setNumMultiRenderTargets(1);
  724. }
  725. /// Create the texture manager
  726. TextureManager::startUp(new GLTextureManager(*mGLSupport));
  727. mGLInitialised = true;
  728. }
  729. void GLRenderSystem::shutdown(void)
  730. {
  731. RenderSystem::shutdown();
  732. // Deleting the GLSL program factory
  733. if (mGLSLProgramFactory)
  734. {
  735. // Remove from manager safely
  736. HighLevelGpuProgramManager::instance().removeFactory(mGLSLProgramFactory);
  737. delete mGLSLProgramFactory;
  738. mGLSLProgramFactory = 0;
  739. }
  740. // Deleting Cg GLSL program factory
  741. if (mCgProgramFactory)
  742. {
  743. // Remove from manager safely
  744. HighLevelGpuProgramManager::instance().removeFactory(mCgProgramFactory);
  745. delete mCgProgramFactory;
  746. mCgProgramFactory = 0;
  747. }
  748. // Deleting the GPU program manager and hardware buffer manager. Has to be done before the mGLSupport->stop().
  749. GpuProgramManager::shutDown();
  750. HardwareBufferManager::shutDown();
  751. GLRTTManager::shutDown();
  752. // Delete extra threads contexts
  753. for (GLContextList::iterator i = mBackgroundContextList.begin();
  754. i != mBackgroundContextList.end(); ++i)
  755. {
  756. GLContext* pCurContext = *i;
  757. pCurContext->releaseContext();
  758. delete pCurContext;
  759. }
  760. mBackgroundContextList.clear();
  761. mGLSupport->stop();
  762. mStopRendering = true;
  763. TextureManager::shutDown();
  764. // There will be a new initial window and so forth, thus any call to test
  765. // some params will access an invalid pointer, so it is best to reset
  766. // the whole state.
  767. mGLInitialised = 0;
  768. }
  769. void GLRenderSystem::initialiseContext(RenderWindow* primary)
  770. {
  771. // Set main and current context
  772. mMainContext = 0;
  773. primary->getCustomAttribute("GLCONTEXT", &mMainContext);
  774. mCurrentContext = mMainContext;
  775. // Set primary context as active
  776. if(mCurrentContext)
  777. mCurrentContext->setCurrent();
  778. // Setup GLSupport
  779. mGLSupport->initialiseExtensions();
  780. // Get extension function pointers
  781. #if CM_THREAD_SUPPORT != 1
  782. glewContextInit(mGLSupport);
  783. #endif
  784. }
  785. //-----------------------------------------------------------------------
  786. MultiRenderTarget * GLRenderSystem::createMultiRenderTarget(const String & name)
  787. {
  788. MultiRenderTarget *retval = GLRTTManager::instancePtr()->createMultiRenderTarget(name);
  789. attachRenderTarget( *retval );
  790. return retval;
  791. }
  792. //-----------------------------------------------------------------------
  793. void GLRenderSystem::destroyRenderWindow(RenderWindow* pWin)
  794. {
  795. // Find it to remove from list
  796. RenderTargetMap::iterator i = mRenderTargets.begin();
  797. while (i != mRenderTargets.end())
  798. {
  799. if (i->second == pWin)
  800. {
  801. mRenderTargets.erase(i);
  802. delete pWin;
  803. break;
  804. }
  805. }
  806. }
  807. //-----------------------------------------------------------------------------
  808. void GLRenderSystem::makeGLMatrix(GLfloat gl_matrix[16], const Matrix4& m)
  809. {
  810. size_t x = 0;
  811. for (size_t i = 0; i < 4; i++)
  812. {
  813. for (size_t j = 0; j < 4; j++)
  814. {
  815. gl_matrix[x] = m[j][i];
  816. x++;
  817. }
  818. }
  819. }
  820. //-----------------------------------------------------------------------------
  821. void GLRenderSystem::setPointParameters(float size,
  822. bool attenuationEnabled, float constant, float linear, float quadratic,
  823. float minSize, float maxSize)
  824. {
  825. float val[4] = {1, 0, 0, 1};
  826. if(attenuationEnabled)
  827. {
  828. // Point size is still calculated in pixels even when attenuation is
  829. // enabled, which is pretty awkward, since you typically want a viewport
  830. // independent size if you're looking for attenuation.
  831. // So, scale the point size up by viewport size (this is equivalent to
  832. // what D3D does as standard)
  833. size = size * mActiveViewport.getActualHeight();
  834. minSize = minSize * mActiveViewport.getActualHeight();
  835. if (maxSize == 0.0f)
  836. maxSize = mCurrentCapabilities->getMaxPointSize(); // pixels
  837. else
  838. maxSize = maxSize * mActiveViewport.getActualHeight();
  839. // XXX: why do I need this for results to be consistent with D3D?
  840. // Equations are supposedly the same once you factor in vp height
  841. float correction = 0.005f;
  842. // scaling required
  843. val[0] = constant;
  844. val[1] = linear * correction;
  845. val[2] = quadratic * correction;
  846. val[3] = 1;
  847. if (mCurrentCapabilities->hasCapability(RSC_VERTEX_PROGRAM))
  848. glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
  849. }
  850. else
  851. {
  852. if (maxSize == 0.0f)
  853. maxSize = mCurrentCapabilities->getMaxPointSize();
  854. if (mCurrentCapabilities->hasCapability(RSC_VERTEX_PROGRAM))
  855. glDisable(GL_VERTEX_PROGRAM_POINT_SIZE);
  856. }
  857. // no scaling required
  858. // GL has no disabled flag for this so just set to constant
  859. glPointSize(size);
  860. if (mCurrentCapabilities->hasCapability(RSC_POINT_EXTENDED_PARAMETERS))
  861. {
  862. glPointParameterfv(GL_POINT_DISTANCE_ATTENUATION, val);
  863. glPointParameterf(GL_POINT_SIZE_MIN, minSize);
  864. glPointParameterf(GL_POINT_SIZE_MAX, maxSize);
  865. }
  866. else if (mCurrentCapabilities->hasCapability(RSC_POINT_EXTENDED_PARAMETERS_ARB))
  867. {
  868. glPointParameterfvARB(GL_POINT_DISTANCE_ATTENUATION, val);
  869. glPointParameterfARB(GL_POINT_SIZE_MIN, minSize);
  870. glPointParameterfARB(GL_POINT_SIZE_MAX, maxSize);
  871. }
  872. else if (mCurrentCapabilities->hasCapability(RSC_POINT_EXTENDED_PARAMETERS_EXT))
  873. {
  874. glPointParameterfvEXT(GL_POINT_DISTANCE_ATTENUATION, val);
  875. glPointParameterfEXT(GL_POINT_SIZE_MIN, minSize);
  876. glPointParameterfEXT(GL_POINT_SIZE_MAX, maxSize);
  877. }
  878. }
  879. //-----------------------------------------------------------------------------
  880. void GLRenderSystem::setTexture(size_t stage, bool enabled, const TexturePtr &texPtr)
  881. {
  882. GLTexturePtr tex = std::static_pointer_cast<GLTexture>(texPtr);
  883. GLenum lastTextureType = mTextureTypes[stage];
  884. if (!activateGLTextureUnit(stage))
  885. return;
  886. if (enabled)
  887. {
  888. if (tex)
  889. {
  890. // note used
  891. mTextureTypes[stage] = tex->getGLTextureTarget();
  892. }
  893. else
  894. // assume 2D
  895. mTextureTypes[stage] = GL_TEXTURE_2D;
  896. if(lastTextureType != mTextureTypes[stage] && lastTextureType != 0)
  897. {
  898. if (stage < mFixedFunctionTextureUnits)
  899. {
  900. glDisable( lastTextureType );
  901. }
  902. }
  903. if (stage < mFixedFunctionTextureUnits)
  904. {
  905. glEnable( mTextureTypes[stage] );
  906. }
  907. if(tex)
  908. glBindTexture( mTextureTypes[stage], tex->getGLID() );
  909. else
  910. {
  911. glBindTexture( mTextureTypes[stage], static_cast<GLTextureManager*>(&TextureManager::instance())->getWarningTextureID() );
  912. }
  913. }
  914. else
  915. {
  916. if (stage < mFixedFunctionTextureUnits)
  917. {
  918. if (lastTextureType != 0)
  919. {
  920. glDisable( mTextureTypes[stage] );
  921. }
  922. glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
  923. }
  924. // bind zero texture
  925. glBindTexture(GL_TEXTURE_2D, 0);
  926. }
  927. activateGLTextureUnit(0);
  928. }
  929. //-----------------------------------------------------------------------------
  930. GLint GLRenderSystem::getTextureAddressingMode(
  931. SamplerState::TextureAddressingMode tam) const
  932. {
  933. switch(tam)
  934. {
  935. default:
  936. case SamplerState::TAM_WRAP:
  937. return GL_REPEAT;
  938. case SamplerState::TAM_MIRROR:
  939. return GL_MIRRORED_REPEAT;
  940. case SamplerState::TAM_CLAMP:
  941. return GL_CLAMP_TO_EDGE;
  942. case SamplerState::TAM_BORDER:
  943. return GL_CLAMP_TO_BORDER;
  944. }
  945. }
  946. //-----------------------------------------------------------------------------
  947. void GLRenderSystem::setTextureAddressingMode(size_t stage, const SamplerState::UVWAddressingMode& uvw)
  948. {
  949. if (!activateGLTextureUnit(stage))
  950. return;
  951. glTexParameteri( mTextureTypes[stage], GL_TEXTURE_WRAP_S,
  952. getTextureAddressingMode(uvw.u));
  953. glTexParameteri( mTextureTypes[stage], GL_TEXTURE_WRAP_T,
  954. getTextureAddressingMode(uvw.v));
  955. glTexParameteri( mTextureTypes[stage], GL_TEXTURE_WRAP_R,
  956. getTextureAddressingMode(uvw.w));
  957. activateGLTextureUnit(0);
  958. }
  959. //-----------------------------------------------------------------------------
  960. void GLRenderSystem::setTextureBorderColor(size_t stage, const Color& colour)
  961. {
  962. GLfloat border[4] = { colour.r, colour.g, colour.b, colour.a };
  963. if (activateGLTextureUnit(stage))
  964. {
  965. glTexParameterfv( mTextureTypes[stage], GL_TEXTURE_BORDER_COLOR, border);
  966. activateGLTextureUnit(0);
  967. }
  968. }
  969. //-----------------------------------------------------------------------------
  970. void GLRenderSystem::setTextureMipmapBias(size_t stage, float bias)
  971. {
  972. if (mCurrentCapabilities->hasCapability(RSC_MIPMAP_LOD_BIAS))
  973. {
  974. if (activateGLTextureUnit(stage))
  975. {
  976. glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, bias);
  977. activateGLTextureUnit(0);
  978. }
  979. }
  980. }
  981. //-----------------------------------------------------------------------------
  982. GLint GLRenderSystem::getBlendMode(SceneBlendFactor ogreBlend) const
  983. {
  984. switch(ogreBlend)
  985. {
  986. case SBF_ONE:
  987. return GL_ONE;
  988. case SBF_ZERO:
  989. return GL_ZERO;
  990. case SBF_DEST_COLOUR:
  991. return GL_DST_COLOR;
  992. case SBF_SOURCE_COLOUR:
  993. return GL_SRC_COLOR;
  994. case SBF_ONE_MINUS_DEST_COLOUR:
  995. return GL_ONE_MINUS_DST_COLOR;
  996. case SBF_ONE_MINUS_SOURCE_COLOUR:
  997. return GL_ONE_MINUS_SRC_COLOR;
  998. case SBF_DEST_ALPHA:
  999. return GL_DST_ALPHA;
  1000. case SBF_SOURCE_ALPHA:
  1001. return GL_SRC_ALPHA;
  1002. case SBF_ONE_MINUS_DEST_ALPHA:
  1003. return GL_ONE_MINUS_DST_ALPHA;
  1004. case SBF_ONE_MINUS_SOURCE_ALPHA:
  1005. return GL_ONE_MINUS_SRC_ALPHA;
  1006. };
  1007. // to keep compiler happy
  1008. return GL_ONE;
  1009. }
  1010. void GLRenderSystem::setSceneBlending(SceneBlendFactor sourceFactor, SceneBlendFactor destFactor, SceneBlendOperation op )
  1011. {
  1012. GLint sourceBlend = getBlendMode(sourceFactor);
  1013. GLint destBlend = getBlendMode(destFactor);
  1014. if(sourceFactor == SBF_ONE && destFactor == SBF_ZERO)
  1015. {
  1016. glDisable(GL_BLEND);
  1017. }
  1018. else
  1019. {
  1020. glEnable(GL_BLEND);
  1021. glBlendFunc(sourceBlend, destBlend);
  1022. }
  1023. GLint func = GL_FUNC_ADD;
  1024. switch(op)
  1025. {
  1026. case SBO_ADD:
  1027. func = GL_FUNC_ADD;
  1028. break;
  1029. case SBO_SUBTRACT:
  1030. func = GL_FUNC_SUBTRACT;
  1031. break;
  1032. case SBO_REVERSE_SUBTRACT:
  1033. func = GL_FUNC_REVERSE_SUBTRACT;
  1034. break;
  1035. case SBO_MIN:
  1036. func = GL_MIN;
  1037. break;
  1038. case SBO_MAX:
  1039. func = GL_MAX;
  1040. break;
  1041. }
  1042. if(GLEW_VERSION_1_4 || GLEW_ARB_imaging)
  1043. {
  1044. glBlendEquation(func);
  1045. }
  1046. else if(GLEW_EXT_blend_minmax && (func == GL_MIN || func == GL_MAX))
  1047. {
  1048. glBlendEquationEXT(func);
  1049. }
  1050. }
  1051. //-----------------------------------------------------------------------------
  1052. void GLRenderSystem::setSeparateSceneBlending(
  1053. SceneBlendFactor sourceFactor, SceneBlendFactor destFactor,
  1054. SceneBlendFactor sourceFactorAlpha, SceneBlendFactor destFactorAlpha,
  1055. SceneBlendOperation op, SceneBlendOperation alphaOp )
  1056. {
  1057. GLint sourceBlend = getBlendMode(sourceFactor);
  1058. GLint destBlend = getBlendMode(destFactor);
  1059. GLint sourceBlendAlpha = getBlendMode(sourceFactorAlpha);
  1060. GLint destBlendAlpha = getBlendMode(destFactorAlpha);
  1061. if(sourceFactor == SBF_ONE && destFactor == SBF_ZERO &&
  1062. sourceFactorAlpha == SBF_ONE && destFactorAlpha == SBF_ZERO)
  1063. {
  1064. glDisable(GL_BLEND);
  1065. }
  1066. else
  1067. {
  1068. glEnable(GL_BLEND);
  1069. glBlendFuncSeparate(sourceBlend, destBlend, sourceBlendAlpha, destBlendAlpha);
  1070. }
  1071. GLint func = GL_FUNC_ADD, alphaFunc = GL_FUNC_ADD;
  1072. switch(op)
  1073. {
  1074. case SBO_ADD:
  1075. func = GL_FUNC_ADD;
  1076. break;
  1077. case SBO_SUBTRACT:
  1078. func = GL_FUNC_SUBTRACT;
  1079. break;
  1080. case SBO_REVERSE_SUBTRACT:
  1081. func = GL_FUNC_REVERSE_SUBTRACT;
  1082. break;
  1083. case SBO_MIN:
  1084. func = GL_MIN;
  1085. break;
  1086. case SBO_MAX:
  1087. func = GL_MAX;
  1088. break;
  1089. }
  1090. switch(alphaOp)
  1091. {
  1092. case SBO_ADD:
  1093. alphaFunc = GL_FUNC_ADD;
  1094. break;
  1095. case SBO_SUBTRACT:
  1096. alphaFunc = GL_FUNC_SUBTRACT;
  1097. break;
  1098. case SBO_REVERSE_SUBTRACT:
  1099. alphaFunc = GL_FUNC_REVERSE_SUBTRACT;
  1100. break;
  1101. case SBO_MIN:
  1102. alphaFunc = GL_MIN;
  1103. break;
  1104. case SBO_MAX:
  1105. alphaFunc = GL_MAX;
  1106. break;
  1107. }
  1108. if(GLEW_VERSION_2_0) {
  1109. glBlendEquationSeparate(func, alphaFunc);
  1110. }
  1111. else if(GLEW_EXT_blend_equation_separate) {
  1112. glBlendEquationSeparateEXT(func, alphaFunc);
  1113. }
  1114. }
  1115. //-----------------------------------------------------------------------------
  1116. void GLRenderSystem::setAlphaRejectSettings(CompareFunction func, unsigned char value, bool alphaToCoverage)
  1117. {
  1118. bool a2c = false;
  1119. static bool lasta2c = false;
  1120. if(func == CMPF_ALWAYS_PASS)
  1121. {
  1122. glDisable(GL_ALPHA_TEST);
  1123. }
  1124. else
  1125. {
  1126. glEnable(GL_ALPHA_TEST);
  1127. a2c = alphaToCoverage;
  1128. glAlphaFunc(convertCompareFunction(func), value / 255.0f);
  1129. }
  1130. if (a2c != lasta2c && getCapabilities()->hasCapability(RSC_ALPHA_TO_COVERAGE))
  1131. {
  1132. if (a2c)
  1133. glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  1134. else
  1135. glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  1136. lasta2c = a2c;
  1137. }
  1138. }
  1139. //-----------------------------------------------------------------------------
  1140. void GLRenderSystem::setViewport(const Viewport& vp)
  1141. {
  1142. RenderTarget* target;
  1143. target = vp.getTarget();
  1144. setRenderTarget(target);
  1145. mActiveViewport = vp;
  1146. GLsizei x, y, w, h;
  1147. // Calculate the "lower-left" corner of the viewport
  1148. w = vp.getActualWidth();
  1149. h = vp.getActualHeight();
  1150. x = vp.getActualLeft();
  1151. y = vp.getActualTop();
  1152. if (!target->requiresTextureFlipping())
  1153. {
  1154. // Convert "upper-left" corner to "lower-left"
  1155. y = target->getHeight() - h - y;
  1156. }
  1157. glViewport(x, y, w, h);
  1158. // Configure the viewport clipping
  1159. glScissor(x, y, w, h);
  1160. }
  1161. //-----------------------------------------------------------------------------
  1162. void GLRenderSystem::beginFrame(void)
  1163. {
  1164. // Activate the viewport clipping
  1165. glEnable(GL_SCISSOR_TEST);
  1166. }
  1167. //-----------------------------------------------------------------------------
  1168. void GLRenderSystem::endFrame(void)
  1169. {
  1170. // Deactivate the viewport clipping.
  1171. glDisable(GL_SCISSOR_TEST);
  1172. // unbind GPU programs at end of frame
  1173. // this is mostly to avoid holding bound programs that might get deleted
  1174. // outside via the resource manager
  1175. unbindGpuProgram(GPT_VERTEX_PROGRAM);
  1176. unbindGpuProgram(GPT_FRAGMENT_PROGRAM);
  1177. }
  1178. //-----------------------------------------------------------------------------
  1179. void GLRenderSystem::setCullingMode(CullingMode mode)
  1180. {
  1181. mCullingMode = mode;
  1182. // NB: Because two-sided stencil API dependence of the front face, we must
  1183. // use the same 'winding' for the front face everywhere. As the OGRE default
  1184. // culling mode is clockwise, we also treat anticlockwise winding as front
  1185. // face for consistently. On the assumption that, we can't change the front
  1186. // face by glFrontFace anywhere.
  1187. GLenum cullMode;
  1188. switch( mode )
  1189. {
  1190. case CULL_NONE:
  1191. glDisable( GL_CULL_FACE );
  1192. return;
  1193. default:
  1194. case CULL_CLOCKWISE:
  1195. if (mActiveRenderTarget &&
  1196. ((mActiveRenderTarget->requiresTextureFlipping() && !mInvertVertexWinding) ||
  1197. (!mActiveRenderTarget->requiresTextureFlipping() && mInvertVertexWinding)))
  1198. {
  1199. cullMode = GL_FRONT;
  1200. }
  1201. else
  1202. {
  1203. cullMode = GL_BACK;
  1204. }
  1205. break;
  1206. case CULL_ANTICLOCKWISE:
  1207. if (mActiveRenderTarget &&
  1208. ((mActiveRenderTarget->requiresTextureFlipping() && !mInvertVertexWinding) ||
  1209. (!mActiveRenderTarget->requiresTextureFlipping() && mInvertVertexWinding)))
  1210. {
  1211. cullMode = GL_BACK;
  1212. }
  1213. else
  1214. {
  1215. cullMode = GL_FRONT;
  1216. }
  1217. break;
  1218. }
  1219. glEnable( GL_CULL_FACE );
  1220. glCullFace( cullMode );
  1221. }
  1222. //-----------------------------------------------------------------------------
  1223. void GLRenderSystem::setDepthBufferParams(bool depthTest, bool depthWrite, CompareFunction depthFunction)
  1224. {
  1225. setDepthBufferCheckEnabled(depthTest);
  1226. setDepthBufferWriteEnabled(depthWrite);
  1227. setDepthBufferFunction(depthFunction);
  1228. }
  1229. //-----------------------------------------------------------------------------
  1230. void GLRenderSystem::setDepthBufferCheckEnabled(bool enabled)
  1231. {
  1232. if (enabled)
  1233. {
  1234. glClearDepth(1.0f);
  1235. glEnable(GL_DEPTH_TEST);
  1236. }
  1237. else
  1238. {
  1239. glDisable(GL_DEPTH_TEST);
  1240. }
  1241. }
  1242. //-----------------------------------------------------------------------------
  1243. void GLRenderSystem::setDepthBufferWriteEnabled(bool enabled)
  1244. {
  1245. GLboolean flag = enabled ? GL_TRUE : GL_FALSE;
  1246. glDepthMask( flag );
  1247. // Store for reference in _beginFrame
  1248. mDepthWrite = enabled;
  1249. }
  1250. //-----------------------------------------------------------------------------
  1251. void GLRenderSystem::setDepthBufferFunction(CompareFunction func)
  1252. {
  1253. glDepthFunc(convertCompareFunction(func));
  1254. }
  1255. //-----------------------------------------------------------------------------
  1256. void GLRenderSystem::setDepthBias(float constantBias, float slopeScaleBias)
  1257. {
  1258. if (constantBias != 0 || slopeScaleBias != 0)
  1259. {
  1260. glEnable(GL_POLYGON_OFFSET_FILL);
  1261. glEnable(GL_POLYGON_OFFSET_POINT);
  1262. glEnable(GL_POLYGON_OFFSET_LINE);
  1263. glPolygonOffset(-slopeScaleBias, -constantBias);
  1264. }
  1265. else
  1266. {
  1267. glDisable(GL_POLYGON_OFFSET_FILL);
  1268. glDisable(GL_POLYGON_OFFSET_POINT);
  1269. glDisable(GL_POLYGON_OFFSET_LINE);
  1270. }
  1271. }
  1272. //-----------------------------------------------------------------------------
  1273. void GLRenderSystem::setColorBufferWriteEnabled(bool red, bool green, bool blue, bool alpha)
  1274. {
  1275. glColorMask(red, green, blue, alpha);
  1276. // record this
  1277. mColourWrite[0] = red;
  1278. mColourWrite[1] = blue;
  1279. mColourWrite[2] = green;
  1280. mColourWrite[3] = alpha;
  1281. }
  1282. //-----------------------------------------------------------------------------
  1283. String GLRenderSystem::getErrorDescription(long errCode) const
  1284. {
  1285. const GLubyte *errString = gluErrorString (errCode);
  1286. return (errString != 0) ? String((const char*) errString) : StringUtil::BLANK;
  1287. }
  1288. VertexElementType GLRenderSystem::getColorVertexElementType(void) const
  1289. {
  1290. return VET_COLOUR_ABGR;
  1291. }
  1292. void GLRenderSystem::_convertProjectionMatrix(const Matrix4& matrix,
  1293. Matrix4& dest, bool forGpuProgram)
  1294. {
  1295. // no any conversion request for OpenGL
  1296. dest = matrix;
  1297. }
  1298. //---------------------------------------------------------------------
  1299. void GLRenderSystem::setPolygonMode(PolygonMode level)
  1300. {
  1301. GLenum glmode;
  1302. switch(level)
  1303. {
  1304. case PM_POINTS:
  1305. glmode = GL_POINT;
  1306. break;
  1307. case PM_WIREFRAME:
  1308. glmode = GL_LINE;
  1309. break;
  1310. default:
  1311. case PM_SOLID:
  1312. glmode = GL_FILL;
  1313. break;
  1314. }
  1315. glPolygonMode(GL_FRONT_AND_BACK, glmode);
  1316. }
  1317. //---------------------------------------------------------------------
  1318. void GLRenderSystem::setStencilCheckEnabled(bool enabled)
  1319. {
  1320. if (enabled)
  1321. {
  1322. glEnable(GL_STENCIL_TEST);
  1323. }
  1324. else
  1325. {
  1326. glDisable(GL_STENCIL_TEST);
  1327. }
  1328. }
  1329. //---------------------------------------------------------------------
  1330. void GLRenderSystem::setStencilBufferParams(CompareFunction func,
  1331. UINT32 refValue, UINT32 mask, StencilOperation stencilFailOp,
  1332. StencilOperation depthFailOp, StencilOperation passOp,
  1333. bool twoSidedOperation)
  1334. {
  1335. bool flip;
  1336. mStencilMask = mask;
  1337. if (twoSidedOperation)
  1338. {
  1339. if (!mCurrentCapabilities->hasCapability(RSC_TWO_SIDED_STENCIL))
  1340. CM_EXCEPT(InvalidParametersException, "2-sided stencils are not supported");
  1341. // NB: We should always treat CCW as front face for consistent with default
  1342. // culling mode. Therefore, we must take care with two-sided stencil settings.
  1343. flip = (mInvertVertexWinding && !mActiveRenderTarget->requiresTextureFlipping()) ||
  1344. (!mInvertVertexWinding && mActiveRenderTarget->requiresTextureFlipping());
  1345. if(GLEW_VERSION_2_0) // New GL2 commands
  1346. {
  1347. // Back
  1348. glStencilMaskSeparate(GL_BACK, mask);
  1349. glStencilFuncSeparate(GL_BACK, convertCompareFunction(func), refValue, mask);
  1350. glStencilOpSeparate(GL_BACK,
  1351. convertStencilOp(stencilFailOp, !flip),
  1352. convertStencilOp(depthFailOp, !flip),
  1353. convertStencilOp(passOp, !flip));
  1354. // Front
  1355. glStencilMaskSeparate(GL_FRONT, mask);
  1356. glStencilFuncSeparate(GL_FRONT, convertCompareFunction(func), refValue, mask);
  1357. glStencilOpSeparate(GL_FRONT,
  1358. convertStencilOp(stencilFailOp, flip),
  1359. convertStencilOp(depthFailOp, flip),
  1360. convertStencilOp(passOp, flip));
  1361. }
  1362. else // EXT_stencil_two_side
  1363. {
  1364. glEnable(GL_STENCIL_TEST_TWO_SIDE_EXT);
  1365. // Back
  1366. glActiveStencilFaceEXT(GL_BACK);
  1367. glStencilMask(mask);
  1368. glStencilFunc(convertCompareFunction(func), refValue, mask);
  1369. glStencilOp(
  1370. convertStencilOp(stencilFailOp, !flip),
  1371. convertStencilOp(depthFailOp, !flip),
  1372. convertStencilOp(passOp, !flip));
  1373. // Front
  1374. glActiveStencilFaceEXT(GL_FRONT);
  1375. glStencilMask(mask);
  1376. glStencilFunc(convertCompareFunction(func), refValue, mask);
  1377. glStencilOp(
  1378. convertStencilOp(stencilFailOp, flip),
  1379. convertStencilOp(depthFailOp, flip),
  1380. convertStencilOp(passOp, flip));
  1381. }
  1382. }
  1383. else
  1384. {
  1385. if(!GLEW_VERSION_2_0)
  1386. glDisable(GL_STENCIL_TEST_TWO_SIDE_EXT);
  1387. flip = false;
  1388. glStencilMask(mask);
  1389. glStencilFunc(convertCompareFunction(func), refValue, mask);
  1390. glStencilOp(
  1391. convertStencilOp(stencilFailOp, flip),
  1392. convertStencilOp(depthFailOp, flip),
  1393. convertStencilOp(passOp, flip));
  1394. }
  1395. }
  1396. //---------------------------------------------------------------------
  1397. GLint GLRenderSystem::convertCompareFunction(CompareFunction func) const
  1398. {
  1399. switch(func)
  1400. {
  1401. case CMPF_ALWAYS_FAIL:
  1402. return GL_NEVER;
  1403. case CMPF_ALWAYS_PASS:
  1404. return GL_ALWAYS;
  1405. case CMPF_LESS:
  1406. return GL_LESS;
  1407. case CMPF_LESS_EQUAL:
  1408. return GL_LEQUAL;
  1409. case CMPF_EQUAL:
  1410. return GL_EQUAL;
  1411. case CMPF_NOT_EQUAL:
  1412. return GL_NOTEQUAL;
  1413. case CMPF_GREATER_EQUAL:
  1414. return GL_GEQUAL;
  1415. case CMPF_GREATER:
  1416. return GL_GREATER;
  1417. };
  1418. // to keep compiler happy
  1419. return GL_ALWAYS;
  1420. }
  1421. //---------------------------------------------------------------------
  1422. GLint GLRenderSystem::convertStencilOp(StencilOperation op, bool invert) const
  1423. {
  1424. switch(op)
  1425. {
  1426. case SOP_KEEP:
  1427. return GL_KEEP;
  1428. case SOP_ZERO:
  1429. return GL_ZERO;
  1430. case SOP_REPLACE:
  1431. return GL_REPLACE;
  1432. case SOP_INCREMENT:
  1433. return invert ? GL_DECR : GL_INCR;
  1434. case SOP_DECREMENT:
  1435. return invert ? GL_INCR : GL_DECR;
  1436. case SOP_INCREMENT_WRAP:
  1437. return invert ? GL_DECR_WRAP_EXT : GL_INCR_WRAP_EXT;
  1438. case SOP_DECREMENT_WRAP:
  1439. return invert ? GL_INCR_WRAP_EXT : GL_DECR_WRAP_EXT;
  1440. case SOP_INVERT:
  1441. return GL_INVERT;
  1442. };
  1443. // to keep compiler happy
  1444. return SOP_KEEP;
  1445. }
  1446. //---------------------------------------------------------------------
  1447. GLuint GLRenderSystem::getCombinedMinMipFilter(void) const
  1448. {
  1449. switch(mMinFilter)
  1450. {
  1451. case FO_ANISOTROPIC:
  1452. case FO_LINEAR:
  1453. switch(mMipFilter)
  1454. {
  1455. case FO_ANISOTROPIC:
  1456. case FO_LINEAR:
  1457. // linear min, linear mip
  1458. return GL_LINEAR_MIPMAP_LINEAR;
  1459. case FO_POINT:
  1460. // linear min, point mip
  1461. return GL_LINEAR_MIPMAP_NEAREST;
  1462. case FO_NONE:
  1463. // linear min, no mip
  1464. return GL_LINEAR;
  1465. }
  1466. break;
  1467. case FO_POINT:
  1468. case FO_NONE:
  1469. switch(mMipFilter)
  1470. {
  1471. case FO_ANISOTROPIC:
  1472. case FO_LINEAR:
  1473. // nearest min, linear mip
  1474. return GL_NEAREST_MIPMAP_LINEAR;
  1475. case FO_POINT:
  1476. // nearest min, point mip
  1477. return GL_NEAREST_MIPMAP_NEAREST;
  1478. case FO_NONE:
  1479. // nearest min, no mip
  1480. return GL_NEAREST;
  1481. }
  1482. break;
  1483. }
  1484. // should never get here
  1485. return 0;
  1486. }
  1487. //---------------------------------------------------------------------
  1488. void GLRenderSystem::setTextureFiltering(size_t unit,
  1489. FilterType ftype, FilterOptions fo)
  1490. {
  1491. if (!activateGLTextureUnit(unit))
  1492. return;
  1493. switch(ftype)
  1494. {
  1495. case FT_MIN:
  1496. mMinFilter = fo;
  1497. // Combine with existing mip filter
  1498. glTexParameteri(
  1499. mTextureTypes[unit],
  1500. GL_TEXTURE_MIN_FILTER,
  1501. getCombinedMinMipFilter());
  1502. break;
  1503. case FT_MAG:
  1504. switch (fo)
  1505. {
  1506. case FO_ANISOTROPIC: // GL treats linear and aniso the same
  1507. case FO_LINEAR:
  1508. glTexParameteri(
  1509. mTextureTypes[unit],
  1510. GL_TEXTURE_MAG_FILTER,
  1511. GL_LINEAR);
  1512. break;
  1513. case FO_POINT:
  1514. case FO_NONE:
  1515. glTexParameteri(
  1516. mTextureTypes[unit],
  1517. GL_TEXTURE_MAG_FILTER,
  1518. GL_NEAREST);
  1519. break;
  1520. }
  1521. break;
  1522. case FT_MIP:
  1523. mMipFilter = fo;
  1524. // Combine with existing min filter
  1525. glTexParameteri(
  1526. mTextureTypes[unit],
  1527. GL_TEXTURE_MIN_FILTER,
  1528. getCombinedMinMipFilter());
  1529. break;
  1530. }
  1531. activateGLTextureUnit(0);
  1532. }
  1533. //---------------------------------------------------------------------
  1534. GLfloat GLRenderSystem::_getCurrentAnisotropy(size_t unit)
  1535. {
  1536. GLfloat curAniso = 0;
  1537. glGetTexParameterfv(mTextureTypes[unit],
  1538. GL_TEXTURE_MAX_ANISOTROPY_EXT, &curAniso);
  1539. return curAniso ? curAniso : 1;
  1540. }
  1541. //---------------------------------------------------------------------
  1542. void GLRenderSystem::setTextureAnisotropy(size_t unit, unsigned int maxAnisotropy)
  1543. {
  1544. if (!mCurrentCapabilities->hasCapability(RSC_ANISOTROPY))
  1545. return;
  1546. if (!activateGLTextureUnit(unit))
  1547. return;
  1548. GLfloat largest_supported_anisotropy = 0;
  1549. glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &largest_supported_anisotropy);
  1550. if (maxAnisotropy > largest_supported_anisotropy)
  1551. maxAnisotropy = largest_supported_anisotropy ?
  1552. static_cast<UINT32>(largest_supported_anisotropy) : 1;
  1553. if (_getCurrentAnisotropy(unit) != maxAnisotropy)
  1554. glTexParameterf(mTextureTypes[unit], GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)maxAnisotropy);
  1555. activateGLTextureUnit(0);
  1556. }
  1557. //---------------------------------------------------------------------
  1558. void GLRenderSystem::setVertexDeclaration(VertexDeclarationPtr decl)
  1559. {
  1560. }
  1561. //---------------------------------------------------------------------
  1562. void GLRenderSystem::setVertexBufferBinding(VertexBufferBinding* binding)
  1563. {
  1564. }
  1565. //---------------------------------------------------------------------
  1566. void GLRenderSystem::render(const RenderOperation& op)
  1567. {
  1568. // Call super class
  1569. RenderSystem::render(op);
  1570. void* pBufferData = 0;
  1571. bool multitexturing = (getCapabilities()->getNumTextureUnits() > 1);
  1572. const VertexDeclaration::VertexElementList& decl =
  1573. op.vertexData->vertexDeclaration->getElements();
  1574. VertexDeclaration::VertexElementList::const_iterator elem, elemEnd;
  1575. elemEnd = decl.end();
  1576. vector<GLuint>::type attribsBound;
  1577. for (elem = decl.begin(); elem != elemEnd; ++elem)
  1578. {
  1579. if (!op.vertexData->vertexBufferBinding->isBufferBound(elem->getSource()))
  1580. continue; // skip unbound elements
  1581. HardwareVertexBufferPtr vertexBuffer =
  1582. op.vertexData->vertexBufferBinding->getBuffer(elem->getSource());
  1583. if(mCurrentCapabilities->hasCapability(RSC_VBO))
  1584. {
  1585. glBindBufferARB(GL_ARRAY_BUFFER_ARB,
  1586. static_cast<const GLHardwareVertexBuffer*>(vertexBuffer.get())->getGLBufferId());
  1587. pBufferData = VBO_BUFFER_OFFSET(elem->getOffset());
  1588. }
  1589. else
  1590. {
  1591. pBufferData = static_cast<const GLDefaultHardwareVertexBuffer*>(vertexBuffer.get())->getDataPtr(elem->getOffset());
  1592. }
  1593. if (op.vertexData->vertexStart)
  1594. {
  1595. pBufferData = static_cast<char*>(pBufferData) + op.vertexData->vertexStart * vertexBuffer->getVertexSize();
  1596. }
  1597. unsigned int i = 0;
  1598. VertexElementSemantic sem = elem->getSemantic();
  1599. bool isCustomAttrib = false;
  1600. if (mCurrentVertexProgram)
  1601. isCustomAttrib = mCurrentVertexProgram->isAttributeValid(sem, elem->getIndex());
  1602. // Custom attribute support
  1603. // tangents, binormals, blendweights etc always via this route
  1604. // builtins may be done this way too
  1605. if (isCustomAttrib)
  1606. {
  1607. GLint attrib = mCurrentVertexProgram->getAttributeIndex(sem, elem->getIndex());
  1608. unsigned short typeCount = VertexElement::getTypeCount(elem->getType());
  1609. GLboolean normalised = GL_FALSE;
  1610. switch(elem->getType())
  1611. {
  1612. case VET_COLOUR:
  1613. case VET_COLOUR_ABGR:
  1614. case VET_COLOUR_ARGB:
  1615. // Because GL takes these as a sequence of single unsigned bytes, count needs to be 4
  1616. // VertexElement::getTypeCount treats them as 1 (RGBA)
  1617. // Also need to normalise the fixed-point data
  1618. typeCount = 4;
  1619. normalised = GL_TRUE;
  1620. break;
  1621. default:
  1622. break;
  1623. };
  1624. glVertexAttribPointerARB(
  1625. attrib,
  1626. typeCount,
  1627. GLHardwareBufferManager::getGLType(elem->getType()),
  1628. normalised,
  1629. static_cast<GLsizei>(vertexBuffer->getVertexSize()),
  1630. pBufferData);
  1631. glEnableVertexAttribArrayARB(attrib);
  1632. attribsBound.push_back(attrib);
  1633. }
  1634. else
  1635. {
  1636. // fixed-function & builtin attribute support
  1637. switch(sem)
  1638. {
  1639. case VES_POSITION:
  1640. glVertexPointer(VertexElement::getTypeCount(
  1641. elem->getType()),
  1642. GLHardwareBufferManager::getGLType(elem->getType()),
  1643. static_cast<GLsizei>(vertexBuffer->getVertexSize()),
  1644. pBufferData);
  1645. glEnableClientState( GL_VERTEX_ARRAY );
  1646. break;
  1647. case VES_NORMAL:
  1648. glNormalPointer(
  1649. GLHardwareBufferManager::getGLType(elem->getType()),
  1650. static_cast<GLsizei>(vertexBuffer->getVertexSize()),
  1651. pBufferData);
  1652. glEnableClientState( GL_NORMAL_ARRAY );
  1653. break;
  1654. case VES_DIFFUSE:
  1655. glColorPointer(4,
  1656. GLHardwareBufferManager::getGLType(elem->getType()),
  1657. static_cast<GLsizei>(vertexBuffer->getVertexSize()),
  1658. pBufferData);
  1659. glEnableClientState( GL_COLOR_ARRAY );
  1660. break;
  1661. case VES_SPECULAR:
  1662. if (GLEW_EXT_secondary_color)
  1663. {
  1664. glSecondaryColorPointerEXT(4,
  1665. GLHardwareBufferManager::getGLType(elem->getType()),
  1666. static_cast<GLsizei>(vertexBuffer->getVertexSize()),
  1667. pBufferData);
  1668. glEnableClientState( GL_SECONDARY_COLOR_ARRAY );
  1669. }
  1670. break;
  1671. case VES_TEXTURE_COORDINATES:
  1672. if (mCurrentVertexProgram)
  1673. {
  1674. // Programmable pipeline - direct UV assignment
  1675. glClientActiveTextureARB(GL_TEXTURE0 + elem->getIndex());
  1676. glTexCoordPointer(
  1677. VertexElement::getTypeCount(elem->getType()),
  1678. GLHardwareBufferManager::getGLType(elem->getType()),
  1679. static_cast<GLsizei>(vertexBuffer->getVertexSize()),
  1680. pBufferData);
  1681. glEnableClientState( GL_TEXTURE_COORD_ARRAY );
  1682. }
  1683. else
  1684. {
  1685. // fixed function matching to units based on tex_coord_set
  1686. for (i = 0; i < mDisabledTexUnitsFrom; i++)
  1687. {
  1688. // Only set this texture unit's texcoord pointer if it
  1689. // is supposed to be using this element's index
  1690. if (mTextureCoordIndex[i] == elem->getIndex() && i < mFixedFunctionTextureUnits)
  1691. {
  1692. if (multitexturing)
  1693. glClientActiveTextureARB(GL_TEXTURE0 + i);
  1694. glTexCoordPointer(
  1695. VertexElement::getTypeCount(elem->getType()),
  1696. GLHardwareBufferManager::getGLType(elem->getType()),
  1697. static_cast<GLsizei>(vertexBuffer->getVertexSize()),
  1698. pBufferData);
  1699. glEnableClientState( GL_TEXTURE_COORD_ARRAY );
  1700. }
  1701. }
  1702. }
  1703. break;
  1704. default:
  1705. break;
  1706. };
  1707. } // isCustomAttrib
  1708. }
  1709. if (multitexturing)
  1710. glClientActiveTextureARB(GL_TEXTURE0);
  1711. // Find the correct type to render
  1712. GLint primType;
  1713. //Use adjacency if there is a geometry program and it requested adjacency info
  1714. bool useAdjacency = (mGeometryProgramBound && mCurrentGeometryProgram->isAdjacencyInfoRequired());
  1715. switch (op.operationType)
  1716. {
  1717. case RenderOperation::OT_POINT_LIST:
  1718. primType = GL_POINTS;
  1719. break;
  1720. case RenderOperation::OT_LINE_LIST:
  1721. primType = useAdjacency ? GL_LINES_ADJACENCY_EXT : GL_LINES;
  1722. break;
  1723. case RenderOperation::OT_LINE_STRIP:
  1724. primType = useAdjacency ? GL_LINE_STRIP_ADJACENCY_EXT : GL_LINE_STRIP;
  1725. break;
  1726. default:
  1727. case RenderOperation::OT_TRIANGLE_LIST:
  1728. primType = useAdjacency ? GL_TRIANGLES_ADJACENCY_EXT : GL_TRIANGLES;
  1729. break;
  1730. case RenderOperation::OT_TRIANGLE_STRIP:
  1731. primType = useAdjacency ? GL_TRIANGLE_STRIP_ADJACENCY_EXT : GL_TRIANGLE_STRIP;
  1732. break;
  1733. case RenderOperation::OT_TRIANGLE_FAN:
  1734. primType = GL_TRIANGLE_FAN;
  1735. break;
  1736. }
  1737. if (op.useIndexes)
  1738. {
  1739. if(mCurrentCapabilities->hasCapability(RSC_VBO))
  1740. {
  1741. glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB,
  1742. static_cast<GLHardwareIndexBuffer*>(
  1743. op.indexData->indexBuffer.get())->getGLBufferId());
  1744. pBufferData = VBO_BUFFER_OFFSET(
  1745. op.indexData->indexStart * op.indexData->indexBuffer->getIndexSize());
  1746. }
  1747. else
  1748. {
  1749. pBufferData = static_cast<GLDefaultHardwareIndexBuffer*>(
  1750. op.indexData->indexBuffer.get())->getDataPtr(
  1751. op.indexData->indexStart * op.indexData->indexBuffer->getIndexSize());
  1752. }
  1753. GLenum indexType = (op.indexData->indexBuffer->getType() == HardwareIndexBuffer::IT_16BIT) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
  1754. glDrawElements(primType, op.indexData->indexCount, indexType, pBufferData);
  1755. }
  1756. else
  1757. {
  1758. glDrawArrays(primType, 0, op.vertexData->vertexCount);
  1759. }
  1760. glDisableClientState( GL_VERTEX_ARRAY );
  1761. // only valid up to GL_MAX_TEXTURE_UNITS, which is recorded in mFixedFunctionTextureUnits
  1762. if (multitexturing)
  1763. {
  1764. for (int i = 0; i < mFixedFunctionTextureUnits; i++)
  1765. {
  1766. glClientActiveTextureARB(GL_TEXTURE0 + i);
  1767. glDisableClientState( GL_TEXTURE_COORD_ARRAY );
  1768. }
  1769. glClientActiveTextureARB(GL_TEXTURE0);
  1770. }
  1771. else
  1772. {
  1773. glDisableClientState( GL_TEXTURE_COORD_ARRAY );
  1774. }
  1775. glDisableClientState( GL_NORMAL_ARRAY );
  1776. glDisableClientState( GL_COLOR_ARRAY );
  1777. if (GLEW_EXT_secondary_color)
  1778. {
  1779. glDisableClientState( GL_SECONDARY_COLOR_ARRAY );
  1780. }
  1781. // unbind any custom attributes
  1782. for (vector<GLuint>::type::iterator ai = attribsBound.begin(); ai != attribsBound.end(); ++ai)
  1783. {
  1784. glDisableVertexAttribArrayARB(*ai);
  1785. }
  1786. glColor4f(1,1,1,1);
  1787. if (GLEW_EXT_secondary_color)
  1788. {
  1789. glSecondaryColor3fEXT(0.0f, 0.0f, 0.0f);
  1790. }
  1791. }
  1792. //---------------------------------------------------------------------
  1793. void GLRenderSystem::bindGpuProgram(GpuProgramRef prg)
  1794. {
  1795. GpuProgram* bindingPrg = prg->_getBindingDelegate();
  1796. GLGpuProgram* glprg = static_cast<GLGpuProgram*>(bindingPrg);
  1797. // Unbind previous gpu program first.
  1798. //
  1799. // Note:
  1800. // 1. Even if both previous and current are the same object, we can't
  1801. // bypass re-bind completely since the object itself maybe modified.
  1802. // But we can bypass unbind based on the assumption that object
  1803. // internally GL program type shouldn't be changed after it has
  1804. // been created. The behavior of bind to a GL program type twice
  1805. // should be same as unbind and rebind that GL program type, even
  1806. // for difference objects.
  1807. // 2. We also assumed that the program's type (vertex or fragment) should
  1808. // not be changed during it's in using. If not, the following switch
  1809. // statement will confuse GL state completely, and we can't fix it
  1810. // here. To fix this case, we must coding the program implementation
  1811. // itself, if type is changing (during load/unload, etc), and it's inuse,
  1812. // unbind and notify render system to correct for its state.
  1813. //
  1814. switch (glprg->getType())
  1815. {
  1816. case GPT_VERTEX_PROGRAM:
  1817. if (mCurrentVertexProgram != glprg)
  1818. {
  1819. if (mCurrentVertexProgram)
  1820. mCurrentVertexProgram->unbindProgram();
  1821. mCurrentVertexProgram = glprg;
  1822. }
  1823. break;
  1824. case GPT_FRAGMENT_PROGRAM:
  1825. if (mCurrentFragmentProgram != glprg)
  1826. {
  1827. if (mCurrentFragmentProgram)
  1828. mCurrentFragmentProgram->unbindProgram();
  1829. mCurrentFragmentProgram = glprg;
  1830. }
  1831. break;
  1832. case GPT_GEOMETRY_PROGRAM:
  1833. if (mCurrentGeometryProgram != glprg)
  1834. {
  1835. if (mCurrentGeometryProgram)
  1836. mCurrentGeometryProgram->unbindProgram();
  1837. mCurrentGeometryProgram = glprg;
  1838. }
  1839. break;
  1840. }
  1841. // Bind the program
  1842. glprg->bindProgram();
  1843. RenderSystem::bindGpuProgram(prg);
  1844. }
  1845. //---------------------------------------------------------------------
  1846. void GLRenderSystem::unbindGpuProgram(GpuProgramType gptype)
  1847. {
  1848. if (gptype == GPT_VERTEX_PROGRAM && mCurrentVertexProgram)
  1849. {
  1850. mActiveVertexGpuProgramParameters = nullptr;
  1851. mCurrentVertexProgram->unbindProgram();
  1852. mCurrentVertexProgram = 0;
  1853. }
  1854. else if (gptype == GPT_GEOMETRY_PROGRAM && mCurrentGeometryProgram)
  1855. {
  1856. mActiveGeometryGpuProgramParameters = nullptr;
  1857. mCurrentGeometryProgram->unbindProgram();
  1858. mCurrentGeometryProgram = 0;
  1859. }
  1860. else if (gptype == GPT_FRAGMENT_PROGRAM && mCurrentFragmentProgram)
  1861. {
  1862. mActiveFragmentGpuProgramParameters = nullptr;
  1863. mCurrentFragmentProgram->unbindProgram();
  1864. mCurrentFragmentProgram = 0;
  1865. }
  1866. RenderSystem::unbindGpuProgram(gptype);
  1867. }
  1868. //---------------------------------------------------------------------
  1869. void GLRenderSystem::bindGpuProgramParameters(GpuProgramType gptype, GpuProgramParametersSharedPtr params, UINT16 mask)
  1870. {
  1871. // Set textures
  1872. const GpuNamedConstants& consts = params->getConstantDefinitions();
  1873. for(auto iter = consts.map.begin(); iter != consts.map.end(); ++iter)
  1874. {
  1875. const GpuConstantDefinition& def = iter->second;
  1876. if(def.variability & mask)
  1877. {
  1878. if(def.constType == GCT_SAMPLER2D || def.constType == GCT_SAMPLERCUBE || def.constType == GCT_SAMPLER1D
  1879. || def.constType == GCT_SAMPLER2DSHADOW || def.constType == GCT_SAMPLER3D || def.constType == GCT_SAMPLER1DSHADOW)
  1880. {
  1881. TextureRef curTexture = params->getTexture(def.physicalIndex);
  1882. setTexture(def.physicalIndex, true, curTexture.getInternalPtr());
  1883. const SamplerState& samplerState = params->getSamplerState(def.physicalIndex);
  1884. setTextureUnitSettings(def.physicalIndex, curTexture.getInternalPtr(), samplerState);
  1885. }
  1886. }
  1887. }
  1888. switch (gptype)
  1889. {
  1890. case GPT_VERTEX_PROGRAM:
  1891. mActiveVertexGpuProgramParameters = params;
  1892. mCurrentVertexProgram->bindProgramParameters(params, mask);
  1893. break;
  1894. case GPT_GEOMETRY_PROGRAM:
  1895. mActiveGeometryGpuProgramParameters = params;
  1896. mCurrentGeometryProgram->bindProgramParameters(params, mask);
  1897. break;
  1898. case GPT_FRAGMENT_PROGRAM:
  1899. mActiveFragmentGpuProgramParameters = params;
  1900. mCurrentFragmentProgram->bindProgramParameters(params, mask);
  1901. break;
  1902. }
  1903. }
  1904. //---------------------------------------------------------------------
  1905. void GLRenderSystem::setClipPlanesImpl(const PlaneList& clipPlanes)
  1906. {
  1907. // A note on GL user clipping:
  1908. // When an ARB vertex program is enabled in GL, user clipping is completely
  1909. // disabled. There is no way around this, it's just turned off.
  1910. // When using GLSL, user clipping can work but you have to include a
  1911. // glClipVertex command in your vertex shader.
  1912. // Thus the planes set here may not actually be respected.
  1913. size_t i = 0;
  1914. size_t numClipPlanes;
  1915. GLdouble clipPlane[4];
  1916. // Save previous modelview
  1917. glMatrixMode(GL_MODELVIEW);
  1918. glPushMatrix();
  1919. // just load view matrix (identity world)
  1920. GLfloat mat[16];
  1921. makeGLMatrix(mat, mViewMatrix);
  1922. glLoadMatrixf(mat);
  1923. numClipPlanes = clipPlanes.size();
  1924. for (i = 0; i < numClipPlanes; ++i)
  1925. {
  1926. GLenum clipPlaneId = static_cast<GLenum>(GL_CLIP_PLANE0 + i);
  1927. const Plane& plane = clipPlanes[i];
  1928. if (i >= 6/*GL_MAX_CLIP_PLANES*/)
  1929. {
  1930. CM_EXCEPT(RenderingAPIException, "Unable to set clip plane");
  1931. }
  1932. clipPlane[0] = plane.normal.x;
  1933. clipPlane[1] = plane.normal.y;
  1934. clipPlane[2] = plane.normal.z;
  1935. clipPlane[3] = plane.d;
  1936. glClipPlane(clipPlaneId, clipPlane);
  1937. glEnable(clipPlaneId);
  1938. }
  1939. // disable remaining clip planes
  1940. for ( ; i < 6/*GL_MAX_CLIP_PLANES*/; ++i)
  1941. {
  1942. glDisable(static_cast<GLenum>(GL_CLIP_PLANE0 + i));
  1943. }
  1944. // restore matrices
  1945. glPopMatrix();
  1946. }
  1947. //---------------------------------------------------------------------
  1948. void GLRenderSystem::setScissorTest(bool enabled, size_t left,
  1949. size_t top, size_t right, size_t bottom)
  1950. {
  1951. // If request texture flipping, use "upper-left", otherwise use "lower-left"
  1952. bool flipping = mActiveRenderTarget->requiresTextureFlipping();
  1953. // GL measures from the bottom, not the top
  1954. size_t targetHeight = mActiveRenderTarget->getHeight();
  1955. // Calculate the "lower-left" corner of the viewport
  1956. GLsizei x = 0, y = 0, w = 0, h = 0;
  1957. if (enabled)
  1958. {
  1959. glEnable(GL_SCISSOR_TEST);
  1960. // NB GL uses width / height rather than right / bottom
  1961. x = left;
  1962. if (flipping)
  1963. y = top;
  1964. else
  1965. y = targetHeight - bottom;
  1966. w = right - left;
  1967. h = bottom - top;
  1968. glScissor(x, y, w, h);
  1969. }
  1970. else
  1971. {
  1972. glDisable(GL_SCISSOR_TEST);
  1973. // GL requires you to reset the scissor when disabling
  1974. w = mActiveViewport.getActualWidth();
  1975. h = mActiveViewport.getActualHeight();
  1976. x = mActiveViewport.getActualLeft();
  1977. if (flipping)
  1978. y = mActiveViewport.getActualTop();
  1979. else
  1980. y = targetHeight - mActiveViewport.getActualTop() - h;
  1981. glScissor(x, y, w, h);
  1982. }
  1983. }
  1984. //---------------------------------------------------------------------
  1985. void GLRenderSystem::clearFrameBuffer(unsigned int buffers,
  1986. const Color& colour, float depth, unsigned short stencil)
  1987. {
  1988. bool colourMask = !mColourWrite[0] || !mColourWrite[1]
  1989. || !mColourWrite[2] || !mColourWrite[3];
  1990. GLbitfield flags = 0;
  1991. if (buffers & FBT_COLOUR)
  1992. {
  1993. flags |= GL_COLOR_BUFFER_BIT;
  1994. // Enable buffer for writing if it isn't
  1995. if (colourMask)
  1996. {
  1997. glColorMask(true, true, true, true);
  1998. }
  1999. glClearColor(colour.r, colour.g, colour.b, colour.a);
  2000. }
  2001. if (buffers & FBT_DEPTH)
  2002. {
  2003. flags |= GL_DEPTH_BUFFER_BIT;
  2004. // Enable buffer for writing if it isn't
  2005. if (!mDepthWrite)
  2006. {
  2007. glDepthMask( GL_TRUE );
  2008. }
  2009. glClearDepth(depth);
  2010. }
  2011. if (buffers & FBT_STENCIL)
  2012. {
  2013. flags |= GL_STENCIL_BUFFER_BIT;
  2014. // Enable buffer for writing if it isn't
  2015. glStencilMask(0xFFFFFFFF);
  2016. glClearStencil(stencil);
  2017. }
  2018. // Should be enable scissor test due the clear region is
  2019. // relied on scissor box bounds.
  2020. GLboolean scissorTestEnabled = glIsEnabled(GL_SCISSOR_TEST);
  2021. if (!scissorTestEnabled)
  2022. {
  2023. glEnable(GL_SCISSOR_TEST);
  2024. }
  2025. // Sets the scissor box as same as viewport
  2026. GLint viewport[4] = { 0, 0, 0, 0 };
  2027. GLint scissor[4] = { 0, 0, 0, 0 };
  2028. glGetIntegerv(GL_VIEWPORT, viewport);
  2029. glGetIntegerv(GL_SCISSOR_BOX, scissor);
  2030. bool scissorBoxDifference =
  2031. viewport[0] != scissor[0] || viewport[1] != scissor[1] ||
  2032. viewport[2] != scissor[2] || viewport[3] != scissor[3];
  2033. if (scissorBoxDifference)
  2034. {
  2035. glScissor(viewport[0], viewport[1], viewport[2], viewport[3]);
  2036. }
  2037. // Clear buffers
  2038. glClear(flags);
  2039. // Restore scissor box
  2040. if (scissorBoxDifference)
  2041. {
  2042. glScissor(scissor[0], scissor[1], scissor[2], scissor[3]);
  2043. }
  2044. // Restore scissor test
  2045. if (!scissorTestEnabled)
  2046. {
  2047. glDisable(GL_SCISSOR_TEST);
  2048. }
  2049. // Reset buffer write state
  2050. if (!mDepthWrite && (buffers & FBT_DEPTH))
  2051. {
  2052. glDepthMask( GL_FALSE );
  2053. }
  2054. if (colourMask && (buffers & FBT_COLOUR))
  2055. {
  2056. glColorMask(mColourWrite[0], mColourWrite[1], mColourWrite[2], mColourWrite[3]);
  2057. }
  2058. if (buffers & FBT_STENCIL)
  2059. {
  2060. glStencilMask(mStencilMask);
  2061. }
  2062. }
  2063. //---------------------------------------------------------------------
  2064. float GLRenderSystem::getHorizontalTexelOffset(void)
  2065. {
  2066. // No offset in GL
  2067. return 0.0f;
  2068. }
  2069. //---------------------------------------------------------------------
  2070. float GLRenderSystem::getVerticalTexelOffset(void)
  2071. {
  2072. // No offset in GL
  2073. return 0.0f;
  2074. }
  2075. //---------------------------------------------------------------------
  2076. void GLRenderSystem::_oneTimeContextInitialization()
  2077. {
  2078. if (GLEW_VERSION_1_2)
  2079. {
  2080. // Set nicer lighting model -- d3d9 has this by default
  2081. glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
  2082. glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, 1);
  2083. }
  2084. if (GLEW_VERSION_1_4)
  2085. {
  2086. glEnable(GL_COLOR_SUM);
  2087. glDisable(GL_DITHER);
  2088. }
  2089. // Check for FSAA
  2090. // Enable the extension if it was enabled by the GLSupport
  2091. if (mGLSupport->checkExtension("GL_ARB_multisample"))
  2092. {
  2093. int fsaa_active = false;
  2094. glGetIntegerv(GL_SAMPLE_BUFFERS_ARB,(GLint*)&fsaa_active);
  2095. if(fsaa_active)
  2096. {
  2097. glEnable(GL_MULTISAMPLE_ARB);
  2098. }
  2099. }
  2100. }
  2101. //---------------------------------------------------------------------
  2102. void GLRenderSystem::_switchContext(GLContext *context)
  2103. {
  2104. // Unbind GPU programs and rebind to new context later, because
  2105. // scene manager treat render system as ONE 'context' ONLY, and it
  2106. // cached the GPU programs using state.
  2107. if (mCurrentVertexProgram)
  2108. mCurrentVertexProgram->unbindProgram();
  2109. if (mCurrentGeometryProgram)
  2110. mCurrentGeometryProgram->unbindProgram();
  2111. if (mCurrentFragmentProgram)
  2112. mCurrentFragmentProgram->unbindProgram();
  2113. // Disable lights
  2114. mCurrentLights = 0;
  2115. // Disable textures
  2116. disableTextureUnitsFrom(0);
  2117. // It's ready for switching
  2118. if (mCurrentContext)
  2119. mCurrentContext->endCurrent();
  2120. mCurrentContext = context;
  2121. mCurrentContext->setCurrent();
  2122. // Check if the context has already done one-time initialisation
  2123. if(!mCurrentContext->getInitialized())
  2124. {
  2125. _oneTimeContextInitialization();
  2126. mCurrentContext->setInitialized();
  2127. }
  2128. // Rebind GPU programs to new context
  2129. if (mCurrentVertexProgram)
  2130. mCurrentVertexProgram->bindProgram();
  2131. if (mCurrentGeometryProgram)
  2132. mCurrentGeometryProgram->bindProgram();
  2133. if (mCurrentFragmentProgram)
  2134. mCurrentFragmentProgram->bindProgram();
  2135. // Must reset depth/colour write mask to according with user desired, otherwise,
  2136. // clearFrameBuffer would be wrong because the value we are recorded may be
  2137. // difference with the really state stored in GL context.
  2138. glDepthMask(mDepthWrite);
  2139. glColorMask(mColourWrite[0], mColourWrite[1], mColourWrite[2], mColourWrite[3]);
  2140. glStencilMask(mStencilMask);
  2141. }
  2142. //---------------------------------------------------------------------
  2143. void GLRenderSystem::setRenderTarget(RenderTarget *target)
  2144. {
  2145. // Unbind frame buffer object
  2146. if(mActiveRenderTarget)
  2147. GLRTTManager::instancePtr()->unbind(mActiveRenderTarget);
  2148. mActiveRenderTarget = target;
  2149. // Switch context if different from current one
  2150. GLContext *newContext = 0;
  2151. target->getCustomAttribute("GLCONTEXT", &newContext);
  2152. if(newContext && mCurrentContext != newContext)
  2153. {
  2154. _switchContext(newContext);
  2155. }
  2156. // Bind frame buffer object
  2157. GLRTTManager::instancePtr()->bind(target);
  2158. if (GLEW_EXT_framebuffer_sRGB)
  2159. {
  2160. // Enable / disable sRGB states
  2161. if (target->isHardwareGammaEnabled())
  2162. {
  2163. glEnable(GL_FRAMEBUFFER_SRGB_EXT);
  2164. // Note: could test GL_FRAMEBUFFER_SRGB_CAPABLE_EXT here before
  2165. // enabling, but GL spec says incapable surfaces ignore the setting
  2166. // anyway. We test the capability to enable isHardwareGammaEnabled.
  2167. }
  2168. else
  2169. {
  2170. glDisable(GL_FRAMEBUFFER_SRGB_EXT);
  2171. }
  2172. }
  2173. }
  2174. //---------------------------------------------------------------------
  2175. void GLRenderSystem::_unregisterContext(GLContext *context)
  2176. {
  2177. if(mCurrentContext == context) {
  2178. // Change the context to something else so that a valid context
  2179. // remains active. When this is the main context being unregistered,
  2180. // we set the main context to 0.
  2181. if(mCurrentContext != mMainContext) {
  2182. _switchContext(mMainContext);
  2183. } else {
  2184. /// No contexts remain
  2185. mCurrentContext->endCurrent();
  2186. mCurrentContext = 0;
  2187. mMainContext = 0;
  2188. }
  2189. }
  2190. }
  2191. //---------------------------------------------------------------------
  2192. float GLRenderSystem::getMinimumDepthInputValue(void)
  2193. {
  2194. // Range [-1.0f, 1.0f]
  2195. return -1.0f;
  2196. }
  2197. //---------------------------------------------------------------------
  2198. float GLRenderSystem::getMaximumDepthInputValue(void)
  2199. {
  2200. // Range [-1.0f, 1.0f]
  2201. return 1.0f;
  2202. }
  2203. //---------------------------------------------------------------------
  2204. void GLRenderSystem::registerThread()
  2205. {
  2206. CM_LOCK_MUTEX(mThreadInitMutex)
  2207. // This is only valid once we've created the main context
  2208. if (!mMainContext)
  2209. {
  2210. CM_EXCEPT(InvalidParametersException,
  2211. "Cannot register a background thread before the main context has been created.");
  2212. }
  2213. // Create a new context for this thread. Cloning from the main context
  2214. // will ensure that resources are shared with the main context
  2215. // We want a separate context so that we can safely create GL
  2216. // objects in parallel with the main thread
  2217. GLContext* newContext = mMainContext->clone();
  2218. mBackgroundContextList.push_back(newContext);
  2219. // Bind this new context to this thread.
  2220. newContext->setCurrent();
  2221. _oneTimeContextInitialization();
  2222. newContext->setInitialized();
  2223. }
  2224. //---------------------------------------------------------------------
  2225. void GLRenderSystem::unregisterThread()
  2226. {
  2227. // nothing to do here?
  2228. // Don't need to worry about active context, just make sure we delete
  2229. // on shutdown.
  2230. }
  2231. //---------------------------------------------------------------------
  2232. bool GLRenderSystem::activateGLTextureUnit(size_t unit)
  2233. {
  2234. if (mActiveTextureUnit != unit)
  2235. {
  2236. if (GLEW_VERSION_1_2 && unit < getCapabilities()->getNumTextureUnits())
  2237. {
  2238. glActiveTextureARB(GL_TEXTURE0 + unit);
  2239. mActiveTextureUnit = unit;
  2240. return true;
  2241. }
  2242. else if (!unit)
  2243. {
  2244. // always ok to use the first unit
  2245. return true;
  2246. }
  2247. else
  2248. {
  2249. return false;
  2250. }
  2251. }
  2252. else
  2253. {
  2254. return true;
  2255. }
  2256. }
  2257. //---------------------------------------------------------------------
  2258. unsigned int GLRenderSystem::getDisplayMonitorCount() const
  2259. {
  2260. return mGLSupport->getDisplayMonitorCount();
  2261. }
  2262. /************************************************************************/
  2263. /* INTERNAL CALLBACKS */
  2264. /************************************************************************/
  2265. void GLRenderSystem::startUp_internal(AsyncOp& asyncOp)
  2266. {
  2267. mGLSupport->start();
  2268. RenderSystem::startUp_internal(asyncOp);
  2269. }
  2270. void GLRenderSystem::createRenderWindow_internal(const String &name,
  2271. unsigned int width, unsigned int height, bool fullScreen,
  2272. const NameValuePairList& miscParams, AsyncOp& asyncOp)
  2273. {
  2274. if (mRenderTargets.find(name) != mRenderTargets.end())
  2275. {
  2276. CM_EXCEPT(InvalidParametersException,
  2277. "Window with name '" + name + "' already exists");
  2278. }
  2279. // Create the window
  2280. RenderWindow* win = mGLSupport->newWindow(name, width, height,
  2281. fullScreen, &miscParams);
  2282. attachRenderTarget( *win );
  2283. if (!mGLInitialised)
  2284. {
  2285. // set up glew and GLSupport
  2286. initialiseContext(win);
  2287. std::vector<CamelotEngine::String> tokens = StringUtil::split(mGLSupport->getGLVersion(), ".");
  2288. if (!tokens.empty())
  2289. {
  2290. mDriverVersion.major = parseInt(tokens[0]);
  2291. if (tokens.size() > 1)
  2292. mDriverVersion.minor = parseInt(tokens[1]);
  2293. if (tokens.size() > 2)
  2294. mDriverVersion.release = parseInt(tokens[2]);
  2295. }
  2296. mDriverVersion.build = 0;
  2297. // Initialise GL after the first window has been created
  2298. // TODO: fire this from emulation options, and don't duplicate float and Current capabilities
  2299. mRealCapabilities = createRenderSystemCapabilities();
  2300. // use real capabilities if custom capabilities are not available
  2301. if(!mUseCustomCapabilities)
  2302. mCurrentCapabilities = mRealCapabilities;
  2303. initialiseFromRenderSystemCapabilities(mCurrentCapabilities, win);
  2304. // Initialise the main context
  2305. _oneTimeContextInitialization();
  2306. if(mCurrentContext)
  2307. mCurrentContext->setInitialized();
  2308. }
  2309. asyncOp.completeOperation(win);
  2310. }
  2311. }