View.cpp 96 KB

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