View.cpp 97 KB

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