Renderer.cpp 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/CoreEvents.h"
  24. #include "../Core/Profiler.h"
  25. #include "../Graphics/Camera.h"
  26. #include "../Graphics/DebugRenderer.h"
  27. #include "../Graphics/Geometry.h"
  28. #include "../Graphics/Graphics.h"
  29. #include "../Graphics/GraphicsEvents.h"
  30. #include "../Graphics/GraphicsImpl.h"
  31. #include "../Graphics/IndexBuffer.h"
  32. #include "../Graphics/Material.h"
  33. #include "../Graphics/OcclusionBuffer.h"
  34. #include "../Graphics/Octree.h"
  35. #include "../Graphics/Renderer.h"
  36. #include "../Graphics/RenderPath.h"
  37. #include "../Graphics/ShaderVariation.h"
  38. #include "../Graphics/Technique.h"
  39. #include "../Graphics/Texture2D.h"
  40. #include "../Graphics/TextureCube.h"
  41. #include "../Graphics/VertexBuffer.h"
  42. #include "../Graphics/View.h"
  43. #include "../Graphics/Zone.h"
  44. #include "../IO/Log.h"
  45. #include "../Resource/ResourceCache.h"
  46. #include "../Resource/XMLFile.h"
  47. #include "../Scene/Scene.h"
  48. #include "../DebugNew.h"
  49. #ifdef _MSC_VER
  50. #pragma warning(disable:6293)
  51. #endif
  52. namespace Atomic
  53. {
  54. static const float dirLightVertexData[] =
  55. {
  56. -1, 1, 0,
  57. 1, 1, 0,
  58. 1, -1, 0,
  59. -1, -1, 0,
  60. };
  61. static const unsigned short dirLightIndexData[] =
  62. {
  63. 0, 1, 2,
  64. 2, 3, 0,
  65. };
  66. static const float pointLightVertexData[] =
  67. {
  68. -0.423169f, -1.000000f, 0.423169f,
  69. -0.423169f, -1.000000f, -0.423169f,
  70. 0.423169f, -1.000000f, -0.423169f,
  71. 0.423169f, -1.000000f, 0.423169f,
  72. 0.423169f, 1.000000f, -0.423169f,
  73. -0.423169f, 1.000000f, -0.423169f,
  74. -0.423169f, 1.000000f, 0.423169f,
  75. 0.423169f, 1.000000f, 0.423169f,
  76. -1.000000f, 0.423169f, -0.423169f,
  77. -1.000000f, -0.423169f, -0.423169f,
  78. -1.000000f, -0.423169f, 0.423169f,
  79. -1.000000f, 0.423169f, 0.423169f,
  80. 0.423169f, 0.423169f, -1.000000f,
  81. 0.423169f, -0.423169f, -1.000000f,
  82. -0.423169f, -0.423169f, -1.000000f,
  83. -0.423169f, 0.423169f, -1.000000f,
  84. 1.000000f, 0.423169f, 0.423169f,
  85. 1.000000f, -0.423169f, 0.423169f,
  86. 1.000000f, -0.423169f, -0.423169f,
  87. 1.000000f, 0.423169f, -0.423169f,
  88. 0.423169f, -0.423169f, 1.000000f,
  89. 0.423169f, 0.423169f, 1.000000f,
  90. -0.423169f, 0.423169f, 1.000000f,
  91. -0.423169f, -0.423169f, 1.000000f
  92. };
  93. static const unsigned short pointLightIndexData[] =
  94. {
  95. 0, 1, 2,
  96. 0, 2, 3,
  97. 4, 5, 6,
  98. 4, 6, 7,
  99. 8, 9, 10,
  100. 8, 10, 11,
  101. 12, 13, 14,
  102. 12, 14, 15,
  103. 16, 17, 18,
  104. 16, 18, 19,
  105. 20, 21, 22,
  106. 20, 22, 23,
  107. 0, 10, 9,
  108. 0, 9, 1,
  109. 13, 2, 1,
  110. 13, 1, 14,
  111. 23, 0, 3,
  112. 23, 3, 20,
  113. 17, 3, 2,
  114. 17, 2, 18,
  115. 21, 7, 6,
  116. 21, 6, 22,
  117. 7, 16, 19,
  118. 7, 19, 4,
  119. 5, 8, 11,
  120. 5, 11, 6,
  121. 4, 12, 15,
  122. 4, 15, 5,
  123. 22, 11, 10,
  124. 22, 10, 23,
  125. 8, 15, 14,
  126. 8, 14, 9,
  127. 12, 19, 18,
  128. 12, 18, 13,
  129. 16, 21, 20,
  130. 16, 20, 17,
  131. 0, 23, 10,
  132. 1, 9, 14,
  133. 2, 13, 18,
  134. 3, 17, 20,
  135. 6, 11, 22,
  136. 5, 15, 8,
  137. 4, 19, 12,
  138. 7, 21, 16
  139. };
  140. static const float spotLightVertexData[] =
  141. {
  142. 0.00001f, 0.00001f, 0.00001f,
  143. 0.00001f, -0.00001f, 0.00001f,
  144. -0.00001f, -0.00001f, 0.00001f,
  145. -0.00001f, 0.00001f, 0.00001f,
  146. 1.00000f, 1.00000f, 0.99999f,
  147. 1.00000f, -1.00000f, 0.99999f,
  148. -1.00000f, -1.00000f, 0.99999f,
  149. -1.00000f, 1.00000f, 0.99999f,
  150. };
  151. static const unsigned short spotLightIndexData[] =
  152. {
  153. 3, 0, 1,
  154. 3, 1, 2,
  155. 0, 4, 5,
  156. 0, 5, 1,
  157. 3, 7, 4,
  158. 3, 4, 0,
  159. 7, 3, 2,
  160. 7, 2, 6,
  161. 6, 2, 1,
  162. 6, 1, 5,
  163. 7, 5, 4,
  164. 7, 6, 5
  165. };
  166. static const char* shadowVariations[] =
  167. {
  168. #ifdef ATOMIC_OPENGL
  169. // No specific hardware shadow compare variation on OpenGL, it is always supported
  170. "LQSHADOW ",
  171. "LQSHADOW ",
  172. "",
  173. ""
  174. #else
  175. "LQSHADOW SHADOWCMP ",
  176. "LQSHADOW ",
  177. "SHADOWCMP ",
  178. ""
  179. #endif
  180. };
  181. static const char* geometryVSVariations[] =
  182. {
  183. "",
  184. "SKINNED ",
  185. "INSTANCED ",
  186. "BILLBOARD "
  187. };
  188. static const char* lightVSVariations[] =
  189. {
  190. "PERPIXEL DIRLIGHT ",
  191. "PERPIXEL SPOTLIGHT ",
  192. "PERPIXEL POINTLIGHT ",
  193. "PERPIXEL DIRLIGHT SHADOW ",
  194. "PERPIXEL SPOTLIGHT SHADOW ",
  195. "PERPIXEL POINTLIGHT SHADOW ",
  196. };
  197. static const char* vertexLightVSVariations[] =
  198. {
  199. "",
  200. "NUMVERTEXLIGHTS=1 ",
  201. "NUMVERTEXLIGHTS=2 ",
  202. "NUMVERTEXLIGHTS=3 ",
  203. "NUMVERTEXLIGHTS=4 ",
  204. };
  205. static const char* deferredLightVSVariations[] =
  206. {
  207. "",
  208. "DIRLIGHT ",
  209. "ORTHO ",
  210. "DIRLIGHT ORTHO "
  211. };
  212. static const char* lightPSVariations[] =
  213. {
  214. "PERPIXEL DIRLIGHT ",
  215. "PERPIXEL SPOTLIGHT ",
  216. "PERPIXEL POINTLIGHT ",
  217. "PERPIXEL POINTLIGHT CUBEMASK ",
  218. "PERPIXEL DIRLIGHT SPECULAR ",
  219. "PERPIXEL SPOTLIGHT SPECULAR ",
  220. "PERPIXEL POINTLIGHT SPECULAR ",
  221. "PERPIXEL POINTLIGHT CUBEMASK SPECULAR ",
  222. "PERPIXEL DIRLIGHT SHADOW ",
  223. "PERPIXEL SPOTLIGHT SHADOW ",
  224. "PERPIXEL POINTLIGHT SHADOW ",
  225. "PERPIXEL POINTLIGHT CUBEMASK SHADOW ",
  226. "PERPIXEL DIRLIGHT SPECULAR SHADOW ",
  227. "PERPIXEL SPOTLIGHT SPECULAR SHADOW ",
  228. "PERPIXEL POINTLIGHT SPECULAR SHADOW ",
  229. "PERPIXEL POINTLIGHT CUBEMASK SPECULAR SHADOW "
  230. };
  231. static const char* heightFogVariations[] =
  232. {
  233. "",
  234. "HEIGHTFOG "
  235. };
  236. static const unsigned INSTANCING_BUFFER_MASK = MASK_INSTANCEMATRIX1 | MASK_INSTANCEMATRIX2 | MASK_INSTANCEMATRIX3;
  237. static const unsigned MAX_BUFFER_AGE = 1000;
  238. Renderer::Renderer(Context* context) :
  239. Object(context),
  240. defaultZone_(new Zone(context)),
  241. textureAnisotropy_(4),
  242. textureFilterMode_(FILTER_TRILINEAR),
  243. textureQuality_(QUALITY_HIGH),
  244. materialQuality_(QUALITY_HIGH),
  245. shadowMapSize_(1024),
  246. shadowQuality_(SHADOWQUALITY_HIGH_16BIT),
  247. maxShadowMaps_(1),
  248. minInstances_(2),
  249. maxSortedInstances_(1000),
  250. maxOccluderTriangles_(5000),
  251. occlusionBufferSize_(256),
  252. occluderSizeThreshold_(0.025f),
  253. mobileShadowBiasMul_(2.0f),
  254. mobileShadowBiasAdd_(0.0001f),
  255. numOcclusionBuffers_(0),
  256. numShadowCameras_(0),
  257. shadersChangedFrameNumber_(M_MAX_UNSIGNED),
  258. hdrRendering_(false),
  259. specularLighting_(true),
  260. drawShadows_(true),
  261. reuseShadowMaps_(true),
  262. dynamicInstancing_(true),
  263. shadersDirty_(true),
  264. initialized_(false),
  265. resetViews_(false)
  266. {
  267. SubscribeToEvent(E_SCREENMODE, HANDLER(Renderer, HandleScreenMode));
  268. // Try to initialize right now, but skip if screen mode is not yet set
  269. Initialize();
  270. }
  271. Renderer::~Renderer()
  272. {
  273. }
  274. void Renderer::SetNumViewports(unsigned num)
  275. {
  276. viewports_.Resize(num);
  277. }
  278. void Renderer::SetViewport(unsigned index, Viewport* viewport)
  279. {
  280. if (index >= viewports_.Size())
  281. viewports_.Resize(index + 1);
  282. viewports_[index] = viewport;
  283. }
  284. void Renderer::SetDefaultRenderPath(RenderPath* renderPath)
  285. {
  286. if (renderPath)
  287. defaultRenderPath_ = renderPath;
  288. }
  289. void Renderer::SetDefaultRenderPath(XMLFile* xmlFile)
  290. {
  291. SharedPtr<RenderPath> newRenderPath(new RenderPath());
  292. if (newRenderPath->Load(xmlFile))
  293. defaultRenderPath_ = newRenderPath;
  294. }
  295. void Renderer::SetHDRRendering(bool enable)
  296. {
  297. hdrRendering_ = enable;
  298. }
  299. void Renderer::SetSpecularLighting(bool enable)
  300. {
  301. specularLighting_ = enable;
  302. }
  303. void Renderer::SetTextureAnisotropy(int level)
  304. {
  305. textureAnisotropy_ = Max(level, 1);
  306. }
  307. void Renderer::SetTextureFilterMode(TextureFilterMode mode)
  308. {
  309. textureFilterMode_ = mode;
  310. }
  311. void Renderer::SetTextureQuality(int quality)
  312. {
  313. quality = Clamp(quality, QUALITY_LOW, QUALITY_HIGH);
  314. if (quality != textureQuality_)
  315. {
  316. textureQuality_ = quality;
  317. ReloadTextures();
  318. }
  319. }
  320. void Renderer::SetMaterialQuality(int quality)
  321. {
  322. quality = Clamp(quality, QUALITY_LOW, QUALITY_MAX);
  323. if (quality != materialQuality_)
  324. {
  325. materialQuality_ = quality;
  326. shadersDirty_ = true;
  327. // Reallocate views to not store eg. pass information that might be unnecessary on the new material quality level
  328. resetViews_ = true;
  329. }
  330. }
  331. void Renderer::SetDrawShadows(bool enable)
  332. {
  333. if (!graphics_ || !graphics_->GetShadowMapFormat())
  334. return;
  335. drawShadows_ = enable;
  336. if (!drawShadows_)
  337. ResetShadowMaps();
  338. }
  339. void Renderer::SetShadowMapSize(int size)
  340. {
  341. if (!graphics_)
  342. return;
  343. size = NextPowerOfTwo((unsigned)Max(size, SHADOW_MIN_PIXELS));
  344. if (size != shadowMapSize_)
  345. {
  346. shadowMapSize_ = size;
  347. ResetShadowMaps();
  348. }
  349. }
  350. void Renderer::SetShadowQuality(int quality)
  351. {
  352. if (!graphics_)
  353. return;
  354. quality &= SHADOWQUALITY_HIGH_24BIT;
  355. // If no hardware PCF, do not allow to select one-sample quality
  356. if (!graphics_->GetHardwareShadowSupport())
  357. quality |= SHADOWQUALITY_HIGH_16BIT;
  358. if (!graphics_->GetHiresShadowMapFormat())
  359. quality &= SHADOWQUALITY_HIGH_16BIT;
  360. if (quality != shadowQuality_)
  361. {
  362. shadowQuality_ = quality;
  363. shadersDirty_ = true;
  364. ResetShadowMaps();
  365. }
  366. }
  367. void Renderer::SetReuseShadowMaps(bool enable)
  368. {
  369. if (enable == reuseShadowMaps_)
  370. return;
  371. reuseShadowMaps_ = enable;
  372. }
  373. void Renderer::SetMaxShadowMaps(int shadowMaps)
  374. {
  375. if (shadowMaps < 1)
  376. return;
  377. maxShadowMaps_ = shadowMaps;
  378. for (HashMap<int, Vector<SharedPtr<Texture2D> > >::Iterator i = shadowMaps_.Begin(); i != shadowMaps_.End(); ++i)
  379. {
  380. if ((int)i->second_.Size() > maxShadowMaps_)
  381. i->second_.Resize((unsigned)maxShadowMaps_);
  382. }
  383. }
  384. void Renderer::SetDynamicInstancing(bool enable)
  385. {
  386. if (!instancingBuffer_)
  387. enable = false;
  388. dynamicInstancing_ = enable;
  389. }
  390. void Renderer::SetMinInstances(int instances)
  391. {
  392. minInstances_ = Max(instances, 2);
  393. }
  394. void Renderer::SetMaxSortedInstances(int instances)
  395. {
  396. maxSortedInstances_ = Max(instances, 0);
  397. }
  398. void Renderer::SetMaxOccluderTriangles(int triangles)
  399. {
  400. maxOccluderTriangles_ = Max(triangles, 0);
  401. }
  402. void Renderer::SetOcclusionBufferSize(int size)
  403. {
  404. occlusionBufferSize_ = Max(size, 1);
  405. occlusionBuffers_.Clear();
  406. }
  407. void Renderer::SetMobileShadowBiasMul(float mul)
  408. {
  409. mobileShadowBiasMul_ = mul;
  410. }
  411. void Renderer::SetMobileShadowBiasAdd(float add)
  412. {
  413. mobileShadowBiasAdd_ = add;
  414. }
  415. void Renderer::SetOccluderSizeThreshold(float screenSize)
  416. {
  417. occluderSizeThreshold_ = Max(screenSize, 0.0f);
  418. }
  419. void Renderer::ReloadShaders()
  420. {
  421. shadersDirty_ = true;
  422. }
  423. Viewport* Renderer::GetViewport(unsigned index) const
  424. {
  425. return index < viewports_.Size() ? viewports_[index] : (Viewport*)0;
  426. }
  427. RenderPath* Renderer::GetDefaultRenderPath() const
  428. {
  429. return defaultRenderPath_;
  430. }
  431. unsigned Renderer::GetNumGeometries(bool allViews) const
  432. {
  433. unsigned numGeometries = 0;
  434. unsigned lastView = allViews ? views_.Size() : 1;
  435. for (unsigned i = 0; i < lastView; ++i)
  436. {
  437. if (views_[i])
  438. numGeometries += views_[i]->GetGeometries().Size();
  439. }
  440. return numGeometries;
  441. }
  442. unsigned Renderer::GetNumLights(bool allViews) const
  443. {
  444. unsigned numLights = 0;
  445. unsigned lastView = allViews ? views_.Size() : 1;
  446. for (unsigned i = 0; i < lastView; ++i)
  447. {
  448. if (views_[i])
  449. numLights += views_[i]->GetLights().Size();
  450. }
  451. return numLights;
  452. }
  453. unsigned Renderer::GetNumShadowMaps(bool allViews) const
  454. {
  455. unsigned numShadowMaps = 0;
  456. unsigned lastView = allViews ? views_.Size() : 1;
  457. for (unsigned i = 0; i < lastView; ++i)
  458. {
  459. if (!views_[i])
  460. continue;
  461. const Vector<LightBatchQueue>& lightQueues = views_[i]->GetLightQueues();
  462. for (Vector<LightBatchQueue>::ConstIterator i = lightQueues.Begin(); i != lightQueues.End(); ++i)
  463. {
  464. if (i->shadowMap_)
  465. ++numShadowMaps;
  466. }
  467. }
  468. return numShadowMaps;
  469. }
  470. unsigned Renderer::GetNumOccluders(bool allViews) const
  471. {
  472. unsigned numOccluders = 0;
  473. unsigned lastView = allViews ? views_.Size() : 1;
  474. for (unsigned i = 0; i < lastView; ++i)
  475. {
  476. if (views_[i])
  477. numOccluders += views_[i]->GetOccluders().Size();
  478. }
  479. return numOccluders;
  480. }
  481. void Renderer::Update(float timeStep)
  482. {
  483. PROFILE(UpdateViews);
  484. views_.Clear();
  485. // If device lost, do not perform update. This is because any dynamic vertex/index buffer updates happen already here,
  486. // and if the device is lost, the updates queue up, causing memory use to rise constantly
  487. if (!graphics_ || !graphics_->IsInitialized() || graphics_->IsDeviceLost())
  488. return;
  489. // Set up the frameinfo structure for this frame
  490. frame_.frameNumber_ = GetSubsystem<Time>()->GetFrameNumber();
  491. frame_.timeStep_ = timeStep;
  492. frame_.camera_ = 0;
  493. numShadowCameras_ = 0;
  494. numOcclusionBuffers_ = 0;
  495. updatedOctrees_.Clear();
  496. // Reload shaders now if needed
  497. if (shadersDirty_)
  498. LoadShaders();
  499. // Queue update of the main viewports. Use reverse order, as rendering order is also reverse
  500. // to render auxiliary views before dependant main views
  501. for (unsigned i = viewports_.Size() - 1; i < viewports_.Size(); --i)
  502. QueueViewport(0, viewports_[i]);
  503. // Gather other render surfaces that are autoupdated
  504. SendEvent(E_RENDERSURFACEUPDATE);
  505. // Process gathered views. This may queue further views (render surfaces that are only updated when visible)
  506. for (unsigned i = 0; i < queuedViewports_.Size(); ++i)
  507. {
  508. WeakPtr<RenderSurface>& renderTarget = queuedViewports_[i].first_;
  509. WeakPtr<Viewport>& viewport = queuedViewports_[i].second_;
  510. // Null pointer means backbuffer view. Differentiate between that and an expired rendersurface
  511. if ((renderTarget.NotNull() && renderTarget.Expired()) || viewport.Expired())
  512. continue;
  513. // (Re)allocate the view structure if necessary
  514. if (!viewport->GetView() || resetViews_)
  515. viewport->AllocateView();
  516. View* view = viewport->GetView();
  517. assert(view);
  518. // Check if view can be defined successfully (has either valid scene, camera and octree, or no scene passes)
  519. if (!view->Define(renderTarget, viewport))
  520. continue;
  521. views_.Push(WeakPtr<View>(view));
  522. const IntRect& viewRect = viewport->GetRect();
  523. Scene* scene = viewport->GetScene();
  524. if (!scene)
  525. continue;
  526. Octree* octree = scene->GetComponent<Octree>();
  527. // Update octree (perform early update for drawables which need that, and reinsert moved drawables.)
  528. // However, if the same scene is viewed from multiple cameras, update the octree only once
  529. if (!updatedOctrees_.Contains(octree))
  530. {
  531. frame_.camera_ = viewport->GetCamera();
  532. frame_.viewSize_ = viewRect.Size();
  533. if (frame_.viewSize_ == IntVector2::ZERO)
  534. frame_.viewSize_ = IntVector2(graphics_->GetWidth(), graphics_->GetHeight());
  535. octree->Update(frame_);
  536. updatedOctrees_.Insert(octree);
  537. // Set also the view for the debug renderer already here, so that it can use culling
  538. /// \todo May result in incorrect debug geometry culling if the same scene is drawn from multiple viewports
  539. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  540. if (debug)
  541. debug->SetView(viewport->GetCamera());
  542. }
  543. // Update view. This may queue further views. View will send update begin/end events once its state is set
  544. ResetShadowMapAllocations(); // Each view can reuse the same shadow maps
  545. view->Update(frame_);
  546. }
  547. // Reset update flag from queued render surfaces. At this point no new views can be added on this frame
  548. for (unsigned i = 0; i < queuedViewports_.Size(); ++i)
  549. {
  550. WeakPtr<RenderSurface>& renderTarget = queuedViewports_[i].first_;
  551. if (renderTarget)
  552. renderTarget->WasUpdated();
  553. }
  554. queuedViewports_.Clear();
  555. resetViews_ = false;
  556. }
  557. void Renderer::Render()
  558. {
  559. // Engine does not render when window is closed or device is lost
  560. assert(graphics_ && graphics_->IsInitialized() && !graphics_->IsDeviceLost());
  561. PROFILE(RenderViews);
  562. // If the indirection textures have lost content (OpenGL mode only), restore them now
  563. if (faceSelectCubeMap_ && faceSelectCubeMap_->IsDataLost())
  564. SetIndirectionTextureData();
  565. graphics_->SetDefaultTextureFilterMode(textureFilterMode_);
  566. graphics_->SetTextureAnisotropy((unsigned)textureAnisotropy_);
  567. // If no views, just clear the screen
  568. if (views_.Empty())
  569. {
  570. graphics_->SetBlendMode(BLEND_REPLACE);
  571. graphics_->SetColorWrite(true);
  572. graphics_->SetDepthWrite(true);
  573. graphics_->SetScissorTest(false);
  574. graphics_->SetStencilTest(false);
  575. graphics_->ResetRenderTargets();
  576. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH | CLEAR_STENCIL, defaultZone_->GetFogColor());
  577. numPrimitives_ = 0;
  578. numBatches_ = 0;
  579. }
  580. else
  581. {
  582. // Render views from last to first (each main view is rendered after the auxiliary views it depends on)
  583. for (unsigned i = views_.Size() - 1; i < views_.Size(); --i)
  584. {
  585. if (!views_[i])
  586. continue;
  587. using namespace BeginViewRender;
  588. RenderSurface* renderTarget = views_[i]->GetRenderTarget();
  589. VariantMap& eventData = GetEventDataMap();
  590. eventData[P_VIEW] = views_[i];
  591. eventData[P_SURFACE] = renderTarget;
  592. eventData[P_TEXTURE] = (renderTarget ? renderTarget->GetParentTexture() : 0);
  593. eventData[P_SCENE] = views_[i]->GetScene();
  594. eventData[P_CAMERA] = views_[i]->GetCamera();
  595. SendEvent(E_BEGINVIEWRENDER, eventData);
  596. // Screen buffers can be reused between views, as each is rendered completely
  597. PrepareViewRender();
  598. views_[i]->Render();
  599. SendEvent(E_ENDVIEWRENDER, eventData);
  600. }
  601. // Copy the number of batches & primitives from Graphics so that we can account for 3D geometry only
  602. numPrimitives_ = graphics_->GetNumPrimitives();
  603. numBatches_ = graphics_->GetNumBatches();
  604. }
  605. // Remove unused occlusion buffers and renderbuffers
  606. RemoveUnusedBuffers();
  607. }
  608. void Renderer::DrawDebugGeometry(bool depthTest)
  609. {
  610. PROFILE(RendererDrawDebug);
  611. /// \todo Because debug geometry is per-scene, if two cameras show views of the same area, occlusion is not shown correctly
  612. HashSet<Drawable*> processedGeometries;
  613. HashSet<Light*> processedLights;
  614. for (unsigned i = 0; i < views_.Size(); ++i)
  615. {
  616. View* view = views_[i];
  617. if (!view || !view->GetDrawDebug())
  618. continue;
  619. Octree* octree = view->GetOctree();
  620. if (!octree)
  621. continue;
  622. DebugRenderer* debug = octree->GetComponent<DebugRenderer>();
  623. if (!debug || !debug->IsEnabledEffective())
  624. continue;
  625. // Process geometries / lights only once
  626. const PODVector<Drawable*>& geometries = view->GetGeometries();
  627. const PODVector<Light*>& lights = view->GetLights();
  628. for (unsigned i = 0; i < geometries.Size(); ++i)
  629. {
  630. if (!processedGeometries.Contains(geometries[i]))
  631. {
  632. geometries[i]->DrawDebugGeometry(debug, depthTest);
  633. processedGeometries.Insert(geometries[i]);
  634. }
  635. }
  636. for (unsigned i = 0; i < lights.Size(); ++i)
  637. {
  638. if (!processedLights.Contains(lights[i]))
  639. {
  640. lights[i]->DrawDebugGeometry(debug, depthTest);
  641. processedLights.Insert(lights[i]);
  642. }
  643. }
  644. }
  645. }
  646. void Renderer::QueueRenderSurface(RenderSurface* renderTarget)
  647. {
  648. if (renderTarget)
  649. {
  650. unsigned numViewports = renderTarget->GetNumViewports();
  651. for (unsigned i = 0; i < numViewports; ++i)
  652. QueueViewport(renderTarget, renderTarget->GetViewport(i));
  653. }
  654. }
  655. void Renderer::QueueViewport(RenderSurface* renderTarget, Viewport* viewport)
  656. {
  657. if (viewport)
  658. {
  659. queuedViewports_.Push(Pair<WeakPtr<RenderSurface>, WeakPtr<Viewport> >(WeakPtr<RenderSurface>(renderTarget),
  660. WeakPtr<Viewport>(viewport)));
  661. }
  662. }
  663. Geometry* Renderer::GetLightGeometry(Light* light)
  664. {
  665. switch (light->GetLightType())
  666. {
  667. case LIGHT_DIRECTIONAL:
  668. return dirLightGeometry_;
  669. case LIGHT_SPOT:
  670. return spotLightGeometry_;
  671. case LIGHT_POINT:
  672. return pointLightGeometry_;
  673. }
  674. return 0;
  675. }
  676. Geometry* Renderer::GetQuadGeometry()
  677. {
  678. return dirLightGeometry_;
  679. }
  680. Texture2D* Renderer::GetShadowMap(Light* light, Camera* camera, unsigned viewWidth, unsigned viewHeight)
  681. {
  682. LightType type = light->GetLightType();
  683. const FocusParameters& parameters = light->GetShadowFocus();
  684. float size = (float)shadowMapSize_ * light->GetShadowResolution();
  685. // Automatically reduce shadow map size when far away
  686. if (parameters.autoSize_ && type != LIGHT_DIRECTIONAL)
  687. {
  688. const Matrix3x4& view = camera->GetView();
  689. const Matrix4& projection = camera->GetProjection();
  690. BoundingBox lightBox;
  691. float lightPixels;
  692. if (type == LIGHT_POINT)
  693. {
  694. // Calculate point light pixel size from the projection of its diagonal
  695. Vector3 center = view * light->GetNode()->GetWorldPosition();
  696. float extent = 0.58f * light->GetRange();
  697. lightBox.Define(center + Vector3(extent, extent, extent), center - Vector3(extent, extent, extent));
  698. }
  699. else
  700. {
  701. // Calculate spot light pixel size from the projection of its frustum far vertices
  702. Frustum lightFrustum = light->GetFrustum().Transformed(view);
  703. lightBox.Define(&lightFrustum.vertices_[4], 4);
  704. }
  705. Vector2 projectionSize = lightBox.Projected(projection).Size();
  706. lightPixels = Max(0.5f * (float)viewWidth * projectionSize.x_, 0.5f * (float)viewHeight * projectionSize.y_);
  707. // Clamp pixel amount to a sufficient minimum to avoid self-shadowing artifacts due to loss of precision
  708. if (lightPixels < SHADOW_MIN_PIXELS)
  709. lightPixels = SHADOW_MIN_PIXELS;
  710. size = Min(size, lightPixels);
  711. }
  712. /// \todo Allow to specify maximum shadow maps per resolution, as smaller shadow maps take less memory
  713. int width = NextPowerOfTwo((unsigned)size);
  714. int height = width;
  715. // Adjust the size for directional or point light shadow map atlases
  716. if (type == LIGHT_DIRECTIONAL)
  717. {
  718. unsigned numSplits = (unsigned)light->GetNumShadowSplits();
  719. if (numSplits > 1)
  720. width *= 2;
  721. if (numSplits > 2)
  722. height *= 2;
  723. }
  724. else if (type == LIGHT_POINT)
  725. {
  726. width *= 2;
  727. height *= 3;
  728. }
  729. int searchKey = (width << 16) | height;
  730. if (shadowMaps_.Contains(searchKey))
  731. {
  732. // If shadow maps are reused, always return the first
  733. if (reuseShadowMaps_)
  734. return shadowMaps_[searchKey][0];
  735. else
  736. {
  737. // If not reused, check allocation count and return existing shadow map if possible
  738. unsigned allocated = shadowMapAllocations_[searchKey].Size();
  739. if (allocated < shadowMaps_[searchKey].Size())
  740. {
  741. shadowMapAllocations_[searchKey].Push(light);
  742. return shadowMaps_[searchKey][allocated];
  743. }
  744. else if ((int)allocated >= maxShadowMaps_)
  745. return 0;
  746. }
  747. }
  748. unsigned shadowMapFormat =
  749. (shadowQuality_ & SHADOWQUALITY_LOW_24BIT) ? graphics_->GetHiresShadowMapFormat() : graphics_->GetShadowMapFormat();
  750. if (!shadowMapFormat)
  751. return 0;
  752. SharedPtr<Texture2D> newShadowMap(new Texture2D(context_));
  753. int retries = 3;
  754. unsigned dummyColorFormat = graphics_->GetDummyColorFormat();
  755. while (retries)
  756. {
  757. if (!newShadowMap->SetSize(width, height, shadowMapFormat, TEXTURE_DEPTHSTENCIL))
  758. {
  759. width >>= 1;
  760. height >>= 1;
  761. --retries;
  762. }
  763. else
  764. {
  765. #ifndef GL_ES_VERSION_2_0
  766. // OpenGL (desktop) and D3D11: shadow compare mode needs to be specifically enabled for the shadow map
  767. newShadowMap->SetFilterMode(FILTER_BILINEAR);
  768. newShadowMap->SetShadowCompare(true);
  769. #endif
  770. #ifndef ATOMIC_OPENGL
  771. // Direct3D9: when shadow compare must be done manually, use nearest filtering so that the filtering of point lights
  772. // and other shadowed lights matches
  773. newShadowMap->SetFilterMode(graphics_->GetHardwareShadowSupport() ? FILTER_BILINEAR : FILTER_NEAREST);
  774. #endif
  775. // Create dummy color texture for the shadow map if necessary: Direct3D9, or OpenGL when working around an OS X +
  776. // Intel driver bug
  777. if (dummyColorFormat)
  778. {
  779. // If no dummy color rendertarget for this size exists yet, create one now
  780. if (!colorShadowMaps_.Contains(searchKey))
  781. {
  782. colorShadowMaps_[searchKey] = new Texture2D(context_);
  783. colorShadowMaps_[searchKey]->SetSize(width, height, dummyColorFormat, TEXTURE_RENDERTARGET);
  784. }
  785. // Link the color rendertarget to the shadow map
  786. newShadowMap->GetRenderSurface()->SetLinkedRenderTarget(colorShadowMaps_[searchKey]->GetRenderSurface());
  787. }
  788. break;
  789. }
  790. }
  791. // If failed to set size, store a null pointer so that we will not retry
  792. if (!retries)
  793. newShadowMap.Reset();
  794. shadowMaps_[searchKey].Push(newShadowMap);
  795. if (!reuseShadowMaps_)
  796. shadowMapAllocations_[searchKey].Push(light);
  797. return newShadowMap;
  798. }
  799. Texture* Renderer::GetScreenBuffer(int width, int height, unsigned format, bool cubemap, bool filtered, bool srgb,
  800. unsigned persistentKey)
  801. {
  802. bool depthStencil = (format == Graphics::GetDepthStencilFormat()) || (format == Graphics::GetReadableDepthFormat());
  803. if (depthStencil)
  804. {
  805. filtered = false;
  806. srgb = false;
  807. }
  808. if (cubemap)
  809. height = width;
  810. long long searchKey = ((long long)format << 32) | (width << 16) | height;
  811. if (filtered)
  812. searchKey |= 0x8000000000000000LL;
  813. if (srgb)
  814. searchKey |= 0x4000000000000000LL;
  815. if (cubemap)
  816. searchKey |= 0x2000000000000000LL;
  817. // Add persistent key if defined
  818. if (persistentKey)
  819. searchKey += ((long long)persistentKey << 32);
  820. // If new size or format, initialize the allocation stats
  821. if (screenBuffers_.Find(searchKey) == screenBuffers_.End())
  822. screenBufferAllocations_[searchKey] = 0;
  823. // Reuse depth-stencil buffers whenever the size matches, instead of allocating new
  824. unsigned allocations = screenBufferAllocations_[searchKey];
  825. if (!depthStencil)
  826. ++screenBufferAllocations_[searchKey];
  827. if (allocations >= screenBuffers_[searchKey].Size())
  828. {
  829. SharedPtr<Texture> newBuffer;
  830. if (!cubemap)
  831. {
  832. SharedPtr<Texture2D> newTex2D(new Texture2D(context_));
  833. newTex2D->SetSize(width, height, format, depthStencil ? TEXTURE_DEPTHSTENCIL : TEXTURE_RENDERTARGET);
  834. #ifdef ATOMIC_OPENGL
  835. // OpenGL hack: clear persistent floating point screen buffers to ensure the initial contents aren't illegal (NaN)?
  836. // Otherwise eg. the AutoExposure post process will not work correctly
  837. if (persistentKey && Texture::GetDataType(format) == GL_FLOAT)
  838. {
  839. // Note: this loses current rendertarget assignment
  840. graphics_->ResetRenderTargets();
  841. graphics_->SetRenderTarget(0, newTex2D);
  842. graphics_->SetDepthStencil((RenderSurface*)0);
  843. graphics_->SetViewport(IntRect(0, 0, width, height));
  844. graphics_->Clear(CLEAR_COLOR);
  845. }
  846. #endif
  847. newBuffer = StaticCast<Texture>(newTex2D);
  848. }
  849. else
  850. {
  851. SharedPtr<TextureCube> newTexCube(new TextureCube(context_));
  852. newTexCube->SetSize(width, format, TEXTURE_RENDERTARGET);
  853. newBuffer = StaticCast<Texture>(newTexCube);
  854. }
  855. newBuffer->SetSRGB(srgb);
  856. newBuffer->SetFilterMode(filtered ? FILTER_BILINEAR : FILTER_NEAREST);
  857. newBuffer->ResetUseTimer();
  858. screenBuffers_[searchKey].Push(newBuffer);
  859. LOGDEBUG("Allocated new screen buffer size " + String(width) + "x" + String(height) + " format " + String(format));
  860. return newBuffer;
  861. }
  862. else
  863. {
  864. Texture* buffer = screenBuffers_[searchKey][allocations];
  865. buffer->ResetUseTimer();
  866. return buffer;
  867. }
  868. }
  869. RenderSurface* Renderer::GetDepthStencil(int width, int height)
  870. {
  871. // Return the default depth-stencil surface if applicable
  872. // (when using OpenGL Graphics will allocate right size surfaces on demand to emulate Direct3D9)
  873. if (width == graphics_->GetWidth() && height == graphics_->GetHeight() && graphics_->GetMultiSample() <= 1)
  874. return 0;
  875. else
  876. {
  877. return static_cast<Texture2D*>(GetScreenBuffer(width, height, Graphics::GetDepthStencilFormat(), false, false,
  878. false))->GetRenderSurface();
  879. }
  880. }
  881. OcclusionBuffer* Renderer::GetOcclusionBuffer(Camera* camera)
  882. {
  883. assert(numOcclusionBuffers_ <= occlusionBuffers_.Size());
  884. if (numOcclusionBuffers_ == occlusionBuffers_.Size())
  885. {
  886. SharedPtr<OcclusionBuffer> newBuffer(new OcclusionBuffer(context_));
  887. occlusionBuffers_.Push(newBuffer);
  888. }
  889. int width = occlusionBufferSize_;
  890. int height = (int)((float)occlusionBufferSize_ / camera->GetAspectRatio() + 0.5f);
  891. OcclusionBuffer* buffer = occlusionBuffers_[numOcclusionBuffers_++];
  892. buffer->SetSize(width, height);
  893. buffer->SetView(camera);
  894. buffer->ResetUseTimer();
  895. return buffer;
  896. }
  897. Camera* Renderer::GetShadowCamera()
  898. {
  899. MutexLock lock(rendererMutex_);
  900. assert(numShadowCameras_ <= shadowCameraNodes_.Size());
  901. if (numShadowCameras_ == shadowCameraNodes_.Size())
  902. {
  903. SharedPtr<Node> newNode(new Node(context_));
  904. newNode->CreateComponent<Camera>();
  905. shadowCameraNodes_.Push(newNode);
  906. }
  907. Camera* camera = shadowCameraNodes_[numShadowCameras_++]->GetComponent<Camera>();
  908. camera->SetOrthographic(false);
  909. camera->SetZoom(1.0f);
  910. return camera;
  911. }
  912. void Renderer::SetBatchShaders(Batch& batch, Technique* tech, bool allowShadows)
  913. {
  914. // Check if shaders are unloaded or need reloading
  915. Pass* pass = batch.pass_;
  916. Vector<SharedPtr<ShaderVariation> >& vertexShaders = pass->GetVertexShaders();
  917. Vector<SharedPtr<ShaderVariation> >& pixelShaders = pass->GetPixelShaders();
  918. if (!vertexShaders.Size() || !pixelShaders.Size() || pass->GetShadersLoadedFrameNumber() != shadersChangedFrameNumber_)
  919. {
  920. // First release all previous shaders, then load
  921. pass->ReleaseShaders();
  922. LoadPassShaders(pass);
  923. }
  924. // Make sure shaders are loaded now
  925. if (vertexShaders.Size() && pixelShaders.Size())
  926. {
  927. bool heightFog = batch.zone_ && batch.zone_->GetHeightFog();
  928. // If instancing is not supported, but was requested, choose static geometry vertex shader instead
  929. if (batch.geometryType_ == GEOM_INSTANCED && !GetDynamicInstancing())
  930. batch.geometryType_ = GEOM_STATIC;
  931. if (batch.geometryType_ == GEOM_STATIC_NOINSTANCING)
  932. batch.geometryType_ = GEOM_STATIC;
  933. // Check whether is a pixel lit forward pass. If not, there is only one pixel shader
  934. if (pass->GetLightingMode() == LIGHTING_PERPIXEL)
  935. {
  936. LightBatchQueue* lightQueue = batch.lightQueue_;
  937. if (!lightQueue)
  938. {
  939. // Do not log error, as it would result in a lot of spam
  940. batch.vertexShader_ = 0;
  941. batch.pixelShader_ = 0;
  942. return;
  943. }
  944. Light* light = lightQueue->light_;
  945. unsigned vsi = 0;
  946. unsigned psi = 0;
  947. vsi = batch.geometryType_ * MAX_LIGHT_VS_VARIATIONS;
  948. bool materialHasSpecular = batch.material_ ? batch.material_->GetSpecular() : true;
  949. if (specularLighting_ && light->GetSpecularIntensity() > 0.0f && materialHasSpecular)
  950. psi += LPS_SPEC;
  951. if (allowShadows && lightQueue->shadowMap_)
  952. {
  953. vsi += LVS_SHADOW;
  954. psi += LPS_SHADOW;
  955. }
  956. switch (light->GetLightType())
  957. {
  958. case LIGHT_DIRECTIONAL:
  959. vsi += LVS_DIR;
  960. break;
  961. case LIGHT_SPOT:
  962. psi += LPS_SPOT;
  963. vsi += LVS_SPOT;
  964. break;
  965. case LIGHT_POINT:
  966. if (light->GetShapeTexture())
  967. psi += LPS_POINTMASK;
  968. else
  969. psi += LPS_POINT;
  970. vsi += LVS_POINT;
  971. break;
  972. }
  973. if (heightFog)
  974. psi += MAX_LIGHT_PS_VARIATIONS;
  975. batch.vertexShader_ = vertexShaders[vsi];
  976. batch.pixelShader_ = pixelShaders[psi];
  977. }
  978. else
  979. {
  980. // Check if pass has vertex lighting support
  981. if (pass->GetLightingMode() == LIGHTING_PERVERTEX)
  982. {
  983. unsigned numVertexLights = 0;
  984. if (batch.lightQueue_)
  985. numVertexLights = batch.lightQueue_->vertexLights_.Size();
  986. unsigned vsi = batch.geometryType_ * MAX_VERTEXLIGHT_VS_VARIATIONS + numVertexLights;
  987. batch.vertexShader_ = vertexShaders[vsi];
  988. }
  989. else
  990. {
  991. unsigned vsi = batch.geometryType_;
  992. batch.vertexShader_ = vertexShaders[vsi];
  993. }
  994. batch.pixelShader_ = pixelShaders[heightFog ? 1 : 0];
  995. }
  996. }
  997. // Log error if shaders could not be assigned, but only once per technique
  998. if (!batch.vertexShader_ || !batch.pixelShader_)
  999. {
  1000. if (!shaderErrorDisplayed_.Contains(tech))
  1001. {
  1002. shaderErrorDisplayed_.Insert(tech);
  1003. LOGERROR("Technique " + tech->GetName() + " has missing shaders");
  1004. }
  1005. }
  1006. }
  1007. void Renderer::SetLightVolumeBatchShaders(Batch& batch, const String& vsName, const String& psName, const String& vsDefines,
  1008. const String& psDefines)
  1009. {
  1010. assert(deferredLightPSVariations_.Size());
  1011. unsigned vsi = DLVS_NONE;
  1012. unsigned psi = DLPS_NONE;
  1013. Light* light = batch.lightQueue_->light_;
  1014. switch (light->GetLightType())
  1015. {
  1016. case LIGHT_DIRECTIONAL:
  1017. vsi += DLVS_DIR;
  1018. break;
  1019. case LIGHT_SPOT:
  1020. psi += DLPS_SPOT;
  1021. break;
  1022. case LIGHT_POINT:
  1023. if (light->GetShapeTexture())
  1024. psi += DLPS_POINTMASK;
  1025. else
  1026. psi += DLPS_POINT;
  1027. break;
  1028. }
  1029. if (batch.lightQueue_->shadowMap_)
  1030. psi += DLPS_SHADOW;
  1031. if (specularLighting_ && light->GetSpecularIntensity() > 0.0f)
  1032. psi += DLPS_SPEC;
  1033. if (batch.camera_->IsOrthographic())
  1034. {
  1035. vsi += DLVS_ORTHO;
  1036. psi += DLPS_ORTHO;
  1037. }
  1038. if (vsDefines.Length())
  1039. batch.vertexShader_ = graphics_->GetShader(VS, vsName, deferredLightVSVariations[vsi] + vsDefines);
  1040. else
  1041. batch.vertexShader_ = graphics_->GetShader(VS, vsName, deferredLightVSVariations[vsi]);
  1042. if (psDefines.Length())
  1043. batch.pixelShader_ = graphics_->GetShader(PS, psName, deferredLightPSVariations_[psi] + psDefines);
  1044. else
  1045. batch.pixelShader_ = graphics_->GetShader(PS, psName, deferredLightPSVariations_[psi]);
  1046. }
  1047. void Renderer::SetCullMode(CullMode mode, Camera* camera)
  1048. {
  1049. // If a camera is specified, check whether it reverses culling due to vertical flipping or reflection
  1050. if (camera && camera->GetReverseCulling())
  1051. {
  1052. if (mode == CULL_CW)
  1053. mode = CULL_CCW;
  1054. else if (mode == CULL_CCW)
  1055. mode = CULL_CW;
  1056. }
  1057. graphics_->SetCullMode(mode);
  1058. }
  1059. bool Renderer::ResizeInstancingBuffer(unsigned numInstances)
  1060. {
  1061. if (!instancingBuffer_ || !dynamicInstancing_)
  1062. return false;
  1063. unsigned oldSize = instancingBuffer_->GetVertexCount();
  1064. if (numInstances <= oldSize)
  1065. return true;
  1066. unsigned newSize = INSTANCING_BUFFER_DEFAULT_SIZE;
  1067. while (newSize < numInstances)
  1068. newSize <<= 1;
  1069. if (!instancingBuffer_->SetSize(newSize, INSTANCING_BUFFER_MASK, true))
  1070. {
  1071. LOGERROR("Failed to resize instancing buffer to " + String(newSize));
  1072. // If failed, try to restore the old size
  1073. instancingBuffer_->SetSize(oldSize, INSTANCING_BUFFER_MASK, true);
  1074. return false;
  1075. }
  1076. LOGDEBUG("Resized instancing buffer to " + String(newSize));
  1077. return true;
  1078. }
  1079. void Renderer::SaveScreenBufferAllocations()
  1080. {
  1081. savedScreenBufferAllocations_ = screenBufferAllocations_;
  1082. }
  1083. void Renderer::RestoreScreenBufferAllocations()
  1084. {
  1085. screenBufferAllocations_ = savedScreenBufferAllocations_;
  1086. }
  1087. void Renderer::OptimizeLightByScissor(Light* light, Camera* camera)
  1088. {
  1089. if (light && light->GetLightType() != LIGHT_DIRECTIONAL)
  1090. graphics_->SetScissorTest(true, GetLightScissor(light, camera));
  1091. else
  1092. graphics_->SetScissorTest(false);
  1093. }
  1094. void Renderer::OptimizeLightByStencil(Light* light, Camera* camera)
  1095. {
  1096. if (light)
  1097. {
  1098. LightType type = light->GetLightType();
  1099. if (type == LIGHT_DIRECTIONAL)
  1100. {
  1101. graphics_->SetStencilTest(false);
  1102. return;
  1103. }
  1104. Geometry* geometry = GetLightGeometry(light);
  1105. const Matrix3x4& view = camera->GetView();
  1106. const Matrix4& projection = camera->GetProjection();
  1107. Vector3 cameraPos = camera->GetNode()->GetWorldPosition();
  1108. float lightDist;
  1109. if (type == LIGHT_POINT)
  1110. lightDist = Sphere(light->GetNode()->GetWorldPosition(), light->GetRange() * 1.25f).Distance(cameraPos);
  1111. else
  1112. lightDist = light->GetFrustum().Distance(cameraPos);
  1113. // If the camera is actually inside the light volume, do not draw to stencil as it would waste fillrate
  1114. if (lightDist < M_EPSILON)
  1115. {
  1116. graphics_->SetStencilTest(false);
  1117. return;
  1118. }
  1119. // If the stencil value has wrapped, clear the whole stencil first
  1120. if (!lightStencilValue_)
  1121. {
  1122. graphics_->Clear(CLEAR_STENCIL);
  1123. lightStencilValue_ = 1;
  1124. }
  1125. // If possible, render the stencil volume front faces. However, close to the near clip plane render back faces instead
  1126. // to avoid clipping.
  1127. if (lightDist < camera->GetNearClip() * 2.0f)
  1128. {
  1129. SetCullMode(CULL_CW, camera);
  1130. graphics_->SetDepthTest(CMP_GREATER);
  1131. }
  1132. else
  1133. {
  1134. SetCullMode(CULL_CCW, camera);
  1135. graphics_->SetDepthTest(CMP_LESSEQUAL);
  1136. }
  1137. graphics_->SetColorWrite(false);
  1138. graphics_->SetDepthWrite(false);
  1139. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, lightStencilValue_);
  1140. graphics_->SetShaders(graphics_->GetShader(VS, "Stencil"), graphics_->GetShader(PS, "Stencil"));
  1141. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection * view);
  1142. graphics_->SetShaderParameter(VSP_MODEL, light->GetVolumeTransform(camera));
  1143. geometry->Draw(graphics_);
  1144. graphics_->ClearTransformSources();
  1145. graphics_->SetColorWrite(true);
  1146. graphics_->SetStencilTest(true, CMP_EQUAL, OP_KEEP, OP_KEEP, OP_KEEP, lightStencilValue_);
  1147. // Increase stencil value for next light
  1148. ++lightStencilValue_;
  1149. }
  1150. else
  1151. graphics_->SetStencilTest(false);
  1152. }
  1153. const Rect& Renderer::GetLightScissor(Light* light, Camera* camera)
  1154. {
  1155. Pair<Light*, Camera*> combination(light, camera);
  1156. HashMap<Pair<Light*, Camera*>, Rect>::Iterator i = lightScissorCache_.Find(combination);
  1157. if (i != lightScissorCache_.End())
  1158. return i->second_;
  1159. const Matrix3x4& view = camera->GetView();
  1160. const Matrix4& projection = camera->GetProjection();
  1161. assert(light->GetLightType() != LIGHT_DIRECTIONAL);
  1162. if (light->GetLightType() == LIGHT_SPOT)
  1163. {
  1164. Frustum viewFrustum(light->GetFrustum().Transformed(view));
  1165. return lightScissorCache_[combination] = viewFrustum.Projected(projection);
  1166. }
  1167. else // LIGHT_POINT
  1168. {
  1169. BoundingBox viewBox(light->GetWorldBoundingBox().Transformed(view));
  1170. return lightScissorCache_[combination] = viewBox.Projected(projection);
  1171. }
  1172. }
  1173. void Renderer::PrepareViewRender()
  1174. {
  1175. ResetScreenBufferAllocations();
  1176. lightScissorCache_.Clear();
  1177. lightStencilValue_ = 1;
  1178. }
  1179. void Renderer::RemoveUnusedBuffers()
  1180. {
  1181. for (unsigned i = occlusionBuffers_.Size() - 1; i < occlusionBuffers_.Size(); --i)
  1182. {
  1183. if (occlusionBuffers_[i]->GetUseTimer() > MAX_BUFFER_AGE)
  1184. {
  1185. LOGDEBUG("Removed unused occlusion buffer");
  1186. occlusionBuffers_.Erase(i);
  1187. }
  1188. }
  1189. for (HashMap<long long, Vector<SharedPtr<Texture> > >::Iterator i = screenBuffers_.Begin(); i != screenBuffers_.End();)
  1190. {
  1191. HashMap<long long, Vector<SharedPtr<Texture> > >::Iterator current = i++;
  1192. Vector<SharedPtr<Texture> >& buffers = current->second_;
  1193. for (unsigned j = buffers.Size() - 1; j < buffers.Size(); --j)
  1194. {
  1195. Texture* buffer = buffers[j];
  1196. if (buffer->GetUseTimer() > MAX_BUFFER_AGE)
  1197. {
  1198. LOGDEBUG("Removed unused screen buffer size " + String(buffer->GetWidth()) + "x" + String(buffer->GetHeight()) +
  1199. " format " + String(buffer->GetFormat()));
  1200. buffers.Erase(j);
  1201. }
  1202. }
  1203. if (buffers.Empty())
  1204. {
  1205. screenBufferAllocations_.Erase(current->first_);
  1206. screenBuffers_.Erase(current);
  1207. }
  1208. }
  1209. }
  1210. void Renderer::ResetShadowMapAllocations()
  1211. {
  1212. for (HashMap<int, PODVector<Light*> >::Iterator i = shadowMapAllocations_.Begin(); i != shadowMapAllocations_.End(); ++i)
  1213. i->second_.Clear();
  1214. }
  1215. void Renderer::ResetScreenBufferAllocations()
  1216. {
  1217. for (HashMap<long long, unsigned>::Iterator i = screenBufferAllocations_.Begin(); i != screenBufferAllocations_.End(); ++i)
  1218. i->second_ = 0;
  1219. }
  1220. void Renderer::Initialize()
  1221. {
  1222. Graphics* graphics = GetSubsystem<Graphics>();
  1223. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1224. if (!graphics || !graphics->IsInitialized() || !cache)
  1225. return;
  1226. PROFILE(InitRenderer);
  1227. graphics_ = graphics;
  1228. if (!graphics_->GetShadowMapFormat())
  1229. drawShadows_ = false;
  1230. // Validate the shadow quality level
  1231. SetShadowQuality(shadowQuality_);
  1232. defaultLightRamp_ = cache->GetResource<Texture2D>("Textures/Ramp.png");
  1233. defaultLightSpot_ = cache->GetResource<Texture2D>("Textures/Spot.png");
  1234. defaultMaterial_ = new Material(context_);
  1235. defaultRenderPath_ = new RenderPath();
  1236. defaultRenderPath_->Load(cache->GetResource<XMLFile>("RenderPaths/Forward.xml"));
  1237. CreateGeometries();
  1238. CreateInstancingBuffer();
  1239. viewports_.Resize(1);
  1240. ResetShadowMaps();
  1241. ResetBuffers();
  1242. shadersDirty_ = true;
  1243. initialized_ = true;
  1244. SubscribeToEvent(E_RENDERUPDATE, HANDLER(Renderer, HandleRenderUpdate));
  1245. LOGINFO("Initialized renderer");
  1246. }
  1247. void Renderer::LoadShaders()
  1248. {
  1249. LOGDEBUG("Reloading shaders");
  1250. // Release old material shaders, mark them for reload
  1251. ReleaseMaterialShaders();
  1252. shadersChangedFrameNumber_ = GetSubsystem<Time>()->GetFrameNumber();
  1253. // Construct new names for deferred light volume pixel shaders based on rendering options
  1254. deferredLightPSVariations_.Resize(MAX_DEFERRED_LIGHT_PS_VARIATIONS);
  1255. unsigned shadows = (unsigned)((graphics_->GetHardwareShadowSupport() ? 1 : 0) | (shadowQuality_ & SHADOWQUALITY_HIGH_16BIT));
  1256. for (unsigned i = 0; i < MAX_DEFERRED_LIGHT_PS_VARIATIONS; ++i)
  1257. {
  1258. deferredLightPSVariations_[i] = lightPSVariations[i % DLPS_ORTHO];
  1259. if (i & DLPS_SHADOW)
  1260. deferredLightPSVariations_[i] += shadowVariations[shadows];
  1261. if (i & DLPS_ORTHO)
  1262. deferredLightPSVariations_[i] += "ORTHO ";
  1263. }
  1264. shadersDirty_ = false;
  1265. }
  1266. void Renderer::LoadPassShaders(Pass* pass)
  1267. {
  1268. PROFILE(LoadPassShaders);
  1269. unsigned shadows = (unsigned)((graphics_->GetHardwareShadowSupport() ? 1 : 0) | (shadowQuality_ & SHADOWQUALITY_HIGH_16BIT));
  1270. Vector<SharedPtr<ShaderVariation> >& vertexShaders = pass->GetVertexShaders();
  1271. Vector<SharedPtr<ShaderVariation> >& pixelShaders = pass->GetPixelShaders();
  1272. // Forget all the old shaders
  1273. vertexShaders.Clear();
  1274. pixelShaders.Clear();
  1275. if (pass->GetLightingMode() == LIGHTING_PERPIXEL)
  1276. {
  1277. // Load forward pixel lit variations
  1278. vertexShaders.Resize(MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS);
  1279. pixelShaders.Resize(MAX_LIGHT_PS_VARIATIONS * 2);
  1280. for (unsigned j = 0; j < MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS; ++j)
  1281. {
  1282. unsigned g = j / MAX_LIGHT_VS_VARIATIONS;
  1283. unsigned l = j % MAX_LIGHT_VS_VARIATIONS;
  1284. vertexShaders[j] = graphics_->GetShader(VS, pass->GetVertexShader(),
  1285. pass->GetVertexShaderDefines() + " " + lightVSVariations[l] + geometryVSVariations[g]);
  1286. }
  1287. for (unsigned j = 0; j < MAX_LIGHT_PS_VARIATIONS * 2; ++j)
  1288. {
  1289. unsigned l = j % MAX_LIGHT_PS_VARIATIONS;
  1290. unsigned h = j / MAX_LIGHT_PS_VARIATIONS;
  1291. if (l & LPS_SHADOW)
  1292. {
  1293. pixelShaders[j] = graphics_->GetShader(PS, pass->GetPixelShader(),
  1294. pass->GetPixelShaderDefines() + " " + lightPSVariations[l] + shadowVariations[shadows] +
  1295. heightFogVariations[h]);
  1296. }
  1297. else
  1298. pixelShaders[j] = graphics_->GetShader(PS, pass->GetPixelShader(),
  1299. pass->GetPixelShaderDefines() + " " + lightPSVariations[l] + heightFogVariations[h]);
  1300. }
  1301. }
  1302. else
  1303. {
  1304. // Load vertex light variations
  1305. if (pass->GetLightingMode() == LIGHTING_PERVERTEX)
  1306. {
  1307. vertexShaders.Resize(MAX_GEOMETRYTYPES * MAX_VERTEXLIGHT_VS_VARIATIONS);
  1308. for (unsigned j = 0; j < MAX_GEOMETRYTYPES * MAX_VERTEXLIGHT_VS_VARIATIONS; ++j)
  1309. {
  1310. unsigned g = j / MAX_VERTEXLIGHT_VS_VARIATIONS;
  1311. unsigned l = j % MAX_VERTEXLIGHT_VS_VARIATIONS;
  1312. vertexShaders[j] = graphics_->GetShader(VS, pass->GetVertexShader(),
  1313. pass->GetVertexShaderDefines() + " " + vertexLightVSVariations[l] + geometryVSVariations[g]);
  1314. }
  1315. }
  1316. else
  1317. {
  1318. vertexShaders.Resize(MAX_GEOMETRYTYPES);
  1319. for (unsigned j = 0; j < MAX_GEOMETRYTYPES; ++j)
  1320. {
  1321. vertexShaders[j] = graphics_->GetShader(VS, pass->GetVertexShader(),
  1322. pass->GetVertexShaderDefines() + " " + geometryVSVariations[j]);
  1323. }
  1324. }
  1325. pixelShaders.Resize(2);
  1326. for (unsigned j = 0; j < 2; ++j)
  1327. {
  1328. pixelShaders[j] =
  1329. graphics_->GetShader(PS, pass->GetPixelShader(), pass->GetPixelShaderDefines() + " " + heightFogVariations[j]);
  1330. }
  1331. }
  1332. pass->MarkShadersLoaded(shadersChangedFrameNumber_);
  1333. }
  1334. void Renderer::ReleaseMaterialShaders()
  1335. {
  1336. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1337. PODVector<Material*> materials;
  1338. cache->GetResources<Material>(materials);
  1339. for (unsigned i = 0; i < materials.Size(); ++i)
  1340. materials[i]->ReleaseShaders();
  1341. }
  1342. void Renderer::ReloadTextures()
  1343. {
  1344. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1345. PODVector<Resource*> textures;
  1346. cache->GetResources(textures, Texture2D::GetTypeStatic());
  1347. for (unsigned i = 0; i < textures.Size(); ++i)
  1348. cache->ReloadResource(textures[i]);
  1349. cache->GetResources(textures, TextureCube::GetTypeStatic());
  1350. for (unsigned i = 0; i < textures.Size(); ++i)
  1351. cache->ReloadResource(textures[i]);
  1352. }
  1353. void Renderer::CreateGeometries()
  1354. {
  1355. SharedPtr<VertexBuffer> dlvb(new VertexBuffer(context_));
  1356. dlvb->SetShadowed(true);
  1357. dlvb->SetSize(4, MASK_POSITION);
  1358. dlvb->SetData(dirLightVertexData);
  1359. SharedPtr<IndexBuffer> dlib(new IndexBuffer(context_));
  1360. dlib->SetShadowed(true);
  1361. dlib->SetSize(6, false);
  1362. dlib->SetData(dirLightIndexData);
  1363. dirLightGeometry_ = new Geometry(context_);
  1364. dirLightGeometry_->SetVertexBuffer(0, dlvb);
  1365. dirLightGeometry_->SetIndexBuffer(dlib);
  1366. dirLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, dlib->GetIndexCount());
  1367. SharedPtr<VertexBuffer> slvb(new VertexBuffer(context_));
  1368. slvb->SetShadowed(true);
  1369. slvb->SetSize(8, MASK_POSITION);
  1370. slvb->SetData(spotLightVertexData);
  1371. SharedPtr<IndexBuffer> slib(new IndexBuffer(context_));
  1372. slib->SetShadowed(true);
  1373. slib->SetSize(36, false);
  1374. slib->SetData(spotLightIndexData);
  1375. spotLightGeometry_ = new Geometry(context_);
  1376. spotLightGeometry_->SetVertexBuffer(0, slvb);
  1377. spotLightGeometry_->SetIndexBuffer(slib);
  1378. spotLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, slib->GetIndexCount());
  1379. SharedPtr<VertexBuffer> plvb(new VertexBuffer(context_));
  1380. plvb->SetShadowed(true);
  1381. plvb->SetSize(24, MASK_POSITION);
  1382. plvb->SetData(pointLightVertexData);
  1383. SharedPtr<IndexBuffer> plib(new IndexBuffer(context_));
  1384. plib->SetShadowed(true);
  1385. plib->SetSize(132, false);
  1386. plib->SetData(pointLightIndexData);
  1387. pointLightGeometry_ = new Geometry(context_);
  1388. pointLightGeometry_->SetVertexBuffer(0, plvb);
  1389. pointLightGeometry_->SetIndexBuffer(plib);
  1390. pointLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, plib->GetIndexCount());
  1391. #if !defined(ATOMIC_OPENGL) || !defined(GL_ES_VERSION_2_0)
  1392. if (graphics_->GetShadowMapFormat())
  1393. {
  1394. faceSelectCubeMap_ = new TextureCube(context_);
  1395. faceSelectCubeMap_->SetNumLevels(1);
  1396. faceSelectCubeMap_->SetSize(1, graphics_->GetRGBAFormat());
  1397. faceSelectCubeMap_->SetFilterMode(FILTER_NEAREST);
  1398. indirectionCubeMap_ = new TextureCube(context_);
  1399. indirectionCubeMap_->SetNumLevels(1);
  1400. indirectionCubeMap_->SetSize(256, graphics_->GetRGBAFormat());
  1401. indirectionCubeMap_->SetFilterMode(FILTER_BILINEAR);
  1402. indirectionCubeMap_->SetAddressMode(COORD_U, ADDRESS_CLAMP);
  1403. indirectionCubeMap_->SetAddressMode(COORD_V, ADDRESS_CLAMP);
  1404. indirectionCubeMap_->SetAddressMode(COORD_W, ADDRESS_CLAMP);
  1405. SetIndirectionTextureData();
  1406. }
  1407. #endif
  1408. }
  1409. void Renderer::SetIndirectionTextureData()
  1410. {
  1411. unsigned char data[256 * 256 * 4];
  1412. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1413. {
  1414. unsigned axis = i / 2;
  1415. data[0] = (unsigned char)((axis == 0) ? 255 : 0);
  1416. data[1] = (unsigned char)((axis == 1) ? 255 : 0);
  1417. data[2] = (unsigned char)((axis == 2) ? 255 : 0);
  1418. data[3] = 0;
  1419. faceSelectCubeMap_->SetData((CubeMapFace)i, 0, 0, 0, 1, 1, data);
  1420. }
  1421. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1422. {
  1423. unsigned char faceX = (unsigned char)((i & 1) * 255);
  1424. unsigned char faceY = (unsigned char)((i / 2) * 255 / 3);
  1425. unsigned char* dest = data;
  1426. for (unsigned y = 0; y < 256; ++y)
  1427. {
  1428. for (unsigned x = 0; x < 256; ++x)
  1429. {
  1430. #ifdef ATOMIC_OPENGL
  1431. dest[0] = (unsigned char)x;
  1432. dest[1] = (unsigned char)(255 - y);
  1433. dest[2] = faceX;
  1434. dest[3] = (unsigned char)(255 * 2 / 3 - faceY);
  1435. #else
  1436. dest[0] = (unsigned char)x;
  1437. dest[1] = (unsigned char)y;
  1438. dest[2] = faceX;
  1439. dest[3] = faceY;
  1440. #endif
  1441. dest += 4;
  1442. }
  1443. }
  1444. indirectionCubeMap_->SetData((CubeMapFace)i, 0, 0, 0, 256, 256, data);
  1445. }
  1446. faceSelectCubeMap_->ClearDataLost();
  1447. indirectionCubeMap_->ClearDataLost();
  1448. }
  1449. void Renderer::CreateInstancingBuffer()
  1450. {
  1451. // Do not create buffer if instancing not supported
  1452. if (!graphics_->GetInstancingSupport())
  1453. {
  1454. instancingBuffer_.Reset();
  1455. dynamicInstancing_ = false;
  1456. return;
  1457. }
  1458. instancingBuffer_ = new VertexBuffer(context_);
  1459. if (!instancingBuffer_->SetSize(INSTANCING_BUFFER_DEFAULT_SIZE, INSTANCING_BUFFER_MASK, true))
  1460. {
  1461. instancingBuffer_.Reset();
  1462. dynamicInstancing_ = false;
  1463. }
  1464. }
  1465. void Renderer::ResetShadowMaps()
  1466. {
  1467. shadowMaps_.Clear();
  1468. shadowMapAllocations_.Clear();
  1469. colorShadowMaps_.Clear();
  1470. }
  1471. void Renderer::ResetBuffers()
  1472. {
  1473. occlusionBuffers_.Clear();
  1474. screenBuffers_.Clear();
  1475. screenBufferAllocations_.Clear();
  1476. }
  1477. void Renderer::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  1478. {
  1479. if (!initialized_)
  1480. Initialize();
  1481. else
  1482. resetViews_ = true;
  1483. }
  1484. void Renderer::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  1485. {
  1486. using namespace RenderUpdate;
  1487. Update(eventData[P_TIMESTEP].GetFloat());
  1488. }
  1489. }