shadowvolumes.cpp 78 KB

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