shadowvolumes.cpp 79 KB

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