View.cpp 100 KB

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