Renderer.cpp 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378
  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 "OctreeQuery.h"
  38. #include "Profiler.h"
  39. #include "Renderer.h"
  40. #include "ResourceCache.h"
  41. #include "Scene.h"
  42. #include "Shader.h"
  43. #include "ShaderVariation.h"
  44. #include "Technique.h"
  45. #include "Texture2D.h"
  46. #include "TextureCube.h"
  47. #include "VertexBuffer.h"
  48. #include "View.h"
  49. #include "XMLFile.h"
  50. #include "Zone.h"
  51. #include "DebugNew.h"
  52. static const float dirLightVertexData[] =
  53. {
  54. -1, 1, 0,
  55. 1, 1, 0,
  56. 1, -1, 0,
  57. -1, -1, 0,
  58. };
  59. static const unsigned short dirLightIndexData[] =
  60. {
  61. 0, 1, 2,
  62. 2, 3, 0,
  63. };
  64. static const float pointLightVertexData[] =
  65. {
  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. 0.423169f, 1.000000f, 0.423169f,
  74. -1.000000f, 0.423169f, -0.423169f,
  75. -1.000000f, -0.423169f, -0.423169f,
  76. -1.000000f, -0.423169f, 0.423169f,
  77. -1.000000f, 0.423169f, 0.423169f,
  78. 0.423169f, 0.423169f, -1.000000f,
  79. 0.423169f, -0.423169f, -1.000000f,
  80. -0.423169f, -0.423169f, -1.000000f,
  81. -0.423169f, 0.423169f, -1.000000f,
  82. 1.000000f, 0.423169f, 0.423169f,
  83. 1.000000f, -0.423169f, 0.423169f,
  84. 1.000000f, -0.423169f, -0.423169f,
  85. 1.000000f, 0.423169f, -0.423169f,
  86. 0.423169f, -0.423169f, 1.000000f,
  87. 0.423169f, 0.423169f, 1.000000f,
  88. -0.423169f, 0.423169f, 1.000000f,
  89. -0.423169f, -0.423169f, 1.000000f
  90. };
  91. static const unsigned short pointLightIndexData[] =
  92. {
  93. 0, 1, 2,
  94. 0, 2, 3,
  95. 4, 5, 6,
  96. 4, 6, 7,
  97. 8, 9, 10,
  98. 8, 10, 11,
  99. 12, 13, 14,
  100. 12, 14, 15,
  101. 16, 17, 18,
  102. 16, 18, 19,
  103. 20, 21, 22,
  104. 20, 22, 23,
  105. 0, 10, 9,
  106. 0, 9, 1,
  107. 13, 2, 1,
  108. 13, 1, 14,
  109. 23, 0, 3,
  110. 23, 3, 20,
  111. 17, 3, 2,
  112. 17, 2, 18,
  113. 21, 7, 6,
  114. 21, 6, 22,
  115. 7, 16, 19,
  116. 7, 19, 4,
  117. 5, 8, 11,
  118. 5, 11, 6,
  119. 4, 12, 15,
  120. 4, 15, 5,
  121. 22, 11, 10,
  122. 22, 10, 23,
  123. 8, 15, 14,
  124. 8, 14, 9,
  125. 12, 19, 18,
  126. 12, 18, 13,
  127. 16, 21, 20,
  128. 16, 20, 17,
  129. 0, 23, 10,
  130. 1, 9, 14,
  131. 2, 13, 18,
  132. 3, 17, 20,
  133. 6, 11, 22,
  134. 5, 15, 8,
  135. 4, 19, 12,
  136. 7, 21, 16
  137. };
  138. static const float spotLightVertexData[] =
  139. {
  140. // Use slightly clamped Z-range so that shadowed point light splits line up nicely
  141. 0.00001f, 0.00001f, 0.00001f,
  142. 0.00001f, -0.00001f, 0.00001f,
  143. -0.00001f, -0.00001f, 0.00001f,
  144. -0.00001f, 0.00001f, 0.00001f,
  145. 1.00000f, 1.00000f, 0.99999f,
  146. 1.00000f, -1.00000f, 0.99999f,
  147. -1.00000f, -1.00000f, 0.99999f,
  148. -1.00000f, 1.00000f, 0.99999f,
  149. };
  150. static const unsigned short spotLightIndexData[] =
  151. {
  152. 3, 0, 1,
  153. 3, 1, 2,
  154. 0, 4, 5,
  155. 0, 5, 1,
  156. 3, 7, 4,
  157. 3, 4, 0,
  158. 7, 3, 2,
  159. 7, 2, 6,
  160. 6, 2, 1,
  161. 6, 1, 5,
  162. 7, 5, 4,
  163. 7, 6, 5
  164. };
  165. static const String hwVariations[] =
  166. {
  167. "",
  168. // No specific hardware shadow compare variation on OpenGL, it is always supported
  169. #ifdef USE_OPENGL
  170. ""
  171. #else
  172. "HW"
  173. #endif
  174. };
  175. static const String linearVariations[] =
  176. {
  177. "",
  178. "Linear"
  179. };
  180. static const String depthVariations[] =
  181. {
  182. "",
  183. "Depth"
  184. };
  185. static const String geometryVSVariations[] =
  186. {
  187. "",
  188. "Skinned",
  189. "Instanced",
  190. "Billboard"
  191. };
  192. static const String lightVSVariations[] =
  193. {
  194. "",
  195. "Spot",
  196. "Shadow",
  197. "SpotShadow"
  198. };
  199. static const String deferredLightVSVariations[] =
  200. {
  201. "",
  202. "Dir",
  203. "Ortho",
  204. "OrthoDir"
  205. };
  206. static const String lightPSVariations[] =
  207. {
  208. "Dir",
  209. "DirSpec",
  210. "Spot",
  211. "SpotSpec",
  212. "Point",
  213. "PointSpec",
  214. "PointMask",
  215. "PointMaskSpec",
  216. "DirShadow",
  217. "DirShadowSpec",
  218. "SpotShadow",
  219. "SpotShadowSpec",
  220. "PointShadow",
  221. "PointShadowSpec",
  222. "PointMaskShadow",
  223. "PointMaskShadowSpec",
  224. "OrthoDir",
  225. "OrthoDirSpec",
  226. "OrthoSpot",
  227. "OrthoSpotSpec",
  228. "OrthoPoint",
  229. "OrthoPointSpec",
  230. "OrthoPointMask",
  231. "OrthoPointMaskSpec",
  232. "OrthoDirShadow",
  233. "OrthoDirShadowSpec",
  234. "OrthoSpotShadow",
  235. "OrthoSpotShadowSpec",
  236. "OrthoPointShadow",
  237. "OrthoPointShadowSpec",
  238. "OrthoPointMaskShadow",
  239. "OrthoPointMaskShadowSpec"
  240. };
  241. static const unsigned INSTANCING_BUFFER_MASK = MASK_INSTANCEMATRIX1 | MASK_INSTANCEMATRIX2 | MASK_INSTANCEMATRIX3;
  242. static const Viewport noViewport;
  243. OBJECTTYPESTATIC(Renderer);
  244. Renderer::Renderer(Context* context) :
  245. Object(context),
  246. defaultZone_(new Zone(context)),
  247. numViews_(0),
  248. numShadowCameras_(0),
  249. numSplitLights_(0),
  250. numTempNodes_(0),
  251. specularLighting_(true),
  252. drawShadows_(true),
  253. textureAnisotropy_(4),
  254. textureFilterMode_(FILTER_TRILINEAR),
  255. textureQuality_(QUALITY_HIGH),
  256. materialQuality_(QUALITY_HIGH),
  257. shadowMapSize_(1024),
  258. shadowMapHiresDepth_(false),
  259. reuseShadowMaps_(true),
  260. dynamicInstancing_(true),
  261. minInstanceGroupSize_(4),
  262. maxInstanceTriangles_(500),
  263. maxOccluderTriangles_(5000),
  264. occlusionBufferSize_(256),
  265. occluderSizeThreshold_(0.1f),
  266. shadersChangedFrameNumber_(M_MAX_UNSIGNED),
  267. shadersDirty_(true),
  268. initialized_(false)
  269. {
  270. SubscribeToEvent(E_SCREENMODE, HANDLER(Renderer, HandleScreenMode));
  271. SubscribeToEvent(E_RENDERUPDATE, HANDLER(Renderer, HandleRenderUpdate));
  272. // Default to one of each shadow map resolution
  273. for (unsigned i = 0; i < NUM_SHADOWMAP_RESOLUTIONS; ++i)
  274. shadowMaps_[i].Resize(1);
  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::SetSpecularLighting(bool enable)
  295. {
  296. specularLighting_ = enable;
  297. }
  298. void Renderer::SetDrawShadows(bool enable)
  299. {
  300. if (!graphics_)
  301. return;
  302. drawShadows_ = enable;
  303. if (!CreateShadowMaps())
  304. drawShadows_ = false;
  305. }
  306. void Renderer::SetTextureAnisotropy(int level)
  307. {
  308. textureAnisotropy_ = Max(level, 1);
  309. }
  310. void Renderer::SetTextureFilterMode(TextureFilterMode mode)
  311. {
  312. textureFilterMode_ = mode;
  313. }
  314. void Renderer::SetTextureQuality(int quality)
  315. {
  316. quality = Clamp(quality, QUALITY_LOW, QUALITY_HIGH);
  317. if (quality != textureQuality_)
  318. {
  319. textureQuality_ = quality;
  320. ReloadTextures();
  321. }
  322. }
  323. void Renderer::SetMaterialQuality(int quality)
  324. {
  325. materialQuality_ = Clamp(quality, QUALITY_LOW, QUALITY_MAX);
  326. shadersDirty_ = true;
  327. ResetViews();
  328. }
  329. void Renderer::SetShadowMapSize(int size)
  330. {
  331. if (!graphics_)
  332. return;
  333. shadowMapSize_ = Max(size, SHADOW_MIN_PIXELS);
  334. if (!CreateShadowMaps())
  335. {
  336. shadowMapSize_ = 1024;
  337. if (!CreateShadowMaps())
  338. drawShadows_ = false;
  339. }
  340. }
  341. void Renderer::SetShadowMapHiresDepth(bool enable)
  342. {
  343. if (!graphics_)
  344. return;
  345. if (!graphics_->GetHiresShadowSupport())
  346. enable = false;
  347. shadowMapHiresDepth_ = enable;
  348. if (!CreateShadowMaps())
  349. drawShadows_ = false;
  350. }
  351. void Renderer::SetReuseShadowMaps(bool enable)
  352. {
  353. if (enable == reuseShadowMaps_)
  354. return;
  355. reuseShadowMaps_ = enable;
  356. if (reuseShadowMaps_)
  357. {
  358. for (unsigned i = 0; i < NUM_SHADOWMAP_RESOLUTIONS; ++i)
  359. shadowMaps_[i].Resize(1);
  360. }
  361. if (!CreateShadowMaps())
  362. drawShadows_ = false;
  363. shadersDirty_ = true;
  364. }
  365. void Renderer::SetNumShadowMaps(unsigned full, unsigned half, unsigned quarter)
  366. {
  367. shadowMaps_[0].Resize(full ? full : 1);
  368. shadowMaps_[1].Resize(half ? half : 1);
  369. shadowMaps_[2].Resize(quarter ? quarter : 1);
  370. if (!CreateShadowMaps())
  371. drawShadows_ = false;
  372. }
  373. void Renderer::SetDynamicInstancing(bool enable)
  374. {
  375. if (!instancingBuffer_)
  376. enable = false;
  377. dynamicInstancing_ = enable;
  378. }
  379. void Renderer::SetMinInstanceGroupSize(int size)
  380. {
  381. minInstanceGroupSize_ = Max(size, 2);
  382. }
  383. void Renderer::SetMaxInstanceTriangles(int triangles)
  384. {
  385. maxInstanceTriangles_ = Max(triangles, 0);
  386. }
  387. void Renderer::SetMaxOccluderTriangles(int triangles)
  388. {
  389. maxOccluderTriangles_ = Max(triangles, 0);
  390. }
  391. void Renderer::SetOcclusionBufferSize(int size)
  392. {
  393. occlusionBufferSize_ = Max(size, 1);
  394. occlusionBuffers_.Clear();
  395. }
  396. void Renderer::SetOccluderSizeThreshold(float screenSize)
  397. {
  398. occluderSizeThreshold_ = Max(screenSize, 0.0f);
  399. }
  400. const Viewport& Renderer::GetViewport(unsigned index) const
  401. {
  402. return index < viewports_.Size() ? viewports_[index] : noViewport;
  403. }
  404. ShaderVariation* Renderer::GetVertexShader(const String& name, bool checkExists) const
  405. {
  406. return GetShader(name, vsFormat_, checkExists);
  407. }
  408. ShaderVariation* Renderer::GetPixelShader(const String& name, bool checkExists) const
  409. {
  410. return GetShader(name, psFormat_, checkExists);
  411. }
  412. unsigned Renderer::GetNumGeometries(bool allViews) const
  413. {
  414. unsigned numGeometries = 0;
  415. unsigned lastView = allViews ? numViews_ : 1;
  416. for (unsigned i = 0; i < lastView; ++i)
  417. numGeometries += views_[i]->GetGeometries().Size();
  418. return numGeometries;
  419. }
  420. unsigned Renderer::GetNumLights(bool allViews) const
  421. {
  422. unsigned nulights_ = 0;
  423. unsigned lastView = allViews ? numViews_ : 1;
  424. for (unsigned i = 0; i < lastView; ++i)
  425. nulights_ += views_[i]->GetLights().Size();
  426. return nulights_;
  427. }
  428. unsigned Renderer::GetNumShadowMaps(bool allViews) const
  429. {
  430. unsigned numShadowMaps = 0;
  431. unsigned lastView = allViews ? numViews_ : 1;
  432. for (unsigned i = 0; i < lastView; ++i)
  433. {
  434. const Vector<LightBatchQueue>& lightQueues = views_[i]->GetLightQueues();
  435. for (unsigned j = 0; j < lightQueues.Size(); ++j)
  436. {
  437. Light* light = lightQueues[j].light_;
  438. if (light && light->GetShadowMap())
  439. ++numShadowMaps;
  440. }
  441. }
  442. return numShadowMaps;
  443. }
  444. unsigned Renderer::GetNumOccluders(bool allViews) const
  445. {
  446. unsigned numOccluders = 0;
  447. unsigned lastView = allViews ? numViews_ : 1;
  448. for (unsigned i = 0; i < lastView; ++i)
  449. numOccluders += views_[i]->GetOccluders().Size();
  450. return numOccluders;
  451. }
  452. unsigned Renderer::GetNumShadowOccluders(bool allViews) const
  453. {
  454. unsigned numShadowOccluders = 0;
  455. unsigned lastView = allViews ? numViews_ : 1;
  456. for (unsigned i = 0; i < lastView; ++i)
  457. numShadowOccluders += views_[i]->GetShadowOccluders().Size();
  458. return numShadowOccluders;
  459. }
  460. const OcclusionBuffer* Renderer::GetOcclusionBuffer(float aspectRatio, bool halfResolution)
  461. {
  462. // Return an occlusion buffer for debug output purposes. Do not allocate new
  463. int width = occlusionBufferSize_;
  464. int height = (int)(occlusionBufferSize_ / aspectRatio);
  465. if (halfResolution)
  466. {
  467. width >>= 1;
  468. height >>= 1;
  469. }
  470. int searchKey = (width << 16) | height;
  471. HashMap<int, SharedPtr<OcclusionBuffer> >::Iterator i = occlusionBuffers_.Find(searchKey);
  472. if (i != occlusionBuffers_.End())
  473. return i->second_;
  474. else
  475. return 0;
  476. }
  477. void Renderer::Update(float timeStep)
  478. {
  479. PROFILE(UpdateViews);
  480. numViews_ = 0;
  481. // If device lost, do not perform update. This is because any dynamic vertex/index buffer updates happen already here,
  482. // and if the device is lost, the updates queue up, causing memory use to rise constantly
  483. if (!graphics_ || !graphics_->IsInitialized() || graphics_->IsDeviceLost())
  484. return;
  485. // Advance frame number & time, set up the frameinfo structure, and reset views & stats
  486. frame_.frameNumber_ = GetSubsystem<Time>()->GetFrameNumber();
  487. frame_.timeStep_ = timeStep;
  488. frame_.camera_ = 0;
  489. numShadowCameras_ = 0;
  490. numSplitLights_ = 0;
  491. numTempNodes_ = 0;
  492. updateOctrees_.Clear();
  493. // Reload shaders if needed
  494. if (shadersDirty_)
  495. LoadShaders();
  496. // Process all viewports. Use reverse order, because during rendering the order will be reversed again to handle auxiliary
  497. // 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 nodes which need that, and reinsert moved nodes.)
  505. // However, if the same scene is viewed from multiple cameras, update the octree only once
  506. Octree* octree = viewport.scene_->GetComponent<Octree>();
  507. DebugRenderer* debug = viewport.scene_->GetComponent<DebugRenderer>();
  508. if (updateOctrees_.Find(octree) == updateOctrees_.End())
  509. {
  510. frame_.camera_ = viewport.camera_;
  511. frame_.viewSize_ = IntVector2(viewport.rect_.right_ - viewport.rect_.left_, viewport.rect_.bottom_ - viewport.rect_.top_);
  512. if (frame_.viewSize_ == IntVector2::ZERO)
  513. frame_.viewSize_ = IntVector2(graphics_->GetWidth(), graphics_->GetHeight());
  514. octree->Update(frame_);
  515. updateOctrees_.Insert(octree);
  516. // Set also the view for the debug graphics already here, so that it can use culling
  517. /// \todo May result in incorrect debug geometry culling if the same scene is drawn from multiple viewports
  518. if (debug)
  519. debug->SetView(viewport.camera_);
  520. }
  521. // Update the viewport's main view and any auxiliary views it Creates
  522. for (unsigned i = mainView; i < numViews_; ++i)
  523. views_[i]->Update(frame_);
  524. }
  525. return;
  526. }
  527. void Renderer::Render()
  528. {
  529. if (!graphics_)
  530. return;
  531. PROFILE(RenderViews);
  532. graphics_->SetDefaultTextureFilterMode(textureFilterMode_);
  533. graphics_->SetTextureAnisotropy(textureAnisotropy_);
  534. // If no views, just clear the screen
  535. if (!numViews_)
  536. {
  537. numPrimitives_ = 0;
  538. numBatches_ = 0;
  539. graphics_->SetAlphaTest(false);
  540. graphics_->SetBlendMode(BLEND_REPLACE);
  541. graphics_->SetColorWrite(true);
  542. graphics_->SetDepthWrite(true);
  543. graphics_->SetFillMode(FILL_SOLID);
  544. graphics_->SetScissorTest(false);
  545. graphics_->SetStencilTest(false);
  546. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH | CLEAR_STENCIL);
  547. return;
  548. }
  549. // Render views from last to first (each main view is rendered after the auxiliary views it depends on)
  550. for (unsigned i = numViews_ - 1; i < numViews_; --i)
  551. views_[i]->Render();
  552. // Copy the number of batches & primitives from Graphics so that we can account for 3D geometry only
  553. numPrimitives_ = graphics_->GetNumPrimitives();
  554. numBatches_ = graphics_->GetNumBatches();
  555. }
  556. void Renderer::DrawDebugGeometry(bool depthTest)
  557. {
  558. PROFILE(RendererDrawDebug);
  559. /// \todo Because debug geometry is per-scene, if two cameras show views of the same area, occlusion is not shown correctly
  560. HashSet<Drawable*> processedGeometries;
  561. HashSet<Light*> processedLights;
  562. for (unsigned i = 0; i < numViews_; ++i)
  563. {
  564. // Make sure it's a main view, and process each node only once
  565. View* view = views_[i];
  566. if (view->GetRenderTarget())
  567. continue;
  568. Octree* octree = view->GetOctree();
  569. if (!octree)
  570. continue;
  571. Scene* scene = static_cast<Scene*>(octree->GetNode());
  572. if (!scene)
  573. continue;
  574. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  575. if (!debug)
  576. continue;
  577. const PODVector<Drawable*>& geometries = view->GetGeometries();
  578. const PODVector<Light*>& lights = view->GetLights();
  579. for (unsigned i = 0; i < geometries.Size(); ++i)
  580. {
  581. if (processedGeometries.Find(geometries[i]) == processedGeometries.End())
  582. {
  583. geometries[i]->DrawDebugGeometry(debug, depthTest);
  584. processedGeometries.Insert(geometries[i]);
  585. }
  586. }
  587. for (unsigned i = 0; i < lights.Size(); ++i)
  588. {
  589. if (processedLights.Find(lights[i]) == processedLights.End())
  590. {
  591. lights[i]->DrawDebugGeometry(debug, depthTest);
  592. processedLights.Insert(lights[i]);
  593. }
  594. }
  595. }
  596. }
  597. void Renderer::Initialize()
  598. {
  599. Graphics* graphics = GetSubsystem<Graphics>();
  600. ResourceCache* cache = GetSubsystem<ResourceCache>();
  601. if (!graphics || !graphics->IsInitialized() || !cache)
  602. return;
  603. PROFILE(InitRenderer);
  604. graphics_ = graphics;
  605. cache_ = cache;
  606. // Check shader model support
  607. #ifndef USE_OPENGL
  608. if (graphics_->GetSM3Support())
  609. {
  610. shaderPath_ = "Shaders/SM3/";
  611. vsFormat_ = ".vs3";
  612. psFormat_ = ".ps3";
  613. }
  614. else
  615. {
  616. shaderPath_ = "Shaders/SM2/";
  617. vsFormat_ = ".vs2";
  618. psFormat_ = ".ps2";
  619. }
  620. #else
  621. {
  622. shaderPath_ = "Shaders/GLSL/";
  623. vsFormat_ = ".vert";
  624. psFormat_ = ".frag";
  625. }
  626. #endif
  627. defaultLightRamp_ = cache->GetResource<Texture2D>("Textures/Ramp.png");
  628. defaultLightSpot = cache->GetResource<Texture2D>("Textures/Spot.png");
  629. defaultMaterial_ = cache->GetResource<Material>("Materials/Default.xml");
  630. CreateGeometries();
  631. CreateInstancingBuffer();
  632. if (!CreateShadowMaps())
  633. drawShadows_ = false;
  634. viewports_.Resize(1);
  635. ResetViews();
  636. LOGINFO("Initialized renderer");
  637. initialized_ = true;
  638. }
  639. void Renderer::ResetViews()
  640. {
  641. views_.Clear();
  642. numViews_ = 0;
  643. }
  644. bool Renderer::AddView(RenderSurface* renderTarget, const Viewport& viewport)
  645. {
  646. // If using a render target texture, make sure it is supported, and will not be rendered to multiple times
  647. if (renderTarget)
  648. {
  649. if (!graphics_->GetRenderTargetSupport())
  650. return false;
  651. for (unsigned i = 0; i < numViews_; ++i)
  652. {
  653. if (views_[i]->GetRenderTarget() == renderTarget)
  654. return false;
  655. }
  656. }
  657. if (views_.Size() <= numViews_)
  658. views_.Resize(numViews_ + 1);
  659. if (!views_[numViews_])
  660. views_[numViews_] = new View(context_);
  661. if (views_[numViews_]->Define(renderTarget, viewport))
  662. {
  663. ++numViews_;
  664. return true;
  665. }
  666. else
  667. return false;
  668. }
  669. OcclusionBuffer* Renderer::GetOrCreateOcclusionBuffer(Camera* camera, int maxOccluderTriangles, bool halfResolution)
  670. {
  671. // Get an occlusion buffer matching the aspect ratio. If not found, allocate new
  672. int width = occlusionBufferSize_;
  673. int height = (int)(occlusionBufferSize_ / camera->GetAspectRatio());
  674. if (halfResolution)
  675. {
  676. width >>= 1;
  677. height >>= 1;
  678. }
  679. int searchKey = (width << 16) | height;
  680. SharedPtr<OcclusionBuffer> buffer;
  681. HashMap<int, SharedPtr<OcclusionBuffer> >::Iterator i = occlusionBuffers_.Find(searchKey);
  682. if (i != occlusionBuffers_.End())
  683. buffer = i->second_;
  684. else
  685. {
  686. buffer = new OcclusionBuffer(context_);
  687. buffer->SetSize(width, height);
  688. occlusionBuffers_[searchKey] = buffer;
  689. }
  690. buffer->SetView(camera);
  691. buffer->SetMaxTriangles(maxOccluderTriangles);
  692. buffer->Clear();
  693. return buffer;
  694. }
  695. Geometry* Renderer::GetLightGeometry(Light* light)
  696. {
  697. switch (light->GetLightType())
  698. {
  699. case LIGHT_POINT:
  700. return pointLightGeometry_;
  701. case LIGHT_SPOT:
  702. case LIGHT_SPLITPOINT:
  703. return spotLightGeometry_;
  704. default:
  705. return dirLightGeometry_;
  706. }
  707. }
  708. Texture2D* Renderer::GetShadowMap(float resolution)
  709. {
  710. unsigned index = 0;
  711. if (resolution < 0.75f)
  712. index = (resolution >= 0.375f) ? 1 : 2;
  713. if (reuseShadowMaps_)
  714. return shadowMaps_[index][0];
  715. else
  716. {
  717. // If higher resolution shadow maps already used up, fall back to lower resolutions
  718. while (index < NUM_SHADOWMAP_RESOLUTIONS)
  719. {
  720. if (shadowMapUseCount_[index] < shadowMaps_[index].Size())
  721. return shadowMaps_[index][shadowMapUseCount_[index]++];
  722. ++index;
  723. }
  724. return 0;
  725. }
  726. }
  727. void Renderer::ResetShadowMapUseCount()
  728. {
  729. for (unsigned i = 0; i < NUM_SHADOWMAP_RESOLUTIONS; ++i)
  730. shadowMapUseCount_[i] = 0;
  731. }
  732. ShaderVariation* Renderer::GetShader(const String& name, const String& extension, bool checkExists) const
  733. {
  734. String shaderName = shaderPath_;
  735. String variationName;
  736. unsigned split = name.Find('_');
  737. if (split != String::NPOS)
  738. {
  739. shaderName += name.Substring(0, split) + extension;
  740. variationName = name.Substring(split + 1);
  741. }
  742. else
  743. shaderName += name + extension;
  744. if (checkExists)
  745. {
  746. if (!cache_->Exists(shaderName))
  747. return 0;
  748. }
  749. Shader* shader = cache_->GetResource<Shader>(shaderName);
  750. if (shader)
  751. return shader->GetVariation(variationName);
  752. else
  753. return 0;
  754. }
  755. void Renderer::SetBatchShaders(Batch& batch, Technique* technique, Pass* pass, bool allowShadows)
  756. {
  757. batch.pass_ = pass;
  758. // Check if shaders are unloaded or need reloading
  759. Vector<SharedPtr<ShaderVariation> >& vertexShaders = pass->GetVertexShaders();
  760. Vector<SharedPtr<ShaderVariation> >& pixelShaders = pass->GetPixelShaders();
  761. if (!vertexShaders.Size() || !pixelShaders.Size() || technique->GetShadersLoadedFrameNumber() !=
  762. shadersChangedFrameNumber_)
  763. {
  764. // First release all previous shaders, then load
  765. technique->ReleaseShaders();
  766. LoadMaterialShaders(technique);
  767. }
  768. // Make sure shaders are loaded now
  769. if (vertexShaders.Size() && pixelShaders.Size())
  770. {
  771. // Check whether is a forward lit pass. If not, there is only one pixel shader
  772. PassType type = pass->GetType();
  773. if (type == PASS_LIGHT || type == PASS_LITBASE)
  774. {
  775. Light* light = batch.light_;
  776. if (!light)
  777. {
  778. // Do not log error, as it would result in a lot of spam
  779. batch.vertexShader_ = 0;
  780. batch.pixelShader_ = 0;
  781. return;
  782. }
  783. unsigned vsi = 0;
  784. unsigned psi = 0;
  785. vsi = batch.geometryType_ * MAX_LIGHT_VS_VARIATIONS;
  786. bool materialHasSpecular = batch.material_ ? batch.material_->GetSpecular() : true;
  787. if (specularLighting_ && light->GetSpecularIntensity() > 0.0f && materialHasSpecular)
  788. psi += LPS_SPEC;
  789. if (allowShadows && light->GetShadowMap())
  790. {
  791. vsi += LVS_SHADOW;
  792. psi += LPS_SHADOW;
  793. }
  794. switch (light->GetLightType())
  795. {
  796. case LIGHT_POINT:
  797. case LIGHT_SPLITPOINT:
  798. if (light->GetShapeTexture())
  799. psi += LPS_POINTMASK;
  800. else
  801. psi += LPS_POINT;
  802. break;
  803. case LIGHT_SPOT:
  804. psi += LPS_SPOT;
  805. vsi += LVS_SPOT;
  806. break;
  807. }
  808. batch.vertexShader_ = vertexShaders[vsi];
  809. batch.pixelShader_ = pixelShaders[psi];
  810. batch.vertexShaderIndex_ = vsi;
  811. }
  812. else
  813. {
  814. unsigned vsi = batch.geometryType_;
  815. batch.vertexShader_ = vertexShaders[vsi];
  816. batch.pixelShader_ = pixelShaders[0];
  817. batch.vertexShaderIndex_ = vsi;
  818. }
  819. }
  820. batch.CalculateSortKey();
  821. // Log error if shaders could not be assigned, but only once per technique
  822. if (!batch.vertexShader_ || !batch.pixelShader_)
  823. {
  824. if (shaderErrorDisplayed_.Find(technique) == shaderErrorDisplayed_.End())
  825. {
  826. shaderErrorDisplayed_.Insert(technique);
  827. LOGERROR("Technique " + technique->GetName() + " has missing shaders");
  828. }
  829. }
  830. }
  831. void Renderer::SetLightVolumeShaders(Batch& batch)
  832. {
  833. unsigned vsi = DLVS_NONE;
  834. unsigned psi = DLPS_NONE;
  835. Light* light = batch.light_;
  836. switch (light->GetLightType())
  837. {
  838. case LIGHT_DIRECTIONAL:
  839. vsi += DLVS_DIR;
  840. break;
  841. case LIGHT_POINT:
  842. case LIGHT_SPLITPOINT:
  843. if (light->GetShapeTexture())
  844. psi += DLPS_POINTMASK;
  845. else
  846. psi += DLPS_POINT;
  847. break;
  848. case LIGHT_SPOT:
  849. psi += DLPS_SPOT;
  850. break;
  851. }
  852. if (light->GetShadowMap())
  853. psi += DLPS_SHADOW;
  854. if (specularLighting_ && light->GetSpecularIntensity() > 0.0f)
  855. psi += DLPS_SPEC;
  856. if (batch.camera_->IsOrthographic())
  857. {
  858. vsi += DLVS_ORTHO;
  859. psi += DLPS_ORTHO;
  860. }
  861. batch.material_ = 0;
  862. batch.pass_ = 0;
  863. batch.vertexShader_ = lightVS_[vsi];
  864. batch.pixelShader_ = lightPS_[psi];
  865. batch.vertexShaderIndex_ = vsi;
  866. batch.CalculateSortKey();
  867. }
  868. void Renderer::LoadShaders()
  869. {
  870. LOGINFO("Reloading shaders");
  871. // Release old material shaders, mark them for reload
  872. ReleaseMaterialShaders();
  873. shadersChangedFrameNumber_ = GetSubsystem<Time>()->GetFrameNumber();
  874. // Load inbuilt shaders
  875. stencilVS_ = GetVertexShader("Stencil");
  876. stencilPS_ = GetPixelShader("Stencil");
  877. lightVS_.Clear();
  878. lightPS_.Clear();
  879. RenderMode mode = graphics_->GetRenderMode();
  880. if (mode != RENDER_FORWARD)
  881. {
  882. lightVS_.Resize(MAX_DEFERRED_LIGHT_VS_VARIATIONS);
  883. lightPS_.Resize(MAX_DEFERRED_LIGHT_PS_VARIATIONS);
  884. unsigned hwShadows = graphics_->GetHardwareShadowSupport() ? 1 : 0;
  885. for (unsigned i = 0; i < MAX_DEFERRED_LIGHT_VS_VARIATIONS; ++i)
  886. lightVS_[i] = GetVertexShader("Light_" + deferredLightVSVariations[i]);
  887. for (unsigned i = 0; i < MAX_DEFERRED_LIGHT_PS_VARIATIONS; ++i)
  888. {
  889. unsigned linear = !graphics_->GetHardwareDepthSupport() && i < DLPS_ORTHO ? 1 : 0;
  890. if (i & DLPS_SHADOW)
  891. lightPS_[i] = GetPixelShader("Light_" + linearVariations[linear] + lightPSVariations[i] + hwVariations[hwShadows]);
  892. else
  893. lightPS_[i] = GetPixelShader("Light_" + linearVariations[linear] + lightPSVariations[i]);
  894. }
  895. }
  896. // Remove shaders that are no longer referenced from the cache
  897. cache_->ReleaseResources(Shader::GetTypeStatic());
  898. shadersDirty_ = false;
  899. }
  900. void Renderer::LoadMaterialShaders(Technique* technique)
  901. {
  902. LoadPassShaders(technique, PASS_SHADOW);
  903. LoadPassShaders(technique, PASS_EXTRA);
  904. RenderMode mode = graphics_->GetRenderMode();
  905. if (mode == RENDER_FORWARD)
  906. {
  907. LoadPassShaders(technique, PASS_BASE);
  908. LoadPassShaders(technique, PASS_LITBASE);
  909. LoadPassShaders(technique, PASS_LIGHT);
  910. }
  911. else
  912. {
  913. if (technique->HasPass(PASS_GBUFFER))
  914. LoadPassShaders(technique, PASS_GBUFFER);
  915. else
  916. {
  917. LoadPassShaders(technique, PASS_BASE);
  918. // If shadow maps are not reused, forward lighting in deferred mode can render shadows
  919. LoadPassShaders(technique, PASS_LITBASE, !reuseShadowMaps_);
  920. LoadPassShaders(technique, PASS_LIGHT, !reuseShadowMaps_);
  921. }
  922. }
  923. }
  924. void Renderer::LoadPassShaders(Technique* technique, PassType type, bool allowShadows)
  925. {
  926. Pass* pass = technique->GetPass(type);
  927. if (!pass)
  928. return;
  929. String vertexShaderName = pass->GetVertexShaderName();
  930. String pixelShaderName = pass->GetPixelShaderName();
  931. // Check if the shader name is already a variation in itself
  932. if (vertexShaderName.Find('_') == String::NPOS)
  933. vertexShaderName += "_";
  934. if (pixelShaderName.Find('_') == String::NPOS)
  935. pixelShaderName += "_";
  936. // If INTZ depth is used, do not write depth into a rendertarget in the G-buffer pass
  937. if (type == PASS_GBUFFER)
  938. {
  939. unsigned depth = graphics_->GetHardwareDepthSupport() ? 0 : 1;
  940. pixelShaderName += depthVariations[depth];
  941. }
  942. unsigned hwShadows = graphics_->GetHardwareShadowSupport() ? 1 : 0;
  943. Vector<SharedPtr<ShaderVariation> >& vertexShaders = pass->GetVertexShaders();
  944. Vector<SharedPtr<ShaderVariation> >& pixelShaders = pass->GetPixelShaders();
  945. // Forget all the old shaders
  946. vertexShaders.Clear();
  947. pixelShaders.Clear();
  948. if (type == PASS_LIGHT || type == PASS_LITBASE)
  949. {
  950. // If ambient pass is transparent, and shadow maps are reused, do not load shadow variations
  951. if (reuseShadowMaps_)
  952. {
  953. if (!technique->HasPass(PASS_BASE) || technique->GetPass(PASS_BASE)->GetBlendMode() != BLEND_REPLACE)
  954. allowShadows = false;
  955. }
  956. vertexShaders.Resize(MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS);
  957. pixelShaders.Resize(MAX_LIGHT_PS_VARIATIONS);
  958. for (unsigned j = 0; j < MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS; ++j)
  959. {
  960. unsigned g = j / MAX_LIGHT_VS_VARIATIONS;
  961. unsigned l = j % MAX_LIGHT_VS_VARIATIONS;
  962. if (!(l & LVS_SHADOW) || allowShadows)
  963. vertexShaders[j] = GetVertexShader(vertexShaderName + lightVSVariations[l] + geometryVSVariations[g], g != 0);
  964. else
  965. vertexShaders[j].Reset();
  966. }
  967. for (unsigned j = 0; j < MAX_LIGHT_PS_VARIATIONS; ++j)
  968. {
  969. if (j & LPS_SHADOW)
  970. {
  971. if (allowShadows)
  972. pixelShaders[j] = GetPixelShader(pixelShaderName + lightPSVariations[j] + hwVariations[hwShadows]);
  973. else
  974. pixelShaders[j].Reset();
  975. }
  976. else
  977. pixelShaders[j] = GetPixelShader(pixelShaderName + lightPSVariations[j]);
  978. }
  979. }
  980. else
  981. {
  982. vertexShaders.Resize(MAX_GEOMETRYTYPES);
  983. pixelShaders.Resize(1);
  984. for (unsigned j = 0; j < MAX_GEOMETRYTYPES; ++j)
  985. vertexShaders[j] = GetVertexShader(vertexShaderName + geometryVSVariations[j], j != 0);
  986. pixelShaders[0] = GetPixelShader(pixelShaderName);
  987. }
  988. technique->MarkShadersLoaded(shadersChangedFrameNumber_);
  989. }
  990. void Renderer::ReleaseMaterialShaders()
  991. {
  992. PODVector<Material*> materials;
  993. cache_->GetResources<Material>(materials);
  994. for (unsigned i = 0; i < materials.Size(); ++i)
  995. materials[i]->ReleaseShaders();
  996. }
  997. void Renderer::ReloadTextures()
  998. {
  999. PODVector<Resource*> textures;
  1000. cache_->GetResources(textures, Texture2D::GetTypeStatic());
  1001. for (unsigned i = 0; i < textures.Size(); ++i)
  1002. cache_->ReloadResource(textures[i]);
  1003. cache_->GetResources(textures, TextureCube::GetTypeStatic());
  1004. for (unsigned i = 0; i < textures.Size(); ++i)
  1005. cache_->ReloadResource(textures[i]);
  1006. }
  1007. void Renderer::CreateGeometries()
  1008. {
  1009. SharedPtr<VertexBuffer> dlvb(new VertexBuffer(context_));
  1010. dlvb->SetSize(4, MASK_POSITION);
  1011. dlvb->SetData(dirLightVertexData);
  1012. SharedPtr<IndexBuffer> dlib(new IndexBuffer(context_));
  1013. dlib->SetSize(6, false);
  1014. dlib->SetData(dirLightIndexData);
  1015. dirLightGeometry_ = new Geometry(context_);
  1016. dirLightGeometry_->SetVertexBuffer(0, dlvb);
  1017. dirLightGeometry_->SetIndexBuffer(dlib);
  1018. dirLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, dlib->GetIndexCount());
  1019. SharedPtr<VertexBuffer> plvb(new VertexBuffer(context_));
  1020. plvb->SetSize(24, MASK_POSITION);
  1021. plvb->SetData(pointLightVertexData);
  1022. SharedPtr<IndexBuffer> plib(new IndexBuffer(context_));
  1023. plib->SetSize(132, false);
  1024. plib->SetData(pointLightIndexData);
  1025. pointLightGeometry_ = new Geometry(context_);
  1026. pointLightGeometry_->SetVertexBuffer(0, plvb);
  1027. pointLightGeometry_->SetIndexBuffer(plib);
  1028. pointLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, plib->GetIndexCount());
  1029. SharedPtr<VertexBuffer> slvb(new VertexBuffer(context_));
  1030. slvb->SetSize(8, MASK_POSITION);
  1031. slvb->SetData(spotLightVertexData);
  1032. SharedPtr<IndexBuffer> slib(new IndexBuffer(context_));
  1033. slib->SetSize(36, false);
  1034. slib->SetData(spotLightIndexData);
  1035. spotLightGeometry_ = new Geometry(context_);
  1036. spotLightGeometry_->SetVertexBuffer(0, slvb);
  1037. spotLightGeometry_->SetIndexBuffer(slib);
  1038. spotLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, slib->GetIndexCount());
  1039. }
  1040. void Renderer::CreateInstancingBuffer()
  1041. {
  1042. // Do not create buffer if instancing not supported
  1043. if (!graphics_->GetSM3Support())
  1044. {
  1045. dynamicInstancing_ = false;
  1046. return;
  1047. }
  1048. // If must lock the buffer for each batch group, set a smaller size
  1049. unsigned defaultSize = graphics_->GetStreamOffsetSupport() ? INSTANCING_BUFFER_DEFAULT_SIZE : INSTANCING_BUFFER_DEFAULT_SIZE / 4;
  1050. instancingBuffer_ = new VertexBuffer(context_);
  1051. if (!instancingBuffer_->SetSize(defaultSize, INSTANCING_BUFFER_MASK, true))
  1052. {
  1053. instancingBuffer_.Reset();
  1054. dynamicInstancing_ = false;
  1055. }
  1056. }
  1057. bool Renderer::ResizeInstancingBuffer(unsigned numInstances)
  1058. {
  1059. if (!instancingBuffer_)
  1060. return false;
  1061. unsigned oldSize = instancingBuffer_->GetVertexCount();
  1062. if (numInstances <= oldSize)
  1063. return true;
  1064. unsigned newSize = INSTANCING_BUFFER_DEFAULT_SIZE;
  1065. while (newSize < numInstances)
  1066. newSize <<= 1;
  1067. if (!instancingBuffer_->SetSize(newSize, INSTANCING_BUFFER_MASK, true))
  1068. {
  1069. LOGERROR("Failed to resize instancing buffer to " + String(newSize));
  1070. // If failed, try to restore the old size
  1071. instancingBuffer_->SetSize(oldSize, INSTANCING_BUFFER_MASK, true);
  1072. return false;
  1073. }
  1074. LOGDEBUG("Resized instancing buffer to " + String(newSize));
  1075. return true;
  1076. }
  1077. bool Renderer::CreateShadowMaps()
  1078. {
  1079. unsigned shadowMapFormat = shadowMapHiresDepth_ ? graphics_->GetHiresShadowMapFormat() : graphics_->GetShadowMapFormat();
  1080. unsigned dummyColorFormat = graphics_->GetDummyColorFormat();
  1081. bool hardwarePCF = graphics_->GetHardwareShadowSupport();
  1082. if (!shadowMapFormat)
  1083. return false;
  1084. if (!drawShadows_)
  1085. {
  1086. for (unsigned i = 0; i < NUM_SHADOWMAP_RESOLUTIONS; ++i)
  1087. {
  1088. for (unsigned j = 0; j < shadowMaps_[i].Size(); ++j)
  1089. shadowMaps_[i][j].Reset();
  1090. }
  1091. return true;
  1092. }
  1093. #ifdef USE_OPENGL
  1094. // Create shadow maps only. Color rendertargets are not needed
  1095. unsigned size = shadowMapSize_;
  1096. for (unsigned i = 0; i < NUM_SHADOWMAP_RESOLUTIONS; ++i)
  1097. {
  1098. for (unsigned j = 0; j < shadowMaps_[i].Size(); ++j)
  1099. {
  1100. if (!shadowMaps_[i][j])
  1101. shadowMaps_[i][j] = new Texture2D(context_);
  1102. if (!shadowMaps_[i][j]->SetSize(size, size, shadowMapFormat, TEXTURE_DEPTHSTENCIL))
  1103. return false;
  1104. shadowMaps_[i][j]->SetFilterMode(FILTER_BILINEAR);
  1105. shadowMaps_[i][j]->SetShadowCompare(true);
  1106. }
  1107. size >>= 1;
  1108. }
  1109. #else
  1110. // Create shadow maps and dummy color rendertargets
  1111. unsigned size = shadowMapSize_;
  1112. for (unsigned i = 0; i < NUM_SHADOWMAP_RESOLUTIONS; ++i)
  1113. {
  1114. if (!colorShadowMaps_[i])
  1115. colorShadowMaps_[i] = new Texture2D(context_);
  1116. if (!colorShadowMaps_[i]->SetSize(size, size, dummyColorFormat, TEXTURE_RENDERTARGET))
  1117. return false;
  1118. for (unsigned j = 0; j < shadowMaps_[i].Size(); ++j)
  1119. {
  1120. if (!shadowMaps_[i][j])
  1121. shadowMaps_[i][j] = new Texture2D(context_);
  1122. if (!shadowMaps_[i][j]->SetSize(size, size, shadowMapFormat, TEXTURE_DEPTHSTENCIL))
  1123. return false;
  1124. shadowMaps_[i][j]->SetFilterMode(hardwarePCF ? FILTER_BILINEAR : FILTER_NEAREST);
  1125. // Link the color rendertarget to depth rendertarget
  1126. shadowMaps_[i][j]->GetRenderSurface()->SetLinkedRenderTarget(colorShadowMaps_[i]->GetRenderSurface());
  1127. }
  1128. size >>= 1;
  1129. }
  1130. #endif
  1131. return true;
  1132. }
  1133. Camera* Renderer::CreateShadowCamera()
  1134. {
  1135. if (numShadowCameras_ >= shadowCameraStore_.Size())
  1136. shadowCameraStore_.Push(SharedPtr<Camera>(new Camera(context_)));
  1137. Camera* camera = shadowCameraStore_[numShadowCameras_];
  1138. camera->SetNode(CreateTempNode());
  1139. ++numShadowCameras_;
  1140. return camera;
  1141. }
  1142. Light* Renderer::CreateSplitLight(Light* original)
  1143. {
  1144. if (numSplitLights_ >= splitLightStore_.Size())
  1145. splitLightStore_.Push(SharedPtr<Light>(new Light(context_)));
  1146. Light* light = splitLightStore_[numSplitLights_];
  1147. light->SetNode(CreateTempNode());
  1148. light->CopyFrom(original);
  1149. ++numSplitLights_;
  1150. return light;
  1151. }
  1152. Node* Renderer::CreateTempNode()
  1153. {
  1154. if (numTempNodes_ >= tempNodeStore_.Size())
  1155. tempNodeStore_.Push(SharedPtr<Node>(new Node(context_)));
  1156. Node* node = tempNodeStore_[numTempNodes_];
  1157. ++numTempNodes_;
  1158. return node;
  1159. }
  1160. void Renderer::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  1161. {
  1162. if (!initialized_)
  1163. Initialize();
  1164. else
  1165. {
  1166. // When screen mode changes, reload shaders and purge old views and occlusion buffers
  1167. shadersDirty_ = true;
  1168. occlusionBuffers_.Clear();
  1169. ResetViews();
  1170. }
  1171. }
  1172. void Renderer::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  1173. {
  1174. if (initialized_)
  1175. {
  1176. using namespace RenderUpdate;
  1177. Update(eventData[P_TIMESTEP].GetFloat());
  1178. }
  1179. }