Renderer.cpp 55 KB

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