View.cpp 96 KB

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