Renderer.cpp 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Camera.h"
  25. #include "CoreEvents.h"
  26. #include "DebugRenderer.h"
  27. #include "Geometry.h"
  28. #include "Graphics.h"
  29. #include "GraphicsEvents.h"
  30. #include "GraphicsImpl.h"
  31. #include "IndexBuffer.h"
  32. #include "Light.h"
  33. #include "Log.h"
  34. #include "Material.h"
  35. #include "OcclusionBuffer.h"
  36. #include "Octree.h"
  37. #include "Profiler.h"
  38. #include "Renderer.h"
  39. #include "ResourceCache.h"
  40. #include "Scene.h"
  41. #include "Shader.h"
  42. #include "ShaderVariation.h"
  43. #include "Technique.h"
  44. #include "Texture2D.h"
  45. #include "TextureCube.h"
  46. #include "VertexBuffer.h"
  47. #include "View.h"
  48. #include "XMLFile.h"
  49. #include "Zone.h"
  50. #include "DebugNew.h"
  51. static const float dirLightVertexData[] =
  52. {
  53. -1, 1, 0,
  54. 1, 1, 0,
  55. 1, -1, 0,
  56. -1, -1, 0,
  57. };
  58. static const unsigned short dirLightIndexData[] =
  59. {
  60. 0, 1, 2,
  61. 2, 3, 0,
  62. };
  63. static const float pointLightVertexData[] =
  64. {
  65. -0.423169f, -1.000000f, 0.423169f,
  66. -0.423169f, -1.000000f, -0.423169f,
  67. 0.423169f, -1.000000f, -0.423169f,
  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. -1.000000f, 0.423169f, -0.423169f,
  74. -1.000000f, -0.423169f, -0.423169f,
  75. -1.000000f, -0.423169f, 0.423169f,
  76. -1.000000f, 0.423169f, 0.423169f,
  77. 0.423169f, 0.423169f, -1.000000f,
  78. 0.423169f, -0.423169f, -1.000000f,
  79. -0.423169f, -0.423169f, -1.000000f,
  80. -0.423169f, 0.423169f, -1.000000f,
  81. 1.000000f, 0.423169f, 0.423169f,
  82. 1.000000f, -0.423169f, 0.423169f,
  83. 1.000000f, -0.423169f, -0.423169f,
  84. 1.000000f, 0.423169f, -0.423169f,
  85. 0.423169f, -0.423169f, 1.000000f,
  86. 0.423169f, 0.423169f, 1.000000f,
  87. -0.423169f, 0.423169f, 1.000000f,
  88. -0.423169f, -0.423169f, 1.000000f
  89. };
  90. static const unsigned short pointLightIndexData[] =
  91. {
  92. 0, 1, 2,
  93. 0, 2, 3,
  94. 4, 5, 6,
  95. 4, 6, 7,
  96. 8, 9, 10,
  97. 8, 10, 11,
  98. 12, 13, 14,
  99. 12, 14, 15,
  100. 16, 17, 18,
  101. 16, 18, 19,
  102. 20, 21, 22,
  103. 20, 22, 23,
  104. 0, 10, 9,
  105. 0, 9, 1,
  106. 13, 2, 1,
  107. 13, 1, 14,
  108. 23, 0, 3,
  109. 23, 3, 20,
  110. 17, 3, 2,
  111. 17, 2, 18,
  112. 21, 7, 6,
  113. 21, 6, 22,
  114. 7, 16, 19,
  115. 7, 19, 4,
  116. 5, 8, 11,
  117. 5, 11, 6,
  118. 4, 12, 15,
  119. 4, 15, 5,
  120. 22, 11, 10,
  121. 22, 10, 23,
  122. 8, 15, 14,
  123. 8, 14, 9,
  124. 12, 19, 18,
  125. 12, 18, 13,
  126. 16, 21, 20,
  127. 16, 20, 17,
  128. 0, 23, 10,
  129. 1, 9, 14,
  130. 2, 13, 18,
  131. 3, 17, 20,
  132. 6, 11, 22,
  133. 5, 15, 8,
  134. 4, 19, 12,
  135. 7, 21, 16
  136. };
  137. static const float spotLightVertexData[] =
  138. {
  139. 0.00001f, 0.00001f, 0.00001f,
  140. 0.00001f, -0.00001f, 0.00001f,
  141. -0.00001f, -0.00001f, 0.00001f,
  142. -0.00001f, 0.00001f, 0.00001f,
  143. 1.00000f, 1.00000f, 0.99999f,
  144. 1.00000f, -1.00000f, 0.99999f,
  145. -1.00000f, -1.00000f, 0.99999f,
  146. -1.00000f, 1.00000f, 0.99999f,
  147. };
  148. static const unsigned short spotLightIndexData[] =
  149. {
  150. 3, 0, 1,
  151. 3, 1, 2,
  152. 0, 4, 5,
  153. 0, 5, 1,
  154. 3, 7, 4,
  155. 3, 4, 0,
  156. 7, 3, 2,
  157. 7, 2, 6,
  158. 6, 2, 1,
  159. 6, 1, 5,
  160. 7, 5, 4,
  161. 7, 6, 5
  162. };
  163. static const String shadowVariations[] =
  164. {
  165. // No specific hardware shadow compare variation on OpenGL, it is always supported
  166. #ifdef USE_OPENGL
  167. "LQ",
  168. "LQ",
  169. "",
  170. ""
  171. #else
  172. "",
  173. "LQHW",
  174. "",
  175. "HW"
  176. #endif
  177. };
  178. static const String linearVariations[] =
  179. {
  180. "",
  181. "Linear"
  182. };
  183. static const String fallbackVariations[] =
  184. {
  185. "",
  186. "FB"
  187. };
  188. static const String hwVariations[] =
  189. {
  190. "",
  191. "HW"
  192. };
  193. static const String geometryVSVariations[] =
  194. {
  195. "",
  196. "Skinned",
  197. "Instanced",
  198. "Billboard"
  199. };
  200. static const String lightVSVariations[] =
  201. {
  202. "Dir",
  203. "Spot",
  204. "Point",
  205. "DirSpec",
  206. "SpotSpec",
  207. "PointSpec",
  208. "DirShadow",
  209. "SpotShadow",
  210. "PointShadow",
  211. "DirSpecShadow",
  212. "SpotSpecShadow",
  213. "PointSpecShadow"
  214. };
  215. static const String vertexLightVSVariations[] =
  216. {
  217. "",
  218. "1VL",
  219. "2VL",
  220. "3VL",
  221. "4VL",
  222. "5VL",
  223. "6VL"
  224. };
  225. static const String deferredLightVSVariations[] =
  226. {
  227. "",
  228. "Dir",
  229. "Ortho",
  230. "OrthoDir"
  231. };
  232. static const String lightPSVariations[] =
  233. {
  234. "Dir",
  235. "Spot",
  236. "Point",
  237. "PointMask",
  238. "DirSpec",
  239. "SpotSpec",
  240. "PointSpec",
  241. "PointMaskSpec",
  242. "DirShadow",
  243. "SpotShadow",
  244. "PointShadow",
  245. "PointMaskShadow",
  246. "DirSpecShadow",
  247. "SpotSpecShadow",
  248. "PointSpecShadow",
  249. "PointMaskSpecShadow"
  250. };
  251. static const unsigned INSTANCING_BUFFER_MASK = MASK_INSTANCEMATRIX1 | MASK_INSTANCEMATRIX2 | MASK_INSTANCEMATRIX3;
  252. static const Viewport noViewport;
  253. OBJECTTYPESTATIC(Renderer);
  254. Renderer::Renderer(Context* context) :
  255. Object(context),
  256. defaultZone_(new Zone(context)),
  257. numViews_(0),
  258. numShadowCameras_(0),
  259. numOcclusionBuffers_(0),
  260. textureAnisotropy_(4),
  261. textureFilterMode_(FILTER_TRILINEAR),
  262. textureQuality_(QUALITY_HIGH),
  263. materialQuality_(QUALITY_HIGH),
  264. shadowMapSize_(1024),
  265. shadowQuality_(SHADOWQUALITY_HIGH_16BIT),
  266. maxShadowMaps_(1),
  267. maxShadowCascades_(MAX_CASCADE_SPLITS),
  268. maxInstanceTriangles_(500),
  269. maxOccluderTriangles_(5000),
  270. occlusionBufferSize_(256),
  271. occluderSizeThreshold_(0.1f),
  272. shadersChangedFrameNumber_(M_MAX_UNSIGNED),
  273. lightPrepass_(false),
  274. specularLighting_(true),
  275. drawShadows_(true),
  276. reuseShadowMaps_(true),
  277. lightStencilMasking_(true),
  278. dynamicInstancing_(true),
  279. shadersDirty_(true),
  280. initialized_(false)
  281. {
  282. SubscribeToEvent(E_SCREENMODE, HANDLER(Renderer, HandleScreenMode));
  283. SubscribeToEvent(E_GRAPHICSFEATURES, HANDLER(Renderer, HandleGraphicsFeatures));
  284. SubscribeToEvent(E_RENDERUPDATE, HANDLER(Renderer, HandleRenderUpdate));
  285. // Try to initialize right now, but skip if screen mode is not yet set
  286. Initialize();
  287. }
  288. Renderer::~Renderer()
  289. {
  290. }
  291. void Renderer::SetNumViewports(unsigned num)
  292. {
  293. viewports_.Resize(num);
  294. }
  295. void Renderer::SetViewport(unsigned index, const Viewport& viewport)
  296. {
  297. if (index >= viewports_.Size())
  298. {
  299. LOGERROR("Viewport index out of bounds");
  300. return;
  301. }
  302. viewports_[index] = viewport;
  303. }
  304. void Renderer::SetLightPrepass(bool enable)
  305. {
  306. if (!initialized_)
  307. {
  308. LOGERROR("Can not switch light pre-pass rendering before setting initial screen mode");
  309. return;
  310. }
  311. if (!graphics_->GetLightPrepassSupport())
  312. enable = false;
  313. if (enable != lightPrepass_)
  314. {
  315. // Light prepass is incompatible with hardware multisampling, so set new screen mode with 1x sampling if in use
  316. if (graphics_->GetMultiSample() > 1)
  317. graphics_->SetMode(graphics_->GetWidth(), graphics_->GetHeight(), graphics_->GetFullscreen(), graphics_->GetVSync(),
  318. graphics_->GetTripleBuffer(), 1);
  319. // Create the G-buffer textures if necessary
  320. if (enable)
  321. {
  322. if (!normalBuffer_)
  323. {
  324. normalBuffer_ = new Texture2D(context_);
  325. normalBuffer_->SetSize(0, 0, Graphics::GetRGBAFormat(), TEXTURE_RENDERTARGET);
  326. }
  327. if (!depthBuffer_)
  328. {
  329. if (!graphics_->GetHardwareDepthSupport())
  330. {
  331. depthBuffer_ = new Texture2D(context_);
  332. depthBuffer_->SetSize(0, 0, Graphics::GetDepthFormat(), TEXTURE_RENDERTARGET);
  333. }
  334. else
  335. depthBuffer_ = graphics_->GetDepthTexture();
  336. }
  337. if (!lightBuffer_)
  338. {
  339. lightBuffer_ = new Texture2D(context_);
  340. lightBuffer_->SetSize(0, 0, Graphics::GetRGBAFormat(), TEXTURE_RENDERTARGET);
  341. }
  342. }
  343. else
  344. {
  345. normalBuffer_.Reset();
  346. depthBuffer_.Reset();
  347. lightBuffer_.Reset();
  348. }
  349. lightPrepass_ = enable;
  350. shadersDirty_ = true;
  351. }
  352. }
  353. void Renderer::SetSpecularLighting(bool enable)
  354. {
  355. specularLighting_ = enable;
  356. }
  357. void Renderer::SetTextureAnisotropy(int level)
  358. {
  359. textureAnisotropy_ = Max(level, 1);
  360. }
  361. void Renderer::SetTextureFilterMode(TextureFilterMode mode)
  362. {
  363. textureFilterMode_ = mode;
  364. }
  365. void Renderer::SetTextureQuality(int quality)
  366. {
  367. quality = Clamp(quality, QUALITY_LOW, QUALITY_HIGH);
  368. if (quality != textureQuality_)
  369. {
  370. textureQuality_ = quality;
  371. ReloadTextures();
  372. }
  373. }
  374. void Renderer::SetMaterialQuality(int quality)
  375. {
  376. materialQuality_ = Clamp(quality, QUALITY_LOW, QUALITY_MAX);
  377. shadersDirty_ = true;
  378. ResetViews();
  379. }
  380. void Renderer::SetDrawShadows(bool enable)
  381. {
  382. if (!graphics_)
  383. return;
  384. drawShadows_ = enable;
  385. if (!drawShadows_)
  386. ResetShadowMaps();
  387. }
  388. void Renderer::SetShadowMapSize(int size)
  389. {
  390. if (!graphics_)
  391. return;
  392. size = NextPowerOfTwo(Max(size, SHADOW_MIN_PIXELS));
  393. if (size != shadowMapSize_)
  394. {
  395. shadowMapSize_ = size;
  396. ResetShadowMaps();
  397. }
  398. }
  399. void Renderer::SetShadowQuality(int quality)
  400. {
  401. if (!graphics_)
  402. return;
  403. quality &= SHADOWQUALITY_HIGH_24BIT;
  404. // If no hardware PCF, do not allow to select one-sample quality
  405. if (!graphics_->GetHardwareShadowSupport())
  406. quality |= SHADOWQUALITY_HIGH_16BIT;
  407. if (!graphics_->GetHiresShadowSupport())
  408. quality &= SHADOWQUALITY_HIGH_16BIT;
  409. if (graphics_->GetFallback())
  410. quality = SHADOWQUALITY_LOW_16BIT;
  411. if (quality != shadowQuality_)
  412. {
  413. shadowQuality_ = quality;
  414. shadersDirty_ = true;
  415. ResetShadowMaps();
  416. }
  417. }
  418. void Renderer::SetReuseShadowMaps(bool enable)
  419. {
  420. if (enable == reuseShadowMaps_)
  421. return;
  422. reuseShadowMaps_ = enable;
  423. }
  424. void Renderer::SetMaxShadowMaps(int shadowMaps)
  425. {
  426. if (shadowMaps < 1)
  427. return;
  428. maxShadowMaps_ = shadowMaps;
  429. for (HashMap<int, Vector<SharedPtr<Texture2D> > >::Iterator i = shadowMaps_.Begin(); i != shadowMaps_.End(); ++i)
  430. {
  431. if ((int)i->second_.Size() > maxShadowMaps_)
  432. i->second_.Resize(maxShadowMaps_);
  433. }
  434. }
  435. void Renderer::SetMaxShadowCascades(int cascades)
  436. {
  437. cascades = Clamp(cascades, 1, MAX_CASCADE_SPLITS);
  438. if (cascades != maxShadowCascades_)
  439. {
  440. maxShadowCascades_ = cascades;
  441. ResetShadowMaps();
  442. }
  443. }
  444. void Renderer::SetLightStencilMasking(bool enable)
  445. {
  446. lightStencilMasking_ = enable;
  447. }
  448. void Renderer::SetDynamicInstancing(bool enable)
  449. {
  450. if (!instancingBuffer_)
  451. enable = false;
  452. dynamicInstancing_ = enable;
  453. }
  454. void Renderer::SetMaxInstanceTriangles(int triangles)
  455. {
  456. maxInstanceTriangles_ = Max(triangles, 0);
  457. }
  458. void Renderer::SetMaxOccluderTriangles(int triangles)
  459. {
  460. maxOccluderTriangles_ = Max(triangles, 0);
  461. }
  462. void Renderer::SetOcclusionBufferSize(int size)
  463. {
  464. occlusionBufferSize_ = Max(size, 1);
  465. occlusionBuffers_.Clear();
  466. }
  467. void Renderer::SetOccluderSizeThreshold(float screenSize)
  468. {
  469. occluderSizeThreshold_ = Max(screenSize, 0.0f);
  470. }
  471. const Viewport& Renderer::GetViewport(unsigned index) const
  472. {
  473. return index < viewports_.Size() ? viewports_[index] : noViewport;
  474. }
  475. ShaderVariation* Renderer::GetVertexShader(const String& name, bool checkExists) const
  476. {
  477. return GetShader(name, vsFormat_, checkExists);
  478. }
  479. ShaderVariation* Renderer::GetPixelShader(const String& name, bool checkExists) const
  480. {
  481. return GetShader(name, psFormat_, checkExists);
  482. }
  483. unsigned Renderer::GetNumGeometries(bool allViews) const
  484. {
  485. unsigned numGeometries = 0;
  486. unsigned lastView = allViews ? numViews_ : 1;
  487. for (unsigned i = 0; i < lastView; ++i)
  488. numGeometries += views_[i]->GetGeometries().Size();
  489. return numGeometries;
  490. }
  491. unsigned Renderer::GetNumLights(bool allViews) const
  492. {
  493. unsigned numLights = 0;
  494. unsigned lastView = allViews ? numViews_ : 1;
  495. for (unsigned i = 0; i < lastView; ++i)
  496. numLights += views_[i]->GetLights().Size();
  497. return numLights;
  498. }
  499. unsigned Renderer::GetNumShadowMaps(bool allViews) const
  500. {
  501. unsigned numShadowMaps = 0;
  502. unsigned lastView = allViews ? numViews_ : 1;
  503. for (unsigned i = 0; i < lastView; ++i)
  504. {
  505. const List<LightBatchQueue>& lightQueues = views_[i]->GetLightQueues();
  506. for (List<LightBatchQueue>::ConstIterator i = lightQueues.Begin(); i != lightQueues.End(); ++i)
  507. {
  508. if (i->shadowMap_)
  509. ++numShadowMaps;
  510. }
  511. }
  512. return numShadowMaps;
  513. }
  514. unsigned Renderer::GetNumOccluders(bool allViews) const
  515. {
  516. unsigned numOccluders = 0;
  517. unsigned lastView = allViews ? numViews_ : 1;
  518. for (unsigned i = 0; i < lastView; ++i)
  519. numOccluders += views_[i]->GetOccluders().Size();
  520. return numOccluders;
  521. }
  522. void Renderer::Update(float timeStep)
  523. {
  524. PROFILE(UpdateViews);
  525. numViews_ = 0;
  526. // If device lost, do not perform update. This is because any dynamic vertex/index buffer updates happen already here,
  527. // and if the device is lost, the updates queue up, causing memory use to rise constantly
  528. if (!graphics_ || !graphics_->IsInitialized() || graphics_->IsDeviceLost())
  529. return;
  530. // Advance frame number & time, set up the frameinfo structure, and reset views & stats
  531. frame_.frameNumber_ = GetSubsystem<Time>()->GetFrameNumber();
  532. frame_.timeStep_ = timeStep;
  533. frame_.camera_ = 0;
  534. numShadowCameras_ = 0;
  535. numOcclusionBuffers_ = 0;
  536. updateOctrees_.Clear();
  537. // Reload shaders if needed
  538. if (shadersDirty_)
  539. LoadShaders();
  540. // Process all viewports. Use reverse order, because during rendering the order will be reversed again to handle auxiliary
  541. // view dependencies correctly
  542. for (unsigned i = viewports_.Size() - 1; i < viewports_.Size(); --i)
  543. {
  544. unsigned mainView = numViews_;
  545. Viewport& viewport = viewports_[i];
  546. if (!AddView(0, viewport))
  547. continue;
  548. // Update octree (perform early update for nodes which need that, and reinsert moved nodes.)
  549. // However, if the same scene is viewed from multiple cameras, update the octree only once
  550. Octree* octree = viewport.scene_->GetComponent<Octree>();
  551. DebugRenderer* debug = viewport.scene_->GetComponent<DebugRenderer>();
  552. if (!updateOctrees_.Contains(octree))
  553. {
  554. frame_.camera_ = viewport.camera_;
  555. frame_.viewSize_ = IntVector2(viewport.rect_.right_ - viewport.rect_.left_, viewport.rect_.bottom_ - viewport.rect_.top_);
  556. if (frame_.viewSize_ == IntVector2::ZERO)
  557. frame_.viewSize_ = IntVector2(graphics_->GetWidth(), graphics_->GetHeight());
  558. octree->Update(frame_);
  559. updateOctrees_.Insert(octree);
  560. // Set also the view for the debug graphics already here, so that it can use culling
  561. /// \todo May result in incorrect debug geometry culling if the same scene is drawn from multiple viewports
  562. if (debug)
  563. debug->SetView(viewport.camera_);
  564. }
  565. // Update the viewport's main view and any auxiliary views it creates
  566. for (unsigned i = mainView; i < numViews_; ++i)
  567. views_[i]->Update(frame_);
  568. }
  569. return;
  570. }
  571. void Renderer::Render()
  572. {
  573. if (!graphics_)
  574. return;
  575. PROFILE(RenderViews);
  576. graphics_->SetDefaultTextureFilterMode(textureFilterMode_);
  577. graphics_->SetTextureAnisotropy(textureAnisotropy_);
  578. // If no views, just clear the screen
  579. if (!numViews_)
  580. {
  581. numPrimitives_ = 0;
  582. numBatches_ = 0;
  583. graphics_->SetAlphaTest(false);
  584. graphics_->SetBlendMode(BLEND_REPLACE);
  585. graphics_->SetColorWrite(true);
  586. graphics_->SetDepthWrite(true);
  587. graphics_->SetFillMode(FILL_SOLID);
  588. graphics_->SetScissorTest(false);
  589. graphics_->SetStencilTest(false);
  590. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH | CLEAR_STENCIL);
  591. return;
  592. }
  593. // Render views from last to first (each main view is rendered after the auxiliary views it depends on)
  594. for (unsigned i = numViews_ - 1; i < numViews_; --i)
  595. views_[i]->Render();
  596. // Copy the number of batches & primitives from Graphics so that we can account for 3D geometry only
  597. numPrimitives_ = graphics_->GetNumPrimitives();
  598. numBatches_ = graphics_->GetNumBatches();
  599. }
  600. void Renderer::DrawDebugGeometry(bool depthTest)
  601. {
  602. PROFILE(RendererDrawDebug);
  603. /// \todo Because debug geometry is per-scene, if two cameras show views of the same area, occlusion is not shown correctly
  604. HashSet<Drawable*> processedGeometries;
  605. HashSet<Light*> processedLights;
  606. for (unsigned i = 0; i < numViews_; ++i)
  607. {
  608. // Make sure it's a main view, and process each node only once
  609. View* view = views_[i];
  610. if (view->GetRenderTarget())
  611. continue;
  612. Octree* octree = view->GetOctree();
  613. if (!octree)
  614. continue;
  615. Scene* scene = static_cast<Scene*>(octree->GetNode());
  616. if (!scene)
  617. continue;
  618. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  619. if (!debug)
  620. continue;
  621. const PODVector<Drawable*>& geometries = view->GetGeometries();
  622. const PODVector<Light*>& lights = view->GetLights();
  623. for (unsigned i = 0; i < geometries.Size(); ++i)
  624. {
  625. if (!processedGeometries.Contains(geometries[i]))
  626. {
  627. geometries[i]->DrawDebugGeometry(debug, depthTest);
  628. processedGeometries.Insert(geometries[i]);
  629. }
  630. }
  631. for (unsigned i = 0; i < lights.Size(); ++i)
  632. {
  633. if (!processedLights.Contains(lights[i]))
  634. {
  635. lights[i]->DrawDebugGeometry(debug, depthTest);
  636. processedLights.Insert(lights[i]);
  637. }
  638. }
  639. }
  640. }
  641. bool Renderer::AddView(RenderSurface* renderTarget, const Viewport& viewport)
  642. {
  643. // If using a render target texture, make sure it will not be rendered to multiple times
  644. if (renderTarget)
  645. {
  646. for (unsigned i = 0; i < numViews_; ++i)
  647. {
  648. if (views_[i]->GetRenderTarget() == renderTarget)
  649. return false;
  650. }
  651. }
  652. if (views_.Size() <= numViews_)
  653. views_.Resize(numViews_ + 1);
  654. if (!views_[numViews_])
  655. views_[numViews_] = new View(context_);
  656. if (views_[numViews_]->Define(renderTarget, viewport))
  657. {
  658. ++numViews_;
  659. return true;
  660. }
  661. else
  662. return false;
  663. }
  664. Geometry* Renderer::GetLightGeometry(Light* light)
  665. {
  666. LightType type = light->GetLightType();
  667. if (type == LIGHT_DIRECTIONAL)
  668. return dirLightGeometry_;
  669. if (type == LIGHT_SPOT)
  670. return spotLightGeometry_;
  671. else if (type == LIGHT_POINT)
  672. return pointLightGeometry_;
  673. else
  674. return 0;
  675. }
  676. Texture2D* Renderer::GetShadowMap(Light* light, Camera* camera, unsigned viewWidth, unsigned viewHeight)
  677. {
  678. LightType type = light->GetLightType();
  679. const FocusParameters& parameters = light->GetShadowFocus();
  680. float size = (float)shadowMapSize_ * light->GetShadowResolution();
  681. // Automatically reduce shadow map size when far away
  682. if (parameters.autoSize_ && type != LIGHT_DIRECTIONAL)
  683. {
  684. Matrix3x4 view(camera->GetInverseWorldTransform());
  685. Matrix4 projection(camera->GetProjection());
  686. BoundingBox lightBox;
  687. float lightPixels;
  688. if (type == LIGHT_POINT)
  689. {
  690. // Calculate point light pixel size from the projection of its diagonal
  691. Vector3 center = view * light->GetWorldPosition();
  692. float extent = 0.58f * light->GetRange();
  693. lightBox.Define(center + Vector3(extent, extent, extent), center - Vector3(extent, extent, extent));
  694. }
  695. else
  696. {
  697. // Calculate spot light pixel size from the projection of its frustum far vertices
  698. Frustum lightFrustum = light->GetFrustum().Transformed(view);
  699. lightBox.Define(&lightFrustum.vertices_[4], 4);
  700. }
  701. Vector2 projectionSize = lightBox.Projected(projection).Size();
  702. lightPixels = Max(0.5f * (float)viewWidth * projectionSize.x_, 0.5f * (float)viewHeight * projectionSize.y_);
  703. // Clamp pixel amount to a sufficient minimum to avoid self-shadowing artifacts due to loss of precision
  704. if (lightPixels < SHADOW_MIN_PIXELS)
  705. lightPixels = SHADOW_MIN_PIXELS;
  706. size = Min(size, lightPixels);
  707. }
  708. /// \todo Allow to specify maximum shadow maps per resolution, as smaller shadow maps take less memory
  709. int width = NextPowerOfTwo((unsigned)size);
  710. int height = width;
  711. // Adjust the size for directional or point light shadow map atlases
  712. if (type == LIGHT_DIRECTIONAL)
  713. {
  714. if (maxShadowCascades_ > 1)
  715. width *= 2;
  716. if (maxShadowCascades_ > 2)
  717. height *= 2;
  718. }
  719. else if (type == LIGHT_POINT)
  720. {
  721. width *= 2;
  722. height *= 3;
  723. }
  724. int searchKey = (width << 16) | height;
  725. if (shadowMaps_.Contains(searchKey))
  726. {
  727. // If shadow maps are reused, always return the first
  728. if (reuseShadowMaps_)
  729. return shadowMaps_[searchKey][0];
  730. else
  731. {
  732. // If not reused, check allocation count and return existing shadow map if possible
  733. unsigned allocated = shadowMapAllocations_[searchKey].Size();
  734. if (allocated < shadowMaps_[searchKey].Size())
  735. {
  736. shadowMapAllocations_[searchKey].Push(light);
  737. return shadowMaps_[searchKey][allocated];
  738. }
  739. else if ((int)allocated >= maxShadowMaps_)
  740. return 0;
  741. }
  742. }
  743. unsigned shadowMapFormat = (shadowQuality_ & SHADOWQUALITY_LOW_24BIT) ? graphics_->GetHiresShadowMapFormat() :
  744. graphics_->GetShadowMapFormat();
  745. unsigned dummyColorFormat = graphics_->GetDummyColorFormat();
  746. if (!shadowMapFormat)
  747. return 0;
  748. SharedPtr<Texture2D> newShadowMap(new Texture2D(context_));
  749. int retries = 3;
  750. #ifdef USE_OPENGL
  751. // Create shadow map only. Color render target is not needed
  752. while (retries)
  753. {
  754. if (!newShadowMap->SetSize(width, height, shadowMapFormat, TEXTURE_DEPTHSTENCIL))
  755. {
  756. width >>= 1;
  757. height >>= 1;
  758. --retries;
  759. }
  760. else
  761. {
  762. newShadowMap->SetFilterMode(FILTER_BILINEAR);
  763. newShadowMap->SetShadowCompare(true);
  764. break;
  765. }
  766. }
  767. #else
  768. // Create shadow map and dummy color render target
  769. bool fallback = graphics_->GetFallback();
  770. while (retries)
  771. {
  772. if (!newShadowMap->SetSize(width, height, shadowMapFormat, fallback ? TEXTURE_RENDERTARGET : TEXTURE_DEPTHSTENCIL))
  773. {
  774. width >>= 1;
  775. height >>= 1;
  776. --retries;
  777. }
  778. else
  779. {
  780. newShadowMap->SetFilterMode(FILTER_BILINEAR);
  781. if (!fallback)
  782. {
  783. // If no dummy color render target for this size exists yet, create one now
  784. if (!colorShadowMaps_.Contains(searchKey))
  785. {
  786. colorShadowMaps_[searchKey] = new Texture2D(context_);
  787. colorShadowMaps_[searchKey]->SetSize(width, height, dummyColorFormat, TEXTURE_RENDERTARGET);
  788. }
  789. // Link the color render target to the shadow map
  790. newShadowMap->GetRenderSurface()->SetLinkedRenderTarget(colorShadowMaps_[searchKey]->GetRenderSurface());
  791. }
  792. else
  793. {
  794. // In fallback mode link the shared shadow map depth stencil to the shadow map instead.
  795. // Create it first if not created yet, and resize larger if necessary
  796. if (!shadowDepthStencil_)
  797. shadowDepthStencil_ = new Texture2D(context_);
  798. if (shadowDepthStencil_->GetWidth() < width || shadowDepthStencil_->GetHeight() < height)
  799. shadowDepthStencil_->SetSize(width, height, D3DFMT_D16, TEXTURE_DEPTHSTENCIL);
  800. newShadowMap->GetRenderSurface()->SetLinkedDepthBuffer(shadowDepthStencil_->GetRenderSurface());
  801. }
  802. break;
  803. }
  804. }
  805. #endif
  806. // If failed to set size, store a null pointer so that we will not retry
  807. if (!retries)
  808. newShadowMap.Reset();
  809. shadowMaps_[searchKey].Push(newShadowMap);
  810. if (!reuseShadowMaps_)
  811. shadowMapAllocations_[searchKey].Push(light);
  812. return newShadowMap;
  813. }
  814. OcclusionBuffer* Renderer::GetOcclusionBuffer(Camera* camera)
  815. {
  816. if (numOcclusionBuffers_ >= occlusionBuffers_.Size())
  817. {
  818. SharedPtr<OcclusionBuffer> newBuffer(new OcclusionBuffer(context_));
  819. occlusionBuffers_.Push(newBuffer);
  820. }
  821. int width = occlusionBufferSize_;
  822. int height = (int)((float)occlusionBufferSize_ / camera->GetAspectRatio() + 0.5f);
  823. OcclusionBuffer* buffer = occlusionBuffers_[numOcclusionBuffers_];
  824. buffer->SetSize(width, height);
  825. buffer->SetView(camera);
  826. ++numOcclusionBuffers_;
  827. return buffer;
  828. }
  829. Camera* Renderer::GetShadowCamera()
  830. {
  831. MutexLock lock(rendererMutex_);
  832. if (numShadowCameras_ >= shadowCameraNodes_.Size())
  833. {
  834. SharedPtr<Node> newNode(new Node(context_));
  835. newNode->CreateComponent<Camera>();
  836. shadowCameraNodes_.Push(newNode);
  837. }
  838. Camera* camera = shadowCameraNodes_[numShadowCameras_]->GetComponent<Camera>();
  839. camera->SetOrthographic(false);
  840. camera->SetZoom(1.0f);
  841. ++numShadowCameras_;
  842. return camera;
  843. }
  844. ShaderVariation* Renderer::GetShader(const String& name, const String& extension, bool checkExists) const
  845. {
  846. String shaderName = shaderPath_;
  847. String variationName;
  848. unsigned split = name.Find('_');
  849. if (split != String::NPOS)
  850. {
  851. shaderName += name.Substring(0, split) + extension;
  852. variationName = name.Substring(split + 1);
  853. }
  854. else
  855. shaderName += name + extension;
  856. if (checkExists)
  857. {
  858. if (!cache_->Exists(shaderName))
  859. return 0;
  860. }
  861. Shader* shader = cache_->GetResource<Shader>(shaderName);
  862. if (shader)
  863. return shader->GetVariation(variationName);
  864. else
  865. return 0;
  866. }
  867. void Renderer::SetBatchShaders(Batch& batch, Technique* technique, Pass* pass, bool allowShadows)
  868. {
  869. // Check if shaders are unloaded or need reloading
  870. Vector<SharedPtr<ShaderVariation> >& vertexShaders = pass->GetVertexShaders();
  871. Vector<SharedPtr<ShaderVariation> >& pixelShaders = pass->GetPixelShaders();
  872. if (!vertexShaders.Size() || !pixelShaders.Size() || technique->GetShadersLoadedFrameNumber() !=
  873. shadersChangedFrameNumber_)
  874. {
  875. // First release all previous shaders, then load
  876. technique->ReleaseShaders();
  877. LoadMaterialShaders(technique);
  878. }
  879. // Make sure shaders are loaded now
  880. if (vertexShaders.Size() && pixelShaders.Size())
  881. {
  882. GeometryType geomType = batch.geometryType_;
  883. // If instancing is not supported, but was requested, or the object is too large to be instanced,
  884. // choose static geometry vertex shader instead
  885. if (geomType == GEOM_INSTANCED && (!GetDynamicInstancing() || batch.geometry_->GetIndexCount() >
  886. (unsigned)maxInstanceTriangles_ * 3))
  887. geomType = GEOM_STATIC;
  888. // Check whether is a pixel lit forward pass. If not, there is only one pixel shader
  889. PassType type = pass->GetType();
  890. if (type == PASS_LIGHT)
  891. {
  892. LightBatchQueue* lightQueue = batch.lightQueue_;
  893. if (!lightQueue)
  894. {
  895. // Do not log error, as it would result in a lot of spam
  896. batch.vertexShader_ = 0;
  897. batch.pixelShader_ = 0;
  898. return;
  899. }
  900. Light* light = lightQueue->light_;
  901. unsigned vsi = 0;
  902. unsigned psi = 0;
  903. vsi = geomType * MAX_LIGHT_VS_VARIATIONS;
  904. bool materialHasSpecular = batch.material_ ? batch.material_->GetSpecular() : true;
  905. if (specularLighting_ && light->GetSpecularIntensity() > 0.0f && materialHasSpecular)
  906. {
  907. vsi += LVS_SPEC;
  908. psi += LPS_SPEC;
  909. }
  910. if (allowShadows && lightQueue->shadowMap_)
  911. {
  912. vsi += LVS_SHADOW;
  913. psi += LPS_SHADOW;
  914. }
  915. switch (light->GetLightType())
  916. {
  917. case LIGHT_DIRECTIONAL:
  918. vsi += LVS_DIR;
  919. break;
  920. case LIGHT_POINT:
  921. if (light->GetShapeTexture())
  922. psi += LPS_POINTMASK;
  923. else
  924. psi += LPS_POINT;
  925. vsi += LVS_POINT;
  926. break;
  927. case LIGHT_SPOT:
  928. psi += LPS_SPOT;
  929. vsi += LVS_SPOT;
  930. break;
  931. }
  932. batch.vertexShader_ = vertexShaders[vsi];
  933. batch.pixelShader_ = pixelShaders[psi];
  934. // If shadow or specular variations do not exist, try without them
  935. if ((!batch.vertexShader_ || !batch.pixelShader_) && (vsi >= LVS_SHADOW))
  936. {
  937. vsi -= LVS_SHADOW;
  938. psi -= LPS_SHADOW;
  939. batch.vertexShader_ = vertexShaders[vsi];
  940. batch.pixelShader_ = pixelShaders[psi];
  941. }
  942. if ((!batch.vertexShader_ || !batch.pixelShader_) && (vsi >= LVS_SPEC))
  943. {
  944. vsi -= LVS_SPEC;
  945. psi -= LPS_SPEC;
  946. batch.vertexShader_ = vertexShaders[vsi];
  947. batch.pixelShader_ = pixelShaders[psi];
  948. }
  949. }
  950. else
  951. {
  952. if (type == PASS_BASE || type == PASS_MATERIAL)
  953. {
  954. unsigned numVertexLights = 0;
  955. if (batch.lightQueue_)
  956. numVertexLights = batch.lightQueue_->vertexLights_.Size();
  957. unsigned vsi = geomType * MAX_VERTEXLIGHT_VS_VARIATIONS + numVertexLights;
  958. batch.vertexShader_ = vertexShaders[vsi];
  959. // If vertex lights variations do not exist, try without them
  960. if (!batch.vertexShader_)
  961. {
  962. unsigned vsi = geomType * MAX_VERTEXLIGHT_VS_VARIATIONS;
  963. batch.vertexShader_ = vertexShaders[vsi];
  964. }
  965. }
  966. else
  967. {
  968. unsigned vsi = geomType;
  969. batch.vertexShader_ = vertexShaders[vsi];
  970. }
  971. batch.pixelShader_ = pixelShaders[0];
  972. }
  973. }
  974. // Log error if shaders could not be assigned, but only once per technique
  975. if (!batch.vertexShader_ || !batch.pixelShader_)
  976. {
  977. if (!shaderErrorDisplayed_.Contains(technique))
  978. {
  979. shaderErrorDisplayed_.Insert(technique);
  980. LOGERROR("Technique " + technique->GetName() + " has missing shaders");
  981. }
  982. }
  983. }
  984. void Renderer::SetLightVolumeBatchShaders(Batch& batch)
  985. {
  986. unsigned vsi = DLVS_NONE;
  987. unsigned psi = DLPS_NONE;
  988. Light* light = batch.lightQueue_->light_;
  989. switch (light->GetLightType())
  990. {
  991. case LIGHT_DIRECTIONAL:
  992. vsi += DLVS_DIR;
  993. break;
  994. case LIGHT_POINT:
  995. if (light->GetShapeTexture())
  996. psi += DLPS_POINTMASK;
  997. else
  998. psi += DLPS_POINT;
  999. break;
  1000. case LIGHT_SPOT:
  1001. psi += DLPS_SPOT;
  1002. break;
  1003. }
  1004. if (batch.lightQueue_->shadowMap_)
  1005. psi += DLPS_SHADOW;
  1006. if (specularLighting_ && light->GetSpecularIntensity() > 0.0f)
  1007. psi += DLPS_SPEC;
  1008. if (batch.camera_->IsOrthographic())
  1009. {
  1010. vsi += DLVS_ORTHO;
  1011. psi += DLPS_ORTHO;
  1012. }
  1013. batch.vertexShader_ = lightVS_[vsi];
  1014. batch.pixelShader_ = lightPS_[psi];
  1015. }
  1016. bool Renderer::ResizeInstancingBuffer(unsigned numInstances)
  1017. {
  1018. if (!instancingBuffer_ || !dynamicInstancing_)
  1019. return false;
  1020. unsigned oldSize = instancingBuffer_->GetVertexCount();
  1021. if (numInstances <= oldSize)
  1022. return true;
  1023. unsigned newSize = INSTANCING_BUFFER_DEFAULT_SIZE;
  1024. while (newSize < numInstances)
  1025. newSize <<= 1;
  1026. if (!instancingBuffer_->SetSize(newSize, INSTANCING_BUFFER_MASK, true))
  1027. {
  1028. LOGERROR("Failed to resize instancing buffer to " + String(newSize));
  1029. // If failed, try to restore the old size
  1030. instancingBuffer_->SetSize(oldSize, INSTANCING_BUFFER_MASK, true);
  1031. return false;
  1032. }
  1033. LOGDEBUG("Resized instancing buffer to " + String(newSize));
  1034. return true;
  1035. }
  1036. void Renderer::ResetShadowMapAllocations()
  1037. {
  1038. for (HashMap<int, PODVector<Light*> >::Iterator i = shadowMapAllocations_.Begin(); i != shadowMapAllocations_.End(); ++i)
  1039. i->second_.Clear();
  1040. }
  1041. void Renderer::Initialize()
  1042. {
  1043. Graphics* graphics = GetSubsystem<Graphics>();
  1044. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1045. if (!graphics || !graphics->IsInitialized() || !cache)
  1046. return;
  1047. PROFILE(InitRenderer);
  1048. graphics_ = graphics;
  1049. cache_ = cache;
  1050. // Check shader model support
  1051. #ifndef USE_OPENGL
  1052. if (graphics_->GetSM3Support())
  1053. {
  1054. shaderPath_ = "Shaders/SM3/";
  1055. vsFormat_ = ".vs3";
  1056. psFormat_ = ".ps3";
  1057. }
  1058. else
  1059. {
  1060. shaderPath_ = "Shaders/SM2/";
  1061. vsFormat_ = ".vs2";
  1062. psFormat_ = ".ps2";
  1063. }
  1064. #else
  1065. {
  1066. shaderPath_ = "Shaders/GLSL/";
  1067. vsFormat_ = ".vert";
  1068. psFormat_ = ".frag";
  1069. }
  1070. #endif
  1071. defaultLightRamp_ = cache->GetResource<Texture2D>("Textures/Ramp.png");
  1072. defaultLightSpot_ = cache->GetResource<Texture2D>("Textures/Spot.png");
  1073. defaultMaterial_ = cache->GetResource<Material>("Materials/Default.xml");
  1074. CreateGeometries();
  1075. CreateInstancingBuffer();
  1076. viewports_.Resize(1);
  1077. ResetViews();
  1078. ResetShadowMaps();
  1079. shadersDirty_ = true;
  1080. initialized_ = true;
  1081. LOGINFO("Initialized renderer");
  1082. }
  1083. void Renderer::ResetViews()
  1084. {
  1085. views_.Clear();
  1086. numViews_ = 0;
  1087. }
  1088. void Renderer::LoadShaders()
  1089. {
  1090. LOGINFO("Reloading shaders");
  1091. // Release old material shaders, mark them for reload
  1092. ReleaseMaterialShaders();
  1093. shadersChangedFrameNumber_ = GetSubsystem<Time>()->GetFrameNumber();
  1094. // Load inbuilt shaders
  1095. stencilVS_ = GetVertexShader("Stencil");
  1096. stencilPS_ = GetPixelShader("Stencil");
  1097. lightVS_.Clear();
  1098. lightPS_.Clear();
  1099. if (lightPrepass_)
  1100. {
  1101. lightVS_.Resize(MAX_DEFERRED_LIGHT_VS_VARIATIONS);
  1102. lightPS_.Resize(MAX_DEFERRED_LIGHT_PS_VARIATIONS);
  1103. unsigned shadows = (graphics_->GetHardwareShadowSupport() ? 1 : 0) | (shadowQuality_ & SHADOWQUALITY_HIGH_16BIT);
  1104. for (unsigned i = 0; i < MAX_DEFERRED_LIGHT_VS_VARIATIONS; ++i)
  1105. lightVS_[i] = GetVertexShader("DeferredLight_" + deferredLightVSVariations[i]);
  1106. for (unsigned i = 0; i < lightPS_.Size(); ++i)
  1107. {
  1108. /// \todo Allow specifying the light volume shader name for different lighting models
  1109. String linearDepth = linearVariations[(!graphics_->GetHardwareDepthSupport() && i < DLPS_ORTHO) ? 1 : 0];
  1110. if (i & DLPS_SHADOW)
  1111. {
  1112. lightPS_[i] = GetPixelShader("DeferredLight_" + linearDepth + lightPSVariations[i % DLPS_ORTHO] +
  1113. shadowVariations[shadows]);
  1114. }
  1115. else
  1116. {
  1117. lightPS_[i] = GetPixelShader("DeferredLight_" + linearDepth + lightPSVariations[i % DLPS_ORTHO]);
  1118. }
  1119. }
  1120. }
  1121. shadersDirty_ = false;
  1122. }
  1123. void Renderer::LoadMaterialShaders(Technique* technique)
  1124. {
  1125. if (lightPrepass_ && technique->HasPass(PASS_GBUFFER))
  1126. {
  1127. LoadPassShaders(technique, PASS_GBUFFER);
  1128. LoadPassShaders(technique, PASS_MATERIAL);
  1129. }
  1130. else
  1131. {
  1132. LoadPassShaders(technique, PASS_BASE);
  1133. LoadPassShaders(technique, PASS_LIGHT);
  1134. }
  1135. LoadPassShaders(technique, PASS_PREALPHA);
  1136. LoadPassShaders(technique, PASS_POSTALPHA);
  1137. LoadPassShaders(technique, PASS_SHADOW);
  1138. }
  1139. void Renderer::LoadPassShaders(Technique* technique, PassType type, bool allowShadows)
  1140. {
  1141. Pass* pass = technique->GetPass(type);
  1142. if (!pass)
  1143. return;
  1144. unsigned shadows = (graphics_->GetHardwareShadowSupport() ? 1 : 0) | (shadowQuality_ & SHADOWQUALITY_HIGH_16BIT);
  1145. unsigned fallback = graphics_->GetFallback() ? 1 : 0;
  1146. if (fallback)
  1147. shadows = SHADOWQUALITY_HIGH_16BIT;
  1148. String vertexShaderName = pass->GetVertexShaderName();
  1149. String pixelShaderName = pass->GetPixelShaderName();
  1150. // Check if the shader name is already a variation in itself
  1151. if (vertexShaderName.Find('_') == String::NPOS)
  1152. vertexShaderName += "_";
  1153. if (pixelShaderName.Find('_') == String::NPOS)
  1154. pixelShaderName += "_";
  1155. // If hardware depth is used, choose a G-buffer shader that does not write depth manually
  1156. if (type == PASS_GBUFFER)
  1157. {
  1158. unsigned hwDepth = graphics_->GetHardwareDepthSupport() ? 1 : 0;
  1159. vertexShaderName += hwVariations[hwDepth];
  1160. pixelShaderName += hwVariations[hwDepth];
  1161. }
  1162. // Check for fallback shadow rendering mode (write depth into an RGBA render target)
  1163. if (type == PASS_SHADOW)
  1164. {
  1165. vertexShaderName += fallbackVariations[fallback];
  1166. pixelShaderName += fallbackVariations[fallback];
  1167. }
  1168. Vector<SharedPtr<ShaderVariation> >& vertexShaders = pass->GetVertexShaders();
  1169. Vector<SharedPtr<ShaderVariation> >& pixelShaders = pass->GetPixelShaders();
  1170. // Forget all the old shaders
  1171. vertexShaders.Clear();
  1172. pixelShaders.Clear();
  1173. if (type == PASS_LIGHT)
  1174. {
  1175. // Load forward pixel lit variations. If material is transparent, and shadow maps are reused,
  1176. // do not load shadowed variations
  1177. if (reuseShadowMaps_)
  1178. {
  1179. if (!technique->HasPass(PASS_BASE) || technique->GetPass(PASS_BASE)->GetBlendMode() != BLEND_REPLACE)
  1180. allowShadows = false;
  1181. }
  1182. vertexShaders.Resize(MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS);
  1183. pixelShaders.Resize(MAX_LIGHT_PS_VARIATIONS);
  1184. for (unsigned j = 0; j < MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS; ++j)
  1185. {
  1186. unsigned g = j / MAX_LIGHT_VS_VARIATIONS;
  1187. unsigned l = j % MAX_LIGHT_VS_VARIATIONS;
  1188. if (l < LVS_SHADOW || allowShadows)
  1189. vertexShaders[j] = GetVertexShader(vertexShaderName + lightVSVariations[l] + geometryVSVariations[g], g != 0);
  1190. else
  1191. vertexShaders[j].Reset();
  1192. }
  1193. for (unsigned j = 0; j < MAX_LIGHT_PS_VARIATIONS; ++j)
  1194. {
  1195. if (j & LPS_SHADOW)
  1196. {
  1197. if (allowShadows)
  1198. {
  1199. pixelShaders[j] = GetPixelShader(pixelShaderName + lightPSVariations[j] + shadowVariations[shadows] +
  1200. fallbackVariations[fallback]);
  1201. }
  1202. else
  1203. pixelShaders[j].Reset();
  1204. }
  1205. else
  1206. pixelShaders[j] = GetPixelShader(pixelShaderName + lightPSVariations[j]);
  1207. }
  1208. }
  1209. else
  1210. {
  1211. // Load vertex light variations for forward ambient pass and pre-pass material pass
  1212. if (type == PASS_BASE || type == PASS_MATERIAL)
  1213. {
  1214. vertexShaders.Resize(MAX_VERTEXLIGHT_VS_VARIATIONS * MAX_GEOMETRYTYPES);
  1215. for (unsigned j = 0; j < MAX_GEOMETRYTYPES * MAX_VERTEXLIGHT_VS_VARIATIONS; ++j)
  1216. {
  1217. unsigned g = j / MAX_VERTEXLIGHT_VS_VARIATIONS;
  1218. unsigned l = j % MAX_VERTEXLIGHT_VS_VARIATIONS;
  1219. vertexShaders[j] = GetVertexShader(vertexShaderName + vertexLightVSVariations[l] + geometryVSVariations[g],
  1220. g != 0 || l != 0);
  1221. }
  1222. }
  1223. else
  1224. {
  1225. vertexShaders.Resize(MAX_GEOMETRYTYPES);
  1226. for (unsigned j = 0; j < MAX_GEOMETRYTYPES; ++j)
  1227. vertexShaders[j] = GetVertexShader(vertexShaderName + geometryVSVariations[j], j != 0);
  1228. }
  1229. pixelShaders.Resize(1);
  1230. pixelShaders[0] = GetPixelShader(pixelShaderName);
  1231. }
  1232. technique->MarkShadersLoaded(shadersChangedFrameNumber_);
  1233. }
  1234. void Renderer::ReleaseMaterialShaders()
  1235. {
  1236. PODVector<Material*> materials;
  1237. cache_->GetResources<Material>(materials);
  1238. for (unsigned i = 0; i < materials.Size(); ++i)
  1239. materials[i]->ReleaseShaders();
  1240. }
  1241. void Renderer::ReloadTextures()
  1242. {
  1243. PODVector<Resource*> textures;
  1244. cache_->GetResources(textures, Texture2D::GetTypeStatic());
  1245. for (unsigned i = 0; i < textures.Size(); ++i)
  1246. cache_->ReloadResource(textures[i]);
  1247. cache_->GetResources(textures, TextureCube::GetTypeStatic());
  1248. for (unsigned i = 0; i < textures.Size(); ++i)
  1249. cache_->ReloadResource(textures[i]);
  1250. }
  1251. void Renderer::CreateGeometries()
  1252. {
  1253. SharedPtr<VertexBuffer> dlvb(new VertexBuffer(context_));
  1254. dlvb->SetSize(4, MASK_POSITION);
  1255. dlvb->SetData(dirLightVertexData);
  1256. SharedPtr<IndexBuffer> dlib(new IndexBuffer(context_));
  1257. dlib->SetSize(6, false);
  1258. dlib->SetData(dirLightIndexData);
  1259. dirLightGeometry_ = new Geometry(context_);
  1260. dirLightGeometry_->SetVertexBuffer(0, dlvb);
  1261. dirLightGeometry_->SetIndexBuffer(dlib);
  1262. dirLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, dlib->GetIndexCount());
  1263. SharedPtr<VertexBuffer> slvb(new VertexBuffer(context_));
  1264. slvb->SetSize(8, MASK_POSITION);
  1265. slvb->SetData(spotLightVertexData);
  1266. SharedPtr<IndexBuffer> slib(new IndexBuffer(context_));
  1267. slib->SetSize(36, false);
  1268. slib->SetData(spotLightIndexData);
  1269. spotLightGeometry_ = new Geometry(context_);
  1270. spotLightGeometry_->SetVertexBuffer(0, slvb);
  1271. spotLightGeometry_->SetIndexBuffer(slib);
  1272. spotLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, slib->GetIndexCount());
  1273. SharedPtr<VertexBuffer> plvb(new VertexBuffer(context_));
  1274. plvb->SetSize(24, MASK_POSITION);
  1275. plvb->SetData(pointLightVertexData);
  1276. SharedPtr<IndexBuffer> plib(new IndexBuffer(context_));
  1277. plib->SetSize(132, false);
  1278. plib->SetData(pointLightIndexData);
  1279. pointLightGeometry_ = new Geometry(context_);
  1280. pointLightGeometry_->SetVertexBuffer(0, plvb);
  1281. pointLightGeometry_->SetIndexBuffer(plib);
  1282. pointLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, plib->GetIndexCount());
  1283. faceSelectCubeMap_ = new TextureCube(context_);
  1284. faceSelectCubeMap_->SetNumLevels(1);
  1285. faceSelectCubeMap_->SetSize(1, graphics_->GetRGBAFormat());
  1286. faceSelectCubeMap_->SetFilterMode(FILTER_NEAREST);
  1287. unsigned char data[256 * 256 * 4];
  1288. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1289. {
  1290. unsigned axis = i / 2;
  1291. data[0] = (axis == 0) ? 255 : 0;
  1292. data[1] = (axis == 1) ? 255 : 0;
  1293. data[2] = (axis == 2) ? 255 : 0;
  1294. data[3] = 0;
  1295. faceSelectCubeMap_->SetData((CubeMapFace)i, 0, 0, 0, 1, 1, data);
  1296. }
  1297. indirectionCubeMap_ = new TextureCube(context_);
  1298. indirectionCubeMap_->SetNumLevels(1);
  1299. indirectionCubeMap_->SetSize(256, graphics_->GetRGBAFormat());
  1300. indirectionCubeMap_->SetFilterMode(FILTER_BILINEAR);
  1301. indirectionCubeMap_->SetAddressMode(COORD_U, ADDRESS_CLAMP);
  1302. indirectionCubeMap_->SetAddressMode(COORD_V, ADDRESS_CLAMP);
  1303. indirectionCubeMap_->SetAddressMode(COORD_W, ADDRESS_CLAMP);
  1304. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1305. {
  1306. unsigned char faceX = (i & 1) * 255;
  1307. unsigned char faceY = (i / 2) * 255 / 3;
  1308. unsigned char* dest = data;
  1309. for (unsigned y = 0; y < 256; ++y)
  1310. {
  1311. for (unsigned x = 0; x < 256; ++x)
  1312. {
  1313. #ifdef USE_OPENGL
  1314. *dest++ = x;
  1315. *dest++ = 255 - y;
  1316. *dest++ = faceX;
  1317. *dest++ = 255 * 2 / 3 - faceY;
  1318. #else
  1319. *dest++ = x;
  1320. *dest++ = y;
  1321. *dest++ = faceX;
  1322. *dest++ = faceY;
  1323. #endif
  1324. }
  1325. }
  1326. indirectionCubeMap_->SetData((CubeMapFace)i, 0, 0, 0, 256, 256, data);
  1327. }
  1328. }
  1329. void Renderer::CreateInstancingBuffer()
  1330. {
  1331. // Do not create buffer if instancing not supported
  1332. if (!graphics_->GetSM3Support())
  1333. {
  1334. instancingBuffer_.Reset();
  1335. dynamicInstancing_ = false;
  1336. return;
  1337. }
  1338. // If must lock the buffer for each batch group, set a smaller size
  1339. unsigned defaultSize = graphics_->GetStreamOffsetSupport() ? INSTANCING_BUFFER_DEFAULT_SIZE : INSTANCING_BUFFER_DEFAULT_SIZE / 4;
  1340. instancingBuffer_ = new VertexBuffer(context_);
  1341. if (!instancingBuffer_->SetSize(defaultSize, INSTANCING_BUFFER_MASK, true))
  1342. {
  1343. instancingBuffer_.Reset();
  1344. dynamicInstancing_ = false;
  1345. }
  1346. }
  1347. void Renderer::ResetShadowMaps()
  1348. {
  1349. shadowMaps_.Clear();
  1350. colorShadowMaps_.Clear();
  1351. shadowDepthStencil_.Reset();
  1352. }
  1353. void Renderer::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  1354. {
  1355. if (!initialized_)
  1356. Initialize();
  1357. else
  1358. {
  1359. // When screen mode changes, purge old views
  1360. ResetViews();
  1361. }
  1362. }
  1363. void Renderer::HandleGraphicsFeatures(StringHash eventType, VariantMap& eventData)
  1364. {
  1365. // Reinitialize if already initialized
  1366. if (initialized_)
  1367. Initialize();
  1368. }
  1369. void Renderer::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  1370. {
  1371. if (initialized_)
  1372. {
  1373. using namespace RenderUpdate;
  1374. Update(eventData[P_TIMESTEP].GetFloat());
  1375. }
  1376. }