Renderer.cpp 46 KB

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