View.cpp 97 KB

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