Renderer.cpp 42 KB

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