Renderer.cpp 45 KB

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