Renderer.cpp 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Camera.h"
  25. #include "CoreEvents.h"
  26. #include "DebugRenderer.h"
  27. #include "Geometry.h"
  28. #include "Graphics.h"
  29. #include "GraphicsEvents.h"
  30. #include "GraphicsImpl.h"
  31. #include "IndexBuffer.h"
  32. #include "Light.h"
  33. #include "Log.h"
  34. #include "Material.h"
  35. #include "OcclusionBuffer.h"
  36. #include "Octree.h"
  37. #include "Profiler.h"
  38. #include "Renderer.h"
  39. #include "ResourceCache.h"
  40. #include "Scene.h"
  41. #include "Shader.h"
  42. #include "ShaderVariation.h"
  43. #include "Technique.h"
  44. #include "Texture2D.h"
  45. #include "TextureCube.h"
  46. #include "VertexBuffer.h"
  47. #include "View.h"
  48. #include "XMLFile.h"
  49. #include "Zone.h"
  50. #include "DebugNew.h"
  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 String shadowVariations[] =
  164. {
  165. // No specific hardware shadow compare variation on OpenGL, it is always supported
  166. #ifdef USE_OPENGL
  167. "LQ",
  168. "LQ",
  169. "",
  170. ""
  171. #else
  172. "",
  173. "LQHW",
  174. "",
  175. "HW"
  176. #endif
  177. };
  178. static const String hwVariations[] =
  179. {
  180. "",
  181. "HW"
  182. };
  183. static const String geometryVSVariations[] =
  184. {
  185. "",
  186. "Skinned",
  187. "Instanced",
  188. "Billboard"
  189. };
  190. static const String lightVSVariations[] =
  191. {
  192. "Dir",
  193. "Spot",
  194. "Point",
  195. "DirSpec",
  196. "SpotSpec",
  197. "PointSpec",
  198. "DirShadow",
  199. "SpotShadow",
  200. "PointShadow",
  201. "DirSpecShadow",
  202. "SpotSpecShadow",
  203. "PointSpecShadow"
  204. };
  205. static const String vertexLightVSVariations[] =
  206. {
  207. "",
  208. "1VL",
  209. "2VL",
  210. "3VL",
  211. "4VL",
  212. "5VL",
  213. "6VL"
  214. };
  215. static const String deferredLightVSVariations[] =
  216. {
  217. "",
  218. "Dir",
  219. "Ortho",
  220. "OrthoDir"
  221. };
  222. static const String lightPSVariations[] =
  223. {
  224. "Dir",
  225. "Spot",
  226. "Point",
  227. "PointMask",
  228. "DirSpec",
  229. "SpotSpec",
  230. "PointSpec",
  231. "PointMaskSpec",
  232. "DirShadow",
  233. "SpotShadow",
  234. "PointShadow",
  235. "PointMaskShadow",
  236. "DirSpecShadow",
  237. "SpotSpecShadow",
  238. "PointSpecShadow",
  239. "PointMaskSpecShadow"
  240. };
  241. static const unsigned INSTANCING_BUFFER_MASK = MASK_INSTANCEMATRIX1 | MASK_INSTANCEMATRIX2 | MASK_INSTANCEMATRIX3;
  242. static const Viewport noViewport;
  243. void EdgeFilterParameters::Validate()
  244. {
  245. radius_ = Max(radius_, 0.0f);
  246. threshold_ = Max(threshold_, 0.0f);
  247. strength_ = Max(strength_, 0.0f);
  248. }
  249. OBJECTTYPESTATIC(Renderer);
  250. Renderer::Renderer(Context* context) :
  251. Object(context),
  252. defaultZone_(new Zone(context)),
  253. edgeFilterParameters_(EdgeFilterParameters(0.4f, 0.5f, 0.9f)),
  254. numViews_(0),
  255. numShadowCameras_(0),
  256. numOcclusionBuffers_(0),
  257. textureAnisotropy_(4),
  258. textureFilterMode_(FILTER_TRILINEAR),
  259. textureQuality_(QUALITY_HIGH),
  260. materialQuality_(QUALITY_HIGH),
  261. shadowMapSize_(1024),
  262. shadowQuality_(SHADOWQUALITY_HIGH_16BIT),
  263. maxShadowMaps_(1),
  264. maxShadowCascades_(MAX_CASCADE_SPLITS),
  265. maxInstanceTriangles_(500),
  266. maxOccluderTriangles_(5000),
  267. occlusionBufferSize_(256),
  268. occluderSizeThreshold_(0.1f),
  269. shadersChangedFrameNumber_(M_MAX_UNSIGNED),
  270. lightPrepass_(false),
  271. specularLighting_(true),
  272. drawShadows_(true),
  273. reuseShadowMaps_(true),
  274. dynamicInstancing_(true),
  275. edgeFilter_(false),
  276. shadersDirty_(true),
  277. initialized_(false)
  278. {
  279. SubscribeToEvent(E_SCREENMODE, HANDLER(Renderer, HandleScreenMode));
  280. SubscribeToEvent(E_GRAPHICSFEATURES, HANDLER(Renderer, HandleGraphicsFeatures));
  281. SubscribeToEvent(E_RENDERUPDATE, HANDLER(Renderer, HandleRenderUpdate));
  282. // Try to initialize right now, but skip if screen mode is not yet set
  283. Initialize();
  284. }
  285. Renderer::~Renderer()
  286. {
  287. }
  288. void Renderer::SetNumViewports(unsigned num)
  289. {
  290. viewports_.Resize(num);
  291. }
  292. void Renderer::SetViewport(unsigned index, const Viewport& viewport)
  293. {
  294. if (index >= viewports_.Size())
  295. {
  296. LOGERROR("Viewport index out of bounds");
  297. return;
  298. }
  299. viewports_[index] = viewport;
  300. }
  301. void Renderer::SetLightPrepass(bool enable)
  302. {
  303. if (!initialized_)
  304. {
  305. LOGERROR("Can not switch light pre-pass rendering before setting initial screen mode");
  306. return;
  307. }
  308. if (!graphics_->GetLightPrepassSupport())
  309. enable = false;
  310. if (enable != lightPrepass_)
  311. {
  312. // Light prepass is incompatible with hardware multisampling, so set new screen mode with 1x sampling if in use
  313. if (graphics_->GetMultiSample() > 1)
  314. {
  315. graphics_->SetMode(graphics_->GetWidth(), graphics_->GetHeight(), graphics_->GetFullscreen(), graphics_->GetVSync(),
  316. graphics_->GetTripleBuffer(), 1);
  317. }
  318. lightPrepass_ = enable;
  319. shadersDirty_ = true;
  320. }
  321. }
  322. void Renderer::SetSpecularLighting(bool enable)
  323. {
  324. specularLighting_ = enable;
  325. }
  326. void Renderer::SetTextureAnisotropy(int level)
  327. {
  328. textureAnisotropy_ = Max(level, 1);
  329. }
  330. void Renderer::SetTextureFilterMode(TextureFilterMode mode)
  331. {
  332. textureFilterMode_ = mode;
  333. }
  334. void Renderer::SetTextureQuality(int quality)
  335. {
  336. quality = Clamp(quality, QUALITY_LOW, QUALITY_HIGH);
  337. if (quality != textureQuality_)
  338. {
  339. textureQuality_ = quality;
  340. ReloadTextures();
  341. }
  342. }
  343. void Renderer::SetMaterialQuality(int quality)
  344. {
  345. materialQuality_ = Clamp(quality, QUALITY_LOW, QUALITY_MAX);
  346. shadersDirty_ = true;
  347. ResetViews();
  348. }
  349. void Renderer::SetDrawShadows(bool enable)
  350. {
  351. if (!graphics_ || !graphics_->GetShadowMapFormat())
  352. return;
  353. drawShadows_ = enable;
  354. if (!drawShadows_)
  355. ResetShadowMaps();
  356. }
  357. void Renderer::SetShadowMapSize(int size)
  358. {
  359. if (!graphics_)
  360. return;
  361. size = NextPowerOfTwo(Max(size, SHADOW_MIN_PIXELS));
  362. if (size != shadowMapSize_)
  363. {
  364. shadowMapSize_ = size;
  365. ResetShadowMaps();
  366. }
  367. }
  368. void Renderer::SetShadowQuality(int quality)
  369. {
  370. if (!graphics_)
  371. return;
  372. quality &= SHADOWQUALITY_HIGH_24BIT;
  373. // If no hardware PCF, do not allow to select one-sample quality
  374. if (!graphics_->GetHardwareShadowSupport())
  375. quality |= SHADOWQUALITY_HIGH_16BIT;
  376. if (!graphics_->GetHiresShadowSupport())
  377. quality &= SHADOWQUALITY_HIGH_16BIT;
  378. if (quality != shadowQuality_)
  379. {
  380. shadowQuality_ = quality;
  381. shadersDirty_ = true;
  382. ResetShadowMaps();
  383. }
  384. }
  385. void Renderer::SetReuseShadowMaps(bool enable)
  386. {
  387. if (enable == reuseShadowMaps_)
  388. return;
  389. reuseShadowMaps_ = enable;
  390. }
  391. void Renderer::SetMaxShadowMaps(int shadowMaps)
  392. {
  393. if (shadowMaps < 1)
  394. return;
  395. maxShadowMaps_ = shadowMaps;
  396. for (HashMap<int, Vector<SharedPtr<Texture2D> > >::Iterator i = shadowMaps_.Begin(); i != shadowMaps_.End(); ++i)
  397. {
  398. if ((int)i->second_.Size() > maxShadowMaps_)
  399. i->second_.Resize(maxShadowMaps_);
  400. }
  401. }
  402. void Renderer::SetMaxShadowCascades(int cascades)
  403. {
  404. cascades = Clamp(cascades, 1, MAX_CASCADE_SPLITS);
  405. if (cascades != maxShadowCascades_)
  406. {
  407. maxShadowCascades_ = cascades;
  408. ResetShadowMaps();
  409. }
  410. }
  411. void Renderer::SetDynamicInstancing(bool enable)
  412. {
  413. if (!instancingBuffer_)
  414. enable = false;
  415. dynamicInstancing_ = enable;
  416. }
  417. void Renderer::SetMaxInstanceTriangles(int triangles)
  418. {
  419. maxInstanceTriangles_ = Max(triangles, 0);
  420. }
  421. void Renderer::SetEdgeFilter(bool enable)
  422. {
  423. if (enable)
  424. {
  425. // Edge filter is incompatible with hardware multisampling, so set new screen mode with 1x sampling if in use
  426. if (graphics_->GetMultiSample() > 1)
  427. {
  428. graphics_->SetMode(graphics_->GetWidth(), graphics_->GetHeight(), graphics_->GetFullscreen(), graphics_->GetVSync(),
  429. graphics_->GetTripleBuffer(), 1);
  430. }
  431. }
  432. edgeFilter_ = enable;
  433. }
  434. void Renderer::SetEdgeFilterParameters(const EdgeFilterParameters& parameters)
  435. {
  436. edgeFilterParameters_ = parameters;
  437. edgeFilterParameters_.Validate();
  438. }
  439. void Renderer::SetMaxOccluderTriangles(int triangles)
  440. {
  441. maxOccluderTriangles_ = Max(triangles, 0);
  442. }
  443. void Renderer::SetOcclusionBufferSize(int size)
  444. {
  445. occlusionBufferSize_ = Max(size, 1);
  446. occlusionBuffers_.Clear();
  447. }
  448. void Renderer::SetOccluderSizeThreshold(float screenSize)
  449. {
  450. occluderSizeThreshold_ = Max(screenSize, 0.0f);
  451. }
  452. const Viewport& Renderer::GetViewport(unsigned index) const
  453. {
  454. return index < viewports_.Size() ? viewports_[index] : noViewport;
  455. }
  456. ShaderVariation* Renderer::GetVertexShader(const String& name, bool checkExists) const
  457. {
  458. return GetShader(name, vsFormat_, checkExists);
  459. }
  460. ShaderVariation* Renderer::GetPixelShader(const String& name, bool checkExists) const
  461. {
  462. return GetShader(name, psFormat_, checkExists);
  463. }
  464. unsigned Renderer::GetNumGeometries(bool allViews) const
  465. {
  466. unsigned numGeometries = 0;
  467. unsigned lastView = allViews ? numViews_ : 1;
  468. for (unsigned i = 0; i < lastView; ++i)
  469. numGeometries += views_[i]->GetGeometries().Size();
  470. return numGeometries;
  471. }
  472. unsigned Renderer::GetNumLights(bool allViews) const
  473. {
  474. unsigned numLights = 0;
  475. unsigned lastView = allViews ? numViews_ : 1;
  476. for (unsigned i = 0; i < lastView; ++i)
  477. numLights += views_[i]->GetLights().Size();
  478. return numLights;
  479. }
  480. unsigned Renderer::GetNumShadowMaps(bool allViews) const
  481. {
  482. unsigned numShadowMaps = 0;
  483. unsigned lastView = allViews ? numViews_ : 1;
  484. for (unsigned i = 0; i < lastView; ++i)
  485. {
  486. const List<LightBatchQueue>& lightQueues = views_[i]->GetLightQueues();
  487. for (List<LightBatchQueue>::ConstIterator i = lightQueues.Begin(); i != lightQueues.End(); ++i)
  488. {
  489. if (i->shadowMap_)
  490. ++numShadowMaps;
  491. }
  492. }
  493. return numShadowMaps;
  494. }
  495. unsigned Renderer::GetNumOccluders(bool allViews) const
  496. {
  497. unsigned numOccluders = 0;
  498. unsigned lastView = allViews ? numViews_ : 1;
  499. for (unsigned i = 0; i < lastView; ++i)
  500. numOccluders += views_[i]->GetOccluders().Size();
  501. return numOccluders;
  502. }
  503. void Renderer::Update(float timeStep)
  504. {
  505. PROFILE(UpdateViews);
  506. numViews_ = 0;
  507. // If device lost, do not perform update. This is because any dynamic vertex/index buffer updates happen already here,
  508. // and if the device is lost, the updates queue up, causing memory use to rise constantly
  509. if (!graphics_ || !graphics_->IsInitialized() || graphics_->IsDeviceLost())
  510. return;
  511. // Set up the frameinfo structure for this frame
  512. frame_.frameNumber_ = GetSubsystem<Time>()->GetFrameNumber();
  513. frame_.timeStep_ = timeStep;
  514. frame_.camera_ = 0;
  515. numShadowCameras_ = 0;
  516. numOcclusionBuffers_ = 0;
  517. updatedOctrees_.Clear();
  518. // Reload shaders now if needed
  519. if (shadersDirty_)
  520. LoadShaders();
  521. // Process all viewports. Use reverse order, because during rendering the order will be reversed again
  522. // to handle auxiliary view dependencies correctly
  523. for (unsigned i = viewports_.Size() - 1; i < viewports_.Size(); --i)
  524. {
  525. unsigned mainView = numViews_;
  526. Viewport& viewport = viewports_[i];
  527. if (!AddView(0, viewport))
  528. continue;
  529. // Update octree (perform early update for drawables which need that, and reinsert moved drawables.)
  530. // However, if the same scene is viewed from multiple cameras, update the octree only once
  531. Octree* octree = viewport.scene_->GetComponent<Octree>();
  532. if (!updatedOctrees_.Contains(octree))
  533. {
  534. frame_.camera_ = viewport.camera_;
  535. frame_.viewSize_ = IntVector2(viewport.rect_.right_ - viewport.rect_.left_, viewport.rect_.bottom_ - viewport.rect_.top_);
  536. if (frame_.viewSize_ == IntVector2::ZERO)
  537. frame_.viewSize_ = IntVector2(graphics_->GetWidth(), graphics_->GetHeight());
  538. octree->Update(frame_);
  539. updatedOctrees_.Insert(octree);
  540. // Set also the view for the debug graphics already here, so that it can use culling
  541. /// \todo May result in incorrect debug geometry culling if the same scene is drawn from multiple viewports
  542. DebugRenderer* debug = viewport.scene_->GetComponent<DebugRenderer>();
  543. if (debug)
  544. debug->SetView(viewport.camera_);
  545. }
  546. // Update the viewport's main view and any auxiliary views it has created
  547. for (unsigned i = mainView; i < numViews_; ++i)
  548. {
  549. // Reset shadow map allocations; they can be reused between views as each is rendered completely at a time
  550. ResetShadowMapAllocations();
  551. views_[i]->Update(frame_);
  552. }
  553. }
  554. }
  555. void Renderer::Render()
  556. {
  557. if (!graphics_)
  558. return;
  559. PROFILE(RenderViews);
  560. // Remove unused buffers from last frame
  561. ResetRenderBufferAllocations(true);
  562. graphics_->SetDefaultTextureFilterMode(textureFilterMode_);
  563. graphics_->SetTextureAnisotropy(textureAnisotropy_);
  564. // If no views, just clear the screen
  565. if (!numViews_)
  566. {
  567. numPrimitives_ = 0;
  568. numBatches_ = 0;
  569. graphics_->SetAlphaTest(false);
  570. graphics_->SetBlendMode(BLEND_REPLACE);
  571. graphics_->SetColorWrite(true);
  572. graphics_->SetDepthWrite(true);
  573. graphics_->SetFillMode(FILL_SOLID);
  574. graphics_->SetScissorTest(false);
  575. graphics_->SetStencilTest(false);
  576. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH | CLEAR_STENCIL);
  577. return;
  578. }
  579. // Render views from last to first (each main view is rendered after the auxiliary views it depends on)
  580. for (unsigned i = numViews_ - 1; i < numViews_; --i)
  581. {
  582. // Buffers can be reused between views, as each is rendered completely
  583. ResetRenderBufferAllocations();
  584. views_[i]->Render();
  585. }
  586. // Copy the number of batches & primitives from Graphics so that we can account for 3D geometry only
  587. numPrimitives_ = graphics_->GetNumPrimitives();
  588. numBatches_ = graphics_->GetNumBatches();
  589. }
  590. void Renderer::DrawDebugGeometry(bool depthTest)
  591. {
  592. PROFILE(RendererDrawDebug);
  593. /// \todo Because debug geometry is per-scene, if two cameras show views of the same area, occlusion is not shown correctly
  594. HashSet<Drawable*> processedGeometries;
  595. HashSet<Light*> processedLights;
  596. for (unsigned i = 0; i < numViews_; ++i)
  597. {
  598. // Make sure it's a main view, and process each node only once
  599. View* view = views_[i];
  600. if (view->GetRenderTarget())
  601. continue;
  602. Octree* octree = view->GetOctree();
  603. if (!octree)
  604. continue;
  605. Scene* scene = static_cast<Scene*>(octree->GetNode());
  606. if (!scene)
  607. continue;
  608. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  609. if (!debug)
  610. continue;
  611. const PODVector<Drawable*>& geometries = view->GetGeometries();
  612. const PODVector<Light*>& lights = view->GetLights();
  613. for (unsigned i = 0; i < geometries.Size(); ++i)
  614. {
  615. if (!processedGeometries.Contains(geometries[i]))
  616. {
  617. geometries[i]->DrawDebugGeometry(debug, depthTest);
  618. processedGeometries.Insert(geometries[i]);
  619. }
  620. }
  621. for (unsigned i = 0; i < lights.Size(); ++i)
  622. {
  623. if (!processedLights.Contains(lights[i]))
  624. {
  625. lights[i]->DrawDebugGeometry(debug, depthTest);
  626. processedLights.Insert(lights[i]);
  627. }
  628. }
  629. }
  630. }
  631. bool Renderer::AddView(RenderSurface* renderTarget, const Viewport& viewport)
  632. {
  633. // If using a rendertarget texture, make sure it will not be rendered to multiple times
  634. if (renderTarget)
  635. {
  636. for (unsigned i = 0; i < numViews_; ++i)
  637. {
  638. if (views_[i]->GetRenderTarget() == renderTarget)
  639. return false;
  640. }
  641. }
  642. if (views_.Size() <= numViews_)
  643. views_.Resize(numViews_ + 1);
  644. if (!views_[numViews_])
  645. views_[numViews_] = new View(context_);
  646. if (views_[numViews_]->Define(renderTarget, viewport))
  647. {
  648. ++numViews_;
  649. return true;
  650. }
  651. else
  652. return false;
  653. }
  654. Geometry* Renderer::GetLightGeometry(Light* light)
  655. {
  656. LightType type = light->GetLightType();
  657. if (type == LIGHT_DIRECTIONAL)
  658. return dirLightGeometry_;
  659. if (type == LIGHT_SPOT)
  660. return spotLightGeometry_;
  661. else if (type == LIGHT_POINT)
  662. return pointLightGeometry_;
  663. else
  664. return 0;
  665. }
  666. Texture2D* Renderer::GetShadowMap(Light* light, Camera* camera, unsigned viewWidth, unsigned viewHeight)
  667. {
  668. LightType type = light->GetLightType();
  669. const FocusParameters& parameters = light->GetShadowFocus();
  670. float size = (float)shadowMapSize_ * light->GetShadowResolution();
  671. // Automatically reduce shadow map size when far away
  672. if (parameters.autoSize_ && type != LIGHT_DIRECTIONAL)
  673. {
  674. Matrix3x4 view(camera->GetInverseWorldTransform());
  675. Matrix4 projection(camera->GetProjection());
  676. BoundingBox lightBox;
  677. float lightPixels;
  678. if (type == LIGHT_POINT)
  679. {
  680. // Calculate point light pixel size from the projection of its diagonal
  681. Vector3 center = view * light->GetWorldPosition();
  682. float extent = 0.58f * light->GetRange();
  683. lightBox.Define(center + Vector3(extent, extent, extent), center - Vector3(extent, extent, extent));
  684. }
  685. else
  686. {
  687. // Calculate spot light pixel size from the projection of its frustum far vertices
  688. Frustum lightFrustum = light->GetFrustum().Transformed(view);
  689. lightBox.Define(&lightFrustum.vertices_[4], 4);
  690. }
  691. Vector2 projectionSize = lightBox.Projected(projection).Size();
  692. lightPixels = Max(0.5f * (float)viewWidth * projectionSize.x_, 0.5f * (float)viewHeight * projectionSize.y_);
  693. // Clamp pixel amount to a sufficient minimum to avoid self-shadowing artifacts due to loss of precision
  694. if (lightPixels < SHADOW_MIN_PIXELS)
  695. lightPixels = SHADOW_MIN_PIXELS;
  696. size = Min(size, lightPixels);
  697. }
  698. /// \todo Allow to specify maximum shadow maps per resolution, as smaller shadow maps take less memory
  699. int width = NextPowerOfTwo((unsigned)size);
  700. int height = width;
  701. // Adjust the size for directional or point light shadow map atlases
  702. if (type == LIGHT_DIRECTIONAL)
  703. {
  704. if (maxShadowCascades_ > 1)
  705. width *= 2;
  706. if (maxShadowCascades_ > 2)
  707. height *= 2;
  708. }
  709. else if (type == LIGHT_POINT)
  710. {
  711. width *= 2;
  712. height *= 3;
  713. }
  714. int searchKey = (width << 16) | height;
  715. if (shadowMaps_.Contains(searchKey))
  716. {
  717. // If shadow maps are reused, always return the first
  718. if (reuseShadowMaps_)
  719. return shadowMaps_[searchKey][0];
  720. else
  721. {
  722. // If not reused, check allocation count and return existing shadow map if possible
  723. unsigned allocated = shadowMapAllocations_[searchKey].Size();
  724. if (allocated < shadowMaps_[searchKey].Size())
  725. {
  726. shadowMapAllocations_[searchKey].Push(light);
  727. return shadowMaps_[searchKey][allocated];
  728. }
  729. else if ((int)allocated >= maxShadowMaps_)
  730. return 0;
  731. }
  732. }
  733. unsigned shadowMapFormat = (shadowQuality_ & SHADOWQUALITY_LOW_24BIT) ? graphics_->GetHiresShadowMapFormat() :
  734. graphics_->GetShadowMapFormat();
  735. unsigned dummyColorFormat = graphics_->GetDummyColorFormat();
  736. if (!shadowMapFormat)
  737. return 0;
  738. SharedPtr<Texture2D> newShadowMap(new Texture2D(context_));
  739. int retries = 3;
  740. #ifdef USE_OPENGL
  741. // Create shadow map only. Color rendertarget is not needed
  742. while (retries)
  743. {
  744. if (!newShadowMap->SetSize(width, height, shadowMapFormat, TEXTURE_DEPTHSTENCIL))
  745. {
  746. width >>= 1;
  747. height >>= 1;
  748. --retries;
  749. }
  750. else
  751. {
  752. newShadowMap->SetFilterMode(FILTER_BILINEAR);
  753. newShadowMap->SetShadowCompare(true);
  754. break;
  755. }
  756. }
  757. #else
  758. // Create shadow map and dummy color rendertarget
  759. while (retries)
  760. {
  761. if (!newShadowMap->SetSize(width, height, shadowMapFormat, TEXTURE_DEPTHSTENCIL))
  762. {
  763. width >>= 1;
  764. height >>= 1;
  765. --retries;
  766. }
  767. else
  768. {
  769. newShadowMap->SetFilterMode(FILTER_BILINEAR);
  770. // If no dummy color rendertarget for this size exists yet, create one now
  771. if (!colorShadowMaps_.Contains(searchKey))
  772. {
  773. colorShadowMaps_[searchKey] = new Texture2D(context_);
  774. colorShadowMaps_[searchKey]->SetSize(width, height, dummyColorFormat, TEXTURE_RENDERTARGET);
  775. }
  776. // Link the color rendertarget to the shadow map
  777. newShadowMap->GetRenderSurface()->SetLinkedRenderTarget(colorShadowMaps_[searchKey]->GetRenderSurface());
  778. break;
  779. }
  780. }
  781. #endif
  782. // If failed to set size, store a null pointer so that we will not retry
  783. if (!retries)
  784. newShadowMap.Reset();
  785. shadowMaps_[searchKey].Push(newShadowMap);
  786. if (!reuseShadowMaps_)
  787. shadowMapAllocations_[searchKey].Push(light);
  788. return newShadowMap;
  789. }
  790. Texture2D* Renderer::GetRenderBuffer(int width, int height, unsigned format, bool filtered)
  791. {
  792. if (!width)
  793. width = graphics_->GetWidth();
  794. if (!height)
  795. height = graphics_->GetHeight();
  796. bool depthStencil = (format == Graphics::GetDepthStencilFormat());
  797. if (depthStencil)
  798. filtered = false;
  799. long long searchKey = ((long long)format << 32) | (width << 16) | height;
  800. if (filtered)
  801. searchKey |= 0x8000000000000000LL;
  802. // Return the default depth-stencil if applicable
  803. if (width <= graphics_->GetWidth() && height <= graphics_->GetHeight() && depthStencil)
  804. return graphics_->GetDepthTexture();
  805. bool needNew = false;
  806. // If new size or format, initialize the allocation stats
  807. if (renderBuffers_.Find(searchKey) == renderBuffers_.End())
  808. {
  809. renderBufferAllocations_[searchKey] = 0;
  810. renderBufferMaxAllocations_[searchKey] = 0;
  811. }
  812. unsigned& allocations = renderBufferAllocations_[searchKey];
  813. unsigned& maxAllocations = renderBufferMaxAllocations_[searchKey];
  814. ++allocations;
  815. if (allocations > maxAllocations)
  816. maxAllocations = allocations;
  817. if (allocations > renderBuffers_[searchKey].Size())
  818. {
  819. SharedPtr<Texture2D> newBuffer(new Texture2D(context_));
  820. newBuffer->SetSize(width, height, format, depthStencil ? TEXTURE_DEPTHSTENCIL : TEXTURE_RENDERTARGET);
  821. if (filtered)
  822. newBuffer->SetFilterMode(FILTER_BILINEAR);
  823. renderBuffers_[searchKey].Push(newBuffer);
  824. LOGDEBUG("Allocated new renderbuffer, size " + String(width) + "x" + String(height) + " format " + String(format));
  825. return newBuffer;
  826. }
  827. else
  828. return renderBuffers_[searchKey][allocations - 1];
  829. }
  830. RenderSurface* Renderer::GetDepthStencil(int width, int height)
  831. {
  832. // GetRenderBuffer() may return 0 if using the default depth-stencil, so watch out
  833. Texture2D* depthTexture = GetRenderBuffer(width, height, Graphics::GetDepthStencilFormat());
  834. return depthTexture ? depthTexture->GetRenderSurface() : 0;
  835. }
  836. OcclusionBuffer* Renderer::GetOcclusionBuffer(Camera* camera)
  837. {
  838. if (numOcclusionBuffers_ >= occlusionBuffers_.Size())
  839. {
  840. SharedPtr<OcclusionBuffer> newBuffer(new OcclusionBuffer(context_));
  841. occlusionBuffers_.Push(newBuffer);
  842. }
  843. int width = occlusionBufferSize_;
  844. int height = (int)((float)occlusionBufferSize_ / camera->GetAspectRatio() + 0.5f);
  845. OcclusionBuffer* buffer = occlusionBuffers_[numOcclusionBuffers_];
  846. buffer->SetSize(width, height);
  847. buffer->SetView(camera);
  848. ++numOcclusionBuffers_;
  849. return buffer;
  850. }
  851. Camera* Renderer::GetShadowCamera()
  852. {
  853. MutexLock lock(rendererMutex_);
  854. if (numShadowCameras_ >= shadowCameraNodes_.Size())
  855. {
  856. SharedPtr<Node> newNode(new Node(context_));
  857. newNode->CreateComponent<Camera>();
  858. shadowCameraNodes_.Push(newNode);
  859. }
  860. Camera* camera = shadowCameraNodes_[numShadowCameras_]->GetComponent<Camera>();
  861. camera->SetOrthographic(false);
  862. camera->SetZoom(1.0f);
  863. ++numShadowCameras_;
  864. return camera;
  865. }
  866. ShaderVariation* Renderer::GetShader(const String& name, const String& extension, bool checkExists) const
  867. {
  868. String shaderName = shaderPath_;
  869. String variationName;
  870. unsigned split = name.Find('_');
  871. if (split != String::NPOS)
  872. {
  873. shaderName += name.Substring(0, split) + extension;
  874. variationName = name.Substring(split + 1);
  875. }
  876. else
  877. shaderName += name + extension;
  878. if (checkExists)
  879. {
  880. if (!cache_->Exists(shaderName))
  881. return 0;
  882. }
  883. Shader* shader = cache_->GetResource<Shader>(shaderName);
  884. if (shader)
  885. return shader->GetVariation(variationName);
  886. else
  887. return 0;
  888. }
  889. void Renderer::SetBatchShaders(Batch& batch, Technique* technique, Pass* pass, bool allowShadows)
  890. {
  891. // Check if shaders are unloaded or need reloading
  892. Vector<SharedPtr<ShaderVariation> >& vertexShaders = pass->GetVertexShaders();
  893. Vector<SharedPtr<ShaderVariation> >& pixelShaders = pass->GetPixelShaders();
  894. if (!vertexShaders.Size() || !pixelShaders.Size() || technique->GetShadersLoadedFrameNumber() !=
  895. shadersChangedFrameNumber_)
  896. {
  897. // First release all previous shaders, then load
  898. technique->ReleaseShaders();
  899. LoadMaterialShaders(technique);
  900. }
  901. // Make sure shaders are loaded now
  902. if (vertexShaders.Size() && pixelShaders.Size())
  903. {
  904. GeometryType geomType = batch.geometryType_;
  905. // If instancing is not supported, but was requested, or the object is too large to be instanced,
  906. // choose static geometry vertex shader instead
  907. if (geomType == GEOM_INSTANCED && (!GetDynamicInstancing() || batch.geometry_->GetIndexCount() >
  908. (unsigned)maxInstanceTriangles_ * 3))
  909. geomType = GEOM_STATIC;
  910. // Check whether is a pixel lit forward pass. If not, there is only one pixel shader
  911. PassType type = pass->GetType();
  912. if (type == PASS_LIGHT || type == PASS_LITBASE)
  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 = geomType * MAX_LIGHT_VS_VARIATIONS;
  926. bool materialHasSpecular = batch.material_ ? batch.material_->GetSpecular() : true;
  927. if (specularLighting_ && light->GetSpecularIntensity() > 0.0f && materialHasSpecular)
  928. {
  929. vsi += LVS_SPEC;
  930. psi += LPS_SPEC;
  931. }
  932. if (allowShadows && lightQueue->shadowMap_)
  933. {
  934. vsi += LVS_SHADOW;
  935. psi += LPS_SHADOW;
  936. }
  937. switch (light->GetLightType())
  938. {
  939. case LIGHT_DIRECTIONAL:
  940. vsi += LVS_DIR;
  941. break;
  942. case LIGHT_POINT:
  943. if (light->GetShapeTexture())
  944. psi += LPS_POINTMASK;
  945. else
  946. psi += LPS_POINT;
  947. vsi += LVS_POINT;
  948. break;
  949. case LIGHT_SPOT:
  950. psi += LPS_SPOT;
  951. vsi += LVS_SPOT;
  952. break;
  953. }
  954. batch.vertexShader_ = vertexShaders[vsi];
  955. batch.pixelShader_ = pixelShaders[psi];
  956. // If shadow or specular variations do not exist, try without them
  957. if ((!batch.vertexShader_ || !batch.pixelShader_) && (vsi >= LVS_SHADOW))
  958. {
  959. vsi -= LVS_SHADOW;
  960. psi -= LPS_SHADOW;
  961. batch.vertexShader_ = vertexShaders[vsi];
  962. batch.pixelShader_ = pixelShaders[psi];
  963. }
  964. if ((!batch.vertexShader_ || !batch.pixelShader_) && (vsi >= LVS_SPEC))
  965. {
  966. vsi -= LVS_SPEC;
  967. psi -= LPS_SPEC;
  968. batch.vertexShader_ = vertexShaders[vsi];
  969. batch.pixelShader_ = pixelShaders[psi];
  970. }
  971. }
  972. else
  973. {
  974. if (type == PASS_BASE || type == PASS_MATERIAL)
  975. {
  976. unsigned numVertexLights = 0;
  977. if (batch.lightQueue_)
  978. numVertexLights = batch.lightQueue_->vertexLights_.Size();
  979. unsigned vsi = geomType * MAX_VERTEXLIGHT_VS_VARIATIONS + numVertexLights;
  980. batch.vertexShader_ = vertexShaders[vsi];
  981. // If vertex lights variations do not exist, try without them
  982. if (!batch.vertexShader_)
  983. {
  984. unsigned vsi = geomType * MAX_VERTEXLIGHT_VS_VARIATIONS;
  985. batch.vertexShader_ = vertexShaders[vsi];
  986. }
  987. }
  988. else
  989. {
  990. unsigned vsi = geomType;
  991. batch.vertexShader_ = vertexShaders[vsi];
  992. }
  993. batch.pixelShader_ = pixelShaders[0];
  994. }
  995. }
  996. // Log error if shaders could not be assigned, but only once per technique
  997. if (!batch.vertexShader_ || !batch.pixelShader_)
  998. {
  999. if (!shaderErrorDisplayed_.Contains(technique))
  1000. {
  1001. shaderErrorDisplayed_.Insert(technique);
  1002. LOGERROR("Technique " + technique->GetName() + " has missing shaders");
  1003. }
  1004. }
  1005. }
  1006. void Renderer::SetLightVolumeBatchShaders(Batch& batch)
  1007. {
  1008. unsigned vsi = DLVS_NONE;
  1009. unsigned psi = DLPS_NONE;
  1010. Light* light = batch.lightQueue_->light_;
  1011. switch (light->GetLightType())
  1012. {
  1013. case LIGHT_DIRECTIONAL:
  1014. vsi += DLVS_DIR;
  1015. break;
  1016. case LIGHT_POINT:
  1017. if (light->GetShapeTexture())
  1018. psi += DLPS_POINTMASK;
  1019. else
  1020. psi += DLPS_POINT;
  1021. break;
  1022. case LIGHT_SPOT:
  1023. psi += DLPS_SPOT;
  1024. break;
  1025. }
  1026. if (batch.lightQueue_->shadowMap_)
  1027. psi += DLPS_SHADOW;
  1028. if (specularLighting_ && light->GetSpecularIntensity() > 0.0f)
  1029. psi += DLPS_SPEC;
  1030. if (batch.camera_->IsOrthographic())
  1031. {
  1032. vsi += DLVS_ORTHO;
  1033. psi += DLPS_ORTHO;
  1034. }
  1035. batch.vertexShader_ = lightVS_[vsi];
  1036. batch.pixelShader_ = lightPS_[psi];
  1037. }
  1038. void Renderer::SetCullMode(CullMode mode, Camera* camera)
  1039. {
  1040. // If a camera is specified, check for vertical flipping and reverse culling in that case
  1041. if (camera && camera->GetFlipVertical())
  1042. {
  1043. if (mode == CULL_CW)
  1044. mode = CULL_CCW;
  1045. else if (mode == CULL_CCW)
  1046. mode = CULL_CW;
  1047. }
  1048. graphics_->SetCullMode(mode);
  1049. }
  1050. bool Renderer::ResizeInstancingBuffer(unsigned numInstances)
  1051. {
  1052. if (!instancingBuffer_ || !dynamicInstancing_)
  1053. return false;
  1054. unsigned oldSize = instancingBuffer_->GetVertexCount();
  1055. if (numInstances <= oldSize)
  1056. return true;
  1057. unsigned newSize = INSTANCING_BUFFER_DEFAULT_SIZE;
  1058. while (newSize < numInstances)
  1059. newSize <<= 1;
  1060. if (!instancingBuffer_->SetSize(newSize, INSTANCING_BUFFER_MASK, true))
  1061. {
  1062. LOGERROR("Failed to resize instancing buffer to " + String(newSize));
  1063. // If failed, try to restore the old size
  1064. instancingBuffer_->SetSize(oldSize, INSTANCING_BUFFER_MASK, true);
  1065. return false;
  1066. }
  1067. LOGDEBUG("Resized instancing buffer to " + String(newSize));
  1068. return true;
  1069. }
  1070. void Renderer::ResetShadowMapAllocations()
  1071. {
  1072. for (HashMap<int, PODVector<Light*> >::Iterator i = shadowMapAllocations_.Begin(); i != shadowMapAllocations_.End(); ++i)
  1073. i->second_.Clear();
  1074. }
  1075. void Renderer::ResetRenderBufferAllocations(bool remove)
  1076. {
  1077. // Optionally remove ´buffers that were not used at all (at the beginning of each frame's rendering step)
  1078. if (remove)
  1079. {
  1080. for (HashMap<long long, unsigned>::Iterator i = renderBufferMaxAllocations_.Begin(); i != renderBufferMaxAllocations_.End();)
  1081. {
  1082. HashMap<long long, unsigned>::Iterator current = i++;
  1083. if (!current->second_)
  1084. {
  1085. renderBuffers_.Erase(current->first_);
  1086. renderBufferAllocations_.Erase(current->first_);
  1087. renderBufferMaxAllocations_.Erase(current);
  1088. }
  1089. else
  1090. {
  1091. renderBuffers_[current->first_].Resize(current->second_);
  1092. current->second_ = 0;
  1093. }
  1094. }
  1095. }
  1096. // Then reset allocation value of remaining buffer sizes
  1097. for (HashMap<long long, unsigned>::Iterator i = renderBufferAllocations_.Begin(); i != renderBufferAllocations_.End(); ++i)
  1098. i->second_ = 0;
  1099. }
  1100. void Renderer::Initialize()
  1101. {
  1102. Graphics* graphics = GetSubsystem<Graphics>();
  1103. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1104. if (!graphics || !graphics->IsInitialized() || !cache)
  1105. return;
  1106. PROFILE(InitRenderer);
  1107. graphics_ = graphics;
  1108. cache_ = cache;
  1109. // Check shader model support
  1110. #ifndef USE_OPENGL
  1111. if (graphics_->GetSM3Support())
  1112. {
  1113. shaderPath_ = "Shaders/SM3/";
  1114. vsFormat_ = ".vs3";
  1115. psFormat_ = ".ps3";
  1116. }
  1117. else
  1118. {
  1119. shaderPath_ = "Shaders/SM2/";
  1120. vsFormat_ = ".vs2";
  1121. psFormat_ = ".ps2";
  1122. }
  1123. #else
  1124. {
  1125. shaderPath_ = "Shaders/GLSL/";
  1126. vsFormat_ = ".vert";
  1127. psFormat_ = ".frag";
  1128. }
  1129. #endif
  1130. if (!graphics_->GetShadowMapFormat())
  1131. drawShadows_ = false;
  1132. defaultLightRamp_ = cache->GetResource<Texture2D>("Textures/Ramp.png");
  1133. defaultLightSpot_ = cache->GetResource<Texture2D>("Textures/Spot.png");
  1134. defaultMaterial_ = cache->GetResource<Material>("Materials/Default.xml");
  1135. CreateGeometries();
  1136. CreateInstancingBuffer();
  1137. viewports_.Resize(1);
  1138. ResetViews();
  1139. ResetShadowMaps();
  1140. shadersDirty_ = true;
  1141. initialized_ = true;
  1142. LOGINFO("Initialized renderer");
  1143. }
  1144. void Renderer::ResetViews()
  1145. {
  1146. views_.Clear();
  1147. numViews_ = 0;
  1148. }
  1149. void Renderer::LoadShaders()
  1150. {
  1151. LOGINFO("Reloading shaders");
  1152. // Release old material shaders, mark them for reload
  1153. ReleaseMaterialShaders();
  1154. shadersChangedFrameNumber_ = GetSubsystem<Time>()->GetFrameNumber();
  1155. // Load inbuilt shaders
  1156. stencilVS_ = GetVertexShader("Stencil");
  1157. stencilPS_ = GetPixelShader("Stencil");
  1158. lightVS_.Clear();
  1159. lightPS_.Clear();
  1160. if (lightPrepass_)
  1161. {
  1162. lightVS_.Resize(MAX_DEFERRED_LIGHT_VS_VARIATIONS);
  1163. lightPS_.Resize(MAX_DEFERRED_LIGHT_PS_VARIATIONS);
  1164. unsigned shadows = (graphics_->GetHardwareShadowSupport() ? 1 : 0) | (shadowQuality_ & SHADOWQUALITY_HIGH_16BIT);
  1165. for (unsigned i = 0; i < MAX_DEFERRED_LIGHT_VS_VARIATIONS; ++i)
  1166. lightVS_[i] = GetVertexShader("LightVolume_" + deferredLightVSVariations[i]);
  1167. for (unsigned i = 0; i < lightPS_.Size(); ++i)
  1168. {
  1169. /// \todo Allow specifying the light volume shader name for different lighting models
  1170. String ortho, hwDepth;
  1171. #ifdef USE_OPENGL
  1172. hwDepth = hwVariations[graphics_->GetHardwareDepthSupport() ? 1 : 0];
  1173. #else
  1174. if (!graphics_->GetHardwareDepthSupport() && i < DLPS_ORTHO)
  1175. ortho = "Linear";
  1176. #endif
  1177. if (i >= DLPS_ORTHO)
  1178. ortho = "Ortho";
  1179. if (i & DLPS_SHADOW)
  1180. {
  1181. lightPS_[i] = GetPixelShader("LightVolume_" + ortho + lightPSVariations[i % DLPS_ORTHO] +
  1182. shadowVariations[shadows] + hwDepth);
  1183. }
  1184. else
  1185. lightPS_[i] = GetPixelShader("LightVolume_" + ortho + lightPSVariations[i % DLPS_ORTHO] + hwDepth);
  1186. }
  1187. }
  1188. shadersDirty_ = false;
  1189. }
  1190. void Renderer::LoadMaterialShaders(Technique* technique)
  1191. {
  1192. if (lightPrepass_ && technique->HasPass(PASS_GBUFFER))
  1193. {
  1194. LoadPassShaders(technique, PASS_GBUFFER);
  1195. LoadPassShaders(technique, PASS_MATERIAL);
  1196. }
  1197. else
  1198. {
  1199. LoadPassShaders(technique, PASS_BASE);
  1200. LoadPassShaders(technique, PASS_LITBASE);
  1201. LoadPassShaders(technique, PASS_LIGHT);
  1202. }
  1203. LoadPassShaders(technique, PASS_PREALPHA);
  1204. LoadPassShaders(technique, PASS_POSTALPHA);
  1205. LoadPassShaders(technique, PASS_SHADOW);
  1206. }
  1207. void Renderer::LoadPassShaders(Technique* technique, PassType type, bool allowShadows)
  1208. {
  1209. Pass* pass = technique->GetPass(type);
  1210. if (!pass)
  1211. return;
  1212. unsigned shadows = (graphics_->GetHardwareShadowSupport() ? 1 : 0) | (shadowQuality_ & SHADOWQUALITY_HIGH_16BIT);
  1213. String vertexShaderName = pass->GetVertexShader();
  1214. String pixelShaderName = pass->GetPixelShader();
  1215. // Check if the shader name is already a variation in itself
  1216. if (vertexShaderName.Find('_') == String::NPOS)
  1217. vertexShaderName += "_";
  1218. if (pixelShaderName.Find('_') == String::NPOS)
  1219. pixelShaderName += "_";
  1220. // If hardware depth is used, choose a G-buffer shader that does not write depth manually
  1221. if (type == PASS_GBUFFER)
  1222. {
  1223. unsigned hwDepth = graphics_->GetHardwareDepthSupport() ? 1 : 0;
  1224. vertexShaderName += hwVariations[hwDepth];
  1225. pixelShaderName += hwVariations[hwDepth];
  1226. }
  1227. Vector<SharedPtr<ShaderVariation> >& vertexShaders = pass->GetVertexShaders();
  1228. Vector<SharedPtr<ShaderVariation> >& pixelShaders = pass->GetPixelShaders();
  1229. // Forget all the old shaders
  1230. vertexShaders.Clear();
  1231. pixelShaders.Clear();
  1232. if (type == PASS_LIGHT || type == PASS_LITBASE)
  1233. {
  1234. // Load forward pixel lit variations. If material is transparent, and shadow maps are reused,
  1235. // do not load shadowed variations
  1236. if (reuseShadowMaps_)
  1237. {
  1238. if (!technique->HasPass(PASS_BASE) || technique->GetPass(PASS_BASE)->GetBlendMode() != BLEND_REPLACE)
  1239. allowShadows = false;
  1240. }
  1241. vertexShaders.Resize(MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS);
  1242. pixelShaders.Resize(MAX_LIGHT_PS_VARIATIONS);
  1243. for (unsigned j = 0; j < MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS; ++j)
  1244. {
  1245. unsigned g = j / MAX_LIGHT_VS_VARIATIONS;
  1246. unsigned l = j % MAX_LIGHT_VS_VARIATIONS;
  1247. if (l < LVS_SHADOW || allowShadows)
  1248. vertexShaders[j] = GetVertexShader(vertexShaderName + lightVSVariations[l] + geometryVSVariations[g], g != 0);
  1249. else
  1250. vertexShaders[j].Reset();
  1251. }
  1252. for (unsigned j = 0; j < MAX_LIGHT_PS_VARIATIONS; ++j)
  1253. {
  1254. if (j & LPS_SHADOW)
  1255. {
  1256. if (allowShadows)
  1257. pixelShaders[j] = GetPixelShader(pixelShaderName + lightPSVariations[j] + shadowVariations[shadows]);
  1258. else
  1259. pixelShaders[j].Reset();
  1260. }
  1261. else
  1262. pixelShaders[j] = GetPixelShader(pixelShaderName + lightPSVariations[j]);
  1263. }
  1264. }
  1265. else
  1266. {
  1267. // Load vertex light variations for forward ambient pass and pre-pass material pass
  1268. if (type == PASS_BASE || type == PASS_MATERIAL)
  1269. {
  1270. vertexShaders.Resize(MAX_VERTEXLIGHT_VS_VARIATIONS * MAX_GEOMETRYTYPES);
  1271. for (unsigned j = 0; j < MAX_GEOMETRYTYPES * MAX_VERTEXLIGHT_VS_VARIATIONS; ++j)
  1272. {
  1273. unsigned g = j / MAX_VERTEXLIGHT_VS_VARIATIONS;
  1274. unsigned l = j % MAX_VERTEXLIGHT_VS_VARIATIONS;
  1275. vertexShaders[j] = GetVertexShader(vertexShaderName + vertexLightVSVariations[l] + geometryVSVariations[g],
  1276. g != 0 || l != 0);
  1277. }
  1278. }
  1279. else
  1280. {
  1281. vertexShaders.Resize(MAX_GEOMETRYTYPES);
  1282. for (unsigned j = 0; j < MAX_GEOMETRYTYPES; ++j)
  1283. vertexShaders[j] = GetVertexShader(vertexShaderName + geometryVSVariations[j], j != 0);
  1284. }
  1285. pixelShaders.Resize(1);
  1286. pixelShaders[0] = GetPixelShader(pixelShaderName);
  1287. }
  1288. technique->MarkShadersLoaded(shadersChangedFrameNumber_);
  1289. }
  1290. void Renderer::ReleaseMaterialShaders()
  1291. {
  1292. PODVector<Material*> materials;
  1293. cache_->GetResources<Material>(materials);
  1294. for (unsigned i = 0; i < materials.Size(); ++i)
  1295. materials[i]->ReleaseShaders();
  1296. }
  1297. void Renderer::ReloadTextures()
  1298. {
  1299. PODVector<Resource*> textures;
  1300. cache_->GetResources(textures, Texture2D::GetTypeStatic());
  1301. for (unsigned i = 0; i < textures.Size(); ++i)
  1302. cache_->ReloadResource(textures[i]);
  1303. cache_->GetResources(textures, TextureCube::GetTypeStatic());
  1304. for (unsigned i = 0; i < textures.Size(); ++i)
  1305. cache_->ReloadResource(textures[i]);
  1306. }
  1307. void Renderer::CreateGeometries()
  1308. {
  1309. SharedPtr<VertexBuffer> dlvb(new VertexBuffer(context_));
  1310. dlvb->SetSize(4, MASK_POSITION);
  1311. dlvb->SetData(dirLightVertexData);
  1312. SharedPtr<IndexBuffer> dlib(new IndexBuffer(context_));
  1313. dlib->SetSize(6, false);
  1314. dlib->SetData(dirLightIndexData);
  1315. dirLightGeometry_ = new Geometry(context_);
  1316. dirLightGeometry_->SetVertexBuffer(0, dlvb);
  1317. dirLightGeometry_->SetIndexBuffer(dlib);
  1318. dirLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, dlib->GetIndexCount());
  1319. SharedPtr<VertexBuffer> slvb(new VertexBuffer(context_));
  1320. slvb->SetSize(8, MASK_POSITION);
  1321. slvb->SetData(spotLightVertexData);
  1322. SharedPtr<IndexBuffer> slib(new IndexBuffer(context_));
  1323. slib->SetSize(36, false);
  1324. slib->SetData(spotLightIndexData);
  1325. spotLightGeometry_ = new Geometry(context_);
  1326. spotLightGeometry_->SetVertexBuffer(0, slvb);
  1327. spotLightGeometry_->SetIndexBuffer(slib);
  1328. spotLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, slib->GetIndexCount());
  1329. SharedPtr<VertexBuffer> plvb(new VertexBuffer(context_));
  1330. plvb->SetSize(24, MASK_POSITION);
  1331. plvb->SetData(pointLightVertexData);
  1332. SharedPtr<IndexBuffer> plib(new IndexBuffer(context_));
  1333. plib->SetSize(132, false);
  1334. plib->SetData(pointLightIndexData);
  1335. pointLightGeometry_ = new Geometry(context_);
  1336. pointLightGeometry_->SetVertexBuffer(0, plvb);
  1337. pointLightGeometry_->SetIndexBuffer(plib);
  1338. pointLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, plib->GetIndexCount());
  1339. faceSelectCubeMap_ = new TextureCube(context_);
  1340. faceSelectCubeMap_->SetNumLevels(1);
  1341. faceSelectCubeMap_->SetSize(1, graphics_->GetRGBAFormat());
  1342. faceSelectCubeMap_->SetFilterMode(FILTER_NEAREST);
  1343. unsigned char data[256 * 256 * 4];
  1344. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1345. {
  1346. unsigned axis = i / 2;
  1347. data[0] = (axis == 0) ? 255 : 0;
  1348. data[1] = (axis == 1) ? 255 : 0;
  1349. data[2] = (axis == 2) ? 255 : 0;
  1350. data[3] = 0;
  1351. faceSelectCubeMap_->SetData((CubeMapFace)i, 0, 0, 0, 1, 1, data);
  1352. }
  1353. indirectionCubeMap_ = new TextureCube(context_);
  1354. indirectionCubeMap_->SetNumLevels(1);
  1355. indirectionCubeMap_->SetSize(256, graphics_->GetRGBAFormat());
  1356. indirectionCubeMap_->SetFilterMode(FILTER_BILINEAR);
  1357. indirectionCubeMap_->SetAddressMode(COORD_U, ADDRESS_CLAMP);
  1358. indirectionCubeMap_->SetAddressMode(COORD_V, ADDRESS_CLAMP);
  1359. indirectionCubeMap_->SetAddressMode(COORD_W, ADDRESS_CLAMP);
  1360. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1361. {
  1362. unsigned char faceX = (i & 1) * 255;
  1363. unsigned char faceY = (i / 2) * 255 / 3;
  1364. unsigned char* dest = data;
  1365. for (unsigned y = 0; y < 256; ++y)
  1366. {
  1367. for (unsigned x = 0; x < 256; ++x)
  1368. {
  1369. #ifdef USE_OPENGL
  1370. *dest++ = x;
  1371. *dest++ = 255 - y;
  1372. *dest++ = faceX;
  1373. *dest++ = 255 * 2 / 3 - faceY;
  1374. #else
  1375. *dest++ = x;
  1376. *dest++ = y;
  1377. *dest++ = faceX;
  1378. *dest++ = faceY;
  1379. #endif
  1380. }
  1381. }
  1382. indirectionCubeMap_->SetData((CubeMapFace)i, 0, 0, 0, 256, 256, data);
  1383. }
  1384. }
  1385. void Renderer::CreateInstancingBuffer()
  1386. {
  1387. // Do not create buffer if instancing not supported
  1388. if (!graphics_->GetSM3Support())
  1389. {
  1390. instancingBuffer_.Reset();
  1391. dynamicInstancing_ = false;
  1392. return;
  1393. }
  1394. // If must lock the buffer for each batch group, set a smaller size
  1395. unsigned defaultSize = graphics_->GetStreamOffsetSupport() ? INSTANCING_BUFFER_DEFAULT_SIZE : INSTANCING_BUFFER_DEFAULT_SIZE / 4;
  1396. instancingBuffer_ = new VertexBuffer(context_);
  1397. if (!instancingBuffer_->SetSize(defaultSize, INSTANCING_BUFFER_MASK, true))
  1398. {
  1399. instancingBuffer_.Reset();
  1400. dynamicInstancing_ = false;
  1401. }
  1402. }
  1403. void Renderer::ResetShadowMaps()
  1404. {
  1405. shadowMaps_.Clear();
  1406. shadowMapAllocations_.Clear();
  1407. colorShadowMaps_.Clear();
  1408. }
  1409. void Renderer::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  1410. {
  1411. if (!initialized_)
  1412. Initialize();
  1413. else
  1414. {
  1415. // When screen mode changes, purge old views
  1416. ResetViews();
  1417. }
  1418. }
  1419. void Renderer::HandleGraphicsFeatures(StringHash eventType, VariantMap& eventData)
  1420. {
  1421. // Reinitialize if already initialized
  1422. if (initialized_)
  1423. Initialize();
  1424. }
  1425. void Renderer::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  1426. {
  1427. if (initialized_)
  1428. {
  1429. using namespace RenderUpdate;
  1430. Update(eventData[P_TIMESTEP].GetFloat());
  1431. }
  1432. }