View.cpp 103 KB

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