View.cpp 107 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730
  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 "DebugRenderer.h"
  25. #include "FileSystem.h"
  26. #include "Geometry.h"
  27. #include "Graphics.h"
  28. #include "GraphicsImpl.h"
  29. #include "Log.h"
  30. #include "Material.h"
  31. #include "OcclusionBuffer.h"
  32. #include "Octree.h"
  33. #include "Renderer.h"
  34. #include "RenderPath.h"
  35. #include "ResourceCache.h"
  36. #include "Profiler.h"
  37. #include "Scene.h"
  38. #include "ShaderVariation.h"
  39. #include "Skybox.h"
  40. #include "Technique.h"
  41. #include "Texture2D.h"
  42. #include "Texture3D.h"
  43. #include "TextureCube.h"
  44. #include "VertexBuffer.h"
  45. #include "View.h"
  46. #include "WorkQueue.h"
  47. #include "DebugNew.h"
  48. namespace Urho3D
  49. {
  50. static const Vector3* directions[] =
  51. {
  52. &Vector3::RIGHT,
  53. &Vector3::LEFT,
  54. &Vector3::UP,
  55. &Vector3::DOWN,
  56. &Vector3::FORWARD,
  57. &Vector3::BACK
  58. };
  59. static const float LIGHT_INTENSITY_THRESHOLD = 0.003f;
  60. /// %Frustum octree query for shadowcasters.
  61. class ShadowCasterOctreeQuery : public FrustumOctreeQuery
  62. {
  63. public:
  64. /// Construct with frustum and query parameters.
  65. ShadowCasterOctreeQuery(PODVector<Drawable*>& result, const Frustum& frustum, unsigned char drawableFlags = DRAWABLE_ANY,
  66. unsigned viewMask = DEFAULT_VIEWMASK) :
  67. FrustumOctreeQuery(result, frustum, drawableFlags, viewMask)
  68. {
  69. }
  70. /// Intersection test for drawables.
  71. virtual void TestDrawables(Drawable** start, Drawable** end, bool inside)
  72. {
  73. while (start != end)
  74. {
  75. Drawable* drawable = *start++;
  76. if (drawable->GetCastShadows() && (drawable->GetDrawableFlags() & drawableFlags_) &&
  77. (drawable->GetViewMask() & viewMask_))
  78. {
  79. if (inside || frustum_.IsInsideFast(drawable->GetWorldBoundingBox()))
  80. result_.Push(drawable);
  81. }
  82. }
  83. }
  84. };
  85. /// %Frustum octree query for zones and occluders.
  86. class ZoneOccluderOctreeQuery : public FrustumOctreeQuery
  87. {
  88. public:
  89. /// Construct with frustum and query parameters.
  90. ZoneOccluderOctreeQuery(PODVector<Drawable*>& result, const Frustum& frustum, unsigned char drawableFlags = DRAWABLE_ANY,
  91. unsigned viewMask = DEFAULT_VIEWMASK) :
  92. FrustumOctreeQuery(result, frustum, drawableFlags, viewMask)
  93. {
  94. }
  95. /// Intersection test for drawables.
  96. virtual void TestDrawables(Drawable** start, Drawable** end, bool inside)
  97. {
  98. while (start != end)
  99. {
  100. Drawable* drawable = *start++;
  101. unsigned char flags = drawable->GetDrawableFlags();
  102. if ((flags == DRAWABLE_ZONE || (flags == DRAWABLE_GEOMETRY && drawable->IsOccluder())) && (drawable->GetViewMask() &
  103. viewMask_))
  104. {
  105. if (inside || frustum_.IsInsideFast(drawable->GetWorldBoundingBox()))
  106. result_.Push(drawable);
  107. }
  108. }
  109. }
  110. };
  111. /// %Frustum octree query with occlusion.
  112. class OccludedFrustumOctreeQuery : public FrustumOctreeQuery
  113. {
  114. public:
  115. /// Construct with frustum, occlusion buffer and query parameters.
  116. OccludedFrustumOctreeQuery(PODVector<Drawable*>& result, const Frustum& frustum, OcclusionBuffer* buffer, unsigned char
  117. drawableFlags = DRAWABLE_ANY, unsigned viewMask = DEFAULT_VIEWMASK) :
  118. FrustumOctreeQuery(result, frustum, drawableFlags, viewMask),
  119. buffer_(buffer)
  120. {
  121. }
  122. /// Intersection test for an octant.
  123. virtual Intersection TestOctant(const BoundingBox& box, bool inside)
  124. {
  125. if (inside)
  126. return buffer_->IsVisible(box) ? INSIDE : OUTSIDE;
  127. else
  128. {
  129. Intersection result = frustum_.IsInside(box);
  130. if (result != OUTSIDE && !buffer_->IsVisible(box))
  131. result = OUTSIDE;
  132. return result;
  133. }
  134. }
  135. /// Intersection test for drawables. Note: drawable occlusion is performed later in worker threads.
  136. virtual void TestDrawables(Drawable** start, Drawable** end, bool inside)
  137. {
  138. while (start != end)
  139. {
  140. Drawable* drawable = *start++;
  141. if ((drawable->GetDrawableFlags() & drawableFlags_) && (drawable->GetViewMask() & viewMask_))
  142. {
  143. if (inside || frustum_.IsInsideFast(drawable->GetWorldBoundingBox()))
  144. result_.Push(drawable);
  145. }
  146. }
  147. }
  148. /// Occlusion buffer.
  149. OcclusionBuffer* buffer_;
  150. };
  151. void CheckVisibilityWork(const WorkItem* item, unsigned threadIndex)
  152. {
  153. View* view = reinterpret_cast<View*>(item->aux_);
  154. Drawable** start = reinterpret_cast<Drawable**>(item->start_);
  155. Drawable** end = reinterpret_cast<Drawable**>(item->end_);
  156. OcclusionBuffer* buffer = view->occlusionBuffer_;
  157. const Matrix3x4& viewMatrix = view->camera_->GetView();
  158. Vector3 viewZ = Vector3(viewMatrix.m20_, viewMatrix.m21_, viewMatrix.m22_);
  159. Vector3 absViewZ = viewZ.Abs();
  160. unsigned cameraViewMask = view->camera_->GetViewMask();
  161. bool cameraZoneOverride = view->cameraZoneOverride_;
  162. PerThreadSceneResult& result = view->sceneResults_[threadIndex];
  163. while (start != end)
  164. {
  165. Drawable* drawable = *start++;
  166. bool batchesUpdated = false;
  167. // If draw distance non-zero, update and check it
  168. float maxDistance = drawable->GetDrawDistance();
  169. if (maxDistance > 0.0f)
  170. {
  171. drawable->UpdateBatches(view->frame_);
  172. batchesUpdated = true;
  173. if (drawable->GetDistance() > maxDistance)
  174. continue;
  175. }
  176. if (!buffer || !drawable->IsOccludee() || buffer->IsVisible(drawable->GetWorldBoundingBox()))
  177. {
  178. if (!batchesUpdated)
  179. drawable->UpdateBatches(view->frame_);
  180. drawable->MarkInView(view->frame_);
  181. // For geometries, find zone, clear lights and calculate view space Z range
  182. if (drawable->GetDrawableFlags() & DRAWABLE_GEOMETRY)
  183. {
  184. Zone* drawableZone = drawable->GetZone();
  185. if ((!drawableZone || (drawableZone->GetViewMask() & cameraViewMask) == 0) && !cameraZoneOverride)
  186. view->FindZone(drawable);
  187. const BoundingBox& geomBox = drawable->GetWorldBoundingBox();
  188. Vector3 center = geomBox.Center();
  189. float viewCenterZ = viewZ.DotProduct(center) + viewMatrix.m23_;
  190. Vector3 edge = geomBox.Size() * 0.5f;
  191. float viewEdgeZ = absViewZ.DotProduct(edge);
  192. float minZ = viewCenterZ - viewEdgeZ;
  193. float maxZ = viewCenterZ + viewEdgeZ;
  194. drawable->SetMinMaxZ(viewCenterZ - viewEdgeZ, viewCenterZ + viewEdgeZ);
  195. drawable->ClearLights();
  196. // Expand the scene bounding box and Z range (skybox not included because of infinite size) and store the drawawble
  197. if (drawable->GetType() != Skybox::GetTypeStatic())
  198. {
  199. result.minZ_ = Min(result.minZ_, minZ);
  200. result.maxZ_ = Max(result.maxZ_, maxZ);
  201. }
  202. result.geometries_.Push(drawable);
  203. }
  204. else if (drawable->GetDrawableFlags() & DRAWABLE_LIGHT)
  205. {
  206. Light* light = static_cast<Light*>(drawable);
  207. // Skip lights which are so dim that they can not contribute to a rendertarget
  208. if (light->GetColor().SumRGB() > LIGHT_INTENSITY_THRESHOLD)
  209. result.lights_.Push(light);
  210. }
  211. }
  212. }
  213. }
  214. void ProcessLightWork(const WorkItem* item, unsigned threadIndex)
  215. {
  216. View* view = reinterpret_cast<View*>(item->aux_);
  217. LightQueryResult* query = reinterpret_cast<LightQueryResult*>(item->start_);
  218. view->ProcessLight(*query, threadIndex);
  219. }
  220. void UpdateDrawableGeometriesWork(const WorkItem* item, unsigned threadIndex)
  221. {
  222. const FrameInfo& frame = *(reinterpret_cast<FrameInfo*>(item->aux_));
  223. Drawable** start = reinterpret_cast<Drawable**>(item->start_);
  224. Drawable** end = reinterpret_cast<Drawable**>(item->end_);
  225. while (start != end)
  226. {
  227. Drawable* drawable = *start++;
  228. drawable->UpdateGeometry(frame);
  229. }
  230. }
  231. void SortBatchQueueFrontToBackWork(const WorkItem* item, unsigned threadIndex)
  232. {
  233. BatchQueue* queue = reinterpret_cast<BatchQueue*>(item->start_);
  234. queue->SortFrontToBack();
  235. }
  236. void SortBatchQueueBackToFrontWork(const WorkItem* item, unsigned threadIndex)
  237. {
  238. BatchQueue* queue = reinterpret_cast<BatchQueue*>(item->start_);
  239. queue->SortBackToFront();
  240. }
  241. void SortLightQueueWork(const WorkItem* item, unsigned threadIndex)
  242. {
  243. LightBatchQueue* start = reinterpret_cast<LightBatchQueue*>(item->start_);
  244. start->litBatches_.SortFrontToBack();
  245. }
  246. void SortShadowQueueWork(const WorkItem* item, unsigned threadIndex)
  247. {
  248. LightBatchQueue* start = reinterpret_cast<LightBatchQueue*>(item->start_);
  249. for (unsigned i = 0; i < start->shadowSplits_.Size(); ++i)
  250. start->shadowSplits_[i].shadowBatches_.SortFrontToBack();
  251. }
  252. View::View(Context* context) :
  253. Object(context),
  254. graphics_(GetSubsystem<Graphics>()),
  255. renderer_(GetSubsystem<Renderer>()),
  256. scene_(0),
  257. octree_(0),
  258. camera_(0),
  259. cameraZone_(0),
  260. farClipZone_(0),
  261. renderTarget_(0),
  262. substituteRenderTarget_(0)
  263. {
  264. // Create octree query and scene results vector for each thread
  265. unsigned numThreads = GetSubsystem<WorkQueue>()->GetNumThreads() + 1; // Worker threads + main thread
  266. tempDrawables_.Resize(numThreads);
  267. sceneResults_.Resize(numThreads);
  268. frame_.camera_ = 0;
  269. }
  270. View::~View()
  271. {
  272. }
  273. bool View::Define(RenderSurface* renderTarget, Viewport* viewport)
  274. {
  275. Scene* scene = viewport->GetScene();
  276. Camera* camera = viewport->GetCamera();
  277. if (!scene || !camera || !camera->IsEnabledEffective())
  278. return false;
  279. // If scene is loading asynchronously, it is incomplete and should not be rendered
  280. if (scene->IsAsyncLoading())
  281. return false;
  282. Octree* octree = scene->GetComponent<Octree>();
  283. if (!octree)
  284. return false;
  285. // Do not accept view if camera projection is illegal
  286. // (there is a possibility of crash if occlusion is used and it can not clip properly)
  287. if (!camera->IsProjectionValid())
  288. return false;
  289. scene_ = scene;
  290. octree_ = octree;
  291. camera_ = camera;
  292. cameraNode_ = camera->GetNode();
  293. renderTarget_ = renderTarget;
  294. renderPath_ = viewport->GetRenderPath();
  295. gBufferPassName_ = StringHash();
  296. basePassName_ = PASS_BASE;
  297. alphaPassName_ = PASS_ALPHA;
  298. lightPassName_ = PASS_LIGHT;
  299. litBasePassName_ = PASS_LITBASE;
  300. litAlphaPassName_ = PASS_LITALPHA;
  301. // Make sure that all necessary batch queues exist
  302. scenePasses_.Clear();
  303. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  304. {
  305. const RenderPathCommand& command = renderPath_->commands_[i];
  306. if (!command.enabled_)
  307. continue;
  308. if (command.type_ == CMD_SCENEPASS)
  309. {
  310. ScenePassInfo info;
  311. info.pass_ = command.pass_;
  312. info.allowInstancing_ = command.sortMode_ != SORT_BACKTOFRONT;
  313. info.markToStencil_ = command.markToStencil_;
  314. info.useScissor_ = command.useScissor_;
  315. info.vertexLights_ = command.vertexLights_;
  316. // Check scenepass metadata for defining custom passes which interact with lighting
  317. String metadata = command.metadata_.Trimmed().ToLower();
  318. if (!metadata.Empty())
  319. {
  320. if (metadata == "gbuffer")
  321. gBufferPassName_ = command.pass_;
  322. else if (metadata == "base")
  323. {
  324. basePassName_ = command.pass_;
  325. litBasePassName_ = "lit" + command.pass_;
  326. }
  327. else if (metadata == "alpha")
  328. {
  329. alphaPassName_ = command.pass_;
  330. litAlphaPassName_ = "lit" + command.pass_;
  331. }
  332. }
  333. HashMap<StringHash, BatchQueue>::Iterator j = batchQueues_.Find(command.pass_);
  334. if (j == batchQueues_.End())
  335. j = batchQueues_.Insert(Pair<StringHash, BatchQueue>(command.pass_, BatchQueue()));
  336. info.batchQueue_ = &j->second_;
  337. scenePasses_.Push(info);
  338. }
  339. else if (command.type_ == CMD_FORWARDLIGHTS)
  340. {
  341. if (!command.pass_.Trimmed().Empty())
  342. lightPassName_ = command.pass_;
  343. }
  344. }
  345. // Get light volume shaders according to the renderpath, if it needs them
  346. deferred_ = false;
  347. deferredAmbient_ = false;
  348. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  349. {
  350. const RenderPathCommand& command = renderPath_->commands_[i];
  351. if (!command.enabled_)
  352. continue;
  353. // Check if ambient pass and G-buffer rendering happens at the same time
  354. if (command.type_ == CMD_SCENEPASS && command.outputNames_.Size() > 1)
  355. {
  356. if (CheckViewportWrite(command))
  357. deferredAmbient_ = true;
  358. }
  359. if (command.type_ == CMD_LIGHTVOLUMES)
  360. {
  361. renderer_->GetLightVolumeShaders(lightVS_, lightPS_, command.vertexShaderName_, command.pixelShaderName_);
  362. deferred_ = true;
  363. }
  364. }
  365. if (!deferred_)
  366. {
  367. lightVS_.Clear();
  368. lightPS_.Clear();
  369. }
  370. // Validate the rect and calculate size. If zero rect, use whole rendertarget size
  371. int rtWidth = renderTarget ? renderTarget->GetWidth() : graphics_->GetWidth();
  372. int rtHeight = renderTarget ? renderTarget->GetHeight() : graphics_->GetHeight();
  373. const IntRect& rect = viewport->GetRect();
  374. if (rect != IntRect::ZERO)
  375. {
  376. viewRect_.left_ = Clamp(rect.left_, 0, rtWidth - 1);
  377. viewRect_.top_ = Clamp(rect.top_, 0, rtHeight - 1);
  378. viewRect_.right_ = Clamp(rect.right_, viewRect_.left_ + 1, rtWidth);
  379. viewRect_.bottom_ = Clamp(rect.bottom_, viewRect_.top_ + 1, rtHeight);
  380. }
  381. else
  382. viewRect_ = IntRect(0, 0, rtWidth, rtHeight);
  383. viewSize_ = viewRect_.Size();
  384. rtSize_ = IntVector2(rtWidth, rtHeight);
  385. // On OpenGL flip the viewport if rendering to a texture for consistent UV addressing with Direct3D9
  386. #ifdef USE_OPENGL
  387. if (renderTarget_)
  388. {
  389. viewRect_.bottom_ = rtSize_.y_ - viewRect_.top_;
  390. viewRect_.top_ = viewRect_.bottom_ - viewSize_.y_;
  391. }
  392. #endif
  393. drawShadows_ = renderer_->GetDrawShadows();
  394. materialQuality_ = renderer_->GetMaterialQuality();
  395. maxOccluderTriangles_ = renderer_->GetMaxOccluderTriangles();
  396. minInstances_ = renderer_->GetMinInstances();
  397. // Set possible quality overrides from the camera
  398. unsigned viewOverrideFlags = camera_->GetViewOverrideFlags();
  399. if (viewOverrideFlags & VO_LOW_MATERIAL_QUALITY)
  400. materialQuality_ = QUALITY_LOW;
  401. if (viewOverrideFlags & VO_DISABLE_SHADOWS)
  402. drawShadows_ = false;
  403. if (viewOverrideFlags & VO_DISABLE_OCCLUSION)
  404. maxOccluderTriangles_ = 0;
  405. // Occlusion buffer has constant width. If resulting height would be too large due to aspect ratio, disable occlusion
  406. if (viewSize_.y_ > viewSize_.x_ * 4)
  407. maxOccluderTriangles_ = 0;
  408. return true;
  409. }
  410. void View::Update(const FrameInfo& frame)
  411. {
  412. if (!camera_ || !octree_)
  413. return;
  414. frame_.camera_ = camera_;
  415. frame_.timeStep_ = frame.timeStep_;
  416. frame_.frameNumber_ = frame.frameNumber_;
  417. frame_.viewSize_ = viewSize_;
  418. int maxSortedInstances = renderer_->GetMaxSortedInstances();
  419. // Clear buffers, geometry, light, occluder & batch list
  420. renderTargets_.Clear();
  421. geometries_.Clear();
  422. shadowGeometries_.Clear();
  423. lights_.Clear();
  424. zones_.Clear();
  425. occluders_.Clear();
  426. vertexLightQueues_.Clear();
  427. for (HashMap<StringHash, BatchQueue>::Iterator i = batchQueues_.Begin(); i != batchQueues_.End(); ++i)
  428. i->second_.Clear(maxSortedInstances);
  429. // Set automatic aspect ratio if required
  430. if (camera_->GetAutoAspectRatio())
  431. camera_->SetAspectRatio((float)frame_.viewSize_.x_ / (float)frame_.viewSize_.y_);
  432. GetDrawables();
  433. GetBatches();
  434. }
  435. void View::Render()
  436. {
  437. if (!octree_ || !camera_)
  438. return;
  439. // Actually update geometry data now
  440. UpdateGeometries();
  441. // Allocate screen buffers as necessary
  442. AllocateScreenBuffers();
  443. // Forget parameter sources from the previous view
  444. graphics_->ClearParameterSources();
  445. // If stream offset is supported, write all instance transforms to a single large buffer
  446. // Else we must lock the instance buffer for each batch group
  447. if (renderer_->GetDynamicInstancing() && graphics_->GetStreamOffsetSupport())
  448. PrepareInstancingBuffer();
  449. // It is possible, though not recommended, that the same camera is used for multiple main views. Set automatic aspect ratio
  450. // again to ensure correct projection will be used
  451. if (camera_->GetAutoAspectRatio())
  452. camera_->SetAspectRatio((float)(viewSize_.x_) / (float)(viewSize_.y_));
  453. // Bind the face selection and indirection cube maps for point light shadows
  454. if (renderer_->GetDrawShadows())
  455. {
  456. graphics_->SetTexture(TU_FACESELECT, renderer_->GetFaceSelectCubeMap());
  457. graphics_->SetTexture(TU_INDIRECTION, renderer_->GetIndirectionCubeMap());
  458. }
  459. if (renderTarget_)
  460. {
  461. // On OpenGL, flip the projection if rendering to a texture so that the texture can be addressed in the same way
  462. // as a render texture produced on Direct3D9
  463. #ifdef USE_OPENGL
  464. camera_->SetFlipVertical(true);
  465. #endif
  466. }
  467. // Render
  468. ExecuteRenderPathCommands();
  469. #ifdef USE_OPENGL
  470. camera_->SetFlipVertical(false);
  471. #endif
  472. graphics_->SetDepthBias(0.0f, 0.0f);
  473. graphics_->SetScissorTest(false);
  474. graphics_->SetStencilTest(false);
  475. graphics_->ResetStreamFrequencies();
  476. // Run framebuffer blitting if necessary
  477. if (currentRenderTarget_ != renderTarget_)
  478. BlitFramebuffer(static_cast<Texture2D*>(currentRenderTarget_->GetParentTexture()), renderTarget_, true);
  479. // If this is a main view, draw the associated debug geometry now
  480. if (!renderTarget_)
  481. {
  482. DebugRenderer* debug = octree_->GetComponent<DebugRenderer>();
  483. if (debug)
  484. {
  485. debug->SetView(camera_);
  486. debug->Render();
  487. }
  488. }
  489. // "Forget" the scene, camera, octree and zone after rendering
  490. scene_ = 0;
  491. camera_ = 0;
  492. octree_ = 0;
  493. cameraZone_ = 0;
  494. farClipZone_ = 0;
  495. occlusionBuffer_ = 0;
  496. frame_.camera_ = 0;
  497. }
  498. Graphics* View::GetGraphics() const
  499. {
  500. return graphics_;
  501. }
  502. Renderer* View::GetRenderer() const
  503. {
  504. return renderer_;
  505. }
  506. void View::GetDrawables()
  507. {
  508. PROFILE(GetDrawables);
  509. WorkQueue* queue = GetSubsystem<WorkQueue>();
  510. PODVector<Drawable*>& tempDrawables = tempDrawables_[0];
  511. // Get zones and occluders first
  512. {
  513. ZoneOccluderOctreeQuery query(tempDrawables, camera_->GetFrustum(), DRAWABLE_GEOMETRY | DRAWABLE_ZONE, camera_->GetViewMask());
  514. octree_->GetDrawables(query);
  515. }
  516. highestZonePriority_ = M_MIN_INT;
  517. int bestPriority = M_MIN_INT;
  518. Vector3 cameraPos = cameraNode_->GetWorldPosition();
  519. // Get default zone first in case we do not have zones defined
  520. Zone* defaultZone = renderer_->GetDefaultZone();
  521. cameraZone_ = farClipZone_ = defaultZone;
  522. for (PODVector<Drawable*>::ConstIterator i = tempDrawables.Begin(); i != tempDrawables.End(); ++i)
  523. {
  524. Drawable* drawable = *i;
  525. unsigned char flags = drawable->GetDrawableFlags();
  526. if (flags & DRAWABLE_ZONE)
  527. {
  528. Zone* zone = static_cast<Zone*>(drawable);
  529. zones_.Push(zone);
  530. int priority = zone->GetPriority();
  531. if (priority > highestZonePriority_)
  532. highestZonePriority_ = priority;
  533. if (priority > bestPriority && zone->IsInside(cameraPos))
  534. {
  535. cameraZone_ = zone;
  536. bestPriority = priority;
  537. }
  538. }
  539. else
  540. occluders_.Push(drawable);
  541. }
  542. // Determine the zone at far clip distance. If not found, or camera zone has override mode, use camera zone
  543. cameraZoneOverride_ = cameraZone_->GetOverride();
  544. if (!cameraZoneOverride_)
  545. {
  546. Vector3 farClipPos = cameraPos + cameraNode_->GetWorldDirection() * Vector3(0.0f, 0.0f, camera_->GetFarClip());
  547. bestPriority = M_MIN_INT;
  548. for (PODVector<Zone*>::Iterator i = zones_.Begin(); i != zones_.End(); ++i)
  549. {
  550. int priority = (*i)->GetPriority();
  551. if (priority > bestPriority && (*i)->IsInside(farClipPos))
  552. {
  553. farClipZone_ = *i;
  554. bestPriority = priority;
  555. }
  556. }
  557. }
  558. if (farClipZone_ == defaultZone)
  559. farClipZone_ = cameraZone_;
  560. // If occlusion in use, get & render the occluders
  561. occlusionBuffer_ = 0;
  562. if (maxOccluderTriangles_ > 0)
  563. {
  564. UpdateOccluders(occluders_, camera_);
  565. if (occluders_.Size())
  566. {
  567. PROFILE(DrawOcclusion);
  568. occlusionBuffer_ = renderer_->GetOcclusionBuffer(camera_);
  569. DrawOccluders(occlusionBuffer_, occluders_);
  570. }
  571. }
  572. // Get lights and geometries. Coarse occlusion for octants is used at this point
  573. if (occlusionBuffer_)
  574. {
  575. OccludedFrustumOctreeQuery query(tempDrawables, camera_->GetFrustum(), occlusionBuffer_, DRAWABLE_GEOMETRY |
  576. DRAWABLE_LIGHT, camera_->GetViewMask());
  577. octree_->GetDrawables(query);
  578. }
  579. else
  580. {
  581. FrustumOctreeQuery query(tempDrawables, camera_->GetFrustum(), DRAWABLE_GEOMETRY | DRAWABLE_LIGHT,
  582. camera_->GetViewMask());
  583. octree_->GetDrawables(query);
  584. }
  585. // Check drawable occlusion, find zones for moved drawables and collect geometries & lights in worker threads
  586. {
  587. for (unsigned i = 0; i < sceneResults_.Size(); ++i)
  588. {
  589. PerThreadSceneResult& result = sceneResults_[i];
  590. result.geometries_.Clear();
  591. result.lights_.Clear();
  592. result.minZ_ = M_INFINITY;
  593. result.maxZ_ = 0.0f;
  594. }
  595. int numWorkItems = queue->GetNumThreads() + 1; // Worker threads + main thread
  596. int drawablesPerItem = tempDrawables.Size() / numWorkItems;
  597. WorkItem item;
  598. item.workFunction_ = CheckVisibilityWork;
  599. item.aux_ = this;
  600. PODVector<Drawable*>::Iterator start = tempDrawables.Begin();
  601. // Create a work item for each thread
  602. for (int i = 0; i < numWorkItems; ++i)
  603. {
  604. PODVector<Drawable*>::Iterator end = tempDrawables.End();
  605. if (i < numWorkItems - 1 && end - start > drawablesPerItem)
  606. end = start + drawablesPerItem;
  607. item.start_ = &(*start);
  608. item.end_ = &(*end);
  609. queue->AddWorkItem(item);
  610. start = end;
  611. }
  612. queue->Complete(M_MAX_UNSIGNED);
  613. }
  614. // Combine lights, geometries & scene Z range from the threads
  615. geometries_.Clear();
  616. lights_.Clear();
  617. minZ_ = M_INFINITY;
  618. maxZ_ = 0.0f;
  619. if (sceneResults_.Size() > 1)
  620. {
  621. for (unsigned i = 0; i < sceneResults_.Size(); ++i)
  622. {
  623. PerThreadSceneResult& result = sceneResults_[i];
  624. geometries_.Push(result.geometries_);
  625. lights_.Push(result.lights_);
  626. minZ_ = Min(minZ_, result.minZ_);
  627. maxZ_ = Max(maxZ_, result.maxZ_);
  628. }
  629. }
  630. else
  631. {
  632. // If just 1 thread, copy the results directly
  633. PerThreadSceneResult& result = sceneResults_[0];
  634. minZ_ = result.minZ_;
  635. maxZ_ = result.maxZ_;
  636. Swap(geometries_, result.geometries_);
  637. Swap(lights_, result.lights_);
  638. }
  639. if (minZ_ == M_INFINITY)
  640. minZ_ = 0.0f;
  641. // Sort the lights to brightest/closest first
  642. for (unsigned i = 0; i < lights_.Size(); ++i)
  643. {
  644. Light* light = lights_[i];
  645. light->SetIntensitySortValue(camera_->GetDistance(light->GetNode()->GetWorldPosition()));
  646. light->SetLightQueue(0);
  647. }
  648. Sort(lights_.Begin(), lights_.End(), CompareDrawables);
  649. }
  650. void View::GetBatches()
  651. {
  652. WorkQueue* queue = GetSubsystem<WorkQueue>();
  653. PODVector<Light*> vertexLights;
  654. BatchQueue* alphaQueue = batchQueues_.Contains(alphaPassName_) ? &batchQueues_[alphaPassName_] : (BatchQueue*)0;
  655. // Check whether to use the lit base pass optimization
  656. bool useLitBase = true;
  657. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  658. {
  659. const RenderPathCommand& command = renderPath_->commands_[i];
  660. if (command.type_ == CMD_FORWARDLIGHTS)
  661. useLitBase = command.useLitBase_;
  662. }
  663. // Process lit geometries and shadow casters for each light
  664. {
  665. PROFILE(ProcessLights);
  666. lightQueryResults_.Resize(lights_.Size());
  667. WorkItem item;
  668. item.workFunction_ = ProcessLightWork;
  669. item.aux_ = this;
  670. for (unsigned i = 0; i < lightQueryResults_.Size(); ++i)
  671. {
  672. LightQueryResult& query = lightQueryResults_[i];
  673. query.light_ = lights_[i];
  674. item.start_ = &query;
  675. queue->AddWorkItem(item);
  676. }
  677. // Ensure all lights have been processed before proceeding
  678. queue->Complete(M_MAX_UNSIGNED);
  679. }
  680. // Build light queues and lit batches
  681. {
  682. PROFILE(GetLightBatches);
  683. // Preallocate light queues: per-pixel lights which have lit geometries
  684. unsigned numLightQueues = 0;
  685. unsigned usedLightQueues = 0;
  686. for (Vector<LightQueryResult>::ConstIterator i = lightQueryResults_.Begin(); i != lightQueryResults_.End(); ++i)
  687. {
  688. if (!i->light_->GetPerVertex() && i->litGeometries_.Size())
  689. ++numLightQueues;
  690. }
  691. lightQueues_.Resize(numLightQueues);
  692. maxLightsDrawables_.Clear();
  693. unsigned maxSortedInstances = renderer_->GetMaxSortedInstances();
  694. for (Vector<LightQueryResult>::Iterator i = lightQueryResults_.Begin(); i != lightQueryResults_.End(); ++i)
  695. {
  696. LightQueryResult& query = *i;
  697. // If light has no affected geometries, no need to process further
  698. if (query.litGeometries_.Empty())
  699. continue;
  700. Light* light = query.light_;
  701. // Per-pixel light
  702. if (!light->GetPerVertex())
  703. {
  704. unsigned shadowSplits = query.numSplits_;
  705. // Initialize light queue and store it to the light so that it can be found later
  706. LightBatchQueue& lightQueue = lightQueues_[usedLightQueues++];
  707. light->SetLightQueue(&lightQueue);
  708. lightQueue.light_ = light;
  709. lightQueue.shadowMap_ = 0;
  710. lightQueue.litBatches_.Clear(maxSortedInstances);
  711. lightQueue.volumeBatches_.Clear();
  712. // Allocate shadow map now
  713. if (shadowSplits > 0)
  714. {
  715. lightQueue.shadowMap_ = renderer_->GetShadowMap(light, camera_, viewSize_.x_, viewSize_.y_);
  716. // If did not manage to get a shadow map, convert the light to unshadowed
  717. if (!lightQueue.shadowMap_)
  718. shadowSplits = 0;
  719. }
  720. // Setup shadow batch queues
  721. lightQueue.shadowSplits_.Resize(shadowSplits);
  722. for (unsigned j = 0; j < shadowSplits; ++j)
  723. {
  724. ShadowBatchQueue& shadowQueue = lightQueue.shadowSplits_[j];
  725. Camera* shadowCamera = query.shadowCameras_[j];
  726. shadowQueue.shadowCamera_ = shadowCamera;
  727. shadowQueue.nearSplit_ = query.shadowNearSplits_[j];
  728. shadowQueue.farSplit_ = query.shadowFarSplits_[j];
  729. shadowQueue.shadowBatches_.Clear(maxSortedInstances);
  730. // Setup the shadow split viewport and finalize shadow camera parameters
  731. shadowQueue.shadowViewport_ = GetShadowMapViewport(light, j, lightQueue.shadowMap_);
  732. FinalizeShadowCamera(shadowCamera, light, shadowQueue.shadowViewport_, query.shadowCasterBox_[j]);
  733. // Loop through shadow casters
  734. for (PODVector<Drawable*>::ConstIterator k = query.shadowCasters_.Begin() + query.shadowCasterBegin_[j];
  735. k < query.shadowCasters_.Begin() + query.shadowCasterEnd_[j]; ++k)
  736. {
  737. Drawable* drawable = *k;
  738. if (!drawable->IsInView(frame_, false))
  739. {
  740. drawable->MarkInView(frame_, false);
  741. shadowGeometries_.Push(drawable);
  742. }
  743. Zone* zone = GetZone(drawable);
  744. const Vector<SourceBatch>& batches = drawable->GetBatches();
  745. for (unsigned l = 0; l < batches.Size(); ++l)
  746. {
  747. const SourceBatch& srcBatch = batches[l];
  748. Technique* tech = GetTechnique(drawable, srcBatch.material_);
  749. if (!srcBatch.geometry_ || !srcBatch.numWorldTransforms_ || !tech)
  750. continue;
  751. Pass* pass = tech->GetPass(PASS_SHADOW);
  752. // Skip if material has no shadow pass
  753. if (!pass)
  754. continue;
  755. Batch destBatch(srcBatch);
  756. destBatch.pass_ = pass;
  757. destBatch.camera_ = shadowCamera;
  758. destBatch.zone_ = zone;
  759. destBatch.lightQueue_ = &lightQueue;
  760. AddBatchToQueue(shadowQueue.shadowBatches_, destBatch, tech);
  761. }
  762. }
  763. }
  764. // Process lit geometries
  765. for (PODVector<Drawable*>::ConstIterator j = query.litGeometries_.Begin(); j != query.litGeometries_.End(); ++j)
  766. {
  767. Drawable* drawable = *j;
  768. drawable->AddLight(light);
  769. // If drawable limits maximum lights, only record the light, and check maximum count / build batches later
  770. if (!drawable->GetMaxLights())
  771. GetLitBatches(drawable, lightQueue, alphaQueue, useLitBase);
  772. else
  773. maxLightsDrawables_.Insert(drawable);
  774. }
  775. // In deferred modes, store the light volume batch now
  776. if (deferred_)
  777. {
  778. Batch volumeBatch;
  779. volumeBatch.geometry_ = renderer_->GetLightGeometry(light);
  780. volumeBatch.geometryType_ = GEOM_STATIC;
  781. volumeBatch.worldTransform_ = &light->GetVolumeTransform(camera_);
  782. volumeBatch.numWorldTransforms_ = 1;
  783. volumeBatch.overrideView_ = light->GetLightType() == LIGHT_DIRECTIONAL;
  784. volumeBatch.camera_ = camera_;
  785. volumeBatch.lightQueue_ = &lightQueue;
  786. volumeBatch.distance_ = light->GetDistance();
  787. volumeBatch.material_ = 0;
  788. volumeBatch.pass_ = 0;
  789. volumeBatch.zone_ = 0;
  790. renderer_->SetLightVolumeBatchShaders(volumeBatch, lightVS_, lightPS_);
  791. lightQueue.volumeBatches_.Push(volumeBatch);
  792. }
  793. }
  794. // Per-vertex light
  795. else
  796. {
  797. // Add the vertex light to lit drawables. It will be processed later during base pass batch generation
  798. for (PODVector<Drawable*>::ConstIterator j = query.litGeometries_.Begin(); j != query.litGeometries_.End(); ++j)
  799. {
  800. Drawable* drawable = *j;
  801. drawable->AddVertexLight(light);
  802. }
  803. }
  804. }
  805. }
  806. // Process drawables with limited per-pixel light count
  807. if (maxLightsDrawables_.Size())
  808. {
  809. PROFILE(GetMaxLightsBatches);
  810. for (HashSet<Drawable*>::Iterator i = maxLightsDrawables_.Begin(); i != maxLightsDrawables_.End(); ++i)
  811. {
  812. Drawable* drawable = *i;
  813. drawable->LimitLights();
  814. const PODVector<Light*>& lights = drawable->GetLights();
  815. for (unsigned i = 0; i < lights.Size(); ++i)
  816. {
  817. Light* light = lights[i];
  818. // Find the correct light queue again
  819. LightBatchQueue* queue = light->GetLightQueue();
  820. if (queue)
  821. GetLitBatches(drawable, *queue, alphaQueue, useLitBase);
  822. }
  823. }
  824. }
  825. // Build base pass batches
  826. {
  827. PROFILE(GetBaseBatches);
  828. for (PODVector<Drawable*>::ConstIterator i = geometries_.Begin(); i != geometries_.End(); ++i)
  829. {
  830. Drawable* drawable = *i;
  831. Zone* zone = GetZone(drawable);
  832. const Vector<SourceBatch>& batches = drawable->GetBatches();
  833. const PODVector<Light*>& drawableVertexLights = drawable->GetVertexLights();
  834. if (!drawableVertexLights.Empty())
  835. drawable->LimitVertexLights();
  836. for (unsigned j = 0; j < batches.Size(); ++j)
  837. {
  838. const SourceBatch& srcBatch = batches[j];
  839. // Check here if the material refers to a rendertarget texture with camera(s) attached
  840. // Only check this for backbuffer views (null rendertarget)
  841. if (srcBatch.material_ && srcBatch.material_->GetAuxViewFrameNumber() != frame_.frameNumber_ && !renderTarget_)
  842. CheckMaterialForAuxView(srcBatch.material_);
  843. Technique* tech = GetTechnique(drawable, srcBatch.material_);
  844. if (!srcBatch.geometry_ || !srcBatch.numWorldTransforms_ || !tech)
  845. continue;
  846. Batch destBatch(srcBatch);
  847. destBatch.camera_ = camera_;
  848. destBatch.zone_ = zone;
  849. destBatch.isBase_ = true;
  850. destBatch.pass_ = 0;
  851. destBatch.lightMask_ = GetLightMask(drawable);
  852. // Check each of the scene passes
  853. for (unsigned k = 0; k < scenePasses_.Size(); ++k)
  854. {
  855. ScenePassInfo& info = scenePasses_[k];
  856. destBatch.pass_ = tech->GetPass(info.pass_);
  857. if (!destBatch.pass_)
  858. continue;
  859. // Skip forward base pass if the corresponding litbase pass already exists
  860. if (info.pass_ == basePassName_ && j < 32 && drawable->HasBasePass(j))
  861. continue;
  862. if (info.vertexLights_ && !drawableVertexLights.Empty())
  863. {
  864. // For a deferred opaque batch, check if the vertex lights include converted per-pixel lights, and remove
  865. // them to prevent double-lighting
  866. if (deferred_ && destBatch.pass_->GetBlendMode() == BLEND_REPLACE)
  867. {
  868. vertexLights.Clear();
  869. for (unsigned i = 0; i < drawableVertexLights.Size(); ++i)
  870. {
  871. if (drawableVertexLights[i]->GetPerVertex())
  872. vertexLights.Push(drawableVertexLights[i]);
  873. }
  874. }
  875. else
  876. vertexLights = drawableVertexLights;
  877. if (!vertexLights.Empty())
  878. {
  879. // Find a vertex light queue. If not found, create new
  880. unsigned long long hash = GetVertexLightQueueHash(vertexLights);
  881. HashMap<unsigned long long, LightBatchQueue>::Iterator i = vertexLightQueues_.Find(hash);
  882. if (i == vertexLightQueues_.End())
  883. {
  884. i = vertexLightQueues_.Insert(MakePair(hash, LightBatchQueue()));
  885. i->second_.light_ = 0;
  886. i->second_.shadowMap_ = 0;
  887. i->second_.vertexLights_ = vertexLights;
  888. }
  889. destBatch.lightQueue_ = &(i->second_);
  890. }
  891. }
  892. else
  893. destBatch.lightQueue_ = 0;
  894. bool allowInstancing = info.allowInstancing_;
  895. if (allowInstancing && info.markToStencil_ && destBatch.lightMask_ != (zone->GetLightMask() & 0xff))
  896. allowInstancing = false;
  897. AddBatchToQueue(*info.batchQueue_, destBatch, tech, allowInstancing);
  898. }
  899. }
  900. }
  901. }
  902. }
  903. void View::UpdateGeometries()
  904. {
  905. PROFILE(SortAndUpdateGeometry);
  906. WorkQueue* queue = GetSubsystem<WorkQueue>();
  907. // Sort batches
  908. {
  909. WorkItem item;
  910. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  911. {
  912. const RenderPathCommand& command = renderPath_->commands_[i];
  913. if (!IsNecessary(command))
  914. continue;
  915. if (command.type_ == CMD_SCENEPASS)
  916. {
  917. BatchQueue* passQueue = &batchQueues_[command.pass_];
  918. item.workFunction_ = command.sortMode_ == SORT_FRONTTOBACK ? SortBatchQueueFrontToBackWork :
  919. SortBatchQueueBackToFrontWork;
  920. item.start_ = &batchQueues_[command.pass_];
  921. queue->AddWorkItem(item);
  922. }
  923. }
  924. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  925. {
  926. item.workFunction_ = SortLightQueueWork;
  927. item.start_ = &(*i);
  928. queue->AddWorkItem(item);
  929. if (i->shadowSplits_.Size())
  930. {
  931. item.workFunction_ = SortShadowQueueWork;
  932. queue->AddWorkItem(item);
  933. }
  934. }
  935. }
  936. // Update geometries. Split into threaded and non-threaded updates.
  937. {
  938. nonThreadedGeometries_.Clear();
  939. threadedGeometries_.Clear();
  940. for (PODVector<Drawable*>::Iterator i = geometries_.Begin(); i != geometries_.End(); ++i)
  941. {
  942. UpdateGeometryType type = (*i)->GetUpdateGeometryType();
  943. if (type == UPDATE_MAIN_THREAD)
  944. nonThreadedGeometries_.Push(*i);
  945. else if (type == UPDATE_WORKER_THREAD)
  946. threadedGeometries_.Push(*i);
  947. }
  948. for (PODVector<Drawable*>::Iterator i = shadowGeometries_.Begin(); i != shadowGeometries_.End(); ++i)
  949. {
  950. UpdateGeometryType type = (*i)->GetUpdateGeometryType();
  951. if (type == UPDATE_MAIN_THREAD)
  952. nonThreadedGeometries_.Push(*i);
  953. else if (type == UPDATE_WORKER_THREAD)
  954. threadedGeometries_.Push(*i);
  955. }
  956. if (threadedGeometries_.Size())
  957. {
  958. int numWorkItems = queue->GetNumThreads() + 1; // Worker threads + main thread
  959. int drawablesPerItem = threadedGeometries_.Size() / numWorkItems;
  960. WorkItem item;
  961. item.workFunction_ = UpdateDrawableGeometriesWork;
  962. item.aux_ = const_cast<FrameInfo*>(&frame_);
  963. PODVector<Drawable*>::Iterator start = threadedGeometries_.Begin();
  964. for (int i = 0; i < numWorkItems; ++i)
  965. {
  966. PODVector<Drawable*>::Iterator end = threadedGeometries_.End();
  967. if (i < numWorkItems - 1 && end - start > drawablesPerItem)
  968. end = start + drawablesPerItem;
  969. item.start_ = &(*start);
  970. item.end_ = &(*end);
  971. queue->AddWorkItem(item);
  972. start = end;
  973. }
  974. }
  975. // While the work queue is processed, update non-threaded geometries
  976. for (PODVector<Drawable*>::ConstIterator i = nonThreadedGeometries_.Begin(); i != nonThreadedGeometries_.End(); ++i)
  977. (*i)->UpdateGeometry(frame_);
  978. }
  979. // Finally ensure all threaded work has completed
  980. queue->Complete(M_MAX_UNSIGNED);
  981. }
  982. void View::GetLitBatches(Drawable* drawable, LightBatchQueue& lightQueue, BatchQueue* alphaQueue, bool useLitBase)
  983. {
  984. Light* light = lightQueue.light_;
  985. Zone* zone = GetZone(drawable);
  986. const Vector<SourceBatch>& batches = drawable->GetBatches();
  987. bool hasAmbientGradient = zone->GetAmbientGradient() && zone->GetAmbientStartColor() != zone->GetAmbientEndColor();
  988. // Shadows on transparencies can only be rendered if shadow maps are not reused
  989. bool allowTransparentShadows = !renderer_->GetReuseShadowMaps();
  990. bool allowLitBase = useLitBase && light == drawable->GetFirstLight() && drawable->GetVertexLights().Empty() && !hasAmbientGradient;
  991. for (unsigned i = 0; i < batches.Size(); ++i)
  992. {
  993. const SourceBatch& srcBatch = batches[i];
  994. Technique* tech = GetTechnique(drawable, srcBatch.material_);
  995. if (!srcBatch.geometry_ || !srcBatch.numWorldTransforms_ || !tech)
  996. continue;
  997. // Do not create pixel lit forward passes for materials that render into the G-buffer
  998. if (gBufferPassName_.Value() && tech->HasPass(gBufferPassName_))
  999. continue;
  1000. Batch destBatch(srcBatch);
  1001. bool isLitAlpha = false;
  1002. // Check for lit base pass. Because it uses the replace blend mode, it must be ensured to be the first light
  1003. // Also vertex lighting or ambient gradient require the non-lit base pass, so skip in those cases
  1004. if (i < 32 && allowLitBase)
  1005. {
  1006. destBatch.pass_ = tech->GetPass(litBasePassName_);
  1007. if (destBatch.pass_)
  1008. {
  1009. destBatch.isBase_ = true;
  1010. drawable->SetBasePass(i);
  1011. }
  1012. else
  1013. destBatch.pass_ = tech->GetPass(lightPassName_);
  1014. }
  1015. else
  1016. destBatch.pass_ = tech->GetPass(lightPassName_);
  1017. // If no lit pass, check for lit alpha
  1018. if (!destBatch.pass_)
  1019. {
  1020. destBatch.pass_ = tech->GetPass(litAlphaPassName_);
  1021. isLitAlpha = true;
  1022. }
  1023. // Skip if material does not receive light at all
  1024. if (!destBatch.pass_)
  1025. continue;
  1026. destBatch.camera_ = camera_;
  1027. destBatch.lightQueue_ = &lightQueue;
  1028. destBatch.zone_ = zone;
  1029. if (!isLitAlpha)
  1030. AddBatchToQueue(lightQueue.litBatches_, destBatch, tech);
  1031. else if (alphaQueue)
  1032. {
  1033. // Transparent batches can not be instanced
  1034. AddBatchToQueue(*alphaQueue, destBatch, tech, false, allowTransparentShadows);
  1035. }
  1036. }
  1037. }
  1038. void View::ExecuteRenderPathCommands()
  1039. {
  1040. // If not reusing shadowmaps, render all of them first
  1041. if (!renderer_->GetReuseShadowMaps() && renderer_->GetDrawShadows() && !lightQueues_.Empty())
  1042. {
  1043. PROFILE(RenderShadowMaps);
  1044. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1045. {
  1046. if (i->shadowMap_)
  1047. RenderShadowMap(*i);
  1048. }
  1049. }
  1050. {
  1051. PROFILE(ExecuteRenderPath);
  1052. // Set for safety in case of empty renderpath
  1053. currentRenderTarget_ = substituteRenderTarget_ ? substituteRenderTarget_ : renderTarget_;
  1054. currentViewportTexture_ = 0;
  1055. bool viewportModified = false;
  1056. bool isPingponging = false;
  1057. unsigned lastCommandIndex = 0;
  1058. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1059. {
  1060. RenderPathCommand& command = renderPath_->commands_[i];
  1061. if (IsNecessary(command))
  1062. lastCommandIndex = i;
  1063. }
  1064. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1065. {
  1066. RenderPathCommand& command = renderPath_->commands_[i];
  1067. if (!IsNecessary(command))
  1068. continue;
  1069. bool viewportRead = CheckViewportRead(command);
  1070. bool viewportWrite = CheckViewportWrite(command);
  1071. bool beginPingpong = CheckPingpong(i);
  1072. // Has the viewport been modified and will be read as a texture by the current command?
  1073. if (viewportRead && viewportModified)
  1074. {
  1075. // Start pingponging without a blit if already rendering to the substitute render target
  1076. if (currentRenderTarget_ && currentRenderTarget_ == substituteRenderTarget_ && beginPingpong)
  1077. isPingponging = true;
  1078. // If not using pingponging, simply resolve/copy to the first viewport texture
  1079. if (!isPingponging)
  1080. {
  1081. if (!currentRenderTarget_)
  1082. {
  1083. graphics_->ResolveToTexture(viewportTextures_[0], viewRect_);
  1084. currentViewportTexture_ = viewportTextures_[0];
  1085. viewportModified = false;
  1086. }
  1087. else
  1088. {
  1089. if (viewportWrite)
  1090. {
  1091. BlitFramebuffer(static_cast<Texture2D*>(currentRenderTarget_->GetParentTexture()),
  1092. viewportTextures_[0]->GetRenderSurface(), false);
  1093. currentViewportTexture_ = viewportTextures_[0];
  1094. viewportModified = false;
  1095. }
  1096. else
  1097. {
  1098. // If the current render target is already a texture, and we are not writing to it, can read that
  1099. // texture directly instead of blitting. However keep the viewport dirty flag in case a later command
  1100. // will do both read and write, and then we need to blit / resolve
  1101. currentViewportTexture_ = static_cast<Texture2D*>(currentRenderTarget_->GetParentTexture());
  1102. }
  1103. }
  1104. }
  1105. else
  1106. {
  1107. // Swap the pingpong double buffer sides. Texture 0 will be read next
  1108. viewportTextures_[1] = viewportTextures_[0];
  1109. viewportTextures_[0] = static_cast<Texture2D*>(currentRenderTarget_->GetParentTexture());
  1110. currentViewportTexture_ = viewportTextures_[0];
  1111. viewportModified = false;
  1112. }
  1113. }
  1114. if (beginPingpong)
  1115. isPingponging = true;
  1116. // Determine viewport write target
  1117. if (viewportWrite)
  1118. {
  1119. if (isPingponging)
  1120. {
  1121. currentRenderTarget_ = viewportTextures_[1]->GetRenderSurface();
  1122. // If the render path ends into a quad, it can be redirected to the final render target
  1123. if (i == lastCommandIndex && command.type_ == CMD_QUAD)
  1124. currentRenderTarget_ = renderTarget_;
  1125. }
  1126. else
  1127. currentRenderTarget_ = substituteRenderTarget_ ? substituteRenderTarget_ : renderTarget_;
  1128. }
  1129. switch (command.type_)
  1130. {
  1131. case CMD_CLEAR:
  1132. {
  1133. PROFILE(ClearRenderTarget);
  1134. Color clearColor = command.clearColor_;
  1135. if (command.useFogColor_)
  1136. clearColor = farClipZone_->GetFogColor();
  1137. SetRenderTargets(command);
  1138. graphics_->Clear(command.clearFlags_, clearColor, command.clearDepth_, command.clearStencil_);
  1139. }
  1140. break;
  1141. case CMD_SCENEPASS:
  1142. if (!batchQueues_[command.pass_].IsEmpty())
  1143. {
  1144. PROFILE(RenderScenePass);
  1145. SetRenderTargets(command);
  1146. SetTextures(command);
  1147. graphics_->SetFillMode(camera_->GetFillMode());
  1148. graphics_->SetClipPlane(camera_->GetUseClipping(), camera_->GetClipPlane(), camera_->GetView(), camera_->GetProjection());
  1149. batchQueues_[command.pass_].Draw(this, command.useScissor_, command.markToStencil_);
  1150. }
  1151. break;
  1152. case CMD_QUAD:
  1153. {
  1154. PROFILE(RenderQuad);
  1155. SetRenderTargets(command);
  1156. SetTextures(command);
  1157. RenderQuad(command);
  1158. }
  1159. break;
  1160. case CMD_FORWARDLIGHTS:
  1161. // Render shadow maps + opaque objects' additive lighting
  1162. if (!lightQueues_.Empty())
  1163. {
  1164. PROFILE(RenderLights);
  1165. SetRenderTargets(command);
  1166. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1167. {
  1168. // If reusing shadowmaps, render each of them before the lit batches
  1169. if (renderer_->GetReuseShadowMaps() && i->shadowMap_)
  1170. {
  1171. RenderShadowMap(*i);
  1172. SetRenderTargets(command);
  1173. }
  1174. SetTextures(command);
  1175. graphics_->SetFillMode(camera_->GetFillMode());
  1176. graphics_->SetClipPlane(camera_->GetUseClipping(), camera_->GetClipPlane(), camera_->GetView(), camera_->GetProjection());
  1177. i->litBatches_.Draw(i->light_, this);
  1178. }
  1179. graphics_->SetScissorTest(false);
  1180. graphics_->SetStencilTest(false);
  1181. }
  1182. break;
  1183. case CMD_LIGHTVOLUMES:
  1184. // Render shadow maps + light volumes
  1185. if (!lightQueues_.Empty())
  1186. {
  1187. PROFILE(RenderLightVolumes);
  1188. SetRenderTargets(command);
  1189. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1190. {
  1191. // If reusing shadowmaps, render each of them before the lit batches
  1192. if (renderer_->GetReuseShadowMaps() && i->shadowMap_)
  1193. {
  1194. RenderShadowMap(*i);
  1195. SetRenderTargets(command);
  1196. }
  1197. SetTextures(command);
  1198. for (unsigned j = 0; j < i->volumeBatches_.Size(); ++j)
  1199. {
  1200. SetupLightVolumeBatch(i->volumeBatches_[j]);
  1201. i->volumeBatches_[j].Draw(this);
  1202. }
  1203. }
  1204. graphics_->SetScissorTest(false);
  1205. graphics_->SetStencilTest(false);
  1206. }
  1207. break;
  1208. default:
  1209. break;
  1210. }
  1211. // If current command output to the viewport, mark it modified
  1212. if (viewportWrite)
  1213. viewportModified = true;
  1214. }
  1215. }
  1216. // After executing all commands, reset rendertarget for debug geometry rendering
  1217. graphics_->SetRenderTarget(0, renderTarget_);
  1218. for (unsigned i = 1; i < MAX_RENDERTARGETS; ++i)
  1219. graphics_->SetRenderTarget(i, (RenderSurface*)0);
  1220. graphics_->SetDepthStencil(GetDepthStencil(renderTarget_));
  1221. graphics_->SetViewport(viewRect_);
  1222. graphics_->SetFillMode(FILL_SOLID);
  1223. graphics_->SetClipPlane(false);
  1224. }
  1225. void View::SetRenderTargets(RenderPathCommand& command)
  1226. {
  1227. unsigned index = 0;
  1228. IntRect viewPort = viewRect_;
  1229. while (index < command.outputNames_.Size())
  1230. {
  1231. if (!command.outputNames_[index].Compare("viewport", false))
  1232. graphics_->SetRenderTarget(index, currentRenderTarget_);
  1233. else
  1234. {
  1235. StringHash nameHash(command.outputNames_[index]);
  1236. if (renderTargets_.Contains(nameHash))
  1237. {
  1238. Texture2D* texture = renderTargets_[nameHash];
  1239. graphics_->SetRenderTarget(index, texture);
  1240. if (!index)
  1241. {
  1242. // Determine viewport size from rendertarget info
  1243. for (unsigned i = 0; i < renderPath_->renderTargets_.Size(); ++i)
  1244. {
  1245. const RenderTargetInfo& info = renderPath_->renderTargets_[i];
  1246. if (!info.name_.Compare(command.outputNames_[index], false))
  1247. {
  1248. switch (info.sizeMode_)
  1249. {
  1250. // If absolute or a divided viewport size, use the full texture
  1251. case SIZE_ABSOLUTE:
  1252. case SIZE_VIEWPORTDIVISOR:
  1253. viewPort = IntRect(0, 0, texture->GetWidth(), texture->GetHeight());
  1254. break;
  1255. // If a divided rendertarget size, retain the same viewport, but scaled
  1256. case SIZE_RENDERTARGETDIVISOR:
  1257. if (info.size_.x_ && info.size_.y_)
  1258. {
  1259. viewPort = IntRect(viewRect_.left_ / info.size_.x_, viewRect_.top_ / info.size_.y_,
  1260. viewRect_.right_ / info.size_.x_, viewRect_.bottom_ / info.size_.y_);
  1261. }
  1262. break;
  1263. }
  1264. break;
  1265. }
  1266. }
  1267. }
  1268. }
  1269. else
  1270. graphics_->SetRenderTarget(0, (RenderSurface*)0);
  1271. }
  1272. ++index;
  1273. }
  1274. while (index < MAX_RENDERTARGETS)
  1275. {
  1276. graphics_->SetRenderTarget(index, (RenderSurface*)0);
  1277. ++index;
  1278. }
  1279. graphics_->SetDepthStencil(GetDepthStencil(graphics_->GetRenderTarget(0)));
  1280. graphics_->SetViewport(viewPort);
  1281. graphics_->SetColorWrite(true);
  1282. }
  1283. void View::SetTextures(RenderPathCommand& command)
  1284. {
  1285. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1286. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1287. {
  1288. if (command.textureNames_[i].Empty())
  1289. continue;
  1290. // Bind the rendered output
  1291. if (!command.textureNames_[i].Compare("viewport", false))
  1292. {
  1293. graphics_->SetTexture(i, currentViewportTexture_);
  1294. continue;
  1295. }
  1296. // Bind a rendertarget
  1297. HashMap<StringHash, Texture2D*>::ConstIterator j = renderTargets_.Find(command.textureNames_[i]);
  1298. if (j != renderTargets_.End())
  1299. {
  1300. graphics_->SetTexture(i, j->second_);
  1301. continue;
  1302. }
  1303. // Bind a texture from the resource system
  1304. Texture* texture;
  1305. // Detect cube/3D textures by file extension: they are defined by an XML file
  1306. if (GetExtension(command.textureNames_[i]) == ".xml")
  1307. {
  1308. // Assume 3D textures are only bound to the volume map unit, otherwise it's a cube texture
  1309. if (i == TU_VOLUMEMAP)
  1310. texture = cache->GetResource<Texture3D>(command.textureNames_[i]);
  1311. else
  1312. texture = cache->GetResource<TextureCube>(command.textureNames_[i]);
  1313. }
  1314. else
  1315. texture = cache->GetResource<Texture2D>(command.textureNames_[i]);
  1316. if (texture)
  1317. graphics_->SetTexture(i, texture);
  1318. else
  1319. {
  1320. // If requesting a texture fails, clear the texture name to prevent redundant attempts
  1321. command.textureNames_[i] = String::EMPTY;
  1322. }
  1323. }
  1324. }
  1325. void View::RenderQuad(RenderPathCommand& command)
  1326. {
  1327. // If shader can not be found, clear it from the command to prevent redundant attempts
  1328. ShaderVariation* vs = renderer_->GetVertexShader(command.vertexShaderName_);
  1329. if (!vs)
  1330. command.vertexShaderName_ = String::EMPTY;
  1331. ShaderVariation* ps = renderer_->GetPixelShader(command.pixelShaderName_);
  1332. if (!ps)
  1333. command.pixelShaderName_ = String::EMPTY;
  1334. // Set shaders & shader parameters and textures
  1335. graphics_->SetShaders(vs, ps);
  1336. const HashMap<StringHash, Variant>& parameters = command.shaderParameters_;
  1337. for (HashMap<StringHash, Variant>::ConstIterator k = parameters.Begin(); k != parameters.End(); ++k)
  1338. graphics_->SetShaderParameter(k->first_, k->second_);
  1339. graphics_->SetShaderParameter(VSP_DELTATIME, frame_.timeStep_);
  1340. graphics_->SetShaderParameter(PSP_DELTATIME, frame_.timeStep_);
  1341. float nearClip = camera_->GetNearClip();
  1342. float farClip = camera_->GetFarClip();
  1343. graphics_->SetShaderParameter(VSP_NEARCLIP, nearClip);
  1344. graphics_->SetShaderParameter(VSP_FARCLIP, farClip);
  1345. graphics_->SetShaderParameter(PSP_NEARCLIP, nearClip);
  1346. graphics_->SetShaderParameter(PSP_FARCLIP, farClip);
  1347. float rtWidth = (float)rtSize_.x_;
  1348. float rtHeight = (float)rtSize_.y_;
  1349. float widthRange = 0.5f * viewSize_.x_ / rtWidth;
  1350. float heightRange = 0.5f * viewSize_.y_ / rtHeight;
  1351. #ifdef USE_OPENGL
  1352. Vector4 bufferUVOffset(((float)viewRect_.left_) / rtWidth + widthRange,
  1353. 1.0f - (((float)viewRect_.top_) / rtHeight + heightRange), widthRange, heightRange);
  1354. #else
  1355. Vector4 bufferUVOffset((0.5f + (float)viewRect_.left_) / rtWidth + widthRange,
  1356. (0.5f + (float)viewRect_.top_) / rtHeight + heightRange, widthRange, heightRange);
  1357. #endif
  1358. graphics_->SetShaderParameter(VSP_GBUFFEROFFSETS, bufferUVOffset);
  1359. graphics_->SetShaderParameter(PSP_GBUFFERINVSIZE, Vector4(1.0f / rtWidth, 1.0f / rtHeight, 0.0f, 0.0f));
  1360. // Set per-rendertarget inverse size / offset shader parameters as necessary
  1361. for (unsigned i = 0; i < renderPath_->renderTargets_.Size(); ++i)
  1362. {
  1363. const RenderTargetInfo& rtInfo = renderPath_->renderTargets_[i];
  1364. if (!rtInfo.enabled_)
  1365. continue;
  1366. StringHash nameHash(rtInfo.name_);
  1367. if (!renderTargets_.Contains(nameHash))
  1368. continue;
  1369. String invSizeName = rtInfo.name_ + "InvSize";
  1370. String offsetsName = rtInfo.name_ + "Offsets";
  1371. float width = (float)renderTargets_[nameHash]->GetWidth();
  1372. float height = (float)renderTargets_[nameHash]->GetHeight();
  1373. graphics_->SetShaderParameter(invSizeName, Vector4(1.0f / width, 1.0f / height, 0.0f, 0.0f));
  1374. #ifdef USE_OPENGL
  1375. graphics_->SetShaderParameter(offsetsName, Vector4::ZERO);
  1376. #else
  1377. graphics_->SetShaderParameter(offsetsName, Vector4(0.5f / width, 0.5f / height, 0.0f, 0.0f));
  1378. #endif
  1379. }
  1380. graphics_->SetBlendMode(BLEND_REPLACE);
  1381. graphics_->SetDepthTest(CMP_ALWAYS);
  1382. graphics_->SetDepthWrite(false);
  1383. graphics_->SetFillMode(FILL_SOLID);
  1384. graphics_->SetClipPlane(false);
  1385. graphics_->SetScissorTest(false);
  1386. graphics_->SetStencilTest(false);
  1387. DrawFullscreenQuad(false);
  1388. }
  1389. bool View::IsNecessary(const RenderPathCommand& command)
  1390. {
  1391. return command.enabled_ && command.outputNames_.Size() && (command.type_ != CMD_SCENEPASS ||
  1392. !batchQueues_[command.pass_].IsEmpty());
  1393. }
  1394. bool View::CheckViewportRead(const RenderPathCommand& command)
  1395. {
  1396. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1397. {
  1398. if (!command.textureNames_[i].Empty() && !command.textureNames_[i].Compare("viewport", false))
  1399. return true;
  1400. }
  1401. return false;
  1402. }
  1403. bool View::CheckViewportWrite(const RenderPathCommand& command)
  1404. {
  1405. for (unsigned i = 0; i < command.outputNames_.Size(); ++i)
  1406. {
  1407. if (!command.outputNames_[i].Compare("viewport", false))
  1408. return true;
  1409. }
  1410. return false;
  1411. }
  1412. bool View::CheckPingpong(unsigned index)
  1413. {
  1414. // Current command must be a viewport-writing quad to begin the pingpong chain
  1415. RenderPathCommand& current = renderPath_->commands_[index];
  1416. if (current.type_ != CMD_QUAD || !CheckViewportWrite(current))
  1417. return false;
  1418. // If there are commands other than quads that target the viewport, we must keep rendering to the final target and resolving
  1419. // to a viewport texture when necessary instead of pingponging, as a scene pass is not guaranteed to fill the entire viewport
  1420. for (unsigned i = index + 1; i < renderPath_->commands_.Size(); ++i)
  1421. {
  1422. RenderPathCommand& command = renderPath_->commands_[i];
  1423. if (!IsNecessary(command))
  1424. continue;
  1425. if (CheckViewportWrite(command))
  1426. {
  1427. if (command.type_ != CMD_QUAD)
  1428. return false;
  1429. }
  1430. }
  1431. return true;
  1432. }
  1433. void View::AllocateScreenBuffers()
  1434. {
  1435. bool needSubstitute = false;
  1436. unsigned numViewportTextures = 0;
  1437. #ifdef USE_OPENGL
  1438. // Due to FBO limitations, in OpenGL deferred modes need to render to texture first and then blit to the backbuffer
  1439. // Also, if rendering to a texture with full deferred rendering, it must be RGBA to comply with the rest of the buffers.
  1440. if ((deferred_ && !renderTarget_) || (deferredAmbient_ && renderTarget_ && renderTarget_->GetParentTexture()->GetFormat() !=
  1441. Graphics::GetRGBAFormat()))
  1442. needSubstitute = true;
  1443. #endif
  1444. // If backbuffer is antialiased when using deferred rendering, need to reserve a buffer
  1445. if (deferred_ && !renderTarget_ && graphics_->GetMultiSample() > 1)
  1446. needSubstitute = true;
  1447. // Follow final rendertarget format, or use RGB to match the backbuffer format
  1448. unsigned format = renderTarget_ ? renderTarget_->GetParentTexture()->GetFormat() : Graphics::GetRGBFormat();
  1449. // If HDR rendering is enabled use RGBA16f and reserve a buffer
  1450. bool hdrRendering = renderer_->GetHDRRendering();
  1451. if (renderer_->GetHDRRendering())
  1452. {
  1453. format = Graphics::GetRGBAFloat16Format();
  1454. needSubstitute = true;
  1455. }
  1456. #ifdef USE_OPENGL
  1457. if (deferred_ && !hdrRendering)
  1458. format = Graphics::GetRGBAFormat();
  1459. #endif
  1460. // Check for commands which read the viewport, or pingpong between viewport textures
  1461. bool hasViewportRead = false;
  1462. bool hasPingpong = false;
  1463. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1464. {
  1465. const RenderPathCommand& command = renderPath_->commands_[i];
  1466. if (!IsNecessary(command))
  1467. continue;
  1468. if (CheckViewportRead(command))
  1469. hasViewportRead = true;
  1470. if (!hasPingpong && CheckPingpong(i))
  1471. hasPingpong = true;
  1472. }
  1473. if (hasViewportRead)
  1474. {
  1475. ++numViewportTextures;
  1476. // If OpenGL ES, use substitute target to avoid resolve from the backbuffer, which may be slow. However if multisampling
  1477. // is specified, there is no choice
  1478. #ifdef GL_ES_VERSION_2_0
  1479. if (!renderTarget_ && graphics_->GetMultiSample() < 2)
  1480. needSubstitute = true;
  1481. #endif
  1482. // If we have viewport read and target is a cube map, must allocate a substitute target instead as BlitFramebuffer()
  1483. // does not support reading a cube map
  1484. if (renderTarget_ && renderTarget_->GetParentTexture()->GetType() == TextureCube::GetTypeStatic())
  1485. needSubstitute = true;
  1486. if (hasPingpong && !needSubstitute)
  1487. ++numViewportTextures;
  1488. }
  1489. // Allocate screen buffers with filtering active in case the quad commands need that
  1490. // Follow the sRGB mode of the destination render target
  1491. bool sRGB = renderTarget_ ? renderTarget_->GetParentTexture()->GetSRGB() : graphics_->GetSRGB();
  1492. if (needSubstitute)
  1493. {
  1494. substituteRenderTarget_ = needSubstitute ?
  1495. renderer_->GetScreenBuffer(rtSize_.x_, rtSize_.y_, format, true, sRGB)->GetRenderSurface() : (RenderSurface*)0;
  1496. }
  1497. for (unsigned i = 0; i < MAX_VIEWPORT_TEXTURES; ++i)
  1498. {
  1499. viewportTextures_[i] = i < numViewportTextures ? renderer_->GetScreenBuffer(rtSize_.x_, rtSize_.y_, format, true, sRGB) :
  1500. (Texture2D*)0;
  1501. }
  1502. // If using a substitute render target and pingponging, the substitute can act as the second viewport texture
  1503. if (numViewportTextures == 1 && substituteRenderTarget_)
  1504. viewportTextures_[1] = static_cast<Texture2D*>(substituteRenderTarget_->GetParentTexture());
  1505. // Allocate extra render targets defined by the rendering path
  1506. for (unsigned i = 0; i < renderPath_->renderTargets_.Size(); ++i)
  1507. {
  1508. const RenderTargetInfo& rtInfo = renderPath_->renderTargets_[i];
  1509. if (!rtInfo.enabled_)
  1510. continue;
  1511. unsigned width = rtInfo.size_.x_;
  1512. unsigned height = rtInfo.size_.y_;
  1513. if (rtInfo.sizeMode_ == SIZE_VIEWPORTDIVISOR)
  1514. {
  1515. width = viewSize_.x_ / (width ? width : 1);
  1516. height = viewSize_.y_ / (height ? height : 1);
  1517. }
  1518. if (rtInfo.sizeMode_ == SIZE_RENDERTARGETDIVISOR)
  1519. {
  1520. width = rtSize_.x_ / (width ? width : 1);
  1521. height = rtSize_.y_ / (height ? height : 1);
  1522. }
  1523. renderTargets_[rtInfo.name_] = renderer_->GetScreenBuffer(width, height, rtInfo.format_, rtInfo.filtered_, rtInfo.sRGB_);
  1524. }
  1525. }
  1526. void View::BlitFramebuffer(Texture2D* source, RenderSurface* destination, bool depthWrite)
  1527. {
  1528. if (!source)
  1529. return;
  1530. PROFILE(BlitFramebuffer);
  1531. graphics_->SetBlendMode(BLEND_REPLACE);
  1532. graphics_->SetDepthTest(CMP_ALWAYS);
  1533. graphics_->SetDepthWrite(depthWrite);
  1534. graphics_->SetFillMode(FILL_SOLID);
  1535. graphics_->SetClipPlane(false);
  1536. graphics_->SetScissorTest(false);
  1537. graphics_->SetStencilTest(false);
  1538. graphics_->SetRenderTarget(0, destination);
  1539. for (unsigned i = 1; i < MAX_RENDERTARGETS; ++i)
  1540. graphics_->SetRenderTarget(i, (RenderSurface*)0);
  1541. graphics_->SetDepthStencil(GetDepthStencil(destination));
  1542. graphics_->SetViewport(viewRect_);
  1543. String shaderName = "CopyFramebuffer";
  1544. graphics_->SetShaders(renderer_->GetVertexShader(shaderName), renderer_->GetPixelShader(shaderName));
  1545. float rtWidth = (float)rtSize_.x_;
  1546. float rtHeight = (float)rtSize_.y_;
  1547. float widthRange = 0.5f * viewSize_.x_ / rtWidth;
  1548. float heightRange = 0.5f * viewSize_.y_ / rtHeight;
  1549. #ifdef USE_OPENGL
  1550. Vector4 bufferUVOffset(((float)viewRect_.left_) / rtWidth + widthRange,
  1551. 1.0f - (((float)viewRect_.top_) / rtHeight + heightRange), widthRange, heightRange);
  1552. #else
  1553. Vector4 bufferUVOffset((0.5f + (float)viewRect_.left_) / rtWidth + widthRange,
  1554. (0.5f + (float)viewRect_.top_) / rtHeight + heightRange, widthRange, heightRange);
  1555. #endif
  1556. graphics_->SetShaderParameter(VSP_GBUFFEROFFSETS, bufferUVOffset);
  1557. graphics_->SetTexture(TU_DIFFUSE, source);
  1558. DrawFullscreenQuad(false);
  1559. }
  1560. void View::DrawFullscreenQuad(bool nearQuad)
  1561. {
  1562. Light* quadDirLight = renderer_->GetQuadDirLight();
  1563. Geometry* geometry = renderer_->GetLightGeometry(quadDirLight);
  1564. Matrix3x4 model = Matrix3x4::IDENTITY;
  1565. Matrix4 projection = Matrix4::IDENTITY;
  1566. #ifdef USE_OPENGL
  1567. if (camera_->GetFlipVertical())
  1568. projection.m11_ = -1.0f;
  1569. model.m23_ = nearQuad ? -1.0f : 1.0f;
  1570. #else
  1571. model.m23_ = nearQuad ? 0.0f : 1.0f;
  1572. #endif
  1573. graphics_->SetCullMode(CULL_NONE);
  1574. graphics_->SetShaderParameter(VSP_MODEL, model);
  1575. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  1576. graphics_->ClearTransformSources();
  1577. geometry->Draw(graphics_);
  1578. }
  1579. void View::UpdateOccluders(PODVector<Drawable*>& occluders, Camera* camera)
  1580. {
  1581. float occluderSizeThreshold_ = renderer_->GetOccluderSizeThreshold();
  1582. float halfViewSize = camera->GetHalfViewSize();
  1583. float invOrthoSize = 1.0f / camera->GetOrthoSize();
  1584. for (PODVector<Drawable*>::Iterator i = occluders.Begin(); i != occluders.End();)
  1585. {
  1586. Drawable* occluder = *i;
  1587. bool erase = false;
  1588. if (!occluder->IsInView(frame_, false))
  1589. occluder->UpdateBatches(frame_);
  1590. // Check occluder's draw distance (in main camera view)
  1591. float maxDistance = occluder->GetDrawDistance();
  1592. if (maxDistance <= 0.0f || occluder->GetDistance() <= maxDistance)
  1593. {
  1594. // Check that occluder is big enough on the screen
  1595. const BoundingBox& box = occluder->GetWorldBoundingBox();
  1596. float diagonal = box.Size().Length();
  1597. float compare;
  1598. if (!camera->IsOrthographic())
  1599. compare = diagonal * halfViewSize / occluder->GetDistance();
  1600. else
  1601. compare = diagonal * invOrthoSize;
  1602. if (compare < occluderSizeThreshold_)
  1603. erase = true;
  1604. else
  1605. {
  1606. // Store amount of triangles divided by screen size as a sorting key
  1607. // (best occluders are big and have few triangles)
  1608. occluder->SetSortValue((float)occluder->GetNumOccluderTriangles() / compare);
  1609. }
  1610. }
  1611. else
  1612. erase = true;
  1613. if (erase)
  1614. i = occluders.Erase(i);
  1615. else
  1616. ++i;
  1617. }
  1618. // Sort occluders so that if triangle budget is exceeded, best occluders have been drawn
  1619. if (occluders.Size())
  1620. Sort(occluders.Begin(), occluders.End(), CompareDrawables);
  1621. }
  1622. void View::DrawOccluders(OcclusionBuffer* buffer, const PODVector<Drawable*>& occluders)
  1623. {
  1624. buffer->SetMaxTriangles(maxOccluderTriangles_);
  1625. buffer->Clear();
  1626. for (unsigned i = 0; i < occluders.Size(); ++i)
  1627. {
  1628. Drawable* occluder = occluders[i];
  1629. if (i > 0)
  1630. {
  1631. // For subsequent occluders, do a test against the pixel-level occlusion buffer to see if rendering is necessary
  1632. if (!buffer->IsVisible(occluder->GetWorldBoundingBox()))
  1633. continue;
  1634. }
  1635. // Check for running out of triangles
  1636. if (!occluder->DrawOcclusion(buffer))
  1637. break;
  1638. }
  1639. buffer->BuildDepthHierarchy();
  1640. }
  1641. void View::ProcessLight(LightQueryResult& query, unsigned threadIndex)
  1642. {
  1643. Light* light = query.light_;
  1644. LightType type = light->GetLightType();
  1645. const Frustum& frustum = camera_->GetFrustum();
  1646. // Check if light should be shadowed
  1647. bool isShadowed = drawShadows_ && light->GetCastShadows() && !light->GetPerVertex() && light->GetShadowIntensity() < 1.0f;
  1648. // If shadow distance non-zero, check it
  1649. if (isShadowed && light->GetShadowDistance() > 0.0f && light->GetDistance() > light->GetShadowDistance())
  1650. isShadowed = false;
  1651. // OpenGL ES can not support point light shadows
  1652. #ifdef GL_ES_VERSION_2_0
  1653. if (isShadowed && type == LIGHT_POINT)
  1654. isShadowed = false;
  1655. #endif
  1656. // Get lit geometries. They must match the light mask and be inside the main camera frustum to be considered
  1657. PODVector<Drawable*>& tempDrawables = tempDrawables_[threadIndex];
  1658. query.litGeometries_.Clear();
  1659. switch (type)
  1660. {
  1661. case LIGHT_DIRECTIONAL:
  1662. for (unsigned i = 0; i < geometries_.Size(); ++i)
  1663. {
  1664. if (GetLightMask(geometries_[i]) & light->GetLightMask())
  1665. query.litGeometries_.Push(geometries_[i]);
  1666. }
  1667. break;
  1668. case LIGHT_SPOT:
  1669. {
  1670. FrustumOctreeQuery octreeQuery(tempDrawables, light->GetFrustum(), DRAWABLE_GEOMETRY, camera_->GetViewMask());
  1671. octree_->GetDrawables(octreeQuery);
  1672. for (unsigned i = 0; i < tempDrawables.Size(); ++i)
  1673. {
  1674. if (tempDrawables[i]->IsInView(frame_) && (GetLightMask(tempDrawables[i]) & light->GetLightMask()))
  1675. query.litGeometries_.Push(tempDrawables[i]);
  1676. }
  1677. }
  1678. break;
  1679. case LIGHT_POINT:
  1680. {
  1681. SphereOctreeQuery octreeQuery(tempDrawables, Sphere(light->GetNode()->GetWorldPosition(), light->GetRange()),
  1682. DRAWABLE_GEOMETRY, camera_->GetViewMask());
  1683. octree_->GetDrawables(octreeQuery);
  1684. for (unsigned i = 0; i < tempDrawables.Size(); ++i)
  1685. {
  1686. if (tempDrawables[i]->IsInView(frame_) && (GetLightMask(tempDrawables[i]) & light->GetLightMask()))
  1687. query.litGeometries_.Push(tempDrawables[i]);
  1688. }
  1689. }
  1690. break;
  1691. }
  1692. // If no lit geometries or not shadowed, no need to process shadow cameras
  1693. if (query.litGeometries_.Empty() || !isShadowed)
  1694. {
  1695. query.numSplits_ = 0;
  1696. return;
  1697. }
  1698. // Determine number of shadow cameras and setup their initial positions
  1699. SetupShadowCameras(query);
  1700. // Process each split for shadow casters
  1701. query.shadowCasters_.Clear();
  1702. for (unsigned i = 0; i < query.numSplits_; ++i)
  1703. {
  1704. Camera* shadowCamera = query.shadowCameras_[i];
  1705. const Frustum& shadowCameraFrustum = shadowCamera->GetFrustum();
  1706. query.shadowCasterBegin_[i] = query.shadowCasterEnd_[i] = query.shadowCasters_.Size();
  1707. // For point light check that the face is visible: if not, can skip the split
  1708. if (type == LIGHT_POINT && frustum.IsInsideFast(BoundingBox(shadowCameraFrustum)) == OUTSIDE)
  1709. continue;
  1710. // For directional light check that the split is inside the visible scene: if not, can skip the split
  1711. if (type == LIGHT_DIRECTIONAL)
  1712. {
  1713. if (minZ_ > query.shadowFarSplits_[i])
  1714. continue;
  1715. if (maxZ_ < query.shadowNearSplits_[i])
  1716. continue;
  1717. // Reuse lit geometry query for all except directional lights
  1718. ShadowCasterOctreeQuery query(tempDrawables, shadowCameraFrustum, DRAWABLE_GEOMETRY,
  1719. camera_->GetViewMask());
  1720. octree_->GetDrawables(query);
  1721. }
  1722. // Check which shadow casters actually contribute to the shadowing
  1723. ProcessShadowCasters(query, tempDrawables, i);
  1724. }
  1725. // If no shadow casters, the light can be rendered unshadowed. At this point we have not allocated a shadow map yet, so the
  1726. // only cost has been the shadow camera setup & queries
  1727. if (query.shadowCasters_.Empty())
  1728. query.numSplits_ = 0;
  1729. }
  1730. void View::ProcessShadowCasters(LightQueryResult& query, const PODVector<Drawable*>& drawables, unsigned splitIndex)
  1731. {
  1732. Light* light = query.light_;
  1733. Camera* shadowCamera = query.shadowCameras_[splitIndex];
  1734. const Frustum& shadowCameraFrustum = shadowCamera->GetFrustum();
  1735. const Matrix3x4& lightView = shadowCamera->GetView();
  1736. const Matrix4& lightProj = shadowCamera->GetProjection();
  1737. LightType type = light->GetLightType();
  1738. query.shadowCasterBox_[splitIndex].defined_ = false;
  1739. // Transform scene frustum into shadow camera's view space for shadow caster visibility check. For point & spot lights,
  1740. // we can use the whole scene frustum. For directional lights, use the intersection of the scene frustum and the split
  1741. // frustum, so that shadow casters do not get rendered into unnecessary splits
  1742. Frustum lightViewFrustum;
  1743. if (type != LIGHT_DIRECTIONAL)
  1744. lightViewFrustum = camera_->GetSplitFrustum(minZ_, maxZ_).Transformed(lightView);
  1745. else
  1746. lightViewFrustum = camera_->GetSplitFrustum(Max(minZ_, query.shadowNearSplits_[splitIndex]),
  1747. Min(maxZ_, query.shadowFarSplits_[splitIndex])).Transformed(lightView);
  1748. BoundingBox lightViewFrustumBox(lightViewFrustum);
  1749. // Check for degenerate split frustum: in that case there is no need to get shadow casters
  1750. if (lightViewFrustum.vertices_[0] == lightViewFrustum.vertices_[4])
  1751. return;
  1752. BoundingBox lightViewBox;
  1753. BoundingBox lightProjBox;
  1754. for (PODVector<Drawable*>::ConstIterator i = drawables.Begin(); i != drawables.End(); ++i)
  1755. {
  1756. Drawable* drawable = *i;
  1757. // In case this is a point or spot light query result reused for optimization, we may have non-shadowcasters included.
  1758. // Check for that first
  1759. if (!drawable->GetCastShadows())
  1760. continue;
  1761. // Check shadow mask
  1762. if (!(GetShadowMask(drawable) & light->GetLightMask()))
  1763. continue;
  1764. // For point light, check that this drawable is inside the split shadow camera frustum
  1765. if (type == LIGHT_POINT && shadowCameraFrustum.IsInsideFast(drawable->GetWorldBoundingBox()) == OUTSIDE)
  1766. continue;
  1767. // Check shadow distance
  1768. float maxShadowDistance = drawable->GetShadowDistance();
  1769. float drawDistance = drawable->GetDrawDistance();
  1770. bool batchesUpdated = drawable->IsInView(frame_, false);
  1771. if (drawDistance > 0.0f && (maxShadowDistance <= 0.0f || drawDistance < maxShadowDistance))
  1772. maxShadowDistance = drawDistance;
  1773. if (maxShadowDistance > 0.0f)
  1774. {
  1775. if (!batchesUpdated)
  1776. {
  1777. drawable->UpdateBatches(frame_);
  1778. batchesUpdated = true;
  1779. }
  1780. if (drawable->GetDistance() > maxShadowDistance)
  1781. continue;
  1782. }
  1783. // Note: as lights are processed threaded, it is possible a drawable's UpdateBatches() function is called several
  1784. // times. However, this should not cause problems as no scene modification happens at this point.
  1785. if (!batchesUpdated)
  1786. drawable->UpdateBatches(frame_);
  1787. // Project shadow caster bounding box to light view space for visibility check
  1788. lightViewBox = drawable->GetWorldBoundingBox().Transformed(lightView);
  1789. if (IsShadowCasterVisible(drawable, lightViewBox, shadowCamera, lightView, lightViewFrustum, lightViewFrustumBox))
  1790. {
  1791. // Merge to shadow caster bounding box and add to the list
  1792. if (type == LIGHT_DIRECTIONAL)
  1793. query.shadowCasterBox_[splitIndex].Merge(lightViewBox);
  1794. else
  1795. {
  1796. lightProjBox = lightViewBox.Projected(lightProj);
  1797. query.shadowCasterBox_[splitIndex].Merge(lightProjBox);
  1798. }
  1799. query.shadowCasters_.Push(drawable);
  1800. }
  1801. }
  1802. query.shadowCasterEnd_[splitIndex] = query.shadowCasters_.Size();
  1803. }
  1804. bool View::IsShadowCasterVisible(Drawable* drawable, BoundingBox lightViewBox, Camera* shadowCamera, const Matrix3x4& lightView,
  1805. const Frustum& lightViewFrustum, const BoundingBox& lightViewFrustumBox)
  1806. {
  1807. if (shadowCamera->IsOrthographic())
  1808. {
  1809. // Extrude the light space bounding box up to the far edge of the frustum's light space bounding box
  1810. lightViewBox.max_.z_ = Max(lightViewBox.max_.z_,lightViewFrustumBox.max_.z_);
  1811. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  1812. }
  1813. else
  1814. {
  1815. // If light is not directional, can do a simple check: if object is visible, its shadow is too
  1816. if (drawable->IsInView(frame_))
  1817. return true;
  1818. // For perspective lights, extrusion direction depends on the position of the shadow caster
  1819. Vector3 center = lightViewBox.Center();
  1820. Ray extrusionRay(center, center);
  1821. float extrusionDistance = shadowCamera->GetFarClip();
  1822. float originalDistance = Clamp(center.Length(), M_EPSILON, extrusionDistance);
  1823. // Because of the perspective, the bounding box must also grow when it is extruded to the distance
  1824. float sizeFactor = extrusionDistance / originalDistance;
  1825. // Calculate the endpoint box and merge it to the original. Because it's axis-aligned, it will be larger
  1826. // than necessary, so the test will be conservative
  1827. Vector3 newCenter = extrusionDistance * extrusionRay.direction_;
  1828. Vector3 newHalfSize = lightViewBox.Size() * sizeFactor * 0.5f;
  1829. BoundingBox extrudedBox(newCenter - newHalfSize, newCenter + newHalfSize);
  1830. lightViewBox.Merge(extrudedBox);
  1831. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  1832. }
  1833. }
  1834. IntRect View::GetShadowMapViewport(Light* light, unsigned splitIndex, Texture2D* shadowMap)
  1835. {
  1836. unsigned width = shadowMap->GetWidth();
  1837. unsigned height = shadowMap->GetHeight();
  1838. int maxCascades = renderer_->GetMaxShadowCascades();
  1839. switch (light->GetLightType())
  1840. {
  1841. case LIGHT_DIRECTIONAL:
  1842. if (maxCascades == 1)
  1843. return IntRect(0, 0, width, height);
  1844. else if (maxCascades == 2)
  1845. return IntRect(splitIndex * width / 2, 0, (splitIndex + 1) * width / 2, height);
  1846. else
  1847. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 2, ((splitIndex & 1) + 1) * width / 2,
  1848. (splitIndex / 2 + 1) * height / 2);
  1849. case LIGHT_SPOT:
  1850. return IntRect(0, 0, width, height);
  1851. case LIGHT_POINT:
  1852. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 3, ((splitIndex & 1) + 1) * width / 2,
  1853. (splitIndex / 2 + 1) * height / 3);
  1854. }
  1855. return IntRect();
  1856. }
  1857. void View::SetupShadowCameras(LightQueryResult& query)
  1858. {
  1859. Light* light = query.light_;
  1860. int splits = 0;
  1861. switch (light->GetLightType())
  1862. {
  1863. case LIGHT_DIRECTIONAL:
  1864. {
  1865. const CascadeParameters& cascade = light->GetShadowCascade();
  1866. float nearSplit = camera_->GetNearClip();
  1867. float farSplit;
  1868. while (splits < renderer_->GetMaxShadowCascades())
  1869. {
  1870. // If split is completely beyond camera far clip, we are done
  1871. if (nearSplit > camera_->GetFarClip())
  1872. break;
  1873. farSplit = Min(camera_->GetFarClip(), cascade.splits_[splits]);
  1874. if (farSplit <= nearSplit)
  1875. break;
  1876. // Setup the shadow camera for the split
  1877. Camera* shadowCamera = renderer_->GetShadowCamera();
  1878. query.shadowCameras_[splits] = shadowCamera;
  1879. query.shadowNearSplits_[splits] = nearSplit;
  1880. query.shadowFarSplits_[splits] = farSplit;
  1881. SetupDirLightShadowCamera(shadowCamera, light, nearSplit, farSplit);
  1882. nearSplit = farSplit;
  1883. ++splits;
  1884. }
  1885. }
  1886. break;
  1887. case LIGHT_SPOT:
  1888. {
  1889. Camera* shadowCamera = renderer_->GetShadowCamera();
  1890. query.shadowCameras_[0] = shadowCamera;
  1891. Node* cameraNode = shadowCamera->GetNode();
  1892. Node* lightNode = light->GetNode();
  1893. cameraNode->SetTransform(lightNode->GetWorldPosition(), lightNode->GetWorldRotation());
  1894. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  1895. shadowCamera->SetFarClip(light->GetRange());
  1896. shadowCamera->SetFov(light->GetFov());
  1897. shadowCamera->SetAspectRatio(light->GetAspectRatio());
  1898. splits = 1;
  1899. }
  1900. break;
  1901. case LIGHT_POINT:
  1902. {
  1903. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1904. {
  1905. Camera* shadowCamera = renderer_->GetShadowCamera();
  1906. query.shadowCameras_[i] = shadowCamera;
  1907. Node* cameraNode = shadowCamera->GetNode();
  1908. // When making a shadowed point light, align the splits along X, Y and Z axes regardless of light rotation
  1909. cameraNode->SetPosition(light->GetNode()->GetWorldPosition());
  1910. cameraNode->SetDirection(*directions[i]);
  1911. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  1912. shadowCamera->SetFarClip(light->GetRange());
  1913. shadowCamera->SetFov(90.0f);
  1914. shadowCamera->SetAspectRatio(1.0f);
  1915. }
  1916. splits = MAX_CUBEMAP_FACES;
  1917. }
  1918. break;
  1919. }
  1920. query.numSplits_ = splits;
  1921. }
  1922. void View::SetupDirLightShadowCamera(Camera* shadowCamera, Light* light, float nearSplit, float farSplit)
  1923. {
  1924. Node* shadowCameraNode = shadowCamera->GetNode();
  1925. Node* lightNode = light->GetNode();
  1926. float extrusionDistance = camera_->GetFarClip();
  1927. const FocusParameters& parameters = light->GetShadowFocus();
  1928. // Calculate initial position & rotation
  1929. Vector3 pos = cameraNode_->GetWorldPosition() - extrusionDistance * lightNode->GetWorldDirection();
  1930. shadowCameraNode->SetTransform(pos, lightNode->GetWorldRotation());
  1931. // Calculate main camera shadowed frustum in light's view space
  1932. farSplit = Min(farSplit, camera_->GetFarClip());
  1933. // Use the scene Z bounds to limit frustum size if applicable
  1934. if (parameters.focus_)
  1935. {
  1936. nearSplit = Max(minZ_, nearSplit);
  1937. farSplit = Min(maxZ_, farSplit);
  1938. }
  1939. Frustum splitFrustum = camera_->GetSplitFrustum(nearSplit, farSplit);
  1940. Polyhedron frustumVolume;
  1941. frustumVolume.Define(splitFrustum);
  1942. // If focusing enabled, clip the frustum volume by the combined bounding box of the lit geometries within the frustum
  1943. if (parameters.focus_)
  1944. {
  1945. BoundingBox litGeometriesBox;
  1946. for (unsigned i = 0; i < geometries_.Size(); ++i)
  1947. {
  1948. Drawable* drawable = geometries_[i];
  1949. // Skip skyboxes as they have undefinedly large bounding box size
  1950. if (drawable->GetType() == Skybox::GetTypeStatic())
  1951. continue;
  1952. if (drawable->GetMinZ() <= farSplit && drawable->GetMaxZ() >= nearSplit &&
  1953. (GetLightMask(drawable) & light->GetLightMask()))
  1954. litGeometriesBox.Merge(drawable->GetWorldBoundingBox());
  1955. }
  1956. if (litGeometriesBox.defined_)
  1957. {
  1958. frustumVolume.Clip(litGeometriesBox);
  1959. // If volume became empty, restore it to avoid zero size
  1960. if (frustumVolume.Empty())
  1961. frustumVolume.Define(splitFrustum);
  1962. }
  1963. }
  1964. // Transform frustum volume to light space
  1965. const Matrix3x4& lightView = shadowCamera->GetView();
  1966. frustumVolume.Transform(lightView);
  1967. // Fit the frustum volume inside a bounding box. If uniform size, use a sphere instead
  1968. BoundingBox shadowBox;
  1969. if (!parameters.nonUniform_)
  1970. shadowBox.Define(Sphere(frustumVolume));
  1971. else
  1972. shadowBox.Define(frustumVolume);
  1973. shadowCamera->SetOrthographic(true);
  1974. shadowCamera->SetAspectRatio(1.0f);
  1975. shadowCamera->SetNearClip(0.0f);
  1976. shadowCamera->SetFarClip(shadowBox.max_.z_);
  1977. // Center shadow camera on the bounding box. Can not snap to texels yet as the shadow map viewport is unknown
  1978. QuantizeDirLightShadowCamera(shadowCamera, light, IntRect(0, 0, 0, 0), shadowBox);
  1979. }
  1980. void View::FinalizeShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  1981. const BoundingBox& shadowCasterBox)
  1982. {
  1983. const FocusParameters& parameters = light->GetShadowFocus();
  1984. float shadowMapWidth = (float)(shadowViewport.Width());
  1985. LightType type = light->GetLightType();
  1986. if (type == LIGHT_DIRECTIONAL)
  1987. {
  1988. BoundingBox shadowBox;
  1989. shadowBox.max_.y_ = shadowCamera->GetOrthoSize() * 0.5f;
  1990. shadowBox.max_.x_ = shadowCamera->GetAspectRatio() * shadowBox.max_.y_;
  1991. shadowBox.min_.y_ = -shadowBox.max_.y_;
  1992. shadowBox.min_.x_ = -shadowBox.max_.x_;
  1993. // Requantize and snap to shadow map texels
  1994. QuantizeDirLightShadowCamera(shadowCamera, light, shadowViewport, shadowBox);
  1995. }
  1996. if (type == LIGHT_SPOT)
  1997. {
  1998. if (parameters.focus_)
  1999. {
  2000. float viewSizeX = Max(Abs(shadowCasterBox.min_.x_), Abs(shadowCasterBox.max_.x_));
  2001. float viewSizeY = Max(Abs(shadowCasterBox.min_.y_), Abs(shadowCasterBox.max_.y_));
  2002. float viewSize = Max(viewSizeX, viewSizeY);
  2003. // Scale the quantization parameters, because view size is in projection space (-1.0 - 1.0)
  2004. float invOrthoSize = 1.0f / shadowCamera->GetOrthoSize();
  2005. float quantize = parameters.quantize_ * invOrthoSize;
  2006. float minView = parameters.minView_ * invOrthoSize;
  2007. viewSize = Max(ceilf(viewSize / quantize) * quantize, minView);
  2008. if (viewSize < 1.0f)
  2009. shadowCamera->SetZoom(1.0f / viewSize);
  2010. }
  2011. }
  2012. // Perform a finalization step for all lights: ensure zoom out of 2 pixels to eliminate border filtering issues
  2013. // For point lights use 4 pixels, as they must not cross sides of the virtual cube map (maximum 3x3 PCF)
  2014. if (shadowCamera->GetZoom() >= 1.0f)
  2015. {
  2016. if (light->GetLightType() != LIGHT_POINT)
  2017. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 2.0f) / shadowMapWidth));
  2018. else
  2019. {
  2020. #ifdef USE_OPENGL
  2021. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 3.0f) / shadowMapWidth));
  2022. #else
  2023. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 4.0f) / shadowMapWidth));
  2024. #endif
  2025. }
  2026. }
  2027. }
  2028. void View::QuantizeDirLightShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  2029. const BoundingBox& viewBox)
  2030. {
  2031. Node* shadowCameraNode = shadowCamera->GetNode();
  2032. const FocusParameters& parameters = light->GetShadowFocus();
  2033. float shadowMapWidth = (float)(shadowViewport.Width());
  2034. float minX = viewBox.min_.x_;
  2035. float minY = viewBox.min_.y_;
  2036. float maxX = viewBox.max_.x_;
  2037. float maxY = viewBox.max_.y_;
  2038. Vector2 center((minX + maxX) * 0.5f, (minY + maxY) * 0.5f);
  2039. Vector2 viewSize(maxX - minX, maxY - minY);
  2040. // Quantize size to reduce swimming
  2041. // Note: if size is uniform and there is no focusing, quantization is unnecessary
  2042. if (parameters.nonUniform_)
  2043. {
  2044. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  2045. viewSize.y_ = ceilf(sqrtf(viewSize.y_ / parameters.quantize_));
  2046. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  2047. viewSize.y_ = Max(viewSize.y_ * viewSize.y_ * parameters.quantize_, parameters.minView_);
  2048. }
  2049. else if (parameters.focus_)
  2050. {
  2051. viewSize.x_ = Max(viewSize.x_, viewSize.y_);
  2052. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  2053. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  2054. viewSize.y_ = viewSize.x_;
  2055. }
  2056. shadowCamera->SetOrthoSize(viewSize);
  2057. // Center shadow camera to the view space bounding box
  2058. Quaternion rot(shadowCameraNode->GetWorldRotation());
  2059. Vector3 adjust(center.x_, center.y_, 0.0f);
  2060. shadowCameraNode->Translate(rot * adjust);
  2061. // If the shadow map viewport is known, snap to whole texels
  2062. if (shadowMapWidth > 0.0f)
  2063. {
  2064. Vector3 viewPos(rot.Inverse() * shadowCameraNode->GetWorldPosition());
  2065. // Take into account that shadow map border will not be used
  2066. float invActualSize = 1.0f / (shadowMapWidth - 2.0f);
  2067. Vector2 texelSize(viewSize.x_ * invActualSize, viewSize.y_ * invActualSize);
  2068. Vector3 snap(-fmodf(viewPos.x_, texelSize.x_), -fmodf(viewPos.y_, texelSize.y_), 0.0f);
  2069. shadowCameraNode->Translate(rot * snap);
  2070. }
  2071. }
  2072. void View::FindZone(Drawable* drawable)
  2073. {
  2074. Vector3 center = drawable->GetWorldBoundingBox().Center();
  2075. int bestPriority = M_MIN_INT;
  2076. Zone* newZone = 0;
  2077. // If bounding box center is in view, the zone assignment is conclusive also for next frames. Otherwise it is temporary
  2078. // (possibly incorrect) and must be re-evaluated on the next frame
  2079. bool temporary = !camera_->GetFrustum().IsInside(center);
  2080. // First check if the last zone remains a conclusive result
  2081. Zone* lastZone = drawable->GetLastZone();
  2082. if (lastZone && (lastZone->GetViewMask() & camera_->GetViewMask()) && lastZone->GetPriority() >= highestZonePriority_ &&
  2083. (drawable->GetZoneMask() & lastZone->GetZoneMask()) && lastZone->IsInside(center))
  2084. newZone = lastZone;
  2085. else
  2086. {
  2087. for (PODVector<Zone*>::Iterator i = zones_.Begin(); i != zones_.End(); ++i)
  2088. {
  2089. Zone* zone = *i;
  2090. int priority = zone->GetPriority();
  2091. if (priority > bestPriority && (drawable->GetZoneMask() & zone->GetZoneMask()) && zone->IsInside(center))
  2092. {
  2093. newZone = zone;
  2094. bestPriority = priority;
  2095. }
  2096. }
  2097. }
  2098. drawable->SetZone(newZone, temporary);
  2099. }
  2100. Technique* View::GetTechnique(Drawable* drawable, Material* material)
  2101. {
  2102. if (!material)
  2103. {
  2104. const Vector<TechniqueEntry>& techniques = renderer_->GetDefaultMaterial()->GetTechniques();
  2105. return techniques.Size() ? techniques[0].technique_ : (Technique*)0;
  2106. }
  2107. const Vector<TechniqueEntry>& techniques = material->GetTechniques();
  2108. // If only one technique, no choice
  2109. if (techniques.Size() == 1)
  2110. return techniques[0].technique_;
  2111. else
  2112. {
  2113. float lodDistance = drawable->GetLodDistance();
  2114. // Check for suitable technique. Techniques should be ordered like this:
  2115. // Most distant & highest quality
  2116. // Most distant & lowest quality
  2117. // Second most distant & highest quality
  2118. // ...
  2119. for (unsigned i = 0; i < techniques.Size(); ++i)
  2120. {
  2121. const TechniqueEntry& entry = techniques[i];
  2122. Technique* tech = entry.technique_;
  2123. #ifdef USE_OPENGL
  2124. if (!tech || materialQuality_ < entry.qualityLevel_)
  2125. continue;
  2126. #else
  2127. if (!tech || (tech->IsSM3() && !graphics_->GetSM3Support()) || materialQuality_ < entry.qualityLevel_)
  2128. continue;
  2129. #endif
  2130. if (lodDistance >= entry.lodDistance_)
  2131. return tech;
  2132. }
  2133. // If no suitable technique found, fallback to the last
  2134. return techniques.Size() ? techniques.Back().technique_ : (Technique*)0;
  2135. }
  2136. }
  2137. void View::CheckMaterialForAuxView(Material* material)
  2138. {
  2139. const SharedPtr<Texture>* textures = material->GetTextures();
  2140. for (unsigned i = 0; i < MAX_MATERIAL_TEXTURE_UNITS; ++i)
  2141. {
  2142. Texture* texture = textures[i];
  2143. if (texture && texture->GetUsage() == TEXTURE_RENDERTARGET)
  2144. {
  2145. // Have to check cube & 2D textures separately
  2146. if (texture->GetType() == Texture2D::GetTypeStatic())
  2147. {
  2148. Texture2D* tex2D = static_cast<Texture2D*>(texture);
  2149. RenderSurface* target = tex2D->GetRenderSurface();
  2150. if (target && target->GetUpdateMode() == SURFACE_UPDATEVISIBLE)
  2151. target->QueueUpdate();
  2152. }
  2153. else if (texture->GetType() == TextureCube::GetTypeStatic())
  2154. {
  2155. TextureCube* texCube = static_cast<TextureCube*>(texture);
  2156. for (unsigned j = 0; j < MAX_CUBEMAP_FACES; ++j)
  2157. {
  2158. RenderSurface* target = texCube->GetRenderSurface((CubeMapFace)j);
  2159. if (target && target->GetUpdateMode() == SURFACE_UPDATEVISIBLE)
  2160. target->QueueUpdate();
  2161. }
  2162. }
  2163. }
  2164. }
  2165. // Flag as processed so we can early-out next time we come across this material on the same frame
  2166. material->MarkForAuxView(frame_.frameNumber_);
  2167. }
  2168. void View::AddBatchToQueue(BatchQueue& batchQueue, Batch& batch, Technique* tech, bool allowInstancing, bool allowShadows)
  2169. {
  2170. if (!batch.material_)
  2171. batch.material_ = renderer_->GetDefaultMaterial();
  2172. // Convert to instanced if possible
  2173. if (allowInstancing && batch.geometryType_ == GEOM_STATIC && batch.geometry_->GetIndexBuffer() && !batch.overrideView_)
  2174. batch.geometryType_ = GEOM_INSTANCED;
  2175. if (batch.geometryType_ == GEOM_INSTANCED)
  2176. {
  2177. HashMap<BatchGroupKey, BatchGroup>* groups = batch.isBase_ ? &batchQueue.baseBatchGroups_ : &batchQueue.batchGroups_;
  2178. BatchGroupKey key(batch);
  2179. HashMap<BatchGroupKey, BatchGroup>::Iterator i = groups->Find(key);
  2180. if (i == groups->End())
  2181. {
  2182. // Create a new group based on the batch
  2183. // In case the group remains below the instancing limit, do not enable instancing shaders yet
  2184. BatchGroup newGroup(batch);
  2185. newGroup.geometryType_ = GEOM_STATIC;
  2186. renderer_->SetBatchShaders(newGroup, tech, allowShadows);
  2187. newGroup.CalculateSortKey();
  2188. i = groups->Insert(MakePair(key, newGroup));
  2189. }
  2190. int oldSize = i->second_.instances_.Size();
  2191. i->second_.AddTransforms(batch);
  2192. // Convert to using instancing shaders when the instancing limit is reached
  2193. if (oldSize < minInstances_ && (int)i->second_.instances_.Size() >= minInstances_)
  2194. {
  2195. i->second_.geometryType_ = GEOM_INSTANCED;
  2196. renderer_->SetBatchShaders(i->second_, tech, allowShadows);
  2197. i->second_.CalculateSortKey();
  2198. }
  2199. }
  2200. else
  2201. {
  2202. renderer_->SetBatchShaders(batch, tech, allowShadows);
  2203. batch.CalculateSortKey();
  2204. batchQueue.batches_.Push(batch);
  2205. }
  2206. }
  2207. void View::PrepareInstancingBuffer()
  2208. {
  2209. PROFILE(PrepareInstancingBuffer);
  2210. unsigned totalInstances = 0;
  2211. for (HashMap<StringHash, BatchQueue>::Iterator i = batchQueues_.Begin(); i != batchQueues_.End(); ++i)
  2212. totalInstances += i->second_.GetNumInstances();
  2213. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  2214. {
  2215. for (unsigned j = 0; j < i->shadowSplits_.Size(); ++j)
  2216. totalInstances += i->shadowSplits_[j].shadowBatches_.GetNumInstances();
  2217. totalInstances += i->litBatches_.GetNumInstances();
  2218. }
  2219. // If fail to set buffer size, fall back to per-group locking
  2220. if (totalInstances && renderer_->ResizeInstancingBuffer(totalInstances))
  2221. {
  2222. VertexBuffer* instancingBuffer = renderer_->GetInstancingBuffer();
  2223. unsigned freeIndex = 0;
  2224. void* dest = instancingBuffer->Lock(0, totalInstances, true);
  2225. if (!dest)
  2226. return;
  2227. for (HashMap<StringHash, BatchQueue>::Iterator i = batchQueues_.Begin(); i != batchQueues_.End(); ++i)
  2228. i->second_.SetTransforms(dest, freeIndex);
  2229. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  2230. {
  2231. for (unsigned j = 0; j < i->shadowSplits_.Size(); ++j)
  2232. i->shadowSplits_[j].shadowBatches_.SetTransforms(dest, freeIndex);
  2233. i->litBatches_.SetTransforms(dest, freeIndex);
  2234. }
  2235. instancingBuffer->Unlock();
  2236. }
  2237. }
  2238. void View::SetupLightVolumeBatch(Batch& batch)
  2239. {
  2240. Light* light = batch.lightQueue_->light_;
  2241. LightType type = light->GetLightType();
  2242. Vector3 cameraPos = cameraNode_->GetWorldPosition();
  2243. float lightDist;
  2244. graphics_->SetBlendMode(BLEND_ADD);
  2245. graphics_->SetDepthBias(0.0f, 0.0f);
  2246. graphics_->SetDepthWrite(false);
  2247. graphics_->SetFillMode(FILL_SOLID);
  2248. graphics_->SetClipPlane(false);
  2249. if (type != LIGHT_DIRECTIONAL)
  2250. {
  2251. if (type == LIGHT_POINT)
  2252. lightDist = Sphere(light->GetNode()->GetWorldPosition(), light->GetRange() * 1.25f).Distance(cameraPos);
  2253. else
  2254. lightDist = light->GetFrustum().Distance(cameraPos);
  2255. // Draw front faces if not inside light volume
  2256. if (lightDist < camera_->GetNearClip() * 2.0f)
  2257. {
  2258. renderer_->SetCullMode(CULL_CW, camera_);
  2259. graphics_->SetDepthTest(CMP_GREATER);
  2260. }
  2261. else
  2262. {
  2263. renderer_->SetCullMode(CULL_CCW, camera_);
  2264. graphics_->SetDepthTest(CMP_LESSEQUAL);
  2265. }
  2266. }
  2267. else
  2268. {
  2269. // In case the same camera is used for multiple views with differing aspect ratios (not recommended)
  2270. // refresh the directional light's model transform before rendering
  2271. light->GetVolumeTransform(camera_);
  2272. graphics_->SetCullMode(CULL_NONE);
  2273. graphics_->SetDepthTest(CMP_ALWAYS);
  2274. }
  2275. graphics_->SetScissorTest(false);
  2276. graphics_->SetStencilTest(true, CMP_NOTEQUAL, OP_KEEP, OP_KEEP, OP_KEEP, 0, light->GetLightMask());
  2277. }
  2278. void View::RenderShadowMap(const LightBatchQueue& queue)
  2279. {
  2280. PROFILE(RenderShadowMap);
  2281. Texture2D* shadowMap = queue.shadowMap_;
  2282. graphics_->SetTexture(TU_SHADOWMAP, 0);
  2283. graphics_->SetColorWrite(false);
  2284. graphics_->SetFillMode(FILL_SOLID);
  2285. graphics_->SetClipPlane(false);
  2286. graphics_->SetStencilTest(false);
  2287. graphics_->SetRenderTarget(0, shadowMap->GetRenderSurface()->GetLinkedRenderTarget());
  2288. graphics_->SetDepthStencil(shadowMap);
  2289. graphics_->SetViewport(IntRect(0, 0, shadowMap->GetWidth(), shadowMap->GetHeight()));
  2290. graphics_->Clear(CLEAR_DEPTH);
  2291. // Set shadow depth bias
  2292. const BiasParameters& parameters = queue.light_->GetShadowBias();
  2293. // Render each of the splits
  2294. for (unsigned i = 0; i < queue.shadowSplits_.Size(); ++i)
  2295. {
  2296. float multiplier = 1.0f;
  2297. // For directional light cascade splits, adjust depth bias according to the far clip ratio of the splits
  2298. if (i > 0 && queue.light_->GetLightType() == LIGHT_DIRECTIONAL)
  2299. {
  2300. multiplier = Max(queue.shadowSplits_[i].shadowCamera_->GetFarClip() / queue.shadowSplits_[0].shadowCamera_->GetFarClip(), 1.0f);
  2301. multiplier = 1.0f + (multiplier - 1.0f) * queue.light_->GetShadowCascade().biasAutoAdjust_;
  2302. }
  2303. graphics_->SetDepthBias(multiplier * parameters.constantBias_, multiplier * parameters.slopeScaledBias_);
  2304. const ShadowBatchQueue& shadowQueue = queue.shadowSplits_[i];
  2305. if (!shadowQueue.shadowBatches_.IsEmpty())
  2306. {
  2307. graphics_->SetViewport(shadowQueue.shadowViewport_);
  2308. shadowQueue.shadowBatches_.Draw(this);
  2309. }
  2310. }
  2311. graphics_->SetColorWrite(true);
  2312. graphics_->SetDepthBias(0.0f, 0.0f);
  2313. }
  2314. RenderSurface* View::GetDepthStencil(RenderSurface* renderTarget)
  2315. {
  2316. // If using the backbuffer, return the backbuffer depth-stencil
  2317. if (!renderTarget)
  2318. return 0;
  2319. // Then check for linked depth-stencil
  2320. RenderSurface* depthStencil = renderTarget->GetLinkedDepthStencil();
  2321. // Finally get one from Renderer
  2322. if (!depthStencil)
  2323. depthStencil = renderer_->GetDepthStencil(renderTarget->GetWidth(), renderTarget->GetHeight());
  2324. return depthStencil;
  2325. }
  2326. }