shadowvolumes.cpp 80 KB

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