Renderer.cpp 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502
  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(UpdateViews);
  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(RenderViews);
  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_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.0f)
  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_LIGHT);
  899. }
  900. else
  901. {
  902. if (technique->HasPass(PASS_GBUFFER))
  903. LoadPassShaders(technique, PASS_GBUFFER);
  904. else
  905. {
  906. LoadPassShaders(technique, PASS_BASE);
  907. // If shadow maps are not reused, transparencies can be rendered shadowed
  908. LoadPassShaders(technique, PASS_LIGHT, !reuseShadowMaps_);
  909. }
  910. }
  911. }
  912. void Renderer::LoadPassShaders(Technique* technique, PassType pass, bool allowShadows)
  913. {
  914. Map<PassType, Pass>::Iterator i = technique->passes_.Find(pass);
  915. if (i == technique->passes_.End())
  916. return;
  917. String vertexShaderName = i->second_.GetVertexShaderName();
  918. String pixelShaderName = i->second_.GetPixelShaderName();
  919. // Check if the shader name is already a variation in itself
  920. if (vertexShaderName.Find('_') == String::NPOS)
  921. vertexShaderName += "_";
  922. if (pixelShaderName.Find('_') == String::NPOS)
  923. pixelShaderName += "_";
  924. // If ambient pass is transparent, and shadow maps are reused, do not load shadow variations
  925. if (reuseShadowMaps_ && pass == PASS_LIGHT)
  926. {
  927. if (!technique->HasPass(PASS_BASE) || technique->GetPass(PASS_BASE)->GetBlendMode() != BLEND_REPLACE)
  928. allowShadows = false;
  929. }
  930. unsigned hwShadows = graphics_->GetHardwareShadowSupport() ? 1 : 0;
  931. Vector<SharedPtr<ShaderVariation> >& vertexShaders = i->second_.GetVertexShaders();
  932. Vector<SharedPtr<ShaderVariation> >& pixelShaders = i->second_.GetPixelShaders();
  933. // Forget all the old shaders
  934. vertexShaders.Clear();
  935. pixelShaders.Clear();
  936. switch (i->first_)
  937. {
  938. default:
  939. vertexShaders.Resize(MAX_GEOMETRYTYPES);
  940. pixelShaders.Resize(1);
  941. for (unsigned j = 0; j < MAX_GEOMETRYTYPES; ++j)
  942. vertexShaders[j] = GetVertexShader(vertexShaderName + geometryVSVariations[j], j != 0);
  943. pixelShaders[0] = GetPixelShader(pixelShaderName);
  944. break;
  945. case PASS_LIGHT:
  946. {
  947. vertexShaders.Resize(MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS);
  948. pixelShaders.Resize(MAX_LIGHT_PS_VARIATIONS);
  949. for (unsigned j = 0; j < MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS; ++j)
  950. {
  951. unsigned g = j / MAX_LIGHT_VS_VARIATIONS;
  952. unsigned l = j % MAX_LIGHT_VS_VARIATIONS;
  953. if (!(l & LVS_SHADOW) || allowShadows)
  954. vertexShaders[j] = GetVertexShader(vertexShaderName + lightVSVariations[l] + geometryVSVariations[g], g != 0);
  955. else
  956. vertexShaders[j].Reset();
  957. }
  958. for (unsigned j = 0; j < MAX_LIGHT_PS_VARIATIONS; ++j)
  959. {
  960. unsigned variation = j % LPS_SPOT;
  961. if (variation == LPS_SHADOW || variation == LPS_SHADOWSPEC)
  962. {
  963. if (allowShadows)
  964. pixelShaders[j] = GetPixelShader(pixelShaderName + lightPSVariations[j] +
  965. hwVariations[hwShadows]);
  966. else
  967. pixelShaders[j].Reset();
  968. }
  969. else
  970. pixelShaders[j] = GetPixelShader(pixelShaderName + lightPSVariations[j]);
  971. }
  972. break;
  973. }
  974. }
  975. technique->MarkShadersLoaded(shadersChangedFrameNumber_);
  976. }
  977. void Renderer::ReleaseMaterialShaders()
  978. {
  979. PODVector<Material*> materials;
  980. cache_->GetResources<Material>(materials);
  981. for (unsigned i = 0; i < materials.Size(); ++i)
  982. materials[i]->ReleaseShaders();
  983. }
  984. void Renderer::ReloadTextures()
  985. {
  986. PODVector<Resource*> textures;
  987. cache_->GetResources(textures, Texture2D::GetTypeStatic());
  988. for (unsigned i = 0; i < textures.Size(); ++i)
  989. cache_->ReloadResource(textures[i]);
  990. cache_->GetResources(textures, TextureCube::GetTypeStatic());
  991. for (unsigned i = 0; i < textures.Size(); ++i)
  992. cache_->ReloadResource(textures[i]);
  993. }
  994. void Renderer::CreateGeometries()
  995. {
  996. SharedPtr<VertexBuffer> dlvb(new VertexBuffer(context_));
  997. dlvb->SetSize(4, MASK_POSITION);
  998. dlvb->SetData(dirLightVertexData);
  999. SharedPtr<IndexBuffer> dlib(new IndexBuffer(context_));
  1000. dlib->SetSize(6, false);
  1001. dlib->SetData(dirLightIndexData);
  1002. dirLightGeometry_ = new Geometry(context_);
  1003. dirLightGeometry_->SetVertexBuffer(0, dlvb);
  1004. dirLightGeometry_->SetIndexBuffer(dlib);
  1005. dirLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, dlib->GetIndexCount());
  1006. SharedPtr<VertexBuffer> plvb(new VertexBuffer(context_));
  1007. plvb->SetSize(24, MASK_POSITION);
  1008. plvb->SetData(pointLightVertexData);
  1009. SharedPtr<IndexBuffer> plib(new IndexBuffer(context_));
  1010. plib->SetSize(132, false);
  1011. plib->SetData(pointLightIndexData);
  1012. pointLightGeometry_ = new Geometry(context_);
  1013. pointLightGeometry_->SetVertexBuffer(0, plvb);
  1014. pointLightGeometry_->SetIndexBuffer(plib);
  1015. pointLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, plib->GetIndexCount());
  1016. SharedPtr<VertexBuffer> slvb(new VertexBuffer(context_));
  1017. slvb->SetSize(8, MASK_POSITION);
  1018. slvb->SetData(spotLightVertexData);
  1019. SharedPtr<IndexBuffer> slib(new IndexBuffer(context_));
  1020. slib->SetSize(36, false);
  1021. slib->SetData(spotLightIndexData);
  1022. spotLightGeometry_ = new Geometry(context_);
  1023. spotLightGeometry_->SetVertexBuffer(0, slvb);
  1024. spotLightGeometry_->SetIndexBuffer(slib);
  1025. spotLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, slib->GetIndexCount());
  1026. }
  1027. void Renderer::CreateInstancingBuffer()
  1028. {
  1029. // Do not create buffer if instancing not supported
  1030. if (!graphics_->GetSM3Support())
  1031. {
  1032. dynamicInstancing_ = false;
  1033. return;
  1034. }
  1035. // If must lock the buffer for each batch group, set a smaller size
  1036. unsigned defaultSize = graphics_->GetStreamOffsetSupport() ? INSTANCING_BUFFER_DEFAULT_SIZE : INSTANCING_BUFFER_DEFAULT_SIZE / 4;
  1037. instancingBuffer_ = new VertexBuffer(context_);
  1038. if (!instancingBuffer_->SetSize(defaultSize, INSTANCING_BUFFER_MASK, true))
  1039. {
  1040. instancingBuffer_.Reset();
  1041. dynamicInstancing_ = false;
  1042. }
  1043. }
  1044. bool Renderer::ResizeInstancingBuffer(unsigned numInstances)
  1045. {
  1046. if (!instancingBuffer_)
  1047. return false;
  1048. unsigned oldSize = instancingBuffer_->GetVertexCount();
  1049. if (numInstances <= oldSize)
  1050. return true;
  1051. unsigned newSize = INSTANCING_BUFFER_DEFAULT_SIZE;
  1052. while (newSize < numInstances)
  1053. newSize <<= 1;
  1054. if (!instancingBuffer_->SetSize(newSize, INSTANCING_BUFFER_MASK, true))
  1055. {
  1056. LOGERROR("Failed to resize instancing buffer to " + String(newSize));
  1057. // If failed, try to restore the old size
  1058. instancingBuffer_->SetSize(oldSize, INSTANCING_BUFFER_MASK, true);
  1059. return false;
  1060. }
  1061. LOGDEBUG("Resized instancing buffer to " + String(newSize));
  1062. return true;
  1063. }
  1064. bool Renderer::CreateShadowMaps()
  1065. {
  1066. unsigned shadowMapFormat = shadowMapHiresDepth_ ? graphics_->GetHiresShadowMapFormat() : graphics_->GetShadowMapFormat();
  1067. unsigned dummyColorFormat = graphics_->GetDummyColorFormat();
  1068. bool hardwarePCF = graphics_->GetHardwareShadowSupport();
  1069. if (!shadowMapFormat)
  1070. return false;
  1071. if (!drawShadows_)
  1072. {
  1073. for (unsigned i = 0; i < NUM_SHADOWMAP_RESOLUTIONS; ++i)
  1074. {
  1075. for (unsigned j = 0; j < shadowMaps_[i].Size(); ++j)
  1076. shadowMaps_[i][j].Reset();
  1077. }
  1078. return true;
  1079. }
  1080. #ifdef USE_OPENGL
  1081. // Create shadow maps only. Color rendertargets are not needed
  1082. unsigned size = shadowMapSize_;
  1083. for (unsigned i = 0; i < NUM_SHADOWMAP_RESOLUTIONS; ++i)
  1084. {
  1085. for (unsigned j = 0; j < shadowMaps_[i].Size(); ++j)
  1086. {
  1087. if (!shadowMaps_[i][j])
  1088. shadowMaps_[i][j] = new Texture2D(context_);
  1089. if (!shadowMaps_[i][j]->SetSize(size, size, shadowMapFormat, TEXTURE_DEPTHSTENCIL))
  1090. return false;
  1091. shadowMaps_[i][j]->SetFilterMode(FILTER_BILINEAR);
  1092. shadowMaps_[i][j]->SetShadowCompare(true);
  1093. }
  1094. size >>= 1;
  1095. }
  1096. #else
  1097. // Create shadow maps and dummy color rendertargets
  1098. unsigned size = shadowMapSize_;
  1099. for (unsigned i = 0; i < NUM_SHADOWMAP_RESOLUTIONS; ++i)
  1100. {
  1101. if (!colorShadowMaps_[i])
  1102. colorShadowMaps_[i] = new Texture2D(context_);
  1103. if (!colorShadowMaps_[i]->SetSize(size, size, dummyColorFormat, TEXTURE_RENDERTARGET))
  1104. return false;
  1105. for (unsigned j = 0; j < shadowMaps_[i].Size(); ++j)
  1106. {
  1107. if (!shadowMaps_[i][j])
  1108. shadowMaps_[i][j] = new Texture2D(context_);
  1109. if (!shadowMaps_[i][j]->SetSize(size, size, shadowMapFormat, TEXTURE_DEPTHSTENCIL))
  1110. return false;
  1111. shadowMaps_[i][j]->SetFilterMode(hardwarePCF ? FILTER_BILINEAR : FILTER_NEAREST);
  1112. // Link the color rendertarget to depth rendertarget
  1113. shadowMaps_[i][j]->GetRenderSurface()->SetLinkedRenderTarget(colorShadowMaps_[i]->GetRenderSurface());
  1114. }
  1115. size >>= 1;
  1116. }
  1117. #endif
  1118. return true;
  1119. }
  1120. Camera* Renderer::CreateShadowCamera()
  1121. {
  1122. if (numShadowCameras_ >= shadowCameraStore_.Size())
  1123. shadowCameraStore_.Push(SharedPtr<Camera>(new Camera(context_)));
  1124. Camera* camera = shadowCameraStore_[numShadowCameras_];
  1125. camera->SetNode(CreateTempNode());
  1126. ++numShadowCameras_;
  1127. return camera;
  1128. }
  1129. Light* Renderer::CreateSplitLight(Light* original)
  1130. {
  1131. if (numSplitLights_ >= splitLightStore_.Size())
  1132. splitLightStore_.Push(SharedPtr<Light>(new Light(context_)));
  1133. Light* light = splitLightStore_[numSplitLights_];
  1134. light->SetNode(CreateTempNode());
  1135. light->CopyFrom(original);
  1136. ++numSplitLights_;
  1137. return light;
  1138. }
  1139. Node* Renderer::CreateTempNode()
  1140. {
  1141. if (numTempNodes_ >= tempNodeStore_.Size())
  1142. tempNodeStore_.Push(SharedPtr<Node>(new Node(context_)));
  1143. Node* node = tempNodeStore_[numTempNodes_];
  1144. ++numTempNodes_;
  1145. return node;
  1146. }
  1147. void Renderer::SetupLightBatch(Batch& batch)
  1148. {
  1149. Matrix3x4 view(batch.camera_->GetInverseWorldTransform());
  1150. Light* light = batch.light_;
  1151. float lightExtent = light->GetVolumeExtent();
  1152. float lightViewDist = (light->GetWorldPosition() - batch.camera_->GetWorldPosition()).LengthFast();
  1153. graphics_->SetAlphaTest(false);
  1154. graphics_->SetBlendMode(BLEND_ADD);
  1155. graphics_->SetDepthWrite(false);
  1156. if (light->GetLightType() == LIGHT_DIRECTIONAL)
  1157. {
  1158. // Get projection without jitter offset to ensure the whole screen is filled
  1159. Matrix4 projection(batch.camera_->GetProjection(false));
  1160. // If the light does not extend to the near plane, use a stencil test. Else just draw with depth fail
  1161. if (light->GetNearSplit() <= batch.camera_->GetNearClip())
  1162. {
  1163. graphics_->SetCullMode(CULL_NONE);
  1164. graphics_->SetDepthTest(CMP_GREATER);
  1165. graphics_->SetStencilTest(false);
  1166. }
  1167. else
  1168. {
  1169. Matrix3x4 nearTransform = light->GetDirLightTransform(*batch.camera_, true);
  1170. // Set state for stencil rendering
  1171. graphics_->SetColorWrite(false);
  1172. graphics_->SetCullMode(CULL_NONE);
  1173. graphics_->SetDepthTest(CMP_LESSEQUAL);
  1174. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_INCR, OP_KEEP, OP_KEEP, 1);
  1175. graphics_->SetShaders(stencilVS_, stencilPS_);
  1176. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  1177. graphics_->SetShaderParameter(VSP_MODEL, nearTransform);
  1178. graphics_->ClearTransformSources();
  1179. // Draw to stencil
  1180. batch.geometry_->Draw(graphics_);
  1181. // Re-enable color write, set test for rendering the actual light
  1182. graphics_->SetColorWrite(true);
  1183. graphics_->SetDepthTest(CMP_GREATER);
  1184. graphics_->SetStencilTest(true, CMP_EQUAL, OP_ZERO, OP_KEEP, OP_ZERO, 1);
  1185. }
  1186. }
  1187. else
  1188. {
  1189. Matrix4 projection(batch.camera_->GetProjection());
  1190. const Matrix3x4& model = light->GetVolumeTransform(*batch.camera_);
  1191. if (light->GetLightType() == LIGHT_SPLITPOINT)
  1192. {
  1193. // Shadowed point light, split in 6 frustums: mask out overlapping pixels to prevent overlighting
  1194. // Check whether we should draw front or back faces
  1195. bool drawBackFaces = lightViewDist < (lightExtent + batch.camera_->GetNearClip());
  1196. graphics_->SetColorWrite(false);
  1197. graphics_->SetCullMode(drawBackFaces ? CULL_CCW : CULL_CW);
  1198. graphics_->SetDepthTest(drawBackFaces ? CMP_GREATER : CMP_LESS);
  1199. graphics_->SetStencilTest(true, CMP_EQUAL, OP_INCR, OP_KEEP, OP_KEEP, 0);
  1200. graphics_->SetShaders(stencilVS_, stencilPS_);
  1201. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection * view);
  1202. graphics_->SetShaderParameter(VSP_MODEL, model);
  1203. // Draw the other faces to stencil to mark where we should not draw
  1204. batch.geometry_->Draw(graphics_);
  1205. graphics_->SetColorWrite(true);
  1206. graphics_->SetCullMode(drawBackFaces ? CULL_CW : CULL_CCW);
  1207. graphics_->SetStencilTest(true, CMP_EQUAL, OP_DECR, OP_DECR, OP_KEEP, 0);
  1208. }
  1209. else
  1210. {
  1211. // If light is close to near clip plane, we might be inside light volume
  1212. if (lightViewDist < (lightExtent + batch.camera_->GetNearClip()))
  1213. {
  1214. // In this case reverse cull mode & depth test and render back faces
  1215. graphics_->SetCullMode(CULL_CW);
  1216. graphics_->SetDepthTest(CMP_GREATER);
  1217. graphics_->SetStencilTest(false);
  1218. }
  1219. else
  1220. {
  1221. // If not too close to far clip plane, write the back faces to stencil for optimization,
  1222. // then render front faces. Else just render front faces.
  1223. if (lightViewDist < (batch.camera_->GetFarClip() - lightExtent))
  1224. {
  1225. // Set state for stencil rendering
  1226. graphics_->SetColorWrite(false);
  1227. graphics_->SetCullMode(CULL_CW);
  1228. graphics_->SetDepthTest(CMP_GREATER);
  1229. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_INCR, OP_KEEP, OP_KEEP, 1);
  1230. graphics_->SetShaders(stencilVS_, stencilPS_);
  1231. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection * view);
  1232. graphics_->SetShaderParameter(VSP_MODEL, model);
  1233. // Draw to stencil
  1234. batch.geometry_->Draw(graphics_);
  1235. // Re-enable color write, set test for rendering the actual light
  1236. graphics_->SetColorWrite(true);
  1237. graphics_->SetStencilTest(true, CMP_EQUAL, OP_ZERO, OP_KEEP, OP_ZERO, 1);
  1238. graphics_->SetCullMode(CULL_CCW);
  1239. graphics_->SetDepthTest(CMP_LESS);
  1240. }
  1241. else
  1242. {
  1243. graphics_->SetStencilTest(false);
  1244. graphics_->SetCullMode(CULL_CCW);
  1245. graphics_->SetDepthTest(CMP_LESS);
  1246. }
  1247. }
  1248. }
  1249. }
  1250. }
  1251. void Renderer::DrawFullScreenQuad(Camera& camera, ShaderVariation* vs, ShaderVariation* ps, bool nearQuad, const HashMap<StringHash, Vector4>& shaderParameters)
  1252. {
  1253. Light quadDirLight(context_);
  1254. Matrix3x4 model(quadDirLight.GetDirLightTransform(camera, nearQuad));
  1255. graphics_->SetCullMode(CULL_NONE);
  1256. graphics_->SetShaders(vs, ps);
  1257. graphics_->SetShaderParameter(VSP_MODEL, model);
  1258. // Get projection without jitter offset to ensure the whole screen is filled
  1259. graphics_->SetShaderParameter(VSP_VIEWPROJ, camera.GetProjection(false));
  1260. graphics_->ClearTransformSources();
  1261. // Set global shader parameters as needed
  1262. for (HashMap<StringHash, Vector4>::ConstIterator i = shaderParameters.Begin(); i != shaderParameters.End(); ++i)
  1263. {
  1264. if (graphics_->NeedParameterUpdate(i->first_, &shaderParameters))
  1265. graphics_->SetShaderParameter(i->first_, i->second_);
  1266. }
  1267. dirLightGeometry_->Draw(graphics_);
  1268. }
  1269. void Renderer::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  1270. {
  1271. if (!initialized_)
  1272. Initialize();
  1273. else
  1274. {
  1275. // When screen mode changes, reload shaders and purge old views and occlusion buffers
  1276. shadersDirty_ = true;
  1277. occlusionBuffers_.Clear();
  1278. ResetViews();
  1279. }
  1280. }
  1281. void Renderer::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  1282. {
  1283. if (initialized_)
  1284. {
  1285. using namespace RenderUpdate;
  1286. Update(eventData[P_TIMESTEP].GetFloat());
  1287. }
  1288. }