View.cpp 100 KB

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