shadowvolumes.cpp 80 KB

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