Renderer.cpp 55 KB

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