2
0

View.cpp 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Camera.h"
  25. #include "DebugRenderer.h"
  26. #include "Geometry.h"
  27. #include "Graphics.h"
  28. #include "Light.h"
  29. #include "Log.h"
  30. #include "Material.h"
  31. #include "OcclusionBuffer.h"
  32. #include "Octree.h"
  33. #include "OctreeQuery.h"
  34. #include "Renderer.h"
  35. #include "Profiler.h"
  36. #include "Scene.h"
  37. #include "ShaderVariation.h"
  38. #include "Technique.h"
  39. #include "Texture2D.h"
  40. #include "TextureCube.h"
  41. #include "Time.h"
  42. #include "VertexBuffer.h"
  43. #include "View.h"
  44. #include "Zone.h"
  45. #include "DebugNew.h"
  46. static const String aaVariation[] = {
  47. "",
  48. "Ortho"
  49. };
  50. static const Vector3 directions[] =
  51. {
  52. Vector3::RIGHT,
  53. Vector3::LEFT,
  54. Vector3::UP,
  55. Vector3::DOWN,
  56. Vector3::FORWARD,
  57. Vector3::BACK,
  58. };
  59. OBJECTTYPESTATIC(View);
  60. View::View(Context* context) :
  61. Object(context),
  62. graphics_(GetSubsystem<Graphics>()),
  63. renderer_(GetSubsystem<Renderer>()),
  64. octree_(0),
  65. camera_(0),
  66. zone_(0),
  67. renderTarget_(0),
  68. depthStencil_(0),
  69. jitterCounter_(0)
  70. {
  71. frame_.camera_ = 0;
  72. }
  73. View::~View()
  74. {
  75. }
  76. bool View::Define(RenderSurface* renderTarget, const Viewport& viewport)
  77. {
  78. if ((!viewport.scene_) || (!viewport.camera_))
  79. return false;
  80. // If scene is loading asynchronously, it is incomplete and should not be rendered
  81. if (viewport.scene_->IsAsyncLoading())
  82. return false;
  83. Octree* octree = viewport.scene_->GetComponent<Octree>();
  84. if (!octree)
  85. return false;
  86. mode_ = graphics_->GetRenderMode();
  87. // In deferred mode, check for the render texture being too large
  88. if ((mode_ != RENDER_FORWARD) && (renderTarget))
  89. {
  90. if ((renderTarget->GetWidth() > graphics_->GetWidth()) || (renderTarget->GetHeight() > graphics_->GetHeight()))
  91. {
  92. // Display message only once per rendertarget, do not spam each frame
  93. if (gBufferErrorDisplayed_.Find(renderTarget) == gBufferErrorDisplayed_.End())
  94. {
  95. gBufferErrorDisplayed_.Insert(renderTarget);
  96. LOGERROR("Render texture is larger than the G-buffer, can not render");
  97. }
  98. return false;
  99. }
  100. }
  101. octree_ = octree;
  102. camera_ = viewport.camera_;
  103. renderTarget_ = renderTarget;
  104. if (!renderTarget)
  105. depthStencil_ = 0;
  106. else
  107. depthStencil_ = renderTarget->GetLinkedDepthBuffer();
  108. zone_ = renderer_->GetDefaultZone();
  109. // Validate the rect and calculate size. If zero rect, use whole render target size
  110. int rtWidth = renderTarget ? renderTarget->GetWidth() : graphics_->GetWidth();
  111. int rtHeight = renderTarget ? renderTarget->GetHeight() : graphics_->GetHeight();
  112. if (viewport.rect_ != IntRect::ZERO)
  113. {
  114. screenRect_.left_ = Clamp(viewport.rect_.left_, 0, rtWidth - 1);
  115. screenRect_.top_ = Clamp(viewport.rect_.top_, 0, rtHeight - 1);
  116. screenRect_.right_ = Clamp(viewport.rect_.right_, screenRect_.left_ + 1, rtWidth);
  117. screenRect_.bottom_ = Clamp(viewport.rect_.bottom_, screenRect_.top_ + 1, rtHeight);
  118. }
  119. else
  120. screenRect_ = IntRect(0, 0, rtWidth, rtHeight);
  121. width_ = screenRect_.right_ - screenRect_.left_;
  122. height_ = screenRect_.bottom_ - screenRect_.top_;
  123. // Set possible quality overrides from the camera
  124. drawShadows_ = renderer_->GetDrawShadows();
  125. materialQuality_ = renderer_->GetMaterialQuality();
  126. maxOccluderTriangles_ = renderer_->GetMaxOccluderTriangles();
  127. unsigned viewOverrideFlags = camera_->GetViewOverrideFlags();
  128. if (viewOverrideFlags & VOF_LOW_MATERIAL_QUALITY)
  129. materialQuality_ = QUALITY_LOW;
  130. if (viewOverrideFlags & VOF_DISABLE_SHADOWS)
  131. drawShadows_ = false;
  132. if (viewOverrideFlags & VOF_DISABLE_OCCLUSION)
  133. maxOccluderTriangles_ = 0;
  134. return true;
  135. }
  136. void View::Update(const FrameInfo& frame)
  137. {
  138. if ((!camera_) || (!octree_))
  139. return;
  140. frame_.camera_ = camera_;
  141. frame_.timeStep_ = frame.timeStep_;
  142. frame_.frameNumber_ = frame.frameNumber_;
  143. frame_.viewSize_ = IntVector2(width_, height_);
  144. // Clear old light scissor cache, geometry, light, occluder & batch lists
  145. lightScissorCache_.Clear();
  146. geometries_.Clear();
  147. geometryDepthBounds_.Clear();
  148. lights_.Clear();
  149. occluders_.Clear();
  150. shadowOccluders_.Clear();
  151. gBufferQueue_.Clear();
  152. baseQueue_.Clear();
  153. extraQueue_.Clear();
  154. transparentQueue_.Clear();
  155. noShadowLightQueue_.Clear();
  156. lightQueues_.Clear();
  157. // Set automatic aspect ratio if required
  158. if (camera_->GetAutoAspectRatio())
  159. camera_->SetAspectRatio((float)frame_.viewSize_.x_ / (float)frame_.viewSize_.y_);
  160. // Reset projection jitter if was used last frame
  161. camera_->SetProjectionOffset(Vector2::ZERO);
  162. // Reset shadow map use count; they can be reused between views as each is rendered completely at a time
  163. renderer_->ResetShadowMapUseCount();
  164. GetDrawables();
  165. GetBatches();
  166. }
  167. void View::Render()
  168. {
  169. if ((!octree_) || (!camera_))
  170. return;
  171. // If stream offset is supported, write all instance transforms to a single large buffer
  172. // Else we must lock the instance buffer for each batch group
  173. if ((renderer_->GetDynamicInstancing()) && (graphics_->GetStreamOffsetSupport()))
  174. PrepareInstancingBuffer();
  175. // It is possible, though not recommended, that the same camera is used for multiple main views. Set automatic aspect ratio
  176. // again to ensure correct projection will be used
  177. if (camera_->GetAutoAspectRatio())
  178. camera_->SetAspectRatio((float)(screenRect_.right_ - screenRect_.left_) / (float)(screenRect_.bottom_ - screenRect_.top_));
  179. // Set the "view texture" to ensure the rendertarget will not be bound as a texture during rendering
  180. if (renderTarget_)
  181. graphics_->SetViewTexture(renderTarget_->GetParentTexture());
  182. else
  183. graphics_->SetViewTexture(0);
  184. graphics_->SetFillMode(FILL_SOLID);
  185. // Calculate view-global shader parameters
  186. CalculateShaderParameters();
  187. // If not reusing shadowmaps, render all of them first
  188. if (!renderer_->reuseShadowMaps_)
  189. {
  190. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  191. {
  192. LightBatchQueue& queue = lightQueues_[i];
  193. if (queue.light_->GetShadowMap())
  194. RenderShadowMap(queue);
  195. }
  196. }
  197. if (mode_ == RENDER_FORWARD)
  198. RenderBatchesForward();
  199. else
  200. RenderBatchesDeferred();
  201. graphics_->SetViewTexture(0);
  202. // If this is a main view, draw the associated debug geometry now
  203. if (!renderTarget_)
  204. {
  205. Scene* scene = static_cast<Scene*>(octree_->GetNode());
  206. if (scene)
  207. {
  208. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  209. if (debug)
  210. {
  211. debug->SetView(camera_);
  212. debug->Render();
  213. }
  214. }
  215. }
  216. // "Forget" the camera, octree and zone after rendering
  217. camera_ = 0;
  218. octree_ = 0;
  219. zone_ = 0;
  220. frame_.camera_ = 0;
  221. }
  222. void View::GetDrawables()
  223. {
  224. PROFILE(GetDrawables);
  225. Vector3 cameraPos = camera_->GetWorldPosition();
  226. // Get zones & find the zone camera is in
  227. PODVector<Zone*> zones;
  228. PointOctreeQuery query(reinterpret_cast<PODVector<Drawable*>& >(zones), cameraPos, DRAWABLE_ZONE);
  229. octree_->GetDrawables(query);
  230. int highestZonePriority = M_MIN_INT;
  231. for (unsigned i = 0; i < zones.Size(); ++i)
  232. {
  233. Zone* zone = zones[i];
  234. if ((zone->IsInside(cameraPos)) && (zone->GetPriority() > highestZonePriority))
  235. {
  236. zone_ = zone;
  237. highestZonePriority = zone->GetPriority();
  238. }
  239. }
  240. // If occlusion in use, get & render the occluders, then build the depth buffer hierarchy
  241. bool useOcclusion = false;
  242. OcclusionBuffer* buffer = 0;
  243. if (maxOccluderTriangles_ > 0)
  244. {
  245. FrustumOctreeQuery query(occluders_, camera_->GetFrustum(), DRAWABLE_GEOMETRY, true, false);
  246. octree_->GetDrawables(query);
  247. UpdateOccluders(occluders_, camera_);
  248. if (occluders_.Size())
  249. {
  250. buffer = renderer_->GetOrCreateOcclusionBuffer(camera_, maxOccluderTriangles_);
  251. DrawOccluders(buffer, occluders_);
  252. buffer->BuildDepthHierarchy();
  253. useOcclusion = true;
  254. }
  255. }
  256. if (!useOcclusion)
  257. {
  258. // Get geometries & lights without occlusion
  259. FrustumOctreeQuery query(tempDrawables_, camera_->GetFrustum(), DRAWABLE_GEOMETRY | DRAWABLE_LIGHT);
  260. octree_->GetDrawables(query);
  261. }
  262. else
  263. {
  264. // Get geometries & lights using occlusion
  265. OccludedFrustumOctreeQuery query(tempDrawables_, camera_->GetFrustum(), buffer, DRAWABLE_GEOMETRY | DRAWABLE_LIGHT);
  266. octree_->GetDrawables(query);
  267. }
  268. // Sort into geometries & lights, and build visible scene bounding boxes in world and view space
  269. sceneBox_.min_ = sceneBox_.max_ = Vector3::ZERO;
  270. sceneBox_.defined_ = false;
  271. sceneViewBox_.min_ = sceneViewBox_.max_ = Vector3::ZERO;
  272. sceneViewBox_.defined_ = false;
  273. Matrix3x4 view(camera_->GetInverseWorldTransform());
  274. unsigned cameraViewMask = camera_->GetViewMask();
  275. for (unsigned i = 0; i < tempDrawables_.Size(); ++i)
  276. {
  277. Drawable* drawable = tempDrawables_[i];
  278. // Check view mask
  279. if (!(cameraViewMask & drawable->GetViewMask()))
  280. continue;
  281. drawable->UpdateDistance(frame_);
  282. // If draw distance non-zero, check it
  283. float maxDistance = drawable->GetDrawDistance();
  284. if ((maxDistance > 0.0f) && (drawable->GetDistance() > maxDistance))
  285. continue;
  286. unsigned flags = drawable->GetDrawableFlags();
  287. if (flags & DRAWABLE_GEOMETRY)
  288. {
  289. drawable->ClearBasePass();
  290. drawable->MarkInView(frame_);
  291. drawable->UpdateGeometry(frame_);
  292. // Expand the scene bounding boxes
  293. const BoundingBox& geomBox = drawable->GetWorldBoundingBox();
  294. BoundingBox geoview_Box = geomBox.Transformed(view);
  295. sceneBox_.Merge(geomBox);
  296. sceneViewBox_.Merge(geoview_Box);
  297. // Store depth info to speed up split directional light queries
  298. GeometryDepthBounds bounds;
  299. bounds.min_ = geoview_Box.min_.z_;
  300. bounds.max_ = geoview_Box.max_.z_;
  301. geometryDepthBounds_.Push(bounds);
  302. geometries_.Push(drawable);
  303. }
  304. else if (flags & DRAWABLE_LIGHT)
  305. {
  306. Light* light = static_cast<Light*>(drawable);
  307. // Skip if light is culled by the zone
  308. if (!(light->GetViewMask() & zone_->GetViewMask()))
  309. continue;
  310. light->MarkInView(frame_);
  311. lights_.Push(light);
  312. }
  313. }
  314. // Sort the lights to brightest/closest first
  315. for (unsigned i = 0; i < lights_.Size(); ++i)
  316. lights_[i]->SetIntensitySortValue(cameraPos);
  317. Sort(lights_.Begin(), lights_.End(), CompareDrawables);
  318. }
  319. void View::GetBatches()
  320. {
  321. HashSet<LitTransparencyCheck> litTransparencies;
  322. HashSet<Drawable*> maxLightsDrawables;
  323. Map<Light*, unsigned> lightQueueIndex;
  324. PassType gBufferPass = PASS_DEFERRED;
  325. PassType additionalPass = PASS_EXTRA;
  326. if (mode_ == RENDER_PREPASS)
  327. {
  328. gBufferPass = PASS_PREPASS;
  329. additionalPass = PASS_MATERIAL;
  330. }
  331. // Go through lights
  332. {
  333. PROFILE_MULTIPLE(GetLightBatches, lights_.Size());
  334. unsigned lightQueueCount = 0;
  335. for (unsigned i = 0; i < lights_.Size(); ++i)
  336. {
  337. Light* light = lights_[i];
  338. unsigned splits = ProcessLight(light);
  339. if (!splits)
  340. continue;
  341. // Prepare lit object + shadow caster queues for each split
  342. if (lightQueues_.Size() < lightQueueCount + splits)
  343. lightQueues_.Resize(lightQueueCount + splits);
  344. unsigned prevLightQueueCount = lightQueueCount;
  345. for (unsigned j = 0; j < splits; ++j)
  346. {
  347. Light* SplitLight = splitLights_[j];
  348. LightBatchQueue& lightQueue = lightQueues_[lightQueueCount];
  349. lightQueue.light_ = SplitLight;
  350. lightQueue.shadowBatches_.Clear();
  351. lightQueue.litBatches_.Clear();
  352. lightQueue.volumeBatches_.Clear();
  353. lightQueue.lastSplit_ = false;
  354. // Loop through shadow casters
  355. Camera* shadowCamera = SplitLight->GetShadowCamera();
  356. for (unsigned k = 0; k < shadowCasters_[j].Size(); ++k)
  357. {
  358. Drawable* drawable = shadowCasters_[j][k];
  359. unsigned numBatches = drawable->GetNumBatches();
  360. for (unsigned l = 0; l < numBatches; ++l)
  361. {
  362. Batch shadowBatch;
  363. drawable->GetBatch(frame_, l, shadowBatch);
  364. Technique* tech = GetTechnique(drawable, shadowBatch.material_);
  365. if ((!shadowBatch.geometry_) || (!tech))
  366. continue;
  367. Pass* pass = tech->GetPass(PASS_SHADOW);
  368. // Skip if material has no shadow pass
  369. if (!pass)
  370. continue;
  371. // Fill the rest of the batch
  372. shadowBatch.camera_ = shadowCamera;
  373. shadowBatch.distance_ = shadowCamera->GetDistance(drawable->GetWorldPosition());
  374. shadowBatch.light_ = SplitLight;
  375. shadowBatch.hasPriority_ = (!pass->GetAlphaTest()) && (!pass->GetAlphaMask());
  376. renderer_->SetBatchShaders(shadowBatch, tech, pass);
  377. lightQueue.shadowBatches_.AddBatch(shadowBatch);
  378. }
  379. }
  380. // Loop through lit geometries
  381. if (litGeometries_[j].Size())
  382. {
  383. bool storeLightQueue = true;
  384. for (unsigned k = 0; k < litGeometries_[j].Size(); ++k)
  385. {
  386. Drawable* drawable = litGeometries_[j][k];
  387. // If drawable limits maximum lights, only record the light, and check maximum count / build batches later
  388. if (!drawable->GetMaxLights())
  389. GetLitBatches(drawable, light, SplitLight, &lightQueue, litTransparencies, gBufferPass);
  390. else
  391. {
  392. drawable->AddLight(SplitLight);
  393. maxLightsDrawables.Insert(drawable);
  394. }
  395. }
  396. // Store the light queue, and light volume batch in deferred mode
  397. if (mode_ != RENDER_FORWARD)
  398. {
  399. Batch volumeBatch;
  400. volumeBatch.geometry_ = renderer_->GetLightGeometry(SplitLight);
  401. volumeBatch.worldTransform_ = &SplitLight->GetVolumeTransform(*camera_);
  402. volumeBatch.overrideView_ = SplitLight->GetLightType() == LIGHT_DIRECTIONAL;
  403. volumeBatch.camera_ = camera_;
  404. volumeBatch.light_ = SplitLight;
  405. volumeBatch.distance_ = SplitLight->GetDistance();
  406. renderer_->SetLightVolumeShaders(volumeBatch);
  407. // If light is a split point light, it must be treated as shadowed in any case for correct stencil clearing
  408. if ((SplitLight->GetShadowMap()) || (SplitLight->GetLightType() == LIGHT_SPLITPOINT))
  409. lightQueue.volumeBatches_.Push(volumeBatch);
  410. else
  411. {
  412. storeLightQueue = false;
  413. noShadowLightQueue_.AddBatch(volumeBatch, true);
  414. }
  415. }
  416. if (storeLightQueue)
  417. {
  418. lightQueueIndex[SplitLight] = lightQueueCount;
  419. ++lightQueueCount;
  420. }
  421. }
  422. }
  423. // Mark the last split
  424. if (lightQueueCount != prevLightQueueCount)
  425. lightQueues_[lightQueueCount - 1].lastSplit_ = true;
  426. }
  427. // Resize the light queue vector now that final size is known
  428. lightQueues_.Resize(lightQueueCount);
  429. }
  430. // Process drawables with limited light count
  431. if (maxLightsDrawables.Size())
  432. {
  433. PROFILE(GetMaxLightsBatches);
  434. for (HashSet<Drawable*>::Iterator i = maxLightsDrawables.Begin(); i != maxLightsDrawables.End(); ++i)
  435. {
  436. Drawable* drawable = *i;
  437. drawable->LimitLights();
  438. const PODVector<Light*>& lights = drawable->GetLights();
  439. for (unsigned i = 0; i < lights.Size(); ++i)
  440. {
  441. Light* SplitLight = lights[i];
  442. Light* light = SplitLight->GetOriginalLight();
  443. if (!light)
  444. light = SplitLight;
  445. // Find the correct light queue again
  446. LightBatchQueue* queue = 0;
  447. Map<Light*, unsigned>::Iterator j = lightQueueIndex.Find(SplitLight);
  448. if (j != lightQueueIndex.End())
  449. queue = &lightQueues_[j->second_];
  450. GetLitBatches(drawable, light, SplitLight, queue, litTransparencies, gBufferPass);
  451. }
  452. }
  453. }
  454. // Go through geometries for base pass batches
  455. {
  456. PROFILE(GetBaseBatches);
  457. for (unsigned i = 0; i < geometries_.Size(); ++i)
  458. {
  459. Drawable* drawable = geometries_[i];
  460. unsigned numBatches = drawable->GetNumBatches();
  461. for (unsigned j = 0; j < numBatches; ++j)
  462. {
  463. Batch baseBatch;
  464. drawable->GetBatch(frame_, j, baseBatch);
  465. Technique* tech = GetTechnique(drawable, baseBatch.material_);
  466. if ((!baseBatch.geometry_) || (!tech))
  467. continue;
  468. // Check here if the material technique refers to a render target texture with camera(s) attached
  469. // Only check this for the main view (null rendertarget)
  470. if ((!renderTarget_) && (baseBatch.material_) && (baseBatch.material_->GetAuxViewFrameNumber() != frame_.frameNumber_))
  471. CheckMaterialForAuxView(baseBatch.material_);
  472. // If object already has a lit base pass, can skip the unlit base pass
  473. if (drawable->HasBasePass(j))
  474. continue;
  475. // Fill the rest of the batch
  476. baseBatch.camera_ = camera_;
  477. baseBatch.distance_ = drawable->GetDistance();
  478. Pass* pass = 0;
  479. // In deferred mode, check for a G-buffer batch first
  480. if (mode_ != RENDER_FORWARD)
  481. {
  482. pass = tech->GetPass(gBufferPass);
  483. if (pass)
  484. {
  485. renderer_->SetBatchShaders(baseBatch, tech, pass);
  486. baseBatch.hasPriority_ = (!pass->GetAlphaTest()) && (!pass->GetAlphaMask());
  487. gBufferQueue_.AddBatch(baseBatch);
  488. // Check also for an additional pass. In light prepass mode this actually renders the visible geometry
  489. pass = tech->GetPass(additionalPass);
  490. if (pass)
  491. {
  492. renderer_->SetBatchShaders(baseBatch, tech, pass);
  493. baseQueue_.AddBatch(baseBatch);
  494. }
  495. continue;
  496. }
  497. }
  498. // Then check for forward rendering base pass
  499. pass = tech->GetPass(PASS_BASE);
  500. if (pass)
  501. {
  502. renderer_->SetBatchShaders(baseBatch, tech, pass);
  503. if (pass->GetBlendMode() == BLEND_REPLACE)
  504. {
  505. baseBatch.hasPriority_ = (!pass->GetAlphaTest()) && (!pass->GetAlphaMask());
  506. baseQueue_.AddBatch(baseBatch);
  507. }
  508. else
  509. {
  510. baseBatch.hasPriority_ = true;
  511. transparentQueue_.AddBatch(baseBatch, true);
  512. }
  513. continue;
  514. }
  515. else
  516. {
  517. // If no base pass, finally check for extra / custom pass
  518. pass = tech->GetPass(PASS_EXTRA);
  519. if (pass)
  520. {
  521. baseBatch.hasPriority_ = false;
  522. renderer_->SetBatchShaders(baseBatch, tech, pass);
  523. extraQueue_.AddBatch(baseBatch);
  524. }
  525. }
  526. }
  527. }
  528. }
  529. // All batches have been collected. Sort them now
  530. SortBatches();
  531. }
  532. void View::GetLitBatches(Drawable* drawable, Light* light, Light* SplitLight, LightBatchQueue* lightQueue,
  533. HashSet<LitTransparencyCheck>& litTransparencies, PassType gBufferPass)
  534. {
  535. bool splitPointLight = SplitLight->GetLightType() == LIGHT_SPLITPOINT;
  536. // Whether to allow shadows for transparencies, or for forward lit objects in deferred mode
  537. bool allowShadows = (!renderer_->reuseShadowMaps_) && (!splitPointLight);
  538. unsigned numBatches = drawable->GetNumBatches();
  539. for (unsigned i = 0; i < numBatches; ++i)
  540. {
  541. Batch litBatch;
  542. drawable->GetBatch(frame_, i, litBatch);
  543. Technique* tech = GetTechnique(drawable, litBatch.material_);
  544. if ((!litBatch.geometry_) || (!tech))
  545. continue;
  546. // If material uses opaque G-buffer rendering, skip
  547. if ((mode_ != RENDER_FORWARD) && (tech->HasPass(gBufferPass)))
  548. continue;
  549. Pass* pass = 0;
  550. bool priority = false;
  551. // For directional light, check for lit base pass
  552. if (SplitLight->GetLightType() == LIGHT_DIRECTIONAL)
  553. {
  554. if (!drawable->HasBasePass(i))
  555. {
  556. pass = tech->GetPass(PASS_LITBASE);
  557. if (pass)
  558. {
  559. priority = true;
  560. drawable->SetBasePass(i);
  561. }
  562. }
  563. }
  564. // If no first light pass, get ordinary light pass
  565. if (!pass)
  566. pass = tech->GetPass(PASS_LIGHT);
  567. // Skip if material does not receive light at all
  568. if (!pass)
  569. continue;
  570. // Fill the rest of the batch
  571. litBatch.camera_ = camera_;
  572. litBatch.distance_ = drawable->GetDistance();
  573. litBatch.light_ = SplitLight;
  574. litBatch.hasPriority_ = priority;
  575. // Check from the ambient pass whether the object is opaque
  576. Pass* ambientPass = tech->GetPass(PASS_BASE);
  577. if ((!ambientPass) || (ambientPass->GetBlendMode() == BLEND_REPLACE))
  578. {
  579. if (mode_ == RENDER_FORWARD)
  580. {
  581. if (lightQueue)
  582. {
  583. renderer_->SetBatchShaders(litBatch, tech, pass);
  584. lightQueue->litBatches_.AddBatch(litBatch);
  585. }
  586. }
  587. else
  588. {
  589. renderer_->SetBatchShaders(litBatch, tech, pass, allowShadows);
  590. baseQueue_.AddBatch(litBatch);
  591. }
  592. }
  593. else
  594. {
  595. if (splitPointLight)
  596. {
  597. // Check if already lit
  598. LitTransparencyCheck check(light, drawable, i);
  599. if (litTransparencies.Find(check) != litTransparencies.End())
  600. continue;
  601. // Use the original light instead of the split one, to choose correct scissor
  602. litBatch.light_ = light;
  603. litTransparencies.Insert(check);
  604. }
  605. renderer_->SetBatchShaders(litBatch, tech, pass, allowShadows);
  606. transparentQueue_.AddBatch(litBatch, true);
  607. }
  608. }
  609. }
  610. void View::RenderBatchesForward()
  611. {
  612. {
  613. // Render opaque objects' base passes
  614. PROFILE(RenderBasePass);
  615. graphics_->ClearLastParameterSources();
  616. graphics_->SetColorWrite(true);
  617. graphics_->SetStencilTest(false);
  618. graphics_->SetRenderTarget(0, renderTarget_);
  619. graphics_->SetDepthStencil(depthStencil_);
  620. graphics_->SetViewport(screenRect_);
  621. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH | CLEAR_STENCIL, zone_->GetFogColor());
  622. RenderBatchQueue(baseQueue_);
  623. }
  624. {
  625. // Render shadow maps + opaque objects' shadowed additive lighting
  626. PROFILE(RenderLights);
  627. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  628. {
  629. LightBatchQueue& queue = lightQueues_[i];
  630. // If reusing shadowmaps, render each of them before the lit batches
  631. if ((renderer_->reuseShadowMaps_) && (queue.light_->GetShadowMap()))
  632. RenderShadowMap(queue);
  633. graphics_->ClearLastParameterSources();
  634. graphics_->SetRenderTarget(0, renderTarget_);
  635. graphics_->SetDepthStencil(depthStencil_);
  636. graphics_->SetViewport(screenRect_);
  637. RenderForwardLightBatchQueue(queue.litBatches_, queue.light_);
  638. // Clear the stencil buffer after the last split
  639. if (queue.lastSplit_)
  640. {
  641. LightType type = queue.light_->GetLightType();
  642. if ((type == LIGHT_SPLITPOINT) || (type == LIGHT_DIRECTIONAL))
  643. DrawSplitLightToStencil(*camera_, queue.light_, true);
  644. }
  645. }
  646. }
  647. {
  648. // Render extra / custom passes
  649. PROFILE(RenderExtraPass);
  650. graphics_->ClearLastParameterSources();
  651. graphics_->SetRenderTarget(0, renderTarget_);
  652. graphics_->SetDepthStencil(depthStencil_);
  653. graphics_->SetViewport(screenRect_);
  654. RenderBatchQueue(extraQueue_);
  655. }
  656. {
  657. // Render transparent objects last (both base passes & additive lighting)
  658. PROFILE(RenderTransparent);
  659. RenderBatchQueue(transparentQueue_, true);
  660. }
  661. }
  662. void View::RenderBatchesDeferred()
  663. {
  664. bool deferred = mode_ != RENDER_PREPASS;
  665. Texture2D* diffBuffer = graphics_->GetDiffBuffer();
  666. Texture2D* normalBuffer = graphics_->GetNormalBuffer();
  667. Texture2D* depthBuffer = graphics_->GetDepthBuffer();
  668. // Check for temporal antialiasing in deferred mode. Only use it on the main view (null rendertarget)
  669. bool temporalAA = (!renderTarget_) && (graphics_->GetMultiSample() > 0);
  670. if (temporalAA)
  671. {
  672. ++jitterCounter_;
  673. if (jitterCounter_ > 3)
  674. jitterCounter_ = 2;
  675. Vector2 jitter(-0.25f, -0.25f);
  676. if (jitterCounter_ & 1)
  677. jitter = -jitter;
  678. jitter.x_ /= width_;
  679. jitter.y_ /= height_;
  680. camera_->SetProjectionOffset(jitter);
  681. }
  682. RenderSurface* finalRenderTarget = temporalAA ? graphics_->GetScreenBuffer(jitterCounter_ & 1)->GetRenderSurface() : renderTarget_;
  683. // In OpenGL, we will use two depth stencils: one for the G-buffer, and one for light accumulation
  684. #ifdef USE_OPENGL
  685. RenderSurface* lightDepthStencil = deferred ? depthStencil_ : depthBuffer->GetRenderSurface();
  686. RenderSurface* finalDepthStencil = depthStencil_;
  687. // Exception: if temporal AA is used, the G-buffer depth stencil can be used for the whole time,
  688. // as the backbuffer is only copied to in the very end
  689. if (temporalAA)
  690. lightDepthStencil = finalDepthStencil = depthBuffer->GetRenderSurface();
  691. #else
  692. // In Direct3D9 the system depth stencil will be used for the whole time
  693. RenderSurface* lightDepthStencil = 0;
  694. RenderSurface* finalDepthStencil = 0;
  695. #endif
  696. // Calculate shader parameters needed only in deferred rendering
  697. Vector3 nearVector, farVector;
  698. camera_->GetFrustumSize(nearVector, farVector);
  699. Vector4 viewportParams(farVector.x_, farVector.y_, farVector.z_, 0.0f);
  700. float gBufferWidth = (float)diffBuffer->GetWidth();
  701. float gBufferHeight = (float)diffBuffer->GetHeight();
  702. float widthRange = 0.5f * width_ / gBufferWidth;
  703. float heightRange = 0.5f * height_ / gBufferHeight;
  704. #ifdef USE_OPENGL
  705. Vector4 bufferUVOffset(((float)screenRect_.left_) / gBufferWidth + widthRange,
  706. ((float)screenRect_.top_) / gBufferHeight + heightRange, widthRange, heightRange);
  707. // Hardware depth is non-linear in perspective views, so calculate the depth reconstruction parameters
  708. float farClip = camera_->GetFarClip();
  709. float nearClip = camera_->GetNearClip();
  710. Vector4 depthReconstruct = Vector4::ZERO;
  711. depthReconstruct.x_ = farClip / (farClip - nearClip);
  712. depthReconstruct.y_ = -nearClip / (farClip - nearClip);
  713. shaderParameters_[PSP_DEPTHRECONSTRUCT] = depthReconstruct;
  714. #else
  715. Vector4 bufferUVOffset((0.5f + (float)screenRect_.left_) / gBufferWidth + widthRange,
  716. (0.5f + (float)screenRect_.top_) / gBufferHeight + heightRange, widthRange, heightRange);
  717. #endif
  718. Vector4 viewportSize((float)screenRect_.left_ / gBufferWidth, (float)screenRect_.top_ / gBufferHeight,
  719. (float)screenRect_.right_ / gBufferWidth, (float)screenRect_.bottom_ / gBufferHeight);
  720. shaderParameters_[VSP_FRUSTUMSIZE] = viewportParams;
  721. shaderParameters_[VSP_GBUFFEROFFSETS] = bufferUVOffset;
  722. shaderParameters_[PSP_GBUFFEROFFSETS] = bufferUVOffset;
  723. shaderParameters_[PSP_GBUFFERVIEWPORT] = viewportSize;
  724. {
  725. // Clear and render the G-buffer
  726. PROFILE(RenderGBuffer);
  727. graphics_->ClearLastParameterSources();
  728. graphics_->SetColorWrite(true);
  729. graphics_->SetScissorTest(false);
  730. graphics_->SetStencilTest(false);
  731. #ifdef USE_OPENGL
  732. // On OpenGL, clear the diffuse and depth buffers normally
  733. if (deferred)
  734. {
  735. graphics_->SetRenderTarget(0, diffBuffer);
  736. graphics_->SetDepthStencil(depthBuffer);
  737. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH | CLEAR_STENCIL);
  738. graphics_->SetRenderTarget(1, normalBuffer);
  739. }
  740. else
  741. {
  742. graphics_->SetRenderTarget(0, (RenderSurface*)0);
  743. graphics_->SetDepthStencil(depthBuffer);
  744. graphics_->Clear(CLEAR_DEPTH | CLEAR_STENCIL);
  745. graphics_->SetRenderTarget(0, normalBuffer);
  746. }
  747. #else
  748. // On Direct3D9, clear only depth and stencil at first (fillrate optimization)
  749. if (deferred)
  750. {
  751. graphics_->SetRenderTarget(0, diffBuffer);
  752. graphics_->SetRenderTarget(1, normalBuffer);
  753. graphics_->SetRenderTarget(2, depthBuffer);
  754. }
  755. else
  756. {
  757. graphics_->SetRenderTarget(0, normalBuffer);
  758. graphics_->SetRenderTarget(1, depthBuffer);
  759. }
  760. graphics_->SetDepthStencil(lightDepthStencil);
  761. graphics_->SetViewport(screenRect_);
  762. graphics_->Clear(CLEAR_DEPTH | CLEAR_STENCIL);
  763. #endif
  764. RenderBatchQueue(gBufferQueue_);
  765. graphics_->SetAlphaTest(false);
  766. graphics_->SetBlendMode(BLEND_REPLACE);
  767. #ifndef USE_OPENGL
  768. // On Direct3D9, clear now the parts of G-Buffer that were not rendered into
  769. graphics_->SetDepthTest(CMP_LESSEQUAL);
  770. graphics_->SetDepthWrite(false);
  771. if (deferred)
  772. {
  773. graphics_->ResetRenderTarget(2);
  774. graphics_->SetRenderTarget(1, depthBuffer);
  775. renderer_->DrawFullScreenQuad(*camera_, renderer_->GetVertexShader("Deferred/GBufferFill"),
  776. renderer_->GetPixelShader("Deferred/GBufferFill"), false, shaderParameters_);
  777. }
  778. else
  779. {
  780. graphics_->ResetRenderTarget(1);
  781. graphics_->SetRenderTarget(0, depthBuffer);
  782. graphics_->SetViewport(screenRect_);
  783. // The stencil shader writes color 1.0, which equals far depth
  784. renderer_->DrawFullScreenQuad(*camera_, renderer_->GetVertexShader("Stencil"),
  785. renderer_->GetPixelShader("Stencil"), false, shaderParameters_);
  786. }
  787. #endif
  788. }
  789. if (deferred)
  790. {
  791. // Render ambient color & fog. On OpenGL the depth buffer will be copied now if necessary
  792. graphics_->ClearLastParameterSources();
  793. graphics_->SetDepthTest(CMP_ALWAYS);
  794. graphics_->SetRenderTarget(0, finalRenderTarget);
  795. graphics_->ResetRenderTarget(1);
  796. #ifdef USE_OPENGL
  797. bool copyDepth = lightDepthStencil != depthBuffer->GetRenderSurface();
  798. graphics_->SetDepthWrite(copyDepth);
  799. #else
  800. graphics_->ResetRenderTarget(2);
  801. #endif
  802. graphics_->SetDepthStencil(lightDepthStencil);
  803. graphics_->Clear(CLEAR_STENCIL);
  804. graphics_->SetTexture(TU_DIFFBUFFER, diffBuffer);
  805. graphics_->SetTexture(TU_DEPTHBUFFER, depthBuffer);
  806. graphics_->SetViewport(screenRect_);
  807. String pixelShaderName = "Deferred/Ambient";
  808. #ifdef USE_OPENGL
  809. if (camera_->IsOrthographic())
  810. pixelShaderName += "Ortho";
  811. #endif
  812. renderer_->DrawFullScreenQuad(*camera_, renderer_->GetVertexShader("Deferred/Ambient"),
  813. renderer_->GetPixelShader(pixelShaderName), false, shaderParameters_);
  814. }
  815. else
  816. {
  817. // Light prepass: reset the light accumulation buffer with black color
  818. // On OpenGL we still use the GBuffer's depth buffer at this point, so depth is not copied yet
  819. graphics_->SetRenderTarget(0, diffBuffer);
  820. #ifndef USE_OPENGL
  821. graphics_->ResetRenderTarget(1);
  822. #endif
  823. graphics_->SetDepthStencil(lightDepthStencil);
  824. graphics_->SetViewport(screenRect_);
  825. graphics_->Clear(CLEAR_COLOR);
  826. }
  827. {
  828. // Render lights
  829. PROFILE(RenderLights);
  830. // Shadowed lights
  831. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  832. {
  833. LightBatchQueue& queue = lightQueues_[i];
  834. // If reusing shadowmaps, render each of them before the lit batches
  835. if ((renderer_->reuseShadowMaps_) && (queue.light_->GetShadowMap()))
  836. RenderShadowMap(queue);
  837. // Light volume batches are not sorted as there should be only one of them
  838. if (queue.volumeBatches_.Size())
  839. {
  840. graphics_->ClearLastParameterSources();
  841. if (deferred)
  842. {
  843. graphics_->SetRenderTarget(0, finalRenderTarget);
  844. graphics_->SetTexture(TU_DIFFBUFFER, diffBuffer);
  845. }
  846. else
  847. graphics_->SetRenderTarget(0, diffBuffer);
  848. graphics_->SetTexture(TU_NORMALBUFFER, normalBuffer);
  849. graphics_->SetTexture(TU_DEPTHBUFFER, depthBuffer);
  850. graphics_->SetDepthStencil(lightDepthStencil);
  851. graphics_->SetViewport(screenRect_);
  852. for (unsigned j = 0; j < queue.volumeBatches_.Size(); ++j)
  853. {
  854. renderer_->SetupLightBatch(queue.volumeBatches_[j]);
  855. queue.volumeBatches_[j].Draw(graphics_, shaderParameters_);
  856. }
  857. // If was the last split of a split point light, clear the stencil by rendering the point light again
  858. if ((queue.lastSplit_) && (queue.light_->GetLightType() == LIGHT_SPLITPOINT))
  859. DrawSplitLightToStencil(*camera_, queue.light_, true);
  860. }
  861. }
  862. // Non-shadowed lights
  863. if (noShadowLightQueue_.sortedBatches_.Size())
  864. {
  865. graphics_->ClearLastParameterSources();
  866. if (deferred)
  867. {
  868. graphics_->SetRenderTarget(0, finalRenderTarget);
  869. graphics_->SetTexture(TU_DIFFBUFFER, diffBuffer);
  870. }
  871. else
  872. graphics_->SetRenderTarget(0, diffBuffer);
  873. graphics_->SetTexture(TU_NORMALBUFFER, normalBuffer);
  874. graphics_->SetTexture(TU_DEPTHBUFFER, depthBuffer);
  875. graphics_->SetDepthStencil(lightDepthStencil);
  876. graphics_->SetViewport(screenRect_);
  877. for (unsigned i = 0; i < noShadowLightQueue_.sortedBatches_.Size(); ++i)
  878. {
  879. renderer_->SetupLightBatch(*noShadowLightQueue_.sortedBatches_[i]);
  880. noShadowLightQueue_.sortedBatches_[i]->Draw(graphics_, shaderParameters_);
  881. }
  882. }
  883. }
  884. {
  885. // Render base passes
  886. PROFILE(RenderBasePass);
  887. graphics_->ClearLastParameterSources();
  888. graphics_->SetStencilTest(false);
  889. graphics_->SetRenderTarget(0, finalRenderTarget);
  890. graphics_->SetDepthStencil(finalDepthStencil);
  891. graphics_->SetViewport(screenRect_);
  892. graphics_->SetTexture(TU_DIFFBUFFER, 0);
  893. graphics_->SetTexture(TU_NORMALBUFFER, 0);
  894. graphics_->SetTexture(TU_DEPTHBUFFER, 0);
  895. if (!deferred)
  896. {
  897. #ifdef USE_OPENGL
  898. // In OpenGL light prepass mode, copy depth now
  899. if (finalDepthStencil != depthBuffer->GetRenderSurface())
  900. {
  901. graphics_->SetTexture(TU_DEPTHBUFFER, depthBuffer);
  902. graphics_->SetAlphaTest(false);
  903. graphics_->SetBlendMode(BLEND_REPLACE);
  904. graphics_->SetDepthTest(CMP_ALWAYS);
  905. graphics_->SetDepthWrite(true);
  906. renderer_->DrawFullScreenQuad(*camera_, renderer_->GetVertexShader("Prepass/CopyDepth"),
  907. renderer_->GetPixelShader("Prepass/CopyDepth"), false, shaderParameters_);
  908. }
  909. else
  910. graphics_->Clear(CLEAR_COLOR, zone_->GetFogColor());
  911. #else
  912. graphics_->Clear(CLEAR_COLOR, zone_->GetFogColor());
  913. #endif
  914. }
  915. // Remember to bind the light buffer in prepass mode
  916. RenderBatchQueue(baseQueue_, true, !deferred);
  917. }
  918. {
  919. // Render extra / custom passes
  920. PROFILE(RenderExtraPass);
  921. RenderBatchQueue(extraQueue_);
  922. }
  923. {
  924. // Render transparent objects last (both ambient & additive lighting)
  925. PROFILE(RenderTransparent);
  926. RenderBatchQueue(transparentQueue_, true);
  927. }
  928. // Render temporal antialiasing now if enabled
  929. if (temporalAA)
  930. {
  931. PROFILE(RenderTemporalAA);
  932. // Disable averaging if it is the first frame rendered in this view
  933. float thisFrameWeight = jitterCounter_ < 2 ? 1.0f : 0.5f;
  934. Vector4 depthMode = Vector4::ZERO;
  935. if (camera_->IsOrthographic())
  936. depthMode.z_ = 1.0f;
  937. else
  938. depthMode.w_ = 1.0f / camera_->GetFarClip();
  939. unsigned index = camera_->IsOrthographic() ? 1 : 0;
  940. String shaderName = "TemporalAA_" + aaVariation[index];
  941. graphics_->SetAlphaTest(false);
  942. graphics_->SetBlendMode(BLEND_REPLACE);
  943. graphics_->SetDepthTest(CMP_ALWAYS);
  944. graphics_->SetDepthWrite(false);
  945. graphics_->SetScissorTest(false);
  946. graphics_->SetStencilTest(false);
  947. graphics_->SetRenderTarget(0, renderTarget_);
  948. graphics_->SetDepthStencil(depthStencil_);
  949. graphics_->SetViewport(screenRect_);
  950. // Pre-select the right shaders so that we can set shader parameters that can not go into the parameter map
  951. // (matrices)
  952. graphics_->SetShaders(renderer_->GetVertexShader(shaderName), renderer_->GetPixelShader(shaderName));
  953. graphics_->SetShaderParameter(VSP_CAMERAROT, camera_->GetWorldTransform().RotationMatrix());
  954. graphics_->SetShaderParameter(VSP_DEPTHMODE, depthMode);
  955. graphics_->SetShaderParameter(PSP_CAMERAPOS, camera_->GetWorldPosition());
  956. graphics_->SetShaderParameter(PSP_ANTIALIASWEIGHTS, Vector4(thisFrameWeight, 1.0f - thisFrameWeight, 0.0f, 0.0f));
  957. graphics_->SetShaderParameter(PSP_SAMPLEOFFSETS, Vector4(1.0f / gBufferWidth, 1.0f / gBufferHeight, 0.0f, 0.0f));
  958. graphics_->SetShaderParameter(PSP_VIEWPROJ, camera_->GetProjection(false) * lastCameraView_);
  959. graphics_->SetTexture(TU_DIFFBUFFER, graphics_->GetScreenBuffer(jitterCounter_ & 1));
  960. graphics_->SetTexture(TU_NORMALBUFFER, graphics_->GetScreenBuffer((jitterCounter_ + 1) & 1));
  961. graphics_->SetTexture(TU_DEPTHBUFFER, graphics_->GetDepthBuffer());
  962. renderer_->DrawFullScreenQuad(*camera_, renderer_->GetVertexShader(shaderName),
  963. renderer_->GetPixelShader(shaderName), false, shaderParameters_);
  964. // Store view transform for next frame
  965. lastCameraView_ = camera_->GetInverseWorldTransform();
  966. }
  967. }
  968. void View::UpdateOccluders(PODVector<Drawable*>& occluders, Camera* camera)
  969. {
  970. float occluderSizeThreshold_ = renderer_->GetOccluderSizeThreshold();
  971. float halfViewSize = camera->GetHalfViewSize();
  972. float invOrthoSize = 1.0f / camera->GetOrthoSize();
  973. Vector3 cameraPos = camera->GetWorldPosition();
  974. unsigned cameraViewMask = camera->GetViewMask();
  975. for (unsigned i = 0; i < occluders.Size(); ++i)
  976. {
  977. Drawable* occluder = occluders[i];
  978. occluder->UpdateDistance(frame_);
  979. bool erase = false;
  980. // Check view mask
  981. if (!(cameraViewMask & occluder->GetViewMask()))
  982. erase = true;
  983. // Check occluder's draw distance (in main camera view)
  984. float maxDistance = occluder->GetDrawDistance();
  985. if ((maxDistance > 0.0f) && (occluder->GetDistance() > maxDistance))
  986. erase = true;
  987. // Check that occluder is big enough on the screen
  988. const BoundingBox& box = occluder->GetWorldBoundingBox();
  989. float diagonal = (box.max_ - box.min_).LengthFast();
  990. float compare;
  991. if (!camera->IsOrthographic())
  992. compare = diagonal * halfViewSize / occluder->GetDistance();
  993. else
  994. compare = diagonal * invOrthoSize;
  995. if (compare < occluderSizeThreshold_)
  996. erase = true;
  997. if (!erase)
  998. {
  999. unsigned totalTriangles = 0;
  1000. unsigned batches = occluder->GetNumBatches();
  1001. Batch tempBatch;
  1002. for (unsigned j = 0; j < batches; ++j)
  1003. {
  1004. occluder->GetBatch(frame_, j, tempBatch);
  1005. if (tempBatch.geometry_)
  1006. totalTriangles += tempBatch.geometry_->GetIndexCount() / 3;
  1007. }
  1008. // Store amount of triangles divided by screen size as a sorting key
  1009. // (best occluders are big and have few triangles)
  1010. occluder->SetSortValue((float)totalTriangles / compare);
  1011. }
  1012. else
  1013. {
  1014. occluders.Erase(occluders.Begin() + i);
  1015. --i;
  1016. }
  1017. }
  1018. // Sort occluders so that if triangle budget is exceeded, best occluders have been drawn
  1019. if (occluders.Size())
  1020. Sort(occluders.Begin(), occluders.End(), CompareDrawables);
  1021. }
  1022. void View::DrawOccluders(OcclusionBuffer* buffer, const PODVector<Drawable*>& occluders)
  1023. {
  1024. for (unsigned i = 0; i < occluders.Size(); ++i)
  1025. {
  1026. Drawable* occluder = occluders[i];
  1027. if (i > 0)
  1028. {
  1029. // For subsequent occluders, do a test against the pixel-level occlusion buffer to see if rendering is necessary
  1030. if (!buffer->IsVisible(occluder->GetWorldBoundingBox()))
  1031. continue;
  1032. }
  1033. occluder->UpdateGeometry(frame_);
  1034. // Check for running out of triangles
  1035. if (!occluder->DrawOcclusion(buffer))
  1036. return;
  1037. }
  1038. }
  1039. unsigned View::ProcessLight(Light* light)
  1040. {
  1041. unsigned numLitGeometries = 0;
  1042. unsigned numShadowCasters = 0;
  1043. unsigned numSplits;
  1044. // Check if light should be shadowed
  1045. bool isShadowed = (drawShadows_) && (light->GetCastShadows());
  1046. // If shadow distance non-zero, check it
  1047. if ((isShadowed) && (light->GetShadowDistance() > 0.0f) && (light->GetDistance() > light->GetShadowDistance()))
  1048. isShadowed = false;
  1049. // If light has no ramp textures defined, set defaults
  1050. if ((light->GetLightType() != LIGHT_DIRECTIONAL) && (!light->GetRampTexture()))
  1051. light->SetRampTexture(renderer_->GetDefaultLightRamp());
  1052. if ((light->GetLightType() == LIGHT_SPOT) && (!light->GetShapeTexture()))
  1053. light->SetShapeTexture(renderer_->GetDefaultLightSpot());
  1054. // Split the light if necessary
  1055. if (isShadowed)
  1056. numSplits = SplitLight(light);
  1057. else
  1058. {
  1059. // No splitting, use the original light
  1060. splitLights_[0] = light;
  1061. numSplits = 1;
  1062. }
  1063. // For a shadowed directional light, get occluders once using the whole (non-split) light frustum
  1064. bool useOcclusion = false;
  1065. OcclusionBuffer* buffer = 0;
  1066. if ((maxOccluderTriangles_ > 0) && (isShadowed) && (light->GetLightType() == LIGHT_DIRECTIONAL))
  1067. {
  1068. // This shadow camera is never used for actually querying shadow casters, just occluders
  1069. Camera* shadowCamera = renderer_->CreateShadowCamera();
  1070. light->SetShadowCamera(shadowCamera);
  1071. SetupShadowCamera(light, true);
  1072. // Get occluders, which must be shadow-casting themselves
  1073. FrustumOctreeQuery query(shadowOccluders_, shadowCamera->GetFrustum(), DRAWABLE_GEOMETRY, true, true);
  1074. octree_->GetDrawables(query);
  1075. UpdateOccluders(shadowOccluders_, shadowCamera);
  1076. if (shadowOccluders_.Size())
  1077. {
  1078. // Shadow viewport is rectangular and consumes more CPU fillrate, so halve size
  1079. buffer = renderer_->GetOrCreateOcclusionBuffer(shadowCamera, maxOccluderTriangles_, true);
  1080. DrawOccluders(buffer, shadowOccluders_);
  1081. buffer->BuildDepthHierarchy();
  1082. useOcclusion = true;
  1083. }
  1084. }
  1085. // Process each split for shadow camera update, lit geometries, and shadow casters
  1086. for (unsigned i = 0; i < numSplits; ++i)
  1087. {
  1088. litGeometries_[i].Clear();
  1089. shadowCasters_[i].Clear();
  1090. }
  1091. for (unsigned i = 0; i < numSplits; ++i)
  1092. {
  1093. Light* split = splitLights_[i];
  1094. LightType type = split->GetLightType();
  1095. bool isSplitShadowed = (isShadowed) && (split->GetCastShadows());
  1096. Camera* shadowCamera = 0;
  1097. // If shadow casting, choose the shadow map & update shadow camera
  1098. if (isSplitShadowed)
  1099. {
  1100. shadowCamera = renderer_->CreateShadowCamera();
  1101. split->SetShadowMap(renderer_->GetShadowMap(splitLights_[i]->GetShadowResolution()));
  1102. // Check if managed to get a shadow map. Otherwise must convert to non-shadowed
  1103. if (split->GetShadowMap())
  1104. {
  1105. split->SetShadowCamera(shadowCamera);
  1106. SetupShadowCamera(split);
  1107. }
  1108. else
  1109. {
  1110. isSplitShadowed = false;
  1111. split->SetShadowCamera(0);
  1112. }
  1113. }
  1114. else
  1115. {
  1116. split->SetShadowCamera(0);
  1117. split->SetShadowMap(0);
  1118. }
  1119. BoundingBox geometryBox;
  1120. BoundingBox shadowCasterBox;
  1121. switch (type)
  1122. {
  1123. case LIGHT_DIRECTIONAL:
  1124. // Loop through visible geometries and check if they belong to this split
  1125. {
  1126. float nearSplit = split->GetNearSplit() - split->GetNearFadeRange();
  1127. float farSplit = split->GetFarSplit();
  1128. // If split extends to the whole visible frustum, no depth check necessary
  1129. bool optimize = (nearSplit <= camera_->GetNearClip()) && (farSplit >= camera_->GetFarClip());
  1130. // If whole visible scene is outside the split, can reject trivially
  1131. if ((sceneViewBox_.min_.z_ > farSplit) || (sceneViewBox_.max_.z_ < nearSplit))
  1132. {
  1133. split->SetShadowMap(0);
  1134. continue;
  1135. }
  1136. bool generateBoxes = (isSplitShadowed) && (split->GetShadowFocus().focus_);
  1137. Matrix3x4 lightView;
  1138. if (shadowCamera)
  1139. lightView = shadowCamera->GetInverseWorldTransform();
  1140. if (!optimize)
  1141. {
  1142. for (unsigned j = 0; j < geometries_.Size(); ++j)
  1143. {
  1144. Drawable* drawable = geometries_[j];
  1145. const GeometryDepthBounds& bounds = geometryDepthBounds_[j];
  1146. // Check bounds and light mask
  1147. if ((bounds.min_ <= farSplit) && (bounds.max_ >= nearSplit) && (drawable->GetLightMask() &
  1148. split->GetLightMask()))
  1149. {
  1150. litGeometries_[i].Push(drawable);
  1151. if (generateBoxes)
  1152. geometryBox.Merge(drawable->GetWorldBoundingBox().Transformed(lightView));
  1153. }
  1154. }
  1155. }
  1156. else
  1157. {
  1158. for (unsigned j = 0; j < geometries_.Size(); ++j)
  1159. {
  1160. Drawable* drawable = geometries_[j];
  1161. // Need to check light mask only
  1162. if (drawable->GetLightMask() & split->GetLightMask())
  1163. {
  1164. litGeometries_[i].Push(drawable);
  1165. if (generateBoxes)
  1166. geometryBox.Merge(drawable->GetWorldBoundingBox().Transformed(lightView));
  1167. }
  1168. }
  1169. }
  1170. }
  1171. // Then get shadow casters by shadow camera frustum query. Use occlusion because of potentially many geometries
  1172. if ((isSplitShadowed) && (litGeometries_[i].Size()))
  1173. {
  1174. Camera* shadowCamera = split->GetShadowCamera();
  1175. if (!useOcclusion)
  1176. {
  1177. // Get potential shadow casters without occlusion
  1178. FrustumOctreeQuery query(tempDrawables_, shadowCamera->GetFrustum(), DRAWABLE_GEOMETRY);
  1179. octree_->GetDrawables(query);
  1180. }
  1181. else
  1182. {
  1183. // Get potential shadow casters with occlusion
  1184. OccludedFrustumOctreeQuery query(tempDrawables_, shadowCamera->GetFrustum(), buffer,
  1185. DRAWABLE_GEOMETRY);
  1186. octree_->GetDrawables(query);
  1187. }
  1188. ProcessLightQuery(i, tempDrawables_, geometryBox, shadowCasterBox, false, isSplitShadowed);
  1189. }
  1190. break;
  1191. case LIGHT_POINT:
  1192. {
  1193. SphereOctreeQuery query(tempDrawables_, Sphere(split->GetWorldPosition(), split->GetRange()), DRAWABLE_GEOMETRY);
  1194. octree_->GetDrawables(query);
  1195. ProcessLightQuery(i, tempDrawables_, geometryBox, shadowCasterBox, true, false);
  1196. }
  1197. break;
  1198. case LIGHT_SPOT:
  1199. case LIGHT_SPLITPOINT:
  1200. {
  1201. FrustumOctreeQuery query(tempDrawables_, splitLights_[i]->GetFrustum(), DRAWABLE_GEOMETRY);
  1202. octree_->GetDrawables(query);
  1203. ProcessLightQuery(i, tempDrawables_, geometryBox, shadowCasterBox, true, isSplitShadowed);
  1204. }
  1205. break;
  1206. }
  1207. // Optimization: if a particular split has no shadow casters, render as unshadowed
  1208. if (!shadowCasters_[i].Size())
  1209. split->SetShadowMap(0);
  1210. // Focus shadow camera as applicable
  1211. if (split->GetShadowMap())
  1212. {
  1213. if (split->GetShadowFocus().focus_)
  1214. FocusShadowCamera(split, geometryBox, shadowCasterBox);
  1215. // Set a zoom factor to ensure that we do not render to the shadow map border
  1216. // (clamp addressing is necessary because border mode /w hardware shadow maps is not supported by all GPUs)
  1217. Camera* shadowCamera = split->GetShadowCamera();
  1218. Texture2D* shadowMap = split->GetShadowMap();
  1219. if (shadowCamera->GetZoom() >= 1.0f)
  1220. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((float)(shadowMap->GetWidth() - 2) / (float)shadowMap->GetWidth()));
  1221. }
  1222. // Update count of total lit geometries & shadow casters
  1223. numLitGeometries += litGeometries_[i].Size();
  1224. numShadowCasters += shadowCasters_[i].Size();
  1225. }
  1226. // If no lit geometries at all, no need to process further
  1227. if (!numLitGeometries)
  1228. numSplits = 0;
  1229. // If no shadow casters at all, concatenate lit geometries into one & return the original light
  1230. else if (!numShadowCasters)
  1231. {
  1232. if (numSplits > 1)
  1233. {
  1234. // Make sure there are no duplicates
  1235. HashSet<Drawable*> allLitGeometries;
  1236. for (unsigned i = 0; i < numSplits; ++i)
  1237. {
  1238. for (Vector<Drawable*>::Iterator j = litGeometries_[i].Begin(); j != litGeometries_[i].End(); ++j)
  1239. allLitGeometries.Insert(*j);
  1240. }
  1241. litGeometries_[0].Resize(allLitGeometries.Size());
  1242. unsigned index = 0;
  1243. for (HashSet<Drawable*>::Iterator i = allLitGeometries.Begin(); i != allLitGeometries.End(); ++i)
  1244. litGeometries_[0][index++] = *i;
  1245. }
  1246. splitLights_[0] = light;
  1247. splitLights_[0]->SetShadowMap(0);
  1248. numSplits = 1;
  1249. }
  1250. return numSplits;
  1251. }
  1252. void View::ProcessLightQuery(unsigned splitIndex, const PODVector<Drawable*>& result, BoundingBox& geometryBox,
  1253. BoundingBox& shadowCasterBox, bool getLitGeometries, bool GetShadowCasters)
  1254. {
  1255. Light* light = splitLights_[splitIndex];
  1256. Matrix3x4 lightView;
  1257. Matrix4 lightProj;
  1258. Frustum lightViewFrustum;
  1259. BoundingBox lightViewFrustumBox;
  1260. bool mergeBoxes = (light->GetLightType() != LIGHT_SPLITPOINT) && (light->GetShadowMap()) && (light->GetShadowFocus().focus_);
  1261. bool projectBoxes = false;
  1262. Camera* shadowCamera = light->GetShadowCamera();
  1263. if (shadowCamera)
  1264. {
  1265. bool projectBoxes = !shadowCamera->IsOrthographic();
  1266. lightView = shadowCamera->GetInverseWorldTransform();
  1267. lightProj = shadowCamera->GetProjection();
  1268. // Transform scene frustum into shadow camera's view space for shadow caster visibility check
  1269. // For point & spot lights, we can use the whole scene frustum. For directional lights, use the
  1270. // intersection of the scene frustum and the split frustum, so that shadow casters do not get
  1271. // rendered into unnecessary splits
  1272. if (light->GetLightType() != LIGHT_DIRECTIONAL)
  1273. lightViewFrustum = camera_->GetSplitFrustum(sceneViewBox_.min_.z_, sceneViewBox_.max_.z_).Transformed(lightView);
  1274. else
  1275. lightViewFrustum = camera_->GetSplitFrustum(Max(sceneViewBox_.min_.z_, light->GetNearSplit() - light->GetNearFadeRange()),
  1276. Min(sceneViewBox_.max_.z_, light->GetFarSplit())).Transformed(lightView);
  1277. lightViewFrustumBox.Define(lightViewFrustum);
  1278. // Check for degenerate split frustum: in that case there is no need to get shadow casters
  1279. if (lightViewFrustum.vertices_[0] == lightViewFrustum.vertices_[4])
  1280. GetShadowCasters = false;
  1281. }
  1282. else
  1283. GetShadowCasters = false;
  1284. BoundingBox lightViewBox;
  1285. BoundingBox lightProjBox;
  1286. for (unsigned i = 0; i < result.Size(); ++i)
  1287. {
  1288. Drawable* drawable = static_cast<Drawable*>(result[i]);
  1289. drawable->UpdateDistance(frame_);
  1290. bool boxGenerated = false;
  1291. // If draw distance non-zero, check it
  1292. float maxDistance = drawable->GetDrawDistance();
  1293. if ((maxDistance > 0.0f) && (drawable->GetDistance() > maxDistance))
  1294. continue;
  1295. // Check light mask
  1296. if (!(drawable->GetLightMask() & light->GetLightMask()))
  1297. continue;
  1298. // Get lit geometry only if inside main camera frustum this frame
  1299. if ((getLitGeometries) && (drawable->IsInView(frame_)))
  1300. {
  1301. if (mergeBoxes)
  1302. {
  1303. // Transform bounding box into light view space, and to projection space if needed
  1304. lightViewBox = drawable->GetWorldBoundingBox().Transformed(lightView);
  1305. if (!projectBoxes)
  1306. geometryBox.Merge(lightViewBox);
  1307. else
  1308. {
  1309. lightProjBox = lightViewBox.Projected(lightProj);
  1310. geometryBox.Merge(lightProjBox);
  1311. }
  1312. boxGenerated = true;
  1313. }
  1314. litGeometries_[splitIndex].Push(drawable);
  1315. }
  1316. // Shadow caster need not be inside main camera frustum: in that case try to detect whether
  1317. // the shadow projection intersects the view
  1318. if ((GetShadowCasters) && (drawable->GetCastShadows()))
  1319. {
  1320. // If shadow distance non-zero, check it
  1321. float maxShadowDistance = drawable->GetShadowDistance();
  1322. if ((maxShadowDistance > 0.0f) && (drawable->GetDistance() > maxShadowDistance))
  1323. continue;
  1324. if (!boxGenerated)
  1325. lightViewBox = drawable->GetWorldBoundingBox().Transformed(lightView);
  1326. if (IsShadowCasterVisible(drawable, lightViewBox, shadowCamera, lightView, lightViewFrustum, lightViewFrustumBox))
  1327. {
  1328. if (mergeBoxes)
  1329. {
  1330. if (!projectBoxes)
  1331. shadowCasterBox.Merge(lightViewBox);
  1332. else
  1333. {
  1334. if (!boxGenerated)
  1335. lightProjBox = lightViewBox.Projected(lightProj);
  1336. shadowCasterBox.Merge(lightProjBox);
  1337. }
  1338. }
  1339. // Update geometry now if not updated yet
  1340. if (!drawable->IsInView(frame_))
  1341. {
  1342. drawable->MarkInShadowView(frame_);
  1343. drawable->UpdateGeometry(frame_);
  1344. }
  1345. shadowCasters_[splitIndex].Push(drawable);
  1346. }
  1347. }
  1348. }
  1349. }
  1350. bool View::IsShadowCasterVisible(Drawable* drawable, BoundingBox lightViewBox, Camera* shadowCamera, const Matrix3x4& lightView,
  1351. const Frustum& lightViewFrustum, const BoundingBox& lightViewFrustumBox)
  1352. {
  1353. // If shadow caster is also an occluder, must let it be visible, because it has potentially already culled
  1354. // away other shadow casters (could also check the actual shadow occluder vector, but that would be slower)
  1355. if (drawable->IsOccluder())
  1356. return true;
  1357. if (shadowCamera->IsOrthographic())
  1358. {
  1359. // Extrude the light space bounding box up to the far edge of the frustum's light space bounding box
  1360. lightViewBox.max_.z_ = Max(lightViewBox.max_.z_,lightViewFrustumBox.max_.z_);
  1361. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  1362. }
  1363. else
  1364. {
  1365. // If light is not directional, can do a simple check: if object is visible, its shadow is too
  1366. if (drawable->IsInView(frame_))
  1367. return true;
  1368. // For perspective lights, extrusion direction depends on the position of the shadow caster
  1369. Vector3 center = lightViewBox.Center();
  1370. Ray extrusionRay(center, center.Normalized());
  1371. float extrusionDistance = shadowCamera->GetFarClip();
  1372. float originalDistance = Clamp(center.LengthFast(), M_EPSILON, extrusionDistance);
  1373. // Because of the perspective, the bounding box must also grow when it is extruded to the distance
  1374. float sizeFactor = extrusionDistance / originalDistance;
  1375. // Calculate the endpoint box and merge it to the original. Because it's axis-aligned, it will be larger
  1376. // than necessary, so the test will be conservative
  1377. Vector3 newCenter = extrusionDistance * extrusionRay.direction_;
  1378. Vector3 newHalfSize = lightViewBox.Size() * sizeFactor * 0.5f;
  1379. BoundingBox extrudedBox(newCenter - newHalfSize, newCenter + newHalfSize);
  1380. lightViewBox.Merge(extrudedBox);
  1381. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  1382. }
  1383. }
  1384. void View::SetupShadowCamera(Light* light, bool shadowOcclusion)
  1385. {
  1386. Camera* shadowCamera = light->GetShadowCamera();
  1387. Node* cameraNode = shadowCamera->GetNode();
  1388. const FocusParameters& parameters = light->GetShadowFocus();
  1389. // Reset zoom
  1390. shadowCamera->SetZoom(1.0f);
  1391. switch(light->GetLightType())
  1392. {
  1393. case LIGHT_DIRECTIONAL:
  1394. {
  1395. float extrusionDistance = camera_->GetFarClip();
  1396. // Calculate initial position & rotation
  1397. Vector3 lightWorldDirection = light->GetWorldRotation() * Vector3::FORWARD;
  1398. Vector3 pos = camera_->GetWorldPosition() - extrusionDistance * lightWorldDirection;
  1399. Quaternion rot(Vector3::FORWARD, lightWorldDirection);
  1400. cameraNode->SetTransform(pos, rot);
  1401. // Calculate main camera shadowed frustum in light's view space
  1402. float sceneMaxZ = camera_->GetFarClip();
  1403. // When shadow focusing is enabled, use the scene far Z to limit maximum frustum size
  1404. if ((shadowOcclusion) || (parameters.focus_))
  1405. sceneMaxZ = Min(sceneViewBox_.max_.z_, sceneMaxZ);
  1406. Matrix3x4 lightView(shadowCamera->GetInverseWorldTransform());
  1407. Frustum lightViewSplitFrustum = camera_->GetSplitFrustum(light->GetNearSplit() - light->GetNearFadeRange(),
  1408. Min(light->GetFarSplit(), sceneMaxZ)).Transformed(lightView);
  1409. // Fit the frustum inside a bounding box. If uniform size, use a sphere instead
  1410. BoundingBox shadowBox;
  1411. if ((!shadowOcclusion) && (parameters.nonUniform_))
  1412. shadowBox.Define(lightViewSplitFrustum);
  1413. else
  1414. {
  1415. Sphere shadowSphere;
  1416. shadowSphere.Define(lightViewSplitFrustum);
  1417. shadowBox.Define(shadowSphere);
  1418. }
  1419. shadowCamera->SetOrthographic(true);
  1420. shadowCamera->SetNearClip(0.0f);
  1421. shadowCamera->SetFarClip(shadowBox.max_.z_);
  1422. // Center shadow camera on the bounding box, snap to whole texels
  1423. QuantizeDirShadowCamera(light, shadowBox);
  1424. }
  1425. break;
  1426. case LIGHT_SPOT:
  1427. case LIGHT_SPLITPOINT:
  1428. {
  1429. cameraNode->SetTransform(light->GetWorldPosition(), light->GetWorldRotation());
  1430. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  1431. shadowCamera->SetFarClip(light->GetRange());
  1432. shadowCamera->SetOrthographic(false);
  1433. shadowCamera->SetFov(light->GetFov());
  1434. shadowCamera->SetAspectRatio(light->GetAspectRatio());
  1435. // For spot lights, zoom out shadowmap if far away (reduces fillrate)
  1436. if ((light->GetLightType() == LIGHT_SPOT) && (parameters.zoomOut_))
  1437. {
  1438. // Make sure the out-zooming does not start while we are inside the spot
  1439. float distance = Max((camera_->GetInverseWorldTransform() * light->GetWorldPosition()).z_ - light->GetRange(), 1.0f);
  1440. float lightPixels = (((float)height_ * light->GetRange() * camera_->GetZoom() * 0.5f) / distance);
  1441. // Clamp pixel amount to a sufficient minimum to avoid self-shadowing artifacts due to loss of precision
  1442. if (lightPixels < SHADOW_MIN_PIXELS)
  1443. lightPixels = SHADOW_MIN_PIXELS;
  1444. float zoolevel_ = Min(lightPixels / (float)light->GetShadowMap()->GetHeight(), 1.0f);
  1445. shadowCamera->SetZoom(zoolevel_);
  1446. }
  1447. }
  1448. break;
  1449. }
  1450. }
  1451. void View::FocusShadowCamera(Light* light, const BoundingBox& geometryBox, const BoundingBox& shadowCasterBox)
  1452. {
  1453. // If either no geometries or no shadow casters, do nothing
  1454. if ((!geometryBox.defined_) || (!shadowCasterBox.defined_))
  1455. return;
  1456. Camera* shadowCamera = light->GetShadowCamera();
  1457. const FocusParameters& parameters = light->GetShadowFocus();
  1458. switch (light->GetLightType())
  1459. {
  1460. case LIGHT_DIRECTIONAL:
  1461. {
  1462. BoundingBox combinedBox;
  1463. combinedBox.max_.y_ = shadowCamera->GetOrthoSize() * 0.5f;
  1464. combinedBox.max_.x_ = shadowCamera->GetAspectRatio() * combinedBox.max_.y_;
  1465. combinedBox.min_.y_ = -combinedBox.max_.y_;
  1466. combinedBox.min_.x_ = -combinedBox.max_.x_;
  1467. combinedBox.Intersect(geometryBox);
  1468. combinedBox.Intersect(shadowCasterBox);
  1469. QuantizeDirShadowCamera(light, combinedBox);
  1470. }
  1471. break;
  1472. case LIGHT_SPOT:
  1473. // Can not move, but can zoom the shadow camera. Check for out-zooming (distant shadow map), do nothing in that case
  1474. if (shadowCamera->GetZoom() >= 1.0f)
  1475. {
  1476. BoundingBox combinedBox(-1.0f, 1.0f);
  1477. combinedBox.Intersect(geometryBox);
  1478. combinedBox.Intersect(shadowCasterBox);
  1479. float viewSizeX = Max(fabsf(combinedBox.min_.x_), fabsf(combinedBox.max_.x_));
  1480. float viewSizeY = Max(fabsf(combinedBox.min_.y_), fabsf(combinedBox.max_.y_));
  1481. float viewSize = Max(viewSizeX, viewSizeY);
  1482. // Scale the quantization parameters, because view size is in projection space (-1.0 - 1.0)
  1483. float invOrthoSize = 1.0f / shadowCamera->GetOrthoSize();
  1484. float quantize = parameters.quantize_ * invOrthoSize;
  1485. float minView = parameters.minView_ * invOrthoSize;
  1486. viewSize = Max(ceilf(viewSize / quantize) * quantize, minView);
  1487. if (viewSize < 1.0f)
  1488. shadowCamera->SetZoom(1.0f / viewSize);
  1489. }
  1490. break;
  1491. }
  1492. }
  1493. void View::QuantizeDirShadowCamera(Light* light, const BoundingBox& viewBox)
  1494. {
  1495. Camera* shadowCamera = light->GetShadowCamera();
  1496. Node* cameraNode = shadowCamera->GetNode();
  1497. const FocusParameters& parameters = light->GetShadowFocus();
  1498. float minX = viewBox.min_.x_;
  1499. float minY = viewBox.min_.y_;
  1500. float maxX = viewBox.max_.x_;
  1501. float maxY = viewBox.max_.y_;
  1502. Vector2 center((minX + maxX) * 0.5f, (minY + maxY) * 0.5f);
  1503. Vector2 viewSize(maxX - minX, maxY - minY);
  1504. // Quantize size to reduce swimming
  1505. // Note: if size is uniform and there is no focusing, quantization is unnecessary
  1506. if (parameters.nonUniform_)
  1507. {
  1508. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  1509. viewSize.y_ = ceilf(sqrtf(viewSize.y_ / parameters.quantize_));
  1510. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  1511. viewSize.y_ = Max(viewSize.y_ * viewSize.y_ * parameters.quantize_, parameters.minView_);
  1512. }
  1513. else if (parameters.focus_)
  1514. {
  1515. viewSize.x_ = Max(viewSize.x_, viewSize.y_);
  1516. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  1517. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  1518. viewSize.y_ = viewSize.x_;
  1519. }
  1520. shadowCamera->SetOrthoSize(viewSize);
  1521. // Center shadow camera to the view space bounding box
  1522. Vector3 pos = shadowCamera->GetWorldPosition();
  1523. Quaternion rot = shadowCamera->GetWorldRotation();
  1524. Vector3 adjust(center.x_, center.y_, 0.0f);
  1525. cameraNode->Translate(rot * adjust);
  1526. // If there is a shadow map, snap to its whole texels
  1527. Texture2D* shadowMap = light->GetShadowMap();
  1528. if (shadowMap)
  1529. {
  1530. Vector3 viewPos(rot.Inverse() * shadowCamera->GetWorldPosition());
  1531. // Take into account that shadow map border will not be used
  1532. float invActualSize = 1.0f / (float)(shadowMap->GetWidth() - 2);
  1533. Vector2 texelSize(viewSize.x_ * invActualSize, viewSize.y_ * invActualSize);
  1534. Vector3 snap(-fmodf(viewPos.x_, texelSize.x_), -fmodf(viewPos.y_, texelSize.y_), 0.0f);
  1535. cameraNode->Translate(rot * snap);
  1536. }
  1537. }
  1538. void View::OptimizeLightByScissor(Light* light)
  1539. {
  1540. if (light)
  1541. graphics_->SetScissorTest(true, GetLightScissor(light));
  1542. else
  1543. graphics_->SetScissorTest(false);
  1544. }
  1545. const Rect& View::GetLightScissor(Light* light)
  1546. {
  1547. Map<Light*, Rect>::Iterator i = lightScissorCache_.Find(light);
  1548. if (i != lightScissorCache_.End())
  1549. return i->second_;
  1550. Matrix3x4 view(camera_->GetInverseWorldTransform());
  1551. Matrix4 projection(camera_->GetProjection());
  1552. switch (light->GetLightType())
  1553. {
  1554. case LIGHT_POINT:
  1555. {
  1556. BoundingBox viewBox = light->GetWorldBoundingBox().Transformed(view);
  1557. return lightScissorCache_[light] = viewBox.Projected(projection);
  1558. }
  1559. case LIGHT_SPOT:
  1560. case LIGHT_SPLITPOINT:
  1561. {
  1562. Frustum viewFrustum = light->GetFrustum().Transformed(view);
  1563. return lightScissorCache_[light] = viewFrustum.Projected(projection);
  1564. }
  1565. default:
  1566. return lightScissorCache_[light] = Rect::FULL;
  1567. }
  1568. }
  1569. unsigned View::SplitLight(Light* light)
  1570. {
  1571. LightType type = light->GetLightType();
  1572. if (type == LIGHT_DIRECTIONAL)
  1573. {
  1574. const CascadeParameters& cascade = light->GetShadowCascade();
  1575. unsigned splits = cascade.splits_;
  1576. if (splits > MAX_LIGHT_SPLITS - 1)
  1577. splits = MAX_LIGHT_SPLITS;
  1578. // Orthographic view actually has near clip 0, but clamp it to a theoretical minimum
  1579. float farClip = Min(cascade.shadowRange_, camera_->GetFarClip()); // Shadow range end
  1580. float nearClip = Max(camera_->GetNearClip(), M_MIN_NEARCLIP); // Shadow range start
  1581. bool CreateExtraSplit = farClip < camera_->GetFarClip();
  1582. // Practical split scheme (Zhang et al.)
  1583. unsigned i;
  1584. for (i = 0; i < splits; ++i)
  1585. {
  1586. // Set a minimum for the fade range to avoid boundary artifacts (missing lighting)
  1587. float splitFadeRange = Max(cascade.splitFadeRange_, 0.001f);
  1588. float iPerM = (float)i / (float)splits;
  1589. float log = nearClip * powf(farClip / nearClip, iPerM);
  1590. float uniform = nearClip + (farClip - nearClip) * iPerM;
  1591. float nearSplit = log * cascade.lambda_ + uniform * (1.0f - cascade.lambda_);
  1592. float nearFadeRange = nearSplit * splitFadeRange;
  1593. iPerM = (float)(i + 1) / (float)splits;
  1594. log = nearClip * powf(farClip / nearClip, iPerM);
  1595. uniform = nearClip + (farClip - nearClip) * iPerM;
  1596. float farSplit = log * cascade.lambda_ + uniform * (1.0f - cascade.lambda_);
  1597. float farFadeRange = farSplit * splitFadeRange;
  1598. // If split is completely beyond camera far clip, we are done
  1599. if ((nearSplit - nearFadeRange) > camera_->GetFarClip())
  1600. break;
  1601. Light* SplitLight = renderer_->CreateSplitLight(light);
  1602. splitLights_[i] = SplitLight;
  1603. // Though the near clip was previously clamped, use the real near clip value for the first split,
  1604. // so that there are no unlit portions
  1605. if (i)
  1606. SplitLight->SetNearSplit(nearSplit);
  1607. else
  1608. SplitLight->SetNearSplit(camera_->GetNearClip());
  1609. SplitLight->SetNearFadeRange(nearFadeRange);
  1610. SplitLight->SetFarSplit(farSplit);
  1611. // The final split will not fade
  1612. if ((CreateExtraSplit) || (i < splits - 1))
  1613. SplitLight->SetFarFadeRange(farFadeRange);
  1614. // Create an extra unshadowed split if necessary
  1615. if ((CreateExtraSplit) && (i == splits - 1))
  1616. {
  1617. Light* SplitLight = renderer_->CreateSplitLight(light);
  1618. splitLights_[i + 1] = SplitLight;
  1619. SplitLight->SetNearSplit(farSplit);
  1620. SplitLight->SetNearFadeRange(farFadeRange);
  1621. SplitLight->SetCastShadows(false);
  1622. }
  1623. }
  1624. if (CreateExtraSplit)
  1625. return i + 1;
  1626. else
  1627. return i;
  1628. }
  1629. if (type == LIGHT_POINT)
  1630. {
  1631. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1632. {
  1633. Light* SplitLight = renderer_->CreateSplitLight(light);
  1634. Node* lightNode = SplitLight->GetNode();
  1635. splitLights_[i] = SplitLight;
  1636. SplitLight->SetLightType(LIGHT_SPLITPOINT);
  1637. // When making a shadowed point light, align the splits along X, Y and Z axes regardless of light rotation
  1638. lightNode->SetDirection(directions[i]);
  1639. SplitLight->SetFov(90.0f);
  1640. SplitLight->SetAspectRatio(1.0f);
  1641. }
  1642. return MAX_CUBEMAP_FACES;
  1643. }
  1644. // A spot light does not actually need splitting. However, we may be rendering several views,
  1645. // and in some the light might be unshadowed, so better create an unique copy
  1646. Light* SplitLight = renderer_->CreateSplitLight(light);
  1647. splitLights_[0] = SplitLight;
  1648. return 1;
  1649. }
  1650. Technique* View::GetTechnique(Drawable* drawable, Material*& material)
  1651. {
  1652. if (!material)
  1653. material = renderer_->GetDefaultMaterial();
  1654. if (!material)
  1655. return 0;
  1656. float lodDistance = drawable->GetLodDistance();
  1657. const Vector<TechniqueEntry>& techniques = material->GetTechniques();
  1658. if (techniques.Empty())
  1659. return 0;
  1660. // Check for suitable technique. Techniques should be ordered like this:
  1661. // Most distant & highest quality
  1662. // Most distant & lowest quality
  1663. // Second most distant & highest quality
  1664. // ...
  1665. for (unsigned i = 0; i < techniques.Size(); ++i)
  1666. {
  1667. const TechniqueEntry& entry = techniques[i];
  1668. Technique* technique = entry.technique_;
  1669. if ((!technique) || ((technique->IsSM3()) && (!graphics_->GetSM3Support())) || (materialQuality_ < entry.qualityLevel_))
  1670. continue;
  1671. if (lodDistance >= entry.lodDistance_)
  1672. return technique;
  1673. }
  1674. // If no suitable technique found, fallback to the last
  1675. return techniques.Back().technique_;
  1676. }
  1677. void View::CheckMaterialForAuxView(Material* material)
  1678. {
  1679. const Vector<SharedPtr<Texture> >& textures = material->GetTextures();
  1680. for (unsigned i = 0; i < textures.Size(); ++i)
  1681. {
  1682. // Have to check cube & 2D textures separately
  1683. Texture* texture = textures[i];
  1684. if (texture)
  1685. {
  1686. if (texture->GetType() == Texture2D::GetTypeStatic())
  1687. {
  1688. Texture2D* tex2D = static_cast<Texture2D*>(texture);
  1689. RenderSurface* target = tex2D->GetRenderSurface();
  1690. if (target)
  1691. {
  1692. const Viewport& viewport = target->GetViewport();
  1693. if ((viewport.scene_) && (viewport.camera_))
  1694. renderer_->AddView(target, viewport);
  1695. }
  1696. }
  1697. else if (texture->GetType() == TextureCube::GetTypeStatic())
  1698. {
  1699. TextureCube* texCube = static_cast<TextureCube*>(texture);
  1700. for (unsigned j = 0; j < MAX_CUBEMAP_FACES; ++j)
  1701. {
  1702. RenderSurface* target = texCube->GetRenderSurface((CubeMapFace)j);
  1703. if (target)
  1704. {
  1705. const Viewport& viewport = target->GetViewport();
  1706. if ((viewport.scene_) && (viewport.camera_))
  1707. renderer_->AddView(target, viewport);
  1708. }
  1709. }
  1710. }
  1711. }
  1712. }
  1713. // Set frame number so that we can early-out next time we come across this material on the same frame
  1714. material->MarkForAuxView(frame_.frameNumber_);
  1715. }
  1716. void View::SortBatches()
  1717. {
  1718. PROFILE(SortBatches);
  1719. if (mode_ != RENDER_FORWARD)
  1720. {
  1721. gBufferQueue_.SortFrontToBack();
  1722. noShadowLightQueue_.SortFrontToBack();
  1723. }
  1724. baseQueue_.SortFrontToBack();
  1725. extraQueue_.SortFrontToBack();
  1726. transparentQueue_.SortBackToFront();
  1727. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  1728. {
  1729. lightQueues_[i].shadowBatches_.SortFrontToBack();
  1730. lightQueues_[i].litBatches_.SortFrontToBack();
  1731. }
  1732. }
  1733. void View::PrepareInstancingBuffer()
  1734. {
  1735. PROFILE(PrepareInstancingBuffer);
  1736. unsigned totalInstances = 0;
  1737. if (mode_ != RENDER_FORWARD)
  1738. totalInstances += gBufferQueue_.GetNumInstances();
  1739. totalInstances += baseQueue_.GetNumInstances();
  1740. totalInstances += extraQueue_.GetNumInstances();
  1741. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  1742. {
  1743. totalInstances += lightQueues_[i].shadowBatches_.GetNumInstances();
  1744. totalInstances += lightQueues_[i].litBatches_.GetNumInstances();
  1745. }
  1746. // If fail to set buffer size, fall back to per-group locking
  1747. if ((totalInstances) && (renderer_->ResizeInstancingBuffer(totalInstances)))
  1748. {
  1749. unsigned freeIndex = 0;
  1750. void* lockedData = renderer_->instancingBuffer_->Lock(0, totalInstances, LOCK_DISCARD);
  1751. if (lockedData)
  1752. {
  1753. if (mode_ != RENDER_FORWARD)
  1754. gBufferQueue_.SetTransforms(lockedData, freeIndex);
  1755. baseQueue_.SetTransforms(lockedData, freeIndex);
  1756. extraQueue_.SetTransforms(lockedData, freeIndex);
  1757. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  1758. {
  1759. lightQueues_[i].shadowBatches_.SetTransforms(lockedData, freeIndex);
  1760. lightQueues_[i].litBatches_.SetTransforms(lockedData, freeIndex);
  1761. }
  1762. renderer_->instancingBuffer_->Unlock();
  1763. }
  1764. }
  1765. }
  1766. void View::CalculateShaderParameters()
  1767. {
  1768. Time* time = GetSubsystem<Time>();
  1769. float fogStart = zone_->GetFogStart();
  1770. float fogEnd = zone_->GetFogEnd();
  1771. float fogRange = Max(fogEnd - fogStart, M_EPSILON);
  1772. float farClip = camera_->GetFarClip();
  1773. float nearClip = camera_->GetNearClip();
  1774. Vector4 fogParams(fogStart / farClip, fogEnd / farClip, 1.0f / (fogRange / farClip), 0.0f);
  1775. Vector4 elapsedTime((time->GetTotalMSec() & 0x3fffff) / 1000.0f, 0.0f, 0.0f, 0.0f);
  1776. shaderParameters_.Clear();
  1777. shaderParameters_[VSP_ELAPSEDTIME] = elapsedTime;
  1778. shaderParameters_[PSP_AMBIENTCOLOR] = zone_->GetAmbientColor().ToVector4();
  1779. shaderParameters_[PSP_ELAPSEDTIME] = elapsedTime;
  1780. shaderParameters_[PSP_FOGCOLOR] = zone_->GetFogColor().ToVector4(),
  1781. shaderParameters_[PSP_FOGPARAMS] = fogParams;
  1782. }
  1783. void View::DrawSplitLightToStencil(Camera& camera, Light* light, bool clear)
  1784. {
  1785. graphics_->ClearTransformSources();
  1786. Matrix3x4 view(camera.GetInverseWorldTransform());
  1787. switch (light->GetLightType())
  1788. {
  1789. case LIGHT_SPLITPOINT:
  1790. if (!clear)
  1791. {
  1792. Matrix4 projection(camera.GetProjection());
  1793. const Matrix3x4& model = light->GetVolumeTransform(camera);
  1794. float lightExtent = light->GetVolumeExtent();
  1795. float lightViewDist = (light->GetWorldPosition() - camera.GetWorldPosition()).LengthFast();
  1796. bool drawBackFaces = lightViewDist < (lightExtent + camera.GetNearClip());
  1797. graphics_->SetAlphaTest(false);
  1798. graphics_->SetColorWrite(false);
  1799. graphics_->SetDepthWrite(false);
  1800. graphics_->SetCullMode(drawBackFaces ? CULL_CW : CULL_CCW);
  1801. graphics_->SetDepthTest(drawBackFaces ? CMP_GREATER : CMP_LESS);
  1802. graphics_->SetShaders(renderer_->stencilVS_, renderer_->stencilPS_);
  1803. graphics_->SetShaderParameter(VSP_MODEL, model);
  1804. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection * view);
  1805. // Draw the faces to stencil which we should draw (where no light has not been rendered yet)
  1806. graphics_->SetStencilTest(true, CMP_EQUAL, OP_INCR, OP_KEEP, OP_KEEP, 0);
  1807. renderer_->spotLightGeometry_->Draw(graphics_);
  1808. // Draw the other faces to stencil to mark where we should not draw ("frees up" the pixels for other faces)
  1809. graphics_->SetCullMode(drawBackFaces ? CULL_CCW : CULL_CW);
  1810. graphics_->SetStencilTest(true, CMP_EQUAL, OP_DECR, OP_KEEP, OP_KEEP, 1);
  1811. renderer_->spotLightGeometry_->Draw(graphics_);
  1812. // Now set stencil test for rendering the lit geometries (also marks the pixels so that they will not be used again)
  1813. graphics_->SetStencilTest(true, CMP_EQUAL, OP_INCR, OP_KEEP, OP_KEEP, 1);
  1814. graphics_->SetColorWrite(true);
  1815. }
  1816. else
  1817. {
  1818. // Clear stencil with a scissored clear operation
  1819. OptimizeLightByScissor(light->GetOriginalLight());
  1820. graphics_->Clear(CLEAR_STENCIL);
  1821. graphics_->SetScissorTest(false);
  1822. graphics_->SetStencilTest(false);
  1823. }
  1824. break;
  1825. case LIGHT_DIRECTIONAL:
  1826. // If light encompasses whole frustum, no drawing to frustum necessary
  1827. if ((light->GetNearSplit() <= camera.GetNearClip()) && (light->GetFarSplit() >= camera.GetFarClip()))
  1828. return;
  1829. else
  1830. {
  1831. if (!clear)
  1832. {
  1833. // Get projection without jitter offset to ensure the whole screen is filled
  1834. Matrix4 projection(camera.GetProjection(false));
  1835. Matrix3x4 nearTransform(light->GetDirLightTransform(camera, true));
  1836. Matrix3x4 farTransform(light->GetDirLightTransform(camera, false));
  1837. graphics_->SetAlphaTest(false);
  1838. graphics_->SetColorWrite(false);
  1839. graphics_->SetDepthWrite(false);
  1840. graphics_->SetCullMode(CULL_NONE);
  1841. // If the split begins at the near plane (first split), draw at split far plane
  1842. if (light->GetNearSplit() <= camera.GetNearClip())
  1843. {
  1844. graphics_->SetDepthTest(CMP_GREATEREQUAL);
  1845. graphics_->SetShaders(renderer_->stencilVS_, renderer_->stencilPS_);
  1846. graphics_->SetShaderParameter(VSP_MODEL, farTransform);
  1847. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  1848. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_ZERO, OP_ZERO, 1);
  1849. }
  1850. // Otherwise draw at split near plane
  1851. else
  1852. {
  1853. graphics_->SetDepthTest(CMP_LESSEQUAL);
  1854. graphics_->SetShaders(renderer_->stencilVS_, renderer_->stencilPS_);
  1855. graphics_->SetShaderParameter(VSP_MODEL, nearTransform);
  1856. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  1857. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_ZERO, OP_ZERO, 1);
  1858. }
  1859. renderer_->dirLightGeometry_->Draw(graphics_);
  1860. graphics_->SetColorWrite(true);
  1861. graphics_->SetStencilTest(true, CMP_EQUAL, OP_KEEP, OP_KEEP, OP_KEEP, 1);
  1862. }
  1863. else
  1864. {
  1865. // Clear the whole stencil
  1866. graphics_->SetScissorTest(false);
  1867. graphics_->Clear(CLEAR_STENCIL);
  1868. graphics_->SetStencilTest(false);
  1869. }
  1870. }
  1871. break;
  1872. }
  1873. }
  1874. void View::RenderBatchQueue(const BatchQueue& queue, bool useScissor, bool useLightBuffer, bool disableScissor)
  1875. {
  1876. Texture2D* diffBuffer = 0;
  1877. VertexBuffer* instancingBuffer = 0;
  1878. if (useLightBuffer)
  1879. diffBuffer = graphics_->GetDiffBuffer();
  1880. if (renderer_->GetDynamicInstancing())
  1881. instancingBuffer = renderer_->instancingBuffer_;
  1882. if (disableScissor)
  1883. graphics_->SetScissorTest(false);
  1884. graphics_->SetStencilTest(false);
  1885. // Priority instanced
  1886. for (Map<BatchGroupKey, BatchGroup>::ConstIterator i = queue.priorityBatchGroups_.Begin(); i !=
  1887. queue.priorityBatchGroups_.End(); ++i)
  1888. {
  1889. const BatchGroup& group = i->second_;
  1890. if ((useLightBuffer) && (!group.light_))
  1891. graphics_->SetTexture(TU_LIGHTBUFFER, diffBuffer);
  1892. group.Draw(graphics_, instancingBuffer, shaderParameters_);
  1893. }
  1894. // Priority non-instanced
  1895. for (PODVector<Batch*>::ConstIterator i = queue.sortedPriorityBatches_.Begin(); i != queue.sortedPriorityBatches_.End(); ++i)
  1896. {
  1897. Batch* batch = *i;
  1898. if ((useLightBuffer) && (!batch->light_))
  1899. graphics_->SetTexture(TU_LIGHTBUFFER, diffBuffer);
  1900. batch->Draw(graphics_, shaderParameters_);
  1901. }
  1902. // Non-priority instanced
  1903. for (Map<BatchGroupKey, BatchGroup>::ConstIterator i = queue.batchGroups_.Begin(); i !=
  1904. queue.batchGroups_.End(); ++i)
  1905. {
  1906. const BatchGroup& group = i->second_;
  1907. if ((useScissor) && (group.light_))
  1908. OptimizeLightByScissor(group.light_);
  1909. else
  1910. graphics_->SetScissorTest(false);
  1911. if ((useLightBuffer) && (!group.light_))
  1912. graphics_->SetTexture(TU_LIGHTBUFFER, diffBuffer);
  1913. group.Draw(graphics_, instancingBuffer, shaderParameters_);
  1914. }
  1915. // Non-priority non-instanced
  1916. for (PODVector<Batch*>::ConstIterator i = queue.sortedBatches_.Begin(); i != queue.sortedBatches_.End(); ++i)
  1917. {
  1918. Batch* batch = *i;
  1919. // For the transparent queue, both priority and non-priority batches are copied here, so check the flag
  1920. if ((useScissor) && (batch->light_) && (!batch->hasPriority_))
  1921. OptimizeLightByScissor(batch->light_);
  1922. else
  1923. graphics_->SetScissorTest(false);
  1924. if ((useLightBuffer) && (!batch->light_))
  1925. graphics_->SetTexture(TU_LIGHTBUFFER, diffBuffer);
  1926. batch->Draw(graphics_, shaderParameters_);
  1927. }
  1928. }
  1929. void View::RenderForwardLightBatchQueue(const BatchQueue& queue, Light* light)
  1930. {
  1931. VertexBuffer* instancingBuffer = 0;
  1932. if (renderer_->GetDynamicInstancing())
  1933. instancingBuffer = renderer_->instancingBuffer_;
  1934. graphics_->SetScissorTest(false);
  1935. graphics_->SetStencilTest(false);
  1936. // Priority instanced
  1937. for (Map<BatchGroupKey, BatchGroup>::ConstIterator i = queue.priorityBatchGroups_.Begin(); i !=
  1938. queue.priorityBatchGroups_.End(); ++i)
  1939. {
  1940. const BatchGroup& group = i->second_;
  1941. group.Draw(graphics_, instancingBuffer, shaderParameters_);
  1942. }
  1943. // Priority non-instanced
  1944. for (PODVector<Batch*>::ConstIterator i = queue.sortedPriorityBatches_.Begin(); i != queue.sortedPriorityBatches_.End(); ++i)
  1945. {
  1946. Batch* batch = *i;
  1947. batch->Draw(graphics_, shaderParameters_);
  1948. }
  1949. // All base passes have been drawn. Optimize at this point by both scissor and stencil
  1950. if (light)
  1951. {
  1952. OptimizeLightByScissor(light);
  1953. LightType type = light->GetLightType();
  1954. if ((type == LIGHT_SPLITPOINT) || (type == LIGHT_DIRECTIONAL))
  1955. DrawSplitLightToStencil(*camera_, light);
  1956. }
  1957. // Non-priority instanced
  1958. for (Map<BatchGroupKey, BatchGroup>::ConstIterator i = queue.batchGroups_.Begin(); i !=
  1959. queue.batchGroups_.End(); ++i)
  1960. {
  1961. const BatchGroup& group = i->second_;
  1962. group.Draw(graphics_, instancingBuffer, shaderParameters_);
  1963. }
  1964. // Non-priority non-instanced
  1965. for (PODVector<Batch*>::ConstIterator i = queue.sortedBatches_.Begin(); i != queue.sortedBatches_.End(); ++i)
  1966. {
  1967. Batch* batch = *i;
  1968. batch->Draw(graphics_, shaderParameters_);
  1969. }
  1970. }
  1971. void View::RenderShadowMap(const LightBatchQueue& queue)
  1972. {
  1973. PROFILE(RenderShadowMap);
  1974. Texture2D* shadowMap = queue.light_->GetShadowMap();
  1975. graphics_->ClearLastParameterSources();
  1976. graphics_->SetColorWrite(false);
  1977. graphics_->SetStencilTest(false);
  1978. graphics_->SetTexture(TU_SHADOWMAP, 0);
  1979. graphics_->SetRenderTarget(0, shadowMap->GetRenderSurface()->GetLinkedRenderTarget());
  1980. graphics_->SetDepthStencil(shadowMap);
  1981. graphics_->Clear(CLEAR_DEPTH);
  1982. // Set shadow depth bias
  1983. BiasParameters parameters = queue.light_->GetShadowBias();
  1984. graphics_->SetDepthBias(parameters.constantBias_, parameters.slopeScaledBias_);
  1985. // Set a scissor rectangle to match possible shadow map size reduction by out-zooming
  1986. // However, do not do this for point lights
  1987. if (queue.light_->GetLightType() != LIGHT_SPLITPOINT)
  1988. {
  1989. float zoom = Min(queue.light_->GetShadowCamera()->GetZoom(),
  1990. (float)(shadowMap->GetWidth() - 2) / (float)shadowMap->GetWidth());
  1991. Rect zoomRect(Vector2(-1.0f, -1.0f) * zoom, Vector2(1.0f, 1.0f) * zoom);
  1992. graphics_->SetScissorTest(true, zoomRect, false);
  1993. }
  1994. else
  1995. graphics_->SetScissorTest(false);
  1996. // Draw instanced and non-instanced shadow casters
  1997. RenderBatchQueue(queue.shadowBatches_, false, false, false);
  1998. graphics_->SetColorWrite(true);
  1999. graphics_->SetDepthBias(0.0f, 0.0f);
  2000. }