stencil.cpp 37 KB

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