Renderer.cpp 55 KB

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