View.cpp 120 KB

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