Renderer.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Camera.h"
  25. #include "CoreEvents.h"
  26. #include "DebugRenderer.h"
  27. #include "Geometry.h"
  28. #include "Graphics.h"
  29. #include "GraphicsEvents.h"
  30. #include "GraphicsImpl.h"
  31. #include "IndexBuffer.h"
  32. #include "Light.h"
  33. #include "Log.h"
  34. #include "Material.h"
  35. #include "OcclusionBuffer.h"
  36. #include "Octree.h"
  37. #include "OctreeQuery.h"
  38. #include "Profiler.h"
  39. #include "Renderer.h"
  40. #include "ResourceCache.h"
  41. #include "Scene.h"
  42. #include "Shader.h"
  43. #include "ShaderVariation.h"
  44. #include "Technique.h"
  45. #include "Texture2D.h"
  46. #include "TextureCube.h"
  47. #include "VertexBuffer.h"
  48. #include "View.h"
  49. #include "XMLFile.h"
  50. #include "Zone.h"
  51. #include "DebugNew.h"
  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. // Use slightly clamped Z-range so that shadowed point light splits line up nicely
  141. 0.00001f, 0.00001f, 0.00001f,
  142. 0.00001f, -0.00001f, 0.00001f,
  143. -0.00001f, -0.00001f, 0.00001f,
  144. -0.00001f, 0.00001f, 0.00001f,
  145. 1.00000f, 1.00000f, 0.99999f,
  146. 1.00000f, -1.00000f, 0.99999f,
  147. -1.00000f, -1.00000f, 0.99999f,
  148. -1.00000f, 1.00000f, 0.99999f,
  149. };
  150. static const unsigned short spotLightIndexData[] =
  151. {
  152. 3, 0, 1,
  153. 3, 1, 2,
  154. 0, 4, 5,
  155. 0, 5, 1,
  156. 3, 7, 4,
  157. 3, 4, 0,
  158. 7, 3, 2,
  159. 7, 2, 6,
  160. 6, 2, 1,
  161. 6, 1, 5,
  162. 7, 5, 4,
  163. 7, 6, 5
  164. };
  165. static const String shadowVariations[] =
  166. {
  167. // No specific hardware shadow compare variation on OpenGL, it is always supported
  168. #ifdef USE_OPENGL
  169. "LQ",
  170. "LQ",
  171. "",
  172. ""
  173. #else
  174. "LQ",
  175. "LQHW",
  176. "",
  177. "HW"
  178. #endif
  179. };
  180. static const String fallbackVariations[] =
  181. {
  182. "",
  183. "FB"
  184. };
  185. static const String linearVariations[] =
  186. {
  187. "",
  188. "Linear"
  189. };
  190. static const String depthVariations[] =
  191. {
  192. "",
  193. "Depth"
  194. };
  195. static const String geometryVSVariations[] =
  196. {
  197. "",
  198. "Skinned",
  199. "Instanced",
  200. "Billboard"
  201. };
  202. static const String lightVSVariations[] =
  203. {
  204. "",
  205. "Spot",
  206. "Shadow",
  207. "SpotShadow"
  208. };
  209. static const String deferredLightVSVariations[] =
  210. {
  211. "",
  212. "Dir",
  213. "Ortho",
  214. "OrthoDir"
  215. };
  216. static const String lightPSVariations[] =
  217. {
  218. "Dir",
  219. "DirSpec",
  220. "Spot",
  221. "SpotSpec",
  222. "Point",
  223. "PointSpec",
  224. "PointMask",
  225. "PointMaskSpec",
  226. "DirShadow",
  227. "DirShadowSpec",
  228. "SpotShadow",
  229. "SpotShadowSpec",
  230. "PointShadow",
  231. "PointShadowSpec",
  232. "PointMaskShadow",
  233. "PointMaskShadowSpec",
  234. "OrthoDir",
  235. "OrthoDirSpec",
  236. "OrthoSpot",
  237. "OrthoSpotSpec",
  238. "OrthoPoint",
  239. "OrthoPointSpec",
  240. "OrthoPointMask",
  241. "OrthoPointMaskSpec",
  242. "OrthoDirShadow",
  243. "OrthoDirShadowSpec",
  244. "OrthoSpotShadow",
  245. "OrthoSpotShadowSpec",
  246. "OrthoPointShadow",
  247. "OrthoPointShadowSpec",
  248. "OrthoPointMaskShadow",
  249. "OrthoPointMaskShadowSpec"
  250. };
  251. static const unsigned INSTANCING_BUFFER_MASK = MASK_INSTANCEMATRIX1 | MASK_INSTANCEMATRIX2 | MASK_INSTANCEMATRIX3;
  252. static const Viewport noViewport;
  253. OBJECTTYPESTATIC(Renderer);
  254. Renderer::Renderer(Context* context) :
  255. Object(context),
  256. defaultZone_(new Zone(context)),
  257. numViews_(0),
  258. numShadowCameras_(0),
  259. numSplitLights_(0),
  260. numTempNodes_(0),
  261. specularLighting_(true),
  262. drawShadows_(true),
  263. textureAnisotropy_(4),
  264. textureFilterMode_(FILTER_TRILINEAR),
  265. textureQuality_(QUALITY_HIGH),
  266. materialQuality_(QUALITY_HIGH),
  267. shadowMapSize_(1024),
  268. shadowQuality_(SHADOWQUALITY_HIGH_16BIT),
  269. reuseShadowMaps_(true),
  270. dynamicInstancing_(true),
  271. minInstanceGroupSize_(4),
  272. maxInstanceTriangles_(500),
  273. maxOccluderTriangles_(5000),
  274. occlusionBufferSize_(256),
  275. occluderSizeThreshold_(0.1f),
  276. shadersChangedFrameNumber_(M_MAX_UNSIGNED),
  277. shadersDirty_(true),
  278. initialized_(false)
  279. {
  280. SubscribeToEvent(E_SCREENMODE, HANDLER(Renderer, HandleScreenMode));
  281. SubscribeToEvent(E_RENDERUPDATE, HANDLER(Renderer, HandleRenderUpdate));
  282. // Default to one of each shadow map resolution
  283. for (unsigned i = 0; i < NUM_SHADOWMAP_RESOLUTIONS; ++i)
  284. shadowMaps_[i].Resize(1);
  285. // Try to initialize right now, but skip if screen mode is not yet set
  286. Initialize();
  287. }
  288. Renderer::~Renderer()
  289. {
  290. }
  291. void Renderer::SetNumViewports(unsigned num)
  292. {
  293. viewports_.Resize(num);
  294. }
  295. void Renderer::SetViewport(unsigned index, const Viewport& viewport)
  296. {
  297. if (index >= viewports_.Size())
  298. {
  299. LOGERROR("Viewport index out of bounds");
  300. return;
  301. }
  302. viewports_[index] = viewport;
  303. }
  304. void Renderer::SetSpecularLighting(bool enable)
  305. {
  306. specularLighting_ = enable;
  307. }
  308. void Renderer::SetDrawShadows(bool enable)
  309. {
  310. if (!graphics_)
  311. return;
  312. drawShadows_ = enable;
  313. if (!CreateShadowMaps())
  314. drawShadows_ = false;
  315. }
  316. void Renderer::SetTextureAnisotropy(int level)
  317. {
  318. textureAnisotropy_ = Max(level, 1);
  319. }
  320. void Renderer::SetTextureFilterMode(TextureFilterMode mode)
  321. {
  322. textureFilterMode_ = mode;
  323. }
  324. void Renderer::SetTextureQuality(int quality)
  325. {
  326. quality = Clamp(quality, QUALITY_LOW, QUALITY_HIGH);
  327. if (quality != textureQuality_)
  328. {
  329. textureQuality_ = quality;
  330. ReloadTextures();
  331. }
  332. }
  333. void Renderer::SetMaterialQuality(int quality)
  334. {
  335. materialQuality_ = Clamp(quality, QUALITY_LOW, QUALITY_MAX);
  336. shadersDirty_ = true;
  337. ResetViews();
  338. }
  339. void Renderer::SetShadowMapSize(int size)
  340. {
  341. if (!graphics_)
  342. return;
  343. shadowMapSize_ = Max(size, SHADOW_MIN_PIXELS);
  344. if (!CreateShadowMaps())
  345. {
  346. shadowMapSize_ = 1024;
  347. if (!CreateShadowMaps())
  348. drawShadows_ = false;
  349. }
  350. }
  351. void Renderer::SetShadowQuality(int quality)
  352. {
  353. if (!graphics_)
  354. return;
  355. quality &= SHADOWQUALITY_HIGH_24BIT;
  356. if (!graphics_->GetHiresShadowSupport())
  357. quality &= SHADOWQUALITY_HIGH_16BIT;
  358. if (quality != shadowQuality_)
  359. {
  360. shadowQuality_ = quality;
  361. shadersDirty_ = true;
  362. if (!CreateShadowMaps())
  363. drawShadows_ = false;
  364. }
  365. }
  366. void Renderer::SetReuseShadowMaps(bool enable)
  367. {
  368. if (enable == reuseShadowMaps_)
  369. return;
  370. reuseShadowMaps_ = enable;
  371. if (reuseShadowMaps_)
  372. {
  373. for (unsigned i = 0; i < NUM_SHADOWMAP_RESOLUTIONS; ++i)
  374. shadowMaps_[i].Resize(1);
  375. }
  376. if (!CreateShadowMaps())
  377. drawShadows_ = false;
  378. shadersDirty_ = true;
  379. }
  380. void Renderer::SetNumShadowMaps(unsigned full, unsigned half, unsigned quarter)
  381. {
  382. shadowMaps_[0].Resize(full ? full : 1);
  383. shadowMaps_[1].Resize(half ? half : 1);
  384. shadowMaps_[2].Resize(quarter ? quarter : 1);
  385. if (!CreateShadowMaps())
  386. drawShadows_ = false;
  387. }
  388. void Renderer::SetDynamicInstancing(bool enable)
  389. {
  390. if (!instancingBuffer_)
  391. enable = false;
  392. dynamicInstancing_ = enable;
  393. }
  394. void Renderer::SetMinInstanceGroupSize(int size)
  395. {
  396. minInstanceGroupSize_ = Max(size, 2);
  397. }
  398. void Renderer::SetMaxInstanceTriangles(int triangles)
  399. {
  400. maxInstanceTriangles_ = Max(triangles, 0);
  401. }
  402. void Renderer::SetMaxOccluderTriangles(int triangles)
  403. {
  404. maxOccluderTriangles_ = Max(triangles, 0);
  405. }
  406. void Renderer::SetOcclusionBufferSize(int size)
  407. {
  408. occlusionBufferSize_ = Max(size, 1);
  409. occlusionBuffers_.Clear();
  410. }
  411. void Renderer::SetOccluderSizeThreshold(float screenSize)
  412. {
  413. occluderSizeThreshold_ = Max(screenSize, 0.0f);
  414. }
  415. const Viewport& Renderer::GetViewport(unsigned index) const
  416. {
  417. return index < viewports_.Size() ? viewports_[index] : noViewport;
  418. }
  419. ShaderVariation* Renderer::GetVertexShader(const String& name, bool checkExists) const
  420. {
  421. return GetShader(name, vsFormat_, checkExists);
  422. }
  423. ShaderVariation* Renderer::GetPixelShader(const String& name, bool checkExists) const
  424. {
  425. return GetShader(name, psFormat_, checkExists);
  426. }
  427. unsigned Renderer::GetNumGeometries(bool allViews) const
  428. {
  429. unsigned numGeometries = 0;
  430. unsigned lastView = allViews ? numViews_ : 1;
  431. for (unsigned i = 0; i < lastView; ++i)
  432. numGeometries += views_[i]->GetGeometries().Size();
  433. return numGeometries;
  434. }
  435. unsigned Renderer::GetNumLights(bool allViews) const
  436. {
  437. unsigned nulights_ = 0;
  438. unsigned lastView = allViews ? numViews_ : 1;
  439. for (unsigned i = 0; i < lastView; ++i)
  440. nulights_ += views_[i]->GetLights().Size();
  441. return nulights_;
  442. }
  443. unsigned Renderer::GetNumShadowMaps(bool allViews) const
  444. {
  445. unsigned numShadowMaps = 0;
  446. unsigned lastView = allViews ? numViews_ : 1;
  447. for (unsigned i = 0; i < lastView; ++i)
  448. {
  449. const Vector<LightBatchQueue>& lightQueues = views_[i]->GetLightQueues();
  450. for (unsigned j = 0; j < lightQueues.Size(); ++j)
  451. {
  452. Light* light = lightQueues[j].light_;
  453. if (light && light->GetShadowMap())
  454. ++numShadowMaps;
  455. }
  456. }
  457. return numShadowMaps;
  458. }
  459. unsigned Renderer::GetNumOccluders(bool allViews) const
  460. {
  461. unsigned numOccluders = 0;
  462. unsigned lastView = allViews ? numViews_ : 1;
  463. for (unsigned i = 0; i < lastView; ++i)
  464. numOccluders += views_[i]->GetOccluders().Size();
  465. return numOccluders;
  466. }
  467. unsigned Renderer::GetNumShadowOccluders(bool allViews) const
  468. {
  469. unsigned numShadowOccluders = 0;
  470. unsigned lastView = allViews ? numViews_ : 1;
  471. for (unsigned i = 0; i < lastView; ++i)
  472. numShadowOccluders += views_[i]->GetShadowOccluders().Size();
  473. return numShadowOccluders;
  474. }
  475. const OcclusionBuffer* Renderer::GetOcclusionBuffer(float aspectRatio, bool halfResolution)
  476. {
  477. // Return an occlusion buffer for debug output purposes. Do not allocate new
  478. int width = occlusionBufferSize_;
  479. int height = (int)(occlusionBufferSize_ / aspectRatio);
  480. if (halfResolution)
  481. {
  482. width >>= 1;
  483. height >>= 1;
  484. }
  485. int searchKey = (width << 16) | height;
  486. HashMap<int, SharedPtr<OcclusionBuffer> >::Iterator i = occlusionBuffers_.Find(searchKey);
  487. if (i != occlusionBuffers_.End())
  488. return i->second_;
  489. else
  490. return 0;
  491. }
  492. void Renderer::Update(float timeStep)
  493. {
  494. PROFILE(UpdateViews);
  495. numViews_ = 0;
  496. // If device lost, do not perform update. This is because any dynamic vertex/index buffer updates happen already here,
  497. // and if the device is lost, the updates queue up, causing memory use to rise constantly
  498. if (!graphics_ || !graphics_->IsInitialized() || graphics_->IsDeviceLost())
  499. return;
  500. // Advance frame number & time, set up the frameinfo structure, and reset views & stats
  501. frame_.frameNumber_ = GetSubsystem<Time>()->GetFrameNumber();
  502. frame_.timeStep_ = timeStep;
  503. frame_.camera_ = 0;
  504. numShadowCameras_ = 0;
  505. numSplitLights_ = 0;
  506. numTempNodes_ = 0;
  507. updateOctrees_.Clear();
  508. // Reload shaders if needed
  509. if (shadersDirty_)
  510. LoadShaders();
  511. // Process all viewports. Use reverse order, because during rendering the order will be reversed again to handle auxiliary
  512. // view dependencies correctly
  513. for (unsigned i = viewports_.Size() - 1; i < viewports_.Size(); --i)
  514. {
  515. unsigned mainView = numViews_;
  516. Viewport& viewport = viewports_[i];
  517. if (!AddView(0, viewport))
  518. continue;
  519. // Update octree (perform early update for nodes which need that, and reinsert moved nodes.)
  520. // However, if the same scene is viewed from multiple cameras, update the octree only once
  521. Octree* octree = viewport.scene_->GetComponent<Octree>();
  522. DebugRenderer* debug = viewport.scene_->GetComponent<DebugRenderer>();
  523. if (!updateOctrees_.Contains(octree))
  524. {
  525. frame_.camera_ = viewport.camera_;
  526. frame_.viewSize_ = IntVector2(viewport.rect_.right_ - viewport.rect_.left_, viewport.rect_.bottom_ - viewport.rect_.top_);
  527. if (frame_.viewSize_ == IntVector2::ZERO)
  528. frame_.viewSize_ = IntVector2(graphics_->GetWidth(), graphics_->GetHeight());
  529. octree->Update(frame_);
  530. updateOctrees_.Insert(octree);
  531. // Set also the view for the debug graphics already here, so that it can use culling
  532. /// \todo May result in incorrect debug geometry culling if the same scene is drawn from multiple viewports
  533. if (debug)
  534. debug->SetView(viewport.camera_);
  535. }
  536. // Update the viewport's main view and any auxiliary views it Creates
  537. for (unsigned i = mainView; i < numViews_; ++i)
  538. views_[i]->Update(frame_);
  539. }
  540. return;
  541. }
  542. void Renderer::Render()
  543. {
  544. if (!graphics_)
  545. return;
  546. PROFILE(RenderViews);
  547. graphics_->SetDefaultTextureFilterMode(textureFilterMode_);
  548. graphics_->SetTextureAnisotropy(textureAnisotropy_);
  549. // If no views, just clear the screen
  550. if (!numViews_)
  551. {
  552. numPrimitives_ = 0;
  553. numBatches_ = 0;
  554. graphics_->SetAlphaTest(false);
  555. graphics_->SetBlendMode(BLEND_REPLACE);
  556. graphics_->SetColorWrite(true);
  557. graphics_->SetDepthWrite(true);
  558. graphics_->SetFillMode(FILL_SOLID);
  559. graphics_->SetScissorTest(false);
  560. graphics_->SetStencilTest(false);
  561. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH | CLEAR_STENCIL);
  562. return;
  563. }
  564. // Render views from last to first (each main view is rendered after the auxiliary views it depends on)
  565. for (unsigned i = numViews_ - 1; i < numViews_; --i)
  566. views_[i]->Render();
  567. // Copy the number of batches & primitives from Graphics so that we can account for 3D geometry only
  568. numPrimitives_ = graphics_->GetNumPrimitives();
  569. numBatches_ = graphics_->GetNumBatches();
  570. }
  571. void Renderer::DrawDebugGeometry(bool depthTest)
  572. {
  573. PROFILE(RendererDrawDebug);
  574. /// \todo Because debug geometry is per-scene, if two cameras show views of the same area, occlusion is not shown correctly
  575. HashSet<Drawable*> processedGeometries;
  576. HashSet<Light*> processedLights;
  577. for (unsigned i = 0; i < numViews_; ++i)
  578. {
  579. // Make sure it's a main view, and process each node only once
  580. View* view = views_[i];
  581. if (view->GetRenderTarget())
  582. continue;
  583. Octree* octree = view->GetOctree();
  584. if (!octree)
  585. continue;
  586. Scene* scene = static_cast<Scene*>(octree->GetNode());
  587. if (!scene)
  588. continue;
  589. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  590. if (!debug)
  591. continue;
  592. const PODVector<Drawable*>& geometries = view->GetGeometries();
  593. const PODVector<Light*>& lights = view->GetLights();
  594. for (unsigned i = 0; i < geometries.Size(); ++i)
  595. {
  596. if (!processedGeometries.Contains(geometries[i]))
  597. {
  598. geometries[i]->DrawDebugGeometry(debug, depthTest);
  599. processedGeometries.Insert(geometries[i]);
  600. }
  601. }
  602. for (unsigned i = 0; i < lights.Size(); ++i)
  603. {
  604. if (!processedLights.Contains(lights[i]))
  605. {
  606. lights[i]->DrawDebugGeometry(debug, depthTest);
  607. processedLights.Insert(lights[i]);
  608. }
  609. }
  610. }
  611. }
  612. void Renderer::Initialize()
  613. {
  614. Graphics* graphics = GetSubsystem<Graphics>();
  615. ResourceCache* cache = GetSubsystem<ResourceCache>();
  616. if (!graphics || !graphics->IsInitialized() || !cache)
  617. return;
  618. PROFILE(InitRenderer);
  619. graphics_ = graphics;
  620. cache_ = cache;
  621. // Check shader model support
  622. #ifndef USE_OPENGL
  623. if (graphics_->GetSM3Support())
  624. {
  625. shaderPath_ = "Shaders/SM3/";
  626. vsFormat_ = ".vs3";
  627. psFormat_ = ".ps3";
  628. }
  629. else
  630. {
  631. shaderPath_ = "Shaders/SM2/";
  632. vsFormat_ = ".vs2";
  633. psFormat_ = ".ps2";
  634. }
  635. #else
  636. {
  637. shaderPath_ = "Shaders/GLSL/";
  638. vsFormat_ = ".vert";
  639. psFormat_ = ".frag";
  640. }
  641. #endif
  642. defaultLightRamp_ = cache->GetResource<Texture2D>("Textures/Ramp.png");
  643. defaultLightSpot = cache->GetResource<Texture2D>("Textures/Spot.png");
  644. defaultMaterial_ = cache->GetResource<Material>("Materials/Default.xml");
  645. CreateGeometries();
  646. CreateInstancingBuffer();
  647. if (!CreateShadowMaps())
  648. drawShadows_ = false;
  649. viewports_.Resize(1);
  650. ResetViews();
  651. LOGINFO("Initialized renderer");
  652. initialized_ = true;
  653. }
  654. void Renderer::ResetViews()
  655. {
  656. views_.Clear();
  657. numViews_ = 0;
  658. }
  659. bool Renderer::AddView(RenderSurface* renderTarget, const Viewport& viewport)
  660. {
  661. // If using a render target texture, make sure it will not be rendered to multiple times
  662. if (renderTarget)
  663. {
  664. for (unsigned i = 0; i < numViews_; ++i)
  665. {
  666. if (views_[i]->GetRenderTarget() == renderTarget)
  667. return false;
  668. }
  669. }
  670. if (views_.Size() <= numViews_)
  671. views_.Resize(numViews_ + 1);
  672. if (!views_[numViews_])
  673. views_[numViews_] = new View(context_);
  674. if (views_[numViews_]->Define(renderTarget, viewport))
  675. {
  676. ++numViews_;
  677. return true;
  678. }
  679. else
  680. return false;
  681. }
  682. OcclusionBuffer* Renderer::GetOrCreateOcclusionBuffer(Camera* camera, int maxOccluderTriangles, bool halfResolution)
  683. {
  684. // Get an occlusion buffer matching the aspect ratio. If not found, allocate new
  685. int width = occlusionBufferSize_;
  686. int height = (int)(occlusionBufferSize_ / camera->GetAspectRatio());
  687. if (halfResolution)
  688. {
  689. width >>= 1;
  690. height >>= 1;
  691. }
  692. int searchKey = (width << 16) | height;
  693. SharedPtr<OcclusionBuffer> buffer;
  694. HashMap<int, SharedPtr<OcclusionBuffer> >::Iterator i = occlusionBuffers_.Find(searchKey);
  695. if (i != occlusionBuffers_.End())
  696. buffer = i->second_;
  697. else
  698. {
  699. buffer = new OcclusionBuffer(context_);
  700. buffer->SetSize(width, height);
  701. occlusionBuffers_[searchKey] = buffer;
  702. }
  703. buffer->SetView(camera);
  704. buffer->SetMaxTriangles(maxOccluderTriangles);
  705. buffer->Clear();
  706. return buffer;
  707. }
  708. Geometry* Renderer::GetLightGeometry(Light* light)
  709. {
  710. switch (light->GetLightType())
  711. {
  712. case LIGHT_POINT:
  713. return pointLightGeometry_;
  714. case LIGHT_SPOT:
  715. case LIGHT_SPLITPOINT:
  716. return spotLightGeometry_;
  717. default:
  718. return dirLightGeometry_;
  719. }
  720. }
  721. Texture2D* Renderer::GetShadowMap(float resolution)
  722. {
  723. unsigned index = 0;
  724. if (resolution < 0.75f)
  725. index = (resolution >= 0.375f) ? 1 : 2;
  726. if (reuseShadowMaps_)
  727. return shadowMaps_[index][0];
  728. else
  729. {
  730. // If higher resolution shadow maps already used up, fall back to lower resolutions
  731. while (index < NUM_SHADOWMAP_RESOLUTIONS)
  732. {
  733. if (shadowMapUseCount_[index] < shadowMaps_[index].Size())
  734. return shadowMaps_[index][shadowMapUseCount_[index]++];
  735. ++index;
  736. }
  737. return 0;
  738. }
  739. }
  740. void Renderer::ResetShadowMapUseCount()
  741. {
  742. for (unsigned i = 0; i < NUM_SHADOWMAP_RESOLUTIONS; ++i)
  743. shadowMapUseCount_[i] = 0;
  744. }
  745. ShaderVariation* Renderer::GetShader(const String& name, const String& extension, bool checkExists) const
  746. {
  747. String shaderName = shaderPath_;
  748. String variationName;
  749. unsigned split = name.Find('_');
  750. if (split != String::NPOS)
  751. {
  752. shaderName += name.Substring(0, split) + extension;
  753. variationName = name.Substring(split + 1);
  754. }
  755. else
  756. shaderName += name + extension;
  757. if (checkExists)
  758. {
  759. if (!cache_->Exists(shaderName))
  760. return 0;
  761. }
  762. Shader* shader = cache_->GetResource<Shader>(shaderName);
  763. if (shader)
  764. return shader->GetVariation(variationName);
  765. else
  766. return 0;
  767. }
  768. void Renderer::SetBatchShaders(Batch& batch, Technique* technique, Pass* pass, bool allowShadows)
  769. {
  770. batch.pass_ = pass;
  771. // Check if shaders are unloaded or need reloading
  772. Vector<SharedPtr<ShaderVariation> >& vertexShaders = pass->GetVertexShaders();
  773. Vector<SharedPtr<ShaderVariation> >& pixelShaders = pass->GetPixelShaders();
  774. if (!vertexShaders.Size() || !pixelShaders.Size() || technique->GetShadersLoadedFrameNumber() !=
  775. shadersChangedFrameNumber_)
  776. {
  777. // First release all previous shaders, then load
  778. technique->ReleaseShaders();
  779. LoadMaterialShaders(technique);
  780. }
  781. // Make sure shaders are loaded now
  782. if (vertexShaders.Size() && pixelShaders.Size())
  783. {
  784. // Check whether is a forward lit pass. If not, there is only one pixel shader
  785. PassType type = pass->GetType();
  786. if (type == PASS_LIGHT || type == PASS_LITBASE)
  787. {
  788. Light* light = batch.light_;
  789. if (!light)
  790. {
  791. // Do not log error, as it would result in a lot of spam
  792. batch.vertexShader_ = 0;
  793. batch.pixelShader_ = 0;
  794. return;
  795. }
  796. unsigned vsi = 0;
  797. unsigned psi = 0;
  798. vsi = batch.geometryType_ * MAX_LIGHT_VS_VARIATIONS;
  799. bool materialHasSpecular = batch.material_ ? batch.material_->GetSpecular() : true;
  800. if (specularLighting_ && light->GetSpecularIntensity() > 0.0f && materialHasSpecular)
  801. psi += LPS_SPEC;
  802. if (allowShadows && light->GetShadowMap())
  803. {
  804. vsi += LVS_SHADOW;
  805. psi += LPS_SHADOW;
  806. }
  807. switch (light->GetLightType())
  808. {
  809. case LIGHT_POINT:
  810. case LIGHT_SPLITPOINT:
  811. if (light->GetShapeTexture())
  812. psi += LPS_POINTMASK;
  813. else
  814. psi += LPS_POINT;
  815. break;
  816. case LIGHT_SPOT:
  817. psi += LPS_SPOT;
  818. vsi += LVS_SPOT;
  819. break;
  820. }
  821. batch.vertexShader_ = vertexShaders[vsi];
  822. batch.pixelShader_ = pixelShaders[psi];
  823. batch.vertexShaderIndex_ = vsi;
  824. }
  825. else
  826. {
  827. unsigned vsi = batch.geometryType_;
  828. batch.vertexShader_ = vertexShaders[vsi];
  829. batch.pixelShader_ = pixelShaders[0];
  830. batch.vertexShaderIndex_ = vsi;
  831. }
  832. }
  833. batch.CalculateSortKey();
  834. // Log error if shaders could not be assigned, but only once per technique
  835. if (!batch.vertexShader_ || !batch.pixelShader_)
  836. {
  837. if (!shaderErrorDisplayed_.Contains(technique))
  838. {
  839. shaderErrorDisplayed_.Insert(technique);
  840. LOGERROR("Technique " + technique->GetName() + " has missing shaders");
  841. }
  842. }
  843. }
  844. void Renderer::SetLightVolumeShaders(Batch& batch)
  845. {
  846. unsigned vsi = DLVS_NONE;
  847. unsigned psi = DLPS_NONE;
  848. Light* light = batch.light_;
  849. switch (light->GetLightType())
  850. {
  851. case LIGHT_DIRECTIONAL:
  852. vsi += DLVS_DIR;
  853. break;
  854. case LIGHT_POINT:
  855. case LIGHT_SPLITPOINT:
  856. if (light->GetShapeTexture())
  857. psi += DLPS_POINTMASK;
  858. else
  859. psi += DLPS_POINT;
  860. break;
  861. case LIGHT_SPOT:
  862. psi += DLPS_SPOT;
  863. break;
  864. }
  865. if (light->GetShadowMap())
  866. psi += DLPS_SHADOW;
  867. // Deferred fallback mode does not support specular
  868. if (specularLighting_ && light->GetSpecularIntensity() > 0.0f && !graphics_->GetFallback())
  869. psi += DLPS_SPEC;
  870. if (batch.camera_->IsOrthographic())
  871. {
  872. vsi += DLVS_ORTHO;
  873. psi += DLPS_ORTHO;
  874. }
  875. batch.material_ = 0;
  876. batch.pass_ = 0;
  877. batch.vertexShader_ = lightVS_[vsi];
  878. batch.pixelShader_ = lightPS_[psi];
  879. batch.vertexShaderIndex_ = vsi;
  880. batch.CalculateSortKey();
  881. }
  882. void Renderer::LoadShaders()
  883. {
  884. LOGINFO("Reloading shaders");
  885. // Release old material shaders, mark them for reload
  886. ReleaseMaterialShaders();
  887. shadersChangedFrameNumber_ = GetSubsystem<Time>()->GetFrameNumber();
  888. // Load inbuilt shaders
  889. stencilVS_ = GetVertexShader("Stencil");
  890. stencilPS_ = GetPixelShader("Stencil");
  891. lightVS_.Clear();
  892. lightPS_.Clear();
  893. RenderMode mode = graphics_->GetRenderMode();
  894. if (mode != RENDER_FORWARD)
  895. {
  896. lightVS_.Resize(MAX_DEFERRED_LIGHT_VS_VARIATIONS);
  897. lightPS_.Resize(MAX_DEFERRED_LIGHT_PS_VARIATIONS);
  898. unsigned shadows = (graphics_->GetHardwareShadowSupport() ? 1 : 0) | (shadowQuality_ & SHADOWQUALITY_HIGH_16BIT);
  899. unsigned fallback = graphics_->GetFallback() ? 1 : 0;
  900. if (fallback)
  901. shadows = SHADOWQUALITY_HIGH_16BIT;
  902. for (unsigned i = 0; i < MAX_DEFERRED_LIGHT_VS_VARIATIONS; ++i)
  903. lightVS_[i] = GetVertexShader("Light_" + deferredLightVSVariations[i]);
  904. for (unsigned i = 0; i < MAX_DEFERRED_LIGHT_PS_VARIATIONS; ++i)
  905. {
  906. unsigned linear = fallback == 0 && !graphics_->GetHardwareDepthSupport() && i < DLPS_ORTHO ? 1 : 0;
  907. if (i & DLPS_SHADOW)
  908. {
  909. lightPS_[i] = GetPixelShader("Light_" + linearVariations[linear] + lightPSVariations[i] +
  910. shadowVariations[shadows] + fallbackVariations[fallback]);
  911. }
  912. else
  913. {
  914. lightPS_[i] = GetPixelShader("Light_" + linearVariations[linear] + lightPSVariations[i] +
  915. fallbackVariations[fallback]);
  916. }
  917. }
  918. }
  919. // Remove shaders that are no longer referenced from the cache
  920. cache_->ReleaseResources(Shader::GetTypeStatic());
  921. shadersDirty_ = false;
  922. }
  923. void Renderer::LoadMaterialShaders(Technique* technique)
  924. {
  925. LoadPassShaders(technique, PASS_SHADOW);
  926. LoadPassShaders(technique, PASS_EXTRA);
  927. RenderMode mode = graphics_->GetRenderMode();
  928. if (mode == RENDER_FORWARD)
  929. {
  930. LoadPassShaders(technique, PASS_BASE);
  931. LoadPassShaders(technique, PASS_LITBASE);
  932. LoadPassShaders(technique, PASS_LIGHT);
  933. }
  934. else
  935. {
  936. if (technique->HasPass(PASS_GBUFFER))
  937. {
  938. LoadPassShaders(technique, PASS_GBUFFER);
  939. if (graphics_->GetFallback())
  940. LoadPassShaders(technique, PASS_GBUFFER2);
  941. }
  942. else
  943. {
  944. LoadPassShaders(technique, PASS_BASE);
  945. // If shadow maps are not reused, forward lighting in deferred mode can render shadows
  946. LoadPassShaders(technique, PASS_LITBASE, !reuseShadowMaps_);
  947. LoadPassShaders(technique, PASS_LIGHT, !reuseShadowMaps_);
  948. }
  949. }
  950. }
  951. void Renderer::LoadPassShaders(Technique* technique, PassType type, bool allowShadows)
  952. {
  953. Pass* pass = technique->GetPass(type);
  954. if (!pass)
  955. return;
  956. String vertexShaderName = pass->GetVertexShaderName();
  957. String pixelShaderName = pass->GetPixelShaderName();
  958. // Check if the shader name is already a variation in itself
  959. if (vertexShaderName.Find('_') == String::NPOS)
  960. vertexShaderName += "_";
  961. if (pixelShaderName.Find('_') == String::NPOS)
  962. pixelShaderName += "_";
  963. unsigned shadows = (graphics_->GetHardwareShadowSupport() ? 1 : 0) | (shadowQuality_ & SHADOWQUALITY_HIGH_16BIT);
  964. unsigned fallback = graphics_->GetFallback() ? 1 : 0;
  965. if (fallback)
  966. shadows = SHADOWQUALITY_HIGH_16BIT;
  967. // If INTZ depth is used, do not write depth into a rendertarget in the G-buffer pass
  968. if (type == PASS_GBUFFER || type == PASS_GBUFFER2)
  969. {
  970. unsigned depth = graphics_->GetHardwareDepthSupport() ? 0 : 1;
  971. if (fallback)
  972. pixelShaderName += fallbackVariations[fallback];
  973. else
  974. pixelShaderName += depthVariations[depth];
  975. }
  976. if (type == PASS_SHADOW)
  977. {
  978. vertexShaderName += fallbackVariations[fallback];
  979. pixelShaderName += fallbackVariations[fallback];
  980. }
  981. Vector<SharedPtr<ShaderVariation> >& vertexShaders = pass->GetVertexShaders();
  982. Vector<SharedPtr<ShaderVariation> >& pixelShaders = pass->GetPixelShaders();
  983. // Forget all the old shaders
  984. vertexShaders.Clear();
  985. pixelShaders.Clear();
  986. if (type == PASS_LIGHT || type == PASS_LITBASE)
  987. {
  988. // If ambient pass is transparent, and shadow maps are reused, do not load shadow variations
  989. if (reuseShadowMaps_)
  990. {
  991. if (!technique->HasPass(PASS_BASE) || technique->GetPass(PASS_BASE)->GetBlendMode() != BLEND_REPLACE)
  992. allowShadows = false;
  993. }
  994. vertexShaders.Resize(MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS);
  995. pixelShaders.Resize(MAX_LIGHT_PS_VARIATIONS);
  996. for (unsigned j = 0; j < MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS; ++j)
  997. {
  998. unsigned g = j / MAX_LIGHT_VS_VARIATIONS;
  999. unsigned l = j % MAX_LIGHT_VS_VARIATIONS;
  1000. if (!(l & LVS_SHADOW) || allowShadows)
  1001. vertexShaders[j] = GetVertexShader(vertexShaderName + lightVSVariations[l] + geometryVSVariations[g], g != 0);
  1002. else
  1003. vertexShaders[j].Reset();
  1004. }
  1005. for (unsigned j = 0; j < MAX_LIGHT_PS_VARIATIONS; ++j)
  1006. {
  1007. if (j & LPS_SHADOW)
  1008. {
  1009. if (allowShadows)
  1010. {
  1011. pixelShaders[j] = GetPixelShader(pixelShaderName + lightPSVariations[j] + shadowVariations[shadows] +
  1012. fallbackVariations[fallback]);
  1013. }
  1014. else
  1015. pixelShaders[j].Reset();
  1016. }
  1017. else
  1018. pixelShaders[j] = GetPixelShader(pixelShaderName + lightPSVariations[j]);
  1019. }
  1020. }
  1021. else
  1022. {
  1023. vertexShaders.Resize(MAX_GEOMETRYTYPES);
  1024. pixelShaders.Resize(1);
  1025. for (unsigned j = 0; j < MAX_GEOMETRYTYPES; ++j)
  1026. vertexShaders[j] = GetVertexShader(vertexShaderName + geometryVSVariations[j], j != 0);
  1027. pixelShaders[0] = GetPixelShader(pixelShaderName);
  1028. }
  1029. technique->MarkShadersLoaded(shadersChangedFrameNumber_);
  1030. }
  1031. void Renderer::ReleaseMaterialShaders()
  1032. {
  1033. PODVector<Material*> materials;
  1034. cache_->GetResources<Material>(materials);
  1035. for (unsigned i = 0; i < materials.Size(); ++i)
  1036. materials[i]->ReleaseShaders();
  1037. }
  1038. void Renderer::ReloadTextures()
  1039. {
  1040. PODVector<Resource*> textures;
  1041. cache_->GetResources(textures, Texture2D::GetTypeStatic());
  1042. for (unsigned i = 0; i < textures.Size(); ++i)
  1043. cache_->ReloadResource(textures[i]);
  1044. cache_->GetResources(textures, TextureCube::GetTypeStatic());
  1045. for (unsigned i = 0; i < textures.Size(); ++i)
  1046. cache_->ReloadResource(textures[i]);
  1047. }
  1048. void Renderer::CreateGeometries()
  1049. {
  1050. SharedPtr<VertexBuffer> dlvb(new VertexBuffer(context_));
  1051. dlvb->SetSize(4, MASK_POSITION);
  1052. dlvb->SetData(dirLightVertexData);
  1053. SharedPtr<IndexBuffer> dlib(new IndexBuffer(context_));
  1054. dlib->SetSize(6, false);
  1055. dlib->SetData(dirLightIndexData);
  1056. dirLightGeometry_ = new Geometry(context_);
  1057. dirLightGeometry_->SetVertexBuffer(0, dlvb);
  1058. dirLightGeometry_->SetIndexBuffer(dlib);
  1059. dirLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, dlib->GetIndexCount());
  1060. SharedPtr<VertexBuffer> plvb(new VertexBuffer(context_));
  1061. plvb->SetSize(24, MASK_POSITION);
  1062. plvb->SetData(pointLightVertexData);
  1063. SharedPtr<IndexBuffer> plib(new IndexBuffer(context_));
  1064. plib->SetSize(132, false);
  1065. plib->SetData(pointLightIndexData);
  1066. pointLightGeometry_ = new Geometry(context_);
  1067. pointLightGeometry_->SetVertexBuffer(0, plvb);
  1068. pointLightGeometry_->SetIndexBuffer(plib);
  1069. pointLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, plib->GetIndexCount());
  1070. SharedPtr<VertexBuffer> slvb(new VertexBuffer(context_));
  1071. slvb->SetSize(8, MASK_POSITION);
  1072. slvb->SetData(spotLightVertexData);
  1073. SharedPtr<IndexBuffer> slib(new IndexBuffer(context_));
  1074. slib->SetSize(36, false);
  1075. slib->SetData(spotLightIndexData);
  1076. spotLightGeometry_ = new Geometry(context_);
  1077. spotLightGeometry_->SetVertexBuffer(0, slvb);
  1078. spotLightGeometry_->SetIndexBuffer(slib);
  1079. spotLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, slib->GetIndexCount());
  1080. }
  1081. void Renderer::CreateInstancingBuffer()
  1082. {
  1083. // Do not create buffer if instancing not supported
  1084. if (!graphics_->GetSM3Support())
  1085. {
  1086. dynamicInstancing_ = false;
  1087. return;
  1088. }
  1089. // If must lock the buffer for each batch group, set a smaller size
  1090. unsigned defaultSize = graphics_->GetStreamOffsetSupport() ? INSTANCING_BUFFER_DEFAULT_SIZE : INSTANCING_BUFFER_DEFAULT_SIZE / 4;
  1091. instancingBuffer_ = new VertexBuffer(context_);
  1092. if (!instancingBuffer_->SetSize(defaultSize, INSTANCING_BUFFER_MASK, true))
  1093. {
  1094. instancingBuffer_.Reset();
  1095. dynamicInstancing_ = false;
  1096. }
  1097. }
  1098. bool Renderer::ResizeInstancingBuffer(unsigned numInstances)
  1099. {
  1100. if (!instancingBuffer_)
  1101. return false;
  1102. unsigned oldSize = instancingBuffer_->GetVertexCount();
  1103. if (numInstances <= oldSize)
  1104. return true;
  1105. unsigned newSize = INSTANCING_BUFFER_DEFAULT_SIZE;
  1106. while (newSize < numInstances)
  1107. newSize <<= 1;
  1108. if (!instancingBuffer_->SetSize(newSize, INSTANCING_BUFFER_MASK, true))
  1109. {
  1110. LOGERROR("Failed to resize instancing buffer to " + String(newSize));
  1111. // If failed, try to restore the old size
  1112. instancingBuffer_->SetSize(oldSize, INSTANCING_BUFFER_MASK, true);
  1113. return false;
  1114. }
  1115. LOGDEBUG("Resized instancing buffer to " + String(newSize));
  1116. return true;
  1117. }
  1118. bool Renderer::CreateShadowMaps()
  1119. {
  1120. unsigned shadowMapFormat = (shadowQuality_ & SHADOWQUALITY_LOW_24BIT) ? graphics_->GetHiresShadowMapFormat() :
  1121. graphics_->GetShadowMapFormat();
  1122. unsigned dummyColorFormat = graphics_->GetDummyColorFormat();
  1123. bool hardwarePCF = graphics_->GetHardwareShadowSupport();
  1124. if (!shadowMapFormat)
  1125. return false;
  1126. if (!drawShadows_)
  1127. {
  1128. shadowDepthStencil_.Reset();
  1129. for (unsigned i = 0; i < NUM_SHADOWMAP_RESOLUTIONS; ++i)
  1130. {
  1131. colorShadowMaps_[i].Reset();
  1132. for (unsigned j = 0; j < shadowMaps_[i].Size(); ++j)
  1133. shadowMaps_[i][j].Reset();
  1134. }
  1135. return true;
  1136. }
  1137. #ifdef USE_OPENGL
  1138. // Create shadow maps only. Color rendertargets are not needed
  1139. unsigned size = shadowMapSize_;
  1140. for (unsigned i = 0; i < NUM_SHADOWMAP_RESOLUTIONS; ++i)
  1141. {
  1142. for (unsigned j = 0; j < shadowMaps_[i].Size(); ++j)
  1143. {
  1144. if (!shadowMaps_[i][j])
  1145. shadowMaps_[i][j] = new Texture2D(context_);
  1146. if (!shadowMaps_[i][j]->SetSize(size, size, shadowMapFormat, TEXTURE_DEPTHSTENCIL))
  1147. return false;
  1148. shadowMaps_[i][j]->SetFilterMode(FILTER_BILINEAR);
  1149. shadowMaps_[i][j]->SetShadowCompare(true);
  1150. }
  1151. size >>= 1;
  1152. }
  1153. #else
  1154. // Create shadow maps and dummy color rendertargets
  1155. unsigned size = shadowMapSize_;
  1156. bool fallback = graphics_->GetFallback();
  1157. // Create one depth stencil buffer in fallback mode to be shared by all shadow maps
  1158. if (fallback)
  1159. {
  1160. if (!shadowDepthStencil_)
  1161. shadowDepthStencil_ = new Texture2D(context_);
  1162. if (!shadowDepthStencil_->SetSize(size, size, D3DFMT_D16, TEXTURE_DEPTHSTENCIL))
  1163. return false;
  1164. }
  1165. for (unsigned i = 0; i < NUM_SHADOWMAP_RESOLUTIONS; ++i)
  1166. {
  1167. // Dummy color rendertargets are not required in fallback mode, as the shadows are rendered into a color texture
  1168. if (!fallback)
  1169. {
  1170. if (!colorShadowMaps_[i])
  1171. colorShadowMaps_[i] = new Texture2D(context_);
  1172. if (!colorShadowMaps_[i]->SetSize(size, size, dummyColorFormat, TEXTURE_RENDERTARGET))
  1173. return false;
  1174. }
  1175. for (unsigned j = 0; j < shadowMaps_[i].Size(); ++j)
  1176. {
  1177. if (!shadowMaps_[i][j])
  1178. shadowMaps_[i][j] = new Texture2D(context_);
  1179. if (!shadowMaps_[i][j]->SetSize(size, size, shadowMapFormat, fallback ? TEXTURE_RENDERTARGET : TEXTURE_DEPTHSTENCIL))
  1180. return false;
  1181. if (!fallback)
  1182. {
  1183. shadowMaps_[i][j]->SetFilterMode(hardwarePCF ? FILTER_BILINEAR : FILTER_NEAREST);
  1184. // Link the color rendertarget to depth rendertarget
  1185. shadowMaps_[i][j]->GetRenderSurface()->SetLinkedRenderTarget(colorShadowMaps_[i]->GetRenderSurface());
  1186. }
  1187. else
  1188. // In fallback mode, link the shared depth stencil buffer to all shadow maps
  1189. shadowMaps_[i][j]->GetRenderSurface()->SetLinkedDepthBuffer(shadowDepthStencil_->GetRenderSurface());
  1190. }
  1191. size >>= 1;
  1192. }
  1193. #endif
  1194. return true;
  1195. }
  1196. Camera* Renderer::CreateShadowCamera()
  1197. {
  1198. if (numShadowCameras_ >= shadowCameraStore_.Size())
  1199. shadowCameraStore_.Push(SharedPtr<Camera>(new Camera(context_)));
  1200. Camera* camera = shadowCameraStore_[numShadowCameras_];
  1201. camera->SetNode(CreateTempNode());
  1202. ++numShadowCameras_;
  1203. return camera;
  1204. }
  1205. Light* Renderer::CreateSplitLight(Light* original)
  1206. {
  1207. if (numSplitLights_ >= splitLightStore_.Size())
  1208. splitLightStore_.Push(SharedPtr<Light>(new Light(context_)));
  1209. Light* light = splitLightStore_[numSplitLights_];
  1210. light->SetNode(CreateTempNode());
  1211. light->CopyFrom(original);
  1212. ++numSplitLights_;
  1213. return light;
  1214. }
  1215. Node* Renderer::CreateTempNode()
  1216. {
  1217. if (numTempNodes_ >= tempNodeStore_.Size())
  1218. tempNodeStore_.Push(SharedPtr<Node>(new Node(context_)));
  1219. Node* node = tempNodeStore_[numTempNodes_];
  1220. ++numTempNodes_;
  1221. return node;
  1222. }
  1223. void Renderer::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  1224. {
  1225. if (!initialized_)
  1226. Initialize();
  1227. else
  1228. {
  1229. // When screen mode changes, reload shaders and purge old views and occlusion buffers
  1230. shadersDirty_ = true;
  1231. occlusionBuffers_.Clear();
  1232. ResetViews();
  1233. }
  1234. }
  1235. void Renderer::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  1236. {
  1237. if (initialized_)
  1238. {
  1239. using namespace RenderUpdate;
  1240. Update(eventData[P_TIMESTEP].GetFloat());
  1241. }
  1242. }