View.cpp 111 KB

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