shadowvolumes.cpp 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843
  1. /*
  2. * Copyright 2013-2014 Dario Manesku. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
  4. */
  5. #include <string>
  6. #include <vector>
  7. #include <map>
  8. #include <tinystl/allocator.h>
  9. #include <tinystl/unordered_map.h>
  10. namespace stl = tinystl;
  11. #include "common.h"
  12. #include "bgfx_utils.h"
  13. #include <bgfx/bgfx.h>
  14. #include <bx/timer.h>
  15. #include <bx/allocator.h>
  16. #include <bx/hash.h>
  17. #include <bx/simd_t.h>
  18. #include <bx/math.h>
  19. #include <bx/file.h>
  20. #include "entry/entry.h"
  21. #include "camera.h"
  22. #include "imgui/imgui.h"
  23. namespace bgfx
  24. {
  25. int32_t read(bx::ReaderI* _reader, bgfx::VertexLayout& _layout, bx::Error* _err = NULL);
  26. }
  27. namespace
  28. {
  29. #define SV_USE_SIMD 1
  30. #define MAX_INSTANCE_COUNT 25
  31. #define MAX_LIGHTS_COUNT 5
  32. #define VIEWID_RANGE1_PASS0 1
  33. #define VIEWID_RANGE1_RT_PASS1 2
  34. #define VIEWID_RANGE15_PASS2 3
  35. #define VIEWID_RANGE1_PASS3 20
  36. struct PosNormalTexcoordVertex
  37. {
  38. float m_x;
  39. float m_y;
  40. float m_z;
  41. uint32_t m_normal;
  42. float m_u;
  43. float m_v;
  44. static void init()
  45. {
  46. ms_layout
  47. .begin()
  48. .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
  49. .add(bgfx::Attrib::Normal, 4, bgfx::AttribType::Uint8, true, true)
  50. .add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float)
  51. .end();
  52. }
  53. static bgfx::VertexLayout ms_layout;
  54. };
  55. bgfx::VertexLayout PosNormalTexcoordVertex::ms_layout;
  56. static const float s_texcoord = 50.0f;
  57. static PosNormalTexcoordVertex s_hplaneVertices[] =
  58. {
  59. { -1.0f, 0.0f, 1.0f, encodeNormalRgba8(0.0f, 1.0f, 0.0f), s_texcoord, s_texcoord },
  60. { 1.0f, 0.0f, 1.0f, encodeNormalRgba8(0.0f, 1.0f, 0.0f), s_texcoord, 0.0f },
  61. { -1.0f, 0.0f, -1.0f, encodeNormalRgba8(0.0f, 1.0f, 0.0f), 0.0f, s_texcoord },
  62. { 1.0f, 0.0f, -1.0f, encodeNormalRgba8(0.0f, 1.0f, 0.0f), 0.0f, 0.0f },
  63. };
  64. static PosNormalTexcoordVertex s_vplaneVertices[] =
  65. {
  66. { -1.0f, 1.0f, 0.0f, encodeNormalRgba8(0.0f, 0.0f, -1.0f), 1.0f, 1.0f },
  67. { 1.0f, 1.0f, 0.0f, encodeNormalRgba8(0.0f, 0.0f, -1.0f), 1.0f, 0.0f },
  68. { -1.0f, -1.0f, 0.0f, encodeNormalRgba8(0.0f, 0.0f, -1.0f), 0.0f, 1.0f },
  69. { 1.0f, -1.0f, 0.0f, encodeNormalRgba8(0.0f, 0.0f, -1.0f), 0.0f, 0.0f },
  70. };
  71. static const uint16_t s_planeIndices[] =
  72. {
  73. 0, 1, 2,
  74. 1, 3, 2,
  75. };
  76. static bool s_oglNdc = false;
  77. static float s_texelHalf = 0.0f;
  78. static uint32_t s_viewMask = 0;
  79. static bgfx::UniformHandle s_texColor;
  80. static bgfx::UniformHandle s_texStencil;
  81. static bgfx::FrameBufferHandle s_stencilFb;
  82. void setViewClearMask(uint32_t _viewMask, uint8_t _flags, uint32_t _rgba, float _depth, uint8_t _stencil)
  83. {
  84. for (uint32_t view = 0, viewMask = _viewMask; 0 != viewMask; viewMask >>= 1, view += 1 )
  85. {
  86. const uint32_t ntz = bx::uint32_cnttz(viewMask);
  87. viewMask >>= ntz;
  88. view += ntz;
  89. bgfx::setViewClear( (uint8_t)view, _flags, _rgba, _depth, _stencil);
  90. }
  91. }
  92. void setViewTransformMask(uint32_t _viewMask, const void* _view, const void* _proj)
  93. {
  94. for (uint32_t view = 0, viewMask = _viewMask; 0 != viewMask; viewMask >>= 1, view += 1 )
  95. {
  96. const uint32_t ntz = bx::uint32_cnttz(viewMask);
  97. viewMask >>= ntz;
  98. view += ntz;
  99. bgfx::setViewTransform( (uint8_t)view, _view, _proj);
  100. }
  101. }
  102. void setViewRectMask(uint32_t _viewMask, uint16_t _x, uint16_t _y, uint16_t _width, uint16_t _height)
  103. {
  104. for (uint32_t view = 0, viewMask = _viewMask; 0 != viewMask; viewMask >>= 1, view += 1 )
  105. {
  106. const uint32_t ntz = bx::uint32_cnttz(viewMask);
  107. viewMask >>= ntz;
  108. view += ntz;
  109. bgfx::setViewRect( (uint8_t)view, _x, _y, _width, _height);
  110. }
  111. }
  112. void mtxBillboard(
  113. float* _result
  114. , const float* _view
  115. , const float* _pos
  116. , const float* _scale
  117. )
  118. {
  119. _result[ 0] = _view[0] * _scale[0];
  120. _result[ 1] = _view[4] * _scale[0];
  121. _result[ 2] = _view[8] * _scale[0];
  122. _result[ 3] = 0.0f;
  123. _result[ 4] = _view[1] * _scale[1];
  124. _result[ 5] = _view[5] * _scale[1];
  125. _result[ 6] = _view[9] * _scale[1];
  126. _result[ 7] = 0.0f;
  127. _result[ 8] = _view[2] * _scale[2];
  128. _result[ 9] = _view[6] * _scale[2];
  129. _result[10] = _view[10] * _scale[2];
  130. _result[11] = 0.0f;
  131. _result[12] = _pos[0];
  132. _result[13] = _pos[1];
  133. _result[14] = _pos[2];
  134. _result[15] = 1.0f;
  135. }
  136. void planeNormal(
  137. float* _result
  138. , const float* _v0
  139. , const float* _v1
  140. , const float* _v2
  141. )
  142. {
  143. const bx::Vec3 v0 = bx::load<bx::Vec3>(_v0);
  144. const bx::Vec3 v1 = bx::load<bx::Vec3>(_v1);
  145. const bx::Vec3 v2 = bx::load<bx::Vec3>(_v2);
  146. const bx::Vec3 vec0 = bx::sub(v1, v0);
  147. const bx::Vec3 vec1 = bx::sub(v2, v1);
  148. const bx::Vec3 cross = bx::cross(vec0, vec1);
  149. bx::store(_result, bx::normalize(cross) );
  150. _result[3] = -bx::dot(bx::load<bx::Vec3>(_result), bx::load<bx::Vec3>(_v0) );
  151. }
  152. struct Uniforms
  153. {
  154. void init()
  155. {
  156. m_params.m_ambientPass = 1.0f;
  157. m_params.m_lightingPass = 1.0f;
  158. m_params.m_texelHalf = 0.0f;
  159. m_ambient[0] = 0.05f;
  160. m_ambient[1] = 0.05f;
  161. m_ambient[2] = 0.05f;
  162. m_ambient[3] = 0.0f; //unused
  163. m_diffuse[0] = 0.8f;
  164. m_diffuse[1] = 0.8f;
  165. m_diffuse[2] = 0.8f;
  166. m_diffuse[3] = 0.0f; //unused
  167. m_specular_shininess[0] = 1.0f;
  168. m_specular_shininess[1] = 1.0f;
  169. m_specular_shininess[2] = 1.0f;
  170. m_specular_shininess[3] = 25.0f; //shininess
  171. m_fog[0] = 0.0f; //color
  172. m_fog[1] = 0.0f;
  173. m_fog[2] = 0.0f;
  174. m_fog[3] = 0.0055f; //density
  175. m_color[0] = 1.0f;
  176. m_color[1] = 1.0f;
  177. m_color[2] = 1.0f;
  178. m_color[3] = 1.0f;
  179. m_time = 0.0f;
  180. m_lightPosRadius[0] = 0.0f;
  181. m_lightPosRadius[1] = 0.0f;
  182. m_lightPosRadius[2] = 0.0f;
  183. m_lightPosRadius[3] = 1.0f;
  184. m_lightRgbInnerR[0] = 0.0f;
  185. m_lightRgbInnerR[1] = 0.0f;
  186. m_lightRgbInnerR[2] = 0.0f;
  187. m_lightRgbInnerR[3] = 1.0f;
  188. m_virtualLightPos_extrusionDist[0] = 0.0f;
  189. m_virtualLightPos_extrusionDist[1] = 0.0f;
  190. m_virtualLightPos_extrusionDist[2] = 0.0f;
  191. m_virtualLightPos_extrusionDist[3] = 100.0f;
  192. u_params = bgfx::createUniform("u_params", bgfx::UniformType::Vec4);
  193. u_svparams = bgfx::createUniform("u_svparams", bgfx::UniformType::Vec4);
  194. u_ambient = bgfx::createUniform("u_ambient", bgfx::UniformType::Vec4);
  195. u_diffuse = bgfx::createUniform("u_diffuse", bgfx::UniformType::Vec4);
  196. u_specular_shininess = bgfx::createUniform("u_specular_shininess", bgfx::UniformType::Vec4);
  197. u_fog = bgfx::createUniform("u_fog", bgfx::UniformType::Vec4);
  198. u_color = bgfx::createUniform("u_color", bgfx::UniformType::Vec4);
  199. u_lightPosRadius = bgfx::createUniform("u_lightPosRadius", bgfx::UniformType::Vec4);
  200. u_lightRgbInnerR = bgfx::createUniform("u_lightRgbInnerR", bgfx::UniformType::Vec4);
  201. u_virtualLightPos_extrusionDist = bgfx::createUniform("u_virtualLightPos_extrusionDist", bgfx::UniformType::Vec4);
  202. }
  203. //call this once at initialization
  204. void submitConstUniforms()
  205. {
  206. bgfx::setUniform(u_ambient, &m_ambient);
  207. bgfx::setUniform(u_diffuse, &m_diffuse);
  208. bgfx::setUniform(u_specular_shininess, &m_specular_shininess);
  209. bgfx::setUniform(u_fog, &m_fog);
  210. }
  211. //call this before each draw call
  212. void submitPerDrawUniforms()
  213. {
  214. bgfx::setUniform(u_params, &m_params);
  215. bgfx::setUniform(u_svparams, &m_svparams);
  216. bgfx::setUniform(u_color, &m_color);
  217. bgfx::setUniform(u_lightPosRadius, &m_lightPosRadius);
  218. bgfx::setUniform(u_lightRgbInnerR, &m_lightRgbInnerR);
  219. bgfx::setUniform(u_virtualLightPos_extrusionDist, &m_virtualLightPos_extrusionDist);
  220. }
  221. void destroy()
  222. {
  223. bgfx::destroy(u_params);
  224. bgfx::destroy(u_svparams);
  225. bgfx::destroy(u_ambient);
  226. bgfx::destroy(u_diffuse);
  227. bgfx::destroy(u_specular_shininess);
  228. bgfx::destroy(u_fog);
  229. bgfx::destroy(u_color);
  230. bgfx::destroy(u_lightPosRadius);
  231. bgfx::destroy(u_lightRgbInnerR);
  232. bgfx::destroy(u_virtualLightPos_extrusionDist);
  233. }
  234. struct Params
  235. {
  236. float m_ambientPass;
  237. float m_lightingPass;
  238. float m_texelHalf;
  239. float m_unused00;
  240. };
  241. struct SvParams
  242. {
  243. float m_useStencilTex;
  244. float m_dfail;
  245. float m_unused10;
  246. float m_unused11;
  247. };
  248. Params m_params;
  249. SvParams m_svparams;
  250. float m_ambient[4];
  251. float m_diffuse[4];
  252. float m_specular_shininess[4];
  253. float m_fog[4];
  254. float m_color[4];
  255. float m_time;
  256. float m_lightPosRadius[4];
  257. float m_lightRgbInnerR[4];
  258. float m_virtualLightPos_extrusionDist[4];
  259. /**
  260. * u_params.x - u_ambientPass
  261. * u_params.y - u_lightingPass
  262. * u_params.z - u_texelHalf
  263. * u_params.w - unused
  264. * u_svparams.x - u_useStencilTex
  265. * u_svparams.y - u_dfail
  266. * u_svparams.z - unused
  267. * u_svparams.w - unused
  268. */
  269. bgfx::UniformHandle u_params;
  270. bgfx::UniformHandle u_svparams;
  271. bgfx::UniformHandle u_ambient;
  272. bgfx::UniformHandle u_diffuse;
  273. bgfx::UniformHandle u_specular_shininess;
  274. bgfx::UniformHandle u_fog;
  275. bgfx::UniformHandle u_color;
  276. bgfx::UniformHandle u_lightPosRadius;
  277. bgfx::UniformHandle u_lightRgbInnerR;
  278. bgfx::UniformHandle u_virtualLightPos_extrusionDist;
  279. };
  280. static Uniforms s_uniforms;
  281. struct RenderState
  282. {
  283. enum Enum
  284. {
  285. ShadowVolume_UsingStencilTexture_DrawAmbient = 0,
  286. ShadowVolume_UsingStencilTexture_BuildDepth,
  287. ShadowVolume_UsingStencilTexture_CraftStencil_DepthPass,
  288. ShadowVolume_UsingStencilTexture_CraftStencil_DepthFail,
  289. ShadowVolume_UsingStencilTexture_DrawDiffuse,
  290. ShadowVolume_UsingStencilBuffer_DrawAmbient,
  291. ShadowVolume_UsingStencilBuffer_CraftStencil_DepthPass,
  292. ShadowVolume_UsingStencilBuffer_CraftStencil_DepthFail,
  293. ShadowVolume_UsingStencilBuffer_DrawDiffuse,
  294. Custom_Default,
  295. Custom_BlendLightTexture,
  296. Custom_DrawPlaneBottom,
  297. Custom_DrawShadowVolume_Lines,
  298. Count
  299. };
  300. uint64_t m_state;
  301. uint32_t m_blendFactorRgba;
  302. uint32_t m_fstencil;
  303. uint32_t m_bstencil;
  304. };
  305. static void setRenderState(const RenderState& _renderState)
  306. {
  307. bgfx::setStencil(_renderState.m_fstencil, _renderState.m_bstencil);
  308. bgfx::setState(_renderState.m_state, _renderState.m_blendFactorRgba);
  309. }
  310. static RenderState s_renderStates[RenderState::Count] =
  311. {
  312. { // ShadowVolume_UsingStencilTexture_DrawAmbient
  313. BGFX_STATE_WRITE_RGB
  314. | BGFX_STATE_WRITE_A
  315. | BGFX_STATE_WRITE_Z
  316. | BGFX_STATE_DEPTH_TEST_LESS
  317. | BGFX_STATE_CULL_CCW
  318. | BGFX_STATE_MSAA
  319. , UINT32_MAX
  320. , BGFX_STENCIL_NONE
  321. , BGFX_STENCIL_NONE
  322. },
  323. { // ShadowVolume_UsingStencilTexture_BuildDepth
  324. BGFX_STATE_WRITE_Z
  325. | BGFX_STATE_DEPTH_TEST_LESS
  326. | BGFX_STATE_CULL_CCW
  327. | BGFX_STATE_MSAA
  328. , UINT32_MAX
  329. , BGFX_STENCIL_NONE
  330. , BGFX_STENCIL_NONE
  331. },
  332. { // ShadowVolume_UsingStencilTexture_CraftStencil_DepthPass
  333. BGFX_STATE_WRITE_RGB
  334. | BGFX_STATE_WRITE_A
  335. | BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_ONE)
  336. | BGFX_STATE_DEPTH_TEST_LEQUAL
  337. | BGFX_STATE_MSAA
  338. , UINT32_MAX
  339. , BGFX_STENCIL_NONE
  340. , BGFX_STENCIL_NONE
  341. },
  342. { // ShadowVolume_UsingStencilTexture_CraftStencil_DepthFail
  343. BGFX_STATE_WRITE_RGB
  344. | BGFX_STATE_WRITE_A
  345. | BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_ONE)
  346. | BGFX_STATE_DEPTH_TEST_GEQUAL
  347. | BGFX_STATE_MSAA
  348. , UINT32_MAX
  349. , BGFX_STENCIL_NONE
  350. , BGFX_STENCIL_NONE
  351. },
  352. { // ShadowVolume_UsingStencilTexture_DrawDiffuse
  353. BGFX_STATE_WRITE_RGB
  354. | BGFX_STATE_WRITE_A
  355. | BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_ONE)
  356. | BGFX_STATE_WRITE_Z
  357. | BGFX_STATE_DEPTH_TEST_EQUAL
  358. | BGFX_STATE_CULL_CCW
  359. | BGFX_STATE_MSAA
  360. , UINT32_MAX
  361. , BGFX_STENCIL_NONE
  362. , BGFX_STENCIL_NONE
  363. },
  364. { // ShadowVolume_UsingStencilBuffer_DrawAmbient
  365. BGFX_STATE_WRITE_RGB
  366. | BGFX_STATE_WRITE_A
  367. | BGFX_STATE_WRITE_Z
  368. | BGFX_STATE_DEPTH_TEST_LESS
  369. | BGFX_STATE_CULL_CCW
  370. | BGFX_STATE_MSAA
  371. , UINT32_MAX
  372. , BGFX_STENCIL_NONE
  373. , BGFX_STENCIL_NONE
  374. },
  375. { // ShadowVolume_UsingStencilBuffer_CraftStencil_DepthPass
  376. BGFX_STATE_DEPTH_TEST_LEQUAL
  377. | BGFX_STATE_MSAA
  378. , UINT32_MAX
  379. , BGFX_STENCIL_TEST_ALWAYS
  380. | BGFX_STENCIL_FUNC_REF(1)
  381. | BGFX_STENCIL_FUNC_RMASK(0xff)
  382. | BGFX_STENCIL_OP_FAIL_S_KEEP
  383. | BGFX_STENCIL_OP_FAIL_Z_KEEP
  384. | BGFX_STENCIL_OP_PASS_Z_DECR
  385. , BGFX_STENCIL_TEST_ALWAYS
  386. | BGFX_STENCIL_FUNC_REF(1)
  387. | BGFX_STENCIL_FUNC_RMASK(0xff)
  388. | BGFX_STENCIL_OP_FAIL_S_KEEP
  389. | BGFX_STENCIL_OP_FAIL_Z_KEEP
  390. | BGFX_STENCIL_OP_PASS_Z_INCR
  391. },
  392. { // ShadowVolume_UsingStencilBuffer_CraftStencil_DepthFail
  393. BGFX_STATE_DEPTH_TEST_LEQUAL
  394. | BGFX_STATE_MSAA
  395. , UINT32_MAX
  396. , BGFX_STENCIL_TEST_ALWAYS
  397. | BGFX_STENCIL_FUNC_REF(1)
  398. | BGFX_STENCIL_FUNC_RMASK(0xff)
  399. | BGFX_STENCIL_OP_FAIL_S_KEEP
  400. | BGFX_STENCIL_OP_FAIL_Z_INCR
  401. | BGFX_STENCIL_OP_PASS_Z_KEEP
  402. , BGFX_STENCIL_TEST_ALWAYS
  403. | BGFX_STENCIL_FUNC_REF(1)
  404. | BGFX_STENCIL_FUNC_RMASK(0xff)
  405. | BGFX_STENCIL_OP_FAIL_S_KEEP
  406. | BGFX_STENCIL_OP_FAIL_Z_DECR
  407. | BGFX_STENCIL_OP_PASS_Z_KEEP
  408. },
  409. { // ShadowVolume_UsingStencilBuffer_DrawDiffuse
  410. BGFX_STATE_WRITE_RGB
  411. | BGFX_STATE_WRITE_A
  412. | BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_ONE)
  413. | BGFX_STATE_DEPTH_TEST_EQUAL
  414. | BGFX_STATE_CULL_CCW
  415. | BGFX_STATE_MSAA
  416. , UINT32_MAX
  417. , BGFX_STENCIL_TEST_EQUAL
  418. | BGFX_STENCIL_FUNC_REF(0)
  419. | BGFX_STENCIL_FUNC_RMASK(0xff)
  420. | BGFX_STENCIL_OP_FAIL_S_KEEP
  421. | BGFX_STENCIL_OP_FAIL_Z_KEEP
  422. | BGFX_STENCIL_OP_PASS_Z_KEEP
  423. , BGFX_STENCIL_NONE
  424. },
  425. { // Custom_Default
  426. BGFX_STATE_WRITE_RGB
  427. | BGFX_STATE_WRITE_A
  428. | BGFX_STATE_WRITE_Z
  429. | BGFX_STATE_DEPTH_TEST_LESS
  430. | BGFX_STATE_CULL_CCW
  431. | BGFX_STATE_MSAA
  432. , UINT32_MAX
  433. , BGFX_STENCIL_NONE
  434. , BGFX_STENCIL_NONE
  435. },
  436. { // Custom_BlendLightTexture
  437. BGFX_STATE_WRITE_RGB
  438. | BGFX_STATE_WRITE_A
  439. | BGFX_STATE_WRITE_Z
  440. | BGFX_STATE_DEPTH_TEST_LESS
  441. | BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_SRC_COLOR, BGFX_STATE_BLEND_INV_SRC_COLOR)
  442. | BGFX_STATE_CULL_CCW
  443. | BGFX_STATE_MSAA
  444. , UINT32_MAX
  445. , BGFX_STENCIL_NONE
  446. , BGFX_STENCIL_NONE
  447. },
  448. { // Custom_DrawPlaneBottom
  449. BGFX_STATE_WRITE_RGB
  450. | BGFX_STATE_WRITE_A
  451. | BGFX_STATE_WRITE_Z
  452. | BGFX_STATE_CULL_CW
  453. | BGFX_STATE_MSAA
  454. , UINT32_MAX
  455. , BGFX_STENCIL_NONE
  456. , BGFX_STENCIL_NONE
  457. },
  458. { // Custom_DrawShadowVolume_Lines
  459. BGFX_STATE_WRITE_RGB
  460. | BGFX_STATE_DEPTH_TEST_LESS
  461. | BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_FACTOR, BGFX_STATE_BLEND_SRC_ALPHA)
  462. | BGFX_STATE_PT_LINES
  463. | BGFX_STATE_MSAA
  464. , 0x0f0f0fff
  465. , BGFX_STENCIL_NONE
  466. , BGFX_STENCIL_NONE
  467. }
  468. };
  469. struct ViewState
  470. {
  471. ViewState(uint32_t _width = 0, uint32_t _height = 0)
  472. : m_width(_width)
  473. , m_height(_height)
  474. {
  475. }
  476. uint32_t m_width;
  477. uint32_t m_height;
  478. float m_view[16];
  479. float m_proj[16];
  480. };
  481. struct ClearValues
  482. {
  483. uint32_t m_clearRgba;
  484. float m_clearDepth;
  485. uint8_t m_clearStencil;
  486. };
  487. void submit(bgfx::ViewId _id, bgfx::ProgramHandle _handle, int32_t _depth = 0)
  488. {
  489. bgfx::submit(_id, _handle, _depth);
  490. // Keep track of submited view ids.
  491. s_viewMask |= 1 << _id;
  492. }
  493. void touch(bgfx::ViewId _id)
  494. {
  495. bgfx::ProgramHandle handle = BGFX_INVALID_HANDLE;
  496. ::submit(_id, handle);
  497. }
  498. struct Face
  499. {
  500. uint16_t m_i[3];
  501. float m_plane[4];
  502. };
  503. typedef std::vector<Face> FaceArray;
  504. struct Edge
  505. {
  506. bool m_faceReverseOrder[2];
  507. uint8_t m_faceIndex;
  508. uint16_t m_i0, m_i1;
  509. };
  510. struct Plane
  511. {
  512. float m_plane[4];
  513. };
  514. struct HalfEdge
  515. {
  516. #define INVALID_EDGE_INDEX UINT16_MAX
  517. uint16_t m_secondIndex;
  518. bool m_marked;
  519. };
  520. struct HalfEdges
  521. {
  522. HalfEdges()
  523. : m_data()
  524. , m_offsets()
  525. , m_endPtr()
  526. {
  527. }
  528. void init(uint16_t* _indices, uint32_t _numIndices)
  529. {
  530. m_data = (HalfEdge*)malloc(2 * _numIndices * sizeof(HalfEdge) );
  531. stl::unordered_map<uint16_t, std::vector<uint16_t> > edges;
  532. for (uint32_t ii = 0; ii < _numIndices; ii+=3)
  533. {
  534. uint16_t idx0 = _indices[ii];
  535. uint16_t idx1 = _indices[ii+1];
  536. uint16_t idx2 = _indices[ii+2];
  537. edges[idx0].push_back(idx1);
  538. edges[idx1].push_back(idx2);
  539. edges[idx2].push_back(idx0);
  540. }
  541. uint32_t numRows = (uint32_t)edges.size();
  542. m_offsets = (uint32_t*)malloc(numRows * sizeof(uint32_t) );
  543. HalfEdge* he = m_data;
  544. for (uint16_t ii = 0; ii < numRows; ++ii)
  545. {
  546. m_offsets[ii] = uint32_t(he - m_data);
  547. std::vector<uint16_t>& row = edges[ii];
  548. for (uint32_t jj = 0, size = (uint32_t)row.size(); jj < size; ++jj)
  549. {
  550. he->m_secondIndex = row[jj];
  551. he->m_marked = false;
  552. ++he;
  553. }
  554. he->m_secondIndex = INVALID_EDGE_INDEX;
  555. ++he;
  556. }
  557. he->m_secondIndex = 0;
  558. m_endPtr = he;
  559. }
  560. void destroy()
  561. {
  562. free(m_data);
  563. m_data = NULL;
  564. free(m_offsets);
  565. m_offsets = NULL;
  566. }
  567. void mark(uint16_t _firstIndex, uint16_t _secondIndex)
  568. {
  569. HalfEdge* ptr = &m_data[m_offsets[_firstIndex]];
  570. while (INVALID_EDGE_INDEX != ptr->m_secondIndex)
  571. {
  572. if (ptr->m_secondIndex == _secondIndex)
  573. {
  574. ptr->m_marked = true;
  575. break;
  576. }
  577. ++ptr;
  578. }
  579. }
  580. bool unmark(uint16_t _firstIndex, uint16_t _secondIndex)
  581. {
  582. bool ret = false;
  583. HalfEdge* ptr = &m_data[m_offsets[_firstIndex]];
  584. while (INVALID_EDGE_INDEX != ptr->m_secondIndex)
  585. {
  586. if (ptr->m_secondIndex == _secondIndex && ptr->m_marked)
  587. {
  588. ptr->m_marked = false;
  589. ret = true;
  590. break;
  591. }
  592. ++ptr;
  593. }
  594. return ret;
  595. }
  596. inline HalfEdge* begin() const
  597. {
  598. return m_data;
  599. }
  600. inline HalfEdge* end() const
  601. {
  602. return m_endPtr;
  603. }
  604. HalfEdge* m_data;
  605. uint32_t* m_offsets;
  606. HalfEdge* m_endPtr;
  607. };
  608. struct WeldedVertex
  609. {
  610. uint16_t m_v;
  611. bool m_welded;
  612. };
  613. inline float sqLength(const float _a[3], const float _b[3])
  614. {
  615. const float xx = _a[0] - _b[0];
  616. const float yy = _a[1] - _b[1];
  617. const float zz = _a[2] - _b[2];
  618. return xx*xx + yy*yy + zz*zz;
  619. }
  620. uint16_t weldVertices(WeldedVertex* _output, const bgfx::VertexLayout& _layout, const void* _data, uint16_t _num, float _epsilon)
  621. {
  622. const uint32_t hashSize = bx::uint32_nextpow2(_num);
  623. const uint32_t hashMask = hashSize-1;
  624. const float epsilonSq = _epsilon*_epsilon;
  625. uint16_t numVertices = 0;
  626. const uint32_t size = sizeof(uint16_t)*(hashSize + _num);
  627. uint16_t* hashTable = (uint16_t*)alloca(size);
  628. bx::memSet(hashTable, 0xff, size);
  629. uint16_t* next = hashTable + hashSize;
  630. for (uint16_t ii = 0; ii < _num; ++ii)
  631. {
  632. float pos[4];
  633. vertexUnpack(pos, bgfx::Attrib::Position, _layout, _data, ii);
  634. uint32_t hashValue = bx::hash<bx::HashMurmur2A>(pos, 3*sizeof(float) ) & hashMask;
  635. uint16_t offset = hashTable[hashValue];
  636. for (; UINT16_MAX != offset; offset = next[offset])
  637. {
  638. float test[4];
  639. vertexUnpack(test, bgfx::Attrib::Position, _layout, _data, _output[offset].m_v);
  640. if (sqLength(test, pos) < epsilonSq)
  641. {
  642. _output[ii].m_v = _output[offset].m_v;
  643. _output[ii].m_welded = true;
  644. break;
  645. }
  646. }
  647. if (UINT16_MAX == offset)
  648. {
  649. _output[ii].m_v = ii;
  650. _output[ii].m_welded = false;
  651. next[ii] = hashTable[hashValue];
  652. hashTable[hashValue] = ii;
  653. numVertices++;
  654. }
  655. }
  656. return numVertices;
  657. }
  658. struct Group
  659. {
  660. Group()
  661. {
  662. reset();
  663. }
  664. void reset()
  665. {
  666. m_vbh.idx = bgfx::kInvalidHandle;
  667. m_ibh.idx = bgfx::kInvalidHandle;
  668. m_numVertices = 0;
  669. m_vertices = NULL;
  670. m_numIndices = 0;
  671. m_indices = NULL;
  672. m_numEdges = 0;
  673. m_edges = NULL;
  674. m_edgePlanesUnalignedPtr = NULL;
  675. m_prims.clear();
  676. }
  677. typedef struct { float f[6]; } f6_t;
  678. struct EdgeAndPlane
  679. {
  680. EdgeAndPlane(uint16_t _i0, uint16_t _i1)
  681. : m_faceIndex(0)
  682. , m_i0(_i0)
  683. , m_i1(_i1)
  684. {
  685. }
  686. bool m_faceReverseOrder[2];
  687. uint8_t m_faceIndex;
  688. uint16_t m_i0, m_i1;
  689. Plane m_plane[2];
  690. };
  691. void fillStructures(const bgfx::VertexLayout& _layout)
  692. {
  693. uint16_t stride = _layout.getStride();
  694. m_faces.clear();
  695. m_halfEdges.destroy();
  696. //Init halfedges.
  697. m_halfEdges.init(m_indices, m_numIndices);
  698. //Init faces and edges.
  699. m_faces.reserve(m_numIndices/3); //1 face = 3 indices
  700. m_edges = (Edge*)malloc(m_numIndices * sizeof(Edge) ); //1 triangle = 3 indices = 3 edges.
  701. m_edgePlanesUnalignedPtr = (Plane*)malloc(m_numIndices * sizeof(Plane) + 15);
  702. m_edgePlanes = (Plane*)bx::alignPtr(m_edgePlanesUnalignedPtr, 0, 16);
  703. typedef std::map<std::pair<uint16_t, uint16_t>, EdgeAndPlane> EdgeMap;
  704. EdgeMap edgeMap;
  705. //Get unique indices.
  706. WeldedVertex* uniqueVertices = (WeldedVertex*)malloc(m_numVertices*sizeof(WeldedVertex) );
  707. ::weldVertices(uniqueVertices, _layout, m_vertices, m_numVertices, 0.0001f);
  708. uint16_t* uniqueIndices = (uint16_t*)malloc(m_numIndices*sizeof(uint16_t) );
  709. for (uint32_t ii = 0; ii < m_numIndices; ++ii)
  710. {
  711. uint16_t index = m_indices[ii];
  712. if (uniqueVertices[index].m_welded)
  713. {
  714. uniqueIndices[ii] = uniqueVertices[index].m_v;
  715. }
  716. else
  717. {
  718. uniqueIndices[ii] = index;
  719. }
  720. }
  721. free(uniqueVertices);
  722. for (uint32_t ii = 0, size = m_numIndices/3; ii < size; ++ii)
  723. {
  724. const uint16_t* indices = &m_indices[ii*3];
  725. uint16_t i0 = indices[0];
  726. uint16_t i1 = indices[1];
  727. uint16_t i2 = indices[2];
  728. const float* v0 = (float*)&m_vertices[i0*stride];
  729. const float* v1 = (float*)&m_vertices[i1*stride];
  730. const float* v2 = (float*)&m_vertices[i2*stride];
  731. float plane[4];
  732. planeNormal(plane, v0, v2, v1);
  733. Face face;
  734. face.m_i[0] = i0;
  735. face.m_i[1] = i1;
  736. face.m_i[2] = i2;
  737. bx::memCopy(face.m_plane, plane, 4*sizeof(float) );
  738. m_faces.push_back(face);
  739. //Use unique indices for EdgeMap.
  740. const uint16_t* uindices = &uniqueIndices[ii*3];
  741. i0 = uindices[0];
  742. i1 = uindices[1];
  743. i2 = uindices[2];
  744. const uint16_t triangleEdge[3][2] =
  745. {
  746. { i0, i1 },
  747. { i1, i2 },
  748. { i2, i0 },
  749. };
  750. for (uint8_t jj = 0; jj < 3; ++jj)
  751. {
  752. const uint16_t ui0 = triangleEdge[jj][0];
  753. const uint16_t ui1 = triangleEdge[jj][1];
  754. std::pair<uint16_t, uint16_t> key = std::make_pair(ui0, ui1);
  755. std::pair<uint16_t, uint16_t> keyInv = std::make_pair(ui1, ui0);
  756. EdgeMap::iterator iter = edgeMap.find(keyInv);
  757. if (iter != edgeMap.end() )
  758. {
  759. EdgeAndPlane& ep = iter->second;
  760. bx::memCopy(ep.m_plane[ep.m_faceIndex].m_plane, plane, 4*sizeof(float) );
  761. ep.m_faceReverseOrder[ep.m_faceIndex] = true;
  762. }
  763. else
  764. {
  765. std::pair<EdgeMap::iterator, bool> result = edgeMap.insert(std::make_pair(key, EdgeAndPlane(ui0, ui1) ) );
  766. EdgeAndPlane& ep = result.first->second;
  767. bx::memCopy(ep.m_plane[ep.m_faceIndex].m_plane, plane, 4*sizeof(float) );
  768. ep.m_faceReverseOrder[ep.m_faceIndex] = false;
  769. ep.m_faceIndex++;
  770. }
  771. }
  772. }
  773. free(uniqueIndices);
  774. uint32_t index = 0;
  775. for (EdgeMap::const_iterator iter = edgeMap.begin(), end = edgeMap.end(); iter != end; ++iter)
  776. {
  777. Edge* edge = &m_edges[m_numEdges];
  778. Plane* plane = &m_edgePlanes[index];
  779. bx::memCopy(edge, iter->second.m_faceReverseOrder, sizeof(Edge) );
  780. bx::memCopy(plane, iter->second.m_plane, 2 * sizeof(Plane) );
  781. m_numEdges++;
  782. index += 2;
  783. }
  784. }
  785. void unload()
  786. {
  787. bgfx::destroy(m_vbh);
  788. if (bgfx::kInvalidHandle != m_ibh.idx)
  789. {
  790. bgfx::destroy(m_ibh);
  791. }
  792. free(m_vertices);
  793. m_vertices = NULL;
  794. free(m_indices);
  795. m_indices = NULL;
  796. free(m_edges);
  797. m_edges = NULL;
  798. free(m_edgePlanesUnalignedPtr);
  799. m_edgePlanesUnalignedPtr = NULL;
  800. m_halfEdges.destroy();
  801. }
  802. bgfx::VertexBufferHandle m_vbh;
  803. bgfx::IndexBufferHandle m_ibh;
  804. uint16_t m_numVertices;
  805. uint8_t* m_vertices;
  806. uint32_t m_numIndices;
  807. uint16_t* m_indices;
  808. bx::Sphere m_sphere;
  809. bx::Aabb m_aabb;
  810. bx::Obb m_obb;
  811. PrimitiveArray m_prims;
  812. uint32_t m_numEdges;
  813. Edge* m_edges;
  814. Plane* m_edgePlanesUnalignedPtr;
  815. Plane* m_edgePlanes;
  816. FaceArray m_faces;
  817. HalfEdges m_halfEdges;
  818. };
  819. typedef std::vector<Group> GroupArray;
  820. struct Mesh
  821. {
  822. void load(const void* _vertices, uint16_t _numVertices, const bgfx::VertexLayout _layout, const uint16_t* _indices, uint32_t _numIndices)
  823. {
  824. Group group;
  825. const bgfx::Memory* mem;
  826. uint32_t size;
  827. //vertices
  828. group.m_numVertices = _numVertices;
  829. size = _numVertices*_layout.getStride();
  830. group.m_vertices = (uint8_t*)malloc(size);
  831. bx::memCopy(group.m_vertices, _vertices, size);
  832. mem = bgfx::makeRef(group.m_vertices, size);
  833. group.m_vbh = bgfx::createVertexBuffer(mem, _layout);
  834. //indices
  835. group.m_numIndices = _numIndices;
  836. size = _numIndices*2;
  837. group.m_indices = (uint16_t*)malloc(size);
  838. bx::memCopy(group.m_indices, _indices, size);
  839. mem = bgfx::makeRef(group.m_indices, size);
  840. group.m_ibh = bgfx::createIndexBuffer(mem);
  841. m_groups.push_back(group);
  842. }
  843. void load(const char* _filePath)
  844. {
  845. ::Mesh* mesh = ::meshLoad(_filePath, true);
  846. m_layout = mesh->m_layout;
  847. uint16_t stride = m_layout.getStride();
  848. for (::GroupArray::iterator it = mesh->m_groups.begin(), itEnd = mesh->m_groups.end(); it != itEnd; ++it)
  849. {
  850. Group group;
  851. group.m_numVertices = it->m_numVertices;
  852. const uint32_t vertexSize = group.m_numVertices*stride;
  853. group.m_vertices = (uint8_t*)malloc(vertexSize);
  854. bx::memCopy(group.m_vertices, it->m_vertices, vertexSize);
  855. const bgfx::Memory* mem = bgfx::makeRef(group.m_vertices, vertexSize);
  856. group.m_vbh = bgfx::createVertexBuffer(mem, m_layout);
  857. group.m_numIndices = it->m_numIndices;
  858. const uint32_t indexSize = 2 * group.m_numIndices;
  859. group.m_indices = (uint16_t*)malloc(indexSize);
  860. bx::memCopy(group.m_indices, it->m_indices, indexSize);
  861. mem = bgfx::makeRef(group.m_indices, indexSize);
  862. group.m_ibh = bgfx::createIndexBuffer(mem);
  863. group.m_sphere = it->m_sphere;
  864. group.m_aabb = it->m_aabb;
  865. group.m_obb = it->m_obb;
  866. group.m_prims = it->m_prims;
  867. m_groups.push_back(group);
  868. }
  869. ::meshUnload(mesh);
  870. for (GroupArray::iterator it = m_groups.begin(), itEnd = m_groups.end(); it != itEnd; ++it)
  871. {
  872. it->fillStructures(m_layout);
  873. }
  874. }
  875. void unload()
  876. {
  877. for (GroupArray::iterator it = m_groups.begin(), itEnd = m_groups.end(); it != itEnd; ++it)
  878. {
  879. it->unload();
  880. }
  881. m_groups.clear();
  882. }
  883. bgfx::VertexLayout m_layout;
  884. GroupArray m_groups;
  885. };
  886. struct Model
  887. {
  888. Model()
  889. {
  890. m_program.idx = bgfx::kInvalidHandle;
  891. m_texture.idx = bgfx::kInvalidHandle;
  892. }
  893. void load(const void* _vertices, uint16_t _numVertices, const bgfx::VertexLayout _layout, const uint16_t* _indices, uint32_t _numIndices)
  894. {
  895. m_mesh.load(_vertices, _numVertices, _layout, _indices, _numIndices);
  896. }
  897. void load(const char* _meshFilePath)
  898. {
  899. m_mesh.load(_meshFilePath);
  900. }
  901. void unload()
  902. {
  903. m_mesh.unload();
  904. }
  905. void submit(uint8_t _viewId, float* _mtx, const RenderState& _renderState)
  906. {
  907. for (GroupArray::const_iterator it = m_mesh.m_groups.begin(), itEnd = m_mesh.m_groups.end(); it != itEnd; ++it)
  908. {
  909. const Group& group = *it;
  910. // Set uniforms
  911. s_uniforms.submitPerDrawUniforms();
  912. // Set transform
  913. bgfx::setTransform(_mtx);
  914. // Set buffers
  915. bgfx::setIndexBuffer(group.m_ibh);
  916. bgfx::setVertexBuffer(0, group.m_vbh);
  917. // Set textures
  918. if (bgfx::kInvalidHandle != m_texture.idx)
  919. {
  920. bgfx::setTexture(0, s_texColor, m_texture);
  921. }
  922. bgfx::setTexture(1, s_texStencil, bgfx::getTexture(s_stencilFb) );
  923. // Apply render state
  924. ::setRenderState(_renderState);
  925. // Submit
  926. ::submit(_viewId, m_program);
  927. }
  928. }
  929. Mesh m_mesh;
  930. bgfx::ProgramHandle m_program;
  931. bgfx::TextureHandle m_texture;
  932. };
  933. struct Instance
  934. {
  935. Instance()
  936. : m_svExtrusionDistance(150.0f)
  937. {
  938. m_color[0] = 1.0f;
  939. m_color[1] = 1.0f;
  940. m_color[2] = 1.0f;
  941. }
  942. void submit(uint8_t _viewId, const RenderState& _renderState)
  943. {
  944. bx::memCopy(s_uniforms.m_color, m_color, 3*sizeof(float) );
  945. float mtx[16];
  946. bx::mtxSRT(mtx
  947. , m_scale[0]
  948. , m_scale[1]
  949. , m_scale[2]
  950. , m_rotation[0]
  951. , m_rotation[1]
  952. , m_rotation[2]
  953. , m_pos[0]
  954. , m_pos[1]
  955. , m_pos[2]
  956. );
  957. BX_ASSERT(NULL != m_model, "Instance model cannot be NULL!");
  958. m_model->submit(_viewId, mtx, _renderState);
  959. }
  960. float m_scale[3];
  961. float m_rotation[3];
  962. float m_pos[3];
  963. float m_color[3];
  964. float m_svExtrusionDistance;
  965. Model* m_model;
  966. };
  967. #define SV_INSTANCE_MEM_SIZE (1500 << 10)
  968. #define SV_INSTANCE_COUNT ( (25 > MAX_INSTANCE_COUNT) ? 25 : MAX_INSTANCE_COUNT)
  969. #define SV_PAGE_SIZE (SV_INSTANCE_MEM_SIZE * SV_INSTANCE_COUNT * MAX_LIGHTS_COUNT)
  970. struct ShadowVolumeAllocator
  971. {
  972. ShadowVolumeAllocator()
  973. {
  974. m_mem = (uint8_t*)malloc(SV_PAGE_SIZE*2);
  975. m_ptr = m_mem;
  976. m_firstPage = true;
  977. }
  978. ~ShadowVolumeAllocator()
  979. {
  980. free(m_mem);
  981. }
  982. void* alloc(uint32_t _size)
  983. {
  984. void* ret = (void*)m_ptr;
  985. m_ptr += _size;
  986. BX_ASSERT(m_ptr - m_mem < (m_firstPage ? SV_PAGE_SIZE : 2 * SV_PAGE_SIZE), "Buffer overflow!");
  987. return ret;
  988. }
  989. void swap()
  990. {
  991. m_ptr = m_firstPage ? m_mem + SV_PAGE_SIZE : m_mem;
  992. m_firstPage = !m_firstPage;
  993. }
  994. uint8_t* m_mem;
  995. uint8_t* m_ptr;
  996. bool m_firstPage;
  997. };
  998. static ShadowVolumeAllocator s_svAllocator;
  999. struct ShadowVolumeImpl
  1000. {
  1001. enum Enum
  1002. {
  1003. DepthPass,
  1004. DepthFail,
  1005. };
  1006. };
  1007. struct ShadowVolumeAlgorithm
  1008. {
  1009. enum Enum
  1010. {
  1011. FaceBased,
  1012. EdgeBased,
  1013. };
  1014. };
  1015. struct ShadowVolume
  1016. {
  1017. bgfx::VertexBufferHandle m_vbSides;
  1018. bgfx::IndexBufferHandle m_ibSides;
  1019. bgfx::IndexBufferHandle m_ibFrontCap;
  1020. bgfx::IndexBufferHandle m_ibBackCap;
  1021. uint32_t m_numVertices;
  1022. uint32_t m_numIndices;
  1023. const float* m_mtx;
  1024. const float* m_lightPos;
  1025. bool m_cap;
  1026. };
  1027. void shadowVolumeLightTransform(
  1028. float* _outLightPos
  1029. , const float* _scale
  1030. , const float* _rotate
  1031. , const float* _translate
  1032. , const float* _lightPos // world pos
  1033. )
  1034. {
  1035. /**
  1036. * Instead of transforming all the vertices, transform light instead:
  1037. * mtx = pivotTranslate -> rotateZYX -> invScale
  1038. * light = mtx * origin
  1039. */
  1040. float pivot[16];
  1041. bx::mtxTranslate(pivot
  1042. , _lightPos[0] - _translate[0]
  1043. , _lightPos[1] - _translate[1]
  1044. , _lightPos[2] - _translate[2]
  1045. );
  1046. float mzyx[16];
  1047. bx::mtxRotateZYX(mzyx
  1048. , -_rotate[0]
  1049. , -_rotate[1]
  1050. , -_rotate[2]
  1051. );
  1052. float invScale[16];
  1053. bx::mtxScale(invScale
  1054. , 1.0f / _scale[0]
  1055. , 1.0f / _scale[1]
  1056. , 1.0f / _scale[2]
  1057. );
  1058. float tmp0[16];
  1059. bx::mtxMul(tmp0, pivot, mzyx);
  1060. float mtx[16];
  1061. bx::mtxMul(mtx, tmp0, invScale);
  1062. bx::store(_outLightPos, bx::mul({ 0.0f, 0.0f, 0.0f }, mtx) );
  1063. }
  1064. void shadowVolumeCreate(
  1065. ShadowVolume& _shadowVolume
  1066. , Group& _group
  1067. , uint16_t _stride
  1068. , const float* _mtx
  1069. , const float* _light // in model space
  1070. , ShadowVolumeImpl::Enum _impl = ShadowVolumeImpl::DepthPass
  1071. , ShadowVolumeAlgorithm::Enum _algo = ShadowVolumeAlgorithm::FaceBased
  1072. , bool _textureAsStencil = false
  1073. )
  1074. {
  1075. const uint8_t* vertices = _group.m_vertices;
  1076. const FaceArray& faces = _group.m_faces;
  1077. const Edge* edges = _group.m_edges;
  1078. const Plane* edgePlanes = _group.m_edgePlanes;
  1079. const uint32_t numEdges = _group.m_numEdges;
  1080. HalfEdges& halfEdges = _group.m_halfEdges;
  1081. struct VertexData
  1082. {
  1083. VertexData()
  1084. {
  1085. }
  1086. VertexData(const float* _v3, float _extrude = 0.0f, float _k = 1.0f)
  1087. {
  1088. bx::memCopy(m_v, _v3, 3*sizeof(float) );
  1089. m_extrude = _extrude;
  1090. m_k = _k;
  1091. }
  1092. float m_v[3];
  1093. float m_extrude;
  1094. float m_k;
  1095. };
  1096. bool cap = (ShadowVolumeImpl::DepthFail == _impl);
  1097. VertexData* verticesSide = (VertexData*) s_svAllocator.alloc(20000 * sizeof(VertexData) );
  1098. uint16_t* indicesSide = (uint16_t*) s_svAllocator.alloc(20000 * 3*sizeof(uint16_t) );
  1099. uint16_t* indicesFrontCap = 0;
  1100. uint16_t* indicesBackCap = 0;
  1101. if (cap)
  1102. {
  1103. indicesFrontCap = (uint16_t*)s_svAllocator.alloc(80000 * 3*sizeof(uint16_t) );
  1104. indicesBackCap = (uint16_t*)s_svAllocator.alloc(80000 * 3*sizeof(uint16_t) );
  1105. }
  1106. uint32_t vsideI = 0;
  1107. uint32_t sideI = 0;
  1108. uint32_t frontCapI = 0;
  1109. uint32_t backCapI = 0;
  1110. uint16_t indexSide = 0;
  1111. if (ShadowVolumeAlgorithm::FaceBased == _algo)
  1112. {
  1113. for (FaceArray::const_iterator iter = faces.begin(), end = faces.end(); iter != end; ++iter)
  1114. {
  1115. const Face& face = *iter;
  1116. bool frontFacing = false;
  1117. const float f = bx::dot(bx::load<bx::Vec3>(face.m_plane), bx::load<bx::Vec3>(_light) ) + face.m_plane[3];
  1118. if (f > 0.0f)
  1119. {
  1120. frontFacing = true;
  1121. uint16_t triangleEdges[3][2] =
  1122. {
  1123. { face.m_i[0], face.m_i[1] },
  1124. { face.m_i[1], face.m_i[2] },
  1125. { face.m_i[2], face.m_i[0] },
  1126. };
  1127. for (uint8_t ii = 0; ii < 3; ++ii)
  1128. {
  1129. uint16_t first = triangleEdges[ii][0];
  1130. uint16_t second = triangleEdges[ii][1];
  1131. if (!halfEdges.unmark(second, first) )
  1132. {
  1133. halfEdges.mark(first, second);
  1134. }
  1135. }
  1136. }
  1137. if (cap)
  1138. {
  1139. if (frontFacing)
  1140. {
  1141. indicesFrontCap[frontCapI++] = face.m_i[0];
  1142. indicesFrontCap[frontCapI++] = face.m_i[1];
  1143. indicesFrontCap[frontCapI++] = face.m_i[2];
  1144. }
  1145. else
  1146. {
  1147. indicesBackCap[backCapI++] = face.m_i[0];
  1148. indicesBackCap[backCapI++] = face.m_i[1];
  1149. indicesBackCap[backCapI++] = face.m_i[2];
  1150. }
  1151. /**
  1152. * if '_useFrontFacingFacesAsBackCap' is needed, implement it as such:
  1153. *
  1154. * bool condition0 = frontFacing && _useFrontFacingFacesAsBackCap;
  1155. * bool condition1 = !frontFacing && !_useFrontFacingFacesAsBackCap;
  1156. * if (condition0 || condition1)
  1157. * {
  1158. * indicesBackCap[backCapI++] = face.m_i[0];
  1159. * indicesBackCap[backCapI++] = face.m_i[1+condition0];
  1160. * indicesBackCap[backCapI++] = face.m_i[2-condition0];
  1161. * }
  1162. */
  1163. }
  1164. }
  1165. // Fill side arrays.
  1166. uint16_t firstIndex = 0;
  1167. HalfEdge* he = halfEdges.begin();
  1168. while (halfEdges.end() != he)
  1169. {
  1170. if (he->m_marked)
  1171. {
  1172. he->m_marked = false;
  1173. const float* v0 = (float*)&vertices[firstIndex*_stride];
  1174. const float* v1 = (float*)&vertices[he->m_secondIndex*_stride];
  1175. verticesSide[vsideI++] = VertexData(v0, 0.0f);
  1176. verticesSide[vsideI++] = VertexData(v0, 1.0f);
  1177. verticesSide[vsideI++] = VertexData(v1, 0.0f);
  1178. verticesSide[vsideI++] = VertexData(v1, 1.0f);
  1179. indicesSide[sideI++] = indexSide+0;
  1180. indicesSide[sideI++] = indexSide+1;
  1181. indicesSide[sideI++] = indexSide+2;
  1182. indicesSide[sideI++] = indexSide+2;
  1183. indicesSide[sideI++] = indexSide+1;
  1184. indicesSide[sideI++] = indexSide+3;
  1185. indexSide += 4;
  1186. }
  1187. ++he;
  1188. if (INVALID_EDGE_INDEX == he->m_secondIndex)
  1189. {
  1190. ++he;
  1191. ++firstIndex;
  1192. }
  1193. }
  1194. }
  1195. else // ShadowVolumeAlgorithm::EdgeBased:
  1196. {
  1197. {
  1198. uint32_t ii = 0;
  1199. #if SV_USE_SIMD
  1200. uint32_t numEdgesRounded = numEdges & (~0x1);
  1201. using namespace bx;
  1202. const simd128_t lx = simd_splat(_light[0]);
  1203. const simd128_t ly = simd_splat(_light[1]);
  1204. const simd128_t lz = simd_splat(_light[2]);
  1205. for (; ii < numEdgesRounded; ii+=2)
  1206. {
  1207. const Edge& edge0 = edges[ii];
  1208. const Edge& edge1 = edges[ii+1];
  1209. const Plane* edgePlane0 = &edgePlanes[ii*2];
  1210. const Plane* edgePlane1 = &edgePlanes[ii*2 + 2];
  1211. const simd128_t reverse =
  1212. simd_ild(edge0.m_faceReverseOrder[0]
  1213. , edge1.m_faceReverseOrder[0]
  1214. , edge0.m_faceReverseOrder[1]
  1215. , edge1.m_faceReverseOrder[1]
  1216. );
  1217. const simd128_t p00 = simd_ld(edgePlane0[0].m_plane);
  1218. const simd128_t p10 = simd_ld(edgePlane1[0].m_plane);
  1219. const simd128_t p01 = simd_ld(edgePlane0[1].m_plane);
  1220. const simd128_t p11 = simd_ld(edgePlane1[1].m_plane);
  1221. const simd128_t xxyy0 = simd_shuf_xAyB(p00, p01);
  1222. const simd128_t zzww0 = simd_shuf_zCwD(p00, p01);
  1223. const simd128_t xxyy1 = simd_shuf_xAyB(p10, p11);
  1224. const simd128_t zzww1 = simd_shuf_zCwD(p10, p11);
  1225. const simd128_t vX = simd_shuf_xAyB(xxyy0, xxyy1);
  1226. const simd128_t vY = simd_shuf_zCwD(xxyy0, xxyy1);
  1227. const simd128_t vZ = simd_shuf_xAyB(zzww0, zzww1);
  1228. const simd128_t vW = simd_shuf_zCwD(zzww0, zzww1);
  1229. const simd128_t r0 = simd_mul(vX, lx);
  1230. const simd128_t r1 = simd_mul(vY, ly);
  1231. const simd128_t r2 = simd_mul(vZ, lz);
  1232. const simd128_t dot = simd_add(r0, simd_add(r1, r2) );
  1233. const simd128_t f = simd_add(dot, vW);
  1234. const simd128_t zero = simd_zero();
  1235. const simd128_t mask = simd_cmpgt(f, zero);
  1236. const simd128_t onef = simd_splat(1.0f);
  1237. const simd128_t tmp0 = simd_and(mask, onef);
  1238. const simd128_t tmp1 = simd_ftoi(tmp0);
  1239. const simd128_t tmp2 = simd_xor(tmp1, reverse);
  1240. const simd128_t tmp3 = simd_sll(tmp2, 1);
  1241. const simd128_t onei = simd_isplat(1);
  1242. const simd128_t tmp4 = simd_isub(tmp3, onei);
  1243. BX_ALIGN_DECL_16(int32_t res[4]);
  1244. simd_st(&res, tmp4);
  1245. for (uint16_t jj = 0; jj < 2; ++jj)
  1246. {
  1247. int32_t kk = res[jj] + res[jj+2];
  1248. if (kk != 0)
  1249. {
  1250. float* v0 = (float*)&vertices[edges[ii+jj].m_i0*_stride];
  1251. float* v1 = (float*)&vertices[edges[ii+jj].m_i1*_stride];
  1252. verticesSide[vsideI++] = VertexData(v0, 0.0f, float(kk) );
  1253. verticesSide[vsideI++] = VertexData(v0, 1.0f, float(kk) );
  1254. verticesSide[vsideI++] = VertexData(v1, 0.0f, float(kk) );
  1255. verticesSide[vsideI++] = VertexData(v1, 1.0f, float(kk) );
  1256. kk = _textureAsStencil ? 1 : kk;
  1257. uint16_t winding = uint16_t(kk > 0);
  1258. for (int32_t ll = 0, end = abs(kk); ll < end; ++ll)
  1259. {
  1260. indicesSide[sideI++] = indexSide;
  1261. indicesSide[sideI++] = indexSide + 2 - winding;
  1262. indicesSide[sideI++] = indexSide + 1 + winding;
  1263. indicesSide[sideI++] = indexSide + 2;
  1264. indicesSide[sideI++] = indexSide + 3 - winding*2;
  1265. indicesSide[sideI++] = indexSide + 1 + winding*2;
  1266. }
  1267. indexSide += 4;
  1268. }
  1269. }
  1270. }
  1271. #endif
  1272. for (; ii < numEdges; ++ii)
  1273. {
  1274. const Edge& edge = edges[ii];
  1275. const Plane* edgePlane = &edgePlanes[ii*2];
  1276. int16_t s0 = ( (bx::dot(bx::load<bx::Vec3>(edgePlane[0].m_plane), bx::load<bx::Vec3>(_light) ) + edgePlane[0].m_plane[3]) > 0.0f) ^ edge.m_faceReverseOrder[0];
  1277. int16_t s1 = ( (bx::dot(bx::load<bx::Vec3>(edgePlane[1].m_plane), bx::load<bx::Vec3>(_light) ) + edgePlane[1].m_plane[3]) > 0.0f) ^ edge.m_faceReverseOrder[1];
  1278. int16_t kk = ( (s0 + s1) << 1) - 2;
  1279. if (kk != 0)
  1280. {
  1281. float* v0 = (float*)&vertices[edge.m_i0*_stride];
  1282. float* v1 = (float*)&vertices[edge.m_i1*_stride];
  1283. verticesSide[vsideI++] = VertexData(v0, 0.0f, kk);
  1284. verticesSide[vsideI++] = VertexData(v0, 1.0f, kk);
  1285. verticesSide[vsideI++] = VertexData(v1, 0.0f, kk);
  1286. verticesSide[vsideI++] = VertexData(v1, 1.0f, kk);
  1287. kk = _textureAsStencil ? 1 : kk;
  1288. uint16_t winding = uint16_t(kk > 0);
  1289. for (int32_t jj = 0, end = abs(kk); jj < end; ++jj)
  1290. {
  1291. indicesSide[sideI++] = indexSide;
  1292. indicesSide[sideI++] = indexSide + 2 - winding;
  1293. indicesSide[sideI++] = indexSide + 1 + winding;
  1294. indicesSide[sideI++] = indexSide + 2;
  1295. indicesSide[sideI++] = indexSide + 3 - winding*2;
  1296. indicesSide[sideI++] = indexSide + 1 + winding*2;
  1297. }
  1298. indexSide += 4;
  1299. }
  1300. }
  1301. }
  1302. if (cap)
  1303. {
  1304. // This could/should be done on GPU!
  1305. for (FaceArray::const_iterator iter = faces.begin(), end = faces.end(); iter != end; ++iter)
  1306. {
  1307. const Face& face = *iter;
  1308. const float f = bx::dot(bx::load<bx::Vec3>(face.m_plane), bx::load<bx::Vec3>(_light) ) + face.m_plane[3];
  1309. bool frontFacing = (f > 0.0f);
  1310. for (uint8_t ii = 0, num = 1 + uint8_t(!_textureAsStencil); ii < num; ++ii)
  1311. {
  1312. if (frontFacing)
  1313. {
  1314. indicesFrontCap[frontCapI++] = face.m_i[0];
  1315. indicesFrontCap[frontCapI++] = face.m_i[1];
  1316. indicesFrontCap[frontCapI++] = face.m_i[2];
  1317. }
  1318. else
  1319. {
  1320. indicesBackCap[backCapI++] = face.m_i[0];
  1321. indicesBackCap[backCapI++] = face.m_i[1];
  1322. indicesBackCap[backCapI++] = face.m_i[2];
  1323. }
  1324. }
  1325. }
  1326. }
  1327. }
  1328. bgfx::VertexLayout layout;
  1329. layout.begin()
  1330. .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
  1331. .add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float)
  1332. .end();
  1333. //fill the structure
  1334. _shadowVolume.m_numVertices = vsideI;
  1335. _shadowVolume.m_numIndices = sideI + frontCapI + backCapI;
  1336. _shadowVolume.m_mtx = _mtx;
  1337. _shadowVolume.m_lightPos = _light;
  1338. _shadowVolume.m_cap = cap;
  1339. const bgfx::Memory* mem;
  1340. //sides
  1341. uint32_t vsize = vsideI * 5*sizeof(float);
  1342. uint32_t isize = sideI * sizeof(uint16_t);
  1343. mem = bgfx::makeRef(verticesSide, vsize);
  1344. _shadowVolume.m_vbSides = bgfx::createVertexBuffer(mem, layout);
  1345. mem = bgfx::makeRef(indicesSide, isize);
  1346. _shadowVolume.m_ibSides = bgfx::createIndexBuffer(mem);
  1347. // bgfx::destroy*Buffer doesn't actually destroy buffers now.
  1348. // Instead, these bgfx::destroy*Buffer commands get queued to be executed after the end of the next frame.
  1349. bgfx::destroy(_shadowVolume.m_vbSides);
  1350. bgfx::destroy(_shadowVolume.m_ibSides);
  1351. if (cap)
  1352. {
  1353. //front cap
  1354. isize = frontCapI * sizeof(uint16_t);
  1355. mem = bgfx::makeRef(indicesFrontCap, isize);
  1356. _shadowVolume.m_ibFrontCap = bgfx::createIndexBuffer(mem);
  1357. //gets destroyed after the end of the next frame
  1358. bgfx::destroy(_shadowVolume.m_ibFrontCap);
  1359. //back cap
  1360. isize = backCapI * sizeof(uint16_t);
  1361. mem = bgfx::makeRef(indicesBackCap, isize);
  1362. _shadowVolume.m_ibBackCap = bgfx::createIndexBuffer(mem);
  1363. //gets destroyed after the end of the next frame
  1364. bgfx::destroy(_shadowVolume.m_ibBackCap);
  1365. }
  1366. }
  1367. void createNearClipVolume(
  1368. float* _outPlanes24f
  1369. , float* _lightPos
  1370. , float* _view
  1371. , float _fovy
  1372. , float _aspect
  1373. , float _near
  1374. )
  1375. {
  1376. float (*volumePlanes)[4] = (float(*)[4])_outPlanes24f;
  1377. float mtxViewInv[16];
  1378. float mtxViewTrans[16];
  1379. bx::mtxInverse(mtxViewInv, _view);
  1380. bx::mtxTranspose(mtxViewTrans, _view);
  1381. float lightPosV[4];
  1382. bx::vec4MulMtx(lightPosV, _lightPos, _view);
  1383. const float delta = 0.1f;
  1384. const float nearNormal[4] = { 0.0f, 0.0f, 1.0f, _near };
  1385. const float d = bx::dot(bx::load<bx::Vec3>(lightPosV), bx::load<bx::Vec3>(nearNormal) ) + lightPosV[3] * nearNormal[3];
  1386. // Light is:
  1387. // 1.0f - in front of near plane
  1388. // 0.0f - on the near plane
  1389. // -1.0f - behind near plane
  1390. const float lightSide = float( (d > delta) - (d < -delta) );
  1391. const float t = bx::tan(bx::toRad(_fovy)*0.5f) * _near;
  1392. const float b = -t;
  1393. const float r = t * _aspect;
  1394. const float l = -r;
  1395. const bx::Vec3 corners[4] =
  1396. {
  1397. bx::mul({ r, t, _near }, mtxViewInv),
  1398. bx::mul({ l, t, _near }, mtxViewInv),
  1399. bx::mul({ l, b, _near }, mtxViewInv),
  1400. bx::mul({ r, b, _near }, mtxViewInv),
  1401. };
  1402. float planeNormals[4][3];
  1403. for (uint8_t ii = 0; ii < 4; ++ii)
  1404. {
  1405. float* outNormal = planeNormals[ii];
  1406. float* outPlane = volumePlanes[ii];
  1407. const bx::Vec3 c0 = corners[ii];
  1408. const bx::Vec3 planeVec = bx::sub(c0, corners[(ii-1)&3]);
  1409. const bx::Vec3 light = bx::sub(bx::load<bx::Vec3>(_lightPos), bx::mul(c0, _lightPos[3]) );
  1410. const bx::Vec3 normal = bx::mul(bx::cross(planeVec, light), lightSide);
  1411. const float invLen = 1.0f / bx::sqrt(bx::dot(normal, normal) );
  1412. bx::store(outNormal, normal);
  1413. bx::store(outPlane, bx::mul(normal, invLen) );
  1414. outPlane[3] = -bx::dot(normal, c0) * invLen;
  1415. }
  1416. float nearPlaneV[4] =
  1417. {
  1418. 0.0f * lightSide,
  1419. 0.0f * lightSide,
  1420. 1.0f * lightSide,
  1421. _near * lightSide,
  1422. };
  1423. bx::vec4MulMtx(volumePlanes[4], nearPlaneV, mtxViewTrans);
  1424. float* lightPlane = volumePlanes[5];
  1425. const bx::Vec3 lightPlaneNormal = bx::sub(bx::mul({ 0.0f, 0.0f, -_near * lightSide }, mtxViewInv), bx::load<bx::Vec3>(_lightPos) );
  1426. float lenInv = 1.0f / bx::sqrt(bx::dot(lightPlaneNormal, lightPlaneNormal) );
  1427. lightPlane[0] = lightPlaneNormal.x * lenInv;
  1428. lightPlane[1] = lightPlaneNormal.y * lenInv;
  1429. lightPlane[2] = lightPlaneNormal.z * lenInv;
  1430. lightPlane[3] = -bx::dot(lightPlaneNormal, bx::load<bx::Vec3>(_lightPos) ) * lenInv;
  1431. }
  1432. bool clipTest(const float* _planes, uint8_t _planeNum, const Mesh& _mesh, const float* _scale, const float* _translate)
  1433. {
  1434. float (*volumePlanes)[4] = (float(*)[4])_planes;
  1435. float scale = bx::max(_scale[0], _scale[1], _scale[2]);
  1436. const GroupArray& groups = _mesh.m_groups;
  1437. for (GroupArray::const_iterator it = groups.begin(), itEnd = groups.end(); it != itEnd; ++it)
  1438. {
  1439. const Group& group = *it;
  1440. bx::Sphere sphere = group.m_sphere;
  1441. sphere.center.x = sphere.center.x * scale + _translate[0];
  1442. sphere.center.y = sphere.center.y * scale + _translate[1];
  1443. sphere.center.z = sphere.center.z * scale + _translate[2];
  1444. sphere.radius *= (scale+0.4f);
  1445. bool isInside = true;
  1446. for (uint8_t ii = 0; ii < _planeNum; ++ii)
  1447. {
  1448. const float* plane = volumePlanes[ii];
  1449. float positiveSide = bx::dot(bx::load<bx::Vec3>(plane), sphere.center ) + plane[3] + sphere.radius;
  1450. if (positiveSide < 0.0f)
  1451. {
  1452. isInside = false;
  1453. break;
  1454. }
  1455. }
  1456. if (isInside)
  1457. {
  1458. return true;
  1459. }
  1460. }
  1461. return false;
  1462. }
  1463. struct ShadowVolumeProgramType
  1464. {
  1465. enum Enum
  1466. {
  1467. Blank = 0,
  1468. Color,
  1469. Tex1,
  1470. Tex2,
  1471. Count
  1472. };
  1473. };
  1474. struct ShadowVolumePart
  1475. {
  1476. enum Enum
  1477. {
  1478. Back = 0,
  1479. Side,
  1480. Front,
  1481. Count
  1482. };
  1483. };
  1484. enum LightPattern
  1485. {
  1486. LightPattern0 = 0,
  1487. LightPattern1
  1488. };
  1489. enum MeshChoice
  1490. {
  1491. BunnyHighPoly = 0,
  1492. BunnyLowPoly
  1493. };
  1494. enum Scene
  1495. {
  1496. Scene0 = 0,
  1497. Scene1,
  1498. SceneCount
  1499. };
  1500. class ExampleShadowVolumes : public entry::AppI
  1501. {
  1502. public:
  1503. ExampleShadowVolumes(const char* _name, const char* _description, const char* _url)
  1504. : entry::AppI(_name, _description, _url)
  1505. {
  1506. }
  1507. void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
  1508. {
  1509. Args args(_argc, _argv);
  1510. m_viewState = ViewState(_width, _height);
  1511. m_clearValues = { 0x00000000, 1.0f, 0 };
  1512. m_debug = BGFX_DEBUG_TEXT;
  1513. m_reset = BGFX_RESET_VSYNC;
  1514. bgfx::Init init;
  1515. init.type = args.m_type;
  1516. init.vendorId = args.m_pciId;
  1517. init.resolution.width = m_viewState.m_width;
  1518. init.resolution.height = m_viewState.m_height;
  1519. init.resolution.reset = m_reset;
  1520. bgfx::init(init);
  1521. // Enable debug text.
  1522. bgfx::setDebug(m_debug);
  1523. const bgfx::Caps* caps = bgfx::getCaps();
  1524. s_oglNdc = caps->homogeneousDepth;
  1525. s_texelHalf = bgfx::RendererType::Direct3D9 == caps->rendererType ? 0.5f : 0.0f;
  1526. // Imgui
  1527. imguiCreate();
  1528. PosNormalTexcoordVertex::init();
  1529. s_uniforms.init();
  1530. m_figureTex = loadTexture("textures/figure-rgba.dds");
  1531. m_flareTex = loadTexture("textures/flare.dds");
  1532. m_fieldstoneTex = loadTexture("textures/fieldstone-rgba.dds");
  1533. bgfx::TextureHandle fbtextures[] =
  1534. {
  1535. bgfx::createTexture2D(uint16_t(m_viewState.m_width), uint16_t(m_viewState.m_height), false, 1, bgfx::TextureFormat::BGRA8, BGFX_SAMPLER_U_CLAMP | BGFX_SAMPLER_V_CLAMP | BGFX_TEXTURE_RT),
  1536. bgfx::createTexture2D(uint16_t(m_viewState.m_width), uint16_t(m_viewState.m_height), false, 1, bgfx::TextureFormat::D16, BGFX_TEXTURE_RT_WRITE_ONLY),
  1537. };
  1538. s_stencilFb = bgfx::createFrameBuffer(BX_COUNTOF(fbtextures), fbtextures, true);
  1539. s_texColor = bgfx::createUniform("s_texColor", bgfx::UniformType::Sampler);
  1540. s_texStencil = bgfx::createUniform("s_texStencil", bgfx::UniformType::Sampler);
  1541. m_programTextureLighting = loadProgram("vs_shadowvolume_texture_lighting", "fs_shadowvolume_texture_lighting");
  1542. m_programColorLighting = loadProgram("vs_shadowvolume_color_lighting", "fs_shadowvolume_color_lighting" );
  1543. m_programColorTexture = loadProgram("vs_shadowvolume_color_texture", "fs_shadowvolume_color_texture" );
  1544. m_programTexture = loadProgram("vs_shadowvolume_texture", "fs_shadowvolume_texture" );
  1545. m_programBackBlank = loadProgram("vs_shadowvolume_svback", "fs_shadowvolume_svbackblank" );
  1546. m_programSideBlank = loadProgram("vs_shadowvolume_svside", "fs_shadowvolume_svsideblank" );
  1547. m_programFrontBlank = loadProgram("vs_shadowvolume_svfront", "fs_shadowvolume_svfrontblank");
  1548. m_programBackColor = loadProgram("vs_shadowvolume_svback", "fs_shadowvolume_svbackcolor" );
  1549. m_programSideColor = loadProgram("vs_shadowvolume_svside", "fs_shadowvolume_svsidecolor" );
  1550. m_programFrontColor = loadProgram("vs_shadowvolume_svfront", "fs_shadowvolume_svfrontcolor");
  1551. m_programSideTex = loadProgram("vs_shadowvolume_svside", "fs_shadowvolume_svsidetex" );
  1552. m_programBackTex1 = loadProgram("vs_shadowvolume_svback", "fs_shadowvolume_svbacktex1" );
  1553. m_programBackTex2 = loadProgram("vs_shadowvolume_svback", "fs_shadowvolume_svbacktex2" );
  1554. m_programFrontTex1 = loadProgram("vs_shadowvolume_svfront", "fs_shadowvolume_svfronttex1" );
  1555. m_programFrontTex2 = loadProgram("vs_shadowvolume_svfront", "fs_shadowvolume_svfronttex2" );
  1556. bgfx::ProgramHandle svProgs[ShadowVolumeProgramType::Count][ShadowVolumePart::Count] =
  1557. {
  1558. { m_programBackBlank, m_programSideBlank, m_programFrontBlank }, // Blank
  1559. { m_programBackColor, m_programSideColor, m_programFrontColor }, // Color
  1560. { m_programBackTex1, m_programSideTex, m_programFrontTex1 }, // Tex1
  1561. { m_programBackTex2, m_programSideTex, m_programFrontTex2 }, // Tex2
  1562. };
  1563. bx::memCopy(m_svProgs, svProgs, sizeof(svProgs));
  1564. m_bunnyHighPolyModel.load("meshes/bunny_patched.bin");
  1565. m_bunnyHighPolyModel.m_program = m_programColorLighting;
  1566. m_bunnyLowPolyModel.load("meshes/bunny_decimated.bin");
  1567. m_bunnyLowPolyModel.m_program = m_programColorLighting;
  1568. m_columnModel.load("meshes/column.bin");
  1569. m_columnModel.m_program = m_programColorLighting;
  1570. m_platformModel.load("meshes/platform.bin");
  1571. m_platformModel.m_program = m_programTextureLighting;
  1572. m_platformModel.m_texture = m_figureTex;
  1573. m_cubeModel.load("meshes/cube.bin");
  1574. m_cubeModel.m_program = m_programTextureLighting;
  1575. m_cubeModel.m_texture = m_figureTex;
  1576. m_hplaneFieldModel.load(s_hplaneVertices
  1577. , BX_COUNTOF(s_hplaneVertices)
  1578. , PosNormalTexcoordVertex::ms_layout
  1579. , s_planeIndices
  1580. , BX_COUNTOF(s_planeIndices)
  1581. );
  1582. m_hplaneFieldModel.m_program = m_programTextureLighting;
  1583. m_hplaneFieldModel.m_texture = m_fieldstoneTex;
  1584. m_hplaneFigureModel.load(s_hplaneVertices
  1585. , BX_COUNTOF(s_hplaneVertices)
  1586. , PosNormalTexcoordVertex::ms_layout
  1587. , s_planeIndices
  1588. , BX_COUNTOF(s_planeIndices)
  1589. );
  1590. m_hplaneFigureModel.m_program = m_programTextureLighting;
  1591. m_hplaneFigureModel.m_texture = m_figureTex;
  1592. m_vplaneModel.load(s_vplaneVertices
  1593. , BX_COUNTOF(s_vplaneVertices)
  1594. , PosNormalTexcoordVertex::ms_layout
  1595. , s_planeIndices
  1596. , BX_COUNTOF(s_planeIndices)
  1597. );
  1598. m_vplaneModel.m_program = m_programColorTexture;
  1599. m_vplaneModel.m_texture = m_flareTex;
  1600. // Setup lights.
  1601. const float rgbInnerR[MAX_LIGHTS_COUNT][4] =
  1602. {
  1603. { 1.0f, 0.7f, 0.2f, 0.0f }, //yellow
  1604. { 0.7f, 0.2f, 1.0f, 0.0f }, //purple
  1605. { 0.2f, 1.0f, 0.7f, 0.0f }, //cyan
  1606. { 1.0f, 0.4f, 0.2f, 0.0f }, //orange
  1607. { 0.7f, 0.7f, 0.7f, 0.0f }, //white
  1608. };
  1609. for (uint8_t ii = 0, jj = 0; ii < MAX_LIGHTS_COUNT; ++ii, ++jj)
  1610. {
  1611. const uint8_t index = jj%MAX_LIGHTS_COUNT;
  1612. m_lightRgbInnerR[ii][0] = rgbInnerR[index][0];
  1613. m_lightRgbInnerR[ii][1] = rgbInnerR[index][1];
  1614. m_lightRgbInnerR[ii][2] = rgbInnerR[index][2];
  1615. m_lightRgbInnerR[ii][3] = rgbInnerR[index][3];
  1616. }
  1617. m_profTime = 0;
  1618. m_timeOffset = bx::getHPCounter();
  1619. m_numShadowVolumeVertices = 0;
  1620. m_numShadowVolumeIndices = 0;
  1621. m_oldWidth = 0;
  1622. m_oldHeight = 0;
  1623. // Imgui.
  1624. m_showHelp = false;
  1625. m_updateLights = true;
  1626. m_updateScene = true;
  1627. m_mixedSvImpl = true;
  1628. m_useStencilTexture = false;
  1629. m_drawShadowVolumes = false;
  1630. m_numLights = 1;
  1631. m_instanceCount = 9;
  1632. m_shadowVolumeImpl = ShadowVolumeImpl::DepthFail;
  1633. m_shadowVolumeAlgorithm = ShadowVolumeAlgorithm::EdgeBased;
  1634. m_lightPattern = LightPattern0;
  1635. m_currentMesh = BunnyLowPoly;
  1636. m_currentScene = Scene0;
  1637. // Set view matrix
  1638. cameraCreate();
  1639. cameraSetPosition({ 3.0f, 20.0f, -58.0f });
  1640. cameraSetVerticalAngle(-0.25f);
  1641. cameraGetViewMtx(m_viewState.m_view);
  1642. }
  1643. virtual int shutdown() override
  1644. {
  1645. // Cleanup
  1646. m_bunnyLowPolyModel.unload();
  1647. m_bunnyHighPolyModel.unload();
  1648. m_columnModel.unload();
  1649. m_cubeModel.unload();
  1650. m_platformModel.unload();
  1651. m_hplaneFieldModel.unload();
  1652. m_hplaneFigureModel.unload();
  1653. m_vplaneModel.unload();
  1654. s_uniforms.destroy();
  1655. bgfx::destroy(s_texColor);
  1656. bgfx::destroy(s_texStencil);
  1657. bgfx::destroy(s_stencilFb);
  1658. bgfx::destroy(m_figureTex);
  1659. bgfx::destroy(m_fieldstoneTex);
  1660. bgfx::destroy(m_flareTex);
  1661. bgfx::destroy(m_programTextureLighting);
  1662. bgfx::destroy(m_programColorLighting);
  1663. bgfx::destroy(m_programColorTexture);
  1664. bgfx::destroy(m_programTexture);
  1665. bgfx::destroy(m_programBackBlank);
  1666. bgfx::destroy(m_programSideBlank);
  1667. bgfx::destroy(m_programFrontBlank);
  1668. bgfx::destroy(m_programBackColor);
  1669. bgfx::destroy(m_programSideColor);
  1670. bgfx::destroy(m_programFrontColor);
  1671. bgfx::destroy(m_programSideTex);
  1672. bgfx::destroy(m_programBackTex1);
  1673. bgfx::destroy(m_programBackTex2);
  1674. bgfx::destroy(m_programFrontTex1);
  1675. bgfx::destroy(m_programFrontTex2);
  1676. cameraDestroy();
  1677. imguiDestroy();
  1678. // Shutdown bgfx.
  1679. bgfx::shutdown();
  1680. return 0;
  1681. }
  1682. bool update() override
  1683. {
  1684. if (!entry::processEvents(m_viewState.m_width, m_viewState.m_height, m_debug, m_reset, &m_mouseState) )
  1685. {
  1686. s_uniforms.submitConstUniforms();
  1687. // Set projection matrices.
  1688. const float fov = 60.0f;
  1689. const float aspect = float(m_viewState.m_width)/float(m_viewState.m_height);
  1690. const float nearPlane = 1.0f;
  1691. const float farPlane = 1000.0f;
  1692. // Respond properly on resize.
  1693. if (m_oldWidth != m_viewState.m_width
  1694. || m_oldHeight != m_viewState.m_height)
  1695. {
  1696. m_oldWidth = m_viewState.m_width;
  1697. m_oldHeight = m_viewState.m_height;
  1698. bgfx::destroy(s_stencilFb);
  1699. bgfx::TextureHandle fbtextures[] =
  1700. {
  1701. bgfx::createTexture2D(uint16_t(m_viewState.m_width), uint16_t(m_viewState.m_height), false, 1, bgfx::TextureFormat::BGRA8, BGFX_SAMPLER_U_CLAMP|BGFX_SAMPLER_V_CLAMP|BGFX_TEXTURE_RT),
  1702. bgfx::createTexture2D(uint16_t(m_viewState.m_width), uint16_t(m_viewState.m_height), false, 1, bgfx::TextureFormat::D16, BGFX_TEXTURE_RT_WRITE_ONLY)
  1703. };
  1704. s_stencilFb = bgfx::createFrameBuffer(BX_COUNTOF(fbtextures), fbtextures, true);
  1705. }
  1706. // Time.
  1707. int64_t now = bx::getHPCounter();
  1708. static int64_t last = now;
  1709. const int64_t frameTime = now - last;
  1710. last = now;
  1711. const double freq = double(bx::getHPFrequency() );
  1712. const double toMs = 1000.0/freq;
  1713. float time = (float)( (now - m_timeOffset)/double(bx::getHPFrequency() ) );
  1714. const float deltaTime = float(frameTime/freq);
  1715. s_uniforms.m_time = time;
  1716. // Update camera.
  1717. cameraUpdate(deltaTime, m_mouseState, ImGui::MouseOverArea() );
  1718. // Set view and projection matrix for view 0.
  1719. {
  1720. cameraGetViewMtx(m_viewState.m_view);
  1721. bx::mtxProj(m_viewState.m_proj, fov, aspect, nearPlane, farPlane, s_oglNdc);
  1722. }
  1723. imguiBeginFrame(
  1724. m_mouseState.m_mx
  1725. , m_mouseState.m_my
  1726. , (m_mouseState.m_buttons[entry::MouseButton::Left] ? IMGUI_MBUT_LEFT : 0)
  1727. | (m_mouseState.m_buttons[entry::MouseButton::Right] ? IMGUI_MBUT_RIGHT : 0)
  1728. | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  1729. , m_mouseState.m_mz
  1730. , uint16_t(m_viewState.m_width)
  1731. , uint16_t(m_viewState.m_height)
  1732. );
  1733. showExampleDialog(this);
  1734. ImGui::SetNextWindowPos(
  1735. ImVec2(m_viewState.m_width - 256.0f, 10.0f)
  1736. , ImGuiCond_FirstUseEver
  1737. );
  1738. ImGui::SetNextWindowSize(
  1739. ImVec2(256.0f, 700.0f)
  1740. , ImGuiCond_FirstUseEver
  1741. );
  1742. ImGui::Begin("Settings"
  1743. , NULL
  1744. , 0
  1745. );
  1746. const char* titles[2] =
  1747. {
  1748. "Scene 0",
  1749. "Scene 1",
  1750. };
  1751. if (ImGui::RadioButton(titles[Scene0], Scene0 == m_currentScene) )
  1752. {
  1753. m_currentScene = Scene0;
  1754. }
  1755. if (ImGui::RadioButton(titles[Scene1], Scene1 == m_currentScene) )
  1756. {
  1757. m_currentScene = Scene1;
  1758. }
  1759. ImGui::SliderInt("Lights", &m_numLights, 1, MAX_LIGHTS_COUNT);
  1760. ImGui::Checkbox("Update lights", &m_updateLights);
  1761. ImGui::Indent();
  1762. if (ImGui::RadioButton("Light pattern 0", LightPattern0 == m_lightPattern) )
  1763. {
  1764. m_lightPattern = LightPattern0;
  1765. }
  1766. if (ImGui::RadioButton("Light pattern 1", LightPattern1 == m_lightPattern) )
  1767. {
  1768. m_lightPattern = LightPattern1;
  1769. }
  1770. ImGui::Unindent();
  1771. if ( Scene0 == m_currentScene )
  1772. {
  1773. ImGui::Checkbox("Update scene", &m_updateScene);
  1774. }
  1775. ImGui::Separator();
  1776. ImGui::Text("Stencil buffer implementation:");
  1777. ImGui::Checkbox("Mixed", &m_mixedSvImpl);
  1778. if (!m_mixedSvImpl)
  1779. {
  1780. m_shadowVolumeImpl = (ImGui::RadioButton("Depth fail", ShadowVolumeImpl::DepthFail == m_shadowVolumeImpl) ? ShadowVolumeImpl::DepthFail : m_shadowVolumeImpl);
  1781. m_shadowVolumeImpl = (ImGui::RadioButton("Depth pass", ShadowVolumeImpl::DepthPass == m_shadowVolumeImpl) ? ShadowVolumeImpl::DepthPass : m_shadowVolumeImpl);
  1782. }
  1783. ImGui::Text("Shadow volume implementation:");
  1784. m_shadowVolumeAlgorithm = (ImGui::RadioButton("Face based impl.", ShadowVolumeAlgorithm::FaceBased == m_shadowVolumeAlgorithm) ? ShadowVolumeAlgorithm::FaceBased : m_shadowVolumeAlgorithm);
  1785. m_shadowVolumeAlgorithm = (ImGui::RadioButton("Edge based impl.", ShadowVolumeAlgorithm::EdgeBased == m_shadowVolumeAlgorithm) ? ShadowVolumeAlgorithm::EdgeBased : m_shadowVolumeAlgorithm);
  1786. ImGui::Text("Stencil:");
  1787. if (ImGui::RadioButton("Use stencil buffer", !m_useStencilTexture) )
  1788. {
  1789. if (m_useStencilTexture)
  1790. {
  1791. m_useStencilTexture = false;
  1792. }
  1793. }
  1794. if (ImGui::RadioButton("Use texture as stencil", m_useStencilTexture) )
  1795. {
  1796. if (!m_useStencilTexture)
  1797. {
  1798. m_useStencilTexture = true;
  1799. }
  1800. }
  1801. ImGui::Separator();
  1802. ImGui::Text("Mesh:");
  1803. if (ImGui::RadioButton("Bunny - high poly", BunnyHighPoly == m_currentMesh) )
  1804. {
  1805. m_currentMesh = BunnyHighPoly;
  1806. }
  1807. if (ImGui::RadioButton("Bunny - low poly", BunnyLowPoly == m_currentMesh) )
  1808. {
  1809. m_currentMesh = BunnyLowPoly;
  1810. }
  1811. if (Scene1 == m_currentScene)
  1812. {
  1813. ImGui::SliderInt("Instance count", &m_instanceCount, 1, MAX_INSTANCE_COUNT);
  1814. }
  1815. ImGui::Text("CPU Time: %7.1f [ms]", double(m_profTime)*toMs);
  1816. ImGui::Text("Volume Vertices: %5.uk", m_numShadowVolumeVertices/1000);
  1817. ImGui::Text("Volume Indices: %6.uk", m_numShadowVolumeIndices/1000);
  1818. m_numShadowVolumeVertices = 0;
  1819. m_numShadowVolumeIndices = 0;
  1820. ImGui::Separator();
  1821. ImGui::Checkbox("Draw Shadow Volumes", &m_drawShadowVolumes);
  1822. ImGui::End();
  1823. ImGui::SetNextWindowPos(
  1824. ImVec2(10, float(m_viewState.m_height) - 77.0f - 10.0f)
  1825. , ImGuiCond_FirstUseEver
  1826. );
  1827. ImGui::SetNextWindowSize(
  1828. ImVec2(120.0f, 77.0f)
  1829. , ImGuiCond_FirstUseEver
  1830. );
  1831. ImGui::Begin("Show help:"
  1832. , NULL
  1833. , 0
  1834. );
  1835. if (ImGui::Button(m_showHelp ? "ON" : "OFF") )
  1836. {
  1837. m_showHelp = !m_showHelp;
  1838. }
  1839. ImGui::End();
  1840. imguiEndFrame();
  1841. //update settings
  1842. s_uniforms.m_params.m_ambientPass = 1.0f;
  1843. s_uniforms.m_params.m_lightingPass = 1.0f;
  1844. s_uniforms.m_params.m_texelHalf = s_texelHalf;
  1845. s_uniforms.m_svparams.m_useStencilTex = float(m_useStencilTexture);
  1846. //set picked bunny model
  1847. Model* bunnyModel = BunnyLowPoly == m_currentMesh ? &m_bunnyLowPolyModel : &m_bunnyHighPolyModel;
  1848. //update time accumulators
  1849. static float sceneTimeAccumulator = 0.0f;
  1850. if (m_updateScene)
  1851. {
  1852. sceneTimeAccumulator += deltaTime;
  1853. }
  1854. static float lightTimeAccumulator = 0.0f;
  1855. if (m_updateLights)
  1856. {
  1857. lightTimeAccumulator += deltaTime;
  1858. }
  1859. //setup light positions
  1860. float lightPosRadius[MAX_LIGHTS_COUNT][4];
  1861. if (LightPattern0 == m_lightPattern)
  1862. {
  1863. for (uint8_t ii = 0; ii < m_numLights; ++ii)
  1864. {
  1865. lightPosRadius[ii][0] = bx::cos(2.0f*bx::kPi/float(m_numLights) * float(ii) + lightTimeAccumulator * 1.1f + 3.0f) * 20.0f;
  1866. lightPosRadius[ii][1] = 20.0f;
  1867. lightPosRadius[ii][2] = bx::sin(2.0f*bx::kPi/float(m_numLights) * float(ii) + lightTimeAccumulator * 1.1f + 3.0f) * 20.0f;
  1868. lightPosRadius[ii][3] = 20.0f;
  1869. }
  1870. }
  1871. else
  1872. {
  1873. for (uint8_t ii = 0; ii < m_numLights; ++ii)
  1874. {
  1875. lightPosRadius[ii][0] = bx::cos(float(ii) * 2.0f/float(m_numLights) + lightTimeAccumulator * 1.3f + bx::kPi) * 40.0f;
  1876. lightPosRadius[ii][1] = 20.0f;
  1877. lightPosRadius[ii][2] = bx::sin(float(ii) * 2.0f/float(m_numLights) + lightTimeAccumulator * 1.3f + bx::kPi) * 40.0f;
  1878. lightPosRadius[ii][3] = 20.0f;
  1879. }
  1880. }
  1881. if (m_showHelp)
  1882. {
  1883. uint8_t row = 18;
  1884. bgfx::dbgTextPrintf(3, row++, 0x0f, "Stencil buffer implementation:");
  1885. bgfx::dbgTextPrintf(8, row++, 0x0f, "Depth fail - Robust, but slower than 'Depth pass'. Requires computing and drawing of shadow volume caps.");
  1886. bgfx::dbgTextPrintf(8, row++, 0x0f, "Depth pass - Faster, but not stable. Shadows are wrong when camera is in the shadow.");
  1887. bgfx::dbgTextPrintf(8, row++, 0x0f, "Mixed - 'Depth pass' where possible, 'Depth fail' where necessary. Best of both words.");
  1888. row++;
  1889. bgfx::dbgTextPrintf(3, row++, 0x0f, "Shadow volume implementation:");
  1890. bgfx::dbgTextPrintf(8, row++, 0x0f, "Face Based - Slower. Works fine with either stencil buffer or texture as stencil.");
  1891. bgfx::dbgTextPrintf(8, row++, 0x0f, "Edge Based - Faster, but requires +2 incr/decr on stencil buffer. To avoid massive redraw, use RGBA texture as stencil.");
  1892. row++;
  1893. bgfx::dbgTextPrintf(3, row++, 0x0f, "Stencil:");
  1894. bgfx::dbgTextPrintf(8, row++, 0x0f, "Stencil buffer - Faster, but capable only of +1 incr.");
  1895. bgfx::dbgTextPrintf(8, row++, 0x0f, "Texture as stencil - Slower, but capable of +2 incr.");
  1896. }
  1897. else
  1898. {
  1899. bgfx::dbgTextClear();
  1900. }
  1901. // Setup instances
  1902. Instance shadowCasters[SceneCount][60];
  1903. uint16_t shadowCastersCount[SceneCount];
  1904. for (uint8_t ii = 0; ii < SceneCount; ++ii)
  1905. {
  1906. shadowCastersCount[ii] = 0;
  1907. }
  1908. Instance shadowReceivers[SceneCount][10];
  1909. uint16_t shadowReceiversCount[SceneCount];
  1910. for (uint8_t ii = 0; ii < SceneCount; ++ii)
  1911. {
  1912. shadowReceiversCount[ii] = 0;
  1913. }
  1914. // Scene 0 - shadow casters - Bunny
  1915. {
  1916. Instance& inst = shadowCasters[Scene0][shadowCastersCount[Scene0]++];
  1917. inst.m_scale[0] = 5.0f;
  1918. inst.m_scale[1] = 5.0f;
  1919. inst.m_scale[2] = 5.0f;
  1920. inst.m_rotation[0] = 0.0f;
  1921. inst.m_rotation[1] = float(4.0f - sceneTimeAccumulator * 0.7f);
  1922. inst.m_rotation[2] = 0.0f;
  1923. inst.m_pos[0] = 0.0f;
  1924. inst.m_pos[1] = 10.0f;
  1925. inst.m_pos[2] = 0.0f;
  1926. inst.m_color[0] = 0.68f;
  1927. inst.m_color[1] = 0.65f;
  1928. inst.m_color[2] = 0.60f;
  1929. inst.m_model = bunnyModel;
  1930. }
  1931. // Scene 0 - shadow casters - Cubes top.
  1932. const uint8_t numCubesTop = 9;
  1933. for (uint16_t ii = 0; ii < numCubesTop; ++ii)
  1934. {
  1935. Instance& inst = shadowCasters[Scene0][shadowCastersCount[Scene0]++];
  1936. inst.m_scale[0] = 1.0f;
  1937. inst.m_scale[1] = 1.0f;
  1938. inst.m_scale[2] = 1.0f;
  1939. inst.m_rotation[0] = 0.0f;
  1940. inst.m_rotation[1] = 0.0f;
  1941. inst.m_rotation[2] = 0.0f;
  1942. inst.m_pos[0] = bx::sin(ii * 2.0f + 13.0f + sceneTimeAccumulator * 1.1f) * 13.0f;
  1943. inst.m_pos[1] = 6.0f;
  1944. inst.m_pos[2] = bx::cos(ii * 2.0f + 13.0f + sceneTimeAccumulator * 1.1f) * 13.0f;
  1945. inst.m_model = &m_cubeModel;
  1946. }
  1947. // Scene 0 - shadow casters - Cubes bottom.
  1948. const uint8_t numCubesBottom = 9;
  1949. for (uint16_t ii = 0; ii < numCubesBottom; ++ii)
  1950. {
  1951. Instance& inst = shadowCasters[Scene0][shadowCastersCount[Scene0]++];
  1952. inst.m_scale[0] = 1.0f;
  1953. inst.m_scale[1] = 1.0f;
  1954. inst.m_scale[2] = 1.0f;
  1955. inst.m_rotation[0] = 0.0f;
  1956. inst.m_rotation[1] = 0.0f;
  1957. inst.m_rotation[2] = 0.0f;
  1958. inst.m_pos[0] = bx::sin(ii * 2.0f + 13.0f + sceneTimeAccumulator * 1.1f) * 13.0f;
  1959. inst.m_pos[1] = 22.0f;
  1960. inst.m_pos[2] = bx::cos(ii * 2.0f + 13.0f + sceneTimeAccumulator * 1.1f) * 13.0f;
  1961. inst.m_model = &m_cubeModel;
  1962. }
  1963. // Scene 0 - shadow casters - Columns.
  1964. const float dist = 16.0f;
  1965. const float columnPositions[][3] =
  1966. {
  1967. { dist, 3.3f, dist },
  1968. { -dist, 3.3f, dist },
  1969. { dist, 3.3f, -dist },
  1970. { -dist, 3.3f, -dist },
  1971. };
  1972. for (uint8_t ii = 0; ii < 4; ++ii)
  1973. {
  1974. Instance& inst = shadowCasters[Scene0][shadowCastersCount[Scene0]++];
  1975. inst.m_scale[0] = 1.5f;
  1976. inst.m_scale[1] = 1.5f;
  1977. inst.m_scale[2] = 1.5f;
  1978. inst.m_rotation[0] = 0.0f;
  1979. inst.m_rotation[1] = 1.57f;
  1980. inst.m_rotation[2] = 0.0f;
  1981. inst.m_pos[0] = columnPositions[ii][0];
  1982. inst.m_pos[1] = columnPositions[ii][1];
  1983. inst.m_pos[2] = columnPositions[ii][2];
  1984. inst.m_color[0] = 0.25f;
  1985. inst.m_color[1] = 0.25f;
  1986. inst.m_color[2] = 0.25f;
  1987. inst.m_model = &m_columnModel;
  1988. }
  1989. // Scene 0 - shadow casters - Ceiling.
  1990. {
  1991. Instance& inst = shadowCasters[Scene0][shadowCastersCount[Scene0]++];
  1992. inst.m_scale[0] = 21.0f;
  1993. inst.m_scale[1] = 21.0f;
  1994. inst.m_scale[2] = 21.0f;
  1995. inst.m_rotation[0] = bx::kPi;
  1996. inst.m_rotation[1] = 0.0f;
  1997. inst.m_rotation[2] = 0.0f;
  1998. inst.m_pos[0] = 0.0f;
  1999. inst.m_pos[1] = 28.2f;
  2000. inst.m_pos[2] = 0.0f;
  2001. inst.m_model = &m_platformModel;
  2002. inst.m_svExtrusionDistance = 2.0f; //prevent culling on tight view frustum
  2003. }
  2004. // Scene 0 - shadow casters - Platform.
  2005. {
  2006. Instance& inst = shadowCasters[Scene0][shadowCastersCount[Scene0]++];
  2007. inst.m_scale[0] = 24.0f;
  2008. inst.m_scale[1] = 24.0f;
  2009. inst.m_scale[2] = 24.0f;
  2010. inst.m_rotation[0] = 0.0f;
  2011. inst.m_rotation[1] = 0.0f;
  2012. inst.m_rotation[2] = 0.0f;
  2013. inst.m_pos[0] = 0.0f;
  2014. inst.m_pos[1] = 0.0f;
  2015. inst.m_pos[2] = 0.0f;
  2016. inst.m_model = &m_platformModel;
  2017. inst.m_svExtrusionDistance = 2.0f; //prevent culling on tight view frustum
  2018. }
  2019. // Scene 0 - shadow receivers - Floor.
  2020. {
  2021. Instance& inst = shadowReceivers[Scene0][shadowReceiversCount[Scene0]++];
  2022. inst.m_scale[0] = 500.0f;
  2023. inst.m_scale[1] = 500.0f;
  2024. inst.m_scale[2] = 500.0f;
  2025. inst.m_rotation[0] = 0.0f;
  2026. inst.m_rotation[1] = 0.0f;
  2027. inst.m_rotation[2] = 0.0f;
  2028. inst.m_pos[0] = 0.0f;
  2029. inst.m_pos[1] = 0.0f;
  2030. inst.m_pos[2] = 0.0f;
  2031. inst.m_model = &m_hplaneFieldModel;
  2032. }
  2033. // Scene 1 - shadow casters - Bunny instances
  2034. {
  2035. enum Direction
  2036. {
  2037. Left = 0x0,
  2038. Down = 0x1,
  2039. Right = 0x2,
  2040. Up = 0x3,
  2041. };
  2042. const uint8_t directionMask = 0x3;
  2043. uint8_t currentDirection = Left;
  2044. float currX = 0.0f;
  2045. float currY = 0.0f;
  2046. const float stepX = 20.0f;
  2047. const float stepY = 20.0f;
  2048. uint8_t stateStep = 0;
  2049. uint8_t stateChange = 1;
  2050. for (uint8_t ii = 0; ii < m_instanceCount; ++ii)
  2051. {
  2052. Instance& inst = shadowCasters[Scene1][shadowCastersCount[Scene1]++];
  2053. inst.m_scale[0] = 5.0f;
  2054. inst.m_scale[1] = 5.0f;
  2055. inst.m_scale[2] = 5.0f;
  2056. inst.m_rotation[0] = 0.0f;
  2057. inst.m_rotation[1] = bx::kPi;
  2058. inst.m_rotation[2] = 0.0f;
  2059. inst.m_pos[0] = currX;
  2060. inst.m_pos[1] = 0.0f;
  2061. inst.m_pos[2] = currY;
  2062. inst.m_model = bunnyModel;
  2063. ++stateStep;
  2064. if (stateStep >= ( (stateChange & ~0x1) >> 1) )
  2065. {
  2066. currentDirection = (currentDirection + 1) & directionMask;
  2067. stateStep = 0;
  2068. ++stateChange;
  2069. }
  2070. switch (currentDirection)
  2071. {
  2072. case Left: currX -= stepX; break;
  2073. case Down: currY -= stepY; break;
  2074. case Right: currX += stepX; break;
  2075. case Up: currY += stepY; break;
  2076. }
  2077. }
  2078. }
  2079. // Scene 1 - shadow receivers - Floor.
  2080. {
  2081. Instance& inst = shadowReceivers[Scene1][shadowReceiversCount[Scene1]++];
  2082. inst.m_scale[0] = 500.0f;
  2083. inst.m_scale[1] = 500.0f;
  2084. inst.m_scale[2] = 500.0f;
  2085. inst.m_rotation[0] = 0.0f;
  2086. inst.m_rotation[1] = 0.0f;
  2087. inst.m_rotation[2] = 0.0f;
  2088. inst.m_pos[0] = 0.0f;
  2089. inst.m_pos[1] = 0.0f;
  2090. inst.m_pos[2] = 0.0f;
  2091. inst.m_model = &m_hplaneFigureModel;
  2092. }
  2093. // Make sure at the beginning everything gets cleared.
  2094. bgfx::setViewClear(0
  2095. , BGFX_CLEAR_COLOR
  2096. | BGFX_CLEAR_DEPTH
  2097. | BGFX_CLEAR_STENCIL
  2098. , m_clearValues.m_clearRgba
  2099. , m_clearValues.m_clearDepth
  2100. , m_clearValues.m_clearStencil
  2101. );
  2102. ::touch(0);
  2103. // Draw ambient only.
  2104. s_uniforms.m_params.m_ambientPass = 1.0f;
  2105. s_uniforms.m_params.m_lightingPass = 0.0f;
  2106. s_uniforms.m_color[0] = 1.0f;
  2107. s_uniforms.m_color[1] = 1.0f;
  2108. s_uniforms.m_color[2] = 1.0f;
  2109. const RenderState& drawAmbient = m_useStencilTexture
  2110. ? s_renderStates[RenderState::ShadowVolume_UsingStencilTexture_DrawAmbient]
  2111. : s_renderStates[RenderState::ShadowVolume_UsingStencilBuffer_DrawAmbient]
  2112. ;
  2113. // Draw shadow casters.
  2114. for (uint8_t ii = 0; ii < shadowCastersCount[m_currentScene]; ++ii)
  2115. {
  2116. shadowCasters[m_currentScene][ii].submit(VIEWID_RANGE1_PASS0, drawAmbient);
  2117. }
  2118. // Draw shadow receivers.
  2119. for (uint8_t ii = 0; ii < shadowReceiversCount[m_currentScene]; ++ii)
  2120. {
  2121. shadowReceivers[m_currentScene][ii].submit(VIEWID_RANGE1_PASS0, drawAmbient);
  2122. }
  2123. // Using stencil texture requires rendering to separate render target. first pass is building depth buffer.
  2124. if (m_useStencilTexture)
  2125. {
  2126. bgfx::setViewClear(VIEWID_RANGE1_RT_PASS1, BGFX_CLEAR_DEPTH, 0x00000000, 1.0f, 0);
  2127. bgfx::setViewFrameBuffer(VIEWID_RANGE1_RT_PASS1, s_stencilFb);
  2128. const RenderState& renderState = s_renderStates[RenderState::ShadowVolume_UsingStencilTexture_BuildDepth];
  2129. for (uint8_t ii = 0; ii < shadowCastersCount[m_currentScene]; ++ii)
  2130. {
  2131. shadowCasters[m_currentScene][ii].submit(VIEWID_RANGE1_RT_PASS1, renderState);
  2132. }
  2133. for (uint8_t ii = 0; ii < shadowReceiversCount[m_currentScene]; ++ii)
  2134. {
  2135. shadowReceivers[m_currentScene][ii].submit(VIEWID_RANGE1_RT_PASS1, renderState);
  2136. }
  2137. }
  2138. m_profTime = bx::getHPCounter();
  2139. /**
  2140. * For each light:
  2141. * 1. Compute and draw shadow volume to stencil buffer
  2142. * 2. Draw diffuse with stencil test
  2143. */
  2144. for (uint8_t ii = 0, viewId = VIEWID_RANGE15_PASS2; ii < m_numLights; ++ii, ++viewId)
  2145. {
  2146. const float* lightPos = lightPosRadius[ii];
  2147. bx::memCopy(s_uniforms.m_lightPosRadius, lightPosRadius[ii], 4*sizeof(float) );
  2148. bx::memCopy(s_uniforms.m_lightRgbInnerR, m_lightRgbInnerR[ii], 3*sizeof(float) );
  2149. bx::memCopy(s_uniforms.m_color, m_lightRgbInnerR[ii], 3*sizeof(float) );
  2150. if (m_useStencilTexture)
  2151. {
  2152. bgfx::setViewFrameBuffer(viewId, s_stencilFb);
  2153. bgfx::setViewClear(viewId
  2154. , BGFX_CLEAR_COLOR
  2155. , 0x00000000
  2156. , 1.0f
  2157. , 0
  2158. );
  2159. }
  2160. else
  2161. {
  2162. const bgfx::FrameBufferHandle invalid = BGFX_INVALID_HANDLE;
  2163. bgfx::setViewFrameBuffer(viewId, invalid);
  2164. bgfx::setViewClear(viewId
  2165. , BGFX_CLEAR_STENCIL
  2166. , m_clearValues.m_clearRgba
  2167. , m_clearValues.m_clearDepth
  2168. , m_clearValues.m_clearStencil
  2169. );
  2170. }
  2171. // Create near clip volume for current light.
  2172. float nearClipVolume[6 * 4] = {};
  2173. float pointLight[4];
  2174. if (m_mixedSvImpl)
  2175. {
  2176. pointLight[0] = lightPos[0];
  2177. pointLight[1] = lightPos[1];
  2178. pointLight[2] = lightPos[2];
  2179. pointLight[3] = 1.0f;
  2180. createNearClipVolume(nearClipVolume, pointLight, m_viewState.m_view, fov, aspect, nearPlane);
  2181. }
  2182. for (uint8_t jj = 0; jj < shadowCastersCount[m_currentScene]; ++jj)
  2183. {
  2184. const Instance& instance = shadowCasters[m_currentScene][jj];
  2185. Model* model = instance.m_model;
  2186. ShadowVolumeImpl::Enum shadowVolumeImpl = m_shadowVolumeImpl;
  2187. if (m_mixedSvImpl)
  2188. {
  2189. // If instance is inside near clip volume, depth fail must be used, else depth pass is fine.
  2190. bool isInsideVolume = clipTest(nearClipVolume, 6, model->m_mesh, instance.m_scale, instance.m_pos);
  2191. shadowVolumeImpl = (isInsideVolume ? ShadowVolumeImpl::DepthFail : ShadowVolumeImpl::DepthPass);
  2192. }
  2193. s_uniforms.m_svparams.m_dfail = float(ShadowVolumeImpl::DepthFail == shadowVolumeImpl);
  2194. // Compute virtual light position for shadow volume generation.
  2195. float transformedLightPos[3];
  2196. shadowVolumeLightTransform(transformedLightPos
  2197. , instance.m_scale
  2198. , instance.m_rotation
  2199. , instance.m_pos
  2200. , lightPos
  2201. );
  2202. // Set virtual light pos.
  2203. bx::memCopy(s_uniforms.m_virtualLightPos_extrusionDist, transformedLightPos, 3*sizeof(float) );
  2204. s_uniforms.m_virtualLightPos_extrusionDist[3] = instance.m_svExtrusionDistance;
  2205. // Compute transform for shadow volume.
  2206. float shadowVolumeMtx[16];
  2207. bx::mtxSRT(shadowVolumeMtx
  2208. , instance.m_scale[0]
  2209. , instance.m_scale[1]
  2210. , instance.m_scale[2]
  2211. , instance.m_rotation[0]
  2212. , instance.m_rotation[1]
  2213. , instance.m_rotation[2]
  2214. , instance.m_pos[0]
  2215. , instance.m_pos[1]
  2216. , instance.m_pos[2]
  2217. );
  2218. GroupArray& groups = model->m_mesh.m_groups;
  2219. const uint16_t stride = model->m_mesh.m_layout.getStride();
  2220. for (GroupArray::iterator it = groups.begin(), itEnd = groups.end(); it != itEnd; ++it)
  2221. {
  2222. Group& group = *it;
  2223. // Create shadow volume.
  2224. ShadowVolume shadowVolume;
  2225. shadowVolumeCreate(shadowVolume
  2226. , group
  2227. , stride
  2228. , shadowVolumeMtx
  2229. , transformedLightPos
  2230. , shadowVolumeImpl
  2231. , m_shadowVolumeAlgorithm
  2232. , m_useStencilTexture
  2233. );
  2234. m_numShadowVolumeVertices += shadowVolume.m_numVertices;
  2235. m_numShadowVolumeIndices += shadowVolume.m_numIndices;
  2236. ShadowVolumeProgramType::Enum programIndex = ShadowVolumeProgramType::Blank;
  2237. RenderState::Enum renderStateIndex;
  2238. if (m_useStencilTexture)
  2239. {
  2240. renderStateIndex = ShadowVolumeImpl::DepthFail == shadowVolumeImpl
  2241. ? RenderState::ShadowVolume_UsingStencilTexture_CraftStencil_DepthFail
  2242. : RenderState::ShadowVolume_UsingStencilTexture_CraftStencil_DepthPass
  2243. ;
  2244. programIndex = ShadowVolumeAlgorithm::FaceBased == m_shadowVolumeAlgorithm
  2245. ? ShadowVolumeProgramType::Tex1
  2246. : ShadowVolumeProgramType::Tex2
  2247. ;
  2248. }
  2249. else
  2250. {
  2251. renderStateIndex = ShadowVolumeImpl::DepthFail == shadowVolumeImpl
  2252. ? RenderState::ShadowVolume_UsingStencilBuffer_CraftStencil_DepthFail
  2253. : RenderState::ShadowVolume_UsingStencilBuffer_CraftStencil_DepthPass
  2254. ;
  2255. }
  2256. const RenderState& renderStateCraftStencil = s_renderStates[renderStateIndex];
  2257. s_uniforms.submitPerDrawUniforms();
  2258. bgfx::setTransform(shadowVolumeMtx);
  2259. bgfx::setVertexBuffer(0, shadowVolume.m_vbSides);
  2260. bgfx::setIndexBuffer(shadowVolume.m_ibSides);
  2261. setRenderState(renderStateCraftStencil);
  2262. ::submit(viewId, m_svProgs[programIndex][ShadowVolumePart::Side]);
  2263. if (shadowVolume.m_cap)
  2264. {
  2265. s_uniforms.submitPerDrawUniforms();
  2266. bgfx::setTransform(shadowVolumeMtx);
  2267. bgfx::setVertexBuffer(0, group.m_vbh);
  2268. bgfx::setIndexBuffer(shadowVolume.m_ibFrontCap);
  2269. setRenderState(renderStateCraftStencil);
  2270. ::submit(viewId, m_svProgs[programIndex][ShadowVolumePart::Front]);
  2271. s_uniforms.submitPerDrawUniforms();
  2272. bgfx::setTransform(shadowVolumeMtx);
  2273. bgfx::setVertexBuffer(0, group.m_vbh);
  2274. bgfx::setIndexBuffer(shadowVolume.m_ibBackCap);
  2275. ::setRenderState(renderStateCraftStencil);
  2276. ::submit(viewId, m_svProgs[programIndex][ShadowVolumePart::Back]);
  2277. }
  2278. if (m_drawShadowVolumes)
  2279. {
  2280. const RenderState& renderState = s_renderStates[RenderState::Custom_DrawShadowVolume_Lines];
  2281. s_uniforms.submitPerDrawUniforms();
  2282. bgfx::setTransform(shadowVolumeMtx);
  2283. bgfx::setVertexBuffer(0, shadowVolume.m_vbSides);
  2284. bgfx::setIndexBuffer(shadowVolume.m_ibSides);
  2285. ::setRenderState(renderState);
  2286. ::submit(VIEWID_RANGE1_PASS3, m_svProgs[ShadowVolumeProgramType::Color][ShadowVolumePart::Side]);
  2287. if (shadowVolume.m_cap)
  2288. {
  2289. s_uniforms.submitPerDrawUniforms();
  2290. bgfx::setTransform(shadowVolumeMtx);
  2291. bgfx::setVertexBuffer(0, group.m_vbh);
  2292. bgfx::setIndexBuffer(shadowVolume.m_ibFrontCap);
  2293. ::setRenderState(renderState);
  2294. ::submit(VIEWID_RANGE1_PASS3, m_svProgs[ShadowVolumeProgramType::Color][ShadowVolumePart::Front]);
  2295. s_uniforms.submitPerDrawUniforms();
  2296. bgfx::setTransform(shadowVolumeMtx);
  2297. bgfx::setVertexBuffer(0, group.m_vbh);
  2298. bgfx::setIndexBuffer(shadowVolume.m_ibBackCap);
  2299. ::setRenderState(renderState);
  2300. ::submit(VIEWID_RANGE1_PASS3, m_svProgs[ShadowVolumeProgramType::Color][ShadowVolumePart::Back]);
  2301. }
  2302. }
  2303. }
  2304. }
  2305. // Draw diffuse only.
  2306. s_uniforms.m_params.m_ambientPass = 0.0f;
  2307. s_uniforms.m_params.m_lightingPass = 1.0f;
  2308. RenderState& drawDiffuse = m_useStencilTexture
  2309. ? s_renderStates[RenderState::ShadowVolume_UsingStencilTexture_DrawDiffuse]
  2310. : s_renderStates[RenderState::ShadowVolume_UsingStencilBuffer_DrawDiffuse]
  2311. ;
  2312. // If using stencil texture, viewId is set to render target. Incr it to render to default back buffer.
  2313. viewId += uint8_t(m_useStencilTexture);
  2314. // Draw shadow casters.
  2315. for (uint8_t jj = 0; jj < shadowCastersCount[m_currentScene]; ++jj)
  2316. {
  2317. shadowCasters[m_currentScene][jj].submit(viewId, drawDiffuse);
  2318. }
  2319. // Draw shadow receivers.
  2320. for (uint8_t jj = 0; jj < shadowReceiversCount[m_currentScene]; ++jj)
  2321. {
  2322. shadowReceivers[m_currentScene][jj].submit(viewId, drawDiffuse);
  2323. }
  2324. }
  2325. m_profTime = bx::getHPCounter() - m_profTime;
  2326. // Lights.
  2327. const float lightScale[3] = { 1.5f, 1.5f, 1.5f };
  2328. for (uint8_t ii = 0; ii < m_numLights; ++ii)
  2329. {
  2330. bx::memCopy(s_uniforms.m_color, m_lightRgbInnerR[ii], 3*sizeof(float) );
  2331. float lightMtx[16];
  2332. mtxBillboard(lightMtx, m_viewState.m_view, lightPosRadius[ii], lightScale);
  2333. m_vplaneModel.submit(VIEWID_RANGE1_PASS3, lightMtx, s_renderStates[RenderState::Custom_BlendLightTexture]);
  2334. }
  2335. // Setup view rect and transform for all used views.
  2336. setViewRectMask(s_viewMask, 0, 0, uint16_t(m_viewState.m_width), uint16_t(m_viewState.m_height) );
  2337. setViewTransformMask(s_viewMask, m_viewState.m_view, m_viewState.m_proj);
  2338. s_viewMask = 0;
  2339. // Advance to next frame. Rendering thread will be kicked to
  2340. // process submitted rendering primitives.
  2341. bgfx::frame();
  2342. // Swap memory pages.
  2343. s_svAllocator.swap();
  2344. // Reset clear values.
  2345. setViewClearMask(UINT32_MAX
  2346. , BGFX_CLEAR_NONE
  2347. , m_clearValues.m_clearRgba
  2348. , m_clearValues.m_clearDepth
  2349. , m_clearValues.m_clearStencil
  2350. );
  2351. return true;
  2352. }
  2353. return false;
  2354. }
  2355. ViewState m_viewState;
  2356. ClearValues m_clearValues;
  2357. uint32_t m_debug;
  2358. uint32_t m_reset;
  2359. bgfx::TextureHandle m_figureTex;
  2360. bgfx::TextureHandle m_flareTex;
  2361. bgfx::TextureHandle m_fieldstoneTex;
  2362. bgfx::ProgramHandle m_programTextureLighting;
  2363. bgfx::ProgramHandle m_programColorLighting;
  2364. bgfx::ProgramHandle m_programColorTexture;
  2365. bgfx::ProgramHandle m_programTexture;
  2366. bgfx::ProgramHandle m_programBackBlank;
  2367. bgfx::ProgramHandle m_programSideBlank;
  2368. bgfx::ProgramHandle m_programFrontBlank;
  2369. bgfx::ProgramHandle m_programBackColor;
  2370. bgfx::ProgramHandle m_programSideColor;
  2371. bgfx::ProgramHandle m_programFrontColor;
  2372. bgfx::ProgramHandle m_programSideTex;
  2373. bgfx::ProgramHandle m_programBackTex1;
  2374. bgfx::ProgramHandle m_programBackTex2;
  2375. bgfx::ProgramHandle m_programFrontTex1;
  2376. bgfx::ProgramHandle m_programFrontTex2;
  2377. bgfx::ProgramHandle m_svProgs[ShadowVolumeProgramType::Count][ShadowVolumePart::Count];
  2378. Model m_bunnyLowPolyModel;
  2379. Model m_bunnyHighPolyModel;
  2380. Model m_columnModel;
  2381. Model m_platformModel;
  2382. Model m_cubeModel;
  2383. Model m_hplaneFieldModel;
  2384. Model m_hplaneFigureModel;
  2385. Model m_vplaneModel;
  2386. float m_lightRgbInnerR[MAX_LIGHTS_COUNT][4];
  2387. int64_t m_profTime;
  2388. int64_t m_timeOffset;
  2389. uint32_t m_numShadowVolumeVertices;
  2390. uint32_t m_numShadowVolumeIndices;
  2391. uint32_t m_oldWidth;
  2392. uint32_t m_oldHeight;
  2393. int32_t m_numLights;
  2394. int32_t m_instanceCount;
  2395. bool m_showHelp;
  2396. bool m_updateLights;
  2397. bool m_updateScene;
  2398. bool m_mixedSvImpl;
  2399. bool m_useStencilTexture;
  2400. bool m_drawShadowVolumes;
  2401. ShadowVolumeImpl::Enum m_shadowVolumeImpl;
  2402. ShadowVolumeAlgorithm::Enum m_shadowVolumeAlgorithm;
  2403. LightPattern m_lightPattern;
  2404. MeshChoice m_currentMesh;
  2405. Scene m_currentScene;
  2406. entry::MouseState m_mouseState;
  2407. };
  2408. } // namespace
  2409. ENTRY_IMPLEMENT_MAIN(
  2410. ExampleShadowVolumes
  2411. , "14-shadowvolumes"
  2412. , "Shadow volumes."
  2413. , "https://bkaradzic.github.io/bgfx/examples.html#shadowvolumes");