Renderer.cpp 55 KB

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