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