Renderer.cpp 51 KB

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