Renderer.cpp 55 KB

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