Renderer.cpp 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "Camera.h"
  24. #include "CoreEvents.h"
  25. #include "DebugRenderer.h"
  26. #include "Geometry.h"
  27. #include "Graphics.h"
  28. #include "GraphicsEvents.h"
  29. #include "GraphicsImpl.h"
  30. #include "IndexBuffer.h"
  31. #include "Log.h"
  32. #include "Material.h"
  33. #include "OcclusionBuffer.h"
  34. #include "Octree.h"
  35. #include "Profiler.h"
  36. #include "Renderer.h"
  37. #include "RenderPath.h"
  38. #include "ResourceCache.h"
  39. #include "Scene.h"
  40. #include "Shader.h"
  41. #include "ShaderVariation.h"
  42. #include "Technique.h"
  43. #include "Texture2D.h"
  44. #include "TextureCube.h"
  45. #include "VertexBuffer.h"
  46. #include "View.h"
  47. #include "XMLFile.h"
  48. #include "Zone.h"
  49. #include "DebugNew.h"
  50. namespace Urho3D
  51. {
  52. static const float dirLightVertexData[] =
  53. {
  54. -1, 1, 0,
  55. 1, 1, 0,
  56. 1, -1, 0,
  57. -1, -1, 0,
  58. };
  59. static const unsigned short dirLightIndexData[] =
  60. {
  61. 0, 1, 2,
  62. 2, 3, 0,
  63. };
  64. static const float pointLightVertexData[] =
  65. {
  66. -0.423169f, -1.000000f, 0.423169f,
  67. -0.423169f, -1.000000f, -0.423169f,
  68. 0.423169f, -1.000000f, -0.423169f,
  69. 0.423169f, -1.000000f, 0.423169f,
  70. 0.423169f, 1.000000f, -0.423169f,
  71. -0.423169f, 1.000000f, -0.423169f,
  72. -0.423169f, 1.000000f, 0.423169f,
  73. 0.423169f, 1.000000f, 0.423169f,
  74. -1.000000f, 0.423169f, -0.423169f,
  75. -1.000000f, -0.423169f, -0.423169f,
  76. -1.000000f, -0.423169f, 0.423169f,
  77. -1.000000f, 0.423169f, 0.423169f,
  78. 0.423169f, 0.423169f, -1.000000f,
  79. 0.423169f, -0.423169f, -1.000000f,
  80. -0.423169f, -0.423169f, -1.000000f,
  81. -0.423169f, 0.423169f, -1.000000f,
  82. 1.000000f, 0.423169f, 0.423169f,
  83. 1.000000f, -0.423169f, 0.423169f,
  84. 1.000000f, -0.423169f, -0.423169f,
  85. 1.000000f, 0.423169f, -0.423169f,
  86. 0.423169f, -0.423169f, 1.000000f,
  87. 0.423169f, 0.423169f, 1.000000f,
  88. -0.423169f, 0.423169f, 1.000000f,
  89. -0.423169f, -0.423169f, 1.000000f
  90. };
  91. static const unsigned short pointLightIndexData[] =
  92. {
  93. 0, 1, 2,
  94. 0, 2, 3,
  95. 4, 5, 6,
  96. 4, 6, 7,
  97. 8, 9, 10,
  98. 8, 10, 11,
  99. 12, 13, 14,
  100. 12, 14, 15,
  101. 16, 17, 18,
  102. 16, 18, 19,
  103. 20, 21, 22,
  104. 20, 22, 23,
  105. 0, 10, 9,
  106. 0, 9, 1,
  107. 13, 2, 1,
  108. 13, 1, 14,
  109. 23, 0, 3,
  110. 23, 3, 20,
  111. 17, 3, 2,
  112. 17, 2, 18,
  113. 21, 7, 6,
  114. 21, 6, 22,
  115. 7, 16, 19,
  116. 7, 19, 4,
  117. 5, 8, 11,
  118. 5, 11, 6,
  119. 4, 12, 15,
  120. 4, 15, 5,
  121. 22, 11, 10,
  122. 22, 10, 23,
  123. 8, 15, 14,
  124. 8, 14, 9,
  125. 12, 19, 18,
  126. 12, 18, 13,
  127. 16, 21, 20,
  128. 16, 20, 17,
  129. 0, 23, 10,
  130. 1, 9, 14,
  131. 2, 13, 18,
  132. 3, 17, 20,
  133. 6, 11, 22,
  134. 5, 15, 8,
  135. 4, 19, 12,
  136. 7, 21, 16
  137. };
  138. static const float spotLightVertexData[] =
  139. {
  140. 0.00001f, 0.00001f, 0.00001f,
  141. 0.00001f, -0.00001f, 0.00001f,
  142. -0.00001f, -0.00001f, 0.00001f,
  143. -0.00001f, 0.00001f, 0.00001f,
  144. 1.00000f, 1.00000f, 0.99999f,
  145. 1.00000f, -1.00000f, 0.99999f,
  146. -1.00000f, -1.00000f, 0.99999f,
  147. -1.00000f, 1.00000f, 0.99999f,
  148. };
  149. static const unsigned short spotLightIndexData[] =
  150. {
  151. 3, 0, 1,
  152. 3, 1, 2,
  153. 0, 4, 5,
  154. 0, 5, 1,
  155. 3, 7, 4,
  156. 3, 4, 0,
  157. 7, 3, 2,
  158. 7, 2, 6,
  159. 6, 2, 1,
  160. 6, 1, 5,
  161. 7, 5, 4,
  162. 7, 6, 5
  163. };
  164. static const char* shadowVariations[] =
  165. {
  166. #ifdef USE_OPENGL
  167. // No specific hardware shadow compare variation on OpenGL, it is always supported
  168. "LQSHADOW ",
  169. "LQSHADOW ",
  170. "",
  171. ""
  172. #else
  173. // On Direct3D the quality is always "low" if not using hardware shadow compare
  174. "",
  175. "LQSHADOW HWSHADOW ",
  176. "",
  177. "HWSHADOW "
  178. #endif
  179. };
  180. static const char* geometryVSVariations[] =
  181. {
  182. "",
  183. "SKINNED ",
  184. "INSTANCED ",
  185. "BILLBOARD "
  186. };
  187. static const char* lightVSVariations[] =
  188. {
  189. "PERPIXEL DIRLIGHT ",
  190. "PERPIXEL SPOTLIGHT ",
  191. "PERPIXEL POINTLIGHT ",
  192. "PERPIXEL DIRLIGHT SPECULAR ",
  193. "PERPIXEL SPOTLIGHT SPECULAR ",
  194. "PERPIXEL POINTLIGHT SPECULAR ",
  195. "PERPIXEL DIRLIGHT SHADOW ",
  196. "PERPIXEL SPOTLIGHT SHADOW ",
  197. "PERPIXEL POINTLIGHT SHADOW ",
  198. "PERPIXEL DIRLIGHT SPECULAR SHADOW ",
  199. "PERPIXEL SPOTLIGHT SPECULAR SHADOW ",
  200. "PERPIXEL POINTLIGHT SPECULAR SHADOW "
  201. };
  202. static const char* vertexLightVSVariations[] =
  203. {
  204. "",
  205. "NUMVERTEXLIGHTS=1 ",
  206. "NUMVERTEXLIGHTS=2 ",
  207. "NUMVERTEXLIGHTS=3 ",
  208. "NUMVERTEXLIGHTS=4 ",
  209. };
  210. static const char* deferredLightVSVariations[] =
  211. {
  212. "",
  213. "DIRLIGHT ",
  214. "ORTHO ",
  215. "DIRLIGHT ORTHO "
  216. };
  217. static const char* lightPSVariations[] =
  218. {
  219. "PERPIXEL DIRLIGHT ",
  220. "PERPIXEL SPOTLIGHT ",
  221. "PERPIXEL POINTLIGHT ",
  222. "PERPIXEL POINTLIGHT CUBEMASK ",
  223. "PERPIXEL DIRLIGHT SPECULAR ",
  224. "PERPIXEL SPOTLIGHT SPECULAR ",
  225. "PERPIXEL POINTLIGHT SPECULAR ",
  226. "PERPIXEL POINTLIGHT CUBEMASK SPECULAR ",
  227. "PERPIXEL DIRLIGHT SHADOW ",
  228. "PERPIXEL SPOTLIGHT SHADOW ",
  229. "PERPIXEL POINTLIGHT SHADOW ",
  230. "PERPIXEL POINTLIGHT CUBEMASK SHADOW ",
  231. "PERPIXEL DIRLIGHT SPECULAR SHADOW ",
  232. "PERPIXEL SPOTLIGHT SPECULAR SHADOW ",
  233. "PERPIXEL POINTLIGHT SPECULAR SHADOW ",
  234. "PERPIXEL POINTLIGHT CUBEMASK SPECULAR SHADOW "
  235. };
  236. static const char* heightFogVariations[] =
  237. {
  238. "",
  239. "HEIGHTFOG "
  240. };
  241. static const unsigned INSTANCING_BUFFER_MASK = MASK_INSTANCEMATRIX1 | MASK_INSTANCEMATRIX2 | MASK_INSTANCEMATRIX3;
  242. static const unsigned MAX_BUFFER_AGE = 1000;
  243. Renderer::Renderer(Context* context) :
  244. Object(context),
  245. defaultZone_(new Zone(context)),
  246. quadDirLight_(new Light(context)),
  247. textureAnisotropy_(4),
  248. textureFilterMode_(FILTER_TRILINEAR),
  249. textureQuality_(QUALITY_HIGH),
  250. materialQuality_(QUALITY_HIGH),
  251. shadowMapSize_(1024),
  252. shadowQuality_(SHADOWQUALITY_HIGH_16BIT),
  253. maxShadowMaps_(1),
  254. maxShadowCascades_(MAX_CASCADE_SPLITS),
  255. minInstances_(2),
  256. maxInstanceTriangles_(500),
  257. maxSortedInstances_(1000),
  258. maxOccluderTriangles_(5000),
  259. occlusionBufferSize_(256),
  260. occluderSizeThreshold_(0.025f),
  261. numViews_(0),
  262. numOcclusionBuffers_(0),
  263. numShadowCameras_(0),
  264. shadersChangedFrameNumber_(M_MAX_UNSIGNED),
  265. hdrRendering_(false),
  266. specularLighting_(true),
  267. drawShadows_(true),
  268. reuseShadowMaps_(true),
  269. dynamicInstancing_(true),
  270. shadersDirty_(true),
  271. initialized_(false)
  272. {
  273. #ifndef USE_OPENGL
  274. shaderPath_ = "Shaders/HLSL/";
  275. shaderExtension_ = ".hlsl";
  276. #else
  277. shaderPath_ = "Shaders/GLSL/";
  278. shaderExtension_ = ".glsl";
  279. #endif
  280. SubscribeToEvent(E_SCREENMODE, HANDLER(Renderer, HandleScreenMode));
  281. SubscribeToEvent(E_GRAPHICSFEATURES, HANDLER(Renderer, HandleGraphicsFeatures));
  282. quadDirLight_->SetLightType(LIGHT_DIRECTIONAL);
  283. // Try to initialize right now, but skip if screen mode is not yet set
  284. Initialize();
  285. }
  286. Renderer::~Renderer()
  287. {
  288. }
  289. void Renderer::SetNumViewports(unsigned num)
  290. {
  291. viewports_.Resize(num);
  292. }
  293. void Renderer::SetViewport(unsigned index, Viewport* viewport)
  294. {
  295. if (index >= viewports_.Size())
  296. viewports_.Resize(index + 1);
  297. viewports_[index] = viewport;
  298. }
  299. void Renderer::SetDefaultRenderPath(RenderPath* renderPath)
  300. {
  301. if (renderPath)
  302. defaultRenderPath_ = renderPath;
  303. }
  304. void Renderer::SetDefaultRenderPath(XMLFile* xmlFile)
  305. {
  306. SharedPtr<RenderPath> newRenderPath(new RenderPath());
  307. if (newRenderPath->Load(xmlFile))
  308. defaultRenderPath_ = newRenderPath;
  309. }
  310. void Renderer::SetHDRRendering(bool enable)
  311. {
  312. hdrRendering_ = enable;
  313. }
  314. void Renderer::SetSpecularLighting(bool enable)
  315. {
  316. specularLighting_ = enable;
  317. }
  318. void Renderer::SetTextureAnisotropy(int level)
  319. {
  320. textureAnisotropy_ = Max(level, 1);
  321. }
  322. void Renderer::SetTextureFilterMode(TextureFilterMode mode)
  323. {
  324. textureFilterMode_ = mode;
  325. }
  326. void Renderer::SetTextureQuality(int quality)
  327. {
  328. quality = Clamp(quality, QUALITY_LOW, QUALITY_HIGH);
  329. if (quality != textureQuality_)
  330. {
  331. textureQuality_ = quality;
  332. ReloadTextures();
  333. }
  334. }
  335. void Renderer::SetMaterialQuality(int quality)
  336. {
  337. quality = Clamp(quality, QUALITY_LOW, QUALITY_MAX);
  338. if (quality != materialQuality_)
  339. {
  340. materialQuality_ = quality;
  341. shadersDirty_ = true;
  342. ResetViews();
  343. }
  344. }
  345. void Renderer::SetDrawShadows(bool enable)
  346. {
  347. if (!graphics_ || !graphics_->GetShadowMapFormat())
  348. return;
  349. drawShadows_ = enable;
  350. if (!drawShadows_)
  351. ResetShadowMaps();
  352. }
  353. void Renderer::SetShadowMapSize(int size)
  354. {
  355. if (!graphics_)
  356. return;
  357. size = NextPowerOfTwo(Max(size, SHADOW_MIN_PIXELS));
  358. if (size != shadowMapSize_)
  359. {
  360. shadowMapSize_ = size;
  361. ResetShadowMaps();
  362. }
  363. }
  364. void Renderer::SetShadowQuality(int quality)
  365. {
  366. if (!graphics_)
  367. return;
  368. quality &= SHADOWQUALITY_HIGH_24BIT;
  369. // If no hardware PCF, do not allow to select one-sample quality
  370. if (!graphics_->GetHardwareShadowSupport())
  371. quality |= SHADOWQUALITY_HIGH_16BIT;
  372. if (!graphics_->GetHiresShadowMapFormat())
  373. quality &= SHADOWQUALITY_HIGH_16BIT;
  374. if (quality != shadowQuality_)
  375. {
  376. shadowQuality_ = quality;
  377. shadersDirty_ = true;
  378. ResetShadowMaps();
  379. }
  380. }
  381. void Renderer::SetReuseShadowMaps(bool enable)
  382. {
  383. if (enable == reuseShadowMaps_)
  384. return;
  385. reuseShadowMaps_ = enable;
  386. }
  387. void Renderer::SetMaxShadowMaps(int shadowMaps)
  388. {
  389. if (shadowMaps < 1)
  390. return;
  391. maxShadowMaps_ = shadowMaps;
  392. for (HashMap<int, Vector<SharedPtr<Texture2D> > >::Iterator i = shadowMaps_.Begin(); i != shadowMaps_.End(); ++i)
  393. {
  394. if ((int)i->second_.Size() > maxShadowMaps_)
  395. i->second_.Resize(maxShadowMaps_);
  396. }
  397. }
  398. void Renderer::SetMaxShadowCascades(int cascades)
  399. {
  400. cascades = Clamp(cascades, 1, MAX_CASCADE_SPLITS);
  401. if (cascades != maxShadowCascades_)
  402. {
  403. maxShadowCascades_ = cascades;
  404. ResetShadowMaps();
  405. }
  406. }
  407. void Renderer::SetDynamicInstancing(bool enable)
  408. {
  409. if (!instancingBuffer_)
  410. enable = false;
  411. dynamicInstancing_ = enable;
  412. }
  413. void Renderer::SetMinInstances(int instances)
  414. {
  415. minInstances_ = Max(instances, 2);
  416. }
  417. void Renderer::SetMaxInstanceTriangles(int triangles)
  418. {
  419. maxInstanceTriangles_ = Max(triangles, 0);
  420. }
  421. void Renderer::SetMaxSortedInstances(int instances)
  422. {
  423. maxSortedInstances_ = Max(instances, 0);
  424. }
  425. void Renderer::SetMaxOccluderTriangles(int triangles)
  426. {
  427. maxOccluderTriangles_ = Max(triangles, 0);
  428. }
  429. void Renderer::SetOcclusionBufferSize(int size)
  430. {
  431. occlusionBufferSize_ = Max(size, 1);
  432. occlusionBuffers_.Clear();
  433. }
  434. void Renderer::SetOccluderSizeThreshold(float screenSize)
  435. {
  436. occluderSizeThreshold_ = Max(screenSize, 0.0f);
  437. }
  438. void Renderer::ReloadShaders()
  439. {
  440. shadersDirty_ = true;
  441. }
  442. Viewport* Renderer::GetViewport(unsigned index) const
  443. {
  444. return index < viewports_.Size() ? viewports_[index] : (Viewport*)0;
  445. }
  446. RenderPath* Renderer::GetDefaultRenderPath() const
  447. {
  448. return defaultRenderPath_;
  449. }
  450. unsigned Renderer::GetNumGeometries(bool allViews) const
  451. {
  452. unsigned numGeometries = 0;
  453. unsigned lastView = allViews ? numViews_ : 1;
  454. for (unsigned i = 0; i < lastView; ++i)
  455. numGeometries += views_[i]->GetGeometries().Size();
  456. return numGeometries;
  457. }
  458. unsigned Renderer::GetNumLights(bool allViews) const
  459. {
  460. unsigned numLights = 0;
  461. unsigned lastView = allViews ? numViews_ : 1;
  462. for (unsigned i = 0; i < lastView; ++i)
  463. numLights += views_[i]->GetLights().Size();
  464. return numLights;
  465. }
  466. unsigned Renderer::GetNumShadowMaps(bool allViews) const
  467. {
  468. unsigned numShadowMaps = 0;
  469. unsigned lastView = allViews ? numViews_ : 1;
  470. for (unsigned i = 0; i < lastView; ++i)
  471. {
  472. const Vector<LightBatchQueue>& lightQueues = views_[i]->GetLightQueues();
  473. for (Vector<LightBatchQueue>::ConstIterator i = lightQueues.Begin(); i != lightQueues.End(); ++i)
  474. {
  475. if (i->shadowMap_)
  476. ++numShadowMaps;
  477. }
  478. }
  479. return numShadowMaps;
  480. }
  481. unsigned Renderer::GetNumOccluders(bool allViews) const
  482. {
  483. unsigned numOccluders = 0;
  484. unsigned lastView = allViews ? numViews_ : 1;
  485. for (unsigned i = 0; i < lastView; ++i)
  486. numOccluders += views_[i]->GetOccluders().Size();
  487. return numOccluders;
  488. }
  489. ShaderVariation* Renderer::GetShader(ShaderType type, const String& name, const String& defines) const
  490. {
  491. return GetShader(type, name.CString(), defines.CString());
  492. }
  493. ShaderVariation* Renderer::GetShader(ShaderType type, const char* name, const char* defines) const
  494. {
  495. if (lastShaderName_ != name || !lastShader_)
  496. {
  497. ResourceCache* cache = GetSubsystem<ResourceCache>();
  498. String fullShaderName = shaderPath_ + name + shaderExtension_;
  499. // Try to reduce repeated error log prints because of missing shaders
  500. if (lastShaderName_ == name && !cache->Exists(fullShaderName))
  501. return 0;
  502. lastShader_ = cache->GetResource<Shader>(fullShaderName);
  503. lastShaderName_ = name;
  504. }
  505. return lastShader_ ? lastShader_->GetVariation(type, defines) : (ShaderVariation*)0;
  506. }
  507. void Renderer::Update(float timeStep)
  508. {
  509. PROFILE(UpdateViews);
  510. numViews_ = 0;
  511. // If device lost, do not perform update. This is because any dynamic vertex/index buffer updates happen already here,
  512. // and if the device is lost, the updates queue up, causing memory use to rise constantly
  513. if (!graphics_ || !graphics_->IsInitialized() || graphics_->IsDeviceLost())
  514. return;
  515. // Set up the frameinfo structure for this frame
  516. frame_.frameNumber_ = GetSubsystem<Time>()->GetFrameNumber();
  517. frame_.timeStep_ = timeStep;
  518. frame_.camera_ = 0;
  519. numShadowCameras_ = 0;
  520. numOcclusionBuffers_ = 0;
  521. updatedOctrees_.Clear();
  522. // Reload shaders now if needed
  523. if (shadersDirty_)
  524. LoadShaders();
  525. // Queue update of the main viewports. Use reverse order, as rendering order is also reverse
  526. // to render auxiliary views before dependant main views
  527. for (unsigned i = viewports_.Size() - 1; i < viewports_.Size(); --i)
  528. QueueViewport(0, viewports_[i]);
  529. // Gather other render surfaces that are autoupdated
  530. SendEvent(E_RENDERSURFACEUPDATE);
  531. // Process gathered views. This may queue further views (render surfaces that are only updated when visible)
  532. for (unsigned i = 0; i < queuedViews_.Size(); ++i)
  533. {
  534. WeakPtr<RenderSurface>& renderTarget = queuedViews_[i].first_;
  535. WeakPtr<Viewport>& viewport = queuedViews_[i].second_;
  536. // Null pointer means backbuffer view. Differentiate between that and an expired rendersurface
  537. if ((renderTarget.NotNull() && renderTarget.Expired()) || viewport.Expired())
  538. continue;
  539. // Allocate new view if necessary
  540. if (numViews_ == views_.Size())
  541. views_.Push(SharedPtr<View>(new View(context_)));
  542. // Check if view can be defined successfully (has valid scene, camera and octree)
  543. assert(numViews_ < views_.Size());
  544. View* view = views_[numViews_];
  545. if (!view->Define(renderTarget, viewport))
  546. continue;
  547. ++numViews_;
  548. const IntRect& viewRect = viewport->GetRect();
  549. Scene* scene = viewport->GetScene();
  550. Octree* octree = scene->GetComponent<Octree>();
  551. // Update octree (perform early update for drawables which need that, and reinsert moved drawables.)
  552. // However, if the same scene is viewed from multiple cameras, update the octree only once
  553. if (!updatedOctrees_.Contains(octree))
  554. {
  555. frame_.camera_ = viewport->GetCamera();
  556. frame_.viewSize_ = viewRect.Size();
  557. if (frame_.viewSize_ == IntVector2::ZERO)
  558. frame_.viewSize_ = IntVector2(graphics_->GetWidth(), graphics_->GetHeight());
  559. octree->Update(frame_);
  560. updatedOctrees_.Insert(octree);
  561. // Set also the view for the debug renderer already here, so that it can use culling
  562. /// \todo May result in incorrect debug geometry culling if the same scene is drawn from multiple viewports
  563. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  564. if (debug)
  565. debug->SetView(viewport->GetCamera());
  566. }
  567. // Update view. This may queue further views
  568. using namespace BeginViewUpdate;
  569. VariantMap& eventData = GetEventDataMap();
  570. eventData[P_SURFACE] = (void*)renderTarget.Get();
  571. eventData[P_TEXTURE] = (void*)(renderTarget ? renderTarget->GetParentTexture() : 0);
  572. eventData[P_SCENE] = (void*)scene;
  573. eventData[P_CAMERA] = (void*)viewport->GetCamera();
  574. SendEvent(E_BEGINVIEWUPDATE, eventData);
  575. ResetShadowMapAllocations(); // Each view can reuse the same shadow maps
  576. view->Update(frame_);
  577. SendEvent(E_ENDVIEWUPDATE, eventData);
  578. }
  579. // Reset update flag from queued render surfaces. At this point no new views can be added on this frame
  580. for (unsigned i = 0; i < queuedViews_.Size(); ++i)
  581. {
  582. WeakPtr<RenderSurface>& renderTarget = queuedViews_[i].first_;
  583. if (renderTarget)
  584. renderTarget->WasUpdated();
  585. }
  586. queuedViews_.Clear();
  587. }
  588. void Renderer::Render()
  589. {
  590. // Engine does not render when window is closed or device is lost
  591. assert(graphics_ && graphics_->IsInitialized() && !graphics_->IsDeviceLost());
  592. PROFILE(RenderViews);
  593. // If the indirection textures have lost content (OpenGL mode only), restore them now
  594. if (faceSelectCubeMap_ && faceSelectCubeMap_->IsDataLost())
  595. SetIndirectionTextureData();
  596. graphics_->SetDefaultTextureFilterMode(textureFilterMode_);
  597. graphics_->SetTextureAnisotropy(textureAnisotropy_);
  598. graphics_->ClearParameterSources();
  599. // If no views, just clear the screen
  600. if (!numViews_)
  601. {
  602. graphics_->SetBlendMode(BLEND_REPLACE);
  603. graphics_->SetColorWrite(true);
  604. graphics_->SetDepthWrite(true);
  605. graphics_->SetScissorTest(false);
  606. graphics_->SetStencilTest(false);
  607. graphics_->ResetRenderTargets();
  608. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH | CLEAR_STENCIL, defaultZone_->GetFogColor());
  609. numPrimitives_ = 0;
  610. numBatches_ = 0;
  611. }
  612. else
  613. {
  614. // Render views from last to first (each main view is rendered after the auxiliary views it depends on)
  615. for (unsigned i = numViews_ - 1; i < numViews_; --i)
  616. {
  617. using namespace BeginViewRender;
  618. RenderSurface* renderTarget = views_[i]->GetRenderTarget();
  619. VariantMap& eventData = GetEventDataMap();
  620. eventData[P_SURFACE] = (void*)renderTarget;
  621. eventData[P_TEXTURE] = (void*)(renderTarget ? renderTarget->GetParentTexture() : 0);
  622. eventData[P_SCENE] = (void*)views_[i]->GetScene();
  623. eventData[P_CAMERA] = (void*)views_[i]->GetCamera();
  624. SendEvent(E_BEGINVIEWRENDER, eventData);
  625. // Screen buffers can be reused between views, as each is rendered completely
  626. PrepareViewRender();
  627. views_[i]->Render();
  628. SendEvent(E_ENDVIEWRENDER, eventData);
  629. }
  630. // Copy the number of batches & primitives from Graphics so that we can account for 3D geometry only
  631. numPrimitives_ = graphics_->GetNumPrimitives();
  632. numBatches_ = graphics_->GetNumBatches();
  633. }
  634. // Remove unused occlusion buffers and renderbuffers
  635. RemoveUnusedBuffers();
  636. }
  637. void Renderer::DrawDebugGeometry(bool depthTest)
  638. {
  639. PROFILE(RendererDrawDebug);
  640. /// \todo Because debug geometry is per-scene, if two cameras show views of the same area, occlusion is not shown correctly
  641. HashSet<Drawable*> processedGeometries;
  642. HashSet<Light*> processedLights;
  643. for (unsigned i = 0; i < numViews_; ++i)
  644. {
  645. // Make sure it's a main view, and process each node only once
  646. View* view = views_[i];
  647. if (view->GetRenderTarget())
  648. continue;
  649. Octree* octree = view->GetOctree();
  650. if (!octree)
  651. continue;
  652. DebugRenderer* debug = octree->GetComponent<DebugRenderer>();
  653. if (!debug)
  654. continue;
  655. const PODVector<Drawable*>& geometries = view->GetGeometries();
  656. const PODVector<Light*>& lights = view->GetLights();
  657. for (unsigned i = 0; i < geometries.Size(); ++i)
  658. {
  659. if (!processedGeometries.Contains(geometries[i]))
  660. {
  661. geometries[i]->DrawDebugGeometry(debug, depthTest);
  662. processedGeometries.Insert(geometries[i]);
  663. }
  664. }
  665. for (unsigned i = 0; i < lights.Size(); ++i)
  666. {
  667. if (!processedLights.Contains(lights[i]))
  668. {
  669. lights[i]->DrawDebugGeometry(debug, depthTest);
  670. processedLights.Insert(lights[i]);
  671. }
  672. }
  673. }
  674. }
  675. void Renderer::QueueRenderSurface(RenderSurface* renderTarget)
  676. {
  677. if (renderTarget)
  678. {
  679. unsigned numViewports = renderTarget->GetNumViewports();
  680. for (unsigned i = 0; i < numViewports; ++i)
  681. QueueViewport(renderTarget, renderTarget->GetViewport(i));
  682. }
  683. }
  684. void Renderer::QueueViewport(RenderSurface* renderTarget, Viewport* viewport)
  685. {
  686. if (viewport)
  687. {
  688. queuedViews_.Push(Pair<WeakPtr<RenderSurface>, WeakPtr<Viewport> >(WeakPtr<RenderSurface>(renderTarget),
  689. WeakPtr<Viewport>(viewport)));
  690. }
  691. }
  692. Geometry* Renderer::GetLightGeometry(Light* light)
  693. {
  694. switch (light->GetLightType())
  695. {
  696. case LIGHT_DIRECTIONAL:
  697. return dirLightGeometry_;
  698. case LIGHT_SPOT:
  699. return spotLightGeometry_;
  700. case LIGHT_POINT:
  701. return pointLightGeometry_;
  702. }
  703. return 0;
  704. }
  705. Texture2D* Renderer::GetShadowMap(Light* light, Camera* camera, unsigned viewWidth, unsigned viewHeight)
  706. {
  707. LightType type = light->GetLightType();
  708. const FocusParameters& parameters = light->GetShadowFocus();
  709. float size = (float)shadowMapSize_ * light->GetShadowResolution();
  710. // Automatically reduce shadow map size when far away
  711. if (parameters.autoSize_ && type != LIGHT_DIRECTIONAL)
  712. {
  713. const Matrix3x4& view = camera->GetView();
  714. const Matrix4& projection = camera->GetProjection();
  715. BoundingBox lightBox;
  716. float lightPixels;
  717. if (type == LIGHT_POINT)
  718. {
  719. // Calculate point light pixel size from the projection of its diagonal
  720. Vector3 center = view * light->GetNode()->GetWorldPosition();
  721. float extent = 0.58f * light->GetRange();
  722. lightBox.Define(center + Vector3(extent, extent, extent), center - Vector3(extent, extent, extent));
  723. }
  724. else
  725. {
  726. // Calculate spot light pixel size from the projection of its frustum far vertices
  727. Frustum lightFrustum = light->GetFrustum().Transformed(view);
  728. lightBox.Define(&lightFrustum.vertices_[4], 4);
  729. }
  730. Vector2 projectionSize = lightBox.Projected(projection).Size();
  731. lightPixels = Max(0.5f * (float)viewWidth * projectionSize.x_, 0.5f * (float)viewHeight * projectionSize.y_);
  732. // Clamp pixel amount to a sufficient minimum to avoid self-shadowing artifacts due to loss of precision
  733. if (lightPixels < SHADOW_MIN_PIXELS)
  734. lightPixels = SHADOW_MIN_PIXELS;
  735. size = Min(size, lightPixels);
  736. }
  737. /// \todo Allow to specify maximum shadow maps per resolution, as smaller shadow maps take less memory
  738. int width = NextPowerOfTwo((unsigned)size);
  739. int height = width;
  740. // Adjust the size for directional or point light shadow map atlases
  741. if (type == LIGHT_DIRECTIONAL)
  742. {
  743. if (maxShadowCascades_ > 1)
  744. width *= 2;
  745. if (maxShadowCascades_ > 2)
  746. height *= 2;
  747. }
  748. else if (type == LIGHT_POINT)
  749. {
  750. width *= 2;
  751. height *= 3;
  752. }
  753. int searchKey = (width << 16) | height;
  754. if (shadowMaps_.Contains(searchKey))
  755. {
  756. // If shadow maps are reused, always return the first
  757. if (reuseShadowMaps_)
  758. return shadowMaps_[searchKey][0];
  759. else
  760. {
  761. // If not reused, check allocation count and return existing shadow map if possible
  762. unsigned allocated = shadowMapAllocations_[searchKey].Size();
  763. if (allocated < shadowMaps_[searchKey].Size())
  764. {
  765. shadowMapAllocations_[searchKey].Push(light);
  766. return shadowMaps_[searchKey][allocated];
  767. }
  768. else if ((int)allocated >= maxShadowMaps_)
  769. return 0;
  770. }
  771. }
  772. unsigned shadowMapFormat = (shadowQuality_ & SHADOWQUALITY_LOW_24BIT) ? graphics_->GetHiresShadowMapFormat() :
  773. graphics_->GetShadowMapFormat();
  774. if (!shadowMapFormat)
  775. return 0;
  776. SharedPtr<Texture2D> newShadowMap(new Texture2D(context_));
  777. int retries = 3;
  778. // OpenGL: create shadow map only. Color rendertarget is not needed
  779. #ifdef USE_OPENGL
  780. while (retries)
  781. {
  782. if (!newShadowMap->SetSize(width, height, shadowMapFormat, TEXTURE_DEPTHSTENCIL))
  783. {
  784. width >>= 1;
  785. height >>= 1;
  786. --retries;
  787. }
  788. else
  789. {
  790. #ifndef GL_ES_VERSION_2_0
  791. newShadowMap->SetFilterMode(FILTER_BILINEAR);
  792. newShadowMap->SetShadowCompare(true);
  793. #endif
  794. break;
  795. }
  796. }
  797. #else
  798. // Direct3D9: create shadow map and dummy color rendertarget
  799. unsigned dummyColorFormat = graphics_->GetDummyColorFormat();
  800. while (retries)
  801. {
  802. if (!newShadowMap->SetSize(width, height, shadowMapFormat, TEXTURE_DEPTHSTENCIL))
  803. {
  804. width >>= 1;
  805. height >>= 1;
  806. --retries;
  807. }
  808. else
  809. {
  810. newShadowMap->SetFilterMode(FILTER_BILINEAR);
  811. // If no dummy color rendertarget for this size exists yet, create one now
  812. if (!colorShadowMaps_.Contains(searchKey))
  813. {
  814. colorShadowMaps_[searchKey] = new Texture2D(context_);
  815. colorShadowMaps_[searchKey]->SetSize(width, height, dummyColorFormat, TEXTURE_RENDERTARGET);
  816. }
  817. // Link the color rendertarget to the shadow map
  818. newShadowMap->GetRenderSurface()->SetLinkedRenderTarget(colorShadowMaps_[searchKey]->GetRenderSurface());
  819. break;
  820. }
  821. }
  822. #endif
  823. // If failed to set size, store a null pointer so that we will not retry
  824. if (!retries)
  825. newShadowMap.Reset();
  826. shadowMaps_[searchKey].Push(newShadowMap);
  827. if (!reuseShadowMaps_)
  828. shadowMapAllocations_[searchKey].Push(light);
  829. return newShadowMap;
  830. }
  831. Texture2D* Renderer::GetScreenBuffer(int width, int height, unsigned format, bool filtered, bool srgb, unsigned persistentKey)
  832. {
  833. bool depthStencil = (format == Graphics::GetDepthStencilFormat());
  834. if (depthStencil)
  835. {
  836. filtered = false;
  837. srgb = false;
  838. }
  839. long long searchKey = ((long long)format << 32) | (width << 16) | height;
  840. if (filtered)
  841. searchKey |= 0x8000000000000000LL;
  842. if (srgb)
  843. searchKey |= 0x4000000000000000LL;
  844. // Add persistent key if defined
  845. if (persistentKey)
  846. searchKey += ((long long)persistentKey << 32);
  847. // If new size or format, initialize the allocation stats
  848. if (screenBuffers_.Find(searchKey) == screenBuffers_.End())
  849. screenBufferAllocations_[searchKey] = 0;
  850. // Reuse depth-stencil buffers whenever the size matches, instead of allocating new
  851. unsigned allocations = screenBufferAllocations_[searchKey];
  852. if(!depthStencil)
  853. ++screenBufferAllocations_[searchKey];
  854. if (allocations >= screenBuffers_[searchKey].Size())
  855. {
  856. SharedPtr<Texture2D> newBuffer(new Texture2D(context_));
  857. newBuffer->SetSRGB(srgb);
  858. newBuffer->SetSize(width, height, format, depthStencil ? TEXTURE_DEPTHSTENCIL : TEXTURE_RENDERTARGET);
  859. newBuffer->SetFilterMode(filtered ? FILTER_BILINEAR : FILTER_NEAREST);
  860. newBuffer->ResetUseTimer();
  861. screenBuffers_[searchKey].Push(newBuffer);
  862. #ifdef USE_OPENGL
  863. // OpenGL hack: clear persistent floating point screen buffers to ensure the initial contents aren't illegal (NaN)?
  864. // Otherwise eg. the AutoExposure post process will not work correctly
  865. if (persistentKey && Texture::GetDataType(format) == GL_FLOAT)
  866. {
  867. // Note: this loses current rendertarget assignment
  868. graphics_->ResetRenderTargets();
  869. graphics_->SetRenderTarget(0, newBuffer);
  870. graphics_->SetDepthStencil((RenderSurface*)0);
  871. graphics_->SetViewport(IntRect(0, 0, width, height));
  872. graphics_->Clear(CLEAR_COLOR);
  873. }
  874. #endif
  875. LOGDEBUG("Allocated new screen buffer size " + String(width) + "x" + String(height) + " format " + String(format));
  876. return newBuffer;
  877. }
  878. else
  879. {
  880. Texture2D* buffer = screenBuffers_[searchKey][allocations];
  881. buffer->ResetUseTimer();
  882. return buffer;
  883. }
  884. }
  885. RenderSurface* Renderer::GetDepthStencil(int width, int height)
  886. {
  887. // Return the default depth-stencil surface if applicable
  888. // (when using OpenGL Graphics will allocate right size surfaces on demand to emulate Direct3D9)
  889. if (width == graphics_->GetWidth() && height == graphics_->GetHeight() && graphics_->GetMultiSample() <= 1)
  890. return 0;
  891. else
  892. return GetScreenBuffer(width, height, Graphics::GetDepthStencilFormat(), false, false)->GetRenderSurface();
  893. }
  894. OcclusionBuffer* Renderer::GetOcclusionBuffer(Camera* camera)
  895. {
  896. assert(numOcclusionBuffers_ <= occlusionBuffers_.Size());
  897. if (numOcclusionBuffers_ == occlusionBuffers_.Size())
  898. {
  899. SharedPtr<OcclusionBuffer> newBuffer(new OcclusionBuffer(context_));
  900. occlusionBuffers_.Push(newBuffer);
  901. }
  902. int width = occlusionBufferSize_;
  903. int height = (int)((float)occlusionBufferSize_ / camera->GetAspectRatio() + 0.5f);
  904. OcclusionBuffer* buffer = occlusionBuffers_[numOcclusionBuffers_++];
  905. buffer->SetSize(width, height);
  906. buffer->SetView(camera);
  907. buffer->ResetUseTimer();
  908. return buffer;
  909. }
  910. Camera* Renderer::GetShadowCamera()
  911. {
  912. MutexLock lock(rendererMutex_);
  913. assert(numShadowCameras_ <= shadowCameraNodes_.Size());
  914. if (numShadowCameras_ == shadowCameraNodes_.Size())
  915. {
  916. SharedPtr<Node> newNode(new Node(context_));
  917. newNode->CreateComponent<Camera>();
  918. shadowCameraNodes_.Push(newNode);
  919. }
  920. Camera* camera = shadowCameraNodes_[numShadowCameras_++]->GetComponent<Camera>();
  921. camera->SetOrthographic(false);
  922. camera->SetZoom(1.0f);
  923. return camera;
  924. }
  925. void Renderer::SetBatchShaders(Batch& batch, Technique* tech, bool allowShadows)
  926. {
  927. // Check if shaders are unloaded or need reloading
  928. Pass* pass = batch.pass_;
  929. Vector<SharedPtr<ShaderVariation> >& vertexShaders = pass->GetVertexShaders();
  930. Vector<SharedPtr<ShaderVariation> >& pixelShaders = pass->GetPixelShaders();
  931. if (!vertexShaders.Size() || !pixelShaders.Size() || pass->GetShadersLoadedFrameNumber() !=
  932. shadersChangedFrameNumber_)
  933. {
  934. // First release all previous shaders, then load
  935. pass->ReleaseShaders();
  936. LoadPassShaders(tech, pass->GetType());
  937. }
  938. // Make sure shaders are loaded now
  939. if (vertexShaders.Size() && pixelShaders.Size())
  940. {
  941. bool heightFog = graphics_->GetSM3Support() && batch.zone_ && batch.zone_->GetHeightFog();
  942. // If instancing is not supported, but was requested, or the object is too large to be instanced,
  943. // choose static geometry vertex shader instead
  944. if (batch.geometryType_ == GEOM_INSTANCED && (!GetDynamicInstancing() || batch.geometry_->GetIndexCount() >
  945. (unsigned)maxInstanceTriangles_ * 3))
  946. batch.geometryType_ = GEOM_STATIC;
  947. if (batch.geometryType_ == GEOM_STATIC_NOINSTANCING)
  948. batch.geometryType_ = GEOM_STATIC;
  949. // Check whether is a pixel lit forward pass. If not, there is only one pixel shader
  950. if (pass->GetLightingMode() == LIGHTING_PERPIXEL)
  951. {
  952. LightBatchQueue* lightQueue = batch.lightQueue_;
  953. if (!lightQueue)
  954. {
  955. // Do not log error, as it would result in a lot of spam
  956. batch.vertexShader_ = 0;
  957. batch.pixelShader_ = 0;
  958. return;
  959. }
  960. Light* light = lightQueue->light_;
  961. unsigned vsi = 0;
  962. unsigned psi = 0;
  963. vsi = batch.geometryType_ * MAX_LIGHT_VS_VARIATIONS;
  964. bool materialHasSpecular = batch.material_ ? batch.material_->GetSpecular() : true;
  965. if (specularLighting_ && light->GetSpecularIntensity() > 0.0f && materialHasSpecular)
  966. {
  967. vsi += LVS_SPEC;
  968. psi += LPS_SPEC;
  969. }
  970. if (allowShadows && lightQueue->shadowMap_)
  971. {
  972. vsi += LVS_SHADOW;
  973. psi += LPS_SHADOW;
  974. }
  975. switch (light->GetLightType())
  976. {
  977. case LIGHT_DIRECTIONAL:
  978. vsi += LVS_DIR;
  979. break;
  980. case LIGHT_SPOT:
  981. psi += LPS_SPOT;
  982. vsi += LVS_SPOT;
  983. break;
  984. case LIGHT_POINT:
  985. if (light->GetShapeTexture())
  986. psi += LPS_POINTMASK;
  987. else
  988. psi += LPS_POINT;
  989. vsi += LVS_POINT;
  990. break;
  991. }
  992. if (heightFog)
  993. {
  994. vsi += MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS;
  995. psi += MAX_LIGHT_PS_VARIATIONS;
  996. }
  997. batch.vertexShader_ = vertexShaders[vsi];
  998. batch.pixelShader_ = pixelShaders[psi];
  999. }
  1000. else
  1001. {
  1002. // Check if pass has vertex lighting support
  1003. if (pass->GetLightingMode() == LIGHTING_PERVERTEX)
  1004. {
  1005. unsigned numVertexLights = 0;
  1006. if (batch.lightQueue_)
  1007. numVertexLights = batch.lightQueue_->vertexLights_.Size();
  1008. unsigned vsi = batch.geometryType_ * MAX_VERTEXLIGHT_VS_VARIATIONS + numVertexLights;
  1009. if (heightFog)
  1010. vsi += MAX_GEOMETRYTYPES * MAX_VERTEXLIGHT_VS_VARIATIONS;
  1011. batch.vertexShader_ = vertexShaders[vsi];
  1012. }
  1013. else
  1014. {
  1015. unsigned vsi = batch.geometryType_;
  1016. if (heightFog)
  1017. vsi += MAX_GEOMETRYTYPES;
  1018. batch.vertexShader_ = vertexShaders[vsi];
  1019. }
  1020. batch.pixelShader_ = pixelShaders[heightFog ? 1 : 0];
  1021. }
  1022. }
  1023. // Log error if shaders could not be assigned, but only once per technique
  1024. if (!batch.vertexShader_ || !batch.pixelShader_)
  1025. {
  1026. if (!shaderErrorDisplayed_.Contains(tech))
  1027. {
  1028. shaderErrorDisplayed_.Insert(tech);
  1029. LOGERROR("Technique " + tech->GetName() + " has missing shaders");
  1030. }
  1031. }
  1032. }
  1033. void Renderer::SetLightVolumeBatchShaders(Batch& batch, const String& vsName, const String& psName)
  1034. {
  1035. assert(deferredLightPSVariations_.Size());
  1036. unsigned vsi = DLVS_NONE;
  1037. unsigned psi = DLPS_NONE;
  1038. Light* light = batch.lightQueue_->light_;
  1039. switch (light->GetLightType())
  1040. {
  1041. case LIGHT_DIRECTIONAL:
  1042. vsi += DLVS_DIR;
  1043. break;
  1044. case LIGHT_SPOT:
  1045. psi += DLPS_SPOT;
  1046. break;
  1047. case LIGHT_POINT:
  1048. if (light->GetShapeTexture())
  1049. psi += DLPS_POINTMASK;
  1050. else
  1051. psi += DLPS_POINT;
  1052. break;
  1053. }
  1054. if (batch.lightQueue_->shadowMap_)
  1055. psi += DLPS_SHADOW;
  1056. if (specularLighting_ && light->GetSpecularIntensity() > 0.0f)
  1057. psi += DLPS_SPEC;
  1058. if (batch.camera_->IsOrthographic())
  1059. {
  1060. vsi += DLVS_ORTHO;
  1061. psi += DLPS_ORTHO;
  1062. }
  1063. batch.vertexShader_ = GetShader(VS, vsName, deferredLightVSVariations[vsi]);
  1064. batch.pixelShader_ = GetShader(PS, psName, deferredLightPSVariations_[psi]);
  1065. }
  1066. void Renderer::SetCullMode(CullMode mode, Camera* camera)
  1067. {
  1068. // If a camera is specified, check whether it reverses culling due to vertical flipping or reflection
  1069. if (camera && camera->GetReverseCulling())
  1070. {
  1071. if (mode == CULL_CW)
  1072. mode = CULL_CCW;
  1073. else if (mode == CULL_CCW)
  1074. mode = CULL_CW;
  1075. }
  1076. graphics_->SetCullMode(mode);
  1077. }
  1078. bool Renderer::ResizeInstancingBuffer(unsigned numInstances)
  1079. {
  1080. if (!instancingBuffer_ || !dynamicInstancing_)
  1081. return false;
  1082. unsigned oldSize = instancingBuffer_->GetVertexCount();
  1083. if (numInstances <= oldSize)
  1084. return true;
  1085. unsigned newSize = INSTANCING_BUFFER_DEFAULT_SIZE;
  1086. while (newSize < numInstances)
  1087. newSize <<= 1;
  1088. if (!instancingBuffer_->SetSize(newSize, INSTANCING_BUFFER_MASK, true))
  1089. {
  1090. LOGERROR("Failed to resize instancing buffer to " + String(newSize));
  1091. // If failed, try to restore the old size
  1092. instancingBuffer_->SetSize(oldSize, INSTANCING_BUFFER_MASK, true);
  1093. return false;
  1094. }
  1095. LOGDEBUG("Resized instancing buffer to " + String(newSize));
  1096. return true;
  1097. }
  1098. void Renderer::SaveScreenBufferAllocations()
  1099. {
  1100. savedScreenBufferAllocations_ = screenBufferAllocations_;
  1101. }
  1102. void Renderer::RestoreScreenBufferAllocations()
  1103. {
  1104. screenBufferAllocations_ = savedScreenBufferAllocations_;
  1105. }
  1106. void Renderer::OptimizeLightByScissor(Light* light, Camera* camera)
  1107. {
  1108. if (light && light->GetLightType() != LIGHT_DIRECTIONAL)
  1109. graphics_->SetScissorTest(true, GetLightScissor(light, camera));
  1110. else
  1111. graphics_->SetScissorTest(false);
  1112. }
  1113. void Renderer::OptimizeLightByStencil(Light* light, Camera* camera)
  1114. {
  1115. #ifndef GL_ES_VERSION_2_0
  1116. if (light)
  1117. {
  1118. LightType type = light->GetLightType();
  1119. if (type == LIGHT_DIRECTIONAL)
  1120. {
  1121. graphics_->SetStencilTest(false);
  1122. return;
  1123. }
  1124. Geometry* geometry = GetLightGeometry(light);
  1125. const Matrix3x4& view = camera->GetView();
  1126. const Matrix4& projection = camera->GetProjection();
  1127. Vector3 cameraPos = camera->GetNode()->GetWorldPosition();
  1128. float lightDist;
  1129. if (type == LIGHT_POINT)
  1130. lightDist = Sphere(light->GetNode()->GetWorldPosition(), light->GetRange() * 1.25f).Distance(cameraPos);
  1131. else
  1132. lightDist = light->GetFrustum().Distance(cameraPos);
  1133. // If the camera is actually inside the light volume, do not draw to stencil as it would waste fillrate
  1134. if (lightDist < M_EPSILON)
  1135. {
  1136. graphics_->SetStencilTest(false);
  1137. return;
  1138. }
  1139. // If the stencil value has wrapped, clear the whole stencil first
  1140. if (!lightStencilValue_)
  1141. {
  1142. graphics_->Clear(CLEAR_STENCIL);
  1143. lightStencilValue_ = 1;
  1144. }
  1145. // If possible, render the stencil volume front faces. However, close to the near clip plane render back faces instead
  1146. // to avoid clipping.
  1147. if (lightDist < camera->GetNearClip() * 2.0f)
  1148. {
  1149. SetCullMode(CULL_CW, camera);
  1150. graphics_->SetDepthTest(CMP_GREATER);
  1151. }
  1152. else
  1153. {
  1154. SetCullMode(CULL_CCW, camera);
  1155. graphics_->SetDepthTest(CMP_LESSEQUAL);
  1156. }
  1157. graphics_->SetColorWrite(false);
  1158. graphics_->SetDepthWrite(false);
  1159. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, lightStencilValue_);
  1160. graphics_->SetShaders(GetShader(VS, "Stencil"), GetShader(PS, "Stencil"));
  1161. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection * view);
  1162. graphics_->SetShaderParameter(VSP_MODEL, light->GetVolumeTransform(camera));
  1163. geometry->Draw(graphics_);
  1164. graphics_->ClearTransformSources();
  1165. graphics_->SetColorWrite(true);
  1166. graphics_->SetStencilTest(true, CMP_EQUAL, OP_KEEP, OP_KEEP, OP_KEEP, lightStencilValue_);
  1167. // Increase stencil value for next light
  1168. ++lightStencilValue_;
  1169. }
  1170. else
  1171. graphics_->SetStencilTest(false);
  1172. #endif
  1173. }
  1174. const Rect& Renderer::GetLightScissor(Light* light, Camera* camera)
  1175. {
  1176. Pair<Light*, Camera*> combination(light, camera);
  1177. HashMap<Pair<Light*, Camera*>, Rect>::Iterator i = lightScissorCache_.Find(combination);
  1178. if (i != lightScissorCache_.End())
  1179. return i->second_;
  1180. const Matrix3x4& view = camera->GetView();
  1181. const Matrix4& projection = camera->GetProjection();
  1182. assert(light->GetLightType() != LIGHT_DIRECTIONAL);
  1183. if (light->GetLightType() == LIGHT_SPOT)
  1184. {
  1185. Frustum viewFrustum(light->GetFrustum().Transformed(view));
  1186. return lightScissorCache_[combination] = viewFrustum.Projected(projection);
  1187. }
  1188. else // LIGHT_POINT
  1189. {
  1190. BoundingBox viewBox(light->GetWorldBoundingBox().Transformed(view));
  1191. return lightScissorCache_[combination] = viewBox.Projected(projection);
  1192. }
  1193. }
  1194. void Renderer::PrepareViewRender()
  1195. {
  1196. ResetScreenBufferAllocations();
  1197. lightScissorCache_.Clear();
  1198. lightStencilValue_ = 1;
  1199. }
  1200. void Renderer::RemoveUnusedBuffers()
  1201. {
  1202. for (unsigned i = occlusionBuffers_.Size() - 1; i < occlusionBuffers_.Size(); --i)
  1203. {
  1204. if (occlusionBuffers_[i]->GetUseTimer() > MAX_BUFFER_AGE)
  1205. {
  1206. LOGDEBUG("Removed unused occlusion buffer");
  1207. occlusionBuffers_.Erase(i);
  1208. }
  1209. }
  1210. for (HashMap<long long, Vector<SharedPtr<Texture2D> > >::Iterator i = screenBuffers_.Begin(); i != screenBuffers_.End();)
  1211. {
  1212. HashMap<long long, Vector<SharedPtr<Texture2D> > >::Iterator current = i++;
  1213. Vector<SharedPtr<Texture2D> >& buffers = current->second_;
  1214. for (unsigned j = buffers.Size() - 1; j < buffers.Size(); --j)
  1215. {
  1216. Texture2D* buffer = buffers[j];
  1217. if (buffer->GetUseTimer() > MAX_BUFFER_AGE)
  1218. {
  1219. LOGDEBUG("Removed unused screen buffer size " + String(buffer->GetWidth()) + "x" + String(buffer->GetHeight()) + " format " + String(buffer->GetFormat()));
  1220. buffers.Erase(j);
  1221. }
  1222. }
  1223. if (buffers.Empty())
  1224. {
  1225. screenBufferAllocations_.Erase(current->first_);
  1226. screenBuffers_.Erase(current);
  1227. }
  1228. }
  1229. }
  1230. void Renderer::ResetShadowMapAllocations()
  1231. {
  1232. for (HashMap<int, PODVector<Light*> >::Iterator i = shadowMapAllocations_.Begin(); i != shadowMapAllocations_.End(); ++i)
  1233. i->second_.Clear();
  1234. }
  1235. void Renderer::ResetScreenBufferAllocations()
  1236. {
  1237. for (HashMap<long long, unsigned>::Iterator i = screenBufferAllocations_.Begin(); i != screenBufferAllocations_.End(); ++i)
  1238. i->second_ = 0;
  1239. }
  1240. void Renderer::Initialize()
  1241. {
  1242. Graphics* graphics = GetSubsystem<Graphics>();
  1243. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1244. if (!graphics || !graphics->IsInitialized() || !cache)
  1245. return;
  1246. PROFILE(InitRenderer);
  1247. graphics_ = graphics;
  1248. if (!graphics_->GetShadowMapFormat())
  1249. drawShadows_ = false;
  1250. defaultLightRamp_ = cache->GetResource<Texture2D>("Textures/Ramp.png");
  1251. defaultLightSpot_ = cache->GetResource<Texture2D>("Textures/Spot.png");
  1252. defaultMaterial_ = cache->GetResource<Material>("Materials/Default.xml");
  1253. // If default material not found, create one. This will actually not render properly, but prevents crashing
  1254. if (!defaultMaterial_)
  1255. defaultMaterial_ = new Material(context_);
  1256. defaultRenderPath_ = new RenderPath();
  1257. defaultRenderPath_->Load(cache->GetResource<XMLFile>("RenderPaths/Forward.xml"));
  1258. CreateGeometries();
  1259. CreateInstancingBuffer();
  1260. viewports_.Resize(1);
  1261. ResetViews();
  1262. ResetShadowMaps();
  1263. ResetBuffers();
  1264. shadersDirty_ = true;
  1265. initialized_ = true;
  1266. SubscribeToEvent(E_RENDERUPDATE, HANDLER(Renderer, HandleRenderUpdate));
  1267. LOGINFO("Initialized renderer");
  1268. }
  1269. void Renderer::ResetViews()
  1270. {
  1271. views_.Clear();
  1272. numViews_ = 0;
  1273. }
  1274. void Renderer::LoadShaders()
  1275. {
  1276. LOGDEBUG("Reloading shaders");
  1277. // Release old material shaders, mark them for reload
  1278. ReleaseMaterialShaders();
  1279. shadersChangedFrameNumber_ = GetSubsystem<Time>()->GetFrameNumber();
  1280. // Construct new names for deferred light volume pixel shaders based on rendering options
  1281. deferredLightPSVariations_.Resize(MAX_DEFERRED_LIGHT_PS_VARIATIONS);
  1282. unsigned shadows = (graphics_->GetHardwareShadowSupport() ? 1 : 0) | (shadowQuality_ & SHADOWQUALITY_HIGH_16BIT);
  1283. for (unsigned i = 0; i < MAX_DEFERRED_LIGHT_PS_VARIATIONS; ++i)
  1284. {
  1285. deferredLightPSVariations_[i] = lightPSVariations[i % DLPS_ORTHO];
  1286. if (i & DLPS_SHADOW)
  1287. deferredLightPSVariations_[i] += shadowVariations[shadows];
  1288. if (i & DLPS_ORTHO)
  1289. deferredLightPSVariations_[i] += "ORTHO";
  1290. }
  1291. shadersDirty_ = false;
  1292. }
  1293. void Renderer::LoadPassShaders(Technique* tech, StringHash type)
  1294. {
  1295. Pass* pass = tech->GetPass(type);
  1296. if (!pass)
  1297. return;
  1298. PROFILE(LoadPassShaders);
  1299. unsigned shadows = (graphics_->GetHardwareShadowSupport() ? 1 : 0) | (shadowQuality_ & SHADOWQUALITY_HIGH_16BIT);
  1300. Vector<SharedPtr<ShaderVariation> >& vertexShaders = pass->GetVertexShaders();
  1301. Vector<SharedPtr<ShaderVariation> >& pixelShaders = pass->GetPixelShaders();
  1302. // Forget all the old shaders
  1303. vertexShaders.Clear();
  1304. pixelShaders.Clear();
  1305. if (pass->GetLightingMode() == LIGHTING_PERPIXEL)
  1306. {
  1307. // Load forward pixel lit variations
  1308. vertexShaders.Resize(MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS * 2);
  1309. pixelShaders.Resize(MAX_LIGHT_PS_VARIATIONS * 2);
  1310. for (unsigned j = 0; j < MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS * 2; ++j)
  1311. {
  1312. unsigned k = j % (MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS);
  1313. unsigned h = j / (MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS);
  1314. unsigned g = k / MAX_LIGHT_VS_VARIATIONS;
  1315. unsigned l = k % MAX_LIGHT_VS_VARIATIONS;
  1316. vertexShaders[j] = GetShader(VS, pass->GetVertexShader(), pass->GetVertexShaderDefines() + " " +
  1317. lightVSVariations[l] + geometryVSVariations[g] + heightFogVariations[h]);
  1318. }
  1319. for (unsigned j = 0; j < MAX_LIGHT_PS_VARIATIONS * 2; ++j)
  1320. {
  1321. unsigned k = j % MAX_LIGHT_PS_VARIATIONS;
  1322. unsigned h = j / MAX_LIGHT_PS_VARIATIONS;
  1323. if (k & LPS_SHADOW)
  1324. {
  1325. pixelShaders[j] = GetShader(PS, pass->GetPixelShader(), pass->GetPixelShaderDefines() + " " +
  1326. lightPSVariations[k] + shadowVariations[shadows] + heightFogVariations[h]);
  1327. }
  1328. else
  1329. pixelShaders[j] = GetShader(PS, pass->GetPixelShader(), pass->GetPixelShaderDefines() + " " +
  1330. lightPSVariations[k] + heightFogVariations[h]);
  1331. }
  1332. }
  1333. else
  1334. {
  1335. // Load vertex light variations
  1336. if (pass->GetLightingMode() == LIGHTING_PERVERTEX)
  1337. {
  1338. vertexShaders.Resize(MAX_GEOMETRYTYPES * MAX_VERTEXLIGHT_VS_VARIATIONS * 2);
  1339. for (unsigned j = 0; j < MAX_GEOMETRYTYPES * MAX_VERTEXLIGHT_VS_VARIATIONS * 2; ++j)
  1340. {
  1341. unsigned k = j % (MAX_GEOMETRYTYPES * MAX_VERTEXLIGHT_VS_VARIATIONS);
  1342. unsigned h = j / (MAX_GEOMETRYTYPES * MAX_VERTEXLIGHT_VS_VARIATIONS);
  1343. unsigned g = k / MAX_VERTEXLIGHT_VS_VARIATIONS;
  1344. unsigned l = k % MAX_VERTEXLIGHT_VS_VARIATIONS;
  1345. vertexShaders[j] = GetShader(VS, pass->GetVertexShader(), pass->GetVertexShaderDefines() + " " +
  1346. vertexLightVSVariations[l] + geometryVSVariations[g] + heightFogVariations[h]);
  1347. }
  1348. }
  1349. else
  1350. {
  1351. vertexShaders.Resize(MAX_GEOMETRYTYPES * 2);
  1352. for (unsigned j = 0; j < MAX_GEOMETRYTYPES * 2; ++j)
  1353. {
  1354. unsigned k = j % MAX_GEOMETRYTYPES;
  1355. unsigned h = j / MAX_GEOMETRYTYPES;
  1356. vertexShaders[j] = GetShader(VS, pass->GetVertexShader(), pass->GetVertexShaderDefines() + " " +
  1357. geometryVSVariations[k] + heightFogVariations[h]);
  1358. }
  1359. }
  1360. pixelShaders.Resize(2);
  1361. for (unsigned j = 0; j < 2; ++j)
  1362. {
  1363. pixelShaders[j] = GetShader(PS, pass->GetPixelShader(), pass->GetPixelShaderDefines() + " " +
  1364. heightFogVariations[j]);
  1365. }
  1366. }
  1367. pass->MarkShadersLoaded(shadersChangedFrameNumber_);
  1368. }
  1369. void Renderer::ReleaseMaterialShaders()
  1370. {
  1371. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1372. PODVector<Material*> materials;
  1373. cache->GetResources<Material>(materials);
  1374. for (unsigned i = 0; i < materials.Size(); ++i)
  1375. materials[i]->ReleaseShaders();
  1376. }
  1377. void Renderer::ReloadTextures()
  1378. {
  1379. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1380. PODVector<Resource*> textures;
  1381. cache->GetResources(textures, Texture2D::GetTypeStatic());
  1382. for (unsigned i = 0; i < textures.Size(); ++i)
  1383. cache->ReloadResource(textures[i]);
  1384. cache->GetResources(textures, TextureCube::GetTypeStatic());
  1385. for (unsigned i = 0; i < textures.Size(); ++i)
  1386. cache->ReloadResource(textures[i]);
  1387. }
  1388. void Renderer::CreateGeometries()
  1389. {
  1390. SharedPtr<VertexBuffer> dlvb(new VertexBuffer(context_));
  1391. dlvb->SetShadowed(true);
  1392. dlvb->SetSize(4, MASK_POSITION);
  1393. dlvb->SetData(dirLightVertexData);
  1394. SharedPtr<IndexBuffer> dlib(new IndexBuffer(context_));
  1395. dlib->SetShadowed(true);
  1396. dlib->SetSize(6, false);
  1397. dlib->SetData(dirLightIndexData);
  1398. dirLightGeometry_ = new Geometry(context_);
  1399. dirLightGeometry_->SetVertexBuffer(0, dlvb);
  1400. dirLightGeometry_->SetIndexBuffer(dlib);
  1401. dirLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, dlib->GetIndexCount());
  1402. SharedPtr<VertexBuffer> slvb(new VertexBuffer(context_));
  1403. slvb->SetShadowed(true);
  1404. slvb->SetSize(8, MASK_POSITION);
  1405. slvb->SetData(spotLightVertexData);
  1406. SharedPtr<IndexBuffer> slib(new IndexBuffer(context_));
  1407. slib->SetShadowed(true);
  1408. slib->SetSize(36, false);
  1409. slib->SetData(spotLightIndexData);
  1410. spotLightGeometry_ = new Geometry(context_);
  1411. spotLightGeometry_->SetVertexBuffer(0, slvb);
  1412. spotLightGeometry_->SetIndexBuffer(slib);
  1413. spotLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, slib->GetIndexCount());
  1414. SharedPtr<VertexBuffer> plvb(new VertexBuffer(context_));
  1415. plvb->SetShadowed(true);
  1416. plvb->SetSize(24, MASK_POSITION);
  1417. plvb->SetData(pointLightVertexData);
  1418. SharedPtr<IndexBuffer> plib(new IndexBuffer(context_));
  1419. plib->SetShadowed(true);
  1420. plib->SetSize(132, false);
  1421. plib->SetData(pointLightIndexData);
  1422. pointLightGeometry_ = new Geometry(context_);
  1423. pointLightGeometry_->SetVertexBuffer(0, plvb);
  1424. pointLightGeometry_->SetIndexBuffer(plib);
  1425. pointLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, plib->GetIndexCount());
  1426. #if !defined(USE_OPENGL) || !defined(GL_ES_VERSION_2_0)
  1427. if (graphics_->GetShadowMapFormat())
  1428. {
  1429. faceSelectCubeMap_ = new TextureCube(context_);
  1430. faceSelectCubeMap_->SetNumLevels(1);
  1431. faceSelectCubeMap_->SetSize(1, graphics_->GetRGBAFormat());
  1432. faceSelectCubeMap_->SetFilterMode(FILTER_NEAREST);
  1433. indirectionCubeMap_ = new TextureCube(context_);
  1434. indirectionCubeMap_->SetNumLevels(1);
  1435. indirectionCubeMap_->SetSize(256, graphics_->GetRGBAFormat());
  1436. indirectionCubeMap_->SetFilterMode(FILTER_BILINEAR);
  1437. indirectionCubeMap_->SetAddressMode(COORD_U, ADDRESS_CLAMP);
  1438. indirectionCubeMap_->SetAddressMode(COORD_V, ADDRESS_CLAMP);
  1439. indirectionCubeMap_->SetAddressMode(COORD_W, ADDRESS_CLAMP);
  1440. SetIndirectionTextureData();
  1441. }
  1442. #endif
  1443. }
  1444. void Renderer::SetIndirectionTextureData()
  1445. {
  1446. unsigned char data[256 * 256 * 4];
  1447. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1448. {
  1449. unsigned axis = i / 2;
  1450. data[0] = (axis == 0) ? 255 : 0;
  1451. data[1] = (axis == 1) ? 255 : 0;
  1452. data[2] = (axis == 2) ? 255 : 0;
  1453. data[3] = 0;
  1454. faceSelectCubeMap_->SetData((CubeMapFace)i, 0, 0, 0, 1, 1, data);
  1455. }
  1456. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1457. {
  1458. unsigned char faceX = (i & 1) * 255;
  1459. unsigned char faceY = (i / 2) * 255 / 3;
  1460. unsigned char* dest = data;
  1461. for (unsigned y = 0; y < 256; ++y)
  1462. {
  1463. for (unsigned x = 0; x < 256; ++x)
  1464. {
  1465. #ifdef USE_OPENGL
  1466. dest[0] = x;
  1467. dest[1] = 255 - y;
  1468. dest[2] = faceX;
  1469. dest[3] = 255 * 2 / 3 - faceY;
  1470. #else
  1471. dest[0] = x;
  1472. dest[1] = y;
  1473. dest[2] = faceX;
  1474. dest[3] = faceY;
  1475. #endif
  1476. dest += 4;
  1477. }
  1478. }
  1479. indirectionCubeMap_->SetData((CubeMapFace)i, 0, 0, 0, 256, 256, data);
  1480. }
  1481. faceSelectCubeMap_->ClearDataLost();
  1482. indirectionCubeMap_->ClearDataLost();
  1483. }
  1484. void Renderer::CreateInstancingBuffer()
  1485. {
  1486. // Do not create buffer if instancing not supported
  1487. if (!graphics_->GetInstancingSupport())
  1488. {
  1489. instancingBuffer_.Reset();
  1490. dynamicInstancing_ = false;
  1491. return;
  1492. }
  1493. // If must lock the buffer for each batch group, set a smaller size
  1494. unsigned defaultSize = graphics_->GetStreamOffsetSupport() ? INSTANCING_BUFFER_DEFAULT_SIZE : INSTANCING_BUFFER_DEFAULT_SIZE / 4;
  1495. instancingBuffer_ = new VertexBuffer(context_);
  1496. if (!instancingBuffer_->SetSize(defaultSize, INSTANCING_BUFFER_MASK, true))
  1497. {
  1498. instancingBuffer_.Reset();
  1499. dynamicInstancing_ = false;
  1500. }
  1501. }
  1502. void Renderer::ResetShadowMaps()
  1503. {
  1504. shadowMaps_.Clear();
  1505. shadowMapAllocations_.Clear();
  1506. colorShadowMaps_.Clear();
  1507. }
  1508. void Renderer::ResetBuffers()
  1509. {
  1510. occlusionBuffers_.Clear();
  1511. screenBuffers_.Clear();
  1512. screenBufferAllocations_.Clear();
  1513. }
  1514. void Renderer::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  1515. {
  1516. if (!initialized_)
  1517. Initialize();
  1518. else
  1519. {
  1520. // When screen mode changes, purge old views
  1521. ResetViews();
  1522. }
  1523. }
  1524. void Renderer::HandleGraphicsFeatures(StringHash eventType, VariantMap& eventData)
  1525. {
  1526. // Reinitialize if already initialized
  1527. if (initialized_)
  1528. Initialize();
  1529. }
  1530. void Renderer::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  1531. {
  1532. using namespace RenderUpdate;
  1533. Update(eventData[P_TIMESTEP].GetFloat());
  1534. }
  1535. }