Renderer.cpp 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806
  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. if (!cache)
  499. return 0;
  500. String fullShaderName = shaderPath_ + name + shaderExtension_;
  501. // Try to reduce repeated error log prints because of missing shaders
  502. if (lastShaderName_ == name && !cache->Exists(fullShaderName))
  503. return 0;
  504. lastShader_ = cache->GetResource<Shader>(fullShaderName);
  505. lastShaderName_ = name;
  506. }
  507. return lastShader_ ? lastShader_->GetVariation(type, defines) : (ShaderVariation*)0;
  508. }
  509. void Renderer::Update(float timeStep)
  510. {
  511. PROFILE(UpdateViews);
  512. numViews_ = 0;
  513. // If device lost, do not perform update. This is because any dynamic vertex/index buffer updates happen already here,
  514. // and if the device is lost, the updates queue up, causing memory use to rise constantly
  515. if (!graphics_ || !graphics_->IsInitialized() || graphics_->IsDeviceLost())
  516. return;
  517. // Set up the frameinfo structure for this frame
  518. frame_.frameNumber_ = GetSubsystem<Time>()->GetFrameNumber();
  519. frame_.timeStep_ = timeStep;
  520. frame_.camera_ = 0;
  521. numShadowCameras_ = 0;
  522. numOcclusionBuffers_ = 0;
  523. updatedOctrees_.Clear();
  524. // Reload shaders now if needed
  525. if (shadersDirty_)
  526. LoadShaders();
  527. // Queue update of the main viewports. Use reverse order, as rendering order is also reverse
  528. // to render auxiliary views before dependant main views
  529. for (unsigned i = viewports_.Size() - 1; i < viewports_.Size(); --i)
  530. QueueViewport(0, viewports_[i]);
  531. // Gather other render surfaces that are autoupdated
  532. SendEvent(E_RENDERSURFACEUPDATE);
  533. // Process gathered views. This may queue further views (render surfaces that are only updated when visible)
  534. for (unsigned i = 0; i < queuedViews_.Size(); ++i)
  535. {
  536. WeakPtr<RenderSurface>& renderTarget = queuedViews_[i].first_;
  537. WeakPtr<Viewport>& viewport = queuedViews_[i].second_;
  538. // Null pointer means backbuffer view. Differentiate between that and an expired rendersurface
  539. if ((renderTarget.NotNull() && renderTarget.Expired()) || viewport.Expired())
  540. continue;
  541. // Allocate new view if necessary
  542. if (numViews_ == views_.Size())
  543. views_.Push(SharedPtr<View>(new View(context_)));
  544. // Check if view can be defined successfully (has valid scene, camera and octree)
  545. assert(numViews_ < views_.Size());
  546. View* view = views_[numViews_];
  547. if (!view->Define(renderTarget, viewport))
  548. continue;
  549. ++numViews_;
  550. const IntRect& viewRect = viewport->GetRect();
  551. Scene* scene = viewport->GetScene();
  552. Octree* octree = scene->GetComponent<Octree>();
  553. // Update octree (perform early update for drawables which need that, and reinsert moved drawables.)
  554. // However, if the same scene is viewed from multiple cameras, update the octree only once
  555. if (!updatedOctrees_.Contains(octree))
  556. {
  557. frame_.camera_ = viewport->GetCamera();
  558. frame_.viewSize_ = viewRect.Size();
  559. if (frame_.viewSize_ == IntVector2::ZERO)
  560. frame_.viewSize_ = IntVector2(graphics_->GetWidth(), graphics_->GetHeight());
  561. octree->Update(frame_);
  562. updatedOctrees_.Insert(octree);
  563. // Set also the view for the debug renderer already here, so that it can use culling
  564. /// \todo May result in incorrect debug geometry culling if the same scene is drawn from multiple viewports
  565. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  566. if (debug)
  567. debug->SetView(viewport->GetCamera());
  568. }
  569. // Update view. This may queue further views
  570. using namespace BeginViewUpdate;
  571. VariantMap& eventData = GetEventDataMap();
  572. eventData[P_SURFACE] = (void*)renderTarget.Get();
  573. eventData[P_TEXTURE] = (void*)(renderTarget ? renderTarget->GetParentTexture() : 0);
  574. eventData[P_SCENE] = (void*)scene;
  575. eventData[P_CAMERA] = (void*)viewport->GetCamera();
  576. SendEvent(E_BEGINVIEWUPDATE, eventData);
  577. ResetShadowMapAllocations(); // Each view can reuse the same shadow maps
  578. view->Update(frame_);
  579. SendEvent(E_ENDVIEWUPDATE, eventData);
  580. }
  581. // Reset update flag from queued render surfaces. At this point no new views can be added on this frame
  582. for (unsigned i = 0; i < queuedViews_.Size(); ++i)
  583. {
  584. WeakPtr<RenderSurface>& renderTarget = queuedViews_[i].first_;
  585. if (renderTarget)
  586. renderTarget->WasUpdated();
  587. }
  588. queuedViews_.Clear();
  589. }
  590. void Renderer::Render()
  591. {
  592. // Engine does not render when window is closed or device is lost
  593. assert(graphics_ && graphics_->IsInitialized() && !graphics_->IsDeviceLost());
  594. PROFILE(RenderViews);
  595. // If the indirection textures have lost content (OpenGL mode only), restore them now
  596. if (faceSelectCubeMap_ && faceSelectCubeMap_->IsDataLost())
  597. SetIndirectionTextureData();
  598. graphics_->SetDefaultTextureFilterMode(textureFilterMode_);
  599. graphics_->SetTextureAnisotropy(textureAnisotropy_);
  600. graphics_->ClearParameterSources();
  601. // If no views, just clear the screen
  602. if (!numViews_)
  603. {
  604. graphics_->SetBlendMode(BLEND_REPLACE);
  605. graphics_->SetColorWrite(true);
  606. graphics_->SetDepthWrite(true);
  607. graphics_->SetScissorTest(false);
  608. graphics_->SetStencilTest(false);
  609. graphics_->ResetRenderTargets();
  610. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH | CLEAR_STENCIL, defaultZone_->GetFogColor());
  611. numPrimitives_ = 0;
  612. numBatches_ = 0;
  613. }
  614. else
  615. {
  616. // Render views from last to first (each main view is rendered after the auxiliary views it depends on)
  617. for (unsigned i = numViews_ - 1; i < numViews_; --i)
  618. {
  619. using namespace BeginViewRender;
  620. RenderSurface* renderTarget = views_[i]->GetRenderTarget();
  621. VariantMap& eventData = GetEventDataMap();
  622. eventData[P_SURFACE] = (void*)renderTarget;
  623. eventData[P_TEXTURE] = (void*)(renderTarget ? renderTarget->GetParentTexture() : 0);
  624. eventData[P_SCENE] = (void*)views_[i]->GetScene();
  625. eventData[P_CAMERA] = (void*)views_[i]->GetCamera();
  626. SendEvent(E_BEGINVIEWRENDER, eventData);
  627. // Screen buffers can be reused between views, as each is rendered completely
  628. PrepareViewRender();
  629. views_[i]->Render();
  630. SendEvent(E_ENDVIEWRENDER, eventData);
  631. }
  632. // Copy the number of batches & primitives from Graphics so that we can account for 3D geometry only
  633. numPrimitives_ = graphics_->GetNumPrimitives();
  634. numBatches_ = graphics_->GetNumBatches();
  635. }
  636. // Remove unused occlusion buffers and renderbuffers
  637. RemoveUnusedBuffers();
  638. }
  639. void Renderer::DrawDebugGeometry(bool depthTest)
  640. {
  641. PROFILE(RendererDrawDebug);
  642. /// \todo Because debug geometry is per-scene, if two cameras show views of the same area, occlusion is not shown correctly
  643. HashSet<Drawable*> processedGeometries;
  644. HashSet<Light*> processedLights;
  645. for (unsigned i = 0; i < numViews_; ++i)
  646. {
  647. // Make sure it's a main view, and process each node only once
  648. View* view = views_[i];
  649. if (view->GetRenderTarget())
  650. continue;
  651. Octree* octree = view->GetOctree();
  652. if (!octree)
  653. continue;
  654. DebugRenderer* debug = octree->GetComponent<DebugRenderer>();
  655. if (!debug)
  656. continue;
  657. const PODVector<Drawable*>& geometries = view->GetGeometries();
  658. const PODVector<Light*>& lights = view->GetLights();
  659. for (unsigned i = 0; i < geometries.Size(); ++i)
  660. {
  661. if (!processedGeometries.Contains(geometries[i]))
  662. {
  663. geometries[i]->DrawDebugGeometry(debug, depthTest);
  664. processedGeometries.Insert(geometries[i]);
  665. }
  666. }
  667. for (unsigned i = 0; i < lights.Size(); ++i)
  668. {
  669. if (!processedLights.Contains(lights[i]))
  670. {
  671. lights[i]->DrawDebugGeometry(debug, depthTest);
  672. processedLights.Insert(lights[i]);
  673. }
  674. }
  675. }
  676. }
  677. void Renderer::QueueRenderSurface(RenderSurface* renderTarget)
  678. {
  679. if (renderTarget)
  680. {
  681. unsigned numViewports = renderTarget->GetNumViewports();
  682. for (unsigned i = 0; i < numViewports; ++i)
  683. QueueViewport(renderTarget, renderTarget->GetViewport(i));
  684. }
  685. }
  686. void Renderer::QueueViewport(RenderSurface* renderTarget, Viewport* viewport)
  687. {
  688. if (viewport)
  689. {
  690. queuedViews_.Push(Pair<WeakPtr<RenderSurface>, WeakPtr<Viewport> >(WeakPtr<RenderSurface>(renderTarget),
  691. WeakPtr<Viewport>(viewport)));
  692. }
  693. }
  694. Geometry* Renderer::GetLightGeometry(Light* light)
  695. {
  696. switch (light->GetLightType())
  697. {
  698. case LIGHT_DIRECTIONAL:
  699. return dirLightGeometry_;
  700. case LIGHT_SPOT:
  701. return spotLightGeometry_;
  702. case LIGHT_POINT:
  703. return pointLightGeometry_;
  704. }
  705. return 0;
  706. }
  707. Texture2D* Renderer::GetShadowMap(Light* light, Camera* camera, unsigned viewWidth, unsigned viewHeight)
  708. {
  709. LightType type = light->GetLightType();
  710. const FocusParameters& parameters = light->GetShadowFocus();
  711. float size = (float)shadowMapSize_ * light->GetShadowResolution();
  712. // Automatically reduce shadow map size when far away
  713. if (parameters.autoSize_ && type != LIGHT_DIRECTIONAL)
  714. {
  715. const Matrix3x4& view = camera->GetView();
  716. const Matrix4& projection = camera->GetProjection();
  717. BoundingBox lightBox;
  718. float lightPixels;
  719. if (type == LIGHT_POINT)
  720. {
  721. // Calculate point light pixel size from the projection of its diagonal
  722. Vector3 center = view * light->GetNode()->GetWorldPosition();
  723. float extent = 0.58f * light->GetRange();
  724. lightBox.Define(center + Vector3(extent, extent, extent), center - Vector3(extent, extent, extent));
  725. }
  726. else
  727. {
  728. // Calculate spot light pixel size from the projection of its frustum far vertices
  729. Frustum lightFrustum = light->GetFrustum().Transformed(view);
  730. lightBox.Define(&lightFrustum.vertices_[4], 4);
  731. }
  732. Vector2 projectionSize = lightBox.Projected(projection).Size();
  733. lightPixels = Max(0.5f * (float)viewWidth * projectionSize.x_, 0.5f * (float)viewHeight * projectionSize.y_);
  734. // Clamp pixel amount to a sufficient minimum to avoid self-shadowing artifacts due to loss of precision
  735. if (lightPixels < SHADOW_MIN_PIXELS)
  736. lightPixels = SHADOW_MIN_PIXELS;
  737. size = Min(size, lightPixels);
  738. }
  739. /// \todo Allow to specify maximum shadow maps per resolution, as smaller shadow maps take less memory
  740. int width = NextPowerOfTwo((unsigned)size);
  741. int height = width;
  742. // Adjust the size for directional or point light shadow map atlases
  743. if (type == LIGHT_DIRECTIONAL)
  744. {
  745. if (maxShadowCascades_ > 1)
  746. width *= 2;
  747. if (maxShadowCascades_ > 2)
  748. height *= 2;
  749. }
  750. else if (type == LIGHT_POINT)
  751. {
  752. width *= 2;
  753. height *= 3;
  754. }
  755. int searchKey = (width << 16) | height;
  756. if (shadowMaps_.Contains(searchKey))
  757. {
  758. // If shadow maps are reused, always return the first
  759. if (reuseShadowMaps_)
  760. return shadowMaps_[searchKey][0];
  761. else
  762. {
  763. // If not reused, check allocation count and return existing shadow map if possible
  764. unsigned allocated = shadowMapAllocations_[searchKey].Size();
  765. if (allocated < shadowMaps_[searchKey].Size())
  766. {
  767. shadowMapAllocations_[searchKey].Push(light);
  768. return shadowMaps_[searchKey][allocated];
  769. }
  770. else if ((int)allocated >= maxShadowMaps_)
  771. return 0;
  772. }
  773. }
  774. unsigned shadowMapFormat = (shadowQuality_ & SHADOWQUALITY_LOW_24BIT) ? graphics_->GetHiresShadowMapFormat() :
  775. graphics_->GetShadowMapFormat();
  776. if (!shadowMapFormat)
  777. return 0;
  778. SharedPtr<Texture2D> newShadowMap(new Texture2D(context_));
  779. int retries = 3;
  780. // OpenGL: create shadow map only. Color rendertarget is not needed
  781. #ifdef USE_OPENGL
  782. while (retries)
  783. {
  784. if (!newShadowMap->SetSize(width, height, shadowMapFormat, TEXTURE_DEPTHSTENCIL))
  785. {
  786. width >>= 1;
  787. height >>= 1;
  788. --retries;
  789. }
  790. else
  791. {
  792. #ifndef GL_ES_VERSION_2_0
  793. newShadowMap->SetFilterMode(FILTER_BILINEAR);
  794. newShadowMap->SetShadowCompare(true);
  795. #endif
  796. break;
  797. }
  798. }
  799. #else
  800. // Direct3D9: create shadow map and dummy color rendertarget
  801. unsigned dummyColorFormat = graphics_->GetDummyColorFormat();
  802. while (retries)
  803. {
  804. if (!newShadowMap->SetSize(width, height, shadowMapFormat, TEXTURE_DEPTHSTENCIL))
  805. {
  806. width >>= 1;
  807. height >>= 1;
  808. --retries;
  809. }
  810. else
  811. {
  812. newShadowMap->SetFilterMode(FILTER_BILINEAR);
  813. // If no dummy color rendertarget for this size exists yet, create one now
  814. if (!colorShadowMaps_.Contains(searchKey))
  815. {
  816. colorShadowMaps_[searchKey] = new Texture2D(context_);
  817. colorShadowMaps_[searchKey]->SetSize(width, height, dummyColorFormat, TEXTURE_RENDERTARGET);
  818. }
  819. // Link the color rendertarget to the shadow map
  820. newShadowMap->GetRenderSurface()->SetLinkedRenderTarget(colorShadowMaps_[searchKey]->GetRenderSurface());
  821. break;
  822. }
  823. }
  824. #endif
  825. // If failed to set size, store a null pointer so that we will not retry
  826. if (!retries)
  827. newShadowMap.Reset();
  828. shadowMaps_[searchKey].Push(newShadowMap);
  829. if (!reuseShadowMaps_)
  830. shadowMapAllocations_[searchKey].Push(light);
  831. return newShadowMap;
  832. }
  833. Texture2D* Renderer::GetScreenBuffer(int width, int height, unsigned format, bool filtered, bool srgb, unsigned persistentKey)
  834. {
  835. bool depthStencil = (format == Graphics::GetDepthStencilFormat());
  836. if (depthStencil)
  837. {
  838. filtered = false;
  839. srgb = false;
  840. }
  841. long long searchKey = ((long long)format << 32) | (width << 16) | height;
  842. if (filtered)
  843. searchKey |= 0x8000000000000000LL;
  844. if (srgb)
  845. searchKey |= 0x4000000000000000LL;
  846. // Add persistent key if defined
  847. if (persistentKey)
  848. searchKey += ((long long)persistentKey << 32);
  849. // If new size or format, initialize the allocation stats
  850. if (screenBuffers_.Find(searchKey) == screenBuffers_.End())
  851. screenBufferAllocations_[searchKey] = 0;
  852. // Reuse depth-stencil buffers whenever the size matches, instead of allocating new
  853. unsigned allocations = screenBufferAllocations_[searchKey];
  854. if(!depthStencil)
  855. ++screenBufferAllocations_[searchKey];
  856. if (allocations >= screenBuffers_[searchKey].Size())
  857. {
  858. SharedPtr<Texture2D> newBuffer(new Texture2D(context_));
  859. newBuffer->SetSRGB(srgb);
  860. newBuffer->SetSize(width, height, format, depthStencil ? TEXTURE_DEPTHSTENCIL : TEXTURE_RENDERTARGET);
  861. newBuffer->SetFilterMode(filtered ? FILTER_BILINEAR : FILTER_NEAREST);
  862. newBuffer->ResetUseTimer();
  863. screenBuffers_[searchKey].Push(newBuffer);
  864. #ifdef USE_OPENGL
  865. // OpenGL hack: clear persistent floating point screen buffers to ensure the initial contents aren't illegal (NaN)?
  866. // Otherwise eg. the AutoExposure post process will not work correctly
  867. if (persistentKey && Texture::GetDataType(format) == GL_FLOAT)
  868. {
  869. // Note: this loses current rendertarget assignment
  870. graphics_->ResetRenderTargets();
  871. graphics_->SetRenderTarget(0, newBuffer);
  872. graphics_->SetDepthStencil((RenderSurface*)0);
  873. graphics_->SetViewport(IntRect(0, 0, width, height));
  874. graphics_->Clear(CLEAR_COLOR);
  875. }
  876. #endif
  877. LOGDEBUG("Allocated new screen buffer size " + String(width) + "x" + String(height) + " format " + String(format));
  878. return newBuffer;
  879. }
  880. else
  881. {
  882. Texture2D* buffer = screenBuffers_[searchKey][allocations];
  883. buffer->ResetUseTimer();
  884. return buffer;
  885. }
  886. }
  887. RenderSurface* Renderer::GetDepthStencil(int width, int height)
  888. {
  889. // Return the default depth-stencil surface if applicable
  890. // (when using OpenGL Graphics will allocate right size surfaces on demand to emulate Direct3D9)
  891. if (width == graphics_->GetWidth() && height == graphics_->GetHeight() && graphics_->GetMultiSample() <= 1)
  892. return 0;
  893. else
  894. return GetScreenBuffer(width, height, Graphics::GetDepthStencilFormat(), false, false)->GetRenderSurface();
  895. }
  896. OcclusionBuffer* Renderer::GetOcclusionBuffer(Camera* camera)
  897. {
  898. assert(numOcclusionBuffers_ <= occlusionBuffers_.Size());
  899. if (numOcclusionBuffers_ == occlusionBuffers_.Size())
  900. {
  901. SharedPtr<OcclusionBuffer> newBuffer(new OcclusionBuffer(context_));
  902. occlusionBuffers_.Push(newBuffer);
  903. }
  904. int width = occlusionBufferSize_;
  905. int height = (int)((float)occlusionBufferSize_ / camera->GetAspectRatio() + 0.5f);
  906. OcclusionBuffer* buffer = occlusionBuffers_[numOcclusionBuffers_++];
  907. buffer->SetSize(width, height);
  908. buffer->SetView(camera);
  909. buffer->ResetUseTimer();
  910. return buffer;
  911. }
  912. Camera* Renderer::GetShadowCamera()
  913. {
  914. MutexLock lock(rendererMutex_);
  915. assert(numShadowCameras_ <= shadowCameraNodes_.Size());
  916. if (numShadowCameras_ == shadowCameraNodes_.Size())
  917. {
  918. SharedPtr<Node> newNode(new Node(context_));
  919. newNode->CreateComponent<Camera>();
  920. shadowCameraNodes_.Push(newNode);
  921. }
  922. Camera* camera = shadowCameraNodes_[numShadowCameras_++]->GetComponent<Camera>();
  923. camera->SetOrthographic(false);
  924. camera->SetZoom(1.0f);
  925. return camera;
  926. }
  927. void Renderer::SetBatchShaders(Batch& batch, Technique* tech, bool allowShadows)
  928. {
  929. // Check if shaders are unloaded or need reloading
  930. Pass* pass = batch.pass_;
  931. Vector<SharedPtr<ShaderVariation> >& vertexShaders = pass->GetVertexShaders();
  932. Vector<SharedPtr<ShaderVariation> >& pixelShaders = pass->GetPixelShaders();
  933. if (!vertexShaders.Size() || !pixelShaders.Size() || pass->GetShadersLoadedFrameNumber() !=
  934. shadersChangedFrameNumber_)
  935. {
  936. // First release all previous shaders, then load
  937. pass->ReleaseShaders();
  938. LoadPassShaders(tech, pass->GetType());
  939. }
  940. // Make sure shaders are loaded now
  941. if (vertexShaders.Size() && pixelShaders.Size())
  942. {
  943. bool heightFog = graphics_->GetSM3Support() && batch.zone_ && batch.zone_->GetHeightFog();
  944. // If instancing is not supported, but was requested, or the object is too large to be instanced,
  945. // choose static geometry vertex shader instead
  946. if (batch.geometryType_ == GEOM_INSTANCED && (!GetDynamicInstancing() || batch.geometry_->GetIndexCount() >
  947. (unsigned)maxInstanceTriangles_ * 3))
  948. batch.geometryType_ = GEOM_STATIC;
  949. if (batch.geometryType_ == GEOM_STATIC_NOINSTANCING)
  950. batch.geometryType_ = GEOM_STATIC;
  951. // Check whether is a pixel lit forward pass. If not, there is only one pixel shader
  952. if (pass->GetLightingMode() == LIGHTING_PERPIXEL)
  953. {
  954. LightBatchQueue* lightQueue = batch.lightQueue_;
  955. if (!lightQueue)
  956. {
  957. // Do not log error, as it would result in a lot of spam
  958. batch.vertexShader_ = 0;
  959. batch.pixelShader_ = 0;
  960. return;
  961. }
  962. Light* light = lightQueue->light_;
  963. unsigned vsi = 0;
  964. unsigned psi = 0;
  965. vsi = batch.geometryType_ * MAX_LIGHT_VS_VARIATIONS;
  966. bool materialHasSpecular = batch.material_ ? batch.material_->GetSpecular() : true;
  967. if (specularLighting_ && light->GetSpecularIntensity() > 0.0f && materialHasSpecular)
  968. {
  969. vsi += LVS_SPEC;
  970. psi += LPS_SPEC;
  971. }
  972. if (allowShadows && lightQueue->shadowMap_)
  973. {
  974. vsi += LVS_SHADOW;
  975. psi += LPS_SHADOW;
  976. }
  977. switch (light->GetLightType())
  978. {
  979. case LIGHT_DIRECTIONAL:
  980. vsi += LVS_DIR;
  981. break;
  982. case LIGHT_SPOT:
  983. psi += LPS_SPOT;
  984. vsi += LVS_SPOT;
  985. break;
  986. case LIGHT_POINT:
  987. if (light->GetShapeTexture())
  988. psi += LPS_POINTMASK;
  989. else
  990. psi += LPS_POINT;
  991. vsi += LVS_POINT;
  992. break;
  993. }
  994. if (heightFog)
  995. {
  996. vsi += MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS;
  997. psi += MAX_LIGHT_PS_VARIATIONS;
  998. }
  999. batch.vertexShader_ = vertexShaders[vsi];
  1000. batch.pixelShader_ = pixelShaders[psi];
  1001. }
  1002. else
  1003. {
  1004. // Check if pass has vertex lighting support
  1005. if (pass->GetLightingMode() == LIGHTING_PERVERTEX)
  1006. {
  1007. unsigned numVertexLights = 0;
  1008. if (batch.lightQueue_)
  1009. numVertexLights = batch.lightQueue_->vertexLights_.Size();
  1010. unsigned vsi = batch.geometryType_ * MAX_VERTEXLIGHT_VS_VARIATIONS + numVertexLights;
  1011. if (heightFog)
  1012. vsi += MAX_GEOMETRYTYPES * MAX_VERTEXLIGHT_VS_VARIATIONS;
  1013. batch.vertexShader_ = vertexShaders[vsi];
  1014. }
  1015. else
  1016. {
  1017. unsigned vsi = batch.geometryType_;
  1018. if (heightFog)
  1019. vsi += MAX_GEOMETRYTYPES;
  1020. batch.vertexShader_ = vertexShaders[vsi];
  1021. }
  1022. batch.pixelShader_ = pixelShaders[heightFog ? 1 : 0];
  1023. }
  1024. }
  1025. // Log error if shaders could not be assigned, but only once per technique
  1026. if (!batch.vertexShader_ || !batch.pixelShader_)
  1027. {
  1028. if (!shaderErrorDisplayed_.Contains(tech))
  1029. {
  1030. shaderErrorDisplayed_.Insert(tech);
  1031. LOGERROR("Technique " + tech->GetName() + " has missing shaders");
  1032. }
  1033. }
  1034. }
  1035. void Renderer::SetLightVolumeBatchShaders(Batch& batch, const String& vsName, const String& psName)
  1036. {
  1037. assert(deferredLightPSVariations_.Size());
  1038. unsigned vsi = DLVS_NONE;
  1039. unsigned psi = DLPS_NONE;
  1040. Light* light = batch.lightQueue_->light_;
  1041. switch (light->GetLightType())
  1042. {
  1043. case LIGHT_DIRECTIONAL:
  1044. vsi += DLVS_DIR;
  1045. break;
  1046. case LIGHT_SPOT:
  1047. psi += DLPS_SPOT;
  1048. break;
  1049. case LIGHT_POINT:
  1050. if (light->GetShapeTexture())
  1051. psi += DLPS_POINTMASK;
  1052. else
  1053. psi += DLPS_POINT;
  1054. break;
  1055. }
  1056. if (batch.lightQueue_->shadowMap_)
  1057. psi += DLPS_SHADOW;
  1058. if (specularLighting_ && light->GetSpecularIntensity() > 0.0f)
  1059. psi += DLPS_SPEC;
  1060. if (batch.camera_->IsOrthographic())
  1061. {
  1062. vsi += DLVS_ORTHO;
  1063. psi += DLPS_ORTHO;
  1064. }
  1065. batch.vertexShader_ = GetShader(VS, vsName, deferredLightVSVariations[vsi]);
  1066. batch.pixelShader_ = GetShader(PS, psName, deferredLightPSVariations_[psi]);
  1067. }
  1068. void Renderer::SetCullMode(CullMode mode, Camera* camera)
  1069. {
  1070. // If a camera is specified, check whether it reverses culling due to vertical flipping or reflection
  1071. if (camera && camera->GetReverseCulling())
  1072. {
  1073. if (mode == CULL_CW)
  1074. mode = CULL_CCW;
  1075. else if (mode == CULL_CCW)
  1076. mode = CULL_CW;
  1077. }
  1078. graphics_->SetCullMode(mode);
  1079. }
  1080. bool Renderer::ResizeInstancingBuffer(unsigned numInstances)
  1081. {
  1082. if (!instancingBuffer_ || !dynamicInstancing_)
  1083. return false;
  1084. unsigned oldSize = instancingBuffer_->GetVertexCount();
  1085. if (numInstances <= oldSize)
  1086. return true;
  1087. unsigned newSize = INSTANCING_BUFFER_DEFAULT_SIZE;
  1088. while (newSize < numInstances)
  1089. newSize <<= 1;
  1090. if (!instancingBuffer_->SetSize(newSize, INSTANCING_BUFFER_MASK, true))
  1091. {
  1092. LOGERROR("Failed to resize instancing buffer to " + String(newSize));
  1093. // If failed, try to restore the old size
  1094. instancingBuffer_->SetSize(oldSize, INSTANCING_BUFFER_MASK, true);
  1095. return false;
  1096. }
  1097. LOGDEBUG("Resized instancing buffer to " + String(newSize));
  1098. return true;
  1099. }
  1100. void Renderer::SaveScreenBufferAllocations()
  1101. {
  1102. savedScreenBufferAllocations_ = screenBufferAllocations_;
  1103. }
  1104. void Renderer::RestoreScreenBufferAllocations()
  1105. {
  1106. screenBufferAllocations_ = savedScreenBufferAllocations_;
  1107. }
  1108. void Renderer::OptimizeLightByScissor(Light* light, Camera* camera)
  1109. {
  1110. if (light && light->GetLightType() != LIGHT_DIRECTIONAL)
  1111. graphics_->SetScissorTest(true, GetLightScissor(light, camera));
  1112. else
  1113. graphics_->SetScissorTest(false);
  1114. }
  1115. void Renderer::OptimizeLightByStencil(Light* light, Camera* camera)
  1116. {
  1117. #ifndef GL_ES_VERSION_2_0
  1118. if (light)
  1119. {
  1120. LightType type = light->GetLightType();
  1121. if (type == LIGHT_DIRECTIONAL)
  1122. {
  1123. graphics_->SetStencilTest(false);
  1124. return;
  1125. }
  1126. Geometry* geometry = GetLightGeometry(light);
  1127. const Matrix3x4& view = camera->GetView();
  1128. const Matrix4& projection = camera->GetProjection();
  1129. Vector3 cameraPos = camera->GetNode()->GetWorldPosition();
  1130. float lightDist;
  1131. if (type == LIGHT_POINT)
  1132. lightDist = Sphere(light->GetNode()->GetWorldPosition(), light->GetRange() * 1.25f).Distance(cameraPos);
  1133. else
  1134. lightDist = light->GetFrustum().Distance(cameraPos);
  1135. // If the camera is actually inside the light volume, do not draw to stencil as it would waste fillrate
  1136. if (lightDist < M_EPSILON)
  1137. {
  1138. graphics_->SetStencilTest(false);
  1139. return;
  1140. }
  1141. // If the stencil value has wrapped, clear the whole stencil first
  1142. if (!lightStencilValue_)
  1143. {
  1144. graphics_->Clear(CLEAR_STENCIL);
  1145. lightStencilValue_ = 1;
  1146. }
  1147. // If possible, render the stencil volume front faces. However, close to the near clip plane render back faces instead
  1148. // to avoid clipping.
  1149. if (lightDist < camera->GetNearClip() * 2.0f)
  1150. {
  1151. SetCullMode(CULL_CW, camera);
  1152. graphics_->SetDepthTest(CMP_GREATER);
  1153. }
  1154. else
  1155. {
  1156. SetCullMode(CULL_CCW, camera);
  1157. graphics_->SetDepthTest(CMP_LESSEQUAL);
  1158. }
  1159. graphics_->SetColorWrite(false);
  1160. graphics_->SetDepthWrite(false);
  1161. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, lightStencilValue_);
  1162. graphics_->SetShaders(GetShader(VS, "Stencil"), GetShader(PS, "Stencil"));
  1163. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection * view);
  1164. graphics_->SetShaderParameter(VSP_MODEL, light->GetVolumeTransform(camera));
  1165. geometry->Draw(graphics_);
  1166. graphics_->ClearTransformSources();
  1167. graphics_->SetColorWrite(true);
  1168. graphics_->SetStencilTest(true, CMP_EQUAL, OP_KEEP, OP_KEEP, OP_KEEP, lightStencilValue_);
  1169. // Increase stencil value for next light
  1170. ++lightStencilValue_;
  1171. }
  1172. else
  1173. graphics_->SetStencilTest(false);
  1174. #endif
  1175. }
  1176. const Rect& Renderer::GetLightScissor(Light* light, Camera* camera)
  1177. {
  1178. Pair<Light*, Camera*> combination(light, camera);
  1179. HashMap<Pair<Light*, Camera*>, Rect>::Iterator i = lightScissorCache_.Find(combination);
  1180. if (i != lightScissorCache_.End())
  1181. return i->second_;
  1182. const Matrix3x4& view = camera->GetView();
  1183. const Matrix4& projection = camera->GetProjection();
  1184. assert(light->GetLightType() != LIGHT_DIRECTIONAL);
  1185. if (light->GetLightType() == LIGHT_SPOT)
  1186. {
  1187. Frustum viewFrustum(light->GetFrustum().Transformed(view));
  1188. return lightScissorCache_[combination] = viewFrustum.Projected(projection);
  1189. }
  1190. else // LIGHT_POINT
  1191. {
  1192. BoundingBox viewBox(light->GetWorldBoundingBox().Transformed(view));
  1193. return lightScissorCache_[combination] = viewBox.Projected(projection);
  1194. }
  1195. }
  1196. void Renderer::PrepareViewRender()
  1197. {
  1198. ResetScreenBufferAllocations();
  1199. lightScissorCache_.Clear();
  1200. lightStencilValue_ = 1;
  1201. }
  1202. void Renderer::RemoveUnusedBuffers()
  1203. {
  1204. for (unsigned i = occlusionBuffers_.Size() - 1; i < occlusionBuffers_.Size(); --i)
  1205. {
  1206. if (occlusionBuffers_[i]->GetUseTimer() > MAX_BUFFER_AGE)
  1207. {
  1208. LOGDEBUG("Removed unused occlusion buffer");
  1209. occlusionBuffers_.Erase(i);
  1210. }
  1211. }
  1212. for (HashMap<long long, Vector<SharedPtr<Texture2D> > >::Iterator i = screenBuffers_.Begin(); i != screenBuffers_.End();)
  1213. {
  1214. HashMap<long long, Vector<SharedPtr<Texture2D> > >::Iterator current = i++;
  1215. Vector<SharedPtr<Texture2D> >& buffers = current->second_;
  1216. for (unsigned j = buffers.Size() - 1; j < buffers.Size(); --j)
  1217. {
  1218. Texture2D* buffer = buffers[j];
  1219. if (buffer->GetUseTimer() > MAX_BUFFER_AGE)
  1220. {
  1221. LOGDEBUG("Removed unused screen buffer size " + String(buffer->GetWidth()) + "x" + String(buffer->GetHeight()) + " format " + String(buffer->GetFormat()));
  1222. buffers.Erase(j);
  1223. }
  1224. }
  1225. if (buffers.Empty())
  1226. {
  1227. screenBufferAllocations_.Erase(current->first_);
  1228. screenBuffers_.Erase(current);
  1229. }
  1230. }
  1231. }
  1232. void Renderer::ResetShadowMapAllocations()
  1233. {
  1234. for (HashMap<int, PODVector<Light*> >::Iterator i = shadowMapAllocations_.Begin(); i != shadowMapAllocations_.End(); ++i)
  1235. i->second_.Clear();
  1236. }
  1237. void Renderer::ResetScreenBufferAllocations()
  1238. {
  1239. for (HashMap<long long, unsigned>::Iterator i = screenBufferAllocations_.Begin(); i != screenBufferAllocations_.End(); ++i)
  1240. i->second_ = 0;
  1241. }
  1242. void Renderer::Initialize()
  1243. {
  1244. Graphics* graphics = GetSubsystem<Graphics>();
  1245. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1246. if (!graphics || !graphics->IsInitialized() || !cache)
  1247. return;
  1248. PROFILE(InitRenderer);
  1249. graphics_ = graphics;
  1250. if (!graphics_->GetShadowMapFormat())
  1251. drawShadows_ = false;
  1252. defaultLightRamp_ = cache->GetResource<Texture2D>("Textures/Ramp.png");
  1253. defaultLightSpot_ = cache->GetResource<Texture2D>("Textures/Spot.png");
  1254. defaultMaterial_ = cache->GetResource<Material>("Materials/Default.xml");
  1255. // If default material not found, create one. This will actually not render properly, but prevents crashing
  1256. if (!defaultMaterial_)
  1257. defaultMaterial_ = new Material(context_);
  1258. defaultRenderPath_ = new RenderPath();
  1259. defaultRenderPath_->Load(cache->GetResource<XMLFile>("RenderPaths/Forward.xml"));
  1260. CreateGeometries();
  1261. CreateInstancingBuffer();
  1262. viewports_.Resize(1);
  1263. ResetViews();
  1264. ResetShadowMaps();
  1265. ResetBuffers();
  1266. shadersDirty_ = true;
  1267. initialized_ = true;
  1268. SubscribeToEvent(E_RENDERUPDATE, HANDLER(Renderer, HandleRenderUpdate));
  1269. LOGINFO("Initialized renderer");
  1270. }
  1271. void Renderer::ResetViews()
  1272. {
  1273. views_.Clear();
  1274. numViews_ = 0;
  1275. }
  1276. void Renderer::LoadShaders()
  1277. {
  1278. LOGDEBUG("Reloading shaders");
  1279. // Release old material shaders, mark them for reload
  1280. ReleaseMaterialShaders();
  1281. shadersChangedFrameNumber_ = GetSubsystem<Time>()->GetFrameNumber();
  1282. // Construct new names for deferred light volume pixel shaders based on rendering options
  1283. deferredLightPSVariations_.Resize(MAX_DEFERRED_LIGHT_PS_VARIATIONS);
  1284. unsigned shadows = (graphics_->GetHardwareShadowSupport() ? 1 : 0) | (shadowQuality_ & SHADOWQUALITY_HIGH_16BIT);
  1285. for (unsigned i = 0; i < MAX_DEFERRED_LIGHT_PS_VARIATIONS; ++i)
  1286. {
  1287. deferredLightPSVariations_[i] = lightPSVariations[i % DLPS_ORTHO];
  1288. if (i & DLPS_SHADOW)
  1289. deferredLightPSVariations_[i] += shadowVariations[shadows];
  1290. if (i & DLPS_ORTHO)
  1291. deferredLightPSVariations_[i] += "ORTHO";
  1292. }
  1293. shadersDirty_ = false;
  1294. }
  1295. void Renderer::LoadPassShaders(Technique* tech, StringHash type)
  1296. {
  1297. Pass* pass = tech->GetPass(type);
  1298. if (!pass)
  1299. return;
  1300. PROFILE(LoadPassShaders);
  1301. unsigned shadows = (graphics_->GetHardwareShadowSupport() ? 1 : 0) | (shadowQuality_ & SHADOWQUALITY_HIGH_16BIT);
  1302. Vector<SharedPtr<ShaderVariation> >& vertexShaders = pass->GetVertexShaders();
  1303. Vector<SharedPtr<ShaderVariation> >& pixelShaders = pass->GetPixelShaders();
  1304. // Forget all the old shaders
  1305. vertexShaders.Clear();
  1306. pixelShaders.Clear();
  1307. if (pass->GetLightingMode() == LIGHTING_PERPIXEL)
  1308. {
  1309. // Load forward pixel lit variations
  1310. vertexShaders.Resize(MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS * 2);
  1311. pixelShaders.Resize(MAX_LIGHT_PS_VARIATIONS * 2);
  1312. for (unsigned j = 0; j < MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS * 2; ++j)
  1313. {
  1314. unsigned k = j % (MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS);
  1315. unsigned h = j / (MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS);
  1316. unsigned g = k / MAX_LIGHT_VS_VARIATIONS;
  1317. unsigned l = k % MAX_LIGHT_VS_VARIATIONS;
  1318. vertexShaders[j] = GetShader(VS, pass->GetVertexShader(), Shader::SanitateDefines(pass->GetVertexShaderDefines() + " " +
  1319. lightVSVariations[l] + geometryVSVariations[g] + heightFogVariations[h]));
  1320. }
  1321. for (unsigned j = 0; j < MAX_LIGHT_PS_VARIATIONS * 2; ++j)
  1322. {
  1323. unsigned k = j % MAX_LIGHT_PS_VARIATIONS;
  1324. unsigned h = j / MAX_LIGHT_PS_VARIATIONS;
  1325. if (k & LPS_SHADOW)
  1326. {
  1327. pixelShaders[j] = GetShader(PS, pass->GetPixelShader(), Shader::SanitateDefines(pass->GetPixelShaderDefines() +
  1328. " " + lightPSVariations[k] + shadowVariations[shadows] + heightFogVariations[h]));
  1329. }
  1330. else
  1331. pixelShaders[j] = GetShader(PS, pass->GetPixelShader(), Shader::SanitateDefines(pass->GetPixelShaderDefines() +
  1332. " " + lightPSVariations[k] + heightFogVariations[h]));
  1333. }
  1334. }
  1335. else
  1336. {
  1337. // Load vertex light variations
  1338. if (pass->GetLightingMode() == LIGHTING_PERVERTEX)
  1339. {
  1340. vertexShaders.Resize(MAX_GEOMETRYTYPES * MAX_VERTEXLIGHT_VS_VARIATIONS * 2);
  1341. for (unsigned j = 0; j < MAX_GEOMETRYTYPES * MAX_VERTEXLIGHT_VS_VARIATIONS * 2; ++j)
  1342. {
  1343. unsigned k = j % (MAX_GEOMETRYTYPES * MAX_VERTEXLIGHT_VS_VARIATIONS);
  1344. unsigned h = j / (MAX_GEOMETRYTYPES * MAX_VERTEXLIGHT_VS_VARIATIONS);
  1345. unsigned g = k / MAX_VERTEXLIGHT_VS_VARIATIONS;
  1346. unsigned l = k % MAX_VERTEXLIGHT_VS_VARIATIONS;
  1347. vertexShaders[j] = GetShader(VS, pass->GetVertexShader(), Shader::SanitateDefines(pass->GetVertexShaderDefines() +
  1348. " " + vertexLightVSVariations[l] + geometryVSVariations[g] + heightFogVariations[h]));
  1349. }
  1350. }
  1351. else
  1352. {
  1353. vertexShaders.Resize(MAX_GEOMETRYTYPES * 2);
  1354. for (unsigned j = 0; j < MAX_GEOMETRYTYPES * 2; ++j)
  1355. {
  1356. unsigned k = j % MAX_GEOMETRYTYPES;
  1357. unsigned h = j / MAX_GEOMETRYTYPES;
  1358. vertexShaders[j] = GetShader(VS, pass->GetVertexShader(), Shader::SanitateDefines(pass->GetVertexShaderDefines() +
  1359. " " + geometryVSVariations[k] + heightFogVariations[h]));
  1360. }
  1361. }
  1362. pixelShaders.Resize(2);
  1363. for (unsigned j = 0; j < 2; ++j)
  1364. {
  1365. pixelShaders[j] = GetShader(PS, pass->GetPixelShader(), Shader::SanitateDefines(pass->GetPixelShaderDefines() + " " +
  1366. heightFogVariations[j]));
  1367. }
  1368. }
  1369. pass->MarkShadersLoaded(shadersChangedFrameNumber_);
  1370. }
  1371. void Renderer::ReleaseMaterialShaders()
  1372. {
  1373. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1374. PODVector<Material*> materials;
  1375. cache->GetResources<Material>(materials);
  1376. for (unsigned i = 0; i < materials.Size(); ++i)
  1377. materials[i]->ReleaseShaders();
  1378. }
  1379. void Renderer::ReloadTextures()
  1380. {
  1381. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1382. PODVector<Resource*> textures;
  1383. cache->GetResources(textures, Texture2D::GetTypeStatic());
  1384. for (unsigned i = 0; i < textures.Size(); ++i)
  1385. cache->ReloadResource(textures[i]);
  1386. cache->GetResources(textures, TextureCube::GetTypeStatic());
  1387. for (unsigned i = 0; i < textures.Size(); ++i)
  1388. cache->ReloadResource(textures[i]);
  1389. }
  1390. void Renderer::CreateGeometries()
  1391. {
  1392. SharedPtr<VertexBuffer> dlvb(new VertexBuffer(context_));
  1393. dlvb->SetShadowed(true);
  1394. dlvb->SetSize(4, MASK_POSITION);
  1395. dlvb->SetData(dirLightVertexData);
  1396. SharedPtr<IndexBuffer> dlib(new IndexBuffer(context_));
  1397. dlib->SetShadowed(true);
  1398. dlib->SetSize(6, false);
  1399. dlib->SetData(dirLightIndexData);
  1400. dirLightGeometry_ = new Geometry(context_);
  1401. dirLightGeometry_->SetVertexBuffer(0, dlvb);
  1402. dirLightGeometry_->SetIndexBuffer(dlib);
  1403. dirLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, dlib->GetIndexCount());
  1404. SharedPtr<VertexBuffer> slvb(new VertexBuffer(context_));
  1405. slvb->SetShadowed(true);
  1406. slvb->SetSize(8, MASK_POSITION);
  1407. slvb->SetData(spotLightVertexData);
  1408. SharedPtr<IndexBuffer> slib(new IndexBuffer(context_));
  1409. slib->SetShadowed(true);
  1410. slib->SetSize(36, false);
  1411. slib->SetData(spotLightIndexData);
  1412. spotLightGeometry_ = new Geometry(context_);
  1413. spotLightGeometry_->SetVertexBuffer(0, slvb);
  1414. spotLightGeometry_->SetIndexBuffer(slib);
  1415. spotLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, slib->GetIndexCount());
  1416. SharedPtr<VertexBuffer> plvb(new VertexBuffer(context_));
  1417. plvb->SetShadowed(true);
  1418. plvb->SetSize(24, MASK_POSITION);
  1419. plvb->SetData(pointLightVertexData);
  1420. SharedPtr<IndexBuffer> plib(new IndexBuffer(context_));
  1421. plib->SetShadowed(true);
  1422. plib->SetSize(132, false);
  1423. plib->SetData(pointLightIndexData);
  1424. pointLightGeometry_ = new Geometry(context_);
  1425. pointLightGeometry_->SetVertexBuffer(0, plvb);
  1426. pointLightGeometry_->SetIndexBuffer(plib);
  1427. pointLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, plib->GetIndexCount());
  1428. #if !defined(USE_OPENGL) || !defined(GL_ES_VERSION_2_0)
  1429. if (graphics_->GetShadowMapFormat())
  1430. {
  1431. faceSelectCubeMap_ = new TextureCube(context_);
  1432. faceSelectCubeMap_->SetNumLevels(1);
  1433. faceSelectCubeMap_->SetSize(1, graphics_->GetRGBAFormat());
  1434. faceSelectCubeMap_->SetFilterMode(FILTER_NEAREST);
  1435. indirectionCubeMap_ = new TextureCube(context_);
  1436. indirectionCubeMap_->SetNumLevels(1);
  1437. indirectionCubeMap_->SetSize(256, graphics_->GetRGBAFormat());
  1438. indirectionCubeMap_->SetFilterMode(FILTER_BILINEAR);
  1439. indirectionCubeMap_->SetAddressMode(COORD_U, ADDRESS_CLAMP);
  1440. indirectionCubeMap_->SetAddressMode(COORD_V, ADDRESS_CLAMP);
  1441. indirectionCubeMap_->SetAddressMode(COORD_W, ADDRESS_CLAMP);
  1442. SetIndirectionTextureData();
  1443. }
  1444. #endif
  1445. }
  1446. void Renderer::SetIndirectionTextureData()
  1447. {
  1448. unsigned char data[256 * 256 * 4];
  1449. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1450. {
  1451. unsigned axis = i / 2;
  1452. data[0] = (axis == 0) ? 255 : 0;
  1453. data[1] = (axis == 1) ? 255 : 0;
  1454. data[2] = (axis == 2) ? 255 : 0;
  1455. data[3] = 0;
  1456. faceSelectCubeMap_->SetData((CubeMapFace)i, 0, 0, 0, 1, 1, data);
  1457. }
  1458. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1459. {
  1460. unsigned char faceX = (i & 1) * 255;
  1461. unsigned char faceY = (i / 2) * 255 / 3;
  1462. unsigned char* dest = data;
  1463. for (unsigned y = 0; y < 256; ++y)
  1464. {
  1465. for (unsigned x = 0; x < 256; ++x)
  1466. {
  1467. #ifdef USE_OPENGL
  1468. dest[0] = x;
  1469. dest[1] = 255 - y;
  1470. dest[2] = faceX;
  1471. dest[3] = 255 * 2 / 3 - faceY;
  1472. #else
  1473. dest[0] = x;
  1474. dest[1] = y;
  1475. dest[2] = faceX;
  1476. dest[3] = faceY;
  1477. #endif
  1478. dest += 4;
  1479. }
  1480. }
  1481. indirectionCubeMap_->SetData((CubeMapFace)i, 0, 0, 0, 256, 256, data);
  1482. }
  1483. faceSelectCubeMap_->ClearDataLost();
  1484. indirectionCubeMap_->ClearDataLost();
  1485. }
  1486. void Renderer::CreateInstancingBuffer()
  1487. {
  1488. // Do not create buffer if instancing not supported
  1489. if (!graphics_->GetInstancingSupport())
  1490. {
  1491. instancingBuffer_.Reset();
  1492. dynamicInstancing_ = false;
  1493. return;
  1494. }
  1495. // If must lock the buffer for each batch group, set a smaller size
  1496. unsigned defaultSize = graphics_->GetStreamOffsetSupport() ? INSTANCING_BUFFER_DEFAULT_SIZE : INSTANCING_BUFFER_DEFAULT_SIZE / 4;
  1497. instancingBuffer_ = new VertexBuffer(context_);
  1498. if (!instancingBuffer_->SetSize(defaultSize, INSTANCING_BUFFER_MASK, true))
  1499. {
  1500. instancingBuffer_.Reset();
  1501. dynamicInstancing_ = false;
  1502. }
  1503. }
  1504. void Renderer::ResetShadowMaps()
  1505. {
  1506. shadowMaps_.Clear();
  1507. shadowMapAllocations_.Clear();
  1508. colorShadowMaps_.Clear();
  1509. }
  1510. void Renderer::ResetBuffers()
  1511. {
  1512. occlusionBuffers_.Clear();
  1513. screenBuffers_.Clear();
  1514. screenBufferAllocations_.Clear();
  1515. }
  1516. void Renderer::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  1517. {
  1518. if (!initialized_)
  1519. Initialize();
  1520. else
  1521. {
  1522. // When screen mode changes, purge old views
  1523. ResetViews();
  1524. }
  1525. }
  1526. void Renderer::HandleGraphicsFeatures(StringHash eventType, VariantMap& eventData)
  1527. {
  1528. // Reinitialize if already initialized
  1529. if (initialized_)
  1530. Initialize();
  1531. }
  1532. void Renderer::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  1533. {
  1534. using namespace RenderUpdate;
  1535. Update(eventData[P_TIMESTEP].GetFloat());
  1536. }
  1537. }