stencil.cpp 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507
  1. /*
  2. * Copyright 2013-2014 Dario Manesku. All rights reserved.
  3. * License: http://www.opensource.org/licenses/BSD-2-Clause
  4. */
  5. #include <string>
  6. #include <vector>
  7. #include "common.h"
  8. #include <bgfx.h>
  9. #include <bx/timer.h>
  10. #include <bx/readerwriter.h>
  11. #include "entry/entry.h"
  12. #include "camera.h"
  13. #include "fpumath.h"
  14. #include "imgui/imgui.h"
  15. #define RENDER_VIEWID_RANGE1_PASS_0 1
  16. #define RENDER_VIEWID_RANGE1_PASS_1 2
  17. #define RENDER_VIEWID_RANGE1_PASS_2 3
  18. #define RENDER_VIEWID_RANGE1_PASS_3 4
  19. #define RENDER_VIEWID_RANGE1_PASS_4 5
  20. #define RENDER_VIEWID_RANGE1_PASS_5 6
  21. #define RENDER_VIEWID_RANGE5_PASS_6 7
  22. #define RENDER_VIEWID_RANGE1_PASS_7 13
  23. #define MAX_NUM_LIGHTS 5
  24. uint32_t packUint32(uint8_t _x, uint8_t _y, uint8_t _z, uint8_t _w)
  25. {
  26. union
  27. {
  28. uint32_t ui32;
  29. uint8_t arr[4];
  30. } un;
  31. un.arr[0] = _x;
  32. un.arr[1] = _y;
  33. un.arr[2] = _z;
  34. un.arr[3] = _w;
  35. return un.ui32;
  36. }
  37. uint32_t packF4u(float _x, float _y = 0.0f, float _z = 0.0f, float _w = 0.0f)
  38. {
  39. const uint8_t xx = uint8_t(_x*127.0f + 128.0f);
  40. const uint8_t yy = uint8_t(_y*127.0f + 128.0f);
  41. const uint8_t zz = uint8_t(_z*127.0f + 128.0f);
  42. const uint8_t ww = uint8_t(_w*127.0f + 128.0f);
  43. return packUint32(xx, yy, zz, ww);
  44. }
  45. struct PosNormalTexcoordVertex
  46. {
  47. float m_x;
  48. float m_y;
  49. float m_z;
  50. uint32_t m_normal;
  51. float m_u;
  52. float m_v;
  53. };
  54. static const float s_texcoord = 5.0f;
  55. static const uint32_t s_numHPlaneVertices = 4;
  56. static PosNormalTexcoordVertex s_hplaneVertices[s_numHPlaneVertices] =
  57. {
  58. { -1.0f, 0.0f, 1.0f, packF4u(0.0f, 1.0f, 0.0f), s_texcoord, s_texcoord },
  59. { 1.0f, 0.0f, 1.0f, packF4u(0.0f, 1.0f, 0.0f), s_texcoord, 0.0f },
  60. { -1.0f, 0.0f, -1.0f, packF4u(0.0f, 1.0f, 0.0f), 0.0f, s_texcoord },
  61. { 1.0f, 0.0f, -1.0f, packF4u(0.0f, 1.0f, 0.0f), 0.0f, 0.0f },
  62. };
  63. static const uint32_t s_numVPlaneVertices = 4;
  64. static PosNormalTexcoordVertex s_vplaneVertices[s_numVPlaneVertices] =
  65. {
  66. { -1.0f, 1.0f, 0.0f, packF4u(0.0f, 0.0f, -1.0f), 1.0f, 1.0f },
  67. { 1.0f, 1.0f, 0.0f, packF4u(0.0f, 0.0f, -1.0f), 1.0f, 0.0f },
  68. { -1.0f, -1.0f, 0.0f, packF4u(0.0f, 0.0f, -1.0f), 0.0f, 1.0f },
  69. { 1.0f, -1.0f, 0.0f, packF4u(0.0f, 0.0f, -1.0f), 0.0f, 0.0f },
  70. };
  71. static const uint32_t s_numCubeVertices = 24;
  72. static const PosNormalTexcoordVertex s_cubeVertices[s_numCubeVertices] =
  73. {
  74. { -1.0f, 1.0f, 1.0f, packF4u( 0.0f, 1.0f, 0.0f), 1.0f, 1.0f },
  75. { 1.0f, 1.0f, 1.0f, packF4u( 0.0f, 1.0f, 0.0f), 0.0f, 1.0f },
  76. { -1.0f, 1.0f, -1.0f, packF4u( 0.0f, 1.0f, 0.0f), 1.0f, 0.0f },
  77. { 1.0f, 1.0f, -1.0f, packF4u( 0.0f, 1.0f, 0.0f), 0.0f, 0.0f },
  78. { -1.0f, -1.0f, 1.0f, packF4u( 0.0f, -1.0f, 0.0f), 1.0f, 1.0f },
  79. { 1.0f, -1.0f, 1.0f, packF4u( 0.0f, -1.0f, 0.0f), 0.0f, 1.0f },
  80. { -1.0f, -1.0f, -1.0f, packF4u( 0.0f, -1.0f, 0.0f), 1.0f, 0.0f },
  81. { 1.0f, -1.0f, -1.0f, packF4u( 0.0f, -1.0f, 0.0f), 0.0f, 0.0f },
  82. { 1.0f, -1.0f, 1.0f, packF4u( 0.0f, 0.0f, 1.0f), 0.0f, 0.0f },
  83. { 1.0f, 1.0f, 1.0f, packF4u( 0.0f, 0.0f, 1.0f), 0.0f, 1.0f },
  84. { -1.0f, -1.0f, 1.0f, packF4u( 0.0f, 0.0f, 1.0f), 1.0f, 0.0f },
  85. { -1.0f, 1.0f, 1.0f, packF4u( 0.0f, 0.0f, 1.0f), 1.0f, 1.0f },
  86. { 1.0f, -1.0f, -1.0f, packF4u( 0.0f, 0.0f, -1.0f), 0.0f, 0.0f },
  87. { 1.0f, 1.0f, -1.0f, packF4u( 0.0f, 0.0f, -1.0f), 0.0f, 1.0f },
  88. { -1.0f, -1.0f, -1.0f, packF4u( 0.0f, 0.0f, -1.0f), 1.0f, 0.0f },
  89. { -1.0f, 1.0f, -1.0f, packF4u( 0.0f, 0.0f, -1.0f), 1.0f, 1.0f },
  90. { 1.0f, 1.0f, -1.0f, packF4u( 1.0f, 0.0f, 0.0f), 1.0f, 1.0f },
  91. { 1.0f, 1.0f, 1.0f, packF4u( 1.0f, 0.0f, 0.0f), 0.0f, 1.0f },
  92. { 1.0f, -1.0f, -1.0f, packF4u( 1.0f, 0.0f, 0.0f), 1.0f, 0.0f },
  93. { 1.0f, -1.0f, 1.0f, packF4u( 1.0f, 0.0f, 0.0f), 0.0f, 0.0f },
  94. { -1.0f, 1.0f, -1.0f, packF4u(-1.0f, 0.0f, 0.0f), 1.0f, 1.0f },
  95. { -1.0f, 1.0f, 1.0f, packF4u(-1.0f, 0.0f, 0.0f), 0.0f, 1.0f },
  96. { -1.0f, -1.0f, -1.0f, packF4u(-1.0f, 0.0f, 0.0f), 1.0f, 0.0f },
  97. { -1.0f, -1.0f, 1.0f, packF4u(-1.0f, 0.0f, 0.0f), 0.0f, 0.0f },
  98. };
  99. static const uint32_t s_numCubeIndices = 36;
  100. static const uint16_t s_cubeIndices[s_numCubeIndices] =
  101. {
  102. 0, 1, 2,
  103. 1, 3, 2,
  104. 4, 6, 5,
  105. 5, 6, 7,
  106. 8, 9, 10,
  107. 9, 11, 10,
  108. 12, 14, 13,
  109. 13, 14, 15,
  110. 16, 17, 18,
  111. 17, 19, 18,
  112. 20, 22, 21,
  113. 21, 22, 23,
  114. };
  115. static const uint32_t s_numPlaneIndices = 6;
  116. static const uint16_t s_planeIndices[s_numPlaneIndices] =
  117. {
  118. 0, 1, 2,
  119. 1, 3, 2,
  120. };
  121. static const char* s_shaderPath = NULL;
  122. static bool s_flipV = false;
  123. static uint32_t s_viewMask = 0;
  124. static uint32_t s_clearMask = 0;
  125. static bgfx::UniformHandle u_texColor;
  126. static void shaderFilePath(char* _out, const char* _name)
  127. {
  128. strcpy(_out, s_shaderPath);
  129. strcat(_out, _name);
  130. strcat(_out, ".bin");
  131. }
  132. long int fsize(FILE* _file)
  133. {
  134. long int pos = ftell(_file);
  135. fseek(_file, 0L, SEEK_END);
  136. long int size = ftell(_file);
  137. fseek(_file, pos, SEEK_SET);
  138. return size;
  139. }
  140. static const bgfx::Memory* load(const char* _filePath)
  141. {
  142. FILE* file = fopen(_filePath, "rb");
  143. if (NULL != file)
  144. {
  145. uint32_t size = (uint32_t)fsize(file);
  146. const bgfx::Memory* mem = bgfx::alloc(size+1);
  147. size_t ignore = fread(mem->data, 1, size, file);
  148. BX_UNUSED(ignore);
  149. fclose(file);
  150. mem->data[mem->size-1] = '\0';
  151. return mem;
  152. }
  153. return NULL;
  154. }
  155. static const bgfx::Memory* loadShader(const char* _name)
  156. {
  157. char filePath[512];
  158. shaderFilePath(filePath, _name);
  159. return load(filePath);
  160. }
  161. static const bgfx::Memory* loadTexture(const char* _name)
  162. {
  163. char filePath[512];
  164. strcpy(filePath, "textures/");
  165. strcat(filePath, _name);
  166. return load(filePath);
  167. }
  168. static bgfx::ProgramHandle loadProgram(const char* _vsName, const char* _fsName)
  169. {
  170. const bgfx::Memory* mem;
  171. // Load vertex shader.
  172. mem = loadShader(_vsName);
  173. bgfx::ShaderHandle vsh = bgfx::createShader(mem);
  174. // Load fragment shader.
  175. mem = loadShader(_fsName);
  176. bgfx::ShaderHandle fsh = bgfx::createShader(mem);
  177. // Create program from shaders.
  178. return bgfx::createProgram(vsh, fsh, true /* destroy shaders when program is destroyed */);
  179. }
  180. void mtxScaleRotateTranslate(float* _result
  181. , const float _scaleX
  182. , const float _scaleY
  183. , const float _scaleZ
  184. , const float _rotX
  185. , const float _rotY
  186. , const float _rotZ
  187. , const float _translateX
  188. , const float _translateY
  189. , const float _translateZ
  190. )
  191. {
  192. float mtxRotateTranslate[16];
  193. float mtxScale[16];
  194. mtxRotateXYZ(mtxRotateTranslate, _rotX, _rotY, _rotZ);
  195. mtxRotateTranslate[12] = _translateX;
  196. mtxRotateTranslate[13] = _translateY;
  197. mtxRotateTranslate[14] = _translateZ;
  198. memset(mtxScale, 0, sizeof(float)*16);
  199. mtxScale[0] = _scaleX;
  200. mtxScale[5] = _scaleY;
  201. mtxScale[10] = _scaleZ;
  202. mtxScale[15] = 1.0f;
  203. mtxMul(_result, mtxScale, mtxRotateTranslate);
  204. }
  205. void mtxReflected(float*__restrict _result
  206. , const float* __restrict _p /* plane */
  207. , const float* __restrict _n /* normal */
  208. )
  209. {
  210. float dot = vec3Dot(_p, _n);
  211. _result[ 0] = 1.0f - 2.0f * _n[0] * _n[0]; //1-2Nx^2
  212. _result[ 1] = -2.0f * _n[0] * _n[1]; //-2*Nx*Ny
  213. _result[ 2] = -2.0f * _n[0] * _n[2]; //-2*NxNz
  214. _result[ 3] = 0.0f; //0
  215. _result[ 4] = -2.0f * _n[0] * _n[1]; //-2*NxNy
  216. _result[ 5] = 1.0f - 2.0f * _n[1] * _n[1]; //1-2*Ny^2
  217. _result[ 6] = -2.0f * _n[1] * _n[2]; //-2*NyNz
  218. _result[ 7] = 0.0f; //0
  219. _result[ 8] = -2.0f * _n[0] * _n[2]; //-2*NxNz
  220. _result[ 9] = -2.0f * _n[1] * _n[2]; //-2NyNz
  221. _result[10] = 1.0f - 2.0f * _n[2] * _n[2]; //1-2*Nz^2
  222. _result[11] = 0.0f; //0
  223. _result[12] = 2.0f * dot * _n[0]; //2*dot*Nx
  224. _result[13] = 2.0f * dot * _n[1]; //2*dot*Ny
  225. _result[14] = 2.0f * dot * _n[2]; //2*dot*Nz
  226. _result[15] = 1.0f; //1
  227. }
  228. void mtxShadow(float* __restrict _result
  229. , const float* __restrict _ground
  230. , const float* __restrict _light
  231. )
  232. {
  233. float dot = _ground[0] * _light[0]
  234. + _ground[1] * _light[1]
  235. + _ground[2] * _light[2]
  236. + _ground[3] * _light[3]
  237. ;
  238. _result[ 0] = dot - _light[0] * _ground[0];
  239. _result[ 1] = 0.0f - _light[1] * _ground[0];
  240. _result[ 2] = 0.0f - _light[2] * _ground[0];
  241. _result[ 3] = 0.0f - _light[3] * _ground[0];
  242. _result[ 4] = 0.0f - _light[0] * _ground[1];
  243. _result[ 5] = dot - _light[1] * _ground[1];
  244. _result[ 6] = 0.0f - _light[2] * _ground[1];
  245. _result[ 7] = 0.0f - _light[3] * _ground[1];
  246. _result[ 8] = 0.0f - _light[0] * _ground[2];
  247. _result[ 9] = 0.0f - _light[1] * _ground[2];
  248. _result[10] = dot - _light[2] * _ground[2];
  249. _result[11] = 0.0f - _light[3] * _ground[2];
  250. _result[12] = 0.0f - _light[0] * _ground[3];
  251. _result[13] = 0.0f - _light[1] * _ground[3];
  252. _result[14] = 0.0f - _light[2] * _ground[3];
  253. _result[15] = dot - _light[3] * _ground[3];
  254. }
  255. void mtxBillboard(float* __restrict _result
  256. , const float* __restrict _view
  257. , const float* __restrict _pos
  258. , const float* __restrict _scale)
  259. {
  260. _result[ 0] = _view[0] * _scale[0];
  261. _result[ 1] = _view[4] * _scale[0];
  262. _result[ 2] = _view[8] * _scale[0];
  263. _result[ 3] = 0.0f;
  264. _result[ 4] = _view[1] * _scale[1];
  265. _result[ 5] = _view[5] * _scale[1];
  266. _result[ 6] = _view[9] * _scale[1];
  267. _result[ 7] = 0.0f;
  268. _result[ 8] = _view[2] * _scale[2];
  269. _result[ 9] = _view[6] * _scale[2];
  270. _result[10] = _view[10] * _scale[2];
  271. _result[11] = 0.0f;
  272. _result[12] = _pos[0];
  273. _result[13] = _pos[1];
  274. _result[14] = _pos[2];
  275. _result[15] = 1.0f;
  276. }
  277. struct Uniforms
  278. {
  279. void init()
  280. {
  281. m_params.m_ambientPass = 1.0f;
  282. m_params.m_lightningPass = 1.0f;
  283. m_params.m_lightCount = 4.0f;
  284. m_params.m_lightIndex = 4.0f;
  285. m_ambient[0] = 0.02f;
  286. m_ambient[1] = 0.02f;
  287. m_ambient[2] = 0.02f;
  288. m_ambient[3] = 0.0f; //unused
  289. m_diffuse[0] = 0.2f;
  290. m_diffuse[1] = 0.2f;
  291. m_diffuse[2] = 0.2f;
  292. m_diffuse[3] = 0.0f; //unused
  293. m_specular_shininess[0] = 1.0f;
  294. m_specular_shininess[1] = 1.0f;
  295. m_specular_shininess[2] = 1.0f;
  296. m_specular_shininess[3] = 10.0f; //shininess
  297. m_color[0] = 1.0f;
  298. m_color[1] = 1.0f;
  299. m_color[2] = 1.0f;
  300. m_color[3] = 1.0f;
  301. m_time = 0.0f;
  302. for (uint8_t ii = 0; ii < MAX_NUM_LIGHTS; ++ii)
  303. {
  304. m_lightPosRadius[ii][0] = 0.0f;
  305. m_lightPosRadius[ii][1] = 0.0f;
  306. m_lightPosRadius[ii][2] = 0.0f;
  307. m_lightPosRadius[ii][3] = 1.0f;
  308. m_lightRgbInnerR[ii][0] = 1.0f;
  309. m_lightRgbInnerR[ii][1] = 1.0f;
  310. m_lightRgbInnerR[ii][2] = 1.0f;
  311. m_lightRgbInnerR[ii][3] = 1.0f;
  312. }
  313. u_params = bgfx::createUniform("u_params", bgfx::UniformType::Uniform4fv);
  314. u_ambient = bgfx::createUniform("u_ambient", bgfx::UniformType::Uniform4fv);
  315. u_diffuse = bgfx::createUniform("u_diffuse", bgfx::UniformType::Uniform4fv);
  316. u_specular_shininess = bgfx::createUniform("u_specular_shininess", bgfx::UniformType::Uniform4fv);
  317. u_color = bgfx::createUniform("u_color", bgfx::UniformType::Uniform4fv);
  318. u_time = bgfx::createUniform("u_time", bgfx::UniformType::Uniform1f );
  319. u_lightPosRadius = bgfx::createUniform("u_lightPosRadius", bgfx::UniformType::Uniform4fv, MAX_NUM_LIGHTS);
  320. u_lightRgbInnerR = bgfx::createUniform("u_lightRgbInnerR", bgfx::UniformType::Uniform4fv, MAX_NUM_LIGHTS);
  321. }
  322. //call this once at initialization
  323. void submitConstUniforms()
  324. {
  325. bgfx::setUniform(u_ambient, &m_ambient);
  326. bgfx::setUniform(u_diffuse, &m_diffuse);
  327. bgfx::setUniform(u_specular_shininess, &m_specular_shininess);
  328. }
  329. //call this once per frame
  330. void submitPerFrameUniforms()
  331. {
  332. bgfx::setUniform(u_time, &m_time);
  333. }
  334. //call this before each draw call
  335. void submitPerDrawUniforms()
  336. {
  337. bgfx::setUniform(u_params, &m_params);
  338. bgfx::setUniform(u_color, &m_color);
  339. bgfx::setUniform(u_lightPosRadius, &m_lightPosRadius, MAX_NUM_LIGHTS);
  340. bgfx::setUniform(u_lightRgbInnerR, &m_lightRgbInnerR, MAX_NUM_LIGHTS);
  341. }
  342. void destroy()
  343. {
  344. bgfx::destroyUniform(u_params);
  345. bgfx::destroyUniform(u_ambient);
  346. bgfx::destroyUniform(u_diffuse);
  347. bgfx::destroyUniform(u_specular_shininess);
  348. bgfx::destroyUniform(u_color);
  349. bgfx::destroyUniform(u_time);
  350. bgfx::destroyUniform(u_lightPosRadius);
  351. bgfx::destroyUniform(u_lightRgbInnerR);
  352. }
  353. struct Params
  354. {
  355. float m_ambientPass;
  356. float m_lightningPass;
  357. float m_lightCount;
  358. float m_lightIndex;
  359. };
  360. struct SvParams
  361. {
  362. float m_useStencilTex;
  363. float m_dfail;
  364. float m_unused0;
  365. float m_unused1;
  366. };
  367. Params m_params;
  368. SvParams m_svparams;
  369. float m_ambient[4];
  370. float m_diffuse[4];
  371. float m_specular_shininess[4];
  372. float m_color[4];
  373. float m_time;
  374. float m_lightPosRadius[MAX_NUM_LIGHTS][4];
  375. float m_lightRgbInnerR[MAX_NUM_LIGHTS][4];
  376. /**
  377. * u_params.x - u_ambientPass
  378. * u_params.y - u_lightningPass
  379. * u_params.z - u_lightCount
  380. * u_params.w - u_lightIndex
  381. */
  382. bgfx::UniformHandle u_params;
  383. bgfx::UniformHandle u_ambient;
  384. bgfx::UniformHandle u_diffuse;
  385. bgfx::UniformHandle u_specular_shininess;
  386. bgfx::UniformHandle u_color;
  387. bgfx::UniformHandle u_time;
  388. bgfx::UniformHandle u_lightPosRadius;
  389. bgfx::UniformHandle u_lightRgbInnerR;
  390. };
  391. static Uniforms s_uniforms;
  392. //-------------------------------------------------
  393. // Render state
  394. //-------------------------------------------------
  395. struct RenderState
  396. {
  397. enum Enum
  398. {
  399. StencilReflection_CraftStencil = 0,
  400. StencilReflection_DrawReflected,
  401. StencilReflection_BlendPlane,
  402. StencilReflection_DrawScene,
  403. ProjectionShadows_DrawAmbient,
  404. ProjectionShadows_CraftStencil,
  405. ProjectionShadows_DrawDiffuse,
  406. Custom_BlendLightTexture,
  407. Custom_DrawPlaneBottom,
  408. Count
  409. };
  410. uint64_t m_state;
  411. uint32_t m_blendFactorRgba;
  412. uint32_t m_fstencil;
  413. uint32_t m_bstencil;
  414. };
  415. static RenderState s_renderStates[RenderState::Count] =
  416. {
  417. { // StencilReflection_CraftStencil
  418. BGFX_STATE_RGB_WRITE
  419. | BGFX_STATE_DEPTH_WRITE
  420. | BGFX_STATE_DEPTH_TEST_LESS
  421. | BGFX_STATE_MSAA
  422. , UINT32_MAX
  423. , BGFX_STENCIL_TEST_ALWAYS // pass always
  424. | BGFX_STENCIL_FUNC_REF(1) // value = 1
  425. | BGFX_STENCIL_FUNC_RMASK(0xff)
  426. | BGFX_STENCIL_OP_FAIL_S_REPLACE
  427. | BGFX_STENCIL_OP_FAIL_Z_REPLACE
  428. | BGFX_STENCIL_OP_PASS_Z_REPLACE // store the value
  429. , BGFX_STENCIL_NONE
  430. },
  431. { // StencilReflection_DrawReflected
  432. BGFX_STATE_RGB_WRITE
  433. | BGFX_STATE_ALPHA_WRITE
  434. | BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_SRC_ALPHA, BGFX_STATE_BLEND_INV_SRC_ALPHA)
  435. | BGFX_STATE_DEPTH_WRITE
  436. | BGFX_STATE_DEPTH_TEST_LESS
  437. | BGFX_STATE_CULL_CW //reflection matrix has inverted normals. using CCW instead of CW.
  438. | BGFX_STATE_MSAA
  439. , UINT32_MAX
  440. , BGFX_STENCIL_TEST_EQUAL
  441. | BGFX_STENCIL_FUNC_REF(1)
  442. | BGFX_STENCIL_FUNC_RMASK(1)
  443. | BGFX_STENCIL_OP_FAIL_S_KEEP
  444. | BGFX_STENCIL_OP_FAIL_Z_KEEP
  445. | BGFX_STENCIL_OP_PASS_Z_KEEP
  446. , BGFX_STENCIL_NONE
  447. },
  448. { // StencilReflection_BlendPlane
  449. BGFX_STATE_RGB_WRITE
  450. | BGFX_STATE_DEPTH_WRITE
  451. | BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_SRC_COLOR)
  452. | BGFX_STATE_DEPTH_TEST_LESS
  453. | BGFX_STATE_CULL_CCW
  454. | BGFX_STATE_MSAA
  455. , UINT32_MAX
  456. , BGFX_STENCIL_NONE
  457. , BGFX_STENCIL_NONE
  458. },
  459. { // StencilReflection_DrawScene
  460. BGFX_STATE_RGB_WRITE
  461. | BGFX_STATE_DEPTH_WRITE
  462. | BGFX_STATE_DEPTH_TEST_LESS
  463. | BGFX_STATE_CULL_CCW
  464. | BGFX_STATE_MSAA
  465. , UINT32_MAX
  466. , BGFX_STENCIL_NONE
  467. , BGFX_STENCIL_NONE
  468. },
  469. { // ProjectionShadows_DrawAmbient
  470. BGFX_STATE_RGB_WRITE
  471. | BGFX_STATE_DEPTH_WRITE // write depth !
  472. | BGFX_STATE_DEPTH_TEST_LESS
  473. | BGFX_STATE_CULL_CCW
  474. | BGFX_STATE_MSAA
  475. , UINT32_MAX
  476. , BGFX_STENCIL_NONE
  477. , BGFX_STENCIL_NONE
  478. },
  479. { // ProjectionShadows_CraftStencil
  480. BGFX_STATE_DEPTH_TEST_LESS
  481. | BGFX_STATE_MSAA
  482. , UINT32_MAX
  483. , BGFX_STENCIL_TEST_ALWAYS // pass always
  484. | BGFX_STENCIL_FUNC_REF(1) // value = 1
  485. | BGFX_STENCIL_FUNC_RMASK(0xff)
  486. | BGFX_STENCIL_OP_FAIL_S_KEEP
  487. | BGFX_STENCIL_OP_FAIL_Z_KEEP
  488. | BGFX_STENCIL_OP_PASS_Z_REPLACE // store the value
  489. , BGFX_STENCIL_NONE
  490. },
  491. { // ProjectionShadows_DrawDiffuse
  492. BGFX_STATE_RGB_WRITE
  493. | BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_ONE)
  494. | BGFX_STATE_DEPTH_TEST_EQUAL
  495. | BGFX_STATE_CULL_CCW
  496. | BGFX_STATE_MSAA
  497. , UINT32_MAX
  498. , BGFX_STENCIL_TEST_NOTEQUAL
  499. | BGFX_STENCIL_FUNC_REF(1)
  500. | BGFX_STENCIL_FUNC_RMASK(1)
  501. | BGFX_STENCIL_OP_FAIL_S_KEEP
  502. | BGFX_STENCIL_OP_FAIL_Z_KEEP
  503. | BGFX_STENCIL_OP_PASS_Z_KEEP
  504. , BGFX_STENCIL_NONE
  505. },
  506. { // Custom_BlendLightTexture
  507. BGFX_STATE_RGB_WRITE
  508. | BGFX_STATE_ALPHA_WRITE
  509. | BGFX_STATE_DEPTH_WRITE
  510. | BGFX_STATE_DEPTH_TEST_LESS
  511. | BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_SRC_COLOR, BGFX_STATE_BLEND_INV_SRC_COLOR)
  512. | BGFX_STATE_CULL_CCW
  513. | BGFX_STATE_MSAA
  514. , UINT32_MAX
  515. , BGFX_STENCIL_NONE
  516. , BGFX_STENCIL_NONE
  517. },
  518. { // Custom_DrawPlaneBottom
  519. BGFX_STATE_RGB_WRITE
  520. | BGFX_STATE_CULL_CW
  521. | BGFX_STATE_MSAA
  522. , UINT32_MAX
  523. , BGFX_STENCIL_NONE
  524. , BGFX_STENCIL_NONE
  525. },
  526. };
  527. struct ViewState
  528. {
  529. ViewState(uint32_t _width = 1280, uint32_t _height = 720)
  530. : m_width(_width)
  531. , m_height(_height)
  532. {
  533. }
  534. uint32_t m_width;
  535. uint32_t m_height;
  536. float m_view[16];
  537. float m_proj[16];
  538. };
  539. struct ClearValues
  540. {
  541. ClearValues(uint32_t _clearRgba = 0x30303000
  542. , float _clearDepth = 1.0f
  543. , uint8_t _clearStencil = 0
  544. )
  545. : m_clearRgba(_clearRgba)
  546. , m_clearDepth(_clearDepth)
  547. , m_clearStencil(_clearStencil)
  548. { }
  549. uint32_t m_clearRgba;
  550. float m_clearDepth;
  551. uint8_t m_clearStencil;
  552. };
  553. void clearView(uint8_t _id, uint8_t _flags, const ClearValues& _clearValues)
  554. {
  555. bgfx::setViewClear(_id
  556. , _flags
  557. , _clearValues.m_clearRgba
  558. , _clearValues.m_clearDepth
  559. , _clearValues.m_clearStencil
  560. );
  561. // Keep track of cleared views
  562. s_clearMask |= 1 << _id;
  563. }
  564. void clearViewMask(uint32_t _viewMask, uint8_t _flags, const ClearValues& _clearValues)
  565. {
  566. bgfx::setViewClearMask(_viewMask
  567. , _flags
  568. , _clearValues.m_clearRgba
  569. , _clearValues.m_clearDepth
  570. , _clearValues.m_clearStencil
  571. );
  572. // Keep track of cleared views
  573. s_clearMask |= _viewMask;
  574. }
  575. void submit(uint8_t _id, int32_t _depth = 0)
  576. {
  577. // Submit
  578. bgfx::submit(_id, _depth);
  579. // Keep track of submited view ids
  580. s_viewMask |= 1 << _id;
  581. }
  582. void submitMask(uint32_t _viewMask, int32_t _depth = 0)
  583. {
  584. // Submit
  585. bgfx::submitMask(_viewMask, _depth);
  586. // Keep track of submited view ids
  587. s_viewMask |= _viewMask;
  588. }
  589. struct Aabb
  590. {
  591. float m_min[3];
  592. float m_max[3];
  593. };
  594. struct Obb
  595. {
  596. float m_mtx[16];
  597. };
  598. struct Sphere
  599. {
  600. float m_center[3];
  601. float m_radius;
  602. };
  603. struct Primitive
  604. {
  605. uint32_t m_startIndex;
  606. uint32_t m_numIndices;
  607. uint32_t m_startVertex;
  608. uint32_t m_numVertices;
  609. Sphere m_sphere;
  610. Aabb m_aabb;
  611. Obb m_obb;
  612. };
  613. typedef std::vector<Primitive> PrimitiveArray;
  614. struct Group
  615. {
  616. Group()
  617. {
  618. reset();
  619. }
  620. void reset()
  621. {
  622. m_vbh.idx = bgfx::invalidHandle;
  623. m_ibh.idx = bgfx::invalidHandle;
  624. m_prims.clear();
  625. }
  626. bgfx::VertexBufferHandle m_vbh;
  627. bgfx::IndexBufferHandle m_ibh;
  628. Sphere m_sphere;
  629. Aabb m_aabb;
  630. Obb m_obb;
  631. PrimitiveArray m_prims;
  632. };
  633. struct Mesh
  634. {
  635. void load(const void* _vertices, uint32_t _numVertices, const bgfx::VertexDecl _decl
  636. , const uint16_t* _indices, uint32_t _numIndices)
  637. {
  638. Group group;
  639. const bgfx::Memory* mem;
  640. uint32_t size;
  641. size = _numVertices*_decl.getStride();
  642. mem = bgfx::makeRef(_vertices, size);
  643. group.m_vbh = bgfx::createVertexBuffer(mem, _decl);
  644. size = _numIndices*2;
  645. mem = bgfx::makeRef(_indices, size);
  646. group.m_ibh = bgfx::createIndexBuffer(mem);
  647. //TODO:
  648. // group.m_sphere = ...
  649. // group.m_aabb = ...
  650. // group.m_obb = ...
  651. // group.m_prims = ...
  652. m_groups.push_back(group);
  653. }
  654. void load(const char* _filePath)
  655. {
  656. #define BGFX_CHUNK_MAGIC_VB BX_MAKEFOURCC('V', 'B', ' ', 0x0)
  657. #define BGFX_CHUNK_MAGIC_IB BX_MAKEFOURCC('I', 'B', ' ', 0x0)
  658. #define BGFX_CHUNK_MAGIC_PRI BX_MAKEFOURCC('P', 'R', 'I', 0x0)
  659. bx::CrtFileReader reader;
  660. reader.open(_filePath);
  661. Group group;
  662. uint32_t chunk;
  663. while (4 == bx::read(&reader, chunk) )
  664. {
  665. switch (chunk)
  666. {
  667. case BGFX_CHUNK_MAGIC_VB:
  668. {
  669. bx::read(&reader, group.m_sphere);
  670. bx::read(&reader, group.m_aabb);
  671. bx::read(&reader, group.m_obb);
  672. bx::read(&reader, m_decl);
  673. uint16_t stride = m_decl.getStride();
  674. uint16_t numVertices;
  675. bx::read(&reader, numVertices);
  676. const bgfx::Memory* mem = bgfx::alloc(numVertices*stride);
  677. bx::read(&reader, mem->data, mem->size);
  678. group.m_vbh = bgfx::createVertexBuffer(mem, m_decl);
  679. }
  680. break;
  681. case BGFX_CHUNK_MAGIC_IB:
  682. {
  683. uint32_t numIndices;
  684. bx::read(&reader, numIndices);
  685. const bgfx::Memory* mem = bgfx::alloc(numIndices*2);
  686. bx::read(&reader, mem->data, mem->size);
  687. group.m_ibh = bgfx::createIndexBuffer(mem);
  688. }
  689. break;
  690. case BGFX_CHUNK_MAGIC_PRI:
  691. {
  692. uint16_t len;
  693. bx::read(&reader, len);
  694. std::string material;
  695. material.resize(len);
  696. bx::read(&reader, const_cast<char*>(material.c_str() ), len);
  697. uint16_t num;
  698. bx::read(&reader, num);
  699. for (uint32_t ii = 0; ii < num; ++ii)
  700. {
  701. bx::read(&reader, len);
  702. std::string name;
  703. name.resize(len);
  704. bx::read(&reader, const_cast<char*>(name.c_str() ), len);
  705. Primitive prim;
  706. bx::read(&reader, prim.m_startIndex);
  707. bx::read(&reader, prim.m_numIndices);
  708. bx::read(&reader, prim.m_startVertex);
  709. bx::read(&reader, prim.m_numVertices);
  710. bx::read(&reader, prim.m_sphere);
  711. bx::read(&reader, prim.m_aabb);
  712. bx::read(&reader, prim.m_obb);
  713. group.m_prims.push_back(prim);
  714. }
  715. m_groups.push_back(group);
  716. group.reset();
  717. }
  718. break;
  719. default:
  720. DBG("%08x at %d", chunk, reader.seek() );
  721. break;
  722. }
  723. }
  724. reader.close();
  725. }
  726. void unload()
  727. {
  728. for (GroupArray::const_iterator it = m_groups.begin(), itEnd = m_groups.end(); it != itEnd; ++it)
  729. {
  730. const Group& group = *it;
  731. bgfx::destroyVertexBuffer(group.m_vbh);
  732. if (bgfx::invalidHandle != group.m_ibh.idx)
  733. {
  734. bgfx::destroyIndexBuffer(group.m_ibh);
  735. }
  736. }
  737. m_groups.clear();
  738. }
  739. void submit(uint8_t _viewId, float* _mtx, bgfx::ProgramHandle _program, const RenderState& _renderState)
  740. {
  741. bgfx::TextureHandle texture = BGFX_INVALID_HANDLE;
  742. submit(_viewId, _mtx, _program, _renderState, texture);
  743. }
  744. void submit(uint8_t _viewId, float* _mtx, bgfx::ProgramHandle _program, const RenderState& _renderState, bgfx::TextureHandle _texture)
  745. {
  746. for (GroupArray::const_iterator it = m_groups.begin(), itEnd = m_groups.end(); it != itEnd; ++it)
  747. {
  748. const Group& group = *it;
  749. // Set uniforms
  750. s_uniforms.submitPerDrawUniforms();
  751. // Set model matrix for rendering.
  752. bgfx::setTransform(_mtx);
  753. bgfx::setProgram(_program);
  754. bgfx::setIndexBuffer(group.m_ibh);
  755. bgfx::setVertexBuffer(group.m_vbh);
  756. // Set texture
  757. if (bgfx::invalidHandle != _texture.idx)
  758. {
  759. bgfx::setTexture(0, u_texColor, _texture);
  760. }
  761. // Apply render state
  762. bgfx::setStencil(_renderState.m_fstencil, _renderState.m_bstencil);
  763. bgfx::setState(_renderState.m_state, _renderState.m_blendFactorRgba);
  764. // Submit
  765. ::submit(_viewId);
  766. }
  767. }
  768. bgfx::VertexDecl m_decl;
  769. typedef std::vector<Group> GroupArray;
  770. GroupArray m_groups;
  771. };
  772. int _main_(int /*_argc*/, char** /*_argv*/)
  773. {
  774. ViewState viewState(1280, 720);
  775. ClearValues clearValues(0x30303000, 1.0f, 0);
  776. uint32_t debug = BGFX_DEBUG_TEXT;
  777. uint32_t reset = BGFX_RESET_VSYNC;
  778. bgfx::init();
  779. bgfx::reset(viewState.m_width, viewState.m_height, reset);
  780. // Enable debug text.
  781. bgfx::setDebug(debug);
  782. // Setup root path for binary shaders. Shader binaries are different
  783. // for each renderer.
  784. switch (bgfx::getRendererType() )
  785. {
  786. default:
  787. case bgfx::RendererType::Direct3D9:
  788. s_shaderPath = "shaders/dx9/";
  789. break;
  790. case bgfx::RendererType::Direct3D11:
  791. s_shaderPath = "shaders/dx11/";
  792. break;
  793. case bgfx::RendererType::OpenGL:
  794. s_shaderPath = "shaders/glsl/";
  795. s_flipV = true;
  796. break;
  797. case bgfx::RendererType::OpenGLES:
  798. s_shaderPath = "shaders/gles/";
  799. s_flipV = true;
  800. break;
  801. }
  802. FILE* file = fopen("font/droidsans.ttf", "rb");
  803. uint32_t size = (uint32_t)fsize(file);
  804. void* data = malloc(size);
  805. size_t ignore = fread(data, 1, size, file);
  806. BX_UNUSED(ignore);
  807. fclose(file);
  808. imguiCreate(data);
  809. free(data);
  810. bgfx::VertexDecl PosNormalTexcoordDecl;
  811. PosNormalTexcoordDecl.begin();
  812. PosNormalTexcoordDecl.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float);
  813. PosNormalTexcoordDecl.add(bgfx::Attrib::Normal, 4, bgfx::AttribType::Uint8, true, true);
  814. PosNormalTexcoordDecl.add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float);
  815. PosNormalTexcoordDecl.end();
  816. s_uniforms.init();
  817. s_uniforms.submitConstUniforms();
  818. u_texColor = bgfx::createUniform("u_texColor", bgfx::UniformType::Uniform1iv);
  819. bgfx::ProgramHandle programTextureLightning = loadProgram("vs_stencil_texture_lightning", "fs_stencil_texture_lightning");
  820. bgfx::ProgramHandle programColorLightning = loadProgram("vs_stencil_color_lightning", "fs_stencil_color_lightning" );
  821. bgfx::ProgramHandle programColorTexture = loadProgram("vs_stencil_color_texture", "fs_stencil_color_texture" );
  822. bgfx::ProgramHandle programColorBlack = loadProgram("vs_stencil_color", "fs_stencil_color_black" );
  823. bgfx::ProgramHandle programTexture = loadProgram("vs_stencil_texture", "fs_stencil_texture" );
  824. Mesh bunnyMesh;
  825. Mesh columnMesh;
  826. Mesh cubeMesh;
  827. Mesh hplaneMesh;
  828. Mesh vplaneMesh;
  829. bunnyMesh.load("meshes/bunny.bin");
  830. columnMesh.load("meshes/column.bin");
  831. cubeMesh.load(s_cubeVertices, s_numCubeVertices, PosNormalTexcoordDecl, s_cubeIndices, s_numCubeIndices);
  832. hplaneMesh.load(s_hplaneVertices, s_numHPlaneVertices, PosNormalTexcoordDecl, s_planeIndices, s_numPlaneIndices);
  833. vplaneMesh.load(s_vplaneVertices, s_numVPlaneVertices, PosNormalTexcoordDecl, s_planeIndices, s_numPlaneIndices);
  834. const bgfx::Memory* mem;
  835. mem = loadTexture("figure-rgba.dds");
  836. bgfx::TextureHandle figureTex = bgfx::createTexture(mem);
  837. mem = loadTexture("flare.dds");
  838. bgfx::TextureHandle flareTex = bgfx::createTexture(mem);
  839. mem = loadTexture("fieldstone-rgba.dds");
  840. bgfx::TextureHandle fieldstoneTex = bgfx::createTexture(mem);
  841. // Setup lights.
  842. const uint8_t colorCount = 5;
  843. const float rgbInnerR[colorCount][4] =
  844. {
  845. { 1.0f, 0.7f, 0.2f, 0.0f }, //yellow
  846. { 0.7f, 0.2f, 1.0f, 0.0f }, //purple
  847. { 0.2f, 1.0f, 0.7f, 0.0f }, //cyan
  848. { 1.0f, 0.4f, 0.2f, 0.0f }, //orange
  849. { 0.7f, 0.7f, 0.7f, 0.0f }, //white
  850. };
  851. float lightRgbInnerR[MAX_NUM_LIGHTS][4];
  852. for (uint8_t ii = 0, jj = 0; ii < MAX_NUM_LIGHTS; ++ii, ++jj)
  853. {
  854. const uint8_t index = jj%colorCount;
  855. lightRgbInnerR[ii][0] = rgbInnerR[index][0];
  856. lightRgbInnerR[ii][1] = rgbInnerR[index][1];
  857. lightRgbInnerR[ii][2] = rgbInnerR[index][2];
  858. lightRgbInnerR[ii][3] = rgbInnerR[index][3];
  859. }
  860. memcpy(s_uniforms.m_lightRgbInnerR, lightRgbInnerR, MAX_NUM_LIGHTS * 4*sizeof(float));
  861. // Set view and projection matrices.
  862. const float aspect = float(viewState.m_width)/float(viewState.m_height);
  863. mtxProj(viewState.m_proj, 60.0f, aspect, 0.1f, 100.0f);
  864. float initialPos[3] = { 0.0f, 18.0f, -40.0f };
  865. cameraCreate();
  866. cameraSetPosition(initialPos);
  867. cameraSetVerticalAngle(-0.35f);
  868. cameraGetViewMtx(viewState.m_view);
  869. int64_t timeOffset = bx::getHPCounter();
  870. enum Scene
  871. {
  872. StencilReflectionScene = 0,
  873. ProjectionShadowsScene,
  874. };
  875. Scene scene = StencilReflectionScene;
  876. float settings_numLights = 4.0f;
  877. float settings_reflectionValue = 0.8f;
  878. bool settings_updateLights = true;
  879. bool settings_updateScene = true;
  880. static const char* titles[3] =
  881. {
  882. "Stencil Reflection Scene",
  883. "Projection Shadows Scene",
  884. };
  885. entry::MouseState mouseState;
  886. while (!entry::processEvents(viewState.m_width, viewState.m_height, debug, reset, &mouseState) )
  887. {
  888. imguiBeginFrame(mouseState.m_mx
  889. , mouseState.m_my
  890. , (mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0)
  891. | (mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0)
  892. , 0
  893. , viewState.m_width
  894. , viewState.m_height
  895. );
  896. static int32_t scrollArea = 0;
  897. imguiBeginScrollArea("Settings", viewState.m_width - 256 - 10, 10, 256, 215, &scrollArea);
  898. if (imguiCheck(titles[StencilReflectionScene], StencilReflectionScene == scene) )
  899. {
  900. scene = StencilReflectionScene;
  901. settings_numLights = 4.0f;
  902. }
  903. if (imguiCheck(titles[ProjectionShadowsScene], ProjectionShadowsScene == scene) )
  904. {
  905. scene = ProjectionShadowsScene;
  906. settings_numLights = 1.0f;
  907. }
  908. imguiSeparatorLine();
  909. imguiSlider("Lights", &settings_numLights, 1.0f, float(MAX_NUM_LIGHTS), 1.0f);
  910. if (scene == StencilReflectionScene)
  911. {
  912. imguiSlider("Reflection value", &settings_reflectionValue, 0.0f, 1.0f, 0.01f);
  913. }
  914. if (imguiCheck("Update lights", settings_updateLights) )
  915. {
  916. settings_updateLights = !settings_updateLights;
  917. }
  918. if (imguiCheck("Update scene", settings_updateScene) )
  919. {
  920. settings_updateScene = !settings_updateScene;
  921. }
  922. imguiEndScrollArea();
  923. imguiEndFrame();
  924. // Update settings.
  925. uint8_t numLights = (uint8_t)settings_numLights;
  926. s_uniforms.m_params.m_ambientPass = 1.0f;
  927. s_uniforms.m_params.m_lightningPass = 1.0f;
  928. s_uniforms.m_params.m_lightCount = settings_numLights;
  929. s_uniforms.m_params.m_lightIndex = 0.0f;
  930. s_uniforms.m_color[3] = settings_reflectionValue;
  931. s_uniforms.submitPerFrameUniforms();
  932. // Time.
  933. int64_t now = bx::getHPCounter();
  934. static int64_t last = now;
  935. const int64_t frameTime = now - last;
  936. last = now;
  937. const double freq = double(bx::getHPFrequency() );
  938. const double toMs = 1000.0/freq;
  939. float time = (float)( (now - timeOffset)/double(bx::getHPFrequency() ) );
  940. const float deltaTime = float(frameTime/freq);
  941. s_uniforms.m_time = time;
  942. // Use debug font to print information about this example.
  943. bgfx::dbgTextClear();
  944. bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/13-stencil");
  945. bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Stencil reflections and shadows.");
  946. bgfx::dbgTextPrintf(0, 3, 0x0f, "Frame: % 7.3f[ms]", double(frameTime)*toMs);
  947. // Update camera.
  948. cameraUpdate(deltaTime, mouseState.m_mx, mouseState.m_my, !!mouseState.m_buttons[entry::MouseButton::Right]);
  949. cameraGetViewMtx(viewState.m_view);
  950. static float lightTimeAccumulator = 0.0f;
  951. if (settings_updateLights)
  952. {
  953. lightTimeAccumulator += deltaTime;
  954. }
  955. static float sceneTimeAccumulator = 0.0f;
  956. if (settings_updateScene)
  957. {
  958. sceneTimeAccumulator += deltaTime;
  959. }
  960. float lightPosRadius[MAX_NUM_LIGHTS][4];
  961. const float radius = (scene == StencilReflectionScene) ? 15.0f : 25.0f;
  962. for (uint8_t ii = 0; ii < numLights; ++ii)
  963. {
  964. lightPosRadius[ii][0] = sin( (lightTimeAccumulator*1.1f + ii*0.03f + float(ii*M_PI_2)*1.07f ) )*20.0f;
  965. lightPosRadius[ii][1] = 8.0f + (1.0f - cos( (lightTimeAccumulator*1.5f + ii*0.29f + float(ii*M_PI_2)*1.49f ) ))*4.0f;
  966. lightPosRadius[ii][2] = cos( (lightTimeAccumulator*1.3f + ii*0.13f + float(ii*M_PI_2)*1.79f ) )*20.0f;
  967. lightPosRadius[ii][3] = radius;
  968. }
  969. memcpy(s_uniforms.m_lightPosRadius, lightPosRadius, numLights * 4*sizeof(float));
  970. // Floor position.
  971. float floorMtx[16];
  972. mtxScaleRotateTranslate(floorMtx
  973. , 20.0f //scaleX
  974. , 20.0f //scaleY
  975. , 20.0f //scaleZ
  976. , 0.0f //rotX
  977. , 0.0f //rotY
  978. , 0.0f //rotZ
  979. , 0.0f //translateX
  980. , 0.0f //translateY
  981. , 0.0f //translateZ
  982. );
  983. // Bunny position.
  984. float bunnyMtx[16];
  985. mtxScaleRotateTranslate(bunnyMtx
  986. , 5.0f
  987. , 5.0f
  988. , 5.0f
  989. , 0.0f
  990. , 1.56f - sceneTimeAccumulator
  991. , 0.0f
  992. , 0.0f
  993. , 2.0f
  994. , 0.0f
  995. );
  996. // Columns position.
  997. const float dist = 14.0f;
  998. const float columnPositions[4][3] =
  999. {
  1000. { dist, 0.0f, dist },
  1001. { -dist, 0.0f, dist },
  1002. { dist, 0.0f, -dist },
  1003. { -dist, 0.0f, -dist },
  1004. };
  1005. float columnMtx[4][16];
  1006. for (uint8_t ii = 0; ii < 4; ++ii)
  1007. {
  1008. mtxScaleRotateTranslate(columnMtx[ii]
  1009. , 1.0f
  1010. , 1.0f
  1011. , 1.0f
  1012. , 0.0f
  1013. , 0.0f
  1014. , 0.0f
  1015. , columnPositions[ii][0]
  1016. , columnPositions[ii][1]
  1017. , columnPositions[ii][2]
  1018. );
  1019. }
  1020. const uint8_t numCubes = 9;
  1021. float cubeMtx[numCubes][16];
  1022. for (uint16_t ii = 0; ii < numCubes; ++ii)
  1023. {
  1024. mtxScaleRotateTranslate(cubeMtx[ii]
  1025. , 1.0f
  1026. , 1.0f
  1027. , 1.0f
  1028. , 0.0f
  1029. , 0.0f
  1030. , 0.0f
  1031. , sin(ii * 2.0f + 13.0f - sceneTimeAccumulator) * 13.0f
  1032. , 4.0f
  1033. , cos(ii * 2.0f + 13.0f - sceneTimeAccumulator) * 13.0f
  1034. );
  1035. }
  1036. // Make sure at the beginning everything gets cleared.
  1037. clearView(0, BGFX_CLEAR_COLOR_BIT | BGFX_CLEAR_DEPTH_BIT | BGFX_CLEAR_STENCIL_BIT, clearValues);
  1038. submit(0);
  1039. // Bunny and columns color.
  1040. s_uniforms.m_color[0] = 0.70f;
  1041. s_uniforms.m_color[1] = 0.65f;
  1042. s_uniforms.m_color[2] = 0.60f;
  1043. switch (scene)
  1044. {
  1045. case StencilReflectionScene:
  1046. {
  1047. // First pass - Draw plane.
  1048. // Setup params for this scene.
  1049. s_uniforms.m_params.m_ambientPass = 1.0f;
  1050. s_uniforms.m_params.m_lightningPass = 1.0f;
  1051. // Floor.
  1052. hplaneMesh.submit(RENDER_VIEWID_RANGE1_PASS_0
  1053. , floorMtx
  1054. , programColorBlack
  1055. , s_renderStates[RenderState::StencilReflection_CraftStencil]
  1056. );
  1057. // Second pass - Draw reflected objects.
  1058. // Clear depth from previous pass.
  1059. clearView(RENDER_VIEWID_RANGE1_PASS_1, BGFX_CLEAR_DEPTH_BIT, clearValues);
  1060. // Compute reflected matrix.
  1061. float reflectMtx[16];
  1062. float plane_pos[3] = { 0.0f, 0.01f, 0.0f };
  1063. float normal[3] = { 0.0f, 1.0f, 0.0f };
  1064. mtxReflected(reflectMtx, plane_pos, normal);
  1065. // Reflect lights.
  1066. float reflectedLights[MAX_NUM_LIGHTS][4];
  1067. for (uint8_t ii = 0; ii < numLights; ++ii)
  1068. {
  1069. vec3MulMtx(reflectedLights[ii], lightPosRadius[ii], reflectMtx);
  1070. reflectedLights[ii][3] = lightPosRadius[ii][3];
  1071. }
  1072. memcpy(s_uniforms.m_lightPosRadius, reflectedLights, numLights * 4*sizeof(float));
  1073. // Reflect and submit bunny.
  1074. float mtxReflectedBunny[16];
  1075. mtxMul(mtxReflectedBunny, bunnyMtx, reflectMtx);
  1076. bunnyMesh.submit(RENDER_VIEWID_RANGE1_PASS_1
  1077. , mtxReflectedBunny
  1078. , programColorLightning
  1079. , s_renderStates[RenderState::StencilReflection_DrawReflected]
  1080. );
  1081. // Reflect and submit columns.
  1082. float mtxReflectedColumn[16];
  1083. for (uint8_t ii = 0; ii < 4; ++ii)
  1084. {
  1085. mtxMul(mtxReflectedColumn, columnMtx[ii], reflectMtx);
  1086. columnMesh.submit(RENDER_VIEWID_RANGE1_PASS_1
  1087. , mtxReflectedColumn
  1088. , programColorLightning
  1089. , s_renderStates[RenderState::StencilReflection_DrawReflected]
  1090. );
  1091. }
  1092. // Set lights back.
  1093. memcpy(s_uniforms.m_lightPosRadius, lightPosRadius, numLights * 4*sizeof(float));
  1094. // Third pass - Blend plane.
  1095. // Floor.
  1096. hplaneMesh.submit(RENDER_VIEWID_RANGE1_PASS_2
  1097. , floorMtx
  1098. , programTextureLightning
  1099. , s_renderStates[RenderState::StencilReflection_BlendPlane]
  1100. , fieldstoneTex
  1101. );
  1102. // Fourth pass - Draw everything else but the plane.
  1103. // Bunny.
  1104. bunnyMesh.submit(RENDER_VIEWID_RANGE1_PASS_3
  1105. , bunnyMtx
  1106. , programColorLightning
  1107. , s_renderStates[RenderState::StencilReflection_DrawScene]
  1108. );
  1109. // Columns.
  1110. for (uint8_t ii = 0; ii < 4; ++ii)
  1111. {
  1112. columnMesh.submit(RENDER_VIEWID_RANGE1_PASS_3
  1113. , columnMtx[ii]
  1114. , programColorLightning
  1115. , s_renderStates[RenderState::StencilReflection_DrawScene]
  1116. );
  1117. }
  1118. }
  1119. break;
  1120. case ProjectionShadowsScene:
  1121. {
  1122. // First pass - Draw entire scene. (ambient only).
  1123. s_uniforms.m_params.m_ambientPass = 1.0f;
  1124. s_uniforms.m_params.m_lightningPass = 0.0f;
  1125. // Bunny.
  1126. bunnyMesh.submit(RENDER_VIEWID_RANGE1_PASS_0
  1127. , bunnyMtx
  1128. , programColorLightning
  1129. , s_renderStates[RenderState::ProjectionShadows_DrawAmbient]
  1130. );
  1131. // Floor.
  1132. hplaneMesh.submit(RENDER_VIEWID_RANGE1_PASS_0
  1133. , floorMtx
  1134. , programTextureLightning
  1135. , s_renderStates[RenderState::ProjectionShadows_DrawAmbient]
  1136. , fieldstoneTex
  1137. );
  1138. // Cubes.
  1139. for (uint8_t ii = 0; ii < numCubes; ++ii)
  1140. {
  1141. cubeMesh.submit(RENDER_VIEWID_RANGE1_PASS_0
  1142. , cubeMtx[ii]
  1143. , programTextureLightning
  1144. , s_renderStates[RenderState::ProjectionShadows_DrawAmbient]
  1145. , figureTex
  1146. );
  1147. }
  1148. // Ground plane.
  1149. float ground[4];
  1150. float plane_pos[3] = { 0.0f, 0.0f, 0.0f };
  1151. float normal[3] = { 0.0f, 1.0f, 0.0f };
  1152. memcpy(ground, normal, sizeof(float) * 3);
  1153. ground[3] = -vec3Dot(plane_pos, normal) - 0.01f; // - 0.01 against z-fighting
  1154. for (uint8_t ii = 0, viewId = RENDER_VIEWID_RANGE5_PASS_6; ii < numLights; ++ii, ++viewId)
  1155. {
  1156. // Clear stencil for this light source.
  1157. clearView(viewId, BGFX_CLEAR_STENCIL_BIT, clearValues);
  1158. // Draw shadow projection of scene objects.
  1159. // Get homogeneous light pos.
  1160. float* lightPos = lightPosRadius[ii];
  1161. float pos[4];
  1162. memcpy(pos, lightPos, sizeof(float) * 3);
  1163. pos[3] = 1.0f;
  1164. // Calculate shadow mtx for current light.
  1165. float shadowMtx[16];
  1166. mtxShadow(shadowMtx, ground, pos);
  1167. // Submit bunny's shadow.
  1168. float mtxShadowedBunny[16];
  1169. mtxMul(mtxShadowedBunny, bunnyMtx, shadowMtx);
  1170. bunnyMesh.submit(viewId
  1171. , mtxShadowedBunny
  1172. , programColorBlack
  1173. , s_renderStates[RenderState::ProjectionShadows_CraftStencil]
  1174. );
  1175. // Submit cube shadows.
  1176. float mtxShadowedCube[16];
  1177. for (uint8_t jj = 0; jj < numCubes; ++jj)
  1178. {
  1179. mtxMul(mtxShadowedCube, cubeMtx[jj], shadowMtx);
  1180. cubeMesh.submit(viewId
  1181. , mtxShadowedCube
  1182. , programColorBlack
  1183. , s_renderStates[RenderState::ProjectionShadows_CraftStencil]
  1184. );
  1185. }
  1186. // Draw entire scene. (lightning pass only. blending is on)
  1187. s_uniforms.m_params.m_ambientPass = 0.0f;
  1188. s_uniforms.m_params.m_lightningPass = 1.0f;
  1189. s_uniforms.m_params.m_lightCount = 1.0f;
  1190. s_uniforms.m_params.m_lightIndex = float(ii);
  1191. // Bunny.
  1192. bunnyMesh.submit(viewId
  1193. , bunnyMtx
  1194. , programColorLightning
  1195. , s_renderStates[RenderState::ProjectionShadows_DrawDiffuse]
  1196. );
  1197. // Floor.
  1198. hplaneMesh.submit(viewId
  1199. , floorMtx
  1200. , programTextureLightning
  1201. , s_renderStates[RenderState::ProjectionShadows_DrawDiffuse]
  1202. , fieldstoneTex
  1203. );
  1204. // Cubes.
  1205. for (uint8_t ii = 0; ii < numCubes; ++ii)
  1206. {
  1207. cubeMesh.submit(viewId
  1208. , cubeMtx[ii]
  1209. , programTextureLightning
  1210. , s_renderStates[RenderState::ProjectionShadows_DrawDiffuse]
  1211. , figureTex
  1212. );
  1213. }
  1214. }
  1215. // Reset these to default..
  1216. s_uniforms.m_params.m_ambientPass = 1.0f;
  1217. s_uniforms.m_params.m_lightningPass = 1.0f;
  1218. }
  1219. break;
  1220. };
  1221. //lights
  1222. const float lightScale[3] = { 1.5f, 1.5f, 1.5f };
  1223. float lightMtx[16];
  1224. for (uint8_t ii = 0; ii < numLights; ++ii)
  1225. {
  1226. s_uniforms.m_color[0] = lightRgbInnerR[ii][0];
  1227. s_uniforms.m_color[1] = lightRgbInnerR[ii][1];
  1228. s_uniforms.m_color[2] = lightRgbInnerR[ii][2];
  1229. mtxBillboard(lightMtx, viewState.m_view, lightPosRadius[ii], lightScale);
  1230. vplaneMesh.submit(RENDER_VIEWID_RANGE1_PASS_7
  1231. , lightMtx
  1232. , programColorTexture
  1233. , s_renderStates[RenderState::Custom_BlendLightTexture]
  1234. , flareTex
  1235. );
  1236. }
  1237. // Draw floor bottom.
  1238. float floorBottomMtx[16];
  1239. mtxScaleRotateTranslate(floorBottomMtx
  1240. , 20.0f //scaleX
  1241. , 20.0f //scaleY
  1242. , 20.0f //scaleZ
  1243. , 0.0f //rotX
  1244. , 0.0f //rotY
  1245. , 0.0f //rotZ
  1246. , 0.0f //translateX
  1247. , -0.1f //translateY
  1248. , 0.0f //translateZ
  1249. );
  1250. hplaneMesh.submit(RENDER_VIEWID_RANGE1_PASS_7
  1251. , floorBottomMtx
  1252. , programTexture
  1253. , s_renderStates[RenderState::Custom_DrawPlaneBottom]
  1254. , figureTex
  1255. );
  1256. // Setup view rect and transform for all used views.
  1257. bgfx::setViewRectMask(s_viewMask, 0, 0, viewState.m_width, viewState.m_height);
  1258. bgfx::setViewTransformMask(s_viewMask, viewState.m_view, viewState.m_proj);
  1259. s_viewMask = 0;
  1260. // Advance to next frame. Rendering thread will be kicked to
  1261. // process submitted rendering primitives.
  1262. bgfx::frame();
  1263. //reset clear values on used views
  1264. clearViewMask(s_clearMask, BGFX_CLEAR_NONE, clearValues);
  1265. s_clearMask = 0;
  1266. }
  1267. // Cleanup.
  1268. bunnyMesh.unload();
  1269. columnMesh.unload();
  1270. cubeMesh.unload();
  1271. hplaneMesh.unload();
  1272. vplaneMesh.unload();
  1273. bgfx::destroyTexture(figureTex);
  1274. bgfx::destroyTexture(fieldstoneTex);
  1275. bgfx::destroyTexture(flareTex);
  1276. bgfx::destroyProgram(programTextureLightning);
  1277. bgfx::destroyProgram(programColorLightning);
  1278. bgfx::destroyProgram(programColorTexture);
  1279. bgfx::destroyProgram(programColorBlack);
  1280. bgfx::destroyProgram(programTexture);
  1281. bgfx::destroyUniform(u_texColor);
  1282. s_uniforms.destroy();
  1283. cameraDestroy();
  1284. imguiDestroy();
  1285. // Shutdown bgfx.
  1286. bgfx::shutdown();
  1287. return 0;
  1288. }