View.cpp 101 KB

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