Renderer.cpp 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Oorni
  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 "Log.h"
  33. #include "Material.h"
  34. #include "OcclusionBuffer.h"
  35. #include "Octree.h"
  36. #include "Profiler.h"
  37. #include "Renderer.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. renderMode_(RENDER_FORWARD),
  245. textureAnisotropy_(4),
  246. textureFilterMode_(FILTER_TRILINEAR),
  247. textureQuality_(QUALITY_HIGH),
  248. materialQuality_(QUALITY_HIGH),
  249. shadowMapSize_(1024),
  250. shadowQuality_(SHADOWQUALITY_HIGH_16BIT),
  251. maxShadowMaps_(1),
  252. maxShadowCascades_(MAX_CASCADE_SPLITS),
  253. maxInstanceTriangles_(500),
  254. maxSortedInstances_(1000),
  255. maxOccluderTriangles_(5000),
  256. occlusionBufferSize_(256),
  257. occluderSizeThreshold_(0.025f),
  258. numViews_(0),
  259. numOcclusionBuffers_(0),
  260. numShadowCameras_(0),
  261. shadersChangedFrameNumber_(M_MAX_UNSIGNED),
  262. specularLighting_(true),
  263. drawShadows_(true),
  264. reuseShadowMaps_(true),
  265. dynamicInstancing_(true),
  266. shadersDirty_(true),
  267. initialized_(false)
  268. {
  269. SubscribeToEvent(E_SCREENMODE, HANDLER(Renderer, HandleScreenMode));
  270. SubscribeToEvent(E_GRAPHICSFEATURES, HANDLER(Renderer, HandleGraphicsFeatures));
  271. SubscribeToEvent(E_RENDERUPDATE, HANDLER(Renderer, HandleRenderUpdate));
  272. quadDirLight_->SetLightType(LIGHT_DIRECTIONAL);
  273. // Try to initialize right now, but skip if screen mode is not yet set
  274. Initialize();
  275. SetNumViewports(1);
  276. }
  277. Renderer::~Renderer()
  278. {
  279. }
  280. void Renderer::SetNumViewports(unsigned num)
  281. {
  282. viewports_.Resize(num);
  283. for (unsigned i = 0; i < viewports_.Size(); ++i)
  284. {
  285. if (!viewports_[i])
  286. viewports_[i] = new Viewport();
  287. }
  288. }
  289. bool Renderer::SetViewport(unsigned index, Viewport* viewport)
  290. {
  291. if (index >= viewports_.Size())
  292. {
  293. LOGERROR("Viewport index out of bounds");
  294. return false;
  295. }
  296. if (!viewport)
  297. {
  298. LOGERROR("Null viewport");
  299. return false;
  300. }
  301. viewports_[index] = viewport;
  302. return true;
  303. }
  304. void Renderer::SetRenderMode(RenderMode mode)
  305. {
  306. if (!initialized_)
  307. {
  308. LOGERROR("Can not switch rendering mode before setting initial screen mode");
  309. return;
  310. }
  311. if (mode == RENDER_PREPASS && !graphics_->GetLightPrepassSupport())
  312. mode = RENDER_FORWARD;
  313. if (mode == RENDER_DEFERRED && !graphics_->GetDeferredSupport())
  314. mode = RENDER_FORWARD;
  315. if (mode != renderMode_)
  316. {
  317. // Deferred rendering is incompatible with hardware multisampling, so set new screen mode with 1x sampling if in use
  318. if (mode != RENDER_FORWARD && graphics_->GetMultiSample() > 1)
  319. {
  320. graphics_->SetMode(graphics_->GetWidth(), graphics_->GetHeight(), graphics_->GetFullscreen(), graphics_->GetVSync(),
  321. graphics_->GetTripleBuffer(), 1);
  322. }
  323. ResetBuffers();
  324. ResetShadowMaps();
  325. renderMode_ = mode;
  326. shadersDirty_ = true;
  327. }
  328. }
  329. void Renderer::SetSpecularLighting(bool enable)
  330. {
  331. specularLighting_ = enable;
  332. }
  333. void Renderer::SetTextureAnisotropy(int level)
  334. {
  335. textureAnisotropy_ = Max(level, 1);
  336. }
  337. void Renderer::SetTextureFilterMode(TextureFilterMode mode)
  338. {
  339. textureFilterMode_ = mode;
  340. }
  341. void Renderer::SetTextureQuality(int quality)
  342. {
  343. quality = Clamp(quality, QUALITY_LOW, QUALITY_HIGH);
  344. if (quality != textureQuality_)
  345. {
  346. textureQuality_ = quality;
  347. ReloadTextures();
  348. }
  349. }
  350. void Renderer::SetMaterialQuality(int quality)
  351. {
  352. materialQuality_ = Clamp(quality, QUALITY_LOW, QUALITY_MAX);
  353. shadersDirty_ = true;
  354. ResetViews();
  355. }
  356. void Renderer::SetDrawShadows(bool enable)
  357. {
  358. if (!graphics_ || !graphics_->GetShadowMapFormat())
  359. return;
  360. drawShadows_ = enable;
  361. if (!drawShadows_)
  362. ResetShadowMaps();
  363. }
  364. void Renderer::SetShadowMapSize(int size)
  365. {
  366. if (!graphics_)
  367. return;
  368. size = NextPowerOfTwo(Max(size, SHADOW_MIN_PIXELS));
  369. if (size != shadowMapSize_)
  370. {
  371. shadowMapSize_ = size;
  372. ResetShadowMaps();
  373. }
  374. }
  375. void Renderer::SetShadowQuality(int quality)
  376. {
  377. if (!graphics_)
  378. return;
  379. quality &= SHADOWQUALITY_HIGH_24BIT;
  380. // If no hardware PCF, do not allow to select one-sample quality
  381. if (!graphics_->GetHardwareShadowSupport())
  382. quality |= SHADOWQUALITY_HIGH_16BIT;
  383. if (!graphics_->GetHiresShadowMapFormat())
  384. quality &= SHADOWQUALITY_HIGH_16BIT;
  385. if (quality != shadowQuality_)
  386. {
  387. shadowQuality_ = quality;
  388. shadersDirty_ = true;
  389. ResetShadowMaps();
  390. }
  391. }
  392. void Renderer::SetReuseShadowMaps(bool enable)
  393. {
  394. if (enable == reuseShadowMaps_)
  395. return;
  396. reuseShadowMaps_ = enable;
  397. }
  398. void Renderer::SetMaxShadowMaps(int shadowMaps)
  399. {
  400. if (shadowMaps < 1)
  401. return;
  402. maxShadowMaps_ = shadowMaps;
  403. for (HashMap<int, Vector<SharedPtr<Texture2D> > >::Iterator i = shadowMaps_.Begin(); i != shadowMaps_.End(); ++i)
  404. {
  405. if ((int)i->second_.Size() > maxShadowMaps_)
  406. i->second_.Resize(maxShadowMaps_);
  407. }
  408. }
  409. void Renderer::SetMaxShadowCascades(int cascades)
  410. {
  411. cascades = Clamp(cascades, 1, MAX_CASCADE_SPLITS);
  412. if (cascades != maxShadowCascades_)
  413. {
  414. maxShadowCascades_ = cascades;
  415. ResetShadowMaps();
  416. }
  417. }
  418. void Renderer::SetDynamicInstancing(bool enable)
  419. {
  420. if (!instancingBuffer_)
  421. enable = false;
  422. dynamicInstancing_ = enable;
  423. }
  424. void Renderer::SetMaxInstanceTriangles(int triangles)
  425. {
  426. maxInstanceTriangles_ = Max(triangles, 0);
  427. }
  428. void Renderer::SetMaxSortedInstances(int instances)
  429. {
  430. maxSortedInstances_ = Max(instances, 0);
  431. }
  432. void Renderer::SetMaxOccluderTriangles(int triangles)
  433. {
  434. maxOccluderTriangles_ = Max(triangles, 0);
  435. }
  436. void Renderer::SetOcclusionBufferSize(int size)
  437. {
  438. occlusionBufferSize_ = Max(size, 1);
  439. occlusionBuffers_.Clear();
  440. }
  441. void Renderer::SetOccluderSizeThreshold(float screenSize)
  442. {
  443. occluderSizeThreshold_ = Max(screenSize, 0.0f);
  444. }
  445. void Renderer::ReloadShaders()
  446. {
  447. shadersDirty_ = true;
  448. }
  449. Viewport* Renderer::GetViewport(unsigned index) const
  450. {
  451. return index < viewports_.Size() ? viewports_[index] : (Viewport*)0;
  452. }
  453. int Renderer::GetMaxShadowCascades() const
  454. {
  455. // Due to instruction count limits, deferred modes in SM2.0 can only support up to 3 cascades
  456. #ifndef USE_OPENGL
  457. if (renderMode_ != RENDER_FORWARD && !graphics_->GetSM3Support())
  458. return Max(maxShadowCascades_, 3);
  459. #endif
  460. return maxShadowCascades_;
  461. }
  462. ShaderVariation* Renderer::GetVertexShader(const String& name, bool checkExists) const
  463. {
  464. return GetShader(VS, name, checkExists);
  465. }
  466. ShaderVariation* Renderer::GetPixelShader(const String& name, bool checkExists) const
  467. {
  468. return GetShader(PS, name, checkExists);
  469. }
  470. unsigned Renderer::GetNumGeometries(bool allViews) const
  471. {
  472. unsigned numGeometries = 0;
  473. unsigned lastView = allViews ? numViews_ : 1;
  474. for (unsigned i = 0; i < lastView; ++i)
  475. numGeometries += views_[i]->GetGeometries().Size();
  476. return numGeometries;
  477. }
  478. unsigned Renderer::GetNumLights(bool allViews) const
  479. {
  480. unsigned numLights = 0;
  481. unsigned lastView = allViews ? numViews_ : 1;
  482. for (unsigned i = 0; i < lastView; ++i)
  483. numLights += views_[i]->GetLights().Size();
  484. return numLights;
  485. }
  486. unsigned Renderer::GetNumShadowMaps(bool allViews) const
  487. {
  488. unsigned numShadowMaps = 0;
  489. unsigned lastView = allViews ? numViews_ : 1;
  490. for (unsigned i = 0; i < lastView; ++i)
  491. {
  492. const Vector<LightBatchQueue>& lightQueues = views_[i]->GetLightQueues();
  493. for (Vector<LightBatchQueue>::ConstIterator i = lightQueues.Begin(); i != lightQueues.End(); ++i)
  494. {
  495. if (i->shadowMap_)
  496. ++numShadowMaps;
  497. }
  498. }
  499. return numShadowMaps;
  500. }
  501. unsigned Renderer::GetNumOccluders(bool allViews) const
  502. {
  503. unsigned numOccluders = 0;
  504. unsigned lastView = allViews ? numViews_ : 1;
  505. for (unsigned i = 0; i < lastView; ++i)
  506. numOccluders += views_[i]->GetOccluders().Size();
  507. return numOccluders;
  508. }
  509. void Renderer::Update(float timeStep)
  510. {
  511. PROFILE(UpdateViews);
  512. numViews_ = 0;
  513. // If device lost, do not perform update. This is because any dynamic vertex/index buffer updates happen already here,
  514. // and if the device is lost, the updates queue up, causing memory use to rise constantly
  515. if (!graphics_ || !graphics_->IsInitialized() || graphics_->IsDeviceLost())
  516. return;
  517. // Set up the frameinfo structure for this frame
  518. frame_.frameNumber_ = GetSubsystem<Time>()->GetFrameNumber();
  519. frame_.timeStep_ = timeStep;
  520. frame_.camera_ = 0;
  521. numShadowCameras_ = 0;
  522. numOcclusionBuffers_ = 0;
  523. updatedOctrees_.Clear();
  524. // Reload shaders now if needed
  525. if (shadersDirty_)
  526. LoadShaders();
  527. // Process all viewports. Use reverse order, because during rendering the order will be reversed again
  528. // to handle auxiliary view dependencies correctly
  529. for (unsigned i = viewports_.Size() - 1; i < viewports_.Size(); --i)
  530. {
  531. unsigned mainView = numViews_;
  532. Viewport* viewport = viewports_[i];
  533. if (!viewport || !AddView(0, viewport))
  534. continue;
  535. const IntRect& viewRect = viewport->GetRect();
  536. Scene* scene = viewport->GetScene();
  537. // Update octree (perform early update for drawables which need that, and reinsert moved drawables.)
  538. // However, if the same scene is viewed from multiple cameras, update the octree only once
  539. Octree* octree = scene->GetComponent<Octree>();
  540. if (!updatedOctrees_.Contains(octree))
  541. {
  542. frame_.camera_ = viewport->GetCamera();
  543. frame_.viewSize_ = viewRect.Size();
  544. if (frame_.viewSize_ == IntVector2::ZERO)
  545. frame_.viewSize_ = IntVector2(graphics_->GetWidth(), graphics_->GetHeight());
  546. octree->Update(frame_);
  547. updatedOctrees_.Insert(octree);
  548. // Set also the view for the debug graphics already here, so that it can use culling
  549. /// \todo May result in incorrect debug geometry culling if the same scene is drawn from multiple viewports
  550. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  551. if (debug)
  552. debug->SetView(viewport->GetCamera());
  553. }
  554. // Update the viewport's main view and any auxiliary views it has created
  555. for (unsigned i = mainView; i < numViews_; ++i)
  556. {
  557. // Reset shadow map allocations; they can be reused between views as each is rendered completely at a time
  558. ResetShadowMapAllocations();
  559. views_[i]->Update(frame_);
  560. }
  561. }
  562. }
  563. void Renderer::Render()
  564. {
  565. if (!graphics_)
  566. return;
  567. PROFILE(RenderViews);
  568. // If the indirection textures have lost content (OpenGL mode only), restore them now
  569. if (faceSelectCubeMap_ && faceSelectCubeMap_->IsDataLost())
  570. SetIndirectionTextureData();
  571. graphics_->SetDefaultTextureFilterMode(textureFilterMode_);
  572. graphics_->SetTextureAnisotropy(textureAnisotropy_);
  573. graphics_->ClearParameterSources();
  574. // If no views, just clear the screen
  575. if (!numViews_)
  576. {
  577. graphics_->SetBlendMode(BLEND_REPLACE);
  578. graphics_->SetColorWrite(true);
  579. graphics_->SetDepthWrite(true);
  580. graphics_->SetScissorTest(false);
  581. graphics_->SetStencilTest(false);
  582. graphics_->ResetRenderTargets();
  583. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH | CLEAR_STENCIL);
  584. numPrimitives_ = 0;
  585. numBatches_ = 0;
  586. }
  587. else
  588. {
  589. // Render views from last to first (each main view is rendered after the auxiliary views it depends on)
  590. for (unsigned i = numViews_ - 1; i < numViews_; --i)
  591. {
  592. // Screen buffers can be reused between views, as each is rendered completely
  593. PrepareViewRender();
  594. views_[i]->Render();
  595. }
  596. // Copy the number of batches & primitives from Graphics so that we can account for 3D geometry only
  597. numPrimitives_ = graphics_->GetNumPrimitives();
  598. numBatches_ = graphics_->GetNumBatches();
  599. }
  600. // Remove unused occlusion buffers and renderbuffers
  601. RemoveUnusedBuffers();
  602. }
  603. void Renderer::DrawDebugGeometry(bool depthTest)
  604. {
  605. PROFILE(RendererDrawDebug);
  606. /// \todo Because debug geometry is per-scene, if two cameras show views of the same area, occlusion is not shown correctly
  607. HashSet<Drawable*> processedGeometries;
  608. HashSet<Light*> processedLights;
  609. for (unsigned i = 0; i < numViews_; ++i)
  610. {
  611. // Make sure it's a main view, and process each node only once
  612. View* view = views_[i];
  613. if (view->GetRenderTarget())
  614. continue;
  615. Octree* octree = view->GetOctree();
  616. if (!octree)
  617. continue;
  618. DebugRenderer* debug = octree->GetComponent<DebugRenderer>();
  619. if (!debug)
  620. continue;
  621. const PODVector<Drawable*>& geometries = view->GetGeometries();
  622. const PODVector<Light*>& lights = view->GetLights();
  623. for (unsigned i = 0; i < geometries.Size(); ++i)
  624. {
  625. if (!processedGeometries.Contains(geometries[i]))
  626. {
  627. geometries[i]->DrawDebugGeometry(debug, depthTest);
  628. processedGeometries.Insert(geometries[i]);
  629. }
  630. }
  631. for (unsigned i = 0; i < lights.Size(); ++i)
  632. {
  633. if (!processedLights.Contains(lights[i]))
  634. {
  635. lights[i]->DrawDebugGeometry(debug, depthTest);
  636. processedLights.Insert(lights[i]);
  637. }
  638. }
  639. }
  640. }
  641. bool Renderer::AddView(RenderSurface* renderTarget, Viewport* viewport)
  642. {
  643. // If using a rendertarget texture, make sure it will not be rendered to multiple times
  644. if (renderTarget)
  645. {
  646. for (unsigned i = 0; i < numViews_; ++i)
  647. {
  648. if (views_[i]->GetRenderTarget() == renderTarget)
  649. return false;
  650. }
  651. }
  652. if (views_.Size() <= numViews_)
  653. views_.Resize(numViews_ + 1);
  654. if (!views_[numViews_])
  655. views_[numViews_] = new View(context_);
  656. if (views_[numViews_]->Define(renderTarget, viewport))
  657. {
  658. ++numViews_;
  659. return true;
  660. }
  661. else
  662. return false;
  663. }
  664. Geometry* Renderer::GetLightGeometry(Light* light)
  665. {
  666. LightType type = light->GetLightType();
  667. if (type == LIGHT_DIRECTIONAL)
  668. return dirLightGeometry_;
  669. if (type == LIGHT_SPOT)
  670. return spotLightGeometry_;
  671. else if (type == LIGHT_POINT)
  672. return pointLightGeometry_;
  673. else
  674. return 0;
  675. }
  676. Texture2D* Renderer::GetShadowMap(Light* light, Camera* camera, unsigned viewWidth, unsigned viewHeight)
  677. {
  678. LightType type = light->GetLightType();
  679. const FocusParameters& parameters = light->GetShadowFocus();
  680. float size = (float)shadowMapSize_ * light->GetShadowResolution();
  681. // Automatically reduce shadow map size when far away
  682. if (parameters.autoSize_ && type != LIGHT_DIRECTIONAL)
  683. {
  684. const Matrix3x4& view = camera->GetInverseWorldTransform();
  685. const Matrix4& projection = camera->GetProjection();
  686. BoundingBox lightBox;
  687. float lightPixels;
  688. if (type == LIGHT_POINT)
  689. {
  690. // Calculate point light pixel size from the projection of its diagonal
  691. Vector3 center = view * light->GetNode()->GetWorldPosition();
  692. float extent = 0.58f * light->GetRange();
  693. lightBox.Define(center + Vector3(extent, extent, extent), center - Vector3(extent, extent, extent));
  694. }
  695. else
  696. {
  697. // Calculate spot light pixel size from the projection of its frustum far vertices
  698. Frustum lightFrustum = light->GetFrustum().Transformed(view);
  699. lightBox.Define(&lightFrustum.vertices_[4], 4);
  700. }
  701. Vector2 projectionSize = lightBox.Projected(projection).Size();
  702. lightPixels = Max(0.5f * (float)viewWidth * projectionSize.x_, 0.5f * (float)viewHeight * projectionSize.y_);
  703. // Clamp pixel amount to a sufficient minimum to avoid self-shadowing artifacts due to loss of precision
  704. if (lightPixels < SHADOW_MIN_PIXELS)
  705. lightPixels = SHADOW_MIN_PIXELS;
  706. size = Min(size, lightPixels);
  707. }
  708. /// \todo Allow to specify maximum shadow maps per resolution, as smaller shadow maps take less memory
  709. int width = NextPowerOfTwo((unsigned)size);
  710. int height = width;
  711. // Adjust the size for directional or point light shadow map atlases
  712. if (type == LIGHT_DIRECTIONAL)
  713. {
  714. if (maxShadowCascades_ > 1)
  715. width *= 2;
  716. if (maxShadowCascades_ > 2)
  717. height *= 2;
  718. }
  719. else if (type == LIGHT_POINT)
  720. {
  721. width *= 2;
  722. height *= 3;
  723. }
  724. int searchKey = (width << 16) | height;
  725. if (shadowMaps_.Contains(searchKey))
  726. {
  727. // If shadow maps are reused, always return the first
  728. if (reuseShadowMaps_)
  729. return shadowMaps_[searchKey][0];
  730. else
  731. {
  732. // If not reused, check allocation count and return existing shadow map if possible
  733. unsigned allocated = shadowMapAllocations_[searchKey].Size();
  734. if (allocated < shadowMaps_[searchKey].Size())
  735. {
  736. shadowMapAllocations_[searchKey].Push(light);
  737. return shadowMaps_[searchKey][allocated];
  738. }
  739. else if ((int)allocated >= maxShadowMaps_)
  740. return 0;
  741. }
  742. }
  743. unsigned shadowMapFormat = (shadowQuality_ & SHADOWQUALITY_LOW_24BIT) ? graphics_->GetHiresShadowMapFormat() :
  744. graphics_->GetShadowMapFormat();
  745. if (!shadowMapFormat)
  746. return 0;
  747. SharedPtr<Texture2D> newShadowMap(new Texture2D(context_));
  748. int retries = 3;
  749. // OpenGL: create shadow map only. Color rendertarget is not needed
  750. #ifdef USE_OPENGL
  751. while (retries)
  752. {
  753. if (!newShadowMap->SetSize(width, height, shadowMapFormat, TEXTURE_DEPTHSTENCIL))
  754. {
  755. width >>= 1;
  756. height >>= 1;
  757. --retries;
  758. }
  759. else
  760. {
  761. #ifndef GL_ES_VERSION_2_0
  762. newShadowMap->SetFilterMode(FILTER_BILINEAR);
  763. newShadowMap->SetShadowCompare(true);
  764. #endif
  765. break;
  766. }
  767. }
  768. #else
  769. // Direct3D9: create shadow map and dummy color rendertarget
  770. unsigned dummyColorFormat = graphics_->GetDummyColorFormat();
  771. while (retries)
  772. {
  773. if (!newShadowMap->SetSize(width, height, shadowMapFormat, TEXTURE_DEPTHSTENCIL))
  774. {
  775. width >>= 1;
  776. height >>= 1;
  777. --retries;
  778. }
  779. else
  780. {
  781. newShadowMap->SetFilterMode(FILTER_BILINEAR);
  782. // If no dummy color rendertarget for this size exists yet, create one now
  783. if (!colorShadowMaps_.Contains(searchKey))
  784. {
  785. colorShadowMaps_[searchKey] = new Texture2D(context_);
  786. colorShadowMaps_[searchKey]->SetSize(width, height, dummyColorFormat, TEXTURE_RENDERTARGET);
  787. }
  788. // Link the color rendertarget to the shadow map
  789. newShadowMap->GetRenderSurface()->SetLinkedRenderTarget(colorShadowMaps_[searchKey]->GetRenderSurface());
  790. break;
  791. }
  792. }
  793. #endif
  794. // If failed to set size, store a null pointer so that we will not retry
  795. if (!retries)
  796. newShadowMap.Reset();
  797. shadowMaps_[searchKey].Push(newShadowMap);
  798. if (!reuseShadowMaps_)
  799. shadowMapAllocations_[searchKey].Push(light);
  800. return newShadowMap;
  801. }
  802. Texture2D* Renderer::GetScreenBuffer(int width, int height, unsigned format, bool filtered)
  803. {
  804. bool depthStencil = (format == Graphics::GetDepthStencilFormat());
  805. if (depthStencil)
  806. filtered = false;
  807. long long searchKey = ((long long)format << 32) | (width << 16) | height;
  808. if (filtered)
  809. searchKey |= 0x8000000000000000LL;
  810. // If new size or format, initialize the allocation stats
  811. if (screenBuffers_.Find(searchKey) == screenBuffers_.End())
  812. screenBufferAllocations_[searchKey] = 0;
  813. unsigned allocations = screenBufferAllocations_[searchKey]++;
  814. if (allocations >= screenBuffers_[searchKey].Size())
  815. {
  816. SharedPtr<Texture2D> newBuffer(new Texture2D(context_));
  817. newBuffer->SetSize(width, height, format, depthStencil ? TEXTURE_DEPTHSTENCIL : TEXTURE_RENDERTARGET);
  818. if (filtered)
  819. newBuffer->SetFilterMode(FILTER_BILINEAR);
  820. newBuffer->ResetUseTimer();
  821. screenBuffers_[searchKey].Push(newBuffer);
  822. LOGDEBUG("Allocated new screen buffer size " + String(width) + "x" + String(height) + " format " + String(format));
  823. return newBuffer;
  824. }
  825. else
  826. {
  827. Texture2D* buffer = screenBuffers_[searchKey][allocations];
  828. buffer->ResetUseTimer();
  829. return buffer;
  830. }
  831. }
  832. RenderSurface* Renderer::GetDepthStencil(int width, int height)
  833. {
  834. // Return the default depth-stencil surface if applicable
  835. // (when using OpenGL Graphics will allocate right size surfaces on demand to emulate Direct3D9)
  836. if (width <= graphics_->GetWidth() && height <= graphics_->GetHeight() && graphics_->GetMultiSample() <= 1)
  837. return 0;
  838. else
  839. return GetScreenBuffer(width, height, Graphics::GetDepthStencilFormat())->GetRenderSurface();
  840. }
  841. OcclusionBuffer* Renderer::GetOcclusionBuffer(Camera* camera)
  842. {
  843. if (numOcclusionBuffers_ >= occlusionBuffers_.Size())
  844. {
  845. SharedPtr<OcclusionBuffer> newBuffer(new OcclusionBuffer(context_));
  846. occlusionBuffers_.Push(newBuffer);
  847. }
  848. int width = occlusionBufferSize_;
  849. int height = (int)((float)occlusionBufferSize_ / camera->GetAspectRatio() + 0.5f);
  850. OcclusionBuffer* buffer = occlusionBuffers_[numOcclusionBuffers_];
  851. buffer->SetSize(width, height);
  852. buffer->SetView(camera);
  853. buffer->ResetUseTimer();
  854. ++numOcclusionBuffers_;
  855. return buffer;
  856. }
  857. Camera* Renderer::GetShadowCamera()
  858. {
  859. MutexLock lock(rendererMutex_);
  860. if (numShadowCameras_ >= shadowCameraNodes_.Size())
  861. {
  862. SharedPtr<Node> newNode(new Node(context_));
  863. newNode->CreateComponent<Camera>();
  864. shadowCameraNodes_.Push(newNode);
  865. }
  866. Camera* camera = shadowCameraNodes_[numShadowCameras_]->GetComponent<Camera>();
  867. camera->SetOrthographic(false);
  868. camera->SetZoom(1.0f);
  869. ++numShadowCameras_;
  870. return camera;
  871. }
  872. ShaderVariation* Renderer::GetShader(ShaderType type, const String& name, bool checkExists) const
  873. {
  874. String shaderName = shaderPath_;
  875. String variationName;
  876. unsigned split = name.Find('_');
  877. if (split != String::NPOS)
  878. {
  879. shaderName += name.Substring(0, split) + ".xml";
  880. variationName = name.Substring(split + 1);
  881. }
  882. else
  883. shaderName += name + ".xml";
  884. if (checkExists)
  885. {
  886. if (!cache_->Exists(shaderName))
  887. return 0;
  888. }
  889. Shader* shader = cache_->GetResource<Shader>(shaderName);
  890. if (shader)
  891. return shader->GetVariation(type, variationName);
  892. else
  893. return 0;
  894. }
  895. void Renderer::SetBatchShaders(Batch& batch, Technique* tech, bool allowShadows)
  896. {
  897. // Check if shaders are unloaded or need reloading
  898. Vector<SharedPtr<ShaderVariation> >& vertexShaders = batch.pass_->GetVertexShaders();
  899. Vector<SharedPtr<ShaderVariation> >& pixelShaders = batch.pass_->GetPixelShaders();
  900. if (!vertexShaders.Size() || !pixelShaders.Size() || tech->GetShadersLoadedFrameNumber() !=
  901. shadersChangedFrameNumber_)
  902. {
  903. // First release all previous shaders, then load
  904. tech->ReleaseShaders();
  905. LoadMaterialShaders(tech);
  906. }
  907. // Make sure shaders are loaded now
  908. if (vertexShaders.Size() && pixelShaders.Size())
  909. {
  910. GeometryType geomType = batch.geometryType_;
  911. // If instancing is not supported, but was requested, or the object is too large to be instanced,
  912. // choose static geometry vertex shader instead
  913. if (geomType == GEOM_INSTANCED && (!GetDynamicInstancing() || batch.geometry_->GetIndexCount() >
  914. (unsigned)maxInstanceTriangles_ * 3))
  915. geomType = GEOM_STATIC;
  916. if (geomType == GEOM_STATIC_NOINSTANCING)
  917. geomType = GEOM_STATIC;
  918. // Check whether is a pixel lit forward pass. If not, there is only one pixel shader
  919. PassType type = batch.pass_->GetType();
  920. if (type == PASS_LIGHT || type == PASS_LITBASE)
  921. {
  922. LightBatchQueue* lightQueue = batch.lightQueue_;
  923. if (!lightQueue)
  924. {
  925. // Do not log error, as it would result in a lot of spam
  926. batch.vertexShader_ = 0;
  927. batch.pixelShader_ = 0;
  928. return;
  929. }
  930. Light* light = lightQueue->light_;
  931. unsigned vsi = 0;
  932. unsigned psi = 0;
  933. vsi = geomType * MAX_LIGHT_VS_VARIATIONS;
  934. bool materialHasSpecular = batch.material_ ? batch.material_->GetSpecular() : true;
  935. if (specularLighting_ && light->GetSpecularIntensity() > 0.0f && materialHasSpecular)
  936. {
  937. vsi += LVS_SPEC;
  938. psi += LPS_SPEC;
  939. }
  940. if (allowShadows && lightQueue->shadowMap_)
  941. {
  942. vsi += LVS_SHADOW;
  943. psi += LPS_SHADOW;
  944. }
  945. switch (light->GetLightType())
  946. {
  947. case LIGHT_DIRECTIONAL:
  948. vsi += LVS_DIR;
  949. break;
  950. case LIGHT_POINT:
  951. if (light->GetShapeTexture())
  952. psi += LPS_POINTMASK;
  953. else
  954. psi += LPS_POINT;
  955. vsi += LVS_POINT;
  956. break;
  957. case LIGHT_SPOT:
  958. psi += LPS_SPOT;
  959. vsi += LVS_SPOT;
  960. break;
  961. }
  962. batch.vertexShader_ = vertexShaders[vsi];
  963. batch.pixelShader_ = pixelShaders[psi];
  964. // If shadow or specular variations do not exist, try without them
  965. if ((!batch.vertexShader_ || !batch.pixelShader_) && (vsi >= LVS_SHADOW))
  966. {
  967. vsi -= LVS_SHADOW;
  968. psi -= LPS_SHADOW;
  969. batch.vertexShader_ = vertexShaders[vsi];
  970. batch.pixelShader_ = pixelShaders[psi];
  971. }
  972. if ((!batch.vertexShader_ || !batch.pixelShader_) && (vsi >= LVS_SPEC))
  973. {
  974. vsi -= LVS_SPEC;
  975. psi -= LPS_SPEC;
  976. batch.vertexShader_ = vertexShaders[vsi];
  977. batch.pixelShader_ = pixelShaders[psi];
  978. }
  979. }
  980. else
  981. {
  982. // Check if pass has vertex lighting support
  983. if (type == PASS_BASE || type == PASS_MATERIAL || type == PASS_DEFERRED)
  984. {
  985. unsigned numVertexLights = 0;
  986. if (batch.lightQueue_)
  987. numVertexLights = batch.lightQueue_->vertexLights_.Size();
  988. unsigned vsi = geomType * MAX_VERTEXLIGHT_VS_VARIATIONS + numVertexLights;
  989. batch.vertexShader_ = vertexShaders[vsi];
  990. // If vertex lights variations do not exist, try without them
  991. if (!batch.vertexShader_)
  992. {
  993. unsigned vsi = geomType * MAX_VERTEXLIGHT_VS_VARIATIONS;
  994. batch.vertexShader_ = vertexShaders[vsi];
  995. }
  996. }
  997. else
  998. {
  999. unsigned vsi = geomType;
  1000. batch.vertexShader_ = vertexShaders[vsi];
  1001. }
  1002. batch.pixelShader_ = pixelShaders[0];
  1003. }
  1004. }
  1005. // Log error if shaders could not be assigned, but only once per technique
  1006. if (!batch.vertexShader_ || !batch.pixelShader_)
  1007. {
  1008. if (!shaderErrorDisplayed_.Contains(tech))
  1009. {
  1010. shaderErrorDisplayed_.Insert(tech);
  1011. LOGERROR("Technique " + tech->GetName() + " has missing shaders");
  1012. }
  1013. }
  1014. }
  1015. void Renderer::SetLightVolumeBatchShaders(Batch& batch)
  1016. {
  1017. unsigned vsi = DLVS_NONE;
  1018. unsigned psi = DLPS_NONE;
  1019. Light* light = batch.lightQueue_->light_;
  1020. switch (light->GetLightType())
  1021. {
  1022. case LIGHT_DIRECTIONAL:
  1023. vsi += DLVS_DIR;
  1024. break;
  1025. case LIGHT_POINT:
  1026. if (light->GetShapeTexture())
  1027. psi += DLPS_POINTMASK;
  1028. else
  1029. psi += DLPS_POINT;
  1030. break;
  1031. case LIGHT_SPOT:
  1032. psi += DLPS_SPOT;
  1033. break;
  1034. }
  1035. if (batch.lightQueue_->shadowMap_)
  1036. psi += DLPS_SHADOW;
  1037. if (specularLighting_ && light->GetSpecularIntensity() > 0.0f)
  1038. psi += DLPS_SPEC;
  1039. if (batch.camera_->IsOrthographic())
  1040. {
  1041. vsi += DLVS_ORTHO;
  1042. psi += DLPS_ORTHO;
  1043. }
  1044. batch.vertexShader_ = lightVS_[vsi];
  1045. batch.pixelShader_ = lightPS_[psi];
  1046. }
  1047. void Renderer::SetCullMode(CullMode mode, Camera* camera)
  1048. {
  1049. // If a camera is specified, check for vertical flipping and reverse culling in that case
  1050. if (camera && camera->GetFlipVertical())
  1051. {
  1052. if (mode == CULL_CW)
  1053. mode = CULL_CCW;
  1054. else if (mode == CULL_CCW)
  1055. mode = CULL_CW;
  1056. }
  1057. graphics_->SetCullMode(mode);
  1058. }
  1059. bool Renderer::ResizeInstancingBuffer(unsigned numInstances)
  1060. {
  1061. if (!instancingBuffer_ || !dynamicInstancing_)
  1062. return false;
  1063. unsigned oldSize = instancingBuffer_->GetVertexCount();
  1064. if (numInstances <= oldSize)
  1065. return true;
  1066. unsigned newSize = INSTANCING_BUFFER_DEFAULT_SIZE;
  1067. while (newSize < numInstances)
  1068. newSize <<= 1;
  1069. if (!instancingBuffer_->SetSize(newSize, INSTANCING_BUFFER_MASK, true))
  1070. {
  1071. LOGERROR("Failed to resize instancing buffer to " + String(newSize));
  1072. // If failed, try to restore the old size
  1073. instancingBuffer_->SetSize(oldSize, INSTANCING_BUFFER_MASK, true);
  1074. return false;
  1075. }
  1076. LOGDEBUG("Resized instancing buffer to " + String(newSize));
  1077. return true;
  1078. }
  1079. void Renderer::SaveScreenBufferAllocations()
  1080. {
  1081. savedScreenBufferAllocations_ = screenBufferAllocations_;
  1082. }
  1083. void Renderer::RestoreScreenBufferAllocations()
  1084. {
  1085. screenBufferAllocations_ = savedScreenBufferAllocations_;
  1086. }
  1087. void Renderer::OptimizeLightByScissor(Light* light, Camera* camera)
  1088. {
  1089. if (light && light->GetLightType() != LIGHT_DIRECTIONAL)
  1090. graphics_->SetScissorTest(true, GetLightScissor(light, camera));
  1091. else
  1092. graphics_->SetScissorTest(false);
  1093. }
  1094. void Renderer::OptimizeLightByStencil(Light* light, Camera* camera)
  1095. {
  1096. #ifndef GL_ES_VERSION_2_0
  1097. if (light)
  1098. {
  1099. LightType type = light->GetLightType();
  1100. if (type == LIGHT_DIRECTIONAL)
  1101. {
  1102. graphics_->SetStencilTest(false);
  1103. return;
  1104. }
  1105. Geometry* geometry = GetLightGeometry(light);
  1106. const Matrix3x4& view = camera->GetInverseWorldTransform();
  1107. const Matrix4& projection = camera->GetProjection();
  1108. Vector3 cameraPos = camera->GetNode()->GetWorldPosition();
  1109. float lightDist;
  1110. if (type == LIGHT_POINT)
  1111. lightDist = Sphere(light->GetNode()->GetWorldPosition(), light->GetRange() * 1.25f).Distance(cameraPos);
  1112. else
  1113. lightDist = light->GetFrustum().Distance(cameraPos);
  1114. // If the camera is actually inside the light volume, do not draw to stencil as it would waste fillrate
  1115. if (lightDist < M_EPSILON)
  1116. {
  1117. graphics_->SetStencilTest(false);
  1118. return;
  1119. }
  1120. // If the stencil value has wrapped, clear the whole stencil first
  1121. if (!lightStencilValue_)
  1122. {
  1123. graphics_->Clear(CLEAR_STENCIL);
  1124. lightStencilValue_ = 1;
  1125. }
  1126. // If possible, render the stencil volume front faces. However, close to the near clip plane render back faces instead
  1127. // to avoid clipping.
  1128. if (lightDist < camera->GetNearClip() * 2.0f)
  1129. {
  1130. SetCullMode(CULL_CW, camera);
  1131. graphics_->SetDepthTest(CMP_GREATER);
  1132. }
  1133. else
  1134. {
  1135. SetCullMode(CULL_CCW, camera);
  1136. graphics_->SetDepthTest(CMP_LESSEQUAL);
  1137. }
  1138. graphics_->SetColorWrite(false);
  1139. graphics_->SetDepthWrite(false);
  1140. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, lightStencilValue_);
  1141. graphics_->SetShaders(stencilVS_, stencilPS_);
  1142. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection * view);
  1143. graphics_->SetShaderParameter(VSP_MODEL, light->GetVolumeTransform(camera));
  1144. geometry->Draw(graphics_);
  1145. graphics_->ClearTransformSources();
  1146. graphics_->SetColorWrite(true);
  1147. graphics_->SetStencilTest(true, CMP_EQUAL, OP_KEEP, OP_KEEP, OP_KEEP, lightStencilValue_);
  1148. // Increase stencil value for next light
  1149. ++lightStencilValue_;
  1150. }
  1151. else
  1152. graphics_->SetStencilTest(false);
  1153. #endif
  1154. }
  1155. const Rect& Renderer::GetLightScissor(Light* light, Camera* camera)
  1156. {
  1157. Pair<Light*, Camera*> combination(light, camera);
  1158. HashMap<Pair<Light*, Camera*>, Rect>::Iterator i = lightScissorCache_.Find(combination);
  1159. if (i != lightScissorCache_.End())
  1160. return i->second_;
  1161. const Matrix3x4& view = camera->GetInverseWorldTransform();
  1162. const Matrix4& projection = camera->GetProjection();
  1163. switch (light->GetLightType())
  1164. {
  1165. case LIGHT_POINT:
  1166. {
  1167. BoundingBox viewBox(light->GetWorldBoundingBox().Transformed(view));
  1168. return lightScissorCache_[combination] = viewBox.Projected(projection);
  1169. }
  1170. case LIGHT_SPOT:
  1171. {
  1172. Frustum viewFrustum(light->GetFrustum().Transformed(view));
  1173. return lightScissorCache_[combination] = viewFrustum.Projected(projection);
  1174. }
  1175. default:
  1176. return lightScissorCache_[combination] = Rect::FULL;
  1177. }
  1178. }
  1179. void Renderer::PrepareViewRender()
  1180. {
  1181. ResetScreenBufferAllocations();
  1182. lightScissorCache_.Clear();
  1183. lightStencilValue_ = 1;
  1184. }
  1185. void Renderer::RemoveUnusedBuffers()
  1186. {
  1187. for (unsigned i = occlusionBuffers_.Size() - 1; i < occlusionBuffers_.Size(); --i)
  1188. {
  1189. if (occlusionBuffers_[i]->GetUseTimer() > MAX_BUFFER_AGE)
  1190. {
  1191. LOGDEBUG("Removed unused occlusion buffer");
  1192. occlusionBuffers_.Erase(i);
  1193. }
  1194. }
  1195. for (HashMap<long long, Vector<SharedPtr<Texture2D> > >::Iterator i = screenBuffers_.Begin(); i != screenBuffers_.End();)
  1196. {
  1197. HashMap<long long, Vector<SharedPtr<Texture2D> > >::Iterator current = i++;
  1198. Vector<SharedPtr<Texture2D> >& buffers = current->second_;
  1199. for (unsigned j = buffers.Size() - 1; j < buffers.Size(); --j)
  1200. {
  1201. Texture2D* buffer = buffers[j];
  1202. if (buffer->GetUseTimer() > MAX_BUFFER_AGE)
  1203. {
  1204. LOGDEBUG("Removed unused screen buffer size " + String(buffer->GetWidth()) + "x" + String(buffer->GetHeight()) + " format " + String(buffer->GetFormat()));
  1205. buffers.Erase(j);
  1206. }
  1207. }
  1208. if (buffers.Empty())
  1209. {
  1210. screenBufferAllocations_.Erase(current->first_);
  1211. screenBuffers_.Erase(current);
  1212. }
  1213. }
  1214. }
  1215. void Renderer::ResetShadowMapAllocations()
  1216. {
  1217. for (HashMap<int, PODVector<Light*> >::Iterator i = shadowMapAllocations_.Begin(); i != shadowMapAllocations_.End(); ++i)
  1218. i->second_.Clear();
  1219. }
  1220. void Renderer::ResetScreenBufferAllocations()
  1221. {
  1222. for (HashMap<long long, unsigned>::Iterator i = screenBufferAllocations_.Begin(); i != screenBufferAllocations_.End(); ++i)
  1223. i->second_ = 0;
  1224. }
  1225. void Renderer::Initialize()
  1226. {
  1227. Graphics* graphics = GetSubsystem<Graphics>();
  1228. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1229. if (!graphics || !graphics->IsInitialized() || !cache)
  1230. return;
  1231. PROFILE(InitRenderer);
  1232. graphics_ = graphics;
  1233. cache_ = cache;
  1234. #ifndef USE_OPENGL
  1235. shaderPath_ = "Shaders/HLSL/";
  1236. #else
  1237. shaderPath_ = "Shaders/GLSL/";
  1238. #endif
  1239. if (!graphics_->GetShadowMapFormat())
  1240. drawShadows_ = false;
  1241. defaultLightRamp_ = cache->GetResource<Texture2D>("Textures/Ramp.png");
  1242. defaultLightSpot_ = cache->GetResource<Texture2D>("Textures/Spot.png");
  1243. defaultMaterial_ = cache->GetResource<Material>("Materials/Default.xml");
  1244. // If default material not found, create one. This will actually not render properly, but prevents crashing
  1245. if (!defaultMaterial_)
  1246. defaultMaterial_ = new Material(context_);
  1247. CreateGeometries();
  1248. CreateInstancingBuffer();
  1249. viewports_.Resize(1);
  1250. ResetViews();
  1251. ResetShadowMaps();
  1252. ResetBuffers();
  1253. shadersDirty_ = true;
  1254. initialized_ = true;
  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. lightVS_.Clear();
  1272. lightPS_.Clear();
  1273. if (renderMode_ != RENDER_FORWARD)
  1274. {
  1275. lightVS_.Resize(MAX_DEFERRED_LIGHT_VS_VARIATIONS);
  1276. lightPS_.Resize(MAX_DEFERRED_LIGHT_PS_VARIATIONS);
  1277. unsigned shadows = (graphics_->GetHardwareShadowSupport() ? 1 : 0) | (shadowQuality_ & SHADOWQUALITY_HIGH_16BIT);
  1278. String shaderName = renderMode_ == RENDER_PREPASS ? "PrepassLight_" : "DeferredLight_";
  1279. for (unsigned i = 0; i < MAX_DEFERRED_LIGHT_VS_VARIATIONS; ++i)
  1280. lightVS_[i] = GetVertexShader(shaderName + deferredLightVSVariations[i]);
  1281. for (unsigned i = 0; i < lightPS_.Size(); ++i)
  1282. {
  1283. String ortho;
  1284. if (i >= DLPS_ORTHO)
  1285. ortho = "Ortho";
  1286. if (i & DLPS_SHADOW)
  1287. {
  1288. lightPS_[i] = GetPixelShader(shaderName + ortho + lightPSVariations[i % DLPS_ORTHO] +
  1289. shadowVariations[shadows]);
  1290. }
  1291. else
  1292. lightPS_[i] = GetPixelShader(shaderName + ortho + lightPSVariations[i % DLPS_ORTHO]);
  1293. }
  1294. }
  1295. shadersDirty_ = false;
  1296. }
  1297. void Renderer::LoadMaterialShaders(Technique* tech)
  1298. {
  1299. if (renderMode_ == RENDER_PREPASS && tech->HasPass(PASS_PREPASS))
  1300. {
  1301. LoadPassShaders(tech, PASS_PREPASS);
  1302. LoadPassShaders(tech, PASS_MATERIAL);
  1303. }
  1304. else if (renderMode_ == RENDER_DEFERRED && tech->HasPass(PASS_DEFERRED))
  1305. LoadPassShaders(tech, PASS_DEFERRED);
  1306. else
  1307. {
  1308. LoadPassShaders(tech, PASS_BASE);
  1309. LoadPassShaders(tech, PASS_LITBASE);
  1310. LoadPassShaders(tech, PASS_LIGHT);
  1311. }
  1312. LoadPassShaders(tech, PASS_PREALPHA);
  1313. LoadPassShaders(tech, PASS_POSTALPHA);
  1314. LoadPassShaders(tech, PASS_SHADOW);
  1315. }
  1316. void Renderer::LoadPassShaders(Technique* tech, PassType type)
  1317. {
  1318. Pass* pass = tech->GetPass(type);
  1319. if (!pass)
  1320. return;
  1321. unsigned shadows = (graphics_->GetHardwareShadowSupport() ? 1 : 0) | (shadowQuality_ & SHADOWQUALITY_HIGH_16BIT);
  1322. String vertexShaderName = pass->GetVertexShader();
  1323. String pixelShaderName = pass->GetPixelShader();
  1324. // Check if the shader name is already a variation in itself
  1325. if (vertexShaderName.Find('_') == String::NPOS)
  1326. vertexShaderName += "_";
  1327. if (pixelShaderName.Find('_') == String::NPOS)
  1328. pixelShaderName += "_";
  1329. Vector<SharedPtr<ShaderVariation> >& vertexShaders = pass->GetVertexShaders();
  1330. Vector<SharedPtr<ShaderVariation> >& pixelShaders = pass->GetPixelShaders();
  1331. // Forget all the old shaders
  1332. vertexShaders.Clear();
  1333. pixelShaders.Clear();
  1334. if (type == PASS_LIGHT || type == PASS_LITBASE)
  1335. {
  1336. // Load forward pixel lit variations
  1337. vertexShaders.Resize(MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS);
  1338. pixelShaders.Resize(MAX_LIGHT_PS_VARIATIONS);
  1339. for (unsigned j = 0; j < MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS; ++j)
  1340. {
  1341. unsigned g = j / MAX_LIGHT_VS_VARIATIONS;
  1342. unsigned l = j % MAX_LIGHT_VS_VARIATIONS;
  1343. vertexShaders[j] = GetVertexShader(vertexShaderName + lightVSVariations[l] + geometryVSVariations[g], g != 0);
  1344. }
  1345. for (unsigned j = 0; j < MAX_LIGHT_PS_VARIATIONS; ++j)
  1346. {
  1347. if (j & LPS_SHADOW)
  1348. pixelShaders[j] = GetPixelShader(pixelShaderName + lightPSVariations[j] + shadowVariations[shadows]);
  1349. else
  1350. pixelShaders[j] = GetPixelShader(pixelShaderName + lightPSVariations[j]);
  1351. }
  1352. }
  1353. else
  1354. {
  1355. // Load vertex light variations for forward ambient pass, deferred G-buffer pass and pre-pass material pass
  1356. if (type == PASS_BASE || type == PASS_MATERIAL || type == PASS_DEFERRED)
  1357. {
  1358. vertexShaders.Resize(MAX_VERTEXLIGHT_VS_VARIATIONS * MAX_GEOMETRYTYPES);
  1359. for (unsigned j = 0; j < MAX_GEOMETRYTYPES * MAX_VERTEXLIGHT_VS_VARIATIONS; ++j)
  1360. {
  1361. unsigned g = j / MAX_VERTEXLIGHT_VS_VARIATIONS;
  1362. unsigned l = j % MAX_VERTEXLIGHT_VS_VARIATIONS;
  1363. vertexShaders[j] = GetVertexShader(vertexShaderName + vertexLightVSVariations[l] + geometryVSVariations[g],
  1364. g != 0 || l != 0);
  1365. }
  1366. }
  1367. else
  1368. {
  1369. vertexShaders.Resize(MAX_GEOMETRYTYPES);
  1370. for (unsigned j = 0; j < MAX_GEOMETRYTYPES; ++j)
  1371. vertexShaders[j] = GetVertexShader(vertexShaderName + geometryVSVariations[j], j != 0);
  1372. }
  1373. pixelShaders.Resize(1);
  1374. pixelShaders[0] = GetPixelShader(pixelShaderName);
  1375. }
  1376. tech->MarkShadersLoaded(shadersChangedFrameNumber_);
  1377. }
  1378. void Renderer::ReleaseMaterialShaders()
  1379. {
  1380. PODVector<Material*> materials;
  1381. cache_->GetResources<Material>(materials);
  1382. for (unsigned i = 0; i < materials.Size(); ++i)
  1383. materials[i]->ReleaseShaders();
  1384. }
  1385. void Renderer::ReloadTextures()
  1386. {
  1387. PODVector<Resource*> textures;
  1388. cache_->GetResources(textures, Texture2D::GetTypeStatic());
  1389. for (unsigned i = 0; i < textures.Size(); ++i)
  1390. cache_->ReloadResource(textures[i]);
  1391. cache_->GetResources(textures, TextureCube::GetTypeStatic());
  1392. for (unsigned i = 0; i < textures.Size(); ++i)
  1393. cache_->ReloadResource(textures[i]);
  1394. }
  1395. void Renderer::CreateGeometries()
  1396. {
  1397. SharedPtr<VertexBuffer> dlvb(new VertexBuffer(context_));
  1398. dlvb->SetShadowed(true);
  1399. dlvb->SetSize(4, MASK_POSITION);
  1400. dlvb->SetData(dirLightVertexData);
  1401. SharedPtr<IndexBuffer> dlib(new IndexBuffer(context_));
  1402. dlib->SetShadowed(true);
  1403. dlib->SetSize(6, false);
  1404. dlib->SetData(dirLightIndexData);
  1405. dirLightGeometry_ = new Geometry(context_);
  1406. dirLightGeometry_->SetVertexBuffer(0, dlvb);
  1407. dirLightGeometry_->SetIndexBuffer(dlib);
  1408. dirLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, dlib->GetIndexCount());
  1409. SharedPtr<VertexBuffer> slvb(new VertexBuffer(context_));
  1410. slvb->SetShadowed(true);
  1411. slvb->SetSize(8, MASK_POSITION);
  1412. slvb->SetData(spotLightVertexData);
  1413. SharedPtr<IndexBuffer> slib(new IndexBuffer(context_));
  1414. slib->SetShadowed(true);
  1415. slib->SetSize(36, false);
  1416. slib->SetData(spotLightIndexData);
  1417. spotLightGeometry_ = new Geometry(context_);
  1418. spotLightGeometry_->SetVertexBuffer(0, slvb);
  1419. spotLightGeometry_->SetIndexBuffer(slib);
  1420. spotLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, slib->GetIndexCount());
  1421. SharedPtr<VertexBuffer> plvb(new VertexBuffer(context_));
  1422. plvb->SetShadowed(true);
  1423. plvb->SetSize(24, MASK_POSITION);
  1424. plvb->SetData(pointLightVertexData);
  1425. SharedPtr<IndexBuffer> plib(new IndexBuffer(context_));
  1426. plib->SetShadowed(true);
  1427. plib->SetSize(132, false);
  1428. plib->SetData(pointLightIndexData);
  1429. pointLightGeometry_ = new Geometry(context_);
  1430. pointLightGeometry_->SetVertexBuffer(0, plvb);
  1431. pointLightGeometry_->SetIndexBuffer(plib);
  1432. pointLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, plib->GetIndexCount());
  1433. #if !defined(USE_OPENGL) || !defined(GL_ES_VERSION_2_0)
  1434. if (graphics_->GetShadowMapFormat())
  1435. {
  1436. faceSelectCubeMap_ = new TextureCube(context_);
  1437. faceSelectCubeMap_->SetNumLevels(1);
  1438. faceSelectCubeMap_->SetSize(1, graphics_->GetRGBAFormat());
  1439. faceSelectCubeMap_->SetFilterMode(FILTER_NEAREST);
  1440. indirectionCubeMap_ = new TextureCube(context_);
  1441. indirectionCubeMap_->SetNumLevels(1);
  1442. indirectionCubeMap_->SetSize(256, graphics_->GetRGBAFormat());
  1443. indirectionCubeMap_->SetFilterMode(FILTER_BILINEAR);
  1444. indirectionCubeMap_->SetAddressMode(COORD_U, ADDRESS_CLAMP);
  1445. indirectionCubeMap_->SetAddressMode(COORD_V, ADDRESS_CLAMP);
  1446. indirectionCubeMap_->SetAddressMode(COORD_W, ADDRESS_CLAMP);
  1447. SetIndirectionTextureData();
  1448. }
  1449. #endif
  1450. }
  1451. void Renderer::SetIndirectionTextureData()
  1452. {
  1453. unsigned char data[256 * 256 * 4];
  1454. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1455. {
  1456. unsigned axis = i / 2;
  1457. data[0] = (axis == 0) ? 255 : 0;
  1458. data[1] = (axis == 1) ? 255 : 0;
  1459. data[2] = (axis == 2) ? 255 : 0;
  1460. data[3] = 0;
  1461. faceSelectCubeMap_->SetData((CubeMapFace)i, 0, 0, 0, 1, 1, data);
  1462. }
  1463. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1464. {
  1465. unsigned char faceX = (i & 1) * 255;
  1466. unsigned char faceY = (i / 2) * 255 / 3;
  1467. unsigned char* dest = data;
  1468. for (unsigned y = 0; y < 256; ++y)
  1469. {
  1470. for (unsigned x = 0; x < 256; ++x)
  1471. {
  1472. #ifdef USE_OPENGL
  1473. *dest++ = x;
  1474. *dest++ = 255 - y;
  1475. *dest++ = faceX;
  1476. *dest++ = 255 * 2 / 3 - faceY;
  1477. #else
  1478. *dest++ = x;
  1479. *dest++ = y;
  1480. *dest++ = faceX;
  1481. *dest++ = faceY;
  1482. #endif
  1483. }
  1484. }
  1485. indirectionCubeMap_->SetData((CubeMapFace)i, 0, 0, 0, 256, 256, data);
  1486. }
  1487. faceSelectCubeMap_->ClearDataLost();
  1488. indirectionCubeMap_->ClearDataLost();
  1489. }
  1490. void Renderer::CreateInstancingBuffer()
  1491. {
  1492. // Do not create buffer if instancing not supported
  1493. if (!graphics_->GetSM3Support())
  1494. {
  1495. instancingBuffer_.Reset();
  1496. dynamicInstancing_ = false;
  1497. return;
  1498. }
  1499. // If must lock the buffer for each batch group, set a smaller size
  1500. unsigned defaultSize = graphics_->GetStreamOffsetSupport() ? INSTANCING_BUFFER_DEFAULT_SIZE : INSTANCING_BUFFER_DEFAULT_SIZE / 4;
  1501. instancingBuffer_ = new VertexBuffer(context_);
  1502. if (!instancingBuffer_->SetSize(defaultSize, INSTANCING_BUFFER_MASK, true))
  1503. {
  1504. instancingBuffer_.Reset();
  1505. dynamicInstancing_ = false;
  1506. }
  1507. }
  1508. void Renderer::ResetShadowMaps()
  1509. {
  1510. shadowMaps_.Clear();
  1511. shadowMapAllocations_.Clear();
  1512. colorShadowMaps_.Clear();
  1513. }
  1514. void Renderer::ResetBuffers()
  1515. {
  1516. occlusionBuffers_.Clear();
  1517. screenBuffers_.Clear();
  1518. screenBufferAllocations_.Clear();
  1519. }
  1520. void Renderer::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  1521. {
  1522. if (!initialized_)
  1523. Initialize();
  1524. else
  1525. {
  1526. // When screen mode changes, purge old views
  1527. ResetViews();
  1528. }
  1529. }
  1530. void Renderer::HandleGraphicsFeatures(StringHash eventType, VariantMap& eventData)
  1531. {
  1532. // Reinitialize if already initialized
  1533. if (initialized_)
  1534. Initialize();
  1535. }
  1536. void Renderer::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  1537. {
  1538. if (initialized_)
  1539. {
  1540. using namespace RenderUpdate;
  1541. Update(eventData[P_TIMESTEP].GetFloat());
  1542. }
  1543. }
  1544. }