2
0

View.cpp 98 KB

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