Renderer.cpp 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477
  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 "PixelShader.h"
  39. #include "Profiler.h"
  40. #include "Renderer.h"
  41. #include "ResourceCache.h"
  42. #include "Scene.h"
  43. #include "Technique.h"
  44. #include "Texture2D.h"
  45. #include "TextureCube.h"
  46. #include "VertexBuffer.h"
  47. #include "VertexShader.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. "HW"
  169. };
  170. static const String geometryVSVariations[] =
  171. {
  172. "",
  173. "Skinned",
  174. "Instanced",
  175. "Billboard"
  176. };
  177. static const String lightVSVariations[] =
  178. {
  179. "",
  180. "Spot",
  181. "Shadow",
  182. "SpotShadow"
  183. };
  184. static const String deferredLightVSVariations[] =
  185. {
  186. "",
  187. "Dir",
  188. "Ortho",
  189. "OrthoDir"
  190. };
  191. static const String lightPSVariations[] =
  192. {
  193. "Dir",
  194. "DirSpec",
  195. "DirShadow",
  196. "DirShadowSpec",
  197. "Spot",
  198. "SpotSpec",
  199. "SpotShadow",
  200. "SpotShadowSpec",
  201. "Point",
  202. "PointSpec",
  203. "PointShadow",
  204. "PointShadowSpec",
  205. "PointMask",
  206. "PointMaskSpec",
  207. "PointMaskShadow",
  208. "PointMaskShadowSpec",
  209. "OrthoDir",
  210. "OrthoDirSpec",
  211. "OrthoDirShadow",
  212. "OrthoDirShadowSpec",
  213. "OrthoSpot",
  214. "OrthoSpotSpec",
  215. "OrthoSpotShadow",
  216. "OrthoSpotShadowSpec",
  217. "OrthoPoint",
  218. "OrthoPointSpec",
  219. "OrthoPointShadow",
  220. "OrthoPointShadowSpec",
  221. "OrthoPointMask",
  222. "OrthoPointMaskSpec",
  223. "OrthoPointMaskShadow",
  224. "OrthoPointMaskShadowSpec",
  225. "LinearDir",
  226. "LinearDirSpec",
  227. "LinearDirShadow",
  228. "LinearDirShadowSpec",
  229. "LinearSpot",
  230. "LinearSpotSpec",
  231. "LinearSpotShadow",
  232. "LinearSpotShadowSpec",
  233. "LinearPoint",
  234. "LinearPointSpec",
  235. "LinearPointShadow",
  236. "LinearPointShadowSpec",
  237. "LinearPointMask",
  238. "LinearPointMaskSpec",
  239. "LinearPointMaskShadow",
  240. "LinearPointMaskShadowSpec"
  241. };
  242. static const unsigned INSTANCING_BUFFER_MASK = MASK_INSTANCEMATRIX1 | MASK_INSTANCEMATRIX2 | MASK_INSTANCEMATRIX3;
  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. numSplitLights_(0),
  251. numTempNodes_(0),
  252. specularLighting_(true),
  253. drawShadows_(true),
  254. textureAnisotropy_(4),
  255. textureFilterMode_(FILTER_TRILINEAR),
  256. textureQuality_(QUALITY_HIGH),
  257. materialQuality_(QUALITY_HIGH),
  258. shadowMapSize_(1024),
  259. shadowMapHiresDepth_(false),
  260. reuseShadowMaps_(true),
  261. dynamicInstancing_(true),
  262. maxOccluderTriangles_(5000),
  263. occlusionBufferSize_(256),
  264. occluderSizeThreshold_(0.1f),
  265. shadersChangedFrameNumber_(M_MAX_UNSIGNED),
  266. shadersDirty_(true),
  267. initialized_(false)
  268. {
  269. SubscribeToEvent(E_SCREENMODE, HANDLER(Renderer, HandleScreenMode));
  270. SubscribeToEvent(E_RENDERUPDATE, HANDLER(Renderer, HandleRenderUpdate));
  271. // Default to one of each shadow map resolution
  272. for (unsigned i = 0; i < NUM_SHADOWMAP_RESOLUTIONS; ++i)
  273. shadowMaps_[i].Resize(1);
  274. // Try to initialize right now, but skip if screen mode is not yet set
  275. Initialize();
  276. }
  277. Renderer::~Renderer()
  278. {
  279. }
  280. void Renderer::SetNumViewports(unsigned num)
  281. {
  282. viewports_.Resize(num);
  283. }
  284. void Renderer::SetViewport(unsigned index, const Viewport& viewport)
  285. {
  286. if (index >= viewports_.Size())
  287. {
  288. LOGERROR("Viewport index out of bounds");
  289. return;
  290. }
  291. viewports_[index] = viewport;
  292. }
  293. void Renderer::SetSpecularLighting(bool enable)
  294. {
  295. specularLighting_ = enable;
  296. }
  297. void Renderer::SetDrawShadows(bool enable)
  298. {
  299. if (!graphics_)
  300. return;
  301. drawShadows_ = enable;
  302. if (!CreateShadowMaps())
  303. drawShadows_ = false;
  304. }
  305. void Renderer::SetTextureAnisotropy(int level)
  306. {
  307. textureAnisotropy_ = Max(level, 1);
  308. }
  309. void Renderer::SetTextureFilterMode(TextureFilterMode mode)
  310. {
  311. textureFilterMode_ = mode;
  312. }
  313. void Renderer::SetTextureQuality(int quality)
  314. {
  315. quality = Clamp(quality, QUALITY_LOW, QUALITY_HIGH);
  316. if (quality != textureQuality_)
  317. {
  318. textureQuality_ = quality;
  319. ReloadTextures();
  320. }
  321. }
  322. void Renderer::SetMaterialQuality(int quality)
  323. {
  324. materialQuality_ = Clamp(quality, QUALITY_LOW, QUALITY_MAX);
  325. shadersDirty_ = true;
  326. ResetViews();
  327. }
  328. void Renderer::SetShadowMapSize(int size)
  329. {
  330. if (!graphics_)
  331. return;
  332. shadowMapSize_ = Max(size, SHADOW_MIN_PIXELS);
  333. if (!CreateShadowMaps())
  334. {
  335. shadowMapSize_ = 1024;
  336. if (!CreateShadowMaps())
  337. drawShadows_ = false;
  338. }
  339. }
  340. void Renderer::SetShadowMapHiresDepth(bool enable)
  341. {
  342. if (!graphics_)
  343. return;
  344. if (!graphics_->GetHiresShadowSupport())
  345. enable = false;
  346. shadowMapHiresDepth_ = enable;
  347. if (!CreateShadowMaps())
  348. drawShadows_ = false;
  349. }
  350. void Renderer::SetReuseShadowMaps(bool enable)
  351. {
  352. if (enable == reuseShadowMaps_)
  353. return;
  354. reuseShadowMaps_ = enable;
  355. if (reuseShadowMaps_)
  356. {
  357. for (unsigned i = 0; i < NUM_SHADOWMAP_RESOLUTIONS; ++i)
  358. shadowMaps_[i].Resize(1);
  359. }
  360. if (!CreateShadowMaps())
  361. drawShadows_ = false;
  362. shadersDirty_ = true;
  363. }
  364. void Renderer::SetNumShadowMaps(unsigned full, unsigned half, unsigned quarter)
  365. {
  366. shadowMaps_[0].Resize(full ? full : 1);
  367. shadowMaps_[1].Resize(half ? half : 1);
  368. shadowMaps_[2].Resize(quarter ? quarter : 1);
  369. if (!CreateShadowMaps())
  370. drawShadows_ = false;
  371. }
  372. void Renderer::SetDynamicInstancing(bool enable)
  373. {
  374. if (!instancingBuffer_)
  375. enable = false;
  376. dynamicInstancing_ = enable;
  377. }
  378. void Renderer::SetMaxOccluderTriangles(int triangles)
  379. {
  380. maxOccluderTriangles_ = Max(triangles, 0);
  381. }
  382. void Renderer::SetOcclusionBufferSize(int size)
  383. {
  384. occlusionBufferSize_ = Max(size, 1);
  385. occlusionBuffers_.Clear();
  386. }
  387. void Renderer::SetOccluderSizeThreshold(float screenSize)
  388. {
  389. occluderSizeThreshold_ = Max(screenSize, 0.0f);
  390. }
  391. const Viewport& Renderer::GetViewport(unsigned index) const
  392. {
  393. return index < viewports_.Size() ? viewports_[index] : noViewport;
  394. }
  395. VertexShader* Renderer::GetVertexShader(const String& name, bool checkExists) const
  396. {
  397. // Check for extra underscore with no variations and remove
  398. String fullName = (shaderPath_ + name + vsFormat_).Replace("_.", ".");
  399. if (checkExists)
  400. {
  401. if (!cache_->Exists(fullName))
  402. return 0;
  403. }
  404. return cache_->GetResource<VertexShader>(fullName);
  405. }
  406. PixelShader* Renderer::GetPixelShader(const String& name, bool checkExists) const
  407. {
  408. // Check for extra underscore with no variations and remove
  409. String fullName = (shaderPath_ + name + psFormat_).Replace("_.", ".");
  410. if (checkExists)
  411. {
  412. if (!cache_->Exists(fullName))
  413. return 0;
  414. }
  415. return cache_->GetResource<PixelShader>(fullName);
  416. }
  417. unsigned Renderer::GetNumGeometries(bool allViews) const
  418. {
  419. unsigned numGeometries = 0;
  420. unsigned lastView = allViews ? numViews_ : 1;
  421. for (unsigned i = 0; i < lastView; ++i)
  422. numGeometries += views_[i]->GetGeometries().Size();
  423. return numGeometries;
  424. }
  425. unsigned Renderer::GetNumLights(bool allViews) const
  426. {
  427. unsigned nulights_ = 0;
  428. unsigned lastView = allViews ? numViews_ : 1;
  429. for (unsigned i = 0; i < lastView; ++i)
  430. nulights_ += views_[i]->GetLights().Size();
  431. return nulights_;
  432. }
  433. unsigned Renderer::GetNumShadowMaps(bool allViews) const
  434. {
  435. unsigned numShadowMaps = 0;
  436. unsigned lastView = allViews ? numViews_ : 1;
  437. for (unsigned i = 0; i < lastView; ++i)
  438. {
  439. const Vector<LightBatchQueue>& lightQueues = views_[i]->GetLightQueues();
  440. for (unsigned j = 0; j < lightQueues.Size(); ++j)
  441. {
  442. Light* light = lightQueues[j].light_;
  443. if ((light) && (light->GetShadowMap()))
  444. ++numShadowMaps;
  445. }
  446. }
  447. return numShadowMaps;
  448. }
  449. unsigned Renderer::GetNumOccluders(bool allViews) const
  450. {
  451. unsigned numOccluders = 0;
  452. unsigned lastView = allViews ? numViews_ : 1;
  453. for (unsigned i = 0; i < lastView; ++i)
  454. numOccluders += views_[i]->GetOccluders().Size();
  455. return numOccluders;
  456. }
  457. unsigned Renderer::GetNumShadowOccluders(bool allViews) const
  458. {
  459. unsigned numShadowOccluders = 0;
  460. unsigned lastView = allViews ? numViews_ : 1;
  461. for (unsigned i = 0; i < lastView; ++i)
  462. numShadowOccluders += views_[i]->GetShadowOccluders().Size();
  463. return numShadowOccluders;
  464. }
  465. const OcclusionBuffer* Renderer::GetOcclusionBuffer(float aspectRatio, bool halfResolution)
  466. {
  467. // Return an occlusion buffer for debug output purposes. Do not allocate new
  468. int width = occlusionBufferSize_;
  469. int height = (int)(occlusionBufferSize_ / aspectRatio);
  470. if (halfResolution)
  471. {
  472. width >>= 1;
  473. height >>= 1;
  474. }
  475. int searchKey = (width << 12) | height;
  476. Map<int, SharedPtr<OcclusionBuffer> >::Iterator i = occlusionBuffers_.Find(searchKey);
  477. if (i != occlusionBuffers_.End())
  478. return i->second_;
  479. else
  480. return 0;
  481. }
  482. void Renderer::Update(float timeStep)
  483. {
  484. PROFILE(UpdateViewports);
  485. numViews_ = 0;
  486. // If device lost, do not perform update. This is because any dynamic vertex/index buffer updates happen already here,
  487. // and if the device is lost, the updates queue up, causing memory use to rise constantly
  488. if ((!graphics_) || (graphics_->IsDeviceLost()))
  489. return;
  490. // Advance frame number & time, set up the frameinfo structure, and reset views & stats
  491. frame_.frameNumber_ = GetSubsystem<Time>()->GetFrameNumber();
  492. frame_.timeStep_ = timeStep;
  493. frame_.camera_ = 0;
  494. numShadowCameras_ = 0;
  495. numSplitLights_ = 0;
  496. numTempNodes_ = 0;
  497. updateOctrees_.Clear();
  498. // Reload shaders if needed
  499. if (shadersDirty_)
  500. LoadShaders();
  501. // Process all viewports. Use reverse order, because during rendering the order will be reversed again to handle auxiliary
  502. // view dependencies correctly
  503. for (unsigned i = viewports_.Size() - 1; i < viewports_.Size(); --i)
  504. {
  505. unsigned mainView = numViews_;
  506. Viewport& viewport = viewports_[i];
  507. if (!AddView(0, viewport))
  508. continue;
  509. // Update octree (perform early update for nodes which need that, and reinsert moved nodes.)
  510. // However, if the same scene is viewed from multiple cameras, update the octree only once
  511. Octree* octree = viewport.scene_->GetComponent<Octree>();
  512. DebugRenderer* debug = viewport.scene_->GetComponent<DebugRenderer>();
  513. if (updateOctrees_.Find(octree) == updateOctrees_.End())
  514. {
  515. frame_.camera_ = viewport.camera_;
  516. frame_.viewSize_ = IntVector2(viewport.rect_.right_ - viewport.rect_.left_, viewport.rect_.bottom_ - viewport.rect_.top_);
  517. if (frame_.viewSize_ == IntVector2::ZERO)
  518. frame_.viewSize_ = IntVector2(graphics_->GetWidth(), graphics_->GetHeight());
  519. octree->Update(frame_);
  520. updateOctrees_.Insert(octree);
  521. // Set also the view for the debug graphics already here, so that it can use culling
  522. /// \todo May result in incorrect debug geometry culling if the same scene is drawn from multiple viewports
  523. if (debug)
  524. debug->SetView(viewport.camera_);
  525. }
  526. // Update the viewport's main view and any auxiliary views it Creates
  527. for (unsigned i = mainView; i < numViews_; ++i)
  528. views_[i]->Update(frame_);
  529. }
  530. return;
  531. }
  532. void Renderer::Render()
  533. {
  534. if (!graphics_)
  535. return;
  536. PROFILE(RenderViewports);
  537. graphics_->SetDefaultTextureFilterMode(textureFilterMode_);
  538. graphics_->SetTextureAnisotropy(textureAnisotropy_);
  539. // If no views, just clear the screen
  540. if (!numViews_)
  541. {
  542. numPrimitives_ = 0;
  543. numBatches_ = 0;
  544. graphics_->SetAlphaTest(false);
  545. graphics_->SetBlendMode(BLEND_REPLACE);
  546. graphics_->SetColorWrite(true);
  547. graphics_->SetDepthWrite(true);
  548. graphics_->SetFillMode(FILL_SOLID);
  549. graphics_->SetScissorTest(false);
  550. graphics_->SetStencilTest(false);
  551. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH | CLEAR_STENCIL);
  552. return;
  553. }
  554. // Render views from last to first (each main view is rendered after the auxiliary views it depends on)
  555. for (unsigned i = numViews_ - 1; i < numViews_; --i)
  556. views_[i]->Render();
  557. // Disable scissor/stencil tests if left on by lights, and reset stream frequencies
  558. graphics_->SetScissorTest(false);
  559. graphics_->SetStencilTest(false);
  560. graphics_->ResetStreamFrequencies();
  561. // Copy the number of batches & primitives from Graphics so that we can account for 3D geometry only
  562. numPrimitives_ = graphics_->GetNumPrimitives();
  563. numBatches_ = graphics_->GetNumBatches();
  564. }
  565. void Renderer::DrawDebugGeometry(bool depthTest)
  566. {
  567. PROFILE(RendererDrawDebug);
  568. /// \todo Because debug geometry is per-scene, if two cameras show views of the same area, occlusion is not shown correctly
  569. Set<Drawable*> processedGeometries;
  570. Set<Light*> processedLights;
  571. for (unsigned i = 0; i < numViews_; ++i)
  572. {
  573. // Make sure it's a main view, and process each node only once
  574. View* view = views_[i];
  575. if (view->GetRenderTarget())
  576. continue;
  577. Octree* octree = view->GetOctree();
  578. if (!octree)
  579. continue;
  580. Scene* scene = static_cast<Scene*>(octree->GetNode());
  581. if (!scene)
  582. continue;
  583. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  584. if (!debug)
  585. continue;
  586. const PODVector<Drawable*>& geometries = view->GetGeometries();
  587. const PODVector<Light*>& lights = view->GetLights();
  588. for (unsigned i = 0; i < geometries.Size(); ++i)
  589. {
  590. if (processedGeometries.Find(geometries[i]) == processedGeometries.End())
  591. {
  592. geometries[i]->DrawDebugGeometry(debug, depthTest);
  593. processedGeometries.Insert(geometries[i]);
  594. }
  595. }
  596. for (unsigned i = 0; i < lights.Size(); ++i)
  597. {
  598. if (processedLights.Find(lights[i]) == processedLights.End())
  599. {
  600. lights[i]->DrawDebugGeometry(debug, depthTest);
  601. processedLights.Insert(lights[i]);
  602. }
  603. }
  604. }
  605. }
  606. void Renderer::Initialize()
  607. {
  608. Graphics* graphics = GetSubsystem<Graphics>();
  609. ResourceCache* cache = GetSubsystem<ResourceCache>();
  610. if ((!graphics) || (!graphics->IsInitialized()) || (!cache))
  611. return;
  612. PROFILE(InitRenderer);
  613. graphics_ = graphics;
  614. cache_ = cache;
  615. // Check shader model support
  616. if (graphics_->GetSM3Support())
  617. {
  618. shaderPath_ = "Shaders/SM3/";
  619. vsFormat_ = ".vs3";
  620. psFormat_ = ".ps3";
  621. }
  622. else
  623. {
  624. shaderPath_ = "Shaders/SM2/";
  625. vsFormat_ = ".vs2";
  626. psFormat_ = ".ps2";
  627. }
  628. defaultLightRamp_ = cache->GetResource<Texture2D>("Textures/Ramp.png");
  629. defaultLightSpot = cache->GetResource<Texture2D>("Textures/Spot.png");
  630. defaultMaterial_ = cache->GetResource<Material>("Materials/Default.xml");
  631. CreateGeometries();
  632. CreateInstancingBuffer();
  633. if (!CreateShadowMaps())
  634. drawShadows_ = false;
  635. viewports_.Resize(1);
  636. ResetViews();
  637. LOGINFO("Initialized renderer");
  638. initialized_ = true;
  639. }
  640. void Renderer::ResetViews()
  641. {
  642. views_.Clear();
  643. numViews_ = 0;
  644. }
  645. bool Renderer::AddView(RenderSurface* renderTarget, const Viewport& viewport)
  646. {
  647. // If using a render target texture, make sure it will not be rendered to multiple times
  648. if (renderTarget)
  649. {
  650. for (unsigned i = 0; i < numViews_; ++i)
  651. {
  652. if (views_[i]->GetRenderTarget() == renderTarget)
  653. return false;
  654. }
  655. }
  656. if (views_.Size() <= numViews_)
  657. views_.Resize(numViews_ + 1);
  658. if (!views_[numViews_])
  659. views_[numViews_] = new View(context_);
  660. if (views_[numViews_]->Define(renderTarget, viewport))
  661. {
  662. ++numViews_;
  663. return true;
  664. }
  665. else
  666. return false;
  667. }
  668. OcclusionBuffer* Renderer::GetOrCreateOcclusionBuffer(Camera* camera, int maxOccluderTriangles, bool halfResolution)
  669. {
  670. // Get an occlusion buffer matching the aspect ratio. If not found, allocate new
  671. int width = occlusionBufferSize_;
  672. int height = (int)(occlusionBufferSize_ / camera->GetAspectRatio());
  673. if (halfResolution)
  674. {
  675. width >>= 1;
  676. height >>= 1;
  677. }
  678. int searchKey = (width << 12) | height;
  679. SharedPtr<OcclusionBuffer> buffer;
  680. Map<int, SharedPtr<OcclusionBuffer> >::Iterator i = occlusionBuffers_.Find(searchKey);
  681. if (i != occlusionBuffers_.End())
  682. buffer = i->second_;
  683. else
  684. {
  685. buffer = new OcclusionBuffer(context_);
  686. buffer->SetSize(width, height);
  687. occlusionBuffers_[searchKey] = buffer;
  688. }
  689. buffer->SetView(camera);
  690. buffer->SetMaxTriangles(maxOccluderTriangles);
  691. buffer->Clear();
  692. return buffer;
  693. }
  694. Geometry* Renderer::GetLightGeometry(Light* light)
  695. {
  696. switch (light->GetLightType())
  697. {
  698. case LIGHT_POINT:
  699. return pointLightGeometry_;
  700. case LIGHT_SPOT:
  701. case LIGHT_SPLITPOINT:
  702. return spotLightGeometry_;
  703. default:
  704. return dirLightGeometry_;
  705. }
  706. }
  707. Texture2D* Renderer::GetShadowMap(float resolution)
  708. {
  709. unsigned index = 0;
  710. if (resolution < 0.75f)
  711. index = (resolution >= 0.375f) ? 1 : 2;
  712. if (reuseShadowMaps_)
  713. return shadowMaps_[index][0];
  714. else
  715. {
  716. // If higher resolution shadow maps already used up, fall back to lower resolutions
  717. while (index < NUM_SHADOWMAP_RESOLUTIONS)
  718. {
  719. if (shadowMapUseCount_[index] < shadowMaps_[index].Size())
  720. return shadowMaps_[index][shadowMapUseCount_[index]++];
  721. ++index;
  722. }
  723. return 0;
  724. }
  725. }
  726. void Renderer::ResetShadowMapUseCount()
  727. {
  728. for (unsigned i = 0; i < NUM_SHADOWMAP_RESOLUTIONS; ++i)
  729. shadowMapUseCount_[i] = 0;
  730. }
  731. void Renderer::setBatchShaders(Batch& batch, Technique* technique, Pass* pass, bool allowShadows)
  732. {
  733. batch.pass_ = pass;
  734. // Check if shaders are unloaded or need reloading
  735. Vector<SharedPtr<VertexShader> >& vertexShaders = pass->GetVertexShaders();
  736. Vector<SharedPtr<PixelShader> >& pixelShaders = pass->GetPixelShaders();
  737. if ((!vertexShaders.Size()) || (!pixelShaders.Size()) || (technique->GetShadersLoadedFrameNumber() !=
  738. shadersChangedFrameNumber_))
  739. {
  740. // First release all previous shaders, then load
  741. technique->ReleaseShaders();
  742. LoadMaterialShaders(technique);
  743. }
  744. // Make sure shaders are loaded now
  745. if ((vertexShaders.Size()) && (pixelShaders.Size()))
  746. {
  747. // Check whether is a forward lit pass. If not, there is only one pixel shader
  748. PassType type = pass->GetType();
  749. if ((type != PASS_LITBASE) && (type != PASS_LIGHT))
  750. {
  751. unsigned vsi = batch.geometryType_;
  752. batch.vertexShader_ = vertexShaders[vsi];
  753. batch.pixelShader_ = pixelShaders[0];
  754. batch.vertexShaderIndex_ = vsi;
  755. }
  756. else
  757. {
  758. Light* light = batch.light_;
  759. if (!light)
  760. {
  761. // Do not log error, as it would result in a lot of spam
  762. batch.vertexShader_ = 0;
  763. batch.pixelShader_ = 0;
  764. return;
  765. }
  766. unsigned vsi = 0;
  767. unsigned psi = 0;
  768. vsi = batch.geometryType_ * MAX_LIGHT_VS_VARIATIONS;
  769. if ((specularLighting_) && (light->GetSpecularIntensity() > 0.0f))
  770. psi += LPS_SPEC;
  771. if ((allowShadows) && (light->GetShadowMap()))
  772. {
  773. vsi += LVS_SHADOW;
  774. psi += LPS_SHADOW;
  775. }
  776. switch (light->GetLightType())
  777. {
  778. case LIGHT_POINT:
  779. case LIGHT_SPLITPOINT:
  780. if (light->GetShapeTexture())
  781. psi += LPS_POINTMASK;
  782. else
  783. psi += LPS_POINT;
  784. break;
  785. case LIGHT_SPOT:
  786. psi += LPS_SPOT;
  787. vsi += LVS_SPOT;
  788. break;
  789. }
  790. batch.vertexShader_ = vertexShaders[vsi];
  791. batch.pixelShader_ = pixelShaders[psi];
  792. batch.vertexShaderIndex_ = vsi;
  793. }
  794. }
  795. batch.CalculateSortKey();
  796. // Log error if shaders could not be assigned, but only once per technique
  797. if ((!batch.vertexShader_) || (!batch.pixelShader_))
  798. {
  799. if (shaderErrorDisplayed_.Find(technique) == shaderErrorDisplayed_.End())
  800. {
  801. shaderErrorDisplayed_.Insert(technique);
  802. LOGERROR("Technique " + technique->GetName() + " has missing shaders");
  803. }
  804. }
  805. }
  806. void Renderer::SetLightVolumeShaders(Batch& batch)
  807. {
  808. unsigned vsi = DLVS_NONE;
  809. unsigned psi = DLPS_NONE;
  810. Light* light = batch.light_;
  811. switch(light->GetLightType())
  812. {
  813. case LIGHT_DIRECTIONAL:
  814. vsi += DLVS_DIR;
  815. break;
  816. case LIGHT_POINT:
  817. case LIGHT_SPLITPOINT:
  818. if (light->GetShapeTexture())
  819. psi += DLPS_POINTMASK;
  820. else
  821. psi += DLPS_POINT;
  822. break;
  823. case LIGHT_SPOT:
  824. psi += DLPS_SPOT;
  825. break;
  826. }
  827. if (light->GetShadowMap())
  828. psi += DLPS_SHADOW;
  829. if ((specularLighting_) && (light->GetSpecularIntensity() > 0.0))
  830. psi += DLPS_SPEC;
  831. if (batch.camera_->IsOrthographic())
  832. {
  833. vsi += DLVS_ORTHO;
  834. psi += DLPS_ORTHO;
  835. }
  836. unsigned hwShadows = graphics_->GetHardwareShadowSupport() ? 1 : 0;
  837. if (!lightVS_[vsi])
  838. lightVS_[vsi] = GetVertexShader(lightShaderName_ + deferredLightVSVariations[vsi]);
  839. if (!lightPS_[psi])
  840. {
  841. unsigned variation = psi % DLPS_SPOT;
  842. if ((variation == DLPS_SHADOW) || (variation == DLPS_SHADOWSPEC))
  843. lightPS_[psi] = GetPixelShader(lightShaderName_ + lightPSVariations[psi] + hwVariations[hwShadows]);
  844. else
  845. lightPS_[psi] = GetPixelShader(lightShaderName_ + lightPSVariations[psi]);
  846. }
  847. batch.material_ = 0;
  848. batch.pass_ = 0;
  849. batch.vertexShader_ = lightVS_[vsi];
  850. batch.pixelShader_ = lightPS_[psi];
  851. batch.vertexShaderIndex_ = vsi;
  852. batch.CalculateSortKey();
  853. }
  854. void Renderer::LoadShaders()
  855. {
  856. LOGINFO("Reloading shaders");
  857. // Release old material shaders, mark them for reload
  858. ReleaseMaterialShaders();
  859. shadersChangedFrameNumber_ = GetSubsystem<Time>()->GetFrameNumber();
  860. // Load inbuilt shaders
  861. stencilVS_ = GetVertexShader("Stencil");
  862. stencilPS_ = GetPixelShader("Stencil");
  863. lightVS_.Clear();
  864. lightPS_.Clear();
  865. RenderMode mode = graphics_->GetRenderMode();
  866. if (mode != RENDER_FORWARD)
  867. {
  868. // There are rather many light volume shader variations, so load them later on-demand
  869. lightVS_.Resize(MAX_DEFERRED_LIGHT_VS_VARIATIONS);
  870. lightPS_.Resize(MAX_DEFERRED_LIGHT_PS_VARIATIONS);
  871. if (mode == RENDER_DEFERRED)
  872. lightShaderName_ = "Deferred/Light_";
  873. else
  874. lightShaderName_ = "Prepass/Light_";
  875. }
  876. // Remove shaders that are no longer referenced from the cache
  877. cache_->ReleaseResources(VertexShader::GetTypeStatic());
  878. cache_->ReleaseResources(PixelShader::GetTypeStatic());
  879. shadersDirty_ = false;
  880. }
  881. void Renderer::LoadMaterialShaders(Technique* technique)
  882. {
  883. LoadPassShaders(technique, PASS_SHADOW);
  884. LoadPassShaders(technique, PASS_EXTRA);
  885. RenderMode mode = graphics_->GetRenderMode();
  886. if (mode == RENDER_FORWARD)
  887. {
  888. LoadPassShaders(technique, PASS_BASE);
  889. LoadPassShaders(technique, PASS_LITBASE);
  890. LoadPassShaders(technique, PASS_LIGHT);
  891. }
  892. else
  893. {
  894. // G-Buffer pass types depend on whether deferred shading or light prepass is in use
  895. if (mode == RENDER_DEFERRED)
  896. LoadPassShaders(technique, PASS_DEFERRED);
  897. else if (mode == RENDER_PREPASS)
  898. {
  899. LoadPassShaders(technique, PASS_PREPASS);
  900. LoadPassShaders(technique, PASS_MATERIAL);
  901. }
  902. else
  903. {
  904. LoadPassShaders(technique, PASS_BASE);
  905. // If shadow maps are not reused, transparencies can be rendered shadowed
  906. LoadPassShaders(technique, PASS_LITBASE, !reuseShadowMaps_);
  907. LoadPassShaders(technique, PASS_LIGHT, !reuseShadowMaps_);
  908. }
  909. }
  910. }
  911. void Renderer::LoadPassShaders(Technique* technique, PassType pass, bool allowShadows)
  912. {
  913. Map<PassType, Pass>::Iterator i = technique->passes_.Find(pass);
  914. if (i == technique->passes_.End())
  915. return;
  916. String vertexShaderName = i->second_.GetVertexShaderName();
  917. String pixelShaderName = i->second_.GetPixelShaderName();
  918. // Check if the shader name is already a variation in itself
  919. if (vertexShaderName.Find('_') == String::NPOS)
  920. vertexShaderName += "_";
  921. if (pixelShaderName.Find('_') == String::NPOS)
  922. pixelShaderName += "_";
  923. // If ambient pass is not using REPLACE as the blend mode, and shadow maps are reused, do not load shadow variations
  924. if ((reuseShadowMaps_) && ((pass == PASS_LIGHT) || (pass == PASS_LITBASE)))
  925. {
  926. if ((!technique->HasPass(PASS_BASE)) || (technique->GetPass(PASS_BASE)->GetBlendMode() != BLEND_REPLACE))
  927. allowShadows = false;
  928. }
  929. unsigned hwShadows = graphics_->GetHardwareShadowSupport() ? 1 : 0;
  930. Vector<SharedPtr<VertexShader> >& vertexShaders = i->second_.GetVertexShaders();
  931. Vector<SharedPtr<PixelShader> >& pixelShaders = i->second_.GetPixelShaders();
  932. // Forget all the old shaders
  933. vertexShaders.Clear();
  934. pixelShaders.Clear();
  935. switch (i->first_)
  936. {
  937. default:
  938. vertexShaders.Resize(MAX_GEOMETRYTYPES);
  939. pixelShaders.Resize(1);
  940. for (unsigned j = 0; j < MAX_GEOMETRYTYPES; ++j)
  941. vertexShaders[j] = GetVertexShader(vertexShaderName + geometryVSVariations[j], j != 0);
  942. pixelShaders[0] = GetPixelShader(pixelShaderName);
  943. break;
  944. case PASS_LITBASE:
  945. case PASS_LIGHT:
  946. {
  947. // In first light pass, load only directional light shaders
  948. unsigned numPS = i->first_ == PASS_LIGHT ? MAX_LIGHT_PS_VARIATIONS : LPS_SPOT;
  949. vertexShaders.Resize(MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS);
  950. pixelShaders.Resize(numPS);
  951. for (unsigned j = 0; j < MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS; ++j)
  952. {
  953. unsigned g = j / MAX_LIGHT_VS_VARIATIONS;
  954. unsigned l = j % MAX_LIGHT_VS_VARIATIONS;
  955. if ((!(l & LVS_SHADOW)) || (allowShadows))
  956. vertexShaders[j] = GetVertexShader(vertexShaderName + lightVSVariations[l] + geometryVSVariations[g], g != 0);
  957. else
  958. vertexShaders[j].Reset();
  959. }
  960. for (unsigned j = 0; j < numPS; ++j)
  961. {
  962. unsigned variation = j % LPS_SPOT;
  963. if ((variation == LPS_SHADOW) || (variation == LPS_SHADOWSPEC))
  964. {
  965. if (allowShadows)
  966. pixelShaders[j] = GetPixelShader(pixelShaderName + lightPSVariations[j] +
  967. hwVariations[hwShadows]);
  968. else
  969. pixelShaders[j].Reset();
  970. }
  971. else
  972. pixelShaders[j] = GetPixelShader(pixelShaderName + lightPSVariations[j]);
  973. }
  974. break;
  975. }
  976. }
  977. technique->MarkShadersLoaded(shadersChangedFrameNumber_);
  978. }
  979. void Renderer::ReleaseMaterialShaders()
  980. {
  981. Vector<Material*> materials;
  982. cache_->GetResources<Material>(materials);
  983. for (unsigned i = 0; i < materials.Size(); ++i)
  984. {
  985. for (unsigned j = 0; j < materials[i]->GetNumTechniques(); ++j)
  986. materials[i]->ReleaseShaders();
  987. }
  988. }
  989. void Renderer::ReloadTextures()
  990. {
  991. Vector<Resource*> textures;
  992. cache_->GetResources(textures, Texture2D::GetTypeStatic());
  993. for (unsigned i = 0; i < textures.Size(); ++i)
  994. cache_->ReloadResource(textures[i]);
  995. cache_->GetResources(textures, TextureCube::GetTypeStatic());
  996. for (unsigned i = 0; i < textures.Size(); ++i)
  997. cache_->ReloadResource(textures[i]);
  998. }
  999. void Renderer::CreateGeometries()
  1000. {
  1001. SharedPtr<VertexBuffer> dlvb(new VertexBuffer(context_));
  1002. dlvb->SetSize(4, MASK_POSITION);
  1003. dlvb->SetData(dirLightVertexData);
  1004. SharedPtr<IndexBuffer> dlib(new IndexBuffer(context_));
  1005. dlib->SetSize(6, false);
  1006. dlib->SetData(dirLightIndexData);
  1007. dirLightGeometry_ = new Geometry(context_);
  1008. dirLightGeometry_->SetVertexBuffer(0, dlvb);
  1009. dirLightGeometry_->SetIndexBuffer(dlib);
  1010. dirLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, dlib->GetIndexCount());
  1011. SharedPtr<VertexBuffer> plvb(new VertexBuffer(context_));
  1012. plvb->SetSize(24, MASK_POSITION);
  1013. plvb->SetData(pointLightVertexData);
  1014. SharedPtr<IndexBuffer> plib(new IndexBuffer(context_));
  1015. plib->SetSize(132, false);
  1016. plib->SetData(pointLightIndexData);
  1017. pointLightGeometry_ = new Geometry(context_);
  1018. pointLightGeometry_->SetVertexBuffer(0, plvb);
  1019. pointLightGeometry_->SetIndexBuffer(plib);
  1020. pointLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, plib->GetIndexCount());
  1021. SharedPtr<VertexBuffer> slvb(new VertexBuffer(context_));
  1022. slvb->SetSize(8, MASK_POSITION);
  1023. slvb->SetData(spotLightVertexData);
  1024. SharedPtr<IndexBuffer> slib(new IndexBuffer(context_));
  1025. slib->SetSize(36, false);
  1026. slib->SetData(spotLightIndexData);
  1027. spotLightGeometry_ = new Geometry(context_);
  1028. spotLightGeometry_->SetVertexBuffer(0, slvb);
  1029. spotLightGeometry_->SetIndexBuffer(slib);
  1030. spotLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, slib->GetIndexCount());
  1031. }
  1032. void Renderer::CreateInstancingBuffer()
  1033. {
  1034. // Do not create buffer if instancing not supported
  1035. if (!graphics_->GetSM3Support())
  1036. {
  1037. dynamicInstancing_ = false;
  1038. return;
  1039. }
  1040. // If must lock the buffer for each batch group, set a smaller size
  1041. unsigned defaultSize = graphics_->GetStreamOffsetSupport() ? INSTANCING_BUFFER_DEFAULT_SIZE : INSTANCING_BUFFER_DEFAULT_SIZE / 4;
  1042. instancingBuffer_ = new VertexBuffer(context_);
  1043. if (!instancingBuffer_->SetSize(defaultSize, INSTANCING_BUFFER_MASK, true))
  1044. {
  1045. instancingBuffer_.Reset();
  1046. dynamicInstancing_ = false;
  1047. }
  1048. }
  1049. bool Renderer::ResizeInstancingBuffer(unsigned numInstances)
  1050. {
  1051. if (!instancingBuffer_)
  1052. return false;
  1053. unsigned oldSize = instancingBuffer_->GetVertexCount();
  1054. if (numInstances <= oldSize)
  1055. return true;
  1056. unsigned newSize = INSTANCING_BUFFER_DEFAULT_SIZE;
  1057. while (newSize < numInstances)
  1058. newSize <<= 1;
  1059. if (!instancingBuffer_->SetSize(newSize, INSTANCING_BUFFER_MASK, true))
  1060. {
  1061. LOGERROR("Failed to resize instancing buffer to " + newSize);
  1062. // If failed, try to restore the old size
  1063. instancingBuffer_->SetSize(oldSize, INSTANCING_BUFFER_MASK, true);
  1064. return false;
  1065. }
  1066. LOGDEBUG("Resized instancing buffer to " + newSize);
  1067. return true;
  1068. }
  1069. bool Renderer::CreateShadowMaps()
  1070. {
  1071. unsigned shadowMapFormat = shadowMapHiresDepth_ ? graphics_->GetHiresShadowMapFormat() : graphics_->GetShadowMapFormat();
  1072. unsigned dummyColorFormat = graphics_->GetDummyColorFormat();
  1073. bool hardwarePCF = graphics_->GetHardwareShadowSupport();
  1074. if (shadowMapFormat == D3DFMT_UNKNOWN)
  1075. return false;
  1076. if (!drawShadows_)
  1077. {
  1078. for (unsigned i = 0; i < NUM_SHADOWMAP_RESOLUTIONS; ++i)
  1079. {
  1080. for (unsigned j = 0; j < shadowMaps_[i].Size(); ++j)
  1081. shadowMaps_[i][j].Reset();
  1082. }
  1083. return true;
  1084. }
  1085. // Create shadow maps and dummy color rendertargets
  1086. unsigned size = shadowMapSize_;
  1087. for (unsigned i = 0; i < NUM_SHADOWMAP_RESOLUTIONS; ++i)
  1088. {
  1089. if (!colorShadowMaps_[i])
  1090. colorShadowMaps_[i] = new Texture2D(context_);
  1091. if (!colorShadowMaps_[i]->SetSize(size, size, dummyColorFormat, TEXTURE_RENDERTARGET))
  1092. return false;
  1093. for (unsigned j = 0; j < shadowMaps_[i].Size(); ++j)
  1094. {
  1095. if (!shadowMaps_[i][j])
  1096. shadowMaps_[i][j] = new Texture2D(context_);
  1097. if (!shadowMaps_[i][j]->SetSize(size, size, shadowMapFormat, TEXTURE_DEPTHSTENCIL))
  1098. return false;
  1099. shadowMaps_[i][j]->SetFilterMode(hardwarePCF ? FILTER_BILINEAR : FILTER_NEAREST);
  1100. // Link the color rendertarget to depth rendertarget
  1101. shadowMaps_[i][j]->GetRenderSurface()->SetLinkedRenderTarget(colorShadowMaps_[i]->GetRenderSurface());
  1102. }
  1103. size >>= 1;
  1104. }
  1105. return true;
  1106. }
  1107. Camera* Renderer::CreateShadowCamera()
  1108. {
  1109. if (numShadowCameras_ >= shadowCameraStore_.Size())
  1110. shadowCameraStore_.Push(SharedPtr<Camera>(new Camera(context_)));
  1111. Camera* camera = shadowCameraStore_[numShadowCameras_];
  1112. camera->SetNode(CreateTempNode());
  1113. ++numShadowCameras_;
  1114. return camera;
  1115. }
  1116. Light* Renderer::CreateSplitLight(Light* original)
  1117. {
  1118. if (numSplitLights_ >= splitLightStore_.Size())
  1119. splitLightStore_.Push(SharedPtr<Light>(new Light(context_)));
  1120. Light* light = splitLightStore_[numSplitLights_];
  1121. light->SetNode(CreateTempNode());
  1122. light->copyFrom(original);
  1123. ++numSplitLights_;
  1124. return light;
  1125. }
  1126. Node* Renderer::CreateTempNode()
  1127. {
  1128. if (numTempNodes_ >= tempNodeStore_.Size())
  1129. tempNodeStore_.Push(SharedPtr<Node>(new Node(context_)));
  1130. Node* node = tempNodeStore_[numTempNodes_];
  1131. ++numTempNodes_;
  1132. return node;
  1133. }
  1134. void Renderer::SetupLightBatch(Batch& batch)
  1135. {
  1136. graphics_->ClearTransformSources();
  1137. Matrix4x3 view(batch.camera_->GetInverseWorldTransform());
  1138. Light* light = batch.light_;
  1139. float lightExtent = light->GetVolumeExtent();
  1140. float lightViewDist = (light->GetWorldPosition() - batch.camera_->GetWorldPosition()).GetLengthFast();
  1141. graphics_->SetAlphaTest(false);
  1142. graphics_->SetBlendMode(BLEND_ADD);
  1143. graphics_->SetDepthWrite(false);
  1144. if (light->GetLightType() == LIGHT_DIRECTIONAL)
  1145. {
  1146. // Get projection without jitter offset to ensure the whole screen is filled
  1147. Matrix4 projection(batch.camera_->GetProjection(false));
  1148. // If the light does not extend to the near plane, use a stencil test. Else just draw with depth fail
  1149. if (light->GetNearSplit() <= batch.camera_->GetNearClip())
  1150. {
  1151. graphics_->SetCullMode(CULL_NONE);
  1152. graphics_->SetDepthTest(CMP_GREATER);
  1153. graphics_->SetStencilTest(false);
  1154. }
  1155. else
  1156. {
  1157. Matrix4x3 nearTransform = light->GetDirLightTransform(*batch.camera_, true);
  1158. // Set state for stencil rendering
  1159. graphics_->SetColorWrite(false);
  1160. graphics_->SetCullMode(CULL_NONE);
  1161. graphics_->SetDepthTest(CMP_LESSEQUAL);
  1162. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_INCR, OP_KEEP, OP_KEEP, 1);
  1163. graphics_->SetShaders(stencilVS_, stencilPS_);
  1164. graphics_->SetVertexShaderParameter(VSP_VIEWPROJ, projection);
  1165. graphics_->SetVertexShaderParameter(VSP_MODEL, nearTransform);
  1166. // Draw to stencil
  1167. batch.geometry_->Draw(graphics_);
  1168. // Re-enable color write, set test for rendering the actual light
  1169. graphics_->SetColorWrite(true);
  1170. graphics_->SetDepthTest(CMP_GREATER);
  1171. graphics_->SetStencilTest(true, CMP_EQUAL, OP_ZERO, OP_KEEP, OP_ZERO, 1);
  1172. }
  1173. }
  1174. else
  1175. {
  1176. Matrix4 projection(batch.camera_->GetProjection());
  1177. const Matrix4x3& model = light->GetVolumeTransform(*batch.camera_);
  1178. if (light->GetLightType() == LIGHT_SPLITPOINT)
  1179. {
  1180. // Shadowed point light, split in 6 frustums: mask out overlapping pixels to prevent overlighting
  1181. // Check whether we should draw front or back faces
  1182. bool drawBackFaces = lightViewDist < (lightExtent + batch.camera_->GetNearClip());
  1183. graphics_->SetColorWrite(false);
  1184. graphics_->SetCullMode(drawBackFaces ? CULL_CCW : CULL_CW);
  1185. graphics_->SetDepthTest(drawBackFaces ? CMP_GREATER : CMP_LESS);
  1186. graphics_->SetStencilTest(true, CMP_EQUAL, OP_INCR, OP_KEEP, OP_KEEP, 0);
  1187. graphics_->SetShaders(stencilVS_, stencilPS_);
  1188. graphics_->SetVertexShaderParameter(VSP_VIEWPROJ, projection * view);
  1189. graphics_->SetVertexShaderParameter(VSP_MODEL, model);
  1190. // Draw the other faces to stencil to mark where we should not draw
  1191. batch.geometry_->Draw(graphics_);
  1192. graphics_->SetColorWrite(true);
  1193. graphics_->SetCullMode(drawBackFaces ? CULL_CW : CULL_CCW);
  1194. graphics_->SetStencilTest(true, CMP_EQUAL, OP_DECR, OP_DECR, OP_KEEP, 0);
  1195. }
  1196. else
  1197. {
  1198. // If light is close to near clip plane, we might be inside light volume
  1199. if (lightViewDist < (lightExtent + batch.camera_->GetNearClip()))
  1200. {
  1201. // In this case reverse cull mode & depth test and render back faces
  1202. graphics_->SetCullMode(CULL_CW);
  1203. graphics_->SetDepthTest(CMP_GREATER);
  1204. graphics_->SetStencilTest(false);
  1205. }
  1206. else
  1207. {
  1208. // If not too close to far clip plane, write the back faces to stencil for optimization,
  1209. // then render front faces. Else just render front faces.
  1210. if (lightViewDist < (batch.camera_->GetFarClip() - lightExtent))
  1211. {
  1212. // Set state for stencil rendering
  1213. graphics_->SetColorWrite(false);
  1214. graphics_->SetCullMode(CULL_CW);
  1215. graphics_->SetDepthTest(CMP_GREATEREQUAL);
  1216. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_INCR, OP_KEEP, OP_KEEP, 1);
  1217. graphics_->SetShaders(stencilVS_, stencilPS_);
  1218. graphics_->SetVertexShaderParameter(VSP_VIEWPROJ, projection * view);
  1219. graphics_->SetVertexShaderParameter(VSP_MODEL, model);
  1220. // Draw to stencil
  1221. batch.geometry_->Draw(graphics_);
  1222. // Re-enable color write, set test for rendering the actual light
  1223. graphics_->SetColorWrite(true);
  1224. graphics_->SetStencilTest(true, CMP_EQUAL, OP_ZERO, OP_KEEP, OP_ZERO, 1);
  1225. graphics_->SetCullMode(CULL_CCW);
  1226. graphics_->SetDepthTest(CMP_LESS);
  1227. }
  1228. else
  1229. {
  1230. graphics_->SetStencilTest(false);
  1231. graphics_->SetCullMode(CULL_CCW);
  1232. graphics_->SetDepthTest(CMP_LESS);
  1233. }
  1234. }
  1235. }
  1236. }
  1237. }
  1238. void Renderer::DrawFullScreenQuad(Camera& camera, VertexShader* vs, PixelShader* ps, bool nearQuad)
  1239. {
  1240. graphics_->ClearTransformSources();
  1241. Light quadDirLight(context_);
  1242. Matrix4x3 model(quadDirLight.GetDirLightTransform(camera, nearQuad));
  1243. graphics_->SetCullMode(CULL_NONE);
  1244. graphics_->SetShaders(vs, ps);
  1245. graphics_->SetVertexShaderParameter(VSP_MODEL, model);
  1246. // Get projection without jitter offset to ensure the whole screen is filled
  1247. graphics_->SetVertexShaderParameter(VSP_VIEWPROJ, camera.GetProjection(false));
  1248. dirLightGeometry_->Draw(graphics_);
  1249. }
  1250. void Renderer::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  1251. {
  1252. if (!initialized_)
  1253. Initialize();
  1254. else
  1255. {
  1256. // When screen mode changes, reload shaders and purge old views and occlusion buffers
  1257. shadersDirty_ = true;
  1258. occlusionBuffers_.Clear();
  1259. ResetViews();
  1260. }
  1261. }
  1262. void Renderer::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  1263. {
  1264. if (initialized_)
  1265. {
  1266. using namespace RenderUpdate;
  1267. Update(eventData[P_TIMESTEP].GetFloat());
  1268. }
  1269. }