llrender.cpp 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352
  1. /**
  2. * @file llrender.cpp
  3. * @brief LLRender implementation
  4. *
  5. * $LicenseInfo:firstyear=2001&license=viewergpl$
  6. *
  7. * Copyright (c) 2001-2009, Linden Research, Inc.
  8. *
  9. * Second Life Viewer Source Code
  10. * The source code in this file ("Source Code") is provided by Linden Lab
  11. * to you under the terms of the GNU General Public License, version 2.0
  12. * ("GPL"), unless you have obtained a separate licensing agreement
  13. * ("Other License"), formally executed by you and Linden Lab. Terms of
  14. * the GPL can be found in doc/GPL-license.txt in this distribution, or
  15. * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
  16. *
  17. * There are special exceptions to the terms and conditions of the GPL as
  18. * it is applied to this Source Code. View the full text of the exception
  19. * in the file doc/FLOSS-exception.txt in this software distribution, or
  20. * online at
  21. * http://secondlifegrid.net/programs/open_source/licensing/flossexception
  22. *
  23. * By copying, modifying or distributing this software, you acknowledge
  24. * that you have read and understood your obligations described above,
  25. * and agree to abide by those obligations.
  26. *
  27. * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
  28. * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
  29. * COMPLETENESS OR PERFORMANCE.
  30. * ----------------------------------------------------------------------------
  31. * LLRender::projectf & LLRender::unprojectf adapted from gluProject &
  32. * gluUnproject in Mesa's GLU 9.0 library. License/Copyright Statement:
  33. * SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008)
  34. * Copyright (C) 1991-2000 Silicon Graphics, Inc. All Rights Reserved.
  35. *
  36. * Permission is hereby granted, free of charge, to any person obtaining a
  37. * copy of this software and associated documentation files (the "Software"),
  38. * to deal in the Software without restriction, including without limitation
  39. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  40. * and/or sell copies of the Software, and to permit persons to whom the
  41. * Software is furnished to do so, subject to the following conditions:
  42. *
  43. * The above copyright notice including the dates of first publication and
  44. * either this permission notice or a reference to
  45. * http://oss.sgi.com/projects/FreeB/
  46. * shall be included in all copies or substantial portions of the Software.
  47. *
  48. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  49. * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  50. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  51. * SILICON GRAPHICS, INC. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  52. * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
  53. * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  54. * SOFTWARE.
  55. *
  56. * Except as contained in this notice, the name of Silicon Graphics, Inc.
  57. * shall not be used in advertising or otherwise to promote the sale, use or
  58. * other dealings in this Software without prior written authorization from
  59. * Silicon Graphics, Inc.
  60. * $/LicenseInfo$
  61. */
  62. #include "linden_common.h"
  63. #include "llrender.h"
  64. #include "llcubemap.h"
  65. #include "hbfastmap.h"
  66. #include "llglslshader.h"
  67. #include "llgltexture.h"
  68. #include "llimagegl.h"
  69. #include "llmatrix4a.h"
  70. #include "llrendertarget.h"
  71. #include "llshadermgr.h"
  72. #include "llthread.h" // For *_main_thread()
  73. #include "hbtracy.h"
  74. #include "llvertexbuffer.h"
  75. #include "hbxxh.h"
  76. #if !GL_ARB_vertex_array_object && LL_CLANG
  77. // mDummyVAO is unused when there is no support for GL_ARB_vertex_array_object
  78. // (happens with macOS). So disable the corresponding warning in clang. HB
  79. # pragma clang diagnostic ignored "-Wunused-private-field"
  80. #endif
  81. thread_local LLRender gGL;
  82. // Handy copies of last good GL matrices
  83. LLMatrix4a gGLModelView;
  84. LLMatrix4a gGLLastModelView;
  85. LLMatrix4a gGLDeltaModelView;
  86. LLMatrix4a gGLInverseDeltaModelView;
  87. LLMatrix4a gGLLastProjection;
  88. LLMatrix4a gGLProjection;
  89. S32 gGLViewport[4];
  90. U32 LLTexUnit::sWhiteTexture = 0;
  91. U32 LLRender::sCurrentFrame = 0;
  92. bool LLRender::sGLCoreProfile = false;
  93. bool LLRender::sUseBufferCache = false;
  94. static const GLenum sGLTextureType[] =
  95. {
  96. GL_TEXTURE_2D,
  97. GL_TEXTURE_RECTANGLE,
  98. GL_TEXTURE_CUBE_MAP,
  99. GL_TEXTURE_CUBE_MAP_ARRAY,
  100. GL_TEXTURE_2D_MULTISAMPLE,
  101. };
  102. static const S32 sGLAddressMode[] =
  103. {
  104. GL_REPEAT,
  105. GL_MIRRORED_REPEAT,
  106. GL_CLAMP_TO_EDGE
  107. };
  108. constexpr U32 immediate_mask = LLVertexBuffer::MAP_VERTEX |
  109. LLVertexBuffer::MAP_COLOR |
  110. LLVertexBuffer::MAP_TEXCOORD0;
  111. static const GLenum sGLBlendFactor[] =
  112. {
  113. GL_ONE,
  114. GL_ZERO,
  115. GL_DST_COLOR,
  116. GL_SRC_COLOR,
  117. GL_ONE_MINUS_DST_COLOR,
  118. GL_ONE_MINUS_SRC_COLOR,
  119. GL_DST_ALPHA,
  120. GL_SRC_ALPHA,
  121. GL_ONE_MINUS_DST_ALPHA,
  122. GL_ONE_MINUS_SRC_ALPHA,
  123. GL_ZERO // 'BF_UNDEF'
  124. };
  125. ///////////////////////////////////////////////////////////////////////////////
  126. // LLVBCache class: a cache for vertex buffers
  127. ///////////////////////////////////////////////////////////////////////////////
  128. class LLVBCache
  129. {
  130. public:
  131. LLVBCache(LLVertexBuffer* vb)
  132. : mVB(vb),
  133. mLastFrameSeen(LLRender::sCurrentFrame)
  134. {
  135. }
  136. LL_INLINE LLVertexBuffer* get()
  137. {
  138. mLastFrameSeen = LLRender::sCurrentFrame;
  139. return mVB.get();
  140. }
  141. LL_INLINE bool expired() const
  142. {
  143. constexpr U32 MAX_FRAME_AGE = 120;
  144. return LLRender::sCurrentFrame - mLastFrameSeen > MAX_FRAME_AGE;
  145. }
  146. private:
  147. LLPointer<LLVertexBuffer> mVB;
  148. U32 mLastFrameSeen;
  149. };
  150. static flat_hmap<U64, LLVBCache> sVBCache;
  151. ///////////////////////////////////////////////////////////////////////////////
  152. // LLTexUnit class
  153. ///////////////////////////////////////////////////////////////////////////////
  154. LLTexUnit::LLTexUnit(S32 index)
  155. : mCurrTexType(TT_NONE),
  156. mCurrColorScale(1),
  157. mCurrAlphaScale(1),
  158. mCurrTexture(0),
  159. mTexColorSpace(TCS_LINEAR),
  160. mHasMipMaps(false),
  161. mIndex(index)
  162. {
  163. llassert_always(index < (S32)LL_NUM_TEXTURE_LAYERS);
  164. }
  165. //static
  166. U32 LLTexUnit::getInternalType(eTextureType type)
  167. {
  168. return sGLTextureType[type];
  169. }
  170. void LLTexUnit::refreshState()
  171. {
  172. // We set dirty to true so that the tex unit knows to ignore caching and we
  173. // reset the cached tex unit state
  174. gGL.flush();
  175. glActiveTexture(GL_TEXTURE0 + mIndex);
  176. if (mCurrTexType != TT_NONE)
  177. {
  178. glBindTexture(sGLTextureType[mCurrTexType], mCurrTexture);
  179. }
  180. else
  181. {
  182. glBindTexture(GL_TEXTURE_2D, 0);
  183. }
  184. setTextureColorSpace(mTexColorSpace);
  185. }
  186. void LLTexUnit::activate()
  187. {
  188. if (mIndex < 0) return;
  189. if ((S32)gGL.mCurrTextureUnitIndex != mIndex || gGL.mDirty)
  190. {
  191. #if 0
  192. gGL.flush();
  193. #endif
  194. glActiveTexture(GL_TEXTURE0 + mIndex);
  195. gGL.mCurrTextureUnitIndex = mIndex;
  196. }
  197. }
  198. void LLTexUnit::enable(eTextureType type)
  199. {
  200. if (mIndex < 0) return;
  201. if (type != TT_NONE && (mCurrTexType != type || gGL.mDirty))
  202. {
  203. activate();
  204. if (mCurrTexType != TT_NONE && !gGL.mDirty)
  205. {
  206. // Force a disable of a previous texture type if it is enabled:
  207. disable();
  208. }
  209. mCurrTexType = type;
  210. gGL.flush();
  211. }
  212. }
  213. void LLTexUnit::disable()
  214. {
  215. if (mIndex < 0) return;
  216. if (mCurrTexType != TT_NONE)
  217. {
  218. activate();
  219. unbind(mCurrTexType);
  220. gGL.flush();
  221. setTextureColorSpace(TCS_LINEAR);
  222. mCurrTexType = TT_NONE;
  223. }
  224. }
  225. void LLTexUnit::bindFast(LLGLTexture* gltexp)
  226. {
  227. LLImageGL* glimagep = gltexp->getGLImage();
  228. gltexp->setActive();
  229. glActiveTexture(GL_TEXTURE0 + mIndex);
  230. gGL.mCurrTextureUnitIndex = mIndex;
  231. mCurrTexture = glimagep->getTexName();
  232. mHasMipMaps = glimagep->mHasMipMaps;
  233. // Note: LL's code is bogus here, since when mCurrTexture is 0, it binds
  234. // the texture twice (and the second time to mCurrTexture which is 0)...
  235. // This is why I reverted the test and added the return (also favouring
  236. // tail call optimization in the process). HB
  237. if (mCurrTexture)
  238. {
  239. glBindTexture(sGLTextureType[glimagep->getTarget()], mCurrTexture);
  240. return;
  241. }
  242. // If deleted, will re-generate it immediately
  243. gltexp->forceImmediateUpdate();
  244. glimagep->forceUpdateBindStats();
  245. gltexp->bindDefaultImage(mIndex);
  246. }
  247. bool LLTexUnit::bind(LLGLTexture* gltexp, bool force_bind)
  248. {
  249. stop_glerror();
  250. if (mIndex < 0) return false;
  251. LLImageGL* glimagep = NULL;
  252. if (!gltexp || !(glimagep = gltexp->getGLImage()))
  253. {
  254. if (gltexp)
  255. {
  256. llwarns << "getGLImage() returned NULL" << llendl;
  257. }
  258. else
  259. {
  260. llwarns << "NULL texture (1)" << llendl;
  261. }
  262. return false;
  263. }
  264. if (glimagep->getTexName()) // If texture exists
  265. {
  266. // In audit, replace the selected texture by the default one.
  267. if (force_bind || mCurrTexture != glimagep->getTexName())
  268. {
  269. gGL.flush();
  270. activate();
  271. enable(glimagep->getTarget());
  272. mCurrTexture = glimagep->getTexName();
  273. glBindTexture(sGLTextureType[glimagep->getTarget()], mCurrTexture);
  274. if (glimagep->updateBindStats())
  275. {
  276. gltexp->setActive();
  277. }
  278. mHasMipMaps = glimagep->mHasMipMaps;
  279. if (glimagep->mTexOptionsDirty)
  280. {
  281. glimagep->mTexOptionsDirty = false;
  282. setTextureAddressMode(glimagep->mAddressMode);
  283. setTextureFilteringOption(glimagep->mFilterOption);
  284. }
  285. setTextureColorSpace(mTexColorSpace);
  286. }
  287. return true;
  288. }
  289. // If deleted, will re-generate it immediately
  290. gltexp->forceImmediateUpdate();
  291. glimagep->forceUpdateBindStats();
  292. return gltexp->bindDefaultImage(mIndex);
  293. }
  294. bool LLTexUnit::bind(LLImageGL* glimagep, bool force_bind, S32 usename)
  295. {
  296. stop_glerror();
  297. if (mIndex < 0) return false;
  298. U32 texname = usename ? usename : glimagep->getTexName();
  299. if (!glimagep)
  300. {
  301. llwarns << "NULL texture (2)" << llendl;
  302. return false;
  303. }
  304. if (!texname)
  305. {
  306. if (LLImageGL::sDefaultGLImagep &&
  307. LLImageGL::sDefaultGLImagep->getTexName())
  308. {
  309. return bind(LLImageGL::sDefaultGLImagep);
  310. }
  311. return false;
  312. }
  313. if (force_bind || mCurrTexture != texname)
  314. {
  315. gGL.flush();
  316. activate();
  317. enable(glimagep->getTarget());
  318. mCurrTexture = texname;
  319. glBindTexture(sGLTextureType[glimagep->getTarget()], mCurrTexture);
  320. glimagep->updateBindStats();
  321. mHasMipMaps = glimagep->mHasMipMaps;
  322. if (glimagep->mTexOptionsDirty)
  323. {
  324. glimagep->mTexOptionsDirty = false;
  325. setTextureAddressMode(glimagep->mAddressMode);
  326. setTextureFilteringOption(glimagep->mFilterOption);
  327. }
  328. setTextureColorSpace(mTexColorSpace);
  329. }
  330. stop_glerror();
  331. return true;
  332. }
  333. bool LLTexUnit::bind(LLCubeMap* cube_map)
  334. {
  335. if (mIndex < 0) return false;
  336. if (!cube_map)
  337. {
  338. llwarns << "NULL cubemap" << llendl;
  339. return false;
  340. }
  341. if (mCurrTexture == cube_map->mImages[0]->getTexName())
  342. {
  343. return true;
  344. }
  345. gGL.flush();
  346. activate();
  347. enable(LLTexUnit::TT_CUBE_MAP);
  348. mCurrTexture = cube_map->mImages[0]->getTexName();
  349. glBindTexture(GL_TEXTURE_CUBE_MAP, mCurrTexture);
  350. mHasMipMaps = cube_map->mImages[0]->mHasMipMaps;
  351. cube_map->mImages[0]->updateBindStats();
  352. if (cube_map->mImages[0]->mTexOptionsDirty)
  353. {
  354. cube_map->mImages[0]->mTexOptionsDirty = false;
  355. setTextureAddressMode(cube_map->mImages[0]->mAddressMode);
  356. setTextureFilteringOption(cube_map->mImages[0]->mFilterOption);
  357. }
  358. setTextureColorSpace(mTexColorSpace);
  359. return true;
  360. }
  361. bool LLTexUnit::bind(LLRenderTarget* targetp, bool bind_depth)
  362. {
  363. if (mIndex < 0) return false;
  364. if (bind_depth)
  365. {
  366. if (targetp->hasStencil())
  367. {
  368. llwarns_sparse << "Cannot bind. Allocate render target without a stencil buffer."
  369. << llendl;
  370. llassert_always(!gDebugGL);
  371. return false;
  372. }
  373. U32 depth = targetp->getDepth();
  374. if (!depth)
  375. {
  376. llwarns_sparse << "Cannot bind. Allocate render target with a depth buffer."
  377. << llendl;
  378. llassert_always(!gDebugGL);
  379. return false;
  380. }
  381. bindManual(targetp->getUsage(), depth);
  382. }
  383. else
  384. {
  385. bindManual(targetp->getUsage(), targetp->getTexture());
  386. }
  387. return true;
  388. }
  389. bool LLTexUnit::bindManual(eTextureType type, U32 texture, bool has_mips)
  390. {
  391. if (mIndex < 0)
  392. {
  393. return false;
  394. }
  395. if (mCurrTexture != texture)
  396. {
  397. gGL.flush();
  398. activate();
  399. enable(type);
  400. mCurrTexture = texture;
  401. glBindTexture(sGLTextureType[type], texture);
  402. mHasMipMaps = has_mips;
  403. setTextureColorSpace(mTexColorSpace);
  404. }
  405. return true;
  406. }
  407. void LLTexUnit::unbind(eTextureType type)
  408. {
  409. stop_glerror();
  410. if (mIndex < 0) return;
  411. #if 0 // Always flush and activate for consistency since some code paths
  412. // assume unbind always flushes and sets the active texture.
  413. if (gGL.mCurrTextureUnitIndex != (U32)mIndex || gGL.mDirty)
  414. #endif
  415. {
  416. gGL.flush();
  417. activate();
  418. }
  419. // Disabled caching of binding state.
  420. if (mCurrTexType == type && mCurrTexture != 0)
  421. {
  422. mCurrTexture = 0;
  423. // Always make sure our texture color space is reset to linear. SRGB
  424. // sampling should be opt-in in the vast majority of cases. This also
  425. // prevents color space "popping".
  426. mTexColorSpace = TCS_LINEAR;
  427. if (type == LLTexUnit::TT_TEXTURE)
  428. {
  429. glBindTexture(sGLTextureType[type], sWhiteTexture);
  430. }
  431. else
  432. {
  433. glBindTexture(sGLTextureType[type], 0);
  434. }
  435. stop_glerror();
  436. }
  437. }
  438. void LLTexUnit::unbindFast(eTextureType type)
  439. {
  440. activate();
  441. // Disabled caching of binding state.
  442. if (mCurrTexType == type)
  443. {
  444. mCurrTexture = 0;
  445. // Always make sure our texture color space is reset to linear.
  446. // SRGB sampling should be opt-in in the vast majority of cases.
  447. // Also prevents color space "popping".
  448. mTexColorSpace = TCS_LINEAR;
  449. if (type == TT_TEXTURE)
  450. {
  451. glBindTexture(sGLTextureType[type], sWhiteTexture);
  452. }
  453. else
  454. {
  455. glBindTexture(sGLTextureType[type], 0);
  456. }
  457. }
  458. }
  459. void LLTexUnit::setTextureAddressMode(eTextureAddressMode mode)
  460. {
  461. if (mIndex < 0 || mCurrTexture == 0) return;
  462. gGL.flush();
  463. activate();
  464. glTexParameteri(sGLTextureType[mCurrTexType], GL_TEXTURE_WRAP_S,
  465. sGLAddressMode[mode]);
  466. glTexParameteri(sGLTextureType[mCurrTexType], GL_TEXTURE_WRAP_T,
  467. sGLAddressMode[mode]);
  468. if (mCurrTexType == TT_CUBE_MAP)
  469. {
  470. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R,
  471. sGLAddressMode[mode]);
  472. }
  473. }
  474. void LLTexUnit::setTextureFilteringOption(LLTexUnit::eTextureFilterOptions option)
  475. {
  476. if (mIndex < 0 || mCurrTexture == 0 ||
  477. mCurrTexType == TT_MULTISAMPLE_TEXTURE)
  478. {
  479. return;
  480. }
  481. gGL.flush();
  482. if (option == TFO_POINT)
  483. {
  484. glTexParameteri(sGLTextureType[mCurrTexType], GL_TEXTURE_MAG_FILTER,
  485. GL_NEAREST);
  486. }
  487. else
  488. {
  489. glTexParameteri(sGLTextureType[mCurrTexType], GL_TEXTURE_MAG_FILTER,
  490. GL_LINEAR);
  491. }
  492. if (option >= TFO_TRILINEAR && mHasMipMaps)
  493. {
  494. glTexParameteri(sGLTextureType[mCurrTexType],
  495. GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
  496. }
  497. else if (option >= TFO_BILINEAR)
  498. {
  499. if (mHasMipMaps)
  500. {
  501. glTexParameteri(sGLTextureType[mCurrTexType],
  502. GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
  503. }
  504. else
  505. {
  506. glTexParameteri(sGLTextureType[mCurrTexType],
  507. GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  508. }
  509. }
  510. else if (mHasMipMaps)
  511. {
  512. glTexParameteri(sGLTextureType[mCurrTexType], GL_TEXTURE_MIN_FILTER,
  513. GL_NEAREST_MIPMAP_NEAREST);
  514. }
  515. else
  516. {
  517. glTexParameteri(sGLTextureType[mCurrTexType], GL_TEXTURE_MIN_FILTER,
  518. GL_NEAREST);
  519. }
  520. if (gGLManager.mHasAnisotropic)
  521. {
  522. F32 anisotropy = 1.f;
  523. if (LLImageGL::sGlobalUseAnisotropic && option == TFO_ANISOTROPIC)
  524. {
  525. anisotropy = gGLManager.mMaxAnisotropy;
  526. }
  527. glTexParameterf(sGLTextureType[mCurrTexType],
  528. GL_TEXTURE_MAX_ANISOTROPY, anisotropy);
  529. }
  530. }
  531. S32 LLTexUnit::getTextureSource(eTextureBlendSrc src)
  532. {
  533. switch (src)
  534. {
  535. // All four cases should return the same value.
  536. case TBS_PREV_COLOR:
  537. case TBS_PREV_ALPHA:
  538. case TBS_ONE_MINUS_PREV_COLOR:
  539. case TBS_ONE_MINUS_PREV_ALPHA:
  540. return GL_PREVIOUS;
  541. // All four cases should return the same value.
  542. case TBS_TEX_COLOR:
  543. case TBS_TEX_ALPHA:
  544. case TBS_ONE_MINUS_TEX_COLOR:
  545. case TBS_ONE_MINUS_TEX_ALPHA:
  546. return GL_TEXTURE;
  547. // All four cases should return the same value.
  548. case TBS_VERT_COLOR:
  549. case TBS_VERT_ALPHA:
  550. case TBS_ONE_MINUS_VERT_COLOR:
  551. case TBS_ONE_MINUS_VERT_ALPHA:
  552. return GL_PRIMARY_COLOR;
  553. // All four cases should return the same value.
  554. case TBS_CONST_COLOR:
  555. case TBS_CONST_ALPHA:
  556. case TBS_ONE_MINUS_CONST_COLOR:
  557. case TBS_ONE_MINUS_CONST_ALPHA:
  558. return GL_CONSTANT;
  559. default:
  560. llwarns << "Unknown eTextureBlendSrc: " << src
  561. << ". Using Vertex Color instead." << llendl;
  562. return GL_PRIMARY_COLOR;
  563. }
  564. }
  565. S32 LLTexUnit::getTextureSourceType(eTextureBlendSrc src, bool is_alpha)
  566. {
  567. switch (src)
  568. {
  569. // All four cases should return the same value.
  570. case TBS_PREV_COLOR:
  571. case TBS_TEX_COLOR:
  572. case TBS_VERT_COLOR:
  573. case TBS_CONST_COLOR:
  574. return is_alpha ? GL_SRC_ALPHA: GL_SRC_COLOR;
  575. // All four cases should return the same value.
  576. case TBS_PREV_ALPHA:
  577. case TBS_TEX_ALPHA:
  578. case TBS_VERT_ALPHA:
  579. case TBS_CONST_ALPHA:
  580. return GL_SRC_ALPHA;
  581. // All four cases should return the same value.
  582. case TBS_ONE_MINUS_PREV_COLOR:
  583. case TBS_ONE_MINUS_TEX_COLOR:
  584. case TBS_ONE_MINUS_VERT_COLOR:
  585. case TBS_ONE_MINUS_CONST_COLOR:
  586. return is_alpha ? GL_ONE_MINUS_SRC_ALPHA : GL_ONE_MINUS_SRC_COLOR;
  587. // All four cases should return the same value.
  588. case TBS_ONE_MINUS_PREV_ALPHA:
  589. case TBS_ONE_MINUS_TEX_ALPHA:
  590. case TBS_ONE_MINUS_VERT_ALPHA:
  591. case TBS_ONE_MINUS_CONST_ALPHA:
  592. return GL_ONE_MINUS_SRC_ALPHA;
  593. default:
  594. llwarns << "Unknown eTextureBlendSrc: " << src
  595. << ". Using Source Color or Alpha instead." << llendl;
  596. return is_alpha ? GL_SRC_ALPHA: GL_SRC_COLOR;
  597. }
  598. }
  599. void LLTexUnit::setColorScale(S32 scale)
  600. {
  601. if (mCurrColorScale != scale || gGL.mDirty)
  602. {
  603. mCurrColorScale = scale;
  604. gGL.flush();
  605. glTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE, scale);
  606. }
  607. }
  608. void LLTexUnit::setAlphaScale(S32 scale)
  609. {
  610. if (mCurrAlphaScale != scale || gGL.mDirty)
  611. {
  612. mCurrAlphaScale = scale;
  613. gGL.flush();
  614. glTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, scale);
  615. }
  616. }
  617. // Useful for debugging that you have manually assigned a texture operation to
  618. // the correct texture unit based on the currently set active texture in
  619. // openGL.
  620. void LLTexUnit::debugTextureUnit()
  621. {
  622. if (mIndex < 0) return;
  623. GLint active_texture;
  624. glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);
  625. if (GL_TEXTURE0 + mIndex != active_texture)
  626. {
  627. U32 set_unit = (active_texture - GL_TEXTURE0);
  628. llwarns << "Incorrect Texture Unit ! Expected: " << set_unit
  629. << " - Actual: " << mIndex << llendl;
  630. }
  631. }
  632. ///////////////////////////////////////////////////////////////////////////////
  633. // LLLightState class
  634. ///////////////////////////////////////////////////////////////////////////////
  635. LLLightState::LLLightState(S32 index)
  636. : mIndex(index),
  637. mEnabled(false),
  638. mSunIsPrimary(true),
  639. mConstantAtten(1.f),
  640. mLinearAtten(0.f),
  641. mQuadraticAtten(0.f),
  642. mSpotExponent(0.f),
  643. mSpotCutoff(180.f),
  644. mSize(0.f),
  645. mFalloff(0.f)
  646. {
  647. if (mIndex == 0)
  648. {
  649. mDiffuse.set(1.f, 1.f, 1.f, 1.f);
  650. mDiffuseB.set(0.f, 0.f, 0.f, 0.f);
  651. mSpecular.set(1.f, 1.f, 1.f, 1.f);
  652. }
  653. mAmbient.set(0.f, 0.f, 0.f, 1.f);
  654. mPosition.set(0.f, 0.f, 1.f, 0.f);
  655. mSpotDirection.set(0.f, 0.f, -1.f);
  656. }
  657. void LLLightState::enable()
  658. {
  659. if (!mEnabled)
  660. {
  661. mEnabled = true;
  662. }
  663. }
  664. void LLLightState::disable()
  665. {
  666. if (mEnabled)
  667. {
  668. mEnabled = false;
  669. }
  670. }
  671. void LLLightState::setDiffuse(const LLColor4& diffuse)
  672. {
  673. if (mDiffuse != diffuse)
  674. {
  675. ++gGL.mLightHash;
  676. mDiffuse = diffuse;
  677. }
  678. }
  679. void LLLightState::setDiffuseB(const LLColor4& diffuse)
  680. {
  681. if (mDiffuseB != diffuse)
  682. {
  683. ++gGL.mLightHash;
  684. mDiffuseB = diffuse;
  685. }
  686. }
  687. void LLLightState::setSunPrimary(bool b)
  688. {
  689. if (mSunIsPrimary != b)
  690. {
  691. ++gGL.mLightHash;
  692. mSunIsPrimary = b;
  693. }
  694. }
  695. void LLLightState::setSize(F32 size)
  696. {
  697. if (mSize != size)
  698. {
  699. ++gGL.mLightHash;
  700. mSize = size;
  701. }
  702. }
  703. void LLLightState::setFalloff(F32 falloff)
  704. {
  705. if (mFalloff != falloff)
  706. {
  707. ++gGL.mLightHash;
  708. mFalloff = falloff;
  709. }
  710. }
  711. void LLLightState::setAmbient(const LLColor4& ambient)
  712. {
  713. if (mAmbient != ambient)
  714. {
  715. ++gGL.mLightHash;
  716. mAmbient = ambient;
  717. }
  718. }
  719. void LLLightState::setSpecular(const LLColor4& specular)
  720. {
  721. if (mSpecular != specular)
  722. {
  723. ++gGL.mLightHash;
  724. mSpecular = specular;
  725. }
  726. }
  727. void LLLightState::setPosition(const LLVector4& position)
  728. {
  729. ++gGL.mLightHash;
  730. // Always set position because modelview matrix may have changed
  731. mPosition = position;
  732. LLVector4a pos;
  733. pos.loadua(position.mV);
  734. // Transform position by current modelview matrix
  735. gGL.getModelviewMatrix().rotate4(pos, pos);
  736. mPosition.set(pos.getF32ptr());
  737. }
  738. void LLLightState::setConstantAttenuation(F32 atten)
  739. {
  740. if (mConstantAtten != atten)
  741. {
  742. mConstantAtten = atten;
  743. ++gGL.mLightHash;
  744. }
  745. }
  746. void LLLightState::setLinearAttenuation(F32 atten)
  747. {
  748. if (mLinearAtten != atten)
  749. {
  750. ++gGL.mLightHash;
  751. mLinearAtten = atten;
  752. }
  753. }
  754. void LLLightState::setQuadraticAttenuation(F32 atten)
  755. {
  756. if (mQuadraticAtten != atten)
  757. {
  758. ++gGL.mLightHash;
  759. mQuadraticAtten = atten;
  760. }
  761. }
  762. void LLLightState::setSpotExponent(F32 exponent)
  763. {
  764. if (mSpotExponent != exponent)
  765. {
  766. ++gGL.mLightHash;
  767. mSpotExponent = exponent;
  768. }
  769. }
  770. void LLLightState::setSpotCutoff(F32 cutoff)
  771. {
  772. if (mSpotCutoff != cutoff)
  773. {
  774. ++gGL.mLightHash;
  775. mSpotCutoff = cutoff;
  776. }
  777. }
  778. void LLLightState::setSpotDirection(const LLVector3& direction)
  779. {
  780. ++gGL.mLightHash;
  781. // Always set direction because modelview matrix may have changed
  782. mSpotDirection = direction;
  783. // Transform direction by current modelview matrix
  784. LLVector4a dir;
  785. dir.load3(direction.mV);
  786. gGL.getModelviewMatrix().rotate(dir, dir);
  787. mSpotDirection.set(dir.getF32ptr());
  788. }
  789. ///////////////////////////////////////////////////////////////////////////////
  790. // LLRender class
  791. ///////////////////////////////////////////////////////////////////////////////
  792. LLRender::LLRender()
  793. : mDummyVAO(0),
  794. mValid(false),
  795. mDirty(false),
  796. mCacheMissCount(0),
  797. mCount(0),
  798. mMode(TRIANGLES),
  799. mCurrTextureUnitIndex(0),
  800. mLightHash(0),
  801. mFrozenLights(false),
  802. mCurrBlendColorSFactor(BF_UNDEF),
  803. mCurrBlendAlphaSFactor(BF_UNDEF),
  804. mCurrBlendColorDFactor(BF_UNDEF),
  805. mCurrBlendAlphaDFactor(BF_UNDEF),
  806. mMatrixMode(MM_MODELVIEW)
  807. {
  808. mTexUnits.reserve(LL_NUM_TEXTURE_LAYERS);
  809. for (U32 i = 0; i < LL_NUM_TEXTURE_LAYERS; ++i)
  810. {
  811. mTexUnits.push_back(new LLTexUnit(i));
  812. }
  813. mDummyTexUnit = new LLTexUnit(-1);
  814. for (U32 i = 0; i < LL_NUM_LIGHT_UNITS; ++i)
  815. {
  816. mLightState.push_back(new LLLightState(i));
  817. }
  818. for (U32 i = 0; i < 4; ++i)
  819. {
  820. mCurrColorMask[i] = true;
  821. }
  822. for (U32 i = 0; i < NUM_MATRIX_MODES; ++i)
  823. {
  824. mMatIdx[i] = 0;
  825. mMatHash[i] = 0;
  826. mCurMatHash[i] = 0xFFFFFFFF;
  827. }
  828. // Init base matrix for each mode
  829. for (U32 i = 0; i < NUM_MATRIX_MODES; ++i)
  830. {
  831. mMatrix[i][0].setIdentity();
  832. }
  833. gGLModelView.setIdentity();
  834. gGLLastModelView.setIdentity();
  835. gGLProjection.setIdentity();
  836. gGLLastProjection.setIdentity();
  837. }
  838. LLRender::~LLRender()
  839. {
  840. shutdown();
  841. }
  842. //static
  843. void APIENTRY LLRender::debugCallback(GLenum, GLenum type, GLuint id,
  844. GLenum severity, GLsizei,
  845. const GLchar* message, GLvoid*)
  846. {
  847. // We only care about GL errors, and only while debugging GL
  848. if (gDebugGL && severity == GL_DEBUG_SEVERITY_HIGH)
  849. {
  850. llwarns << "GL error type: " << std::hex << type << " - Id: " << id
  851. << std::dec << " - Message: " << message << llendl;
  852. }
  853. }
  854. void LLRender::init()
  855. {
  856. #if GL_ARB_debug_output
  857. // Note: since init() is called at viewer startup, this callback will only
  858. // be setup when gDebugGL is initialized to true via the "DebugGLOnRestart"
  859. // debug setting, set in the previous viewer session or via the command
  860. // line of the current session. HB
  861. if (gDebugGL && gGLManager.mHasDebugOutput)
  862. {
  863. llinfos << "Setting up GL debug callback." << llendl;
  864. glDebugMessageCallback((GLDEBUGPROC)LLRender::debugCallback, NULL);
  865. glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
  866. }
  867. #endif
  868. glPixelStorei(GL_PACK_ALIGNMENT, 1);
  869. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  870. gGL.setSceneBlendType(LLRender::BT_ALPHA);
  871. gGL.setAmbientLightColor(LLColor4::black);
  872. glCullFace(GL_BACK);
  873. if (gGLManager.mGLVersion >= 3.2f)
  874. {
  875. // Necessary for reflection maps
  876. glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
  877. }
  878. // Vertex buffers (and the VBO pools they use) are not thread-safe, so we
  879. // *cannot* use mBuffer from GL threads ! Should we need it in the future
  880. // in shared GL profiles, then both LLVertexBuffer and LLVBOPool would need
  881. // to have their static variables turned into thread_local ones. HB
  882. if (is_main_thread())
  883. {
  884. #if GL_ARB_vertex_array_object
  885. if (sGLCoreProfile && gGLManager.mHasVertexArrayObject)
  886. {
  887. if (mDummyVAO)
  888. {
  889. glBindVertexArray(0);
  890. glDeleteVertexArrays(1, &mDummyVAO);
  891. mDummyVAO = 0;
  892. }
  893. // Bind a dummy vertex array object so that we are compliant with
  894. // the core GL profile.
  895. glGenVertexArrays(1, &mDummyVAO);
  896. glBindVertexArray(mDummyVAO);
  897. }
  898. #endif
  899. initVertexBuffer();
  900. }
  901. stop_glerror();
  902. mValid = true;
  903. }
  904. void LLRender::initVertexBuffer()
  905. {
  906. assert_main_thread();
  907. llassert_always(mBuffer.isNull());
  908. mBuffer = new LLVertexBuffer(immediate_mask);
  909. mBuffer->allocateBuffer(4096, 0);
  910. mBuffer->getVertexStrider(mVerticesp);
  911. mBuffer->getTexCoord0Strider(mTexcoordsp);
  912. mBuffer->getColorStrider(mColorsp);
  913. #if LL_DEBUG_VB_ALLOC
  914. mBuffer->setOwner("LLRender");
  915. #endif
  916. }
  917. void LLRender::resetVertexBuffer()
  918. {
  919. mBuffer = NULL;
  920. if (is_main_thread())
  921. {
  922. sVBCache.clear();
  923. }
  924. }
  925. void LLRender::shutdown()
  926. {
  927. stop_glerror();
  928. mValid = false;
  929. for (U32 i = 0, count = mTexUnits.size(); i < count; ++i)
  930. {
  931. delete mTexUnits[i];
  932. }
  933. mTexUnits.clear();
  934. delete mDummyTexUnit;
  935. mDummyTexUnit = NULL;
  936. for (U32 i = 0, count = mLightState.size(); i < count; ++i)
  937. {
  938. delete mLightState[i];
  939. }
  940. mLightState.clear();
  941. resetVertexBuffer();
  942. #if GL_ARB_vertex_array_object
  943. if (mDummyVAO)
  944. {
  945. glBindVertexArray(0);
  946. glDeleteVertexArrays(1, &mDummyVAO);
  947. mDummyVAO = 0;
  948. }
  949. #endif
  950. }
  951. void LLRender::refreshState()
  952. {
  953. mDirty = true;
  954. U32 active_unit = mCurrTextureUnitIndex;
  955. for (U32 i = 0, count = mTexUnits.size(); i < count; ++i)
  956. {
  957. mTexUnits[i]->refreshState();
  958. }
  959. mTexUnits[active_unit]->activate();
  960. setColorMask(mCurrColorMask[0], mCurrColorMask[1], mCurrColorMask[2],
  961. mCurrColorMask[3]);
  962. mDirty = false;
  963. }
  964. void LLRender::syncLightState()
  965. {
  966. LLGLSLShader* shaderp = LLGLSLShader::sCurBoundShaderPtr;
  967. if (!shaderp || shaderp->mLightHash == mLightHash ||
  968. // *HACK: to prevent lighting changes in preview shaders. HB
  969. (mFrozenLights && shaderp->mLightHash == 0))
  970. {
  971. return;
  972. }
  973. if (mFrozenLights)
  974. {
  975. // *HACK: to prevent lighting changes in preview shaders. HB
  976. shaderp->mLightHash = 0;
  977. }
  978. else
  979. {
  980. shaderp->mLightHash = mLightHash;
  981. }
  982. static LLVector4 position[LL_NUM_LIGHT_UNITS];
  983. static LLVector3 direction[LL_NUM_LIGHT_UNITS];
  984. static LLVector4 attenuation[LL_NUM_LIGHT_UNITS];
  985. static LLVector3 diffuse[LL_NUM_LIGHT_UNITS];
  986. static LLVector2 size[LL_NUM_LIGHT_UNITS];
  987. for (U32 i = 0; i < LL_NUM_LIGHT_UNITS; ++i)
  988. {
  989. LLLightState* lightp = mLightState[i];
  990. position[i] = lightp->mPosition;
  991. direction[i] = lightp->mSpotDirection;
  992. attenuation[i].set(lightp->mLinearAtten, lightp->mQuadraticAtten,
  993. lightp->mSpecular.mV[2], lightp->mSpecular.mV[3]);
  994. diffuse[i].set(lightp->mDiffuse.mV);
  995. if (gUsePBRShaders)
  996. {
  997. size[i].set(lightp->mSize, lightp->mFalloff);
  998. }
  999. }
  1000. shaderp->uniform4fv(LLShaderMgr::LIGHT_POSITION, LL_NUM_LIGHT_UNITS,
  1001. position[0].mV);
  1002. shaderp->uniform3fv(LLShaderMgr::LIGHT_DIRECTION, LL_NUM_LIGHT_UNITS,
  1003. direction[0].mV);
  1004. shaderp->uniform4fv(LLShaderMgr::LIGHT_ATTENUATION, LL_NUM_LIGHT_UNITS,
  1005. attenuation[0].mV);
  1006. shaderp->uniform3fv(LLShaderMgr::LIGHT_DIFFUSE, LL_NUM_LIGHT_UNITS,
  1007. diffuse[0].mV);
  1008. LLLightState* sunlightp = mLightState[0];
  1009. shaderp->uniform1i(LLShaderMgr::SUN_UP_FACTOR,
  1010. sunlightp->mSunIsPrimary ? 1 : 0);
  1011. if (gUsePBRShaders)
  1012. {
  1013. shaderp->uniform2fv(LLShaderMgr::LIGHT_DEFERRED_ATTENUATION,
  1014. LL_NUM_LIGHT_UNITS, size[0].mV);
  1015. shaderp->uniform3fv(LLShaderMgr::LIGHT_AMBIENT, 1,
  1016. mAmbientLightColor.mV);
  1017. }
  1018. else
  1019. {
  1020. shaderp->uniform4fv(LLShaderMgr::LIGHT_AMBIENT, 1,
  1021. mAmbientLightColor.mV);
  1022. shaderp->uniform4fv(LLShaderMgr::AMBIENT, 1, mAmbientLightColor.mV);
  1023. shaderp->uniform4fv(LLShaderMgr::SUNLIGHT_COLOR, 1,
  1024. sunlightp->mDiffuse.mV);
  1025. shaderp->uniform4fv(LLShaderMgr::MOONLIGHT_COLOR, 1,
  1026. sunlightp->mDiffuseB.mV);
  1027. }
  1028. }
  1029. void LLRender::syncMatrices()
  1030. {
  1031. static const U32 name[] =
  1032. {
  1033. LLShaderMgr::MODELVIEW_MATRIX,
  1034. LLShaderMgr::PROJECTION_MATRIX,
  1035. LLShaderMgr::TEXTURE_MATRIX0,
  1036. LLShaderMgr::TEXTURE_MATRIX1,
  1037. LLShaderMgr::TEXTURE_MATRIX2,
  1038. LLShaderMgr::TEXTURE_MATRIX3,
  1039. };
  1040. static LLMatrix4a cached_mvp;
  1041. static LLMatrix4a cached_inv_mdv;
  1042. static U32 cached_mvp_mdv_hash = 0xFFFFFFFF;
  1043. static U32 cached_mvp_proj_hash = 0xFFFFFFFF;
  1044. static LLMatrix4a cached_normal;
  1045. static U32 cached_normal_hash = 0xFFFFFFFF;
  1046. LLGLSLShader* shaderp = LLGLSLShader::sCurBoundShaderPtr;
  1047. if (!shaderp)
  1048. {
  1049. return;
  1050. }
  1051. bool mvp_done = false;
  1052. S32 loc;
  1053. if (mMatHash[MM_MODELVIEW] != shaderp->mMatHash[MM_MODELVIEW])
  1054. {
  1055. // Update modelview, normal, and MVP
  1056. const LLMatrix4a& mat = mMatrix[MM_MODELVIEW][mMatIdx[MM_MODELVIEW]];
  1057. // If model view has changed, update the cached inverse as well
  1058. if (cached_mvp_mdv_hash != mMatHash[MM_MODELVIEW])
  1059. {
  1060. cached_inv_mdv = mat;
  1061. cached_inv_mdv.invert();
  1062. }
  1063. shaderp->uniformMatrix4fv(name[MM_MODELVIEW], 1, GL_FALSE,
  1064. mat.getF32ptr());
  1065. shaderp->mMatHash[MM_MODELVIEW] = mMatHash[MM_MODELVIEW];
  1066. // Update normal matrix
  1067. loc = shaderp->getUniformLocation(LLShaderMgr::NORMAL_MATRIX);
  1068. if (loc > -1)
  1069. {
  1070. if (cached_normal_hash != mMatHash[MM_MODELVIEW])
  1071. {
  1072. cached_normal = cached_inv_mdv;
  1073. cached_normal.transpose();
  1074. cached_normal_hash = mMatHash[MM_MODELVIEW];
  1075. }
  1076. const LLMatrix4a& norm = cached_normal;
  1077. LLVector3 norms[3];
  1078. norms[0].set(norm.getRow<0>().getF32ptr());
  1079. norms[1].set(norm.getRow<1>().getF32ptr());
  1080. norms[2].set(norm.getRow<2>().getF32ptr());
  1081. shaderp->uniformMatrix3fv(LLShaderMgr::NORMAL_MATRIX, 1, GL_FALSE,
  1082. norms[0].mV);
  1083. }
  1084. if (shaderp->getUniformLocation(LLShaderMgr::INVERSE_MODELVIEW_MATRIX) > -1)
  1085. {
  1086. shaderp->uniformMatrix4fv(LLShaderMgr::INVERSE_MODELVIEW_MATRIX, 1,
  1087. GL_FALSE, cached_inv_mdv.getF32ptr());
  1088. }
  1089. // Update MVP matrix
  1090. mvp_done = true;
  1091. loc =
  1092. shaderp->getUniformLocation(LLShaderMgr::MODELVIEW_PROJECTION_MATRIX);
  1093. if (loc > -1)
  1094. {
  1095. if (cached_mvp_mdv_hash != mMatHash[MM_MODELVIEW] ||
  1096. cached_mvp_proj_hash != mMatHash[MM_PROJECTION])
  1097. {
  1098. cached_mvp.setMul(mMatrix[MM_PROJECTION][mMatIdx[MM_PROJECTION]],
  1099. mat);
  1100. cached_mvp_mdv_hash = mMatHash[MM_MODELVIEW];
  1101. cached_mvp_proj_hash = mMatHash[MM_PROJECTION];
  1102. }
  1103. shaderp->uniformMatrix4fv(LLShaderMgr::MODELVIEW_PROJECTION_MATRIX,
  1104. 1, GL_FALSE, cached_mvp.getF32ptr());
  1105. }
  1106. }
  1107. if (mMatHash[MM_PROJECTION] != shaderp->mMatHash[MM_PROJECTION])
  1108. {
  1109. // Update projection matrix, normal, and MVP
  1110. const LLMatrix4a& mat = mMatrix[MM_PROJECTION][mMatIdx[MM_PROJECTION]];
  1111. if (gUsePBRShaders)
  1112. {
  1113. loc =
  1114. shaderp->getUniformLocation(LLShaderMgr::INVERSE_PROJECTION_MATRIX);
  1115. if (loc > -1)
  1116. {
  1117. LLMatrix4a inv_proj = mat;
  1118. inv_proj.invert();
  1119. shaderp->uniformMatrix4fv(LLShaderMgr::INVERSE_PROJECTION_MATRIX,
  1120. 1, GL_FALSE, inv_proj.getF32ptr());
  1121. }
  1122. }
  1123. shaderp->uniformMatrix4fv(name[MM_PROJECTION], 1, GL_FALSE,
  1124. mat.getF32ptr());
  1125. shaderp->mMatHash[MM_PROJECTION] = mMatHash[MM_PROJECTION];
  1126. if (!mvp_done)
  1127. {
  1128. // Update MVP matrix
  1129. loc =
  1130. shaderp->getUniformLocation(LLShaderMgr::MODELVIEW_PROJECTION_MATRIX);
  1131. if (loc > -1)
  1132. {
  1133. if (cached_mvp_mdv_hash != mMatHash[MM_PROJECTION] ||
  1134. cached_mvp_proj_hash != mMatHash[MM_PROJECTION])
  1135. {
  1136. cached_mvp.setMul(mat,
  1137. mMatrix[MM_MODELVIEW][mMatIdx[MM_MODELVIEW]]);
  1138. cached_mvp_mdv_hash = mMatHash[MM_MODELVIEW];
  1139. cached_mvp_proj_hash = mMatHash[MM_PROJECTION];
  1140. }
  1141. shaderp->uniformMatrix4fv(LLShaderMgr::MODELVIEW_PROJECTION_MATRIX,
  1142. 1, GL_FALSE, cached_mvp.getF32ptr());
  1143. }
  1144. }
  1145. }
  1146. for (U32 i = MM_TEXTURE0; i < NUM_MATRIX_MODES; ++i)
  1147. {
  1148. U32 hash = mMatHash[i];
  1149. if (shaderp->mMatHash[i] != hash)
  1150. {
  1151. shaderp->uniformMatrix4fv(name[i], 1, GL_FALSE,
  1152. mMatrix[i][mMatIdx[i]].getF32ptr());
  1153. shaderp->mMatHash[i] = hash;
  1154. }
  1155. }
  1156. if (shaderp->mFeatures.hasLighting ||
  1157. shaderp->mFeatures.calculatesLighting ||
  1158. shaderp->mFeatures.calculatesAtmospherics)
  1159. {
  1160. // Also sync light state
  1161. syncLightState();
  1162. }
  1163. stop_glerror();
  1164. }
  1165. void LLRender::translatef(F32 x, F32 y, F32 z)
  1166. {
  1167. if (fabsf(x) > F_APPROXIMATELY_ZERO || fabsf(y) > F_APPROXIMATELY_ZERO ||
  1168. fabsf(z) > F_APPROXIMATELY_ZERO)
  1169. {
  1170. flush();
  1171. mMatrix[mMatrixMode][mMatIdx[mMatrixMode]].applyTranslationAffine(x,
  1172. y,
  1173. z);
  1174. ++mMatHash[mMatrixMode];
  1175. }
  1176. }
  1177. void LLRender::scalef(F32 x, F32 y, F32 z)
  1178. {
  1179. if (fabsf(x - 1.f) > F_APPROXIMATELY_ZERO ||
  1180. fabsf(y - 1.f) > F_APPROXIMATELY_ZERO ||
  1181. fabsf(z - 1.f) > F_APPROXIMATELY_ZERO)
  1182. {
  1183. flush();
  1184. mMatrix[mMatrixMode][mMatIdx[mMatrixMode]].applyScaleAffine(x, y, z);
  1185. ++mMatHash[mMatrixMode];
  1186. }
  1187. }
  1188. void LLRender::ortho(F32 left, F32 right, F32 bottom, F32 top, F32 z_near,
  1189. F32 z_far)
  1190. {
  1191. flush();
  1192. LLMatrix4a ortho_mat;
  1193. ortho_mat.setRow<0>(LLVector4a(2.f / (right - left), 0.f, 0.f));
  1194. ortho_mat.setRow<1>(LLVector4a(0.f, 2.f / (top - bottom), 0.f));
  1195. ortho_mat.setRow<2>(LLVector4a(0.f, 0.f, -2.f / (z_far - z_near)));
  1196. ortho_mat.setRow<3>(LLVector4a((left + right) / (left - right),
  1197. (bottom + top) / (bottom - top),
  1198. (z_near + z_far) / (z_near - z_far), 1.f));
  1199. mMatrix[mMatrixMode][mMatIdx[mMatrixMode]].mulAffine(ortho_mat);
  1200. ++mMatHash[mMatrixMode];
  1201. }
  1202. void LLRender::rotatef(const LLMatrix4a& rot)
  1203. {
  1204. flush();
  1205. mMatrix[mMatrixMode][mMatIdx[mMatrixMode]].mulAffine(rot);
  1206. ++mMatHash[mMatrixMode];
  1207. }
  1208. void LLRender::rotatef(F32 a, F32 x, F32 y, F32 z)
  1209. {
  1210. if (fabsf(fmodf(a, 360.f)) > F_APPROXIMATELY_ZERO)
  1211. {
  1212. rotatef(gl_gen_rot(a, x, y, z));
  1213. }
  1214. }
  1215. bool LLRender::projectf(const LLVector3& object, const LLMatrix4a& modelview,
  1216. const LLMatrix4a& projection, const LLRect& viewport,
  1217. LLVector3& window_coord)
  1218. {
  1219. // Declare locals
  1220. const LLVector4a obj_vector(object.mV[VX], object.mV[VY], object.mV[VZ]);
  1221. const LLVector4a one(1.f);
  1222. LLVector4a temp_vec; // Scratch vector
  1223. LLVector4a w; // Splatted W-component.
  1224. // temp_vec = modelview * obj_vector;
  1225. modelview.affineTransform(obj_vector, temp_vec);
  1226. // Passing temp_matrix as v and res is safe. res not altered until after
  1227. // all other calculations
  1228. // temp_vec = projection * temp_vec
  1229. projection.rotate4(temp_vec, temp_vec);
  1230. // w = temp_vec.wwww
  1231. w.splat<3>(temp_vec);
  1232. // If w == 0.f, use 1.f instead. Defer return if temp_vec.w == 0.f until
  1233. // after all SSE intrinsics.
  1234. LLVector4a div;
  1235. // float div = (w[N] == 0.f ? 1.f : w[N]);
  1236. div.setSelectWithMask(w.equal(_mm_setzero_ps()), one, w);
  1237. // temp_vec /= div;
  1238. temp_vec.div(div);
  1239. // Map x, y to range 0-1
  1240. temp_vec.mul(.5f);
  1241. temp_vec.add(.5f);
  1242. LLVector4Logical mask = temp_vec.equal(_mm_setzero_ps());
  1243. if (mask.areAllSet(LLVector4Logical::MASK_W))
  1244. {
  1245. return false;
  1246. }
  1247. // Window coordinates
  1248. window_coord[0] = temp_vec[VX] * viewport.getWidth() + viewport.mLeft;
  1249. window_coord[1] = temp_vec[VY] * viewport.getHeight() + viewport.mBottom;
  1250. // This is only correct when glDepthRange(0.f, 1.f)
  1251. window_coord[2] = temp_vec[VZ];
  1252. return true;
  1253. }
  1254. bool LLRender::unprojectf(const LLVector3& window_coord,
  1255. const LLMatrix4a& modelview,
  1256. const LLMatrix4a& projection,
  1257. const LLRect& viewport, LLVector3& object)
  1258. {
  1259. static const LLVector4a one(1.f);
  1260. static const LLVector4a two(2.f);
  1261. LLVector4a norm_view((window_coord.mV[VX] - (F32)viewport.mLeft) /
  1262. (F32)viewport.getWidth(),
  1263. (window_coord.mV[VY] - (F32)viewport.mBottom) /
  1264. (F32)viewport.getHeight(),
  1265. window_coord.mV[VZ], 1.f);
  1266. LLMatrix4a inv_mat; // Inverse transformation matrix
  1267. LLVector4a temp_vec; // Scratch vector
  1268. LLVector4a w; // Splatted W-component.
  1269. // inv_mat = projection * modelview
  1270. inv_mat.setMul(projection, modelview);
  1271. F32 det = inv_mat.invert();
  1272. // Normalize. -1.0 : +1.0
  1273. norm_view.mul(two); // norm_view *= vec4(.2f)
  1274. norm_view.sub(one); // norm_view -= vec4(1.f)
  1275. inv_mat.rotate4(norm_view, temp_vec); // inv_mat * norm_view
  1276. w.splat<3>(temp_vec); // w = temp_vec.wwww
  1277. // If w == 0.f, use 1.f instead. Defer return if temp_vec.w == 0.f until
  1278. // after all SSE intrinsics.
  1279. LLVector4a div;
  1280. // float div = (w[N] == 0.f ? 1.f : w[N]);
  1281. div.setSelectWithMask(w.equal(_mm_setzero_ps()), one, w);
  1282. temp_vec.div(div); // temp_vec /= div;
  1283. LLVector4Logical mask = temp_vec.equal(_mm_setzero_ps());
  1284. if (mask.areAllSet(LLVector4Logical::MASK_W))
  1285. {
  1286. return false;
  1287. }
  1288. if (det == 0.f)
  1289. {
  1290. return false;
  1291. }
  1292. object.set(temp_vec.getF32ptr());
  1293. return true;
  1294. }
  1295. void LLRender::pushMatrix()
  1296. {
  1297. #if 0
  1298. flush();
  1299. #endif
  1300. if (mMatIdx[mMatrixMode] < LL_MATRIX_STACK_DEPTH - 1)
  1301. {
  1302. mMatrix[mMatrixMode][mMatIdx[mMatrixMode] + 1] =
  1303. mMatrix[mMatrixMode][mMatIdx[mMatrixMode]];
  1304. ++mMatIdx[mMatrixMode];
  1305. }
  1306. else
  1307. {
  1308. llwarns << "Matrix stack overflow." << llendl;
  1309. }
  1310. }
  1311. void LLRender::popMatrix()
  1312. {
  1313. flush();
  1314. if (mMatIdx[mMatrixMode] > 0)
  1315. {
  1316. --mMatIdx[mMatrixMode];
  1317. ++mMatHash[mMatrixMode];
  1318. }
  1319. else
  1320. {
  1321. llwarns << "Matrix stack underflow." << llendl;
  1322. }
  1323. }
  1324. void LLRender::loadMatrix(const F32* m)
  1325. {
  1326. flush();
  1327. mMatrix[mMatrixMode][mMatIdx[mMatrixMode]].loadu(m);
  1328. ++mMatHash[mMatrixMode];
  1329. }
  1330. void LLRender::loadMatrix(const LLMatrix4a& mat)
  1331. {
  1332. flush();
  1333. mMatrix[mMatrixMode][mMatIdx[mMatrixMode]] = mat;
  1334. ++mMatHash[mMatrixMode];
  1335. }
  1336. void LLRender::multMatrix(const F32* m)
  1337. {
  1338. flush();
  1339. LLMatrix4a mat;
  1340. mat.loadu(m);
  1341. mMatrix[mMatrixMode][mMatIdx[mMatrixMode]].mulAffine(mat);
  1342. ++mMatHash[mMatrixMode];
  1343. }
  1344. void LLRender::multMatrix(const LLMatrix4a& mat)
  1345. {
  1346. flush();
  1347. mMatrix[mMatrixMode][mMatIdx[mMatrixMode]].mulAffine(mat);
  1348. ++mMatHash[mMatrixMode];
  1349. }
  1350. void LLRender::matrixMode(U32 mode)
  1351. {
  1352. // Normally, mode == MM_TEXTURE or < NUM_MATRIX_MODES; consider any mode
  1353. // above NUM_MATRIX_MODES as being MM_TEXTURE.
  1354. if (mode >= NUM_MATRIX_MODES)
  1355. {
  1356. mode = MM_TEXTURE0 + gGL.getCurrentTexUnitIndex();
  1357. if (mode > MM_TEXTURE3)
  1358. {
  1359. llwarns << "Attempt to set matrix mode above MM_TEXTURE3. "
  1360. << "Current texture unit index is: " << mode - MM_TEXTURE0
  1361. << ". Setting matrix mode to MM_TEXTURE3, expect a render glitch..."
  1362. << llendl;
  1363. llassert(false);
  1364. mode = MM_TEXTURE0;
  1365. }
  1366. }
  1367. mMatrixMode = mode;
  1368. }
  1369. U32 LLRender::getMatrixMode()
  1370. {
  1371. if (mMatrixMode >= MM_TEXTURE0 && mMatrixMode <= MM_TEXTURE3)
  1372. {
  1373. // Always return MM_TEXTURE if current matrix mode points at any
  1374. // texture matrix
  1375. return MM_TEXTURE;
  1376. }
  1377. return mMatrixMode;
  1378. }
  1379. void LLRender::loadIdentity()
  1380. {
  1381. flush();
  1382. mMatrix[mMatrixMode][mMatIdx[mMatrixMode]].setIdentity();
  1383. ++mMatHash[mMatrixMode];
  1384. }
  1385. const LLMatrix4a& LLRender::getModelviewMatrix()
  1386. {
  1387. return mMatrix[MM_MODELVIEW][mMatIdx[MM_MODELVIEW]];
  1388. }
  1389. void LLRender::translateUI(F32 x, F32 y, F32 z)
  1390. {
  1391. if (mUIOffset.empty())
  1392. {
  1393. llerrs << "Need to push a UI translation frame before offsetting"
  1394. << llendl;
  1395. }
  1396. mUIOffset.back().mV[0] += x;
  1397. mUIOffset.back().mV[1] += y;
  1398. mUIOffset.back().mV[2] += z;
  1399. }
  1400. void LLRender::scaleUI(F32 x, F32 y, F32 z)
  1401. {
  1402. if (mUIScale.empty())
  1403. {
  1404. llerrs << "Need to push a UI transformation frame before scaling."
  1405. << llendl;
  1406. }
  1407. mUIScale.back().scaleVec(LLVector3(x, y, z));
  1408. }
  1409. void LLRender::pushUIMatrix()
  1410. {
  1411. if (mUIOffset.empty())
  1412. {
  1413. mUIOffset.emplace_back(0.f, 0.f, 0.f);
  1414. }
  1415. else
  1416. {
  1417. mUIOffset.emplace_back(mUIOffset.back());
  1418. }
  1419. if (mUIScale.empty())
  1420. {
  1421. mUIScale.emplace_back(1.f, 1.f, 1.f);
  1422. }
  1423. else
  1424. {
  1425. mUIScale.emplace_back(mUIScale.back());
  1426. }
  1427. }
  1428. void LLRender::popUIMatrix()
  1429. {
  1430. if (mUIOffset.empty())
  1431. {
  1432. llerrs << "UI offset stack blown." << llendl;
  1433. }
  1434. mUIOffset.pop_back();
  1435. mUIScale.pop_back();
  1436. }
  1437. LLVector3 LLRender::getUITranslation()
  1438. {
  1439. if (mUIOffset.empty())
  1440. {
  1441. return LLVector3::zero;
  1442. }
  1443. return mUIOffset.back();
  1444. }
  1445. LLVector3 LLRender::getUIScale()
  1446. {
  1447. if (mUIScale.empty())
  1448. {
  1449. return LLVector3::all_one;
  1450. }
  1451. return mUIScale.back();
  1452. }
  1453. void LLRender::loadUIIdentity()
  1454. {
  1455. if (mUIOffset.empty() || mUIScale.empty())
  1456. {
  1457. llerrs << "Need to push UI translation frame before clearing offset."
  1458. << llendl;
  1459. }
  1460. mUIOffset.back().clear();
  1461. mUIScale.back().set(1.f, 1.f, 1.f);
  1462. }
  1463. void LLRender::setColorMask(bool write_color, bool write_alpha)
  1464. {
  1465. setColorMask(write_color, write_color, write_color, write_alpha);
  1466. }
  1467. void LLRender::setColorMask(bool write_red, bool write_green,
  1468. bool write_blue, bool write_alpha)
  1469. {
  1470. if (mCurrColorMask[0] != write_red || mCurrColorMask[1] != write_green ||
  1471. mCurrColorMask[2] != write_blue || mCurrColorMask[3] != write_alpha)
  1472. {
  1473. mCurrColorMask[0] = write_red;
  1474. mCurrColorMask[1] = write_green;
  1475. mCurrColorMask[2] = write_blue;
  1476. mCurrColorMask[3] = write_alpha;
  1477. flush();
  1478. glColorMask(write_red ? GL_TRUE : GL_FALSE,
  1479. write_green ? GL_TRUE : GL_FALSE,
  1480. write_blue ? GL_TRUE : GL_FALSE,
  1481. write_alpha ? GL_TRUE : GL_FALSE);
  1482. }
  1483. }
  1484. void LLRender::setSceneBlendType(U32 type)
  1485. {
  1486. switch (type)
  1487. {
  1488. case BT_ALPHA:
  1489. blendFunc(BF_SOURCE_ALPHA, BF_ONE_MINUS_SOURCE_ALPHA);
  1490. break;
  1491. case BT_ADD:
  1492. blendFunc(BF_ONE, BF_ONE);
  1493. break;
  1494. case BT_ADD_WITH_ALPHA:
  1495. blendFunc(BF_SOURCE_ALPHA, BF_ONE);
  1496. break;
  1497. case BT_MULT:
  1498. blendFunc(BF_DEST_COLOR, BF_ZERO);
  1499. break;
  1500. case BT_MULT_ALPHA:
  1501. blendFunc(BF_DEST_ALPHA, BF_ZERO);
  1502. break;
  1503. case BT_MULT_X2:
  1504. blendFunc(BF_DEST_COLOR, BF_SOURCE_COLOR);
  1505. break;
  1506. case BT_REPLACE:
  1507. blendFunc(BF_ONE, BF_ZERO);
  1508. break;
  1509. default:
  1510. llerrs << "Unknown scene blend type: " << type << llendl;
  1511. }
  1512. }
  1513. void LLRender::blendFunc(U32 sfactor, U32 dfactor)
  1514. {
  1515. llassert(sfactor < BF_UNDEF && dfactor < BF_UNDEF);
  1516. if (mCurrBlendColorSFactor != sfactor ||
  1517. mCurrBlendColorDFactor != dfactor ||
  1518. mCurrBlendAlphaSFactor != sfactor ||
  1519. mCurrBlendAlphaDFactor != dfactor)
  1520. {
  1521. mCurrBlendColorSFactor = sfactor;
  1522. mCurrBlendAlphaSFactor = sfactor;
  1523. mCurrBlendColorDFactor = dfactor;
  1524. mCurrBlendAlphaDFactor = dfactor;
  1525. flush();
  1526. glBlendFunc(sGLBlendFactor[sfactor], sGLBlendFactor[dfactor]);
  1527. }
  1528. }
  1529. void LLRender::blendFunc(U32 color_sfactor,
  1530. U32 color_dfactor,
  1531. U32 alpha_sfactor,
  1532. U32 alpha_dfactor)
  1533. {
  1534. llassert(color_sfactor < BF_UNDEF && color_dfactor < BF_UNDEF &&
  1535. alpha_sfactor < BF_UNDEF && alpha_dfactor < BF_UNDEF);
  1536. if (mCurrBlendColorSFactor != color_sfactor ||
  1537. mCurrBlendColorDFactor != color_dfactor ||
  1538. mCurrBlendAlphaSFactor != alpha_sfactor ||
  1539. mCurrBlendAlphaDFactor != alpha_dfactor)
  1540. {
  1541. mCurrBlendColorSFactor = color_sfactor;
  1542. mCurrBlendAlphaSFactor = alpha_sfactor;
  1543. mCurrBlendColorDFactor = color_dfactor;
  1544. mCurrBlendAlphaDFactor = alpha_dfactor;
  1545. flush();
  1546. glBlendFuncSeparate(sGLBlendFactor[color_sfactor],
  1547. sGLBlendFactor[color_dfactor],
  1548. sGLBlendFactor[alpha_sfactor],
  1549. sGLBlendFactor[alpha_dfactor]);
  1550. }
  1551. }
  1552. LLTexUnit* LLRender::getTexUnit(U32 index)
  1553. {
  1554. if (index < mTexUnits.size())
  1555. {
  1556. return mTexUnits[index];
  1557. }
  1558. llwarns_sparse << "Non-existing texture unit layer requested: " << index
  1559. << llendl;
  1560. return mDummyTexUnit;
  1561. }
  1562. LLLightState* LLRender::getLight(U32 index)
  1563. {
  1564. if (index < mLightState.size())
  1565. {
  1566. return mLightState[index];
  1567. }
  1568. return NULL;
  1569. }
  1570. void LLRender::setAmbientLightColor(const LLColor4& color)
  1571. {
  1572. if (color != mAmbientLightColor)
  1573. {
  1574. ++mLightHash;
  1575. mAmbientLightColor = color;
  1576. }
  1577. }
  1578. bool LLRender::verifyTexUnitActive(U32 unit_to_verify)
  1579. {
  1580. if (mCurrTextureUnitIndex == unit_to_verify)
  1581. {
  1582. return true;
  1583. }
  1584. llwarns << "TexUnit currently active: " << mCurrTextureUnitIndex
  1585. << " (expecting " << unit_to_verify << ")" << llendl;
  1586. return false;
  1587. }
  1588. void LLRender::begin(U32 mode)
  1589. {
  1590. if (mode != mMode)
  1591. {
  1592. if (mMode == LINES || mMode == POINTS || mMode == TRIANGLES)
  1593. {
  1594. flush();
  1595. }
  1596. else if (mCount)
  1597. {
  1598. llerrs << "gGL.begin() called redundantly." << llendl;
  1599. }
  1600. mMode = mode;
  1601. }
  1602. }
  1603. void LLRender::end(bool force_flush)
  1604. {
  1605. if (force_flush || mCount > 2048 ||
  1606. (mCount && mMode != LINES && mMode != POINTS && mMode != TRIANGLES))
  1607. {
  1608. flush();
  1609. }
  1610. }
  1611. void LLRender::flush()
  1612. {
  1613. LL_TRACY_TIMER(TRC_RENDER_FLUSH);
  1614. if (mCount > 0)
  1615. {
  1616. // Store mCount in a local variable to avoid re-entrance (drawArrays
  1617. // may call flush)
  1618. U32 count = mCount;
  1619. mCount = 0;
  1620. if (mMode == TRIANGLES)
  1621. {
  1622. if (count % 3 != 0)
  1623. {
  1624. count -= count % 3;
  1625. llwarns << "Incomplete triangle render attempt. Skipping."
  1626. << llendl;
  1627. }
  1628. }
  1629. else if (mMode == LINES)
  1630. {
  1631. if (count % 2 != 0)
  1632. {
  1633. count -= count % 2;
  1634. llwarns << "Incomplete line render attempt. Skipping."
  1635. << llendl;
  1636. }
  1637. }
  1638. if (mBuffer)
  1639. {
  1640. LLGLSLShader* shaderp = LLGLSLShader::sCurBoundShaderPtr;
  1641. if ((sUseBufferCache || gUsePBRShaders) && shaderp)
  1642. {
  1643. U32 attribute_mask = shaderp->mAttributeMask;
  1644. U64 digest;
  1645. {
  1646. LL_TRACY_TIMER(TRC_RENDER_FLUSH_HASH);
  1647. HBXXH64 hash((const void*)mVerticesp.get(),
  1648. count * sizeof(LLVector4a), false);
  1649. if (attribute_mask & LLVertexBuffer::MAP_TEXCOORD0)
  1650. {
  1651. hash.update((const void*)mTexcoordsp.get(),
  1652. count * sizeof(LLVector2));
  1653. }
  1654. if (attribute_mask & LLVertexBuffer::MAP_COLOR)
  1655. {
  1656. hash.update((const void*)mColorsp.get(),
  1657. count * sizeof(LLColor4U));
  1658. }
  1659. digest = hash.digest();
  1660. }
  1661. LL_TRACY_TIMER(TRC_RENDER_FLUSH_DRAW);
  1662. LLPointer<LLVertexBuffer> vb;
  1663. auto it = sVBCache.find(digest);
  1664. if (it != sVBCache.end())
  1665. {
  1666. vb = it->second.get();
  1667. }
  1668. else
  1669. {
  1670. vb = new LLVertexBuffer(attribute_mask);
  1671. vb->allocateBuffer(count, 0);
  1672. if (gUsePBRShaders)
  1673. {
  1674. vb->setBuffer();
  1675. }
  1676. vb->setPositionData((LLVector4a*)mVerticesp.get());
  1677. if (attribute_mask & LLVertexBuffer::MAP_TEXCOORD0)
  1678. {
  1679. vb->setTexCoord0Data(mTexcoordsp.get());
  1680. }
  1681. if (attribute_mask & LLVertexBuffer::MAP_COLOR)
  1682. {
  1683. vb->setColorData(mColorsp.get());
  1684. }
  1685. vb->unbind();
  1686. ++mCacheMissCount;
  1687. sVBCache.emplace(digest, vb.get());
  1688. }
  1689. vb->setBuffer(attribute_mask);
  1690. vb->drawArrays(mMode, 0, count);
  1691. }
  1692. else
  1693. {
  1694. LL_TRACY_TIMER(TRC_RENDER_FLUSH_DRAW);
  1695. if (gUsePBRShaders)
  1696. {
  1697. // If we arrived here, then shaderp is NULL, and we cannot
  1698. // use the legacy code to work arount it... This should not
  1699. // happen. HB
  1700. llwarns << "No bound shader !" << llendl;
  1701. llassert(false);
  1702. return;
  1703. }
  1704. if (!mBuffer->isLocked())
  1705. {
  1706. // Hack to only flush the part of the buffer that was
  1707. // updated (relies on stream draw using buffersubdata)
  1708. mBuffer->getVertexStrider(mVerticesp, 0, count);
  1709. mBuffer->getTexCoord0Strider(mTexcoordsp, 0, count);
  1710. mBuffer->getColorStrider(mColorsp, 0, count);
  1711. }
  1712. mBuffer->unmapBuffer();
  1713. mBuffer->setBuffer(immediate_mask);
  1714. mBuffer->drawArrays(mMode, 0, count);
  1715. }
  1716. mVerticesp[0] = mVerticesp[count];
  1717. mTexcoordsp[0] = mTexcoordsp[count];
  1718. mColorsp[0] = mColorsp[count];
  1719. }
  1720. }
  1721. }
  1722. void LLRender::vertex3f(F32 x, F32 y, F32 z)
  1723. {
  1724. LL_TRACY_TIMER(TRC_RENDER_VERTEX);
  1725. // The range of mVerticesp, mColorsp and mTexcoordsp is [0, 4095]
  1726. if (mCount > 2048)
  1727. {
  1728. // Break when buffer gets reasonably full to keep GL command buffers
  1729. // happy and avoid overflow below
  1730. switch (mMode)
  1731. {
  1732. case POINTS:
  1733. flush();
  1734. break;
  1735. case LINES:
  1736. if (mCount % 2 == 0)
  1737. {
  1738. flush();
  1739. }
  1740. break;
  1741. case TRIANGLES:
  1742. if (mCount % 3 == 0)
  1743. {
  1744. flush();
  1745. }
  1746. }
  1747. }
  1748. if (mCount > 4094)
  1749. {
  1750. if (gDebugGL)
  1751. {
  1752. llwarns_sparse << "GL immediate mode overflow. Some geometry not drawn. mMode = "
  1753. << mMode << llendl;
  1754. llassert(false);
  1755. }
  1756. return;
  1757. }
  1758. if (mUIOffset.empty())
  1759. {
  1760. mVerticesp[mCount++].set(x, y, z);
  1761. }
  1762. else
  1763. {
  1764. LLVector3 vert = (LLVector3(x, y, z) +
  1765. mUIOffset.back()).scaledVec(mUIScale.back());
  1766. mVerticesp[mCount++] = vert;
  1767. }
  1768. mVerticesp[mCount] = mVerticesp[mCount - 1];
  1769. mColorsp[mCount] = mColorsp[mCount - 1];
  1770. mTexcoordsp[mCount] = mTexcoordsp[mCount - 1];
  1771. }
  1772. void LLRender::vertexBatchPreTransformed(LLVector3* verts, S32 vert_count)
  1773. {
  1774. LL_TRACY_TIMER(TRC_RENDER_VERTEX_BATCH);
  1775. if (mCount + vert_count > 4094)
  1776. {
  1777. if (gDebugGL)
  1778. {
  1779. llwarns_sparse << "GL immediate mode overflow. Some geometry not drawn."
  1780. << llendl;
  1781. llassert(false);
  1782. }
  1783. return;
  1784. }
  1785. S32 i = 0;
  1786. while (i < vert_count)
  1787. {
  1788. mVerticesp[mCount++] = verts[i++];
  1789. mTexcoordsp[mCount] = mTexcoordsp[mCount - 1];
  1790. mColorsp[mCount] = mColorsp[mCount - 1];
  1791. }
  1792. if (mCount > 0)
  1793. {
  1794. mVerticesp[mCount] = mVerticesp[mCount - 1];
  1795. }
  1796. }
  1797. void LLRender::vertexBatchPreTransformed(LLVector3* verts, LLVector2* uvs,
  1798. S32 vert_count)
  1799. {
  1800. LL_TRACY_TIMER(TRC_RENDER_VERTEX_BATCH);
  1801. if (mCount + vert_count > 4094)
  1802. {
  1803. if (gDebugGL)
  1804. {
  1805. llwarns_sparse << "GL immediate mode overflow. Some geometry not drawn."
  1806. << llendl;
  1807. llassert(false);
  1808. }
  1809. return;
  1810. }
  1811. S32 i = 0;
  1812. while (i < vert_count)
  1813. {
  1814. mVerticesp[mCount] = verts[i];
  1815. mTexcoordsp[mCount++] = uvs[i++];
  1816. mColorsp[mCount] = mColorsp[mCount - 1];
  1817. }
  1818. if (mCount > 0)
  1819. {
  1820. mVerticesp[mCount] = mVerticesp[mCount - 1];
  1821. mTexcoordsp[mCount] = mTexcoordsp[mCount - 1];
  1822. }
  1823. }
  1824. void LLRender::vertexBatchPreTransformed(LLVector3* verts, LLVector2* uvs,
  1825. LLColor4U* colors, S32 vert_count)
  1826. {
  1827. LL_TRACY_TIMER(TRC_RENDER_VERTEX_BATCH);
  1828. if (mCount + vert_count > 4094)
  1829. {
  1830. if (gDebugGL)
  1831. {
  1832. llwarns_sparse << "GL immediate mode overflow. Some geometry not drawn."
  1833. << llendl;
  1834. llassert(false);
  1835. }
  1836. return;
  1837. }
  1838. S32 i = 0;
  1839. while (i < vert_count)
  1840. {
  1841. mVerticesp[mCount] = verts[i];
  1842. mTexcoordsp[mCount] = uvs[i];
  1843. mColorsp[mCount++] = colors[i++];
  1844. }
  1845. if (mCount > 0)
  1846. {
  1847. mVerticesp[mCount] = mVerticesp[mCount - 1];
  1848. mTexcoordsp[mCount] = mTexcoordsp[mCount - 1];
  1849. mColorsp[mCount] = mColorsp[mCount - 1];
  1850. }
  1851. }
  1852. void LLRender::color4ub(U8 r, U8 g, U8 b, U8 a)
  1853. {
  1854. if (!LLGLSLShader::sCurBoundShaderPtr ||
  1855. (LLGLSLShader::sCurBoundShaderPtr->mAttributeMask &
  1856. LLVertexBuffer::MAP_COLOR))
  1857. {
  1858. mColorsp[mCount] = LLColor4U(r, g, b, a);
  1859. }
  1860. else
  1861. {
  1862. // Not using shaders or shader reads color from a uniform
  1863. diffuseColor4ub(r, g, b, a);
  1864. }
  1865. }
  1866. void LLRender::diffuseColor3f(F32 r, F32 g, F32 b)
  1867. {
  1868. LLGLSLShader* shader = LLGLSLShader::sCurBoundShaderPtr;
  1869. llassert(shader != NULL);
  1870. if (shader)
  1871. {
  1872. shader->uniform4f(LLShaderMgr::DIFFUSE_COLOR, r, g, b, 1.f);
  1873. }
  1874. }
  1875. void LLRender::diffuseColor3fv(const F32* c)
  1876. {
  1877. LLGLSLShader* shader = LLGLSLShader::sCurBoundShaderPtr;
  1878. llassert(shader != NULL);
  1879. if (shader)
  1880. {
  1881. shader->uniform4f(LLShaderMgr::DIFFUSE_COLOR, c[0], c[1], c[2], 1.f);
  1882. }
  1883. }
  1884. void LLRender::diffuseColor4f(F32 r, F32 g, F32 b, F32 a)
  1885. {
  1886. LLGLSLShader* shader = LLGLSLShader::sCurBoundShaderPtr;
  1887. llassert(shader != NULL);
  1888. if (shader)
  1889. {
  1890. shader->uniform4f(LLShaderMgr::DIFFUSE_COLOR, r, g, b, a);
  1891. }
  1892. }
  1893. void LLRender::diffuseColor4fv(const F32* c)
  1894. {
  1895. LLGLSLShader* shader = LLGLSLShader::sCurBoundShaderPtr;
  1896. llassert(shader != NULL);
  1897. if (shader)
  1898. {
  1899. shader->uniform4fv(LLShaderMgr::DIFFUSE_COLOR, 1, c);
  1900. }
  1901. }
  1902. void LLRender::diffuseColor4ubv(const U8* c)
  1903. {
  1904. LLGLSLShader* shader = LLGLSLShader::sCurBoundShaderPtr;
  1905. llassert(shader != NULL);
  1906. if (shader)
  1907. {
  1908. shader->uniform4f(LLShaderMgr::DIFFUSE_COLOR, c[0] / 255.f,
  1909. c[1] / 255.f, c[2] / 255.f, c[3] / 255.f);
  1910. }
  1911. }
  1912. void LLRender::diffuseColor4ub(U8 r, U8 g, U8 b, U8 a)
  1913. {
  1914. LLGLSLShader* shader = LLGLSLShader::sCurBoundShaderPtr;
  1915. llassert(shader != NULL);
  1916. if (shader)
  1917. {
  1918. shader->uniform4f(LLShaderMgr::DIFFUSE_COLOR,
  1919. r / 255.f, g / 255.f, b / 255.f, a / 255.f);
  1920. }
  1921. }
  1922. void LLRender::lineWidth(F32 width)
  1923. {
  1924. if (sGLCoreProfile)
  1925. {
  1926. // Always 1.f (or less, but we never use less) under core GL profile !
  1927. // So, this call is actually a no-operation...
  1928. return;
  1929. }
  1930. glLineWidth(width);
  1931. }
  1932. void LLRender::debugTexUnits()
  1933. {
  1934. llinfos << "Active TexUnit: " << mCurrTextureUnitIndex << llendl;
  1935. std::string active_enabled = "false";
  1936. for (U32 i = 0; i < mTexUnits.size(); ++i)
  1937. {
  1938. LLTexUnit* unit = getTexUnit(i);
  1939. if (unit->mCurrTexType != LLTexUnit::TT_NONE)
  1940. {
  1941. if (i == mCurrTextureUnitIndex)
  1942. {
  1943. active_enabled = "true";
  1944. }
  1945. llinfos << "TexUnit " << i << " enabled as: ";
  1946. switch (unit->mCurrTexType)
  1947. {
  1948. case LLTexUnit::TT_TEXTURE:
  1949. LL_CONT << "2D texture";
  1950. break;
  1951. case LLTexUnit::TT_RECT_TEXTURE:
  1952. LL_CONT << "texture rectangle";
  1953. break;
  1954. case LLTexUnit::TT_CUBE_MAP:
  1955. LL_CONT << "cube map";
  1956. break;
  1957. case LLTexUnit::TT_CUBE_MAP_ARRAY:
  1958. LL_CONT << "cube map array";
  1959. break;
  1960. default:
  1961. LL_CONT << "ARGH !!! NONE !";
  1962. }
  1963. LL_CONT << ", with bound texture: " << unit->mCurrTexture
  1964. << llendl;
  1965. }
  1966. }
  1967. llinfos << "Active TexUnit enabled: " << active_enabled << llendl;
  1968. }
  1969. void LLRender::cleanupVertexBufferCache(U32 current_frame)
  1970. {
  1971. LL_TRACY_TIMER(TRC_RENDER_VB_CACHE_CLEANUP);
  1972. sCurrentFrame = current_frame;
  1973. // Cleanup when enough misses occurred
  1974. constexpr U32 MISS_COUNT_LIMIT = 1024;
  1975. U32 erased = 0;
  1976. if (mCacheMissCount > MISS_COUNT_LIMIT)
  1977. {
  1978. for (auto it = sVBCache.begin(); it != sVBCache.end(); )
  1979. {
  1980. if (it->second.expired())
  1981. {
  1982. it = sVBCache.erase(it);
  1983. ++erased;
  1984. }
  1985. else
  1986. {
  1987. ++it;
  1988. }
  1989. }
  1990. LL_DEBUGS("VertexBuffer") << "Erased " << erased
  1991. << " expired cached buffers. "
  1992. << sVBCache.size() << " buffers in cache."
  1993. << LL_ENDL;
  1994. mCacheMissCount = 0;
  1995. }
  1996. LLVertexBuffer::cleanupVBOPool();
  1997. }
  1998. LLMatrix4a gl_gen_rot(F32 a, const LLVector4a& axis)
  1999. {
  2000. F32 r = a * DEG_TO_RAD;
  2001. F32 c = cosf(r);
  2002. F32 s = sinf(r);
  2003. F32 ic = 1.f - c;
  2004. const LLVector4a add1(c, axis[VZ] * s, -axis[VY] * s); // 1,z,-y
  2005. const LLVector4a add2(-axis[VZ] * s, c, axis[VX] * s); // -z,1,x
  2006. const LLVector4a add3(axis[VY] * s, -axis[VX] * s, c); // y,-x,1
  2007. LLVector4a axis_x;
  2008. axis_x.splat<0>(axis);
  2009. LLVector4a axis_y;
  2010. axis_y.splat<1>(axis);
  2011. LLVector4a axis_z;
  2012. axis_z.splat<2>(axis);
  2013. LLVector4a c_axis;
  2014. c_axis.setMul(axis, ic);
  2015. LLMatrix4a rot_mat;
  2016. rot_mat.getRow<0>().setMul(c_axis, axis_x);
  2017. rot_mat.getRow<0>().add(add1);
  2018. rot_mat.getRow<1>().setMul(c_axis, axis_y);
  2019. rot_mat.getRow<1>().add(add2);
  2020. rot_mat.getRow<2>().setMul(c_axis, axis_z);
  2021. rot_mat.getRow<2>().add(add3);
  2022. rot_mat.setRow<3>(LLVector4a(0.f, 0.f, 0.f, 1.f));
  2023. return rot_mat;
  2024. }
  2025. LLMatrix4a gl_ortho(F32 left, F32 right, F32 bottom, F32 top, F32 z_near,
  2026. F32 z_far)
  2027. {
  2028. LLMatrix4a ret;
  2029. ret.setRow<0>(LLVector4a(2.f / (right - left), 0.f, 0.f));
  2030. ret.setRow<1>(LLVector4a(0.f, 2.f / (top - bottom), 0.f));
  2031. ret.setRow<2>(LLVector4a(0.f, 0.f, -2.f / (z_far - z_near)));
  2032. ret.setRow<3>(LLVector4a((left + right) / (left - right),
  2033. (bottom + top) / (bottom - top),
  2034. (z_near + z_far) / (z_near - z_far), 1.f));
  2035. return ret;
  2036. }
  2037. LLMatrix4a gl_perspective(F32 fovy, F32 aspect, F32 z_near, F32 z_far)
  2038. {
  2039. constexpr F32 factor = DEG_TO_RAD * 0.5f;
  2040. F32 f = 1.f / tanf(factor * fovy);
  2041. LLMatrix4a ret;
  2042. ret.setRow<0>(LLVector4a(f / aspect, 0.f, 0.f));
  2043. ret.setRow<1>(LLVector4a(0.f, f, 0.f));
  2044. ret.setRow<2>(LLVector4a(0.f, 0.f, (z_far + z_near) / (z_near - z_far),
  2045. -1.f));
  2046. ret.setRow<3>(LLVector4a(0.f, 0.f,
  2047. (2.f * z_far * z_near) / (z_near - z_far), 0.f));
  2048. return ret;
  2049. }