View.cpp 101 KB

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