View.cpp 101 KB

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