Renderer.cpp 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355
  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 pointLightVertexData[] =
  53. {
  54. -0.423169f, -1.000000f, 0.423169f,
  55. -0.423169f, -1.000000f, -0.423169f,
  56. 0.423169f, -1.000000f, -0.423169f,
  57. 0.423169f, -1.000000f, 0.423169f,
  58. 0.423169f, 1.000000f, -0.423169f,
  59. -0.423169f, 1.000000f, -0.423169f,
  60. -0.423169f, 1.000000f, 0.423169f,
  61. 0.423169f, 1.000000f, 0.423169f,
  62. -1.000000f, 0.423169f, -0.423169f,
  63. -1.000000f, -0.423169f, -0.423169f,
  64. -1.000000f, -0.423169f, 0.423169f,
  65. -1.000000f, 0.423169f, 0.423169f,
  66. 0.423169f, 0.423169f, -1.000000f,
  67. 0.423169f, -0.423169f, -1.000000f,
  68. -0.423169f, -0.423169f, -1.000000f,
  69. -0.423169f, 0.423169f, -1.000000f,
  70. 1.000000f, 0.423169f, 0.423169f,
  71. 1.000000f, -0.423169f, 0.423169f,
  72. 1.000000f, -0.423169f, -0.423169f,
  73. 1.000000f, 0.423169f, -0.423169f,
  74. 0.423169f, -0.423169f, 1.000000f,
  75. 0.423169f, 0.423169f, 1.000000f,
  76. -0.423169f, 0.423169f, 1.000000f,
  77. -0.423169f, -0.423169f, 1.000000f
  78. };
  79. static const unsigned short pointLightIndexData[] =
  80. {
  81. 0, 1, 2,
  82. 0, 2, 3,
  83. 4, 5, 6,
  84. 4, 6, 7,
  85. 8, 9, 10,
  86. 8, 10, 11,
  87. 12, 13, 14,
  88. 12, 14, 15,
  89. 16, 17, 18,
  90. 16, 18, 19,
  91. 20, 21, 22,
  92. 20, 22, 23,
  93. 0, 10, 9,
  94. 0, 9, 1,
  95. 13, 2, 1,
  96. 13, 1, 14,
  97. 23, 0, 3,
  98. 23, 3, 20,
  99. 17, 3, 2,
  100. 17, 2, 18,
  101. 21, 7, 6,
  102. 21, 6, 22,
  103. 7, 16, 19,
  104. 7, 19, 4,
  105. 5, 8, 11,
  106. 5, 11, 6,
  107. 4, 12, 15,
  108. 4, 15, 5,
  109. 22, 11, 10,
  110. 22, 10, 23,
  111. 8, 15, 14,
  112. 8, 14, 9,
  113. 12, 19, 18,
  114. 12, 18, 13,
  115. 16, 21, 20,
  116. 16, 20, 17,
  117. 0, 23, 10,
  118. 1, 9, 14,
  119. 2, 13, 18,
  120. 3, 17, 20,
  121. 6, 11, 22,
  122. 5, 15, 8,
  123. 4, 19, 12,
  124. 7, 21, 16
  125. };
  126. static const float spotLightVertexData[] =
  127. {
  128. 0.001f, 0.001f, 0.001f,
  129. 0.001f, -0.001f, 0.001f,
  130. -0.001f, -0.001f, 0.001f,
  131. -0.001f, 0.001f, 0.001f,
  132. 1.0f, 1.0f, 1.0f,
  133. 1.0f, -1.0f, 1.0f,
  134. -1.0f, -1.0f, 1.0f,
  135. -1.0f, 1.0f, 1.0f,
  136. };
  137. static const unsigned short spotLightIndexData[] =
  138. {
  139. 3, 0, 1,
  140. 3, 1, 2,
  141. 0, 4, 5,
  142. 0, 5, 1,
  143. 3, 7, 4,
  144. 3, 4, 0,
  145. 7, 3, 2,
  146. 7, 2, 6,
  147. 6, 2, 1,
  148. 6, 1, 5,
  149. 7, 5, 4,
  150. 7, 6, 5
  151. };
  152. static const String shadowVariations[] =
  153. {
  154. // No specific hardware shadow compare variation on OpenGL, it is always supported
  155. #ifdef USE_OPENGL
  156. "LQ",
  157. "LQ",
  158. "",
  159. ""
  160. #else
  161. "",
  162. "LQHW",
  163. "",
  164. "HW"
  165. #endif
  166. };
  167. static const String fallbackVariations[] =
  168. {
  169. "",
  170. "FB"
  171. };
  172. static const String geometryVSVariations[] =
  173. {
  174. "",
  175. "Skinned",
  176. "Instanced",
  177. "Billboard"
  178. };
  179. static const String lightVSVariations[] =
  180. {
  181. "Dir",
  182. "Spot",
  183. "Point",
  184. "DirSpec",
  185. "SpotSpec",
  186. "PointSpec",
  187. "DirShadow",
  188. "SpotShadow",
  189. "PointShadow",
  190. "DirSpecShadow",
  191. "SpotSpecShadow",
  192. "PointSpecShadow"
  193. };
  194. static const String lightPSVariations[] =
  195. {
  196. "Dir",
  197. "Spot",
  198. "Point",
  199. "PointMask",
  200. "DirSpec",
  201. "SpotSpec",
  202. "PointSpec",
  203. "PointMaskSpec",
  204. "DirShadow",
  205. "SpotShadow",
  206. "PointShadow",
  207. "PointMaskShadow",
  208. "DirSpecShadow",
  209. "SpotSpecShadow",
  210. "PointSpecShadow",
  211. "PointMaskSpecShadow"
  212. };
  213. static const unsigned INSTANCING_BUFFER_MASK = MASK_INSTANCEMATRIX1 | MASK_INSTANCEMATRIX2 | MASK_INSTANCEMATRIX3;
  214. static const Viewport noViewport;
  215. OBJECTTYPESTATIC(Renderer);
  216. Renderer::Renderer(Context* context) :
  217. Object(context),
  218. defaultZone_(new Zone(context)),
  219. numViews_(0),
  220. numShadowCameras_(0),
  221. numOcclusionBuffers_(0),
  222. textureAnisotropy_(4),
  223. textureFilterMode_(FILTER_TRILINEAR),
  224. textureQuality_(QUALITY_HIGH),
  225. materialQuality_(QUALITY_HIGH),
  226. shadowMapSize_(1024),
  227. shadowQuality_(SHADOWQUALITY_HIGH_16BIT),
  228. maxShadowMaps_(1),
  229. maxShadowCascades_(MAX_CASCADE_SPLITS),
  230. maxInstanceTriangles_(500),
  231. maxOccluderTriangles_(5000),
  232. occlusionBufferSize_(256),
  233. occluderSizeThreshold_(0.1f),
  234. shadersChangedFrameNumber_(M_MAX_UNSIGNED),
  235. specularLighting_(true),
  236. drawShadows_(true),
  237. reuseShadowMaps_(true),
  238. lightStencilMasking_(true),
  239. dynamicInstancing_(true),
  240. shadersDirty_(true),
  241. initialized_(false)
  242. {
  243. SubscribeToEvent(E_SCREENMODE, HANDLER(Renderer, HandleScreenMode));
  244. SubscribeToEvent(E_GRAPHICSFEATURES, HANDLER(Renderer, HandleGraphicsFeatures));
  245. SubscribeToEvent(E_RENDERUPDATE, HANDLER(Renderer, HandleRenderUpdate));
  246. // Try to initialize right now, but skip if screen mode is not yet set
  247. Initialize();
  248. }
  249. Renderer::~Renderer()
  250. {
  251. }
  252. void Renderer::SetNumViewports(unsigned num)
  253. {
  254. viewports_.Resize(num);
  255. }
  256. void Renderer::SetViewport(unsigned index, const Viewport& viewport)
  257. {
  258. if (index >= viewports_.Size())
  259. {
  260. LOGERROR("Viewport index out of bounds");
  261. return;
  262. }
  263. viewports_[index] = viewport;
  264. }
  265. void Renderer::SetSpecularLighting(bool enable)
  266. {
  267. specularLighting_ = enable;
  268. }
  269. void Renderer::SetTextureAnisotropy(int level)
  270. {
  271. textureAnisotropy_ = Max(level, 1);
  272. }
  273. void Renderer::SetTextureFilterMode(TextureFilterMode mode)
  274. {
  275. textureFilterMode_ = mode;
  276. }
  277. void Renderer::SetTextureQuality(int quality)
  278. {
  279. quality = Clamp(quality, QUALITY_LOW, QUALITY_HIGH);
  280. if (quality != textureQuality_)
  281. {
  282. textureQuality_ = quality;
  283. ReloadTextures();
  284. }
  285. }
  286. void Renderer::SetMaterialQuality(int quality)
  287. {
  288. materialQuality_ = Clamp(quality, QUALITY_LOW, QUALITY_MAX);
  289. shadersDirty_ = true;
  290. ResetViews();
  291. }
  292. void Renderer::SetDrawShadows(bool enable)
  293. {
  294. if (!graphics_)
  295. return;
  296. drawShadows_ = enable;
  297. if (!drawShadows_)
  298. ResetShadowMaps();
  299. }
  300. void Renderer::SetShadowMapSize(int size)
  301. {
  302. if (!graphics_)
  303. return;
  304. size = NextPowerOfTwo(Max(size, SHADOW_MIN_PIXELS));
  305. if (size != shadowMapSize_)
  306. {
  307. shadowMapSize_ = size;
  308. ResetShadowMaps();
  309. }
  310. }
  311. void Renderer::SetShadowQuality(int quality)
  312. {
  313. if (!graphics_)
  314. return;
  315. quality &= SHADOWQUALITY_HIGH_24BIT;
  316. // If no hardware PCF, do not allow to select one-sample quality
  317. if (!graphics_->GetHardwareShadowSupport())
  318. quality |= SHADOWQUALITY_HIGH_16BIT;
  319. if (!graphics_->GetHiresShadowSupport())
  320. quality &= SHADOWQUALITY_HIGH_16BIT;
  321. if (graphics_->GetFallback())
  322. quality = SHADOWQUALITY_LOW_16BIT;
  323. if (quality != shadowQuality_)
  324. {
  325. shadowQuality_ = quality;
  326. shadersDirty_ = true;
  327. ResetShadowMaps();
  328. }
  329. }
  330. void Renderer::SetReuseShadowMaps(bool enable)
  331. {
  332. if (enable == reuseShadowMaps_)
  333. return;
  334. reuseShadowMaps_ = enable;
  335. }
  336. void Renderer::SetMaxShadowMaps(int shadowMaps)
  337. {
  338. if (shadowMaps < 1)
  339. return;
  340. maxShadowMaps_ = shadowMaps;
  341. for (HashMap<int, Vector<SharedPtr<Texture2D> > >::Iterator i = shadowMaps_.Begin(); i != shadowMaps_.End(); ++i)
  342. {
  343. if ((int)i->second_.Size() > maxShadowMaps_)
  344. i->second_.Resize(maxShadowMaps_);
  345. }
  346. }
  347. void Renderer::SetMaxShadowCascades(int cascades)
  348. {
  349. cascades = Clamp(cascades, 1, MAX_CASCADE_SPLITS);
  350. if (cascades != maxShadowCascades_)
  351. {
  352. maxShadowCascades_ = cascades;
  353. ResetShadowMaps();
  354. }
  355. }
  356. void Renderer::SetLightStencilMasking(bool enable)
  357. {
  358. lightStencilMasking_ = enable;
  359. }
  360. void Renderer::SetDynamicInstancing(bool enable)
  361. {
  362. if (!instancingBuffer_)
  363. enable = false;
  364. dynamicInstancing_ = enable;
  365. }
  366. void Renderer::SetMaxInstanceTriangles(int triangles)
  367. {
  368. maxInstanceTriangles_ = Max(triangles, 0);
  369. }
  370. void Renderer::SetMaxOccluderTriangles(int triangles)
  371. {
  372. maxOccluderTriangles_ = Max(triangles, 0);
  373. }
  374. void Renderer::SetOcclusionBufferSize(int size)
  375. {
  376. occlusionBufferSize_ = Max(size, 1);
  377. occlusionBuffers_.Clear();
  378. }
  379. void Renderer::SetOccluderSizeThreshold(float screenSize)
  380. {
  381. occluderSizeThreshold_ = Max(screenSize, 0.0f);
  382. }
  383. const Viewport& Renderer::GetViewport(unsigned index) const
  384. {
  385. return index < viewports_.Size() ? viewports_[index] : noViewport;
  386. }
  387. ShaderVariation* Renderer::GetVertexShader(const String& name, bool checkExists) const
  388. {
  389. return GetShader(name, vsFormat_, checkExists);
  390. }
  391. ShaderVariation* Renderer::GetPixelShader(const String& name, bool checkExists) const
  392. {
  393. return GetShader(name, psFormat_, checkExists);
  394. }
  395. unsigned Renderer::GetNumGeometries(bool allViews) const
  396. {
  397. unsigned numGeometries = 0;
  398. unsigned lastView = allViews ? numViews_ : 1;
  399. for (unsigned i = 0; i < lastView; ++i)
  400. numGeometries += views_[i]->GetGeometries().Size();
  401. return numGeometries;
  402. }
  403. unsigned Renderer::GetNumLights(bool allViews) const
  404. {
  405. unsigned numLights = 0;
  406. unsigned lastView = allViews ? numViews_ : 1;
  407. for (unsigned i = 0; i < lastView; ++i)
  408. numLights += views_[i]->GetLights().Size();
  409. return numLights;
  410. }
  411. unsigned Renderer::GetNumShadowMaps(bool allViews) const
  412. {
  413. unsigned numShadowMaps = 0;
  414. unsigned lastView = allViews ? numViews_ : 1;
  415. for (unsigned i = 0; i < lastView; ++i)
  416. {
  417. const Vector<LightBatchQueue>& lightQueues = views_[i]->GetLightQueues();
  418. for (unsigned j = 0; j < lightQueues.Size(); ++j)
  419. {
  420. if (lightQueues[j].shadowMap_)
  421. ++numShadowMaps;
  422. }
  423. }
  424. return numShadowMaps;
  425. }
  426. unsigned Renderer::GetNumOccluders(bool allViews) const
  427. {
  428. unsigned numOccluders = 0;
  429. unsigned lastView = allViews ? numViews_ : 1;
  430. for (unsigned i = 0; i < lastView; ++i)
  431. numOccluders += views_[i]->GetOccluders().Size();
  432. return numOccluders;
  433. }
  434. void Renderer::Update(float timeStep)
  435. {
  436. PROFILE(UpdateViews);
  437. numViews_ = 0;
  438. // If device lost, do not perform update. This is because any dynamic vertex/index buffer updates happen already here,
  439. // and if the device is lost, the updates queue up, causing memory use to rise constantly
  440. if (!graphics_ || !graphics_->IsInitialized() || graphics_->IsDeviceLost())
  441. return;
  442. // Advance frame number & time, set up the frameinfo structure, and reset views & stats
  443. frame_.frameNumber_ = GetSubsystem<Time>()->GetFrameNumber();
  444. frame_.timeStep_ = timeStep;
  445. frame_.camera_ = 0;
  446. numShadowCameras_ = 0;
  447. numOcclusionBuffers_ = 0;
  448. updateOctrees_.Clear();
  449. // Reload shaders if needed
  450. if (shadersDirty_)
  451. LoadShaders();
  452. // Process all viewports. Use reverse order, because during rendering the order will be reversed again to handle auxiliary
  453. // view dependencies correctly
  454. for (unsigned i = viewports_.Size() - 1; i < viewports_.Size(); --i)
  455. {
  456. unsigned mainView = numViews_;
  457. Viewport& viewport = viewports_[i];
  458. if (!AddView(0, viewport))
  459. continue;
  460. // Update octree (perform early update for nodes which need that, and reinsert moved nodes.)
  461. // However, if the same scene is viewed from multiple cameras, update the octree only once
  462. Octree* octree = viewport.scene_->GetComponent<Octree>();
  463. DebugRenderer* debug = viewport.scene_->GetComponent<DebugRenderer>();
  464. if (!updateOctrees_.Contains(octree))
  465. {
  466. frame_.camera_ = viewport.camera_;
  467. frame_.viewSize_ = IntVector2(viewport.rect_.right_ - viewport.rect_.left_, viewport.rect_.bottom_ - viewport.rect_.top_);
  468. if (frame_.viewSize_ == IntVector2::ZERO)
  469. frame_.viewSize_ = IntVector2(graphics_->GetWidth(), graphics_->GetHeight());
  470. octree->Update(frame_);
  471. updateOctrees_.Insert(octree);
  472. // Set also the view for the debug graphics already here, so that it can use culling
  473. /// \todo May result in incorrect debug geometry culling if the same scene is drawn from multiple viewports
  474. if (debug)
  475. debug->SetView(viewport.camera_);
  476. }
  477. // Update the viewport's main view and any auxiliary views it creates
  478. for (unsigned i = mainView; i < numViews_; ++i)
  479. views_[i]->Update(frame_);
  480. }
  481. return;
  482. }
  483. void Renderer::Render()
  484. {
  485. if (!graphics_)
  486. return;
  487. PROFILE(RenderViews);
  488. graphics_->SetDefaultTextureFilterMode(textureFilterMode_);
  489. graphics_->SetTextureAnisotropy(textureAnisotropy_);
  490. // If no views, just clear the screen
  491. if (!numViews_)
  492. {
  493. numPrimitives_ = 0;
  494. numBatches_ = 0;
  495. graphics_->SetAlphaTest(false);
  496. graphics_->SetBlendMode(BLEND_REPLACE);
  497. graphics_->SetColorWrite(true);
  498. graphics_->SetDepthWrite(true);
  499. graphics_->SetFillMode(FILL_SOLID);
  500. graphics_->SetScissorTest(false);
  501. graphics_->SetStencilTest(false);
  502. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH | CLEAR_STENCIL);
  503. return;
  504. }
  505. // Render views from last to first (each main view is rendered after the auxiliary views it depends on)
  506. for (unsigned i = numViews_ - 1; i < numViews_; --i)
  507. views_[i]->Render();
  508. // Copy the number of batches & primitives from Graphics so that we can account for 3D geometry only
  509. numPrimitives_ = graphics_->GetNumPrimitives();
  510. numBatches_ = graphics_->GetNumBatches();
  511. }
  512. void Renderer::DrawDebugGeometry(bool depthTest)
  513. {
  514. PROFILE(RendererDrawDebug);
  515. /// \todo Because debug geometry is per-scene, if two cameras show views of the same area, occlusion is not shown correctly
  516. HashSet<Drawable*> processedGeometries;
  517. HashSet<Light*> processedLights;
  518. for (unsigned i = 0; i < numViews_; ++i)
  519. {
  520. // Make sure it's a main view, and process each node only once
  521. View* view = views_[i];
  522. if (view->GetRenderTarget())
  523. continue;
  524. Octree* octree = view->GetOctree();
  525. if (!octree)
  526. continue;
  527. Scene* scene = static_cast<Scene*>(octree->GetNode());
  528. if (!scene)
  529. continue;
  530. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  531. if (!debug)
  532. continue;
  533. const PODVector<Drawable*>& geometries = view->GetGeometries();
  534. const PODVector<Light*>& lights = view->GetLights();
  535. for (unsigned i = 0; i < geometries.Size(); ++i)
  536. {
  537. if (!processedGeometries.Contains(geometries[i]))
  538. {
  539. geometries[i]->DrawDebugGeometry(debug, depthTest);
  540. processedGeometries.Insert(geometries[i]);
  541. }
  542. }
  543. for (unsigned i = 0; i < lights.Size(); ++i)
  544. {
  545. if (!processedLights.Contains(lights[i]))
  546. {
  547. lights[i]->DrawDebugGeometry(debug, depthTest);
  548. processedLights.Insert(lights[i]);
  549. }
  550. }
  551. }
  552. }
  553. bool Renderer::AddView(RenderSurface* renderTarget, const Viewport& viewport)
  554. {
  555. // If using a render target texture, make sure it will not be rendered to multiple times
  556. if (renderTarget)
  557. {
  558. for (unsigned i = 0; i < numViews_; ++i)
  559. {
  560. if (views_[i]->GetRenderTarget() == renderTarget)
  561. return false;
  562. }
  563. }
  564. if (views_.Size() <= numViews_)
  565. views_.Resize(numViews_ + 1);
  566. if (!views_[numViews_])
  567. views_[numViews_] = new View(context_);
  568. if (views_[numViews_]->Define(renderTarget, viewport))
  569. {
  570. ++numViews_;
  571. return true;
  572. }
  573. else
  574. return false;
  575. }
  576. Geometry* Renderer::GetLightGeometry(Light* light)
  577. {
  578. LightType type = light->GetLightType();
  579. if (type == LIGHT_SPOT)
  580. return spotLightGeometry_;
  581. else if (type == LIGHT_POINT)
  582. return pointLightGeometry_;
  583. else
  584. return 0;
  585. }
  586. Texture2D* Renderer::GetShadowMap(Light* light, Camera* camera, unsigned viewWidth, unsigned viewHeight)
  587. {
  588. LightType type = light->GetLightType();
  589. const FocusParameters& parameters = light->GetShadowFocus();
  590. float size = (float)shadowMapSize_ * light->GetShadowResolution();
  591. // Automatically reduce shadow map size when far away
  592. if (parameters.autoSize_ && type != LIGHT_DIRECTIONAL)
  593. {
  594. Matrix3x4 view(camera->GetInverseWorldTransform());
  595. Matrix4 projection(camera->GetProjection());
  596. BoundingBox lightBox;
  597. float lightPixels;
  598. if (type == LIGHT_POINT)
  599. {
  600. // Calculate point light pixel size from the projection of its diagonal
  601. Vector3 center = view * light->GetWorldPosition();
  602. float extent = 0.58f * light->GetRange();
  603. lightBox.Define(center + Vector3(extent, extent, extent), center - Vector3(extent, extent, extent));
  604. }
  605. else
  606. {
  607. // Calculate spot light pixel size from the projection of its frustum far vertices
  608. Frustum lightFrustum = light->GetFrustum().Transformed(view);
  609. lightBox.Define(&lightFrustum.vertices_[4], 4);
  610. }
  611. Vector2 projectionSize = lightBox.Projected(projection).Size();
  612. lightPixels = Max(0.5f * (float)viewWidth * projectionSize.x_, 0.5f * (float)viewHeight * projectionSize.y_);
  613. // Clamp pixel amount to a sufficient minimum to avoid self-shadowing artifacts due to loss of precision
  614. if (lightPixels < SHADOW_MIN_PIXELS)
  615. lightPixels = SHADOW_MIN_PIXELS;
  616. size = Min(size, lightPixels);
  617. }
  618. /// \todo Allow to specify maximum shadow maps per resolution, as smaller shadow maps take less memory
  619. int width = NextPowerOfTwo((unsigned)size);
  620. int height = width;
  621. // Adjust the size for directional or point light shadow map atlases
  622. if (type == LIGHT_DIRECTIONAL)
  623. {
  624. if (maxShadowCascades_ > 1)
  625. width *= 2;
  626. if (maxShadowCascades_ > 2)
  627. height *= 2;
  628. }
  629. else if (type == LIGHT_POINT)
  630. {
  631. width *= 2;
  632. height *= 3;
  633. }
  634. int searchKey = (width << 16) | height;
  635. if (shadowMaps_.Contains(searchKey))
  636. {
  637. // If shadow maps are reused, always return the first
  638. if (reuseShadowMaps_)
  639. return shadowMaps_[searchKey][0];
  640. else
  641. {
  642. // If not reused, check allocation count and return existing shadow map if possible
  643. unsigned allocated = shadowMapAllocations_[searchKey].Size();
  644. if (allocated < shadowMaps_[searchKey].Size())
  645. {
  646. shadowMapAllocations_[searchKey].Push(light);
  647. return shadowMaps_[searchKey][allocated];
  648. }
  649. else if ((int)allocated >= maxShadowMaps_)
  650. return 0;
  651. }
  652. }
  653. unsigned shadowMapFormat = (shadowQuality_ & SHADOWQUALITY_LOW_24BIT) ? graphics_->GetHiresShadowMapFormat() :
  654. graphics_->GetShadowMapFormat();
  655. unsigned dummyColorFormat = graphics_->GetDummyColorFormat();
  656. bool hardwarePCF = graphics_->GetHardwareShadowSupport();
  657. if (!shadowMapFormat)
  658. return 0;
  659. SharedPtr<Texture2D> newShadowMap(new Texture2D(context_));
  660. int retries = 3;
  661. #ifdef USE_OPENGL
  662. // Create shadow map only. Color rendertarget is not needed
  663. while (retries)
  664. {
  665. if (!newShadowMap->SetSize(width, height, shadowMapFormat, TEXTURE_DEPTHSTENCIL))
  666. {
  667. width >>= 1;
  668. height >>= 1;
  669. --retries;
  670. }
  671. else
  672. {
  673. newShadowMap->SetFilterMode(FILTER_BILINEAR);
  674. newShadowMap->SetShadowCompare(true);
  675. break;
  676. }
  677. }
  678. #else
  679. // Create shadow map and dummy color rendertarget
  680. bool fallback = graphics_->GetFallback();
  681. while (retries)
  682. {
  683. if (!newShadowMap->SetSize(width, height, shadowMapFormat, fallback ? TEXTURE_RENDERTARGET : TEXTURE_DEPTHSTENCIL))
  684. {
  685. width >>= 1;
  686. height >>= 1;
  687. --retries;
  688. }
  689. else
  690. {
  691. newShadowMap->SetFilterMode(hardwarePCF ? FILTER_BILINEAR : FILTER_NEAREST);
  692. if (!fallback)
  693. {
  694. // If no dummy color rendertarget for this size exists yet, create one now
  695. if (!colorShadowMaps_.Contains(searchKey))
  696. {
  697. colorShadowMaps_[searchKey] = new Texture2D(context_);
  698. colorShadowMaps_[searchKey]->SetSize(width, height, dummyColorFormat, TEXTURE_RENDERTARGET);
  699. }
  700. // Link the color rendertarget to the shadow map
  701. newShadowMap->GetRenderSurface()->SetLinkedRenderTarget(colorShadowMaps_[searchKey]->GetRenderSurface());
  702. }
  703. else
  704. {
  705. // In fallback mode link the shared shadow map depth stencil to the shadow map instead.
  706. // Create it first if not created yet, and resize larger if necessary
  707. if (!shadowDepthStencil_)
  708. shadowDepthStencil_ = new Texture2D(context_);
  709. if (shadowDepthStencil_->GetWidth() < width || shadowDepthStencil_->GetHeight() < height)
  710. shadowDepthStencil_->SetSize(width, height, D3DFMT_D16, TEXTURE_DEPTHSTENCIL);
  711. newShadowMap->GetRenderSurface()->SetLinkedDepthBuffer(shadowDepthStencil_->GetRenderSurface());
  712. }
  713. break;
  714. }
  715. }
  716. #endif
  717. // If failed to set size, store a null pointer so that we will not retry
  718. if (!retries)
  719. newShadowMap.Reset();
  720. shadowMaps_[searchKey].Push(newShadowMap);
  721. if (!reuseShadowMaps_)
  722. shadowMapAllocations_[searchKey].Push(light);
  723. return newShadowMap;
  724. }
  725. OcclusionBuffer* Renderer::GetOcclusionBuffer(Camera* camera)
  726. {
  727. if (numOcclusionBuffers_ >= occlusionBuffers_.Size())
  728. {
  729. SharedPtr<OcclusionBuffer> newBuffer(new OcclusionBuffer(context_));
  730. occlusionBuffers_.Push(newBuffer);
  731. }
  732. int width = occlusionBufferSize_;
  733. int height = (int)((float)occlusionBufferSize_ / camera->GetAspectRatio() + 0.5f);
  734. OcclusionBuffer* buffer = occlusionBuffers_[numOcclusionBuffers_];
  735. buffer->SetSize(width, height);
  736. buffer->SetView(camera);
  737. ++numOcclusionBuffers_;
  738. return buffer;
  739. }
  740. Camera* Renderer::GetShadowCamera()
  741. {
  742. MutexLock lock(rendererMutex_);
  743. if (numShadowCameras_ >= shadowCameraNodes_.Size())
  744. {
  745. SharedPtr<Node> newNode(new Node(context_));
  746. newNode->CreateComponent<Camera>();
  747. shadowCameraNodes_.Push(newNode);
  748. }
  749. Camera* camera = shadowCameraNodes_[numShadowCameras_]->GetComponent<Camera>();
  750. camera->SetOrthographic(false);
  751. camera->SetZoom(1.0f);
  752. ++numShadowCameras_;
  753. return camera;
  754. }
  755. ShaderVariation* Renderer::GetShader(const String& name, const String& extension, bool checkExists) const
  756. {
  757. String shaderName = shaderPath_;
  758. String variationName;
  759. unsigned split = name.Find('_');
  760. if (split != String::NPOS)
  761. {
  762. shaderName += name.Substring(0, split) + extension;
  763. variationName = name.Substring(split + 1);
  764. }
  765. else
  766. shaderName += name + extension;
  767. if (checkExists)
  768. {
  769. if (!cache_->Exists(shaderName))
  770. return 0;
  771. }
  772. Shader* shader = cache_->GetResource<Shader>(shaderName);
  773. if (shader)
  774. return shader->GetVariation(variationName);
  775. else
  776. return 0;
  777. }
  778. void Renderer::SetBatchShaders(Batch& batch, Technique* technique, Pass* pass, bool allowShadows)
  779. {
  780. // Check if shaders are unloaded or need reloading
  781. Vector<SharedPtr<ShaderVariation> >& vertexShaders = pass->GetVertexShaders();
  782. Vector<SharedPtr<ShaderVariation> >& pixelShaders = pass->GetPixelShaders();
  783. if (!vertexShaders.Size() || !pixelShaders.Size() || technique->GetShadersLoadedFrameNumber() !=
  784. shadersChangedFrameNumber_)
  785. {
  786. // First release all previous shaders, then load
  787. technique->ReleaseShaders();
  788. LoadMaterialShaders(technique);
  789. }
  790. // Make sure shaders are loaded now
  791. if (vertexShaders.Size() && pixelShaders.Size())
  792. {
  793. GeometryType geomType = batch.geometryType_;
  794. // If instancing is not supported, but was requested, or the object is too large to be instanced,
  795. // choose static geometry vertex shader instead
  796. if (geomType == GEOM_INSTANCED && (!GetDynamicInstancing() || batch.geometry_->GetIndexCount() >
  797. (unsigned)maxInstanceTriangles_ * 3))
  798. geomType = GEOM_STATIC;
  799. // Check whether is a lit pass. If not, there is only one pixel shader
  800. PassType type = pass->GetType();
  801. if (type == PASS_LIGHT || type == PASS_LITBASE)
  802. {
  803. LightBatchQueue* lightQueue = batch.lightQueue_;
  804. if (!lightQueue)
  805. {
  806. // Do not log error, as it would result in a lot of spam
  807. batch.vertexShader_ = 0;
  808. batch.pixelShader_ = 0;
  809. return;
  810. }
  811. Light* light = lightQueue->light_;
  812. unsigned vsi = 0;
  813. unsigned psi = 0;
  814. vsi = geomType * MAX_LIGHT_VS_VARIATIONS;
  815. bool materialHasSpecular = batch.material_ ? batch.material_->GetSpecular() : true;
  816. if (specularLighting_ && light->GetSpecularIntensity() > 0.0f && materialHasSpecular)
  817. {
  818. vsi += LVS_SPEC;
  819. psi += LPS_SPEC;
  820. }
  821. if (allowShadows && lightQueue->shadowMap_)
  822. {
  823. vsi += LVS_SHADOW;
  824. psi += LPS_SHADOW;
  825. }
  826. switch (light->GetLightType())
  827. {
  828. case LIGHT_DIRECTIONAL:
  829. vsi += LVS_DIR;
  830. break;
  831. case LIGHT_POINT:
  832. if (light->GetShapeTexture())
  833. psi += LPS_POINTMASK;
  834. else
  835. psi += LPS_POINT;
  836. vsi += LVS_POINT;
  837. break;
  838. case LIGHT_SPOT:
  839. psi += LPS_SPOT;
  840. vsi += LVS_SPOT;
  841. break;
  842. }
  843. batch.vertexShader_ = vertexShaders[vsi];
  844. batch.pixelShader_ = pixelShaders[psi];
  845. // If shadow or specular variations do not exist, try without them
  846. if ((!batch.vertexShader_ || !batch.pixelShader_) && (vsi >= LVS_SHADOW))
  847. {
  848. vsi -= LVS_SHADOW;
  849. psi -= LPS_SHADOW;
  850. batch.vertexShader_ = vertexShaders[vsi];
  851. batch.pixelShader_ = pixelShaders[psi];
  852. }
  853. if ((!batch.vertexShader_ || !batch.pixelShader_) && (vsi >= LVS_SPEC))
  854. {
  855. vsi -= LVS_SPEC;
  856. psi -= LPS_SPEC;
  857. batch.vertexShader_ = vertexShaders[vsi];
  858. batch.pixelShader_ = pixelShaders[psi];
  859. }
  860. }
  861. else
  862. {
  863. unsigned vsi = geomType;
  864. batch.vertexShader_ = vertexShaders[vsi];
  865. batch.pixelShader_ = pixelShaders[0];
  866. }
  867. }
  868. // Log error if shaders could not be assigned, but only once per technique
  869. if (!batch.vertexShader_ || !batch.pixelShader_)
  870. {
  871. if (!shaderErrorDisplayed_.Contains(technique))
  872. {
  873. shaderErrorDisplayed_.Insert(technique);
  874. LOGERROR("Technique " + technique->GetName() + " has missing shaders");
  875. }
  876. }
  877. }
  878. bool Renderer::ResizeInstancingBuffer(unsigned numInstances)
  879. {
  880. if (!instancingBuffer_ || !dynamicInstancing_)
  881. return false;
  882. unsigned oldSize = instancingBuffer_->GetVertexCount();
  883. if (numInstances <= oldSize)
  884. return true;
  885. unsigned newSize = INSTANCING_BUFFER_DEFAULT_SIZE;
  886. while (newSize < numInstances)
  887. newSize <<= 1;
  888. if (!instancingBuffer_->SetSize(newSize, INSTANCING_BUFFER_MASK, true))
  889. {
  890. LOGERROR("Failed to resize instancing buffer to " + String(newSize));
  891. // If failed, try to restore the old size
  892. instancingBuffer_->SetSize(oldSize, INSTANCING_BUFFER_MASK, true);
  893. return false;
  894. }
  895. LOGDEBUG("Resized instancing buffer to " + String(newSize));
  896. return true;
  897. }
  898. void Renderer::ResetShadowMapAllocations()
  899. {
  900. for (HashMap<int, PODVector<Light*> >::Iterator i = shadowMapAllocations_.Begin(); i != shadowMapAllocations_.End(); ++i)
  901. i->second_.Clear();
  902. }
  903. void Renderer::Initialize()
  904. {
  905. Graphics* graphics = GetSubsystem<Graphics>();
  906. ResourceCache* cache = GetSubsystem<ResourceCache>();
  907. if (!graphics || !graphics->IsInitialized() || !cache)
  908. return;
  909. PROFILE(InitRenderer);
  910. graphics_ = graphics;
  911. cache_ = cache;
  912. // Check shader model support
  913. #ifndef USE_OPENGL
  914. if (graphics_->GetSM3Support())
  915. {
  916. shaderPath_ = "Shaders/SM3/";
  917. vsFormat_ = ".vs3";
  918. psFormat_ = ".ps3";
  919. }
  920. else
  921. {
  922. shaderPath_ = "Shaders/SM2/";
  923. vsFormat_ = ".vs2";
  924. psFormat_ = ".ps2";
  925. }
  926. #else
  927. {
  928. shaderPath_ = "Shaders/GLSL/";
  929. vsFormat_ = ".vert";
  930. psFormat_ = ".frag";
  931. }
  932. #endif
  933. defaultLightRamp_ = cache->GetResource<Texture2D>("Textures/Ramp.png");
  934. defaultLightSpot_ = cache->GetResource<Texture2D>("Textures/Spot.png");
  935. defaultMaterial_ = cache->GetResource<Material>("Materials/Default.xml");
  936. CreateGeometries();
  937. CreateInstancingBuffer();
  938. viewports_.Resize(1);
  939. ResetViews();
  940. ResetShadowMaps();
  941. shadersDirty_ = true;
  942. initialized_ = true;
  943. LOGINFO("Initialized renderer");
  944. }
  945. void Renderer::ResetViews()
  946. {
  947. views_.Clear();
  948. numViews_ = 0;
  949. }
  950. void Renderer::LoadShaders()
  951. {
  952. LOGINFO("Reloading shaders");
  953. // Release old material shaders, mark them for reload
  954. ReleaseMaterialShaders();
  955. shadersChangedFrameNumber_ = GetSubsystem<Time>()->GetFrameNumber();
  956. // Load inbuilt shaders
  957. stencilVS_ = GetVertexShader("Stencil");
  958. stencilPS_ = GetPixelShader("Stencil");
  959. shadersDirty_ = false;
  960. }
  961. void Renderer::LoadMaterialShaders(Technique* technique)
  962. {
  963. LoadPassShaders(technique, PASS_BASE);
  964. LoadPassShaders(technique, PASS_LITBASE);
  965. LoadPassShaders(technique, PASS_LIGHT);
  966. LoadPassShaders(technique, PASS_PREALPHA);
  967. LoadPassShaders(technique, PASS_POSTALPHA);
  968. LoadPassShaders(technique, PASS_SHADOW);
  969. }
  970. void Renderer::LoadPassShaders(Technique* technique, PassType type, bool allowShadows)
  971. {
  972. Pass* pass = technique->GetPass(type);
  973. if (!pass)
  974. return;
  975. String vertexShaderName = pass->GetVertexShaderName();
  976. String pixelShaderName = pass->GetPixelShaderName();
  977. // Check if the shader name is already a variation in itself
  978. if (vertexShaderName.Find('_') == String::NPOS)
  979. vertexShaderName += "_";
  980. if (pixelShaderName.Find('_') == String::NPOS)
  981. pixelShaderName += "_";
  982. unsigned shadows = (graphics_->GetHardwareShadowSupport() ? 1 : 0) | (shadowQuality_ & SHADOWQUALITY_HIGH_16BIT);
  983. unsigned fallback = graphics_->GetFallback() ? 1 : 0;
  984. if (fallback)
  985. shadows = SHADOWQUALITY_HIGH_16BIT;
  986. if (type == PASS_SHADOW)
  987. {
  988. vertexShaderName += fallbackVariations[fallback];
  989. pixelShaderName += fallbackVariations[fallback];
  990. }
  991. Vector<SharedPtr<ShaderVariation> >& vertexShaders = pass->GetVertexShaders();
  992. Vector<SharedPtr<ShaderVariation> >& pixelShaders = pass->GetPixelShaders();
  993. // Forget all the old shaders
  994. vertexShaders.Clear();
  995. pixelShaders.Clear();
  996. if (type == PASS_LIGHT || type == PASS_LITBASE)
  997. {
  998. // If ambient pass is transparent, and shadow maps are reused, do not load shadow variations
  999. if (reuseShadowMaps_)
  1000. {
  1001. if (!technique->HasPass(PASS_BASE) || technique->GetPass(PASS_BASE)->GetBlendMode() != BLEND_REPLACE)
  1002. allowShadows = false;
  1003. }
  1004. vertexShaders.Resize(MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS);
  1005. pixelShaders.Resize(MAX_LIGHT_PS_VARIATIONS);
  1006. for (unsigned j = 0; j < MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS; ++j)
  1007. {
  1008. unsigned g = j / MAX_LIGHT_VS_VARIATIONS;
  1009. unsigned l = j % MAX_LIGHT_VS_VARIATIONS;
  1010. if (l < LVS_SHADOW || allowShadows)
  1011. vertexShaders[j] = GetVertexShader(vertexShaderName + lightVSVariations[l] + geometryVSVariations[g], g != 0);
  1012. else
  1013. vertexShaders[j].Reset();
  1014. }
  1015. for (unsigned j = 0; j < MAX_LIGHT_PS_VARIATIONS; ++j)
  1016. {
  1017. if (j & LPS_SHADOW)
  1018. {
  1019. if (allowShadows)
  1020. {
  1021. pixelShaders[j] = GetPixelShader(pixelShaderName + lightPSVariations[j] + shadowVariations[shadows] +
  1022. fallbackVariations[fallback]);
  1023. }
  1024. else
  1025. pixelShaders[j].Reset();
  1026. }
  1027. else
  1028. pixelShaders[j] = GetPixelShader(pixelShaderName + lightPSVariations[j]);
  1029. }
  1030. }
  1031. else
  1032. {
  1033. vertexShaders.Resize(MAX_GEOMETRYTYPES);
  1034. pixelShaders.Resize(1);
  1035. for (unsigned j = 0; j < MAX_GEOMETRYTYPES; ++j)
  1036. vertexShaders[j] = GetVertexShader(vertexShaderName + geometryVSVariations[j], j != 0);
  1037. pixelShaders[0] = GetPixelShader(pixelShaderName);
  1038. }
  1039. technique->MarkShadersLoaded(shadersChangedFrameNumber_);
  1040. }
  1041. void Renderer::ReleaseMaterialShaders()
  1042. {
  1043. PODVector<Material*> materials;
  1044. cache_->GetResources<Material>(materials);
  1045. for (unsigned i = 0; i < materials.Size(); ++i)
  1046. materials[i]->ReleaseShaders();
  1047. }
  1048. void Renderer::ReloadTextures()
  1049. {
  1050. PODVector<Resource*> textures;
  1051. cache_->GetResources(textures, Texture2D::GetTypeStatic());
  1052. for (unsigned i = 0; i < textures.Size(); ++i)
  1053. cache_->ReloadResource(textures[i]);
  1054. cache_->GetResources(textures, TextureCube::GetTypeStatic());
  1055. for (unsigned i = 0; i < textures.Size(); ++i)
  1056. cache_->ReloadResource(textures[i]);
  1057. }
  1058. void Renderer::CreateGeometries()
  1059. {
  1060. SharedPtr<VertexBuffer> plvb(new VertexBuffer(context_));
  1061. plvb->SetSize(24, MASK_POSITION);
  1062. plvb->SetData(pointLightVertexData);
  1063. SharedPtr<IndexBuffer> plib(new IndexBuffer(context_));
  1064. plib->SetSize(132, false);
  1065. plib->SetData(pointLightIndexData);
  1066. pointLightGeometry_ = new Geometry(context_);
  1067. pointLightGeometry_->SetVertexBuffer(0, plvb);
  1068. pointLightGeometry_->SetIndexBuffer(plib);
  1069. pointLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, plib->GetIndexCount());
  1070. SharedPtr<VertexBuffer> slvb(new VertexBuffer(context_));
  1071. slvb->SetSize(8, MASK_POSITION);
  1072. slvb->SetData(spotLightVertexData);
  1073. SharedPtr<IndexBuffer> slib(new IndexBuffer(context_));
  1074. slib->SetSize(36, false);
  1075. slib->SetData(spotLightIndexData);
  1076. spotLightGeometry_ = new Geometry(context_);
  1077. spotLightGeometry_->SetVertexBuffer(0, slvb);
  1078. spotLightGeometry_->SetIndexBuffer(slib);
  1079. spotLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, slib->GetIndexCount());
  1080. faceSelectCubeMap_ = new TextureCube(context_);
  1081. faceSelectCubeMap_->SetNumLevels(1);
  1082. faceSelectCubeMap_->SetSize(1, graphics_->GetRGBAFormat());
  1083. faceSelectCubeMap_->SetFilterMode(FILTER_NEAREST);
  1084. unsigned char data[256 * 256 * 4];
  1085. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1086. {
  1087. unsigned axis = i / 2;
  1088. data[0] = (axis == 0) ? 255 : 0;
  1089. data[1] = (axis == 1) ? 255 : 0;
  1090. data[2] = (axis == 2) ? 255 : 0;
  1091. data[3] = 0;
  1092. faceSelectCubeMap_->SetData((CubeMapFace)i, 0, 0, 0, 1, 1, data);
  1093. }
  1094. indirectionCubeMap_ = new TextureCube(context_);
  1095. indirectionCubeMap_->SetNumLevels(1);
  1096. indirectionCubeMap_->SetSize(256, graphics_->GetRGBAFormat());
  1097. indirectionCubeMap_->SetFilterMode(FILTER_BILINEAR);
  1098. indirectionCubeMap_->SetAddressMode(COORD_U, ADDRESS_CLAMP);
  1099. indirectionCubeMap_->SetAddressMode(COORD_V, ADDRESS_CLAMP);
  1100. indirectionCubeMap_->SetAddressMode(COORD_W, ADDRESS_CLAMP);
  1101. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1102. {
  1103. unsigned char faceX = (i & 1) * 255;
  1104. unsigned char faceY = (i / 2) * 255 / 3;
  1105. unsigned char* dest = data;
  1106. for (unsigned y = 0; y < 256; ++y)
  1107. {
  1108. for (unsigned x = 0; x < 256; ++x)
  1109. {
  1110. #ifdef USE_OPENGL
  1111. *dest++ = x;
  1112. *dest++ = 255 - y;
  1113. *dest++ = faceX;
  1114. *dest++ = 255 * 2 / 3 - faceY;
  1115. #else
  1116. *dest++ = x;
  1117. *dest++ = y;
  1118. *dest++ = faceX;
  1119. *dest++ = faceY;
  1120. #endif
  1121. }
  1122. }
  1123. indirectionCubeMap_->SetData((CubeMapFace)i, 0, 0, 0, 256, 256, data);
  1124. }
  1125. }
  1126. void Renderer::CreateInstancingBuffer()
  1127. {
  1128. // Do not create buffer if instancing not supported
  1129. if (!graphics_->GetSM3Support())
  1130. {
  1131. instancingBuffer_.Reset();
  1132. dynamicInstancing_ = false;
  1133. return;
  1134. }
  1135. // If must lock the buffer for each batch group, set a smaller size
  1136. unsigned defaultSize = graphics_->GetStreamOffsetSupport() ? INSTANCING_BUFFER_DEFAULT_SIZE : INSTANCING_BUFFER_DEFAULT_SIZE / 4;
  1137. instancingBuffer_ = new VertexBuffer(context_);
  1138. if (!instancingBuffer_->SetSize(defaultSize, INSTANCING_BUFFER_MASK, true))
  1139. {
  1140. instancingBuffer_.Reset();
  1141. dynamicInstancing_ = false;
  1142. }
  1143. }
  1144. void Renderer::ResetShadowMaps()
  1145. {
  1146. shadowMaps_.Clear();
  1147. colorShadowMaps_.Clear();
  1148. shadowDepthStencil_.Reset();
  1149. }
  1150. void Renderer::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  1151. {
  1152. if (!initialized_)
  1153. Initialize();
  1154. else
  1155. {
  1156. // When screen mode changes, purge old views
  1157. ResetViews();
  1158. }
  1159. }
  1160. void Renderer::HandleGraphicsFeatures(StringHash eventType, VariantMap& eventData)
  1161. {
  1162. // Reinitialize if already initialized
  1163. if (initialized_)
  1164. Initialize();
  1165. }
  1166. void Renderer::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  1167. {
  1168. if (initialized_)
  1169. {
  1170. using namespace RenderUpdate;
  1171. Update(eventData[P_TIMESTEP].GetFloat());
  1172. }
  1173. }