View.cpp 89 KB

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