View.cpp 86 KB

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