Renderer.cpp 54 KB

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