Renderer.cpp 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "Camera.h"
  24. #include "CoreEvents.h"
  25. #include "DebugRenderer.h"
  26. #include "Geometry.h"
  27. #include "Graphics.h"
  28. #include "GraphicsEvents.h"
  29. #include "GraphicsImpl.h"
  30. #include "IndexBuffer.h"
  31. #include "Log.h"
  32. #include "Material.h"
  33. #include "OcclusionBuffer.h"
  34. #include "Octree.h"
  35. #include "Profiler.h"
  36. #include "Renderer.h"
  37. #include "RenderPath.h"
  38. #include "ResourceCache.h"
  39. #include "Scene.h"
  40. #include "ShaderVariation.h"
  41. #include "Technique.h"
  42. #include "Texture2D.h"
  43. #include "TextureCube.h"
  44. #include "VertexBuffer.h"
  45. #include "View.h"
  46. #include "XMLFile.h"
  47. #include "Zone.h"
  48. #include "DebugNew.h"
  49. namespace Urho3D
  50. {
  51. static const float dirLightVertexData[] =
  52. {
  53. -1, 1, 0,
  54. 1, 1, 0,
  55. 1, -1, 0,
  56. -1, -1, 0,
  57. };
  58. static const unsigned short dirLightIndexData[] =
  59. {
  60. 0, 1, 2,
  61. 2, 3, 0,
  62. };
  63. static const float pointLightVertexData[] =
  64. {
  65. -0.423169f, -1.000000f, 0.423169f,
  66. -0.423169f, -1.000000f, -0.423169f,
  67. 0.423169f, -1.000000f, -0.423169f,
  68. 0.423169f, -1.000000f, 0.423169f,
  69. 0.423169f, 1.000000f, -0.423169f,
  70. -0.423169f, 1.000000f, -0.423169f,
  71. -0.423169f, 1.000000f, 0.423169f,
  72. 0.423169f, 1.000000f, 0.423169f,
  73. -1.000000f, 0.423169f, -0.423169f,
  74. -1.000000f, -0.423169f, -0.423169f,
  75. -1.000000f, -0.423169f, 0.423169f,
  76. -1.000000f, 0.423169f, 0.423169f,
  77. 0.423169f, 0.423169f, -1.000000f,
  78. 0.423169f, -0.423169f, -1.000000f,
  79. -0.423169f, -0.423169f, -1.000000f,
  80. -0.423169f, 0.423169f, -1.000000f,
  81. 1.000000f, 0.423169f, 0.423169f,
  82. 1.000000f, -0.423169f, 0.423169f,
  83. 1.000000f, -0.423169f, -0.423169f,
  84. 1.000000f, 0.423169f, -0.423169f,
  85. 0.423169f, -0.423169f, 1.000000f,
  86. 0.423169f, 0.423169f, 1.000000f,
  87. -0.423169f, 0.423169f, 1.000000f,
  88. -0.423169f, -0.423169f, 1.000000f
  89. };
  90. static const unsigned short pointLightIndexData[] =
  91. {
  92. 0, 1, 2,
  93. 0, 2, 3,
  94. 4, 5, 6,
  95. 4, 6, 7,
  96. 8, 9, 10,
  97. 8, 10, 11,
  98. 12, 13, 14,
  99. 12, 14, 15,
  100. 16, 17, 18,
  101. 16, 18, 19,
  102. 20, 21, 22,
  103. 20, 22, 23,
  104. 0, 10, 9,
  105. 0, 9, 1,
  106. 13, 2, 1,
  107. 13, 1, 14,
  108. 23, 0, 3,
  109. 23, 3, 20,
  110. 17, 3, 2,
  111. 17, 2, 18,
  112. 21, 7, 6,
  113. 21, 6, 22,
  114. 7, 16, 19,
  115. 7, 19, 4,
  116. 5, 8, 11,
  117. 5, 11, 6,
  118. 4, 12, 15,
  119. 4, 15, 5,
  120. 22, 11, 10,
  121. 22, 10, 23,
  122. 8, 15, 14,
  123. 8, 14, 9,
  124. 12, 19, 18,
  125. 12, 18, 13,
  126. 16, 21, 20,
  127. 16, 20, 17,
  128. 0, 23, 10,
  129. 1, 9, 14,
  130. 2, 13, 18,
  131. 3, 17, 20,
  132. 6, 11, 22,
  133. 5, 15, 8,
  134. 4, 19, 12,
  135. 7, 21, 16
  136. };
  137. static const float spotLightVertexData[] =
  138. {
  139. 0.00001f, 0.00001f, 0.00001f,
  140. 0.00001f, -0.00001f, 0.00001f,
  141. -0.00001f, -0.00001f, 0.00001f,
  142. -0.00001f, 0.00001f, 0.00001f,
  143. 1.00000f, 1.00000f, 0.99999f,
  144. 1.00000f, -1.00000f, 0.99999f,
  145. -1.00000f, -1.00000f, 0.99999f,
  146. -1.00000f, 1.00000f, 0.99999f,
  147. };
  148. static const unsigned short spotLightIndexData[] =
  149. {
  150. 3, 0, 1,
  151. 3, 1, 2,
  152. 0, 4, 5,
  153. 0, 5, 1,
  154. 3, 7, 4,
  155. 3, 4, 0,
  156. 7, 3, 2,
  157. 7, 2, 6,
  158. 6, 2, 1,
  159. 6, 1, 5,
  160. 7, 5, 4,
  161. 7, 6, 5
  162. };
  163. static const char* shadowVariations[] =
  164. {
  165. #ifdef URHO3D_OPENGL
  166. // No specific hardware shadow compare variation on OpenGL, it is always supported
  167. "LQSHADOW ",
  168. "LQSHADOW ",
  169. "",
  170. ""
  171. #else
  172. "LQSHADOW SHADOWCMP",
  173. "LQSHADOW",
  174. "SHADOWCMP",
  175. ""
  176. #endif
  177. };
  178. static const char* geometryVSVariations[] =
  179. {
  180. "",
  181. "SKINNED ",
  182. "INSTANCED ",
  183. "BILLBOARD "
  184. };
  185. static const char* lightVSVariations[] =
  186. {
  187. "PERPIXEL DIRLIGHT ",
  188. "PERPIXEL SPOTLIGHT ",
  189. "PERPIXEL POINTLIGHT ",
  190. "PERPIXEL DIRLIGHT SHADOW ",
  191. "PERPIXEL SPOTLIGHT SHADOW ",
  192. "PERPIXEL POINTLIGHT SHADOW ",
  193. };
  194. static const char* vertexLightVSVariations[] =
  195. {
  196. "",
  197. "NUMVERTEXLIGHTS=1 ",
  198. "NUMVERTEXLIGHTS=2 ",
  199. "NUMVERTEXLIGHTS=3 ",
  200. "NUMVERTEXLIGHTS=4 ",
  201. };
  202. static const char* deferredLightVSVariations[] =
  203. {
  204. "",
  205. "DIRLIGHT ",
  206. "ORTHO ",
  207. "DIRLIGHT ORTHO "
  208. };
  209. static const char* lightPSVariations[] =
  210. {
  211. "PERPIXEL DIRLIGHT ",
  212. "PERPIXEL SPOTLIGHT ",
  213. "PERPIXEL POINTLIGHT ",
  214. "PERPIXEL POINTLIGHT CUBEMASK ",
  215. "PERPIXEL DIRLIGHT SPECULAR ",
  216. "PERPIXEL SPOTLIGHT SPECULAR ",
  217. "PERPIXEL POINTLIGHT SPECULAR ",
  218. "PERPIXEL POINTLIGHT CUBEMASK SPECULAR ",
  219. "PERPIXEL DIRLIGHT SHADOW ",
  220. "PERPIXEL SPOTLIGHT SHADOW ",
  221. "PERPIXEL POINTLIGHT SHADOW ",
  222. "PERPIXEL POINTLIGHT CUBEMASK SHADOW ",
  223. "PERPIXEL DIRLIGHT SPECULAR SHADOW ",
  224. "PERPIXEL SPOTLIGHT SPECULAR SHADOW ",
  225. "PERPIXEL POINTLIGHT SPECULAR SHADOW ",
  226. "PERPIXEL POINTLIGHT CUBEMASK SPECULAR SHADOW "
  227. };
  228. static const char* heightFogVariations[] =
  229. {
  230. "",
  231. "HEIGHTFOG "
  232. };
  233. static const unsigned INSTANCING_BUFFER_MASK = MASK_INSTANCEMATRIX1 | MASK_INSTANCEMATRIX2 | MASK_INSTANCEMATRIX3;
  234. static const unsigned MAX_BUFFER_AGE = 1000;
  235. Renderer::Renderer(Context* context) :
  236. Object(context),
  237. defaultZone_(new Zone(context)),
  238. quadDirLight_(new Light(context)),
  239. textureAnisotropy_(4),
  240. textureFilterMode_(FILTER_TRILINEAR),
  241. textureQuality_(QUALITY_HIGH),
  242. materialQuality_(QUALITY_HIGH),
  243. shadowMapSize_(1024),
  244. shadowQuality_(SHADOWQUALITY_HIGH_16BIT),
  245. maxShadowMaps_(1),
  246. minInstances_(2),
  247. maxInstanceTriangles_(500),
  248. maxSortedInstances_(1000),
  249. maxOccluderTriangles_(5000),
  250. occlusionBufferSize_(256),
  251. occluderSizeThreshold_(0.025f),
  252. mobileShadowBiasMul_(2.0f),
  253. mobileShadowBiasAdd_(0.0001f),
  254. numViews_(0),
  255. numOcclusionBuffers_(0),
  256. numShadowCameras_(0),
  257. shadersChangedFrameNumber_(M_MAX_UNSIGNED),
  258. hdrRendering_(false),
  259. specularLighting_(true),
  260. drawShadows_(true),
  261. reuseShadowMaps_(true),
  262. dynamicInstancing_(true),
  263. shadersDirty_(true),
  264. initialized_(false)
  265. {
  266. SubscribeToEvent(E_SCREENMODE, HANDLER(Renderer, HandleScreenMode));
  267. SubscribeToEvent(E_GRAPHICSFEATURES, HANDLER(Renderer, HandleGraphicsFeatures));
  268. quadDirLight_->SetLightType(LIGHT_DIRECTIONAL);
  269. // Try to initialize right now, but skip if screen mode is not yet set
  270. Initialize();
  271. }
  272. Renderer::~Renderer()
  273. {
  274. }
  275. void Renderer::SetNumViewports(unsigned num)
  276. {
  277. viewports_.Resize(num);
  278. }
  279. void Renderer::SetViewport(unsigned index, Viewport* viewport)
  280. {
  281. if (index >= viewports_.Size())
  282. viewports_.Resize(index + 1);
  283. viewports_[index] = viewport;
  284. }
  285. void Renderer::SetDefaultRenderPath(RenderPath* renderPath)
  286. {
  287. if (renderPath)
  288. defaultRenderPath_ = renderPath;
  289. }
  290. void Renderer::SetDefaultRenderPath(XMLFile* xmlFile)
  291. {
  292. SharedPtr<RenderPath> newRenderPath(new RenderPath());
  293. if (newRenderPath->Load(xmlFile))
  294. defaultRenderPath_ = newRenderPath;
  295. }
  296. void Renderer::SetHDRRendering(bool enable)
  297. {
  298. hdrRendering_ = enable;
  299. }
  300. void Renderer::SetSpecularLighting(bool enable)
  301. {
  302. specularLighting_ = enable;
  303. }
  304. void Renderer::SetTextureAnisotropy(int level)
  305. {
  306. textureAnisotropy_ = Max(level, 1);
  307. }
  308. void Renderer::SetTextureFilterMode(TextureFilterMode mode)
  309. {
  310. textureFilterMode_ = mode;
  311. }
  312. void Renderer::SetTextureQuality(int quality)
  313. {
  314. quality = Clamp(quality, QUALITY_LOW, QUALITY_HIGH);
  315. if (quality != textureQuality_)
  316. {
  317. textureQuality_ = quality;
  318. ReloadTextures();
  319. }
  320. }
  321. void Renderer::SetMaterialQuality(int quality)
  322. {
  323. quality = Clamp(quality, QUALITY_LOW, QUALITY_MAX);
  324. if (quality != materialQuality_)
  325. {
  326. materialQuality_ = quality;
  327. shadersDirty_ = true;
  328. ResetViews();
  329. }
  330. }
  331. void Renderer::SetDrawShadows(bool enable)
  332. {
  333. if (!graphics_ || !graphics_->GetShadowMapFormat())
  334. return;
  335. drawShadows_ = enable;
  336. if (!drawShadows_)
  337. ResetShadowMaps();
  338. }
  339. void Renderer::SetShadowMapSize(int size)
  340. {
  341. if (!graphics_)
  342. return;
  343. size = NextPowerOfTwo(Max(size, SHADOW_MIN_PIXELS));
  344. if (size != shadowMapSize_)
  345. {
  346. shadowMapSize_ = size;
  347. ResetShadowMaps();
  348. }
  349. }
  350. void Renderer::SetShadowQuality(int quality)
  351. {
  352. if (!graphics_)
  353. return;
  354. quality &= SHADOWQUALITY_HIGH_24BIT;
  355. // If no hardware PCF, do not allow to select one-sample quality
  356. if (!graphics_->GetHardwareShadowSupport())
  357. quality |= SHADOWQUALITY_HIGH_16BIT;
  358. if (!graphics_->GetHiresShadowMapFormat())
  359. quality &= SHADOWQUALITY_HIGH_16BIT;
  360. if (quality != shadowQuality_)
  361. {
  362. shadowQuality_ = quality;
  363. shadersDirty_ = true;
  364. ResetShadowMaps();
  365. }
  366. }
  367. void Renderer::SetReuseShadowMaps(bool enable)
  368. {
  369. if (enable == reuseShadowMaps_)
  370. return;
  371. reuseShadowMaps_ = enable;
  372. }
  373. void Renderer::SetMaxShadowMaps(int shadowMaps)
  374. {
  375. if (shadowMaps < 1)
  376. return;
  377. maxShadowMaps_ = shadowMaps;
  378. for (HashMap<int, Vector<SharedPtr<Texture2D> > >::Iterator i = shadowMaps_.Begin(); i != shadowMaps_.End(); ++i)
  379. {
  380. if ((int)i->second_.Size() > maxShadowMaps_)
  381. i->second_.Resize(maxShadowMaps_);
  382. }
  383. }
  384. void Renderer::SetDynamicInstancing(bool enable)
  385. {
  386. if (!instancingBuffer_)
  387. enable = false;
  388. dynamicInstancing_ = enable;
  389. }
  390. void Renderer::SetMinInstances(int instances)
  391. {
  392. minInstances_ = Max(instances, 2);
  393. }
  394. void Renderer::SetMaxInstanceTriangles(int triangles)
  395. {
  396. maxInstanceTriangles_ = Max(triangles, 0);
  397. }
  398. void Renderer::SetMaxSortedInstances(int instances)
  399. {
  400. maxSortedInstances_ = Max(instances, 0);
  401. }
  402. void Renderer::SetMaxOccluderTriangles(int triangles)
  403. {
  404. maxOccluderTriangles_ = Max(triangles, 0);
  405. }
  406. void Renderer::SetOcclusionBufferSize(int size)
  407. {
  408. occlusionBufferSize_ = Max(size, 1);
  409. occlusionBuffers_.Clear();
  410. }
  411. void Renderer::SetMobileShadowBiasMul(float mul)
  412. {
  413. mobileShadowBiasMul_ = mul;
  414. }
  415. void Renderer::SetMobileShadowBiasAdd(float add)
  416. {
  417. mobileShadowBiasAdd_ = add;
  418. }
  419. void Renderer::SetOccluderSizeThreshold(float screenSize)
  420. {
  421. occluderSizeThreshold_ = Max(screenSize, 0.0f);
  422. }
  423. void Renderer::ReloadShaders()
  424. {
  425. shadersDirty_ = true;
  426. }
  427. Viewport* Renderer::GetViewport(unsigned index) const
  428. {
  429. return index < viewports_.Size() ? viewports_[index] : (Viewport*)0;
  430. }
  431. RenderPath* Renderer::GetDefaultRenderPath() const
  432. {
  433. return defaultRenderPath_;
  434. }
  435. unsigned Renderer::GetNumGeometries(bool allViews) const
  436. {
  437. unsigned numGeometries = 0;
  438. unsigned lastView = allViews ? numViews_ : 1;
  439. for (unsigned i = 0; i < lastView; ++i)
  440. numGeometries += views_[i]->GetGeometries().Size();
  441. return numGeometries;
  442. }
  443. unsigned Renderer::GetNumLights(bool allViews) const
  444. {
  445. unsigned numLights = 0;
  446. unsigned lastView = allViews ? numViews_ : 1;
  447. for (unsigned i = 0; i < lastView; ++i)
  448. numLights += views_[i]->GetLights().Size();
  449. return numLights;
  450. }
  451. unsigned Renderer::GetNumShadowMaps(bool allViews) const
  452. {
  453. unsigned numShadowMaps = 0;
  454. unsigned lastView = allViews ? numViews_ : 1;
  455. for (unsigned i = 0; i < lastView; ++i)
  456. {
  457. const Vector<LightBatchQueue>& lightQueues = views_[i]->GetLightQueues();
  458. for (Vector<LightBatchQueue>::ConstIterator i = lightQueues.Begin(); i != lightQueues.End(); ++i)
  459. {
  460. if (i->shadowMap_)
  461. ++numShadowMaps;
  462. }
  463. }
  464. return numShadowMaps;
  465. }
  466. unsigned Renderer::GetNumOccluders(bool allViews) const
  467. {
  468. unsigned numOccluders = 0;
  469. unsigned lastView = allViews ? numViews_ : 1;
  470. for (unsigned i = 0; i < lastView; ++i)
  471. numOccluders += views_[i]->GetOccluders().Size();
  472. return numOccluders;
  473. }
  474. void Renderer::Update(float timeStep)
  475. {
  476. PROFILE(UpdateViews);
  477. numViews_ = 0;
  478. // If device lost, do not perform update. This is because any dynamic vertex/index buffer updates happen already here,
  479. // and if the device is lost, the updates queue up, causing memory use to rise constantly
  480. if (!graphics_ || !graphics_->IsInitialized() || graphics_->IsDeviceLost())
  481. return;
  482. // Set up the frameinfo structure for this frame
  483. frame_.frameNumber_ = GetSubsystem<Time>()->GetFrameNumber();
  484. frame_.timeStep_ = timeStep;
  485. frame_.camera_ = 0;
  486. numShadowCameras_ = 0;
  487. numOcclusionBuffers_ = 0;
  488. updatedOctrees_.Clear();
  489. // Reload shaders now if needed
  490. if (shadersDirty_)
  491. LoadShaders();
  492. // Queue update of the main viewports. Use reverse order, as rendering order is also reverse
  493. // to render auxiliary views before dependant main views
  494. for (unsigned i = viewports_.Size() - 1; i < viewports_.Size(); --i)
  495. QueueViewport(0, viewports_[i]);
  496. // Gather other render surfaces that are autoupdated
  497. SendEvent(E_RENDERSURFACEUPDATE);
  498. // Process gathered views. This may queue further views (render surfaces that are only updated when visible)
  499. for (unsigned i = 0; i < queuedViews_.Size(); ++i)
  500. {
  501. WeakPtr<RenderSurface>& renderTarget = queuedViews_[i].first_;
  502. WeakPtr<Viewport>& viewport = queuedViews_[i].second_;
  503. // Null pointer means backbuffer view. Differentiate between that and an expired rendersurface
  504. if ((renderTarget.NotNull() && renderTarget.Expired()) || viewport.Expired())
  505. continue;
  506. // Allocate new view if necessary
  507. if (numViews_ == views_.Size())
  508. views_.Push(SharedPtr<View>(new View(context_)));
  509. // Check if view can be defined successfully (has either valid scene, camera and octree, or no scene passes)
  510. assert(numViews_ < views_.Size());
  511. View* view = views_[numViews_];
  512. if (!view->Define(renderTarget, viewport))
  513. continue;
  514. ++numViews_;
  515. const IntRect& viewRect = viewport->GetRect();
  516. Scene* scene = viewport->GetScene();
  517. Octree* octree = scene ? scene->GetComponent<Octree>() : 0;
  518. if (scene && octree)
  519. {
  520. // Update octree (perform early update for drawables which need that, and reinsert moved drawables.)
  521. // However, if the same scene is viewed from multiple cameras, update the octree only once
  522. if (!updatedOctrees_.Contains(octree))
  523. {
  524. frame_.camera_ = viewport->GetCamera();
  525. frame_.viewSize_ = viewRect.Size();
  526. if (frame_.viewSize_ == IntVector2::ZERO)
  527. frame_.viewSize_ = IntVector2(graphics_->GetWidth(), graphics_->GetHeight());
  528. octree->Update(frame_);
  529. updatedOctrees_.Insert(octree);
  530. // Set also the view for the debug renderer already here, so that it can use culling
  531. /// \todo May result in incorrect debug geometry culling if the same scene is drawn from multiple viewports
  532. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  533. if (debug)
  534. debug->SetView(viewport->GetCamera());
  535. }
  536. }
  537. // Update view. This may queue further views
  538. using namespace BeginViewUpdate;
  539. VariantMap& eventData = GetEventDataMap();
  540. eventData[P_SURFACE] = renderTarget.Get();
  541. eventData[P_TEXTURE] = (renderTarget ? renderTarget->GetParentTexture() : 0);
  542. eventData[P_SCENE] = scene;
  543. eventData[P_CAMERA] = viewport->GetCamera();
  544. SendEvent(E_BEGINVIEWUPDATE, eventData);
  545. ResetShadowMapAllocations(); // Each view can reuse the same shadow maps
  546. view->Update(frame_);
  547. SendEvent(E_ENDVIEWUPDATE, eventData);
  548. }
  549. // Reset update flag from queued render surfaces. At this point no new views can be added on this frame
  550. for (unsigned i = 0; i < queuedViews_.Size(); ++i)
  551. {
  552. WeakPtr<RenderSurface>& renderTarget = queuedViews_[i].first_;
  553. if (renderTarget)
  554. renderTarget->WasUpdated();
  555. }
  556. queuedViews_.Clear();
  557. }
  558. void Renderer::Render()
  559. {
  560. // Engine does not render when window is closed or device is lost
  561. assert(graphics_ && graphics_->IsInitialized() && !graphics_->IsDeviceLost());
  562. PROFILE(RenderViews);
  563. // If the indirection textures have lost content (OpenGL mode only), restore them now
  564. if (faceSelectCubeMap_ && faceSelectCubeMap_->IsDataLost())
  565. SetIndirectionTextureData();
  566. graphics_->SetDefaultTextureFilterMode(textureFilterMode_);
  567. graphics_->SetTextureAnisotropy(textureAnisotropy_);
  568. graphics_->ClearParameterSources();
  569. // If no views, just clear the screen
  570. if (!numViews_)
  571. {
  572. graphics_->SetBlendMode(BLEND_REPLACE);
  573. graphics_->SetColorWrite(true);
  574. graphics_->SetDepthWrite(true);
  575. graphics_->SetScissorTest(false);
  576. graphics_->SetStencilTest(false);
  577. graphics_->ResetRenderTargets();
  578. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH | CLEAR_STENCIL, defaultZone_->GetFogColor());
  579. numPrimitives_ = 0;
  580. numBatches_ = 0;
  581. }
  582. else
  583. {
  584. // Render views from last to first (each main view is rendered after the auxiliary views it depends on)
  585. for (unsigned i = numViews_ - 1; i < numViews_; --i)
  586. {
  587. using namespace BeginViewRender;
  588. RenderSurface* renderTarget = views_[i]->GetRenderTarget();
  589. VariantMap& eventData = GetEventDataMap();
  590. eventData[P_SURFACE] = renderTarget;
  591. eventData[P_TEXTURE] = (renderTarget ? renderTarget->GetParentTexture() : 0);
  592. eventData[P_SCENE] = views_[i]->GetScene();
  593. eventData[P_CAMERA] = views_[i]->GetCamera();
  594. SendEvent(E_BEGINVIEWRENDER, eventData);
  595. // Screen buffers can be reused between views, as each is rendered completely
  596. PrepareViewRender();
  597. views_[i]->Render();
  598. SendEvent(E_ENDVIEWRENDER, eventData);
  599. }
  600. // Copy the number of batches & primitives from Graphics so that we can account for 3D geometry only
  601. numPrimitives_ = graphics_->GetNumPrimitives();
  602. numBatches_ = graphics_->GetNumBatches();
  603. }
  604. // Remove unused occlusion buffers and renderbuffers
  605. RemoveUnusedBuffers();
  606. }
  607. void Renderer::DrawDebugGeometry(bool depthTest)
  608. {
  609. PROFILE(RendererDrawDebug);
  610. /// \todo Because debug geometry is per-scene, if two cameras show views of the same area, occlusion is not shown correctly
  611. HashSet<Drawable*> processedGeometries;
  612. HashSet<Light*> processedLights;
  613. for (unsigned i = 0; i < numViews_; ++i)
  614. {
  615. // Make sure it's a main view, and process each node only once
  616. View* view = views_[i];
  617. if (view->GetRenderTarget())
  618. continue;
  619. Octree* octree = view->GetOctree();
  620. if (!octree)
  621. continue;
  622. DebugRenderer* debug = octree->GetComponent<DebugRenderer>();
  623. if (!debug || !debug->IsEnabledEffective())
  624. continue;
  625. const PODVector<Drawable*>& geometries = view->GetGeometries();
  626. const PODVector<Light*>& lights = view->GetLights();
  627. for (unsigned i = 0; i < geometries.Size(); ++i)
  628. {
  629. if (!processedGeometries.Contains(geometries[i]))
  630. {
  631. geometries[i]->DrawDebugGeometry(debug, depthTest);
  632. processedGeometries.Insert(geometries[i]);
  633. }
  634. }
  635. for (unsigned i = 0; i < lights.Size(); ++i)
  636. {
  637. if (!processedLights.Contains(lights[i]))
  638. {
  639. lights[i]->DrawDebugGeometry(debug, depthTest);
  640. processedLights.Insert(lights[i]);
  641. }
  642. }
  643. }
  644. }
  645. void Renderer::QueueRenderSurface(RenderSurface* renderTarget)
  646. {
  647. if (renderTarget)
  648. {
  649. unsigned numViewports = renderTarget->GetNumViewports();
  650. for (unsigned i = 0; i < numViewports; ++i)
  651. QueueViewport(renderTarget, renderTarget->GetViewport(i));
  652. }
  653. }
  654. void Renderer::QueueViewport(RenderSurface* renderTarget, Viewport* viewport)
  655. {
  656. if (viewport)
  657. {
  658. queuedViews_.Push(Pair<WeakPtr<RenderSurface>, WeakPtr<Viewport> >(WeakPtr<RenderSurface>(renderTarget),
  659. WeakPtr<Viewport>(viewport)));
  660. }
  661. }
  662. Geometry* Renderer::GetLightGeometry(Light* light)
  663. {
  664. switch (light->GetLightType())
  665. {
  666. case LIGHT_DIRECTIONAL:
  667. return dirLightGeometry_;
  668. case LIGHT_SPOT:
  669. return spotLightGeometry_;
  670. case LIGHT_POINT:
  671. return pointLightGeometry_;
  672. }
  673. return 0;
  674. }
  675. Texture2D* Renderer::GetShadowMap(Light* light, Camera* camera, unsigned viewWidth, unsigned viewHeight)
  676. {
  677. LightType type = light->GetLightType();
  678. const FocusParameters& parameters = light->GetShadowFocus();
  679. float size = (float)shadowMapSize_ * light->GetShadowResolution();
  680. // Automatically reduce shadow map size when far away
  681. if (parameters.autoSize_ && type != LIGHT_DIRECTIONAL)
  682. {
  683. const Matrix3x4& view = camera->GetView();
  684. const Matrix4& projection = camera->GetProjection();
  685. BoundingBox lightBox;
  686. float lightPixels;
  687. if (type == LIGHT_POINT)
  688. {
  689. // Calculate point light pixel size from the projection of its diagonal
  690. Vector3 center = view * light->GetNode()->GetWorldPosition();
  691. float extent = 0.58f * light->GetRange();
  692. lightBox.Define(center + Vector3(extent, extent, extent), center - Vector3(extent, extent, extent));
  693. }
  694. else
  695. {
  696. // Calculate spot light pixel size from the projection of its frustum far vertices
  697. Frustum lightFrustum = light->GetFrustum().Transformed(view);
  698. lightBox.Define(&lightFrustum.vertices_[4], 4);
  699. }
  700. Vector2 projectionSize = lightBox.Projected(projection).Size();
  701. lightPixels = Max(0.5f * (float)viewWidth * projectionSize.x_, 0.5f * (float)viewHeight * projectionSize.y_);
  702. // Clamp pixel amount to a sufficient minimum to avoid self-shadowing artifacts due to loss of precision
  703. if (lightPixels < SHADOW_MIN_PIXELS)
  704. lightPixels = SHADOW_MIN_PIXELS;
  705. size = Min(size, lightPixels);
  706. }
  707. /// \todo Allow to specify maximum shadow maps per resolution, as smaller shadow maps take less memory
  708. int width = NextPowerOfTwo((unsigned)size);
  709. int height = width;
  710. // Adjust the size for directional or point light shadow map atlases
  711. if (type == LIGHT_DIRECTIONAL)
  712. {
  713. unsigned numSplits = light->GetNumShadowSplits();
  714. if (numSplits > 1)
  715. width *= 2;
  716. if (numSplits > 2)
  717. height *= 2;
  718. }
  719. else if (type == LIGHT_POINT)
  720. {
  721. width *= 2;
  722. height *= 3;
  723. }
  724. int searchKey = (width << 16) | height;
  725. if (shadowMaps_.Contains(searchKey))
  726. {
  727. // If shadow maps are reused, always return the first
  728. if (reuseShadowMaps_)
  729. return shadowMaps_[searchKey][0];
  730. else
  731. {
  732. // If not reused, check allocation count and return existing shadow map if possible
  733. unsigned allocated = shadowMapAllocations_[searchKey].Size();
  734. if (allocated < shadowMaps_[searchKey].Size())
  735. {
  736. shadowMapAllocations_[searchKey].Push(light);
  737. return shadowMaps_[searchKey][allocated];
  738. }
  739. else if ((int)allocated >= maxShadowMaps_)
  740. return 0;
  741. }
  742. }
  743. unsigned shadowMapFormat = (shadowQuality_ & SHADOWQUALITY_LOW_24BIT) ? graphics_->GetHiresShadowMapFormat() :
  744. graphics_->GetShadowMapFormat();
  745. if (!shadowMapFormat)
  746. return 0;
  747. SharedPtr<Texture2D> newShadowMap(new Texture2D(context_));
  748. int retries = 3;
  749. // OpenGL: create shadow map only. Color rendertarget is not needed
  750. #ifdef URHO3D_OPENGL
  751. while (retries)
  752. {
  753. if (!newShadowMap->SetSize(width, height, shadowMapFormat, TEXTURE_DEPTHSTENCIL))
  754. {
  755. width >>= 1;
  756. height >>= 1;
  757. --retries;
  758. }
  759. else
  760. {
  761. #ifndef GL_ES_VERSION_2_0
  762. newShadowMap->SetFilterMode(FILTER_BILINEAR);
  763. newShadowMap->SetShadowCompare(true);
  764. #endif
  765. break;
  766. }
  767. }
  768. #else
  769. // Direct3D9: create shadow map and dummy color rendertarget
  770. unsigned dummyColorFormat = graphics_->GetDummyColorFormat();
  771. while (retries)
  772. {
  773. if (!newShadowMap->SetSize(width, height, shadowMapFormat, TEXTURE_DEPTHSTENCIL))
  774. {
  775. width >>= 1;
  776. height >>= 1;
  777. --retries;
  778. }
  779. else
  780. {
  781. // When shadow compare must be done manually, use nearest filtering so that the filtering of point lights and other
  782. // shadowed lights matches
  783. newShadowMap->SetFilterMode(graphics_->GetHardwareShadowSupport() ? FILTER_BILINEAR : FILTER_NEAREST);
  784. // If no dummy color rendertarget for this size exists yet, create one now
  785. if (!colorShadowMaps_.Contains(searchKey))
  786. {
  787. colorShadowMaps_[searchKey] = new Texture2D(context_);
  788. colorShadowMaps_[searchKey]->SetSize(width, height, dummyColorFormat, TEXTURE_RENDERTARGET);
  789. }
  790. // Link the color rendertarget to the shadow map
  791. newShadowMap->GetRenderSurface()->SetLinkedRenderTarget(colorShadowMaps_[searchKey]->GetRenderSurface());
  792. break;
  793. }
  794. }
  795. #endif
  796. // If failed to set size, store a null pointer so that we will not retry
  797. if (!retries)
  798. newShadowMap.Reset();
  799. shadowMaps_[searchKey].Push(newShadowMap);
  800. if (!reuseShadowMaps_)
  801. shadowMapAllocations_[searchKey].Push(light);
  802. return newShadowMap;
  803. }
  804. Texture2D* Renderer::GetScreenBuffer(int width, int height, unsigned format, bool filtered, bool srgb, unsigned persistentKey)
  805. {
  806. bool depthStencil = (format == Graphics::GetDepthStencilFormat());
  807. if (depthStencil)
  808. {
  809. filtered = false;
  810. srgb = false;
  811. }
  812. long long searchKey = ((long long)format << 32) | (width << 16) | height;
  813. if (filtered)
  814. searchKey |= 0x8000000000000000LL;
  815. if (srgb)
  816. searchKey |= 0x4000000000000000LL;
  817. // Add persistent key if defined
  818. if (persistentKey)
  819. searchKey += ((long long)persistentKey << 32);
  820. // If new size or format, initialize the allocation stats
  821. if (screenBuffers_.Find(searchKey) == screenBuffers_.End())
  822. screenBufferAllocations_[searchKey] = 0;
  823. // Reuse depth-stencil buffers whenever the size matches, instead of allocating new
  824. unsigned allocations = screenBufferAllocations_[searchKey];
  825. if(!depthStencil)
  826. ++screenBufferAllocations_[searchKey];
  827. if (allocations >= screenBuffers_[searchKey].Size())
  828. {
  829. SharedPtr<Texture2D> newBuffer(new Texture2D(context_));
  830. newBuffer->SetSRGB(srgb);
  831. newBuffer->SetSize(width, height, format, depthStencil ? TEXTURE_DEPTHSTENCIL : TEXTURE_RENDERTARGET);
  832. newBuffer->SetFilterMode(filtered ? FILTER_BILINEAR : FILTER_NEAREST);
  833. newBuffer->ResetUseTimer();
  834. screenBuffers_[searchKey].Push(newBuffer);
  835. #ifdef URHO3D_OPENGL
  836. // OpenGL hack: clear persistent floating point screen buffers to ensure the initial contents aren't illegal (NaN)?
  837. // Otherwise eg. the AutoExposure post process will not work correctly
  838. if (persistentKey && Texture::GetDataType(format) == GL_FLOAT)
  839. {
  840. // Note: this loses current rendertarget assignment
  841. graphics_->ResetRenderTargets();
  842. graphics_->SetRenderTarget(0, newBuffer);
  843. graphics_->SetDepthStencil((RenderSurface*)0);
  844. graphics_->SetViewport(IntRect(0, 0, width, height));
  845. graphics_->Clear(CLEAR_COLOR);
  846. }
  847. #endif
  848. LOGDEBUG("Allocated new screen buffer size " + String(width) + "x" + String(height) + " format " + String(format));
  849. return newBuffer;
  850. }
  851. else
  852. {
  853. Texture2D* buffer = screenBuffers_[searchKey][allocations];
  854. buffer->ResetUseTimer();
  855. return buffer;
  856. }
  857. }
  858. RenderSurface* Renderer::GetDepthStencil(int width, int height)
  859. {
  860. // Return the default depth-stencil surface if applicable
  861. // (when using OpenGL Graphics will allocate right size surfaces on demand to emulate Direct3D9)
  862. if (width == graphics_->GetWidth() && height == graphics_->GetHeight() && graphics_->GetMultiSample() <= 1)
  863. return 0;
  864. else
  865. return GetScreenBuffer(width, height, Graphics::GetDepthStencilFormat(), false, false)->GetRenderSurface();
  866. }
  867. OcclusionBuffer* Renderer::GetOcclusionBuffer(Camera* camera)
  868. {
  869. assert(numOcclusionBuffers_ <= occlusionBuffers_.Size());
  870. if (numOcclusionBuffers_ == occlusionBuffers_.Size())
  871. {
  872. SharedPtr<OcclusionBuffer> newBuffer(new OcclusionBuffer(context_));
  873. occlusionBuffers_.Push(newBuffer);
  874. }
  875. int width = occlusionBufferSize_;
  876. int height = (int)((float)occlusionBufferSize_ / camera->GetAspectRatio() + 0.5f);
  877. OcclusionBuffer* buffer = occlusionBuffers_[numOcclusionBuffers_++];
  878. buffer->SetSize(width, height);
  879. buffer->SetView(camera);
  880. buffer->ResetUseTimer();
  881. return buffer;
  882. }
  883. Camera* Renderer::GetShadowCamera()
  884. {
  885. MutexLock lock(rendererMutex_);
  886. assert(numShadowCameras_ <= shadowCameraNodes_.Size());
  887. if (numShadowCameras_ == shadowCameraNodes_.Size())
  888. {
  889. SharedPtr<Node> newNode(new Node(context_));
  890. newNode->CreateComponent<Camera>();
  891. shadowCameraNodes_.Push(newNode);
  892. }
  893. Camera* camera = shadowCameraNodes_[numShadowCameras_++]->GetComponent<Camera>();
  894. camera->SetOrthographic(false);
  895. camera->SetZoom(1.0f);
  896. return camera;
  897. }
  898. void Renderer::SetBatchShaders(Batch& batch, Technique* tech, bool allowShadows)
  899. {
  900. // Check if shaders are unloaded or need reloading
  901. Pass* pass = batch.pass_;
  902. Vector<SharedPtr<ShaderVariation> >& vertexShaders = pass->GetVertexShaders();
  903. Vector<SharedPtr<ShaderVariation> >& pixelShaders = pass->GetPixelShaders();
  904. if (!vertexShaders.Size() || !pixelShaders.Size() || pass->GetShadersLoadedFrameNumber() !=
  905. shadersChangedFrameNumber_)
  906. {
  907. // First release all previous shaders, then load
  908. pass->ReleaseShaders();
  909. LoadPassShaders(tech, pass->GetType());
  910. }
  911. // Make sure shaders are loaded now
  912. if (vertexShaders.Size() && pixelShaders.Size())
  913. {
  914. bool heightFog = batch.zone_ && batch.zone_->GetHeightFog();
  915. // If instancing is not supported, but was requested, or the object is too large to be instanced,
  916. // choose static geometry vertex shader instead
  917. if (batch.geometryType_ == GEOM_INSTANCED && (!GetDynamicInstancing() || batch.geometry_->GetIndexCount() >
  918. (unsigned)maxInstanceTriangles_ * 3))
  919. batch.geometryType_ = GEOM_STATIC;
  920. if (batch.geometryType_ == GEOM_STATIC_NOINSTANCING)
  921. batch.geometryType_ = GEOM_STATIC;
  922. // Check whether is a pixel lit forward pass. If not, there is only one pixel shader
  923. if (pass->GetLightingMode() == LIGHTING_PERPIXEL)
  924. {
  925. LightBatchQueue* lightQueue = batch.lightQueue_;
  926. if (!lightQueue)
  927. {
  928. // Do not log error, as it would result in a lot of spam
  929. batch.vertexShader_ = 0;
  930. batch.pixelShader_ = 0;
  931. return;
  932. }
  933. Light* light = lightQueue->light_;
  934. unsigned vsi = 0;
  935. unsigned psi = 0;
  936. vsi = batch.geometryType_ * MAX_LIGHT_VS_VARIATIONS;
  937. bool materialHasSpecular = batch.material_ ? batch.material_->GetSpecular() : true;
  938. if (specularLighting_ && light->GetSpecularIntensity() > 0.0f && materialHasSpecular)
  939. psi += LPS_SPEC;
  940. if (allowShadows && lightQueue->shadowMap_)
  941. {
  942. vsi += LVS_SHADOW;
  943. psi += LPS_SHADOW;
  944. }
  945. switch (light->GetLightType())
  946. {
  947. case LIGHT_DIRECTIONAL:
  948. vsi += LVS_DIR;
  949. break;
  950. case LIGHT_SPOT:
  951. psi += LPS_SPOT;
  952. vsi += LVS_SPOT;
  953. break;
  954. case LIGHT_POINT:
  955. if (light->GetShapeTexture())
  956. psi += LPS_POINTMASK;
  957. else
  958. psi += LPS_POINT;
  959. vsi += LVS_POINT;
  960. break;
  961. }
  962. if (heightFog)
  963. psi += MAX_LIGHT_PS_VARIATIONS;
  964. batch.vertexShader_ = vertexShaders[vsi];
  965. batch.pixelShader_ = pixelShaders[psi];
  966. }
  967. else
  968. {
  969. // Check if pass has vertex lighting support
  970. if (pass->GetLightingMode() == LIGHTING_PERVERTEX)
  971. {
  972. unsigned numVertexLights = 0;
  973. if (batch.lightQueue_)
  974. numVertexLights = batch.lightQueue_->vertexLights_.Size();
  975. unsigned vsi = batch.geometryType_ * MAX_VERTEXLIGHT_VS_VARIATIONS + numVertexLights;
  976. batch.vertexShader_ = vertexShaders[vsi];
  977. }
  978. else
  979. {
  980. unsigned vsi = batch.geometryType_;
  981. batch.vertexShader_ = vertexShaders[vsi];
  982. }
  983. batch.pixelShader_ = pixelShaders[heightFog ? 1 : 0];
  984. }
  985. }
  986. // Log error if shaders could not be assigned, but only once per technique
  987. if (!batch.vertexShader_ || !batch.pixelShader_)
  988. {
  989. if (!shaderErrorDisplayed_.Contains(tech))
  990. {
  991. shaderErrorDisplayed_.Insert(tech);
  992. LOGERROR("Technique " + tech->GetName() + " has missing shaders");
  993. }
  994. }
  995. }
  996. void Renderer::SetLightVolumeBatchShaders(Batch& batch, const String& vsName, const String& psName)
  997. {
  998. assert(deferredLightPSVariations_.Size());
  999. unsigned vsi = DLVS_NONE;
  1000. unsigned psi = DLPS_NONE;
  1001. Light* light = batch.lightQueue_->light_;
  1002. switch (light->GetLightType())
  1003. {
  1004. case LIGHT_DIRECTIONAL:
  1005. vsi += DLVS_DIR;
  1006. break;
  1007. case LIGHT_SPOT:
  1008. psi += DLPS_SPOT;
  1009. break;
  1010. case LIGHT_POINT:
  1011. if (light->GetShapeTexture())
  1012. psi += DLPS_POINTMASK;
  1013. else
  1014. psi += DLPS_POINT;
  1015. break;
  1016. }
  1017. if (batch.lightQueue_->shadowMap_)
  1018. psi += DLPS_SHADOW;
  1019. if (specularLighting_ && light->GetSpecularIntensity() > 0.0f)
  1020. psi += DLPS_SPEC;
  1021. if (batch.camera_->IsOrthographic())
  1022. {
  1023. vsi += DLVS_ORTHO;
  1024. psi += DLPS_ORTHO;
  1025. }
  1026. batch.vertexShader_ = graphics_->GetShader(VS, vsName, deferredLightVSVariations[vsi]);
  1027. batch.pixelShader_ = graphics_->GetShader(PS, psName, deferredLightPSVariations_[psi]);
  1028. }
  1029. void Renderer::SetCullMode(CullMode mode, Camera* camera)
  1030. {
  1031. // If a camera is specified, check whether it reverses culling due to vertical flipping or reflection
  1032. if (camera && camera->GetReverseCulling())
  1033. {
  1034. if (mode == CULL_CW)
  1035. mode = CULL_CCW;
  1036. else if (mode == CULL_CCW)
  1037. mode = CULL_CW;
  1038. }
  1039. graphics_->SetCullMode(mode);
  1040. }
  1041. bool Renderer::ResizeInstancingBuffer(unsigned numInstances)
  1042. {
  1043. if (!instancingBuffer_ || !dynamicInstancing_)
  1044. return false;
  1045. unsigned oldSize = instancingBuffer_->GetVertexCount();
  1046. if (numInstances <= oldSize)
  1047. return true;
  1048. unsigned newSize = INSTANCING_BUFFER_DEFAULT_SIZE;
  1049. while (newSize < numInstances)
  1050. newSize <<= 1;
  1051. if (!instancingBuffer_->SetSize(newSize, INSTANCING_BUFFER_MASK, true))
  1052. {
  1053. LOGERROR("Failed to resize instancing buffer to " + String(newSize));
  1054. // If failed, try to restore the old size
  1055. instancingBuffer_->SetSize(oldSize, INSTANCING_BUFFER_MASK, true);
  1056. return false;
  1057. }
  1058. LOGDEBUG("Resized instancing buffer to " + String(newSize));
  1059. return true;
  1060. }
  1061. void Renderer::SaveScreenBufferAllocations()
  1062. {
  1063. savedScreenBufferAllocations_ = screenBufferAllocations_;
  1064. }
  1065. void Renderer::RestoreScreenBufferAllocations()
  1066. {
  1067. screenBufferAllocations_ = savedScreenBufferAllocations_;
  1068. }
  1069. void Renderer::OptimizeLightByScissor(Light* light, Camera* camera)
  1070. {
  1071. if (light && light->GetLightType() != LIGHT_DIRECTIONAL)
  1072. graphics_->SetScissorTest(true, GetLightScissor(light, camera));
  1073. else
  1074. graphics_->SetScissorTest(false);
  1075. }
  1076. void Renderer::OptimizeLightByStencil(Light* light, Camera* camera)
  1077. {
  1078. #ifndef GL_ES_VERSION_2_0
  1079. if (light)
  1080. {
  1081. LightType type = light->GetLightType();
  1082. if (type == LIGHT_DIRECTIONAL)
  1083. {
  1084. graphics_->SetStencilTest(false);
  1085. return;
  1086. }
  1087. Geometry* geometry = GetLightGeometry(light);
  1088. const Matrix3x4& view = camera->GetView();
  1089. const Matrix4& projection = camera->GetProjection();
  1090. Vector3 cameraPos = camera->GetNode()->GetWorldPosition();
  1091. float lightDist;
  1092. if (type == LIGHT_POINT)
  1093. lightDist = Sphere(light->GetNode()->GetWorldPosition(), light->GetRange() * 1.25f).Distance(cameraPos);
  1094. else
  1095. lightDist = light->GetFrustum().Distance(cameraPos);
  1096. // If the camera is actually inside the light volume, do not draw to stencil as it would waste fillrate
  1097. if (lightDist < M_EPSILON)
  1098. {
  1099. graphics_->SetStencilTest(false);
  1100. return;
  1101. }
  1102. // If the stencil value has wrapped, clear the whole stencil first
  1103. if (!lightStencilValue_)
  1104. {
  1105. graphics_->Clear(CLEAR_STENCIL);
  1106. lightStencilValue_ = 1;
  1107. }
  1108. // If possible, render the stencil volume front faces. However, close to the near clip plane render back faces instead
  1109. // to avoid clipping.
  1110. if (lightDist < camera->GetNearClip() * 2.0f)
  1111. {
  1112. SetCullMode(CULL_CW, camera);
  1113. graphics_->SetDepthTest(CMP_GREATER);
  1114. }
  1115. else
  1116. {
  1117. SetCullMode(CULL_CCW, camera);
  1118. graphics_->SetDepthTest(CMP_LESSEQUAL);
  1119. }
  1120. graphics_->SetColorWrite(false);
  1121. graphics_->SetDepthWrite(false);
  1122. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, lightStencilValue_);
  1123. graphics_->SetShaders(graphics_->GetShader(VS, "Stencil"), graphics_->GetShader(PS, "Stencil"));
  1124. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection * view);
  1125. graphics_->SetShaderParameter(VSP_MODEL, light->GetVolumeTransform(camera));
  1126. geometry->Draw(graphics_);
  1127. graphics_->ClearTransformSources();
  1128. graphics_->SetColorWrite(true);
  1129. graphics_->SetStencilTest(true, CMP_EQUAL, OP_KEEP, OP_KEEP, OP_KEEP, lightStencilValue_);
  1130. // Increase stencil value for next light
  1131. ++lightStencilValue_;
  1132. }
  1133. else
  1134. graphics_->SetStencilTest(false);
  1135. #endif
  1136. }
  1137. const Rect& Renderer::GetLightScissor(Light* light, Camera* camera)
  1138. {
  1139. Pair<Light*, Camera*> combination(light, camera);
  1140. HashMap<Pair<Light*, Camera*>, Rect>::Iterator i = lightScissorCache_.Find(combination);
  1141. if (i != lightScissorCache_.End())
  1142. return i->second_;
  1143. const Matrix3x4& view = camera->GetView();
  1144. const Matrix4& projection = camera->GetProjection();
  1145. assert(light->GetLightType() != LIGHT_DIRECTIONAL);
  1146. if (light->GetLightType() == LIGHT_SPOT)
  1147. {
  1148. Frustum viewFrustum(light->GetFrustum().Transformed(view));
  1149. return lightScissorCache_[combination] = viewFrustum.Projected(projection);
  1150. }
  1151. else // LIGHT_POINT
  1152. {
  1153. BoundingBox viewBox(light->GetWorldBoundingBox().Transformed(view));
  1154. return lightScissorCache_[combination] = viewBox.Projected(projection);
  1155. }
  1156. }
  1157. void Renderer::PrepareViewRender()
  1158. {
  1159. ResetScreenBufferAllocations();
  1160. lightScissorCache_.Clear();
  1161. lightStencilValue_ = 1;
  1162. }
  1163. void Renderer::RemoveUnusedBuffers()
  1164. {
  1165. for (unsigned i = occlusionBuffers_.Size() - 1; i < occlusionBuffers_.Size(); --i)
  1166. {
  1167. if (occlusionBuffers_[i]->GetUseTimer() > MAX_BUFFER_AGE)
  1168. {
  1169. LOGDEBUG("Removed unused occlusion buffer");
  1170. occlusionBuffers_.Erase(i);
  1171. }
  1172. }
  1173. for (HashMap<long long, Vector<SharedPtr<Texture2D> > >::Iterator i = screenBuffers_.Begin(); i != screenBuffers_.End();)
  1174. {
  1175. HashMap<long long, Vector<SharedPtr<Texture2D> > >::Iterator current = i++;
  1176. Vector<SharedPtr<Texture2D> >& buffers = current->second_;
  1177. for (unsigned j = buffers.Size() - 1; j < buffers.Size(); --j)
  1178. {
  1179. Texture2D* buffer = buffers[j];
  1180. if (buffer->GetUseTimer() > MAX_BUFFER_AGE)
  1181. {
  1182. LOGDEBUG("Removed unused screen buffer size " + String(buffer->GetWidth()) + "x" + String(buffer->GetHeight()) + " format " + String(buffer->GetFormat()));
  1183. buffers.Erase(j);
  1184. }
  1185. }
  1186. if (buffers.Empty())
  1187. {
  1188. screenBufferAllocations_.Erase(current->first_);
  1189. screenBuffers_.Erase(current);
  1190. }
  1191. }
  1192. }
  1193. void Renderer::ResetShadowMapAllocations()
  1194. {
  1195. for (HashMap<int, PODVector<Light*> >::Iterator i = shadowMapAllocations_.Begin(); i != shadowMapAllocations_.End(); ++i)
  1196. i->second_.Clear();
  1197. }
  1198. void Renderer::ResetScreenBufferAllocations()
  1199. {
  1200. for (HashMap<long long, unsigned>::Iterator i = screenBufferAllocations_.Begin(); i != screenBufferAllocations_.End(); ++i)
  1201. i->second_ = 0;
  1202. }
  1203. void Renderer::Initialize()
  1204. {
  1205. Graphics* graphics = GetSubsystem<Graphics>();
  1206. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1207. if (!graphics || !graphics->IsInitialized() || !cache)
  1208. return;
  1209. PROFILE(InitRenderer);
  1210. graphics_ = graphics;
  1211. if (!graphics_->GetShadowMapFormat())
  1212. drawShadows_ = false;
  1213. // Validate the shadow quality level
  1214. SetShadowQuality(shadowQuality_);
  1215. defaultLightRamp_ = cache->GetResource<Texture2D>("Textures/Ramp.png");
  1216. defaultLightSpot_ = cache->GetResource<Texture2D>("Textures/Spot.png");
  1217. defaultMaterial_ = new Material(context_);
  1218. defaultRenderPath_ = new RenderPath();
  1219. defaultRenderPath_->Load(cache->GetResource<XMLFile>("RenderPaths/Forward.xml"));
  1220. CreateGeometries();
  1221. CreateInstancingBuffer();
  1222. viewports_.Resize(1);
  1223. ResetViews();
  1224. ResetShadowMaps();
  1225. ResetBuffers();
  1226. shadersDirty_ = true;
  1227. initialized_ = true;
  1228. SubscribeToEvent(E_RENDERUPDATE, HANDLER(Renderer, HandleRenderUpdate));
  1229. LOGINFO("Initialized renderer");
  1230. }
  1231. void Renderer::ResetViews()
  1232. {
  1233. views_.Clear();
  1234. numViews_ = 0;
  1235. }
  1236. void Renderer::LoadShaders()
  1237. {
  1238. LOGDEBUG("Reloading shaders");
  1239. // Release old material shaders, mark them for reload
  1240. ReleaseMaterialShaders();
  1241. shadersChangedFrameNumber_ = GetSubsystem<Time>()->GetFrameNumber();
  1242. // Construct new names for deferred light volume pixel shaders based on rendering options
  1243. deferredLightPSVariations_.Resize(MAX_DEFERRED_LIGHT_PS_VARIATIONS);
  1244. unsigned shadows = (graphics_->GetHardwareShadowSupport() ? 1 : 0) | (shadowQuality_ & SHADOWQUALITY_HIGH_16BIT);
  1245. for (unsigned i = 0; i < MAX_DEFERRED_LIGHT_PS_VARIATIONS; ++i)
  1246. {
  1247. deferredLightPSVariations_[i] = lightPSVariations[i % DLPS_ORTHO];
  1248. if (i & DLPS_SHADOW)
  1249. deferredLightPSVariations_[i] += shadowVariations[shadows];
  1250. if (i & DLPS_ORTHO)
  1251. deferredLightPSVariations_[i] += "ORTHO";
  1252. }
  1253. shadersDirty_ = false;
  1254. }
  1255. void Renderer::LoadPassShaders(Technique* tech, StringHash type)
  1256. {
  1257. Pass* pass = tech->GetPass(type);
  1258. if (!pass)
  1259. return;
  1260. PROFILE(LoadPassShaders);
  1261. unsigned shadows = (graphics_->GetHardwareShadowSupport() ? 1 : 0) | (shadowQuality_ & SHADOWQUALITY_HIGH_16BIT);
  1262. bool isSM3 = graphics_->GetSM3Support();
  1263. Vector<SharedPtr<ShaderVariation> >& vertexShaders = pass->GetVertexShaders();
  1264. Vector<SharedPtr<ShaderVariation> >& pixelShaders = pass->GetPixelShaders();
  1265. // Forget all the old shaders
  1266. vertexShaders.Clear();
  1267. pixelShaders.Clear();
  1268. if (pass->GetLightingMode() == LIGHTING_PERPIXEL)
  1269. {
  1270. // Load forward pixel lit variations
  1271. vertexShaders.Resize(MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS);
  1272. pixelShaders.Resize(MAX_LIGHT_PS_VARIATIONS * 2);
  1273. for (unsigned j = 0; j < MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS; ++j)
  1274. {
  1275. unsigned g = j / MAX_LIGHT_VS_VARIATIONS;
  1276. unsigned l = j % MAX_LIGHT_VS_VARIATIONS;
  1277. vertexShaders[j] = graphics_->GetShader(VS, pass->GetVertexShader(), pass->GetVertexShaderDefines() + " " +
  1278. lightVSVariations[l] + geometryVSVariations[g]);
  1279. }
  1280. for (unsigned j = 0; j < MAX_LIGHT_PS_VARIATIONS * 2; ++j)
  1281. {
  1282. unsigned l = j % MAX_LIGHT_PS_VARIATIONS;
  1283. unsigned h = j / MAX_LIGHT_PS_VARIATIONS;
  1284. if (l & LPS_SHADOW)
  1285. {
  1286. pixelShaders[j] = graphics_->GetShader(PS, pass->GetPixelShader(), pass->GetPixelShaderDefines() + " " +
  1287. lightPSVariations[l] + shadowVariations[shadows] + heightFogVariations[h]);
  1288. }
  1289. else
  1290. pixelShaders[j] = graphics_->GetShader(PS, pass->GetPixelShader(), pass->GetPixelShaderDefines() + " " +
  1291. lightPSVariations[l] + heightFogVariations[h]);
  1292. }
  1293. }
  1294. else
  1295. {
  1296. // Load vertex light variations
  1297. if (pass->GetLightingMode() == LIGHTING_PERVERTEX)
  1298. {
  1299. vertexShaders.Resize(MAX_GEOMETRYTYPES * MAX_VERTEXLIGHT_VS_VARIATIONS);
  1300. for (unsigned j = 0; j < MAX_GEOMETRYTYPES * MAX_VERTEXLIGHT_VS_VARIATIONS; ++j)
  1301. {
  1302. unsigned g = j / MAX_VERTEXLIGHT_VS_VARIATIONS;
  1303. unsigned l = j % MAX_VERTEXLIGHT_VS_VARIATIONS;
  1304. vertexShaders[j] = graphics_->GetShader(VS, pass->GetVertexShader(), pass->GetVertexShaderDefines() + " " +
  1305. vertexLightVSVariations[l] + geometryVSVariations[g]);
  1306. }
  1307. }
  1308. else
  1309. {
  1310. vertexShaders.Resize(MAX_GEOMETRYTYPES);
  1311. for (unsigned j = 0; j < MAX_GEOMETRYTYPES; ++j)
  1312. {
  1313. vertexShaders[j] = graphics_->GetShader(VS, pass->GetVertexShader(), pass->GetVertexShaderDefines() + " " +
  1314. geometryVSVariations[j]);
  1315. }
  1316. }
  1317. pixelShaders.Resize(2);
  1318. for (unsigned j = 0; j < 2; ++j)
  1319. {
  1320. pixelShaders[j] = graphics_->GetShader(PS, pass->GetPixelShader(), pass->GetPixelShaderDefines() + " " +
  1321. heightFogVariations[j]);
  1322. }
  1323. }
  1324. pass->MarkShadersLoaded(shadersChangedFrameNumber_);
  1325. }
  1326. void Renderer::ReleaseMaterialShaders()
  1327. {
  1328. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1329. PODVector<Material*> materials;
  1330. cache->GetResources<Material>(materials);
  1331. for (unsigned i = 0; i < materials.Size(); ++i)
  1332. materials[i]->ReleaseShaders();
  1333. }
  1334. void Renderer::ReloadTextures()
  1335. {
  1336. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1337. PODVector<Resource*> textures;
  1338. cache->GetResources(textures, Texture2D::GetTypeStatic());
  1339. for (unsigned i = 0; i < textures.Size(); ++i)
  1340. cache->ReloadResource(textures[i]);
  1341. cache->GetResources(textures, TextureCube::GetTypeStatic());
  1342. for (unsigned i = 0; i < textures.Size(); ++i)
  1343. cache->ReloadResource(textures[i]);
  1344. }
  1345. void Renderer::CreateGeometries()
  1346. {
  1347. SharedPtr<VertexBuffer> dlvb(new VertexBuffer(context_));
  1348. dlvb->SetShadowed(true);
  1349. dlvb->SetSize(4, MASK_POSITION);
  1350. dlvb->SetData(dirLightVertexData);
  1351. SharedPtr<IndexBuffer> dlib(new IndexBuffer(context_));
  1352. dlib->SetShadowed(true);
  1353. dlib->SetSize(6, false);
  1354. dlib->SetData(dirLightIndexData);
  1355. dirLightGeometry_ = new Geometry(context_);
  1356. dirLightGeometry_->SetVertexBuffer(0, dlvb);
  1357. dirLightGeometry_->SetIndexBuffer(dlib);
  1358. dirLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, dlib->GetIndexCount());
  1359. SharedPtr<VertexBuffer> slvb(new VertexBuffer(context_));
  1360. slvb->SetShadowed(true);
  1361. slvb->SetSize(8, MASK_POSITION);
  1362. slvb->SetData(spotLightVertexData);
  1363. SharedPtr<IndexBuffer> slib(new IndexBuffer(context_));
  1364. slib->SetShadowed(true);
  1365. slib->SetSize(36, false);
  1366. slib->SetData(spotLightIndexData);
  1367. spotLightGeometry_ = new Geometry(context_);
  1368. spotLightGeometry_->SetVertexBuffer(0, slvb);
  1369. spotLightGeometry_->SetIndexBuffer(slib);
  1370. spotLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, slib->GetIndexCount());
  1371. SharedPtr<VertexBuffer> plvb(new VertexBuffer(context_));
  1372. plvb->SetShadowed(true);
  1373. plvb->SetSize(24, MASK_POSITION);
  1374. plvb->SetData(pointLightVertexData);
  1375. SharedPtr<IndexBuffer> plib(new IndexBuffer(context_));
  1376. plib->SetShadowed(true);
  1377. plib->SetSize(132, false);
  1378. plib->SetData(pointLightIndexData);
  1379. pointLightGeometry_ = new Geometry(context_);
  1380. pointLightGeometry_->SetVertexBuffer(0, plvb);
  1381. pointLightGeometry_->SetIndexBuffer(plib);
  1382. pointLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, plib->GetIndexCount());
  1383. #if !defined(URHO3D_OPENGL) || !defined(GL_ES_VERSION_2_0)
  1384. if (graphics_->GetShadowMapFormat())
  1385. {
  1386. faceSelectCubeMap_ = new TextureCube(context_);
  1387. faceSelectCubeMap_->SetNumLevels(1);
  1388. faceSelectCubeMap_->SetSize(1, graphics_->GetRGBAFormat());
  1389. faceSelectCubeMap_->SetFilterMode(FILTER_NEAREST);
  1390. indirectionCubeMap_ = new TextureCube(context_);
  1391. indirectionCubeMap_->SetNumLevels(1);
  1392. indirectionCubeMap_->SetSize(256, graphics_->GetRGBAFormat());
  1393. indirectionCubeMap_->SetFilterMode(FILTER_BILINEAR);
  1394. indirectionCubeMap_->SetAddressMode(COORD_U, ADDRESS_CLAMP);
  1395. indirectionCubeMap_->SetAddressMode(COORD_V, ADDRESS_CLAMP);
  1396. indirectionCubeMap_->SetAddressMode(COORD_W, ADDRESS_CLAMP);
  1397. SetIndirectionTextureData();
  1398. }
  1399. #endif
  1400. }
  1401. void Renderer::SetIndirectionTextureData()
  1402. {
  1403. unsigned char data[256 * 256 * 4];
  1404. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1405. {
  1406. unsigned axis = i / 2;
  1407. data[0] = (axis == 0) ? 255 : 0;
  1408. data[1] = (axis == 1) ? 255 : 0;
  1409. data[2] = (axis == 2) ? 255 : 0;
  1410. data[3] = 0;
  1411. faceSelectCubeMap_->SetData((CubeMapFace)i, 0, 0, 0, 1, 1, data);
  1412. }
  1413. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1414. {
  1415. unsigned char faceX = (i & 1) * 255;
  1416. unsigned char faceY = (i / 2) * 255 / 3;
  1417. unsigned char* dest = data;
  1418. for (unsigned y = 0; y < 256; ++y)
  1419. {
  1420. for (unsigned x = 0; x < 256; ++x)
  1421. {
  1422. #ifdef URHO3D_OPENGL
  1423. dest[0] = x;
  1424. dest[1] = 255 - y;
  1425. dest[2] = faceX;
  1426. dest[3] = 255 * 2 / 3 - faceY;
  1427. #else
  1428. dest[0] = x;
  1429. dest[1] = y;
  1430. dest[2] = faceX;
  1431. dest[3] = faceY;
  1432. #endif
  1433. dest += 4;
  1434. }
  1435. }
  1436. indirectionCubeMap_->SetData((CubeMapFace)i, 0, 0, 0, 256, 256, data);
  1437. }
  1438. faceSelectCubeMap_->ClearDataLost();
  1439. indirectionCubeMap_->ClearDataLost();
  1440. }
  1441. void Renderer::CreateInstancingBuffer()
  1442. {
  1443. // Do not create buffer if instancing not supported
  1444. if (!graphics_->GetInstancingSupport())
  1445. {
  1446. instancingBuffer_.Reset();
  1447. dynamicInstancing_ = false;
  1448. return;
  1449. }
  1450. // If must lock the buffer for each batch group, set a smaller size
  1451. unsigned defaultSize = graphics_->GetStreamOffsetSupport() ? INSTANCING_BUFFER_DEFAULT_SIZE : INSTANCING_BUFFER_DEFAULT_SIZE / 4;
  1452. instancingBuffer_ = new VertexBuffer(context_);
  1453. if (!instancingBuffer_->SetSize(defaultSize, INSTANCING_BUFFER_MASK, true))
  1454. {
  1455. instancingBuffer_.Reset();
  1456. dynamicInstancing_ = false;
  1457. }
  1458. }
  1459. void Renderer::ResetShadowMaps()
  1460. {
  1461. shadowMaps_.Clear();
  1462. shadowMapAllocations_.Clear();
  1463. colorShadowMaps_.Clear();
  1464. }
  1465. void Renderer::ResetBuffers()
  1466. {
  1467. occlusionBuffers_.Clear();
  1468. screenBuffers_.Clear();
  1469. screenBufferAllocations_.Clear();
  1470. }
  1471. void Renderer::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  1472. {
  1473. if (!initialized_)
  1474. Initialize();
  1475. else
  1476. {
  1477. // When screen mode changes, purge old views
  1478. ResetViews();
  1479. }
  1480. }
  1481. void Renderer::HandleGraphicsFeatures(StringHash eventType, VariantMap& eventData)
  1482. {
  1483. // Reinitialize if already initialized
  1484. if (initialized_)
  1485. Initialize();
  1486. }
  1487. void Renderer::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  1488. {
  1489. using namespace RenderUpdate;
  1490. Update(eventData[P_TIMESTEP].GetFloat());
  1491. }
  1492. }