gfxGLShader.cpp 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "gfx/gl/gfxGLShader.h"
  24. #include "gfx/gl/gfxGLVertexAttribLocation.h"
  25. #include "gfx/gl/gfxGLDevice.h"
  26. #include "core/frameAllocator.h"
  27. #include "core/stream/fileStream.h"
  28. #include "core/strings/stringFunctions.h"
  29. #include "math/mPoint2.h"
  30. #include "gfx/gfxStructs.h"
  31. #include "console/console.h"
  32. #define CHECK_AARG(pos, name) static StringTableEntry attr_##name = StringTable->insert(#name); if (argName == attr_##name) { glBindAttribLocation(mProgram, pos, attr_##name); continue; }
  33. GFXGLShaderConstHandle::GFXGLShaderConstHandle(GFXGLShader* shader)
  34. : mShader(shader),
  35. mUBOUniform(false),
  36. mInstancingConstant(false)
  37. {
  38. dMemset(&mDesc, 0, sizeof(mDesc));
  39. mValid = false;
  40. }
  41. GFXGLShaderConstHandle::GFXGLShaderConstHandle(GFXGLShader* shader,
  42. const GFXShaderConstDesc& desc)
  43. : mShader(shader),
  44. mDesc(desc),
  45. mUBOUniform(false),
  46. mInstancingConstant(false)
  47. {
  48. if (desc.constType == GFXSCT_ConstBuffer)
  49. mValid = false;
  50. else
  51. mValid = true;
  52. }
  53. void GFXGLShaderConstHandle::reinit(const GFXShaderConstDesc& desc)
  54. {
  55. mDesc = desc;
  56. mValid = true;
  57. }
  58. GFXGLShaderConstHandle::~GFXGLShaderConstHandle()
  59. {
  60. }
  61. const GFXShaderConstDesc GFXGLShaderConstHandle::getDesc()
  62. {
  63. return mDesc;
  64. }
  65. static U32 shaderConstTypeSize(GFXShaderConstType type)
  66. {
  67. switch (type)
  68. {
  69. case GFXSCT_Float:
  70. case GFXSCT_Int:
  71. case GFXSCT_UInt:
  72. case GFXSCT_Bool:
  73. case GFXSCT_Sampler:
  74. case GFXSCT_SamplerCube:
  75. case GFXSCT_SamplerCubeArray:
  76. case GFXSCT_SamplerTextureArray:
  77. return 4;
  78. case GFXSCT_Float2:
  79. case GFXSCT_Int2:
  80. case GFXSCT_UInt2:
  81. case GFXSCT_Bool2:
  82. return 8;
  83. case GFXSCT_Float3:
  84. case GFXSCT_Int3:
  85. case GFXSCT_UInt3:
  86. case GFXSCT_Bool3:
  87. return 12;
  88. case GFXSCT_Float4:
  89. case GFXSCT_Int4:
  90. case GFXSCT_UInt4:
  91. case GFXSCT_Bool4:
  92. return 16;
  93. case GFXSCT_Float2x2:
  94. return 16;
  95. case GFXSCT_Float3x3:
  96. return 36;
  97. case GFXSCT_Float4x3:
  98. return 48;
  99. case GFXSCT_Float4x4:
  100. return 64;
  101. default:
  102. AssertFatal(false, "shaderConstTypeSize - Unrecognized constant type");
  103. return 0;
  104. }
  105. }
  106. GFXGLShaderConstBuffer::GFXGLShaderConstBuffer(GFXGLShader* shader)
  107. {
  108. mShader = shader;
  109. mWasLost = true;
  110. }
  111. GFXGLShaderConstBuffer::~GFXGLShaderConstBuffer()
  112. {
  113. if (mShader)
  114. mShader->_unlinkBuffer(this);
  115. }
  116. template<typename ConstType>
  117. void GFXGLShaderConstBuffer::internalSet(GFXShaderConstHandle* handle, const ConstType& param)
  118. {
  119. AssertFatal(handle, "GFXGLShaderConstBuffer::internalSet - Handle is NULL!");
  120. AssertFatal(handle->isValid(), "GFXGLShaderConstBuffer::internalSet - Handle is not valid!");
  121. AssertFatal(dynamic_cast<GFXGLShaderConstHandle*>(handle), "GFXGLShaderConstBuffer::set - Incorrect const buffer type");
  122. GFXGLShaderConstHandle* _glHandle = static_cast<GFXGLShaderConstHandle*>(handle);
  123. AssertFatal(mShader == _glHandle->mShader, "GFXGLShaderConstBuffer::set - Should only set handles which are owned by our shader");
  124. U8* basePointer;
  125. if (!_glHandle->mUBOUniform)
  126. {
  127. basePointer = mBufferMap[-1].data;
  128. }
  129. else
  130. {
  131. basePointer = mBufferMap[_glHandle->mDesc.bindPoint].data;
  132. }
  133. U8* buf = basePointer + _glHandle->mDesc.offset;
  134. if (_glHandle->mInstancingConstant)
  135. buf = mInstPtr + _glHandle->mDesc.offset;
  136. dMemcpy(buf, &param, sizeof(ConstType));
  137. }
  138. GFXShader* GFXGLShaderConstBuffer::getShader()
  139. {
  140. return mShader;
  141. }
  142. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const F32 fv)
  143. {
  144. internalSet(handle, fv);
  145. }
  146. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const Point2F& fv)
  147. {
  148. internalSet(handle, fv);
  149. }
  150. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const Point3F& fv)
  151. {
  152. internalSet(handle, fv);
  153. }
  154. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const Point4F& fv)
  155. {
  156. internalSet(handle, fv);
  157. }
  158. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const PlaneF& fv)
  159. {
  160. internalSet(handle, fv);
  161. }
  162. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const LinearColorF& fv)
  163. {
  164. internalSet(handle, fv);
  165. }
  166. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const S32 fv)
  167. {
  168. internalSet(handle, fv);
  169. }
  170. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const Point2I& fv)
  171. {
  172. internalSet(handle, fv);
  173. }
  174. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const Point3I& fv)
  175. {
  176. internalSet(handle, fv);
  177. }
  178. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const Point4I& fv)
  179. {
  180. internalSet(handle, fv);
  181. }
  182. template<typename ConstType>
  183. void GFXGLShaderConstBuffer::internalSet(GFXShaderConstHandle* handle, const AlignedArray<ConstType>& fv)
  184. {
  185. AssertFatal(handle, "GFXGLShaderConstBuffer::internalSet - Handle is NULL!");
  186. AssertFatal(handle->isValid(), "GFXGLShaderConstBuffer::internalSet - Handle is not valid!");
  187. AssertFatal(dynamic_cast<GFXGLShaderConstHandle*>(handle), "GFXGLShaderConstBuffer::set - Incorrect const buffer type");
  188. GFXGLShaderConstHandle* _glHandle = static_cast<GFXGLShaderConstHandle*>(handle);
  189. AssertFatal(mShader == _glHandle->mShader, "GFXGLShaderConstBuffer::set - Should only set handles which are owned by our shader");
  190. AssertFatal(!_glHandle->mInstancingConstant, "GFXGLShaderConstBuffer::set - Instancing not supported for array");
  191. U8* basePointer;
  192. if (!_glHandle->mUBOUniform)
  193. {
  194. basePointer = mBufferMap[-1].data;
  195. }
  196. else
  197. {
  198. basePointer = mBufferMap[_glHandle->mDesc.bindPoint].data;
  199. }
  200. const U8* fvBuffer = static_cast<const U8*>(fv.getBuffer());
  201. for (U32 i = 0; i < fv.size(); ++i)
  202. {
  203. dMemcpy(basePointer + _glHandle->mDesc.offset + i * sizeof(ConstType), fvBuffer, sizeof(ConstType));
  204. fvBuffer += fv.getElementSize();
  205. }
  206. }
  207. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray<F32>& fv)
  208. {
  209. internalSet(handle, fv);
  210. }
  211. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray<Point2F>& fv)
  212. {
  213. internalSet(handle, fv);
  214. }
  215. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray<Point3F>& fv)
  216. {
  217. internalSet(handle, fv);
  218. }
  219. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray<Point4F>& fv)
  220. {
  221. internalSet(handle, fv);
  222. }
  223. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray<S32>& fv)
  224. {
  225. internalSet(handle, fv);
  226. }
  227. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray<Point2I>& fv)
  228. {
  229. internalSet(handle, fv);
  230. }
  231. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray<Point3I>& fv)
  232. {
  233. internalSet(handle, fv);
  234. }
  235. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray<Point4I>& fv)
  236. {
  237. internalSet(handle, fv);
  238. }
  239. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const MatrixF& mat, const GFXShaderConstType matType)
  240. {
  241. AssertFatal(handle, "GFXGLShaderConstBuffer::set - Handle is NULL!");
  242. AssertFatal(handle->isValid(), "GFXGLShaderConstBuffer::set - Handle is not valid!");
  243. AssertFatal(dynamic_cast<GFXGLShaderConstHandle*>(handle), "GFXGLShaderConstBuffer::set - Incorrect const buffer type");
  244. GFXGLShaderConstHandle* _glHandle = static_cast<GFXGLShaderConstHandle*>(handle);
  245. AssertFatal(mShader == _glHandle->mShader, "GFXGLShaderConstBuffer::set - Should only set handles which are owned by our shader");
  246. AssertFatal(!_glHandle->mInstancingConstant || matType == GFXSCT_Float4x4, "GFXGLShaderConstBuffer::set - Only support GFXSCT_Float4x4 for instancing");
  247. U8* basePointer;
  248. if (!_glHandle->mUBOUniform)
  249. {
  250. basePointer = mBufferMap[-1].data;
  251. }
  252. else
  253. {
  254. basePointer = mBufferMap[_glHandle->mDesc.bindPoint].data;
  255. }
  256. switch (matType)
  257. {
  258. case GFXSCT_Float2x2:
  259. reinterpret_cast<F32*>(basePointer + _glHandle->mDesc.offset)[0] = mat[0];
  260. reinterpret_cast<F32*>(basePointer + _glHandle->mDesc.offset)[1] = mat[1];
  261. reinterpret_cast<F32*>(basePointer + _glHandle->mDesc.offset)[2] = mat[4];
  262. reinterpret_cast<F32*>(basePointer + _glHandle->mDesc.offset)[3] = mat[5];
  263. break;
  264. case GFXSCT_Float3x3:
  265. reinterpret_cast<F32*>(basePointer + _glHandle->mDesc.offset)[0] = mat[0];
  266. reinterpret_cast<F32*>(basePointer + _glHandle->mDesc.offset)[1] = mat[1];
  267. reinterpret_cast<F32*>(basePointer + _glHandle->mDesc.offset)[2] = mat[2];
  268. reinterpret_cast<F32*>(basePointer + _glHandle->mDesc.offset)[3] = mat[4];
  269. reinterpret_cast<F32*>(basePointer + _glHandle->mDesc.offset)[4] = mat[5];
  270. reinterpret_cast<F32*>(basePointer + _glHandle->mDesc.offset)[5] = mat[6];
  271. reinterpret_cast<F32*>(basePointer + _glHandle->mDesc.offset)[6] = mat[8];
  272. reinterpret_cast<F32*>(basePointer + _glHandle->mDesc.offset)[7] = mat[9];
  273. reinterpret_cast<F32*>(basePointer + _glHandle->mDesc.offset)[8] = mat[10];
  274. break;
  275. case GFXSCT_Float4x3:
  276. dMemcpy(basePointer + _glHandle->mDesc.offset, (const F32*)mat, (sizeof(F32) * 12));// matrix with end row chopped off
  277. break;
  278. case GFXSCT_Float4x4:
  279. {
  280. if (_glHandle->mInstancingConstant)
  281. {
  282. MatrixF transposed;
  283. mat.transposeTo(transposed);
  284. dMemcpy(mInstPtr + _glHandle->mDesc.offset, (const F32*)transposed, sizeof(MatrixF));
  285. return;
  286. }
  287. dMemcpy(basePointer + _glHandle->mDesc.offset, (const F32*)mat, sizeof(MatrixF));
  288. break;
  289. }
  290. default:
  291. AssertFatal(false, "GFXGLShaderConstBuffer::set - Invalid matrix type");
  292. break;
  293. }
  294. }
  295. void GFXGLShaderConstBuffer::set(GFXShaderConstHandle* handle, const MatrixF* mat, const U32 arraySize, const GFXShaderConstType matrixType)
  296. {
  297. AssertFatal(handle, "GFXGLShaderConstBuffer::set - Handle is NULL!");
  298. AssertFatal(handle->isValid(), "GFXGLShaderConstBuffer::set - Handle is not valid!");
  299. GFXGLShaderConstHandle* _glHandle = static_cast<GFXGLShaderConstHandle*>(handle);
  300. AssertFatal(mShader == _glHandle->mShader, "GFXGLShaderConstBuffer::set - Should only set handles which are owned by our shader");
  301. AssertFatal(!_glHandle->mInstancingConstant, "GFXGLShaderConstBuffer::set - Instancing not supported for matrix arrays");
  302. U8* basePointer;
  303. if (!_glHandle->mUBOUniform)
  304. {
  305. basePointer = mBufferMap[-1].data;
  306. }
  307. else
  308. {
  309. basePointer = mBufferMap[_glHandle->mDesc.bindPoint].data;
  310. }
  311. switch (matrixType) {
  312. case GFXSCT_Float4x3:
  313. // Copy each item with the last row chopped off
  314. for (int i = 0; i < arraySize; i++)
  315. {
  316. dMemcpy(basePointer + _glHandle->mDesc.offset + (i * (sizeof(F32) * 12)), (F32*)(mat + i), sizeof(F32) * 12);
  317. }
  318. break;
  319. case GFXSCT_Float4x4:
  320. dMemcpy(basePointer + _glHandle->mDesc.offset, (F32*)mat, _glHandle->getSize());
  321. break;
  322. default:
  323. AssertFatal(false, "GFXGLShaderConstBuffer::set - setting array of non 4x4 matrices!");
  324. break;
  325. }
  326. }
  327. void GFXGLShaderConstBuffer::activate(GFXGLShaderConstBuffer* prevShaderBuffer)
  328. {
  329. PROFILE_SCOPE(GFXGLShaderConstBuffer_activate);
  330. for (BufferMap::Iterator i = mBufferMap.begin(); i != mBufferMap.end(); ++i)
  331. {
  332. const S32 thisBufferDesc = i->key;
  333. // set the global buffer differently
  334. if (thisBufferDesc == -1)
  335. {
  336. mShader->setConstantsFromBuffer(mBufferMap[-1].data);
  337. continue;
  338. }
  339. ConstantBuffer thisBuff = i->value;
  340. if (prevShaderBuffer && prevShaderBuffer != this)
  341. {
  342. const ConstantBuffer prevBuffer = prevShaderBuffer->mBufferMap[i->key];
  343. if (prevBuffer.data && !prevBuffer.isDirty)
  344. {
  345. if (prevBuffer.size != thisBuff.size)
  346. {
  347. thisBuff.isDirty = true;
  348. }
  349. else
  350. {
  351. if (dMemcmp(prevBuffer.data, thisBuff.data, thisBuff.size) != 0)
  352. {
  353. thisBuff.isDirty = true;
  354. }
  355. else
  356. {
  357. thisBuff.isDirty = false;
  358. }
  359. }
  360. }
  361. else
  362. {
  363. thisBuff.isDirty = true;
  364. }
  365. }
  366. else
  367. {
  368. thisBuff.isDirty = true;
  369. }
  370. if (thisBuff.data && thisBuff.isDirty)
  371. {
  372. glBindBuffer(GL_UNIFORM_BUFFER, thisBuff.bufHandle);
  373. glBufferData(GL_UNIFORM_BUFFER, thisBuff.size, thisBuff.data, GL_DYNAMIC_DRAW);
  374. glBindBufferBase(GL_UNIFORM_BUFFER, thisBufferDesc, thisBuff.bufHandle);
  375. }
  376. }
  377. mWasLost = false;
  378. }
  379. void GFXGLShaderConstBuffer::addBuffer(const GFXShaderConstDesc desc)
  380. {
  381. // if this is the global buffer set it to the highest.
  382. if (desc.bindPoint == -1)
  383. {
  384. // we dont create a bufferhandle for this one.
  385. U8* buf = new U8[desc.size];
  386. dMemset(buf, 0, desc.size);
  387. mBufferMap[-1].data = buf;
  388. mBufferMap[-1].size = desc.size;
  389. mBufferMap[-1].isDirty = true;
  390. }
  391. else
  392. {
  393. U8* buf = new U8[desc.size];
  394. dMemset(buf, 0, desc.size);
  395. mBufferMap[desc.bindPoint].data = buf;
  396. mBufferMap[desc.bindPoint].size = desc.size;
  397. mBufferMap[desc.bindPoint].isDirty = true;
  398. mBufferMap[desc.bindPoint].bufHandle = GFXGL->getDeviceBuffer(desc);
  399. }
  400. }
  401. const String GFXGLShaderConstBuffer::describeSelf() const
  402. {
  403. return String();
  404. }
  405. void GFXGLShaderConstBuffer::onShaderReload(GFXGLShader* shader)
  406. {
  407. AssertFatal(shader == mShader, "GFXGLShaderConstBuffer::onShaderReload, mismatched shaders!");
  408. for (auto& pair : mBufferMap) {
  409. delete[] pair.value.data;
  410. }
  411. mBufferMap.clear(); // Clear the map
  412. for (GFXGLShader::BufferMap::Iterator i = shader->mBuffers.begin(); i != shader->mBuffers.end(); ++i)
  413. {
  414. // add our buffer descriptions to the full const buffer.
  415. this->addBuffer(i->value);
  416. }
  417. mWasLost = true;
  418. }
  419. GFXGLShader::GFXGLShader(GFXGLDevice* device) :
  420. mVertexShader(0),
  421. mPixelShader(0),
  422. mGeometryShader(0),
  423. mProgram(0),
  424. mDevice(device),
  425. mGlobalConstBuffer(NULL)
  426. {
  427. }
  428. GFXGLShader::~GFXGLShader()
  429. {
  430. clearShaders();
  431. for (auto& pair : mHandles) {
  432. if (pair.value != nullptr) {
  433. delete pair.value;
  434. pair.value = nullptr;
  435. }
  436. }
  437. mHandles.clear();
  438. if (mGlobalConstBuffer)
  439. delete[] mGlobalConstBuffer;
  440. }
  441. void GFXGLShader::clearShaders()
  442. {
  443. glDeleteProgram(mProgram);
  444. glDeleteShader(mVertexShader);
  445. glDeleteShader(mPixelShader);
  446. glDeleteShader(mGeometryShader);
  447. mProgram = 0;
  448. mVertexShader = 0;
  449. mPixelShader = 0;
  450. mGeometryShader = 0;
  451. }
  452. bool GFXGLShader::_init()
  453. {
  454. PROFILE_SCOPE(GFXGLShader_Init);
  455. // Don't initialize empty shaders.
  456. if (mVertexFile.isEmpty() && mPixelFile.isEmpty())
  457. return false;
  458. clearShaders();
  459. mProgram = glCreateProgram();
  460. // Set the macros and add the global ones.
  461. Vector<GFXShaderMacro> macros;
  462. macros.merge(mMacros);
  463. macros.merge(smGlobalMacros);
  464. macros.increment();
  465. macros.last().name = "TORQUE_SM";
  466. macros.last().value = 40;
  467. macros.increment();
  468. macros.last().name = "TORQUE_VERTEX_SHADER";
  469. macros.last().value = "";
  470. // Default to true so we're "successful" if a vertex/pixel shader wasn't specified.
  471. bool compiledVertexShader = true;
  472. bool compiledPixelShader = true;
  473. bool compiledGeometryShader = true;
  474. // Compile the vertex and pixel shaders if specified.
  475. if (!mVertexFile.isEmpty())
  476. {
  477. compiledVertexShader = initShader(mVertexFile, GFXShaderStage::VERTEX_SHADER, macros);
  478. if (!compiledVertexShader)
  479. return false;
  480. }
  481. if (!mPixelFile.isEmpty())
  482. {
  483. macros.last().name = "TORQUE_PIXEL_SHADER";
  484. compiledPixelShader = initShader(mPixelFile, GFXShaderStage::PIXEL_SHADER, macros);
  485. if (!compiledPixelShader)
  486. return false;
  487. }
  488. if (!mGeometryFile.isEmpty())
  489. {
  490. macros.last().name = "TORQUE_GEOMETRY_SHADER";
  491. compiledGeometryShader = initShader(mGeometryFile, GFXShaderStage::GEOMETRY_SHADER, macros);
  492. if (!compiledGeometryShader)
  493. return false;
  494. }
  495. // Link it!
  496. glLinkProgram(mProgram);
  497. GLint activeAttribs = 0;
  498. glGetProgramiv(mProgram, GL_ACTIVE_ATTRIBUTES, &activeAttribs);
  499. GLint maxLength;
  500. glGetProgramiv(mProgram, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &maxLength);
  501. FrameTemp<GLchar> tempData(maxLength + 1);
  502. *tempData.address() = '\0';
  503. // Check atributes
  504. for (U32 i = 0; i < activeAttribs; i++)
  505. {
  506. GLint size;
  507. GLenum type;
  508. glGetActiveAttrib(mProgram, i, maxLength + 1, NULL, &size, &type, tempData.address());
  509. StringTableEntry argName = StringTable->insert(tempData.address());
  510. CHECK_AARG(Torque::GL_VertexAttrib_Position, vPosition);
  511. CHECK_AARG(Torque::GL_VertexAttrib_Normal, vNormal);
  512. CHECK_AARG(Torque::GL_VertexAttrib_Color, vColor);
  513. CHECK_AARG(Torque::GL_VertexAttrib_Tangent, vTangent);
  514. CHECK_AARG(Torque::GL_VertexAttrib_TangentW, vTangentW);
  515. CHECK_AARG(Torque::GL_VertexAttrib_Binormal, vBinormal);
  516. CHECK_AARG(Torque::GL_VertexAttrib_TexCoord0, vTexCoord0);
  517. CHECK_AARG(Torque::GL_VertexAttrib_TexCoord1, vTexCoord1);
  518. CHECK_AARG(Torque::GL_VertexAttrib_TexCoord2, vTexCoord2);
  519. CHECK_AARG(Torque::GL_VertexAttrib_TexCoord3, vTexCoord3);
  520. CHECK_AARG(Torque::GL_VertexAttrib_TexCoord4, vTexCoord4);
  521. CHECK_AARG(Torque::GL_VertexAttrib_TexCoord5, vTexCoord5);
  522. CHECK_AARG(Torque::GL_VertexAttrib_TexCoord6, vTexCoord6);
  523. CHECK_AARG(Torque::GL_VertexAttrib_TexCoord7, vTexCoord7);
  524. CHECK_AARG(Torque::GL_VertexAttrib_TexCoord8, vTexCoord8);
  525. CHECK_AARG(Torque::GL_VertexAttrib_TexCoord9, vTexCoord9);
  526. }
  527. //always have OUT_col
  528. glBindFragDataLocation(mProgram, 0, "OUT_col");
  529. // Check OUT_colN
  530. for (U32 i = 1; i < 4; i++)
  531. {
  532. char buffer[10];
  533. dSprintf(buffer, sizeof(buffer), "OUT_col%u", i);
  534. GLint location = glGetFragDataLocation(mProgram, buffer);
  535. if (location > 0)
  536. glBindFragDataLocation(mProgram, i, buffer);
  537. }
  538. // Link it again!
  539. glLinkProgram(mProgram);
  540. GLint linkStatus;
  541. glGetProgramiv(mProgram, GL_LINK_STATUS, &linkStatus);
  542. // Dump the info log to the console
  543. U32 logLength = 0;
  544. glGetProgramiv(mProgram, GL_INFO_LOG_LENGTH, (GLint*)&logLength);
  545. if (logLength)
  546. {
  547. FrameAllocatorMarker fam;
  548. char* log = (char*)fam.alloc(logLength);
  549. glGetProgramInfoLog(mProgram, logLength, NULL, log);
  550. if (linkStatus == GL_FALSE)
  551. {
  552. if (smLogErrors)
  553. {
  554. Con::errorf("GFXGLShader::init - Error linking shader!");
  555. Con::errorf("Program %s / %s: %s",
  556. mVertexFile.getFullPath().c_str(), mPixelFile.getFullPath().c_str(), log);
  557. }
  558. }
  559. else if (smLogWarnings)
  560. {
  561. Con::warnf("Program %s / %s: %s",
  562. mVertexFile.getFullPath().c_str(), mPixelFile.getFullPath().c_str(), log);
  563. }
  564. }
  565. // If we failed to link, bail.
  566. if (linkStatus == GL_FALSE)
  567. return false;
  568. initConstantDescs();
  569. initHandles();
  570. // Notify Buffers we might have changed in size.
  571. // If this was our first init then we won't have any activeBuffers
  572. // to worry about unnecessarily calling.
  573. Vector<GFXShaderConstBuffer*>::iterator biter = mActiveBuffers.begin();
  574. for (; biter != mActiveBuffers.end(); biter++)
  575. ((GFXGLShaderConstBuffer*)(*biter))->onShaderReload(this);
  576. return true;
  577. }
  578. void GFXGLShader::initConstantDescs()
  579. {
  580. // clear our vectors.
  581. mShaderConsts.clear();
  582. GLint maxNameLength;
  583. glGetProgramiv(mProgram, GL_ACTIVE_UNIFORM_MAX_LENGTH, &maxNameLength);
  584. if (!maxNameLength)
  585. return;
  586. maxNameLength++;
  587. FrameTemp<GLchar> uniformName(maxNameLength);
  588. // parse ubos first and add them to our table, same as in dx
  589. // this is required so that in the other uniform loop we dont add
  590. // a uniform that exists in a ubo again.
  591. GLint numUBOS;
  592. glGetProgramiv(mProgram, GL_ACTIVE_UNIFORM_BLOCKS, &numUBOS);
  593. for (U32 i = 0; i < numUBOS; i++) {
  594. GFXShaderConstDesc desc;
  595. GLint uboNameLen;
  596. glGetActiveUniformBlockiv(mProgram, i, GL_UNIFORM_BLOCK_NAME_LENGTH, &uboNameLen);
  597. if (!uboNameLen)
  598. return;
  599. uboNameLen++;
  600. // get the name of the ubo for getting required data.
  601. FrameTemp<GLchar> uboName(uboNameLen);
  602. glGetActiveUniformBlockName(mProgram, i, uboNameLen, NULL, uboName);
  603. GLint uboBinding;
  604. glGetActiveUniformBlockiv(mProgram, i, GL_UNIFORM_BLOCK_BINDING, &uboBinding);
  605. GLint uboSize;
  606. glGetActiveUniformBlockiv(mProgram, i, GL_UNIFORM_BLOCK_DATA_SIZE, &uboSize);
  607. GLint numUboUniforms;
  608. glGetActiveUniformBlockiv(mProgram, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, &numUboUniforms);
  609. GLint* indices = new GLint[numUboUniforms];
  610. glGetActiveUniformBlockiv(mProgram, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES, indices);
  611. // fill out ubo desc.
  612. desc.name = String((char*)uboName);
  613. desc.bindPoint = uboBinding;
  614. desc.size = uboSize;
  615. desc.constType = GFXSCT_ConstBuffer;
  616. desc.samplerReg = -1;
  617. mBuffers[desc.name] = desc;
  618. // loop uniforms in the ubo.
  619. for (U32 j = 0; j < numUboUniforms; j++)
  620. {
  621. GFXShaderConstDesc varDesc;
  622. GLint uniformIndex = indices[j];
  623. GLint size;
  624. GLenum type;
  625. GLint offset;
  626. glGetActiveUniformsiv(mProgram, 1, (const GLuint*)&uniformIndex, GL_UNIFORM_OFFSET, &offset);
  627. glGetActiveUniform(mProgram, uniformIndex, maxNameLength, NULL, &size, &type, uniformName);
  628. varDesc.name = String((char*)uniformName);
  629. // remove array brackets.
  630. varDesc.name = varDesc.name.substr(0, varDesc.name.find('['));
  631. // Insert $ to match D3D behavior of having a $ prepended to parameters to main.
  632. varDesc.name.insert(0, '$');
  633. varDesc.bindPoint = desc.bindPoint; // just set to the buffer bindpoint for uniforms in a ubo.
  634. varDesc.offset = offset;
  635. varDesc.arraySize = size;
  636. varDesc.constType = convertConstType(type);
  637. varDesc.size = shaderConstTypeSize(varDesc.constType) * size;
  638. varDesc.samplerReg = -1;
  639. #ifdef OPENGL_DEBUG_SPEW
  640. Con::printf("Variable Name %s:, offset: %d, size: %d, constantDesc.Elements: %d", varDesc.name.c_str(), varDesc.offset, varDesc.size, varDesc.arraySize);
  641. #endif
  642. mShaderConsts.push_back(varDesc);
  643. }
  644. }
  645. GLint numUniforms;
  646. glGetProgramiv(mProgram, GL_ACTIVE_UNIFORMS, &numUniforms);
  647. for (U32 i = 0; i < numUniforms; i++)
  648. {
  649. // skip if this uniform is inside a ubo.
  650. GLint blk;
  651. glGetActiveUniformsiv(mProgram, 1, (GLuint*)&i, GL_UNIFORM_BLOCK_INDEX, &blk);
  652. if (blk != -1)
  653. {
  654. continue;
  655. }
  656. GLint size;
  657. GLenum type;
  658. glGetActiveUniform(mProgram, i, maxNameLength, NULL, &size, &type, uniformName);
  659. GFXShaderConstDesc desc;
  660. desc.name = String((char*)uniformName);
  661. // Remove array brackets from the name
  662. desc.name = desc.name.substr(0, desc.name.find('['));
  663. // Insert $ to match D3D behavior of having a $ prepended to parameters to main.
  664. desc.name.insert(0, '$');
  665. desc.bindPoint = -1;
  666. desc.arraySize = size;
  667. desc.constType = convertConstType(type);
  668. desc.size = shaderConstTypeSize(desc.constType) * size;
  669. desc.samplerReg = -1;
  670. mShaderConsts.push_back(desc);
  671. }
  672. }
  673. GFXShaderConstType GFXGLShader::convertConstType(GLenum constType)
  674. {
  675. switch (constType)
  676. {
  677. case GL_FLOAT:
  678. return GFXSCT_Float;
  679. break;
  680. case GL_FLOAT_VEC2:
  681. return GFXSCT_Float2;
  682. break;
  683. case GL_FLOAT_VEC3:
  684. return GFXSCT_Float3;
  685. break;
  686. case GL_FLOAT_VEC4:
  687. return GFXSCT_Float4;
  688. break;
  689. case GL_INT:
  690. return GFXSCT_Int;
  691. break;
  692. case GL_INT_VEC2:
  693. return GFXSCT_Int2;
  694. break;
  695. case GL_INT_VEC3:
  696. return GFXSCT_Int3;
  697. break;
  698. case GL_INT_VEC4:
  699. return GFXSCT_Int4;
  700. break;
  701. case GL_UNSIGNED_INT:
  702. return GFXSCT_UInt;
  703. break;
  704. case GL_UNSIGNED_INT_VEC2:
  705. return GFXSCT_UInt2;
  706. break;
  707. case GL_UNSIGNED_INT_VEC3:
  708. return GFXSCT_UInt3;
  709. break;
  710. case GL_UNSIGNED_INT_VEC4:
  711. return GFXSCT_UInt4;
  712. break;
  713. case GL_BOOL:
  714. return GFXSCT_Bool;
  715. break;
  716. case GL_BOOL_VEC2:
  717. return GFXSCT_Bool2;
  718. break;
  719. case GL_BOOL_VEC3:
  720. return GFXSCT_Bool3;
  721. break;
  722. case GL_BOOL_VEC4:
  723. return GFXSCT_Bool4;
  724. break;
  725. case GL_FLOAT_MAT2:
  726. return GFXSCT_Float2x2;
  727. break;
  728. case GL_FLOAT_MAT3:
  729. return GFXSCT_Float3x3;
  730. break;
  731. case GL_FLOAT_MAT4:
  732. return GFXSCT_Float4x4;
  733. break;
  734. case GL_FLOAT_MAT4x3: // jamesu - columns, rows
  735. return GFXSCT_Float4x3;
  736. break;
  737. case GL_SAMPLER_1D:
  738. case GL_SAMPLER_2D:
  739. case GL_SAMPLER_3D:
  740. case GL_SAMPLER_1D_SHADOW:
  741. case GL_SAMPLER_2D_SHADOW:
  742. return GFXSCT_Sampler;
  743. break;
  744. case GL_SAMPLER_CUBE:
  745. return GFXSCT_SamplerCube;
  746. break;
  747. case GL_SAMPLER_CUBE_MAP_ARRAY_ARB:
  748. return GFXSCT_SamplerCubeArray;
  749. break;
  750. case GL_SAMPLER_2D_ARRAY:
  751. return GFXSCT_SamplerTextureArray;
  752. break;
  753. default:
  754. AssertFatal(false, "Unknown shader constant class enum, maybe you could add it?");
  755. // If we don't recognize the constant don't add its description.
  756. break;
  757. }
  758. return GFXSCT_Uknown;
  759. }
  760. void GFXGLShader::initHandles()
  761. {
  762. // Mark all existing handles as invalid.
  763. // Those that are found when parsing the descriptions will then be marked valid again.
  764. for (HandleMap::Iterator iter = mHandles.begin(); iter != mHandles.end(); ++iter)
  765. (iter->value)->setValid(false);
  766. // Loop through constants that exist in ubos.
  767. for (U32 i = 0; i < mShaderConsts.size(); i++)
  768. {
  769. GFXShaderConstDesc& desc = mShaderConsts[i];
  770. // Index element 1 of the name to skip the '$' we inserted earier.
  771. GLint loc = glGetUniformLocation(mProgram, &desc.name.c_str()[1]);
  772. AssertFatal(loc != -1, avar("uniform %s in shader file Vert: (%s) Frag: (%s)", &desc.name.c_str()[1], mVertexFile.getFullPath().c_str(), mPixelFile.getFullPath().c_str()));
  773. HandleMap::Iterator handle = mHandles.find(desc.name);
  774. S32 sampler = -1;
  775. if (desc.constType == GFXSCT_Sampler ||
  776. desc.constType == GFXSCT_SamplerCube ||
  777. desc.constType == GFXSCT_SamplerCubeArray ||
  778. desc.constType == GFXSCT_SamplerTextureArray)
  779. {
  780. S32 idx = mSamplerNamesOrdered.find_next(desc.name);
  781. AssertFatal(idx != -1, "");
  782. sampler = idx; //assignedSamplerNum++;
  783. desc.samplerReg = idx;
  784. }
  785. if (handle != mHandles.end())
  786. {
  787. if (desc.bindPoint == -1)
  788. {
  789. desc.bindPoint = loc;
  790. mHandles[desc.name]->mUBOUniform = false;
  791. }
  792. else
  793. {
  794. mHandles[desc.name]->mUBOUniform = true;
  795. }
  796. handle->value->reinit(desc);
  797. }
  798. else
  799. {
  800. if (desc.bindPoint == -1)
  801. {
  802. desc.bindPoint = loc;
  803. mHandles[desc.name] = new GFXGLShaderConstHandle(this, desc);
  804. mHandles[desc.name]->mUBOUniform = false;
  805. }
  806. else
  807. {
  808. mHandles[desc.name] = new GFXGLShaderConstHandle(this, desc);
  809. mHandles[desc.name]->mUBOUniform = true;
  810. }
  811. }
  812. }
  813. // we have a global const buffer, set it up and add it.
  814. U32 constBufferSize = 0;
  815. if (mGlobalConstBuffer)
  816. delete[] mGlobalConstBuffer;
  817. for (HandleMap::Iterator iter = mHandles.begin(); iter != mHandles.end(); ++iter)
  818. {
  819. GFXGLShaderConstHandle* handle = iter->value;
  820. if (handle->isValid() && !handle->mUBOUniform)
  821. {
  822. handle->mDesc.offset = constBufferSize;
  823. constBufferSize += handle->getSize();
  824. }
  825. }
  826. if (constBufferSize > 0)
  827. {
  828. GFXShaderConstDesc desc;
  829. // fill out ubo desc.
  830. desc.name = "Global";
  831. desc.bindPoint = -1;
  832. desc.size = constBufferSize;
  833. desc.constType = GFXSCT_ConstBuffer;
  834. desc.samplerReg = -1;
  835. mBuffers[desc.name] = desc;
  836. mGlobalConstBuffer = new U8[constBufferSize];
  837. dMemset(mGlobalConstBuffer, 0, constBufferSize);
  838. }
  839. // Set our program so uniforms are assigned properly.
  840. mDevice->setShader(this, false);
  841. // Iterate through uniforms to set sampler numbers.
  842. for (HandleMap::Iterator iter = mHandles.begin(); iter != mHandles.end(); ++iter)
  843. {
  844. GFXGLShaderConstHandle* handle = iter->value;
  845. if (handle->isValid() &&
  846. (handle->getType() == GFXSCT_Sampler ||
  847. handle->getType() == GFXSCT_SamplerCube ||
  848. handle->getType() == GFXSCT_SamplerCubeArray ||
  849. handle->getType() == GFXSCT_SamplerTextureArray))
  850. {
  851. // Set sampler number on our program.
  852. glUniform1i(handle->mDesc.bindPoint, handle->mDesc.samplerReg);
  853. // Set sampler in constant buffer so it does not get unset later.
  854. dMemcpy(mGlobalConstBuffer + handle->mDesc.offset, &handle->mDesc.samplerReg, handle->getSize());
  855. }
  856. }
  857. //instancing
  858. if (!mInstancingFormat)
  859. return;
  860. U32 offset = 0;
  861. for (U32 i = 0; i < mInstancingFormat->getElementCount(); i++)
  862. {
  863. const GFXVertexElement& element = mInstancingFormat->getElement(i);
  864. String constName = String::ToString("$%s", element.getSemantic().c_str());
  865. HandleMap::Iterator handle = mHandles.find(constName);
  866. if (handle != mHandles.end())
  867. {
  868. AssertFatal(0, "");
  869. }
  870. else
  871. {
  872. GFXShaderConstDesc desc;
  873. desc.name = constName;
  874. desc.arraySize = 1;
  875. switch (element.getType())
  876. {
  877. case GFXDeclType_Float4:
  878. desc.constType = GFXSCT_Float4;
  879. break;
  880. default:
  881. desc.constType = GFXSCT_Float;
  882. break;
  883. }
  884. GFXGLShaderConstHandle* h = new GFXGLShaderConstHandle(this, desc);
  885. h->mInstancingConstant = true;
  886. h->mDesc.offset = offset;
  887. h->mUBOUniform = false;
  888. mHandles[constName] = h;
  889. offset += element.getSizeInBytes();
  890. ++i;
  891. // If this is a matrix we will have 2 or 3 more of these
  892. // semantics with the same name after it.
  893. for (; i < mInstancingFormat->getElementCount(); i++)
  894. {
  895. const GFXVertexElement& nextElement = mInstancingFormat->getElement(i);
  896. if (nextElement.getSemantic() != element.getSemantic())
  897. {
  898. i--;
  899. break;
  900. }
  901. ++desc.arraySize;
  902. if (desc.arraySize == 4 && desc.constType == GFXSCT_Float4)
  903. {
  904. desc.arraySize = 1;
  905. desc.constType = GFXSCT_Float4x4;
  906. }
  907. offset += nextElement.getSizeInBytes();
  908. }
  909. }
  910. }
  911. }
  912. GFXShaderConstHandle* GFXGLShader::getShaderConstHandle(const String& name)
  913. {
  914. HandleMap::Iterator i = mHandles.find(name);
  915. if (i != mHandles.end())
  916. return i->value;
  917. else
  918. {
  919. GFXGLShaderConstHandle* handle = new GFXGLShaderConstHandle(this);
  920. handle->setValid(false);
  921. mHandles[name] = handle;
  922. return handle;
  923. }
  924. }
  925. GFXShaderConstHandle* GFXGLShader::findShaderConstHandle(const String& name)
  926. {
  927. HandleMap::Iterator i = mHandles.find(name);
  928. if (i != mHandles.end())
  929. return i->value;
  930. else
  931. {
  932. return NULL;
  933. }
  934. }
  935. void GFXGLShader::setConstantsFromBuffer(U8* buffer)
  936. {
  937. for (HandleMap::Iterator i = mHandles.begin(); i != mHandles.end(); ++i)
  938. {
  939. GFXGLShaderConstHandle* handle = i->value;
  940. AssertFatal(handle, "GFXGLShader::setConstantsFromBuffer - Null handle");
  941. // skip ubo uniforms.
  942. if (handle->mUBOUniform || !handle->isValid())
  943. continue;
  944. if (handle->mInstancingConstant)
  945. continue;
  946. // Don't set if the value has not be changed.
  947. if (dMemcmp(mGlobalConstBuffer + handle->mDesc.offset, buffer + handle->mDesc.offset, handle->getSize()) == 0)
  948. continue;
  949. // Copy new value into our const buffer and set in GL.
  950. dMemcpy(mGlobalConstBuffer + handle->mDesc.offset, buffer + handle->mDesc.offset, handle->getSize());
  951. switch (handle->mDesc.constType)
  952. {
  953. case GFXSCT_Float:
  954. glUniform1fv(handle->mDesc.bindPoint, handle->mDesc.arraySize, (GLfloat*)(mGlobalConstBuffer + handle->mDesc.offset));
  955. break;
  956. case GFXSCT_Float2:
  957. glUniform2fv(handle->mDesc.bindPoint, handle->mDesc.arraySize, (GLfloat*)(mGlobalConstBuffer + handle->mDesc.offset));
  958. break;
  959. case GFXSCT_Float3:
  960. glUniform3fv(handle->mDesc.bindPoint, handle->mDesc.arraySize, (GLfloat*)(mGlobalConstBuffer + handle->mDesc.offset));
  961. break;
  962. case GFXSCT_Float4:
  963. glUniform4fv(handle->mDesc.bindPoint, handle->mDesc.arraySize, (GLfloat*)(mGlobalConstBuffer + handle->mDesc.offset));
  964. break;
  965. case GFXSCT_Sampler:
  966. case GFXSCT_SamplerCube:
  967. case GFXSCT_SamplerCubeArray:
  968. case GFXSCT_SamplerTextureArray:
  969. // Set sampler number on our program.
  970. glUniform1i(handle->mDesc.bindPoint, handle->mDesc.samplerReg);
  971. break;
  972. case GFXSCT_Int:
  973. glUniform1iv(handle->mDesc.bindPoint, handle->mDesc.arraySize, (GLint*)(mGlobalConstBuffer + handle->mDesc.offset));
  974. break;
  975. case GFXSCT_Int2:
  976. glUniform2iv(handle->mDesc.bindPoint, handle->mDesc.arraySize, (GLint*)(mGlobalConstBuffer + handle->mDesc.offset));
  977. break;
  978. case GFXSCT_Int3:
  979. glUniform3iv(handle->mDesc.bindPoint, handle->mDesc.arraySize, (GLint*)(mGlobalConstBuffer + handle->mDesc.offset));
  980. break;
  981. case GFXSCT_Int4:
  982. glUniform4iv(handle->mDesc.bindPoint, handle->mDesc.arraySize, (GLint*)(mGlobalConstBuffer + handle->mDesc.offset));
  983. break;
  984. case GFXSCT_Float2x2:
  985. glUniformMatrix2fv(handle->mDesc.bindPoint, handle->mDesc.arraySize, true, (GLfloat*)(mGlobalConstBuffer + handle->mDesc.offset));
  986. break;
  987. case GFXSCT_Float3x3:
  988. glUniformMatrix3fv(handle->mDesc.bindPoint, handle->mDesc.arraySize, true, (GLfloat*)(mGlobalConstBuffer + handle->mDesc.offset));
  989. break;
  990. case GFXSCT_Float4x3:
  991. // NOTE: To save a transpose here we could store the matrix transposed (i.e. column major) in the constant buffer.
  992. // See _mesa_uniform_matrix in the mesa source for the correct transpose algorithm for a 4x3 matrix.
  993. glUniformMatrix4x3fv(handle->mDesc.bindPoint, handle->mDesc.arraySize, true, (GLfloat*)(mGlobalConstBuffer + handle->mDesc.offset));
  994. break;
  995. case GFXSCT_Float4x4:
  996. glUniformMatrix4fv(handle->mDesc.bindPoint, handle->mDesc.arraySize, true, (GLfloat*)(mGlobalConstBuffer + handle->mDesc.offset));
  997. break;
  998. default:
  999. AssertFatal(0, "");
  1000. break;
  1001. }
  1002. }
  1003. }
  1004. GFXShaderConstBufferRef GFXGLShader::allocConstBuffer()
  1005. {
  1006. GFXGLShaderConstBuffer* buffer = new GFXGLShaderConstBuffer(this);
  1007. for (BufferMap::Iterator i = mBuffers.begin(); i != mBuffers.end(); ++i)
  1008. {
  1009. // add our buffer descriptions to the full const buffer.
  1010. buffer->addBuffer(i->value);
  1011. }
  1012. buffer->registerResourceWithDevice(getOwningDevice());
  1013. mActiveBuffers.push_back(buffer);
  1014. return buffer;
  1015. }
  1016. void GFXGLShader::useProgram()
  1017. {
  1018. glUseProgram(mProgram);
  1019. }
  1020. void GFXGLShader::zombify()
  1021. {
  1022. clearShaders();
  1023. }
  1024. char* GFXGLShader::_handleIncludes(const Torque::Path& path, FileStream* s)
  1025. {
  1026. // TODO: The #line pragma on GLSL takes something called a
  1027. // "source-string-number" which it then never explains.
  1028. //
  1029. // Until i resolve this mystery i disabled this.
  1030. //
  1031. //String linePragma = String::ToString( "#line 1 \r\n");
  1032. //U32 linePragmaLen = linePragma.length();
  1033. U32 shaderLen = s->getStreamSize();
  1034. char* buffer = (char*)dMalloc(shaderLen + 1);
  1035. //dStrncpy( buffer, linePragma.c_str(), linePragmaLen );
  1036. s->read(shaderLen, buffer);
  1037. buffer[shaderLen] = 0;
  1038. char* p = dStrstr(buffer, "#include");
  1039. while (p)
  1040. {
  1041. char* q = p;
  1042. p += 8;
  1043. if (dIsspace(*p))
  1044. {
  1045. U32 n = 0;
  1046. while (dIsspace(*p)) ++p;
  1047. AssertFatal(*p == '"', "Bad #include directive");
  1048. ++p;
  1049. static char includeFile[256];
  1050. while (*p != '"')
  1051. {
  1052. AssertFatal(*p != 0, "Bad #include directive");
  1053. includeFile[n++] = *p++;
  1054. AssertFatal(n < sizeof(includeFile), "#include directive too long");
  1055. }
  1056. ++p;
  1057. includeFile[n] = 0;
  1058. // First try it as a local file.
  1059. Torque::Path includePath = Torque::Path::Join(path.getPath(), '/', includeFile);
  1060. includePath = Torque::Path::CompressPath(includePath);
  1061. FileStream includeStream;
  1062. if (!includeStream.open(includePath, Torque::FS::File::Read))
  1063. {
  1064. // Try again assuming the path is absolute
  1065. // and/or relative.
  1066. includePath = String(includeFile);
  1067. includePath = Torque::Path::CompressPath(includePath);
  1068. if (!includeStream.open(includePath, Torque::FS::File::Read))
  1069. {
  1070. AssertISV(false, avar("failed to open include '%s'.", includePath.getFullPath().c_str()));
  1071. if (smLogErrors)
  1072. Con::errorf("GFXGLShader::_handleIncludes - Failed to open include '%s'.",
  1073. includePath.getFullPath().c_str());
  1074. // Fail... don't return the buffer.
  1075. dFree(buffer);
  1076. return NULL;
  1077. }
  1078. }
  1079. char* includedText = _handleIncludes(includePath, &includeStream);
  1080. // If a sub-include fails... cleanup and return.
  1081. if (!includedText)
  1082. {
  1083. dFree(buffer);
  1084. return NULL;
  1085. }
  1086. // TODO: Disabled till this is fixed correctly.
  1087. //
  1088. // Count the number of lines in the file
  1089. // before the include.
  1090. /*
  1091. U32 includeLine = 0;
  1092. {
  1093. char* nl = dStrstr( buffer, "\n" );
  1094. while ( nl )
  1095. {
  1096. includeLine++;
  1097. nl = dStrstr( nl, "\n" );
  1098. if(nl) ++nl;
  1099. }
  1100. }
  1101. */
  1102. String manip(buffer);
  1103. manip.erase(q - buffer, p - q);
  1104. String sItx(includedText);
  1105. // TODO: Disabled till this is fixed correctly.
  1106. //
  1107. // Add a new line pragma to restore the proper
  1108. // file and line number after the include.
  1109. //sItx += String::ToString( "\r\n#line %d \r\n", includeLine );
  1110. dFree(includedText);
  1111. manip.insert(q - buffer, sItx);
  1112. char* manipBuf = dStrdup(manip.c_str());
  1113. p = manipBuf + (q - buffer);
  1114. dFree(buffer);
  1115. buffer = manipBuf;
  1116. }
  1117. p = dStrstr(p, "#include");
  1118. }
  1119. return buffer;
  1120. }
  1121. bool GFXGLShader::_loadShaderFromStream(GLuint shader,
  1122. const Torque::Path& path,
  1123. FileStream* s,
  1124. const Vector<GFXShaderMacro>& macros)
  1125. {
  1126. Vector<char*> buffers;
  1127. Vector<U32> lengths;
  1128. // The GLSL version declaration must go first!
  1129. const char* versionDecl = "#version 330\n";
  1130. buffers.push_back(dStrdup(versionDecl));
  1131. lengths.push_back(dStrlen(versionDecl));
  1132. //Required extensions. These are already checked when creating the GFX adapter, if we make it this far it's supported
  1133. const char* cubeArrayExt = "#extension GL_ARB_texture_cube_map_array : enable\n";
  1134. buffers.push_back(dStrdup(cubeArrayExt));
  1135. lengths.push_back(dStrlen(cubeArrayExt));
  1136. const char* gpuShader5Ext = "#extension GL_ARB_gpu_shader5 : enable\n";
  1137. buffers.push_back(dStrdup(gpuShader5Ext));
  1138. lengths.push_back(dStrlen(gpuShader5Ext));
  1139. const char* newLine = "\r\n";
  1140. buffers.push_back(dStrdup(newLine));
  1141. lengths.push_back(dStrlen(newLine));
  1142. // Now add all the macros.
  1143. for (U32 i = 0; i < macros.size(); i++)
  1144. {
  1145. if (macros[i].name.isEmpty()) // TODO OPENGL
  1146. continue;
  1147. String define = String::ToString("#define %s %s\n", macros[i].name.c_str(), macros[i].value.c_str());
  1148. buffers.push_back(dStrdup(define.c_str()));
  1149. lengths.push_back(define.length());
  1150. }
  1151. // Now finally add the shader source.
  1152. U32 shaderLen = s->getStreamSize();
  1153. char* buffer = _handleIncludes(path, s);
  1154. if (!buffer)
  1155. return false;
  1156. buffers.push_back(buffer);
  1157. lengths.push_back(shaderLen);
  1158. glShaderSource(shader, buffers.size(), (const GLchar**)const_cast<const char**>(buffers.address()), NULL);
  1159. #if defined(TORQUE_DEBUG) && defined(TORQUE_DEBUG_GFX)
  1160. FileStream stream;
  1161. if (!stream.open(path.getFullPath() + "_DEBUG", Torque::FS::File::Write))
  1162. {
  1163. AssertISV(false, avar("GFXGLShader::initShader - failed to write debug shader '%s'.", path.getFullPath().c_str()));
  1164. }
  1165. for (int i = 0; i < buffers.size(); ++i)
  1166. stream.writeText(buffers[i]);
  1167. #endif
  1168. // Cleanup the shader source buffer.
  1169. for (U32 i = 0; i < buffers.size(); i++)
  1170. dFree(buffers[i]);
  1171. glCompileShader(shader);
  1172. return true;
  1173. }
  1174. bool GFXGLShader::initShader(const Torque::Path& file,
  1175. GFXShaderStage stage,
  1176. const Vector<GFXShaderMacro>& macros)
  1177. {
  1178. PROFILE_SCOPE(GFXGLShader_CompileShader);
  1179. GLuint activeShader = 0;
  1180. switch (stage)
  1181. {
  1182. case VERTEX_SHADER:
  1183. activeShader = glCreateShader(GL_VERTEX_SHADER);
  1184. mVertexShader = activeShader;
  1185. break;
  1186. case PIXEL_SHADER:
  1187. activeShader = glCreateShader(GL_FRAGMENT_SHADER);
  1188. mPixelShader = activeShader;
  1189. break;
  1190. case GEOMETRY_SHADER:
  1191. activeShader = glCreateShader(GL_GEOMETRY_SHADER);
  1192. mGeometryShader = activeShader;
  1193. break;
  1194. case DOMAIN_SHADER:
  1195. break;
  1196. case HULL_SHADER:
  1197. break;
  1198. case COMPUTE_SHADER:
  1199. break;
  1200. default:
  1201. break;
  1202. }
  1203. glAttachShader(mProgram, activeShader);
  1204. // Ok it's not in the shader gen manager, so ask Torque for it
  1205. FileStream stream;
  1206. if (!stream.open(file, Torque::FS::File::Read))
  1207. {
  1208. AssertISV(false, avar("GFXGLShader::initShader - failed to open shader '%s'.", file.getFullPath().c_str()));
  1209. if (smLogErrors)
  1210. Con::errorf("GFXGLShader::initShader - Failed to open shader file '%s'.",
  1211. file.getFullPath().c_str());
  1212. return false;
  1213. }
  1214. if (!_loadShaderFromStream(activeShader, file, &stream, macros))
  1215. {
  1216. if (smLogErrors)
  1217. Con::errorf("GFXGLShader::initShader - unable to load shader from stream: '%s'.", file.getFullPath().c_str());
  1218. return false;
  1219. }
  1220. GLint compile;
  1221. glGetShaderiv(activeShader, GL_COMPILE_STATUS, &compile);
  1222. // Dump the info log to the console
  1223. U32 logLength = 0;
  1224. glGetShaderiv(activeShader, GL_INFO_LOG_LENGTH, (GLint*)&logLength);
  1225. if (logLength)
  1226. {
  1227. FrameAllocatorMarker fam;
  1228. char* log = (char*)fam.alloc(logLength);
  1229. glGetShaderInfoLog(activeShader, logLength, NULL, log);
  1230. if (compile == GL_FALSE)
  1231. {
  1232. if (smLogErrors)
  1233. {
  1234. Con::errorf("GFXGLShader::initShader - Error compiling shader!");
  1235. Con::errorf("Program %s: %s", file.getFullPath().c_str(), log);
  1236. }
  1237. }
  1238. else if (smLogWarnings)
  1239. Con::warnf("Program %s: %s", file.getFullPath().c_str(), log);
  1240. }
  1241. return compile != GL_FALSE;
  1242. }
  1243. /// Returns our list of shader constants, the material can get this and just set the constants it knows about
  1244. const Vector<GFXShaderConstDesc>& GFXGLShader::getShaderConstDesc() const
  1245. {
  1246. PROFILE_SCOPE(GFXGLShader_GetShaderConstants);
  1247. return mShaderConsts;
  1248. }
  1249. /// Returns the alignment value for constType
  1250. U32 GFXGLShader::getAlignmentValue(const GFXShaderConstType constType) const
  1251. {
  1252. // Alignment is the same thing as size for us.
  1253. return shaderConstTypeSize(constType);
  1254. }
  1255. const String GFXGLShader::describeSelf() const
  1256. {
  1257. String ret;
  1258. ret = String::ToString(" Program: %i", mProgram);
  1259. ret += String::ToString(" Vertex Path: %s", mVertexFile.getFullPath().c_str());
  1260. ret += String::ToString(" Pixel Path: %s", mPixelFile.getFullPath().c_str());
  1261. return ret;
  1262. }