Batch.cpp 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032
  1. //
  2. // Copyright (c) 2008-2013 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "Camera.h"
  24. #include "Geometry.h"
  25. #include "Graphics.h"
  26. #include "GraphicsImpl.h"
  27. #include "Material.h"
  28. #include "Node.h"
  29. #include "Renderer.h"
  30. #include "Profiler.h"
  31. #include "Scene.h"
  32. #include "ShaderVariation.h"
  33. #include "Sort.h"
  34. #include "Technique.h"
  35. #include "Texture2D.h"
  36. #include "VertexBuffer.h"
  37. #include "View.h"
  38. #include "Zone.h"
  39. #include "DebugNew.h"
  40. namespace Urho3D
  41. {
  42. inline bool CompareBatchesState(Batch* lhs, Batch* rhs)
  43. {
  44. if (lhs->sortKey_ != rhs->sortKey_)
  45. return lhs->sortKey_ < rhs->sortKey_;
  46. else
  47. return lhs->distance_ < rhs->distance_;
  48. }
  49. inline bool CompareBatchesFrontToBack(Batch* lhs, Batch* rhs)
  50. {
  51. if (lhs->distance_ != rhs->distance_)
  52. return lhs->distance_ < rhs->distance_;
  53. else
  54. return lhs->sortKey_ < rhs->sortKey_;
  55. }
  56. inline bool CompareBatchesBackToFront(Batch* lhs, Batch* rhs)
  57. {
  58. if (lhs->distance_ != rhs->distance_)
  59. return lhs->distance_ > rhs->distance_;
  60. else
  61. return lhs->sortKey_ < rhs->sortKey_;
  62. }
  63. inline bool CompareInstancesFrontToBack(const InstanceData& lhs, const InstanceData& rhs)
  64. {
  65. return lhs.distance_ < rhs.distance_;
  66. }
  67. void CalculateShadowMatrix(Matrix4& dest, LightBatchQueue* queue, unsigned split, Renderer* renderer, const Vector3& translation)
  68. {
  69. Camera* shadowCamera = queue->shadowSplits_[split].shadowCamera_;
  70. const IntRect& viewport = queue->shadowSplits_[split].shadowViewport_;
  71. Matrix3x4 posAdjust(translation, Quaternion::IDENTITY, 1.0f);
  72. Matrix3x4 shadowView(shadowCamera->GetView());
  73. Matrix4 shadowProj(shadowCamera->GetProjection());
  74. Matrix4 texAdjust(Matrix4::IDENTITY);
  75. Texture2D* shadowMap = queue->shadowMap_;
  76. if (!shadowMap)
  77. return;
  78. float width = (float)shadowMap->GetWidth();
  79. float height = (float)shadowMap->GetHeight();
  80. Vector2 offset(
  81. (float)viewport.left_ / width,
  82. (float)viewport.top_ / height
  83. );
  84. Vector2 scale(
  85. 0.5f * (float)viewport.Width() / width,
  86. 0.5f * (float)viewport.Height() / height
  87. );
  88. #ifdef USE_OPENGL
  89. offset.x_ += scale.x_;
  90. offset.y_ += scale.y_;
  91. offset.y_ = 1.0f - offset.y_;
  92. // If using 4 shadow samples, offset the position diagonally by half pixel
  93. if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT)
  94. {
  95. offset.x_ -= 0.5f / width;
  96. offset.y_ -= 0.5f / height;
  97. }
  98. texAdjust.SetTranslation(Vector3(offset.x_, offset.y_, 0.5f));
  99. texAdjust.SetScale(Vector3(scale.x_, scale.y_, 0.5f));
  100. #else
  101. offset.x_ += scale.x_ + 0.5f / width;
  102. offset.y_ += scale.y_ + 0.5f / height;
  103. if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT)
  104. {
  105. offset.x_ -= 0.5f / width;
  106. offset.y_ -= 0.5f / height;
  107. }
  108. scale.y_ = -scale.y_;
  109. texAdjust.SetTranslation(Vector3(offset.x_, offset.y_, 0.0f));
  110. texAdjust.SetScale(Vector3(scale.x_, scale.y_, 1.0f));
  111. #endif
  112. dest = texAdjust * shadowProj * shadowView * posAdjust;
  113. }
  114. void CalculateSpotMatrix(Matrix4& dest, Light* light, const Vector3& translation)
  115. {
  116. Node* lightNode = light->GetNode();
  117. Matrix3x4 posAdjust(translation, Quaternion::IDENTITY, 1.0f);
  118. Matrix3x4 spotView = Matrix3x4(lightNode->GetWorldPosition(), lightNode->GetWorldRotation(), 1.0f).Inverse();
  119. Matrix4 spotProj(Matrix4::ZERO);
  120. Matrix4 texAdjust(Matrix4::IDENTITY);
  121. // Make the projected light slightly smaller than the shadow map to prevent light spill
  122. float h = 1.005f / tanf(light->GetFov() * M_DEGTORAD * 0.5f);
  123. float w = h / light->GetAspectRatio();
  124. spotProj.m00_ = w;
  125. spotProj.m11_ = h;
  126. spotProj.m22_ = 1.0f / Max(light->GetRange(), M_EPSILON);
  127. spotProj.m32_ = 1.0f;
  128. #ifdef USE_OPENGL
  129. texAdjust.SetTranslation(Vector3(0.5f, 0.5f, 0.5f));
  130. texAdjust.SetScale(Vector3(0.5f, -0.5f, 0.5f));
  131. #else
  132. texAdjust.SetTranslation(Vector3(0.5f, 0.5f, 0.0f));
  133. texAdjust.SetScale(Vector3(0.5f, -0.5f, 1.0f));
  134. #endif
  135. dest = texAdjust * spotProj * spotView * posAdjust;
  136. }
  137. void Batch::CalculateSortKey()
  138. {
  139. unsigned shaderID = ((*((unsigned*)&vertexShader_) / sizeof(ShaderVariation)) + (*((unsigned*)&pixelShader_) / sizeof(ShaderVariation))) & 0x3fff;
  140. if (!isBase_)
  141. shaderID |= 0x8000;
  142. if (pass_ && pass_->GetAlphaMask())
  143. shaderID |= 0x4000;
  144. unsigned lightQueueID = (*((unsigned*)&lightQueue_) / sizeof(LightBatchQueue)) & 0xffff;
  145. unsigned materialID = (*((unsigned*)&material_) / sizeof(Material)) & 0xffff;
  146. unsigned geometryID = (*((unsigned*)&geometry_) / sizeof(Geometry)) & 0xffff;
  147. sortKey_ = (((unsigned long long)shaderID) << 48) | (((unsigned long long)lightQueueID) << 32) |
  148. (((unsigned long long)materialID) << 16) | geometryID;
  149. }
  150. void Batch::Prepare(View* view, bool setModelTransform) const
  151. {
  152. if (!vertexShader_ || !pixelShader_)
  153. return;
  154. Graphics* graphics = view->GetGraphics();
  155. Renderer* renderer = view->GetRenderer();
  156. Node* cameraNode = camera_ ? camera_->GetNode() : 0;
  157. // Set pass / material-specific renderstates
  158. if (pass_ && material_)
  159. {
  160. bool isShadowPass = pass_->GetType() == PASS_SHADOW;
  161. graphics->SetBlendMode(pass_->GetBlendMode());
  162. renderer->SetCullMode(isShadowPass ? material_->GetShadowCullMode() : material_->GetCullMode(), camera_);
  163. if (!isShadowPass)
  164. {
  165. const BiasParameters& depthBias = material_->GetDepthBias();
  166. graphics->SetDepthBias(depthBias.constantBias_, depthBias.slopeScaledBias_);
  167. }
  168. graphics->SetDepthTest(pass_->GetDepthTestMode());
  169. graphics->SetDepthWrite(pass_->GetDepthWrite());
  170. }
  171. // Set shaders
  172. graphics->SetShaders(vertexShader_, pixelShader_);
  173. // Set global frame parameters
  174. if (graphics->NeedParameterUpdate(SP_FRAME, (void*)0))
  175. {
  176. Scene* scene = view->GetScene();
  177. if (scene)
  178. {
  179. float elapsedTime = scene->GetElapsedTime();
  180. graphics->SetShaderParameter(VSP_ELAPSEDTIME, elapsedTime);
  181. graphics->SetShaderParameter(PSP_ELAPSEDTIME, elapsedTime);
  182. }
  183. }
  184. // Set camera shader parameters
  185. unsigned cameraHash = overrideView_ ? (unsigned)(size_t)camera_ + 4 : (unsigned)(size_t)camera_;
  186. if (graphics->NeedParameterUpdate(SP_CAMERA, reinterpret_cast<void*>(cameraHash)))
  187. {
  188. Matrix3x4 cameraEffectiveTransform = camera_->GetEffectiveWorldTransform();
  189. graphics->SetShaderParameter(VSP_CAMERAPOS, cameraEffectiveTransform.Translation());
  190. graphics->SetShaderParameter(VSP_CAMERAROT, cameraEffectiveTransform.RotationMatrix());
  191. Vector4 depthMode = Vector4::ZERO;
  192. if (camera_->IsOrthographic())
  193. {
  194. depthMode.x_ = 1.0f;
  195. #ifdef USE_OPENGL
  196. depthMode.z_ = 0.5f;
  197. depthMode.w_ = 0.5f;
  198. #else
  199. depthMode.z_ = 1.0f;
  200. #endif
  201. }
  202. else
  203. depthMode.w_ = 1.0f / camera_->GetFarClip();
  204. graphics->SetShaderParameter(VSP_DEPTHMODE, depthMode);
  205. Vector3 nearVector, farVector;
  206. camera_->GetFrustumSize(nearVector, farVector);
  207. Vector4 viewportParams(farVector.x_, farVector.y_, farVector.z_, 0.0f);
  208. graphics->SetShaderParameter(VSP_FRUSTUMSIZE, viewportParams);
  209. Matrix4 projection = camera_->GetProjection();
  210. #ifdef USE_OPENGL
  211. // Add constant depth bias manually to the projection matrix due to glPolygonOffset() inconsistency
  212. float constantBias = 2.0f * graphics->GetDepthConstantBias();
  213. // On OpenGL ES slope-scaled bias can not be guaranteed to be available, and the shadow filtering is more coarse,
  214. // so use a higher constant bias
  215. #ifdef GL_ES_VERSION_2_0
  216. constantBias *= 1.5f;
  217. #endif
  218. projection.m22_ += projection.m32_ * constantBias;
  219. projection.m23_ += projection.m33_ * constantBias;
  220. #endif
  221. if (overrideView_)
  222. graphics->SetShaderParameter(VSP_VIEWPROJ, projection);
  223. else
  224. graphics->SetShaderParameter(VSP_VIEWPROJ, projection * camera_->GetView());
  225. }
  226. // Set viewport shader parameters
  227. IntVector2 rtSize = graphics->GetRenderTargetDimensions();
  228. IntRect viewport = graphics->GetViewport();
  229. unsigned viewportHash = (viewport.left_) | (viewport.top_ << 8) | (viewport.right_ << 16) | (viewport.bottom_ << 24);
  230. if (graphics->NeedParameterUpdate(SP_VIEWPORT, reinterpret_cast<void*>(viewportHash)))
  231. {
  232. float rtWidth = (float)rtSize.x_;
  233. float rtHeight = (float)rtSize.y_;
  234. float widthRange = 0.5f * viewport.Width() / rtWidth;
  235. float heightRange = 0.5f * viewport.Height() / rtHeight;
  236. #ifdef USE_OPENGL
  237. Vector4 bufferUVOffset(((float)viewport.left_) / rtWidth + widthRange,
  238. 1.0f - (((float)viewport.top_) / rtHeight + heightRange), widthRange, heightRange);
  239. #else
  240. Vector4 bufferUVOffset((0.5f + (float)viewport.left_) / rtWidth + widthRange,
  241. (0.5f + (float)viewport.top_) / rtHeight + heightRange, widthRange, heightRange);
  242. #endif
  243. graphics->SetShaderParameter(VSP_GBUFFEROFFSETS, bufferUVOffset);
  244. float sizeX = 1.0f / rtWidth;
  245. float sizeY = 1.0f / rtHeight;
  246. graphics->SetShaderParameter(PSP_GBUFFERINVSIZE, Vector4(sizeX, sizeY, 0.0f, 0.0f));
  247. }
  248. // Set model or skinning transforms
  249. if (setModelTransform && graphics->NeedParameterUpdate(SP_OBJECTTRANSFORM, worldTransform_))
  250. {
  251. if (geometryType_ == GEOM_SKINNED)
  252. {
  253. graphics->SetShaderParameter(VSP_SKINMATRICES, reinterpret_cast<const float*>(worldTransform_),
  254. 12 * numWorldTransforms_);
  255. }
  256. else
  257. graphics->SetShaderParameter(VSP_MODEL, *worldTransform_);
  258. // Set the orientation for billboards, either from the object itself or from the camera
  259. if (geometryType_ == GEOM_BILLBOARD)
  260. {
  261. if (numWorldTransforms_ > 1)
  262. graphics->SetShaderParameter(VSP_BILLBOARDROT, worldTransform_[1].RotationMatrix());
  263. else
  264. graphics->SetShaderParameter(VSP_BILLBOARDROT, cameraNode->GetWorldRotation().RotationMatrix());
  265. }
  266. }
  267. // Set zone-related shader parameters
  268. BlendMode blend = graphics->GetBlendMode();
  269. Zone* fogColorZone = (blend == BLEND_ADD || blend == BLEND_ADDALPHA) ? renderer->GetDefaultZone() : zone_;
  270. unsigned zoneHash = (unsigned)(size_t)zone_ + (unsigned)(size_t)fogColorZone;
  271. if (zone_ && graphics->NeedParameterUpdate(SP_ZONE, reinterpret_cast<void*>(zoneHash)))
  272. {
  273. graphics->SetShaderParameter(VSP_AMBIENTSTARTCOLOR, zone_->GetAmbientStartColor());
  274. graphics->SetShaderParameter(VSP_AMBIENTENDCOLOR, zone_->GetAmbientEndColor().ToVector4() - zone_->GetAmbientStartColor().ToVector4());
  275. const BoundingBox& box = zone_->GetBoundingBox();
  276. Vector3 boxSize = box.Size();
  277. Matrix3x4 adjust(Matrix3x4::IDENTITY);
  278. adjust.SetScale(Vector3(1.0f / boxSize.x_, 1.0f / boxSize.y_, 1.0f / boxSize.z_));
  279. adjust.SetTranslation(Vector3(0.5f, 0.5f, 0.5f));
  280. Matrix3x4 zoneTransform = adjust * zone_->GetInverseWorldTransform();
  281. graphics->SetShaderParameter(VSP_ZONE, zoneTransform);
  282. graphics->SetShaderParameter(PSP_AMBIENTCOLOR, zone_->GetAmbientColor());
  283. // If the pass is additive, override fog color to black so that shaders do not need a separate additive path
  284. graphics->SetShaderParameter(PSP_FOGCOLOR, fogColorZone->GetFogColor());
  285. float farClip = camera_->GetFarClip();
  286. float fogStart = Min(zone_->GetFogStart(), farClip);
  287. float fogEnd = Min(zone_->GetFogEnd(), farClip);
  288. if (fogStart >= fogEnd * (1.0f - M_LARGE_EPSILON))
  289. fogStart = fogEnd * (1.0f - M_LARGE_EPSILON);
  290. float fogRange = Max(fogEnd - fogStart, M_EPSILON);
  291. Vector4 fogParams(fogEnd / farClip, farClip / fogRange, 0.0f, 0.0f);
  292. graphics->SetShaderParameter(PSP_FOGPARAMS, fogParams);
  293. }
  294. // Set light-related shader parameters
  295. Light* light = 0;
  296. Texture2D* shadowMap = 0;
  297. if (lightQueue_)
  298. {
  299. light = lightQueue_->light_;
  300. shadowMap = lightQueue_->shadowMap_;
  301. if (graphics->NeedParameterUpdate(SP_VERTEXLIGHTS, lightQueue_) && graphics->HasShaderParameter(VS, VSP_VERTEXLIGHTS))
  302. {
  303. Vector4 vertexLights[MAX_VERTEX_LIGHTS * 3];
  304. const PODVector<Light*>& lights = lightQueue_->vertexLights_;
  305. for (unsigned i = 0; i < lights.Size(); ++i)
  306. {
  307. Light* vertexLight = lights[i];
  308. Node* vertexLightNode = vertexLight->GetNode();
  309. LightType type = vertexLight->GetLightType();
  310. // Attenuation
  311. float invRange, cutoff, invCutoff;
  312. if (type == LIGHT_DIRECTIONAL)
  313. invRange = 0.0f;
  314. else
  315. invRange = 1.0f / Max(vertexLight->GetRange(), M_EPSILON);
  316. if (type == LIGHT_SPOT)
  317. {
  318. cutoff = Cos(vertexLight->GetFov() * 0.5f);
  319. invCutoff = 1.0f / (1.0f - cutoff);
  320. }
  321. else
  322. {
  323. cutoff = -1.0f;
  324. invCutoff = 1.0f;
  325. }
  326. // Color
  327. float fade = 1.0f;
  328. float fadeEnd = vertexLight->GetDrawDistance();
  329. float fadeStart = vertexLight->GetFadeDistance();
  330. // Do fade calculation for light if both fade & draw distance defined
  331. if (vertexLight->GetLightType() != LIGHT_DIRECTIONAL && fadeEnd > 0.0f && fadeStart > 0.0f && fadeStart < fadeEnd)
  332. fade = Min(1.0f - (vertexLight->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 1.0f);
  333. Color color = vertexLight->GetColor() * fade;
  334. vertexLights[i * 3] = Vector4(color.r_, color.g_, color.b_, invRange);
  335. // Direction
  336. vertexLights[i * 3 + 1] = Vector4(-(vertexLightNode->GetWorldDirection()), cutoff);
  337. // Position
  338. vertexLights[i * 3 + 2] = Vector4(vertexLightNode->GetWorldPosition(), invCutoff);
  339. }
  340. if (lights.Size())
  341. graphics->SetShaderParameter(VSP_VERTEXLIGHTS, vertexLights[0].Data(), lights.Size() * 3 * 4);
  342. }
  343. }
  344. if (light && graphics->NeedParameterUpdate(SP_LIGHT, light))
  345. {
  346. Matrix3x4 cameraEffectiveTransform = camera_->GetEffectiveWorldTransform();
  347. Vector3 cameraEffectivePos = cameraEffectiveTransform.Translation();
  348. Node* lightNode = light->GetNode();
  349. Matrix3 lightWorldRotation = lightNode->GetWorldRotation().RotationMatrix();
  350. graphics->SetShaderParameter(VSP_LIGHTDIR, lightWorldRotation * Vector3::BACK);
  351. float atten = 1.0f / Max(light->GetRange(), M_EPSILON);
  352. graphics->SetShaderParameter(VSP_LIGHTPOS, Vector4(lightNode->GetWorldPosition(), atten));
  353. if (graphics->HasShaderParameter(VS, VSP_LIGHTMATRICES))
  354. {
  355. switch (light->GetLightType())
  356. {
  357. case LIGHT_DIRECTIONAL:
  358. {
  359. Matrix4 shadowMatrices[MAX_CASCADE_SPLITS];
  360. unsigned numSplits = lightQueue_->shadowSplits_.Size();
  361. for (unsigned i = 0; i < numSplits; ++i)
  362. CalculateShadowMatrix(shadowMatrices[i], lightQueue_, i, renderer, Vector3::ZERO);
  363. graphics->SetShaderParameter(VSP_LIGHTMATRICES, shadowMatrices[0].Data(), 16 * numSplits);
  364. }
  365. break;
  366. case LIGHT_SPOT:
  367. {
  368. Matrix4 shadowMatrices[2];
  369. CalculateSpotMatrix(shadowMatrices[0], light, Vector3::ZERO);
  370. bool isShadowed = shadowMap && graphics->HasTextureUnit(TU_SHADOWMAP);
  371. if (isShadowed)
  372. CalculateShadowMatrix(shadowMatrices[1], lightQueue_, 0, renderer, Vector3::ZERO);
  373. graphics->SetShaderParameter(VSP_LIGHTMATRICES, shadowMatrices[0].Data(), isShadowed ? 32 : 16);
  374. }
  375. break;
  376. case LIGHT_POINT:
  377. {
  378. Matrix4 lightVecRot(lightNode->GetWorldRotation().RotationMatrix());
  379. // HLSL compiler will pack the parameters as if the matrix is only 3x4, so must be careful to not overwrite
  380. // the next parameter
  381. #ifdef USE_OPENGL
  382. graphics->SetShaderParameter(VSP_LIGHTMATRICES, lightVecRot.Data(), 16);
  383. #else
  384. graphics->SetShaderParameter(VSP_LIGHTMATRICES, lightVecRot.Data(), 12);
  385. #endif
  386. }
  387. break;
  388. }
  389. }
  390. float fade = 1.0f;
  391. float fadeEnd = light->GetDrawDistance();
  392. float fadeStart = light->GetFadeDistance();
  393. // Do fade calculation for light if both fade & draw distance defined
  394. if (light->GetLightType() != LIGHT_DIRECTIONAL && fadeEnd > 0.0f && fadeStart > 0.0f && fadeStart < fadeEnd)
  395. fade = Min(1.0f - (light->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 1.0f);
  396. graphics->SetShaderParameter(PSP_LIGHTCOLOR, Color(light->GetColor(), light->GetSpecularIntensity()) * fade);
  397. graphics->SetShaderParameter(PSP_LIGHTDIR, lightWorldRotation * Vector3::BACK);
  398. graphics->SetShaderParameter(PSP_LIGHTPOS, Vector4(lightNode->GetWorldPosition() - cameraEffectivePos, atten));
  399. if (graphics->HasShaderParameter(PS, PSP_LIGHTMATRICES))
  400. {
  401. switch (light->GetLightType())
  402. {
  403. case LIGHT_DIRECTIONAL:
  404. {
  405. Matrix4 shadowMatrices[MAX_CASCADE_SPLITS];
  406. unsigned numSplits = lightQueue_->shadowSplits_.Size();
  407. for (unsigned i = 0; i < numSplits; ++i)
  408. CalculateShadowMatrix(shadowMatrices[i], lightQueue_, i, renderer, cameraEffectivePos);
  409. graphics->SetShaderParameter(PSP_LIGHTMATRICES, shadowMatrices[0].Data(), 16 * numSplits);
  410. }
  411. break;
  412. case LIGHT_SPOT:
  413. {
  414. Matrix4 shadowMatrices[2];
  415. CalculateSpotMatrix(shadowMatrices[0], light, cameraEffectivePos);
  416. bool isShadowed = lightQueue_->shadowMap_ != 0;
  417. if (isShadowed)
  418. CalculateShadowMatrix(shadowMatrices[1], lightQueue_, 0, renderer, cameraEffectivePos);
  419. graphics->SetShaderParameter(PSP_LIGHTMATRICES, shadowMatrices[0].Data(), isShadowed ? 32 : 16);
  420. }
  421. break;
  422. case LIGHT_POINT:
  423. {
  424. Matrix4 lightVecRot(lightNode->GetWorldRotation().RotationMatrix());
  425. // HLSL compiler will pack the parameters as if the matrix is only 3x4, so must be careful to not overwrite
  426. // the next parameter
  427. #ifdef USE_OPENGL
  428. graphics->SetShaderParameter(PSP_LIGHTMATRICES, lightVecRot.Data(), 16);
  429. #else
  430. graphics->SetShaderParameter(PSP_LIGHTMATRICES, lightVecRot.Data(), 12);
  431. #endif
  432. }
  433. break;
  434. }
  435. }
  436. // Set shadow mapping shader parameters
  437. if (shadowMap)
  438. {
  439. {
  440. unsigned faceWidth = shadowMap->GetWidth() / 2;
  441. unsigned faceHeight = shadowMap->GetHeight() / 3;
  442. float width = (float)shadowMap->GetWidth();
  443. float height = (float)shadowMap->GetHeight();
  444. #ifdef USE_OPENGL
  445. float mulX = (float)(faceWidth - 3) / width;
  446. float mulY = (float)(faceHeight - 3) / height;
  447. float addX = 1.5f / width;
  448. float addY = 1.5f / height;
  449. #else
  450. float mulX = (float)(faceWidth - 4) / width;
  451. float mulY = (float)(faceHeight - 4) / height;
  452. float addX = 2.5f / width;
  453. float addY = 2.5f / height;
  454. #endif
  455. // If using 4 shadow samples, offset the position diagonally by half pixel
  456. if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT)
  457. {
  458. addX -= 0.5f / width;
  459. addY -= 0.5f / height;
  460. }
  461. graphics->SetShaderParameter(PSP_SHADOWCUBEADJUST, Vector4(mulX, mulY, addX, addY));
  462. }
  463. {
  464. Camera* shadowCamera = lightQueue_->shadowSplits_[0].shadowCamera_;
  465. float nearClip = shadowCamera->GetNearClip();
  466. float farClip = shadowCamera->GetFarClip();
  467. float q = farClip / (farClip - nearClip);
  468. float r = -q * nearClip;
  469. const CascadeParameters& parameters = light->GetShadowCascade();
  470. float viewFarClip = camera_->GetFarClip();
  471. float shadowRange = parameters.GetShadowRange();
  472. float fadeStart = parameters.fadeStart_ * shadowRange / viewFarClip;
  473. float fadeEnd = shadowRange / viewFarClip;
  474. float fadeRange = fadeEnd - fadeStart;
  475. graphics->SetShaderParameter(PSP_SHADOWDEPTHFADE, Vector4(q, r, fadeStart, 1.0f / fadeRange));
  476. }
  477. {
  478. float intensity = light->GetShadowIntensity();
  479. float fadeStart = light->GetShadowFadeDistance();
  480. float fadeEnd = light->GetShadowDistance();
  481. if (fadeStart > 0.0f && fadeEnd > 0.0f && fadeEnd > fadeStart)
  482. intensity = Lerp(intensity, 1.0f, Clamp((light->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 0.0f, 1.0f));
  483. float pcfValues = (1.0f - intensity);
  484. float samples = renderer->GetShadowQuality() >= SHADOWQUALITY_HIGH_16BIT ? 4.0f : 1.0f;
  485. graphics->SetShaderParameter(PSP_SHADOWINTENSITY, Vector4(pcfValues / samples, intensity, 0.0f, 0.0f));
  486. }
  487. float sizeX = 1.0f / (float)shadowMap->GetWidth();
  488. float sizeY = 1.0f / (float)shadowMap->GetHeight();
  489. graphics->SetShaderParameter(PSP_SHADOWMAPINVSIZE, Vector4(sizeX, sizeY, 0.0f, 0.0f));
  490. Vector4 lightSplits(M_LARGE_VALUE, M_LARGE_VALUE, M_LARGE_VALUE, M_LARGE_VALUE);
  491. if (lightQueue_->shadowSplits_.Size() > 1)
  492. lightSplits.x_ = lightQueue_->shadowSplits_[0].farSplit_ / camera_->GetFarClip();
  493. if (lightQueue_->shadowSplits_.Size() > 2)
  494. lightSplits.y_ = lightQueue_->shadowSplits_[1].farSplit_ / camera_->GetFarClip();
  495. if (lightQueue_->shadowSplits_.Size() > 3)
  496. lightSplits.z_ = lightQueue_->shadowSplits_[2].farSplit_ / camera_->GetFarClip();
  497. graphics->SetShaderParameter(PSP_SHADOWSPLITS, lightSplits);
  498. }
  499. }
  500. // Set material-specific shader parameters and textures
  501. if (material_)
  502. {
  503. if (graphics->NeedParameterUpdate(SP_MATERIAL, material_))
  504. {
  505. const HashMap<StringHash, MaterialShaderParameter>& parameters = material_->GetShaderParameters();
  506. for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = parameters.Begin(); i != parameters.End(); ++i)
  507. graphics->SetShaderParameter(i->first_, i->second_.value_);
  508. }
  509. const SharedPtr<Texture>* textures = material_->GetTextures();
  510. for (unsigned i = 0; i < MAX_MATERIAL_TEXTURE_UNITS; ++i)
  511. {
  512. TextureUnit unit = (TextureUnit)i;
  513. if (textures[i] && graphics->HasTextureUnit(unit))
  514. graphics->SetTexture(i, textures[i]);
  515. }
  516. }
  517. // Set light-related textures
  518. if (light)
  519. {
  520. if (shadowMap && graphics->HasTextureUnit(TU_SHADOWMAP))
  521. graphics->SetTexture(TU_SHADOWMAP, shadowMap);
  522. if (graphics->HasTextureUnit(TU_LIGHTRAMP))
  523. {
  524. Texture* rampTexture = light->GetRampTexture();
  525. if (!rampTexture)
  526. rampTexture = renderer->GetDefaultLightRamp();
  527. graphics->SetTexture(TU_LIGHTRAMP, rampTexture);
  528. }
  529. if (graphics->HasTextureUnit(TU_LIGHTSHAPE))
  530. {
  531. Texture* shapeTexture = light->GetShapeTexture();
  532. if (!shapeTexture && light->GetLightType() == LIGHT_SPOT)
  533. shapeTexture = renderer->GetDefaultLightSpot();
  534. graphics->SetTexture(TU_LIGHTSHAPE, shapeTexture);
  535. }
  536. }
  537. }
  538. void Batch::Draw(View* view) const
  539. {
  540. if (!geometry_->IsEmpty())
  541. {
  542. Prepare(view);
  543. geometry_->Draw(view->GetGraphics());
  544. }
  545. }
  546. void BatchGroup::SetTransforms(void* lockedData, unsigned& freeIndex)
  547. {
  548. // Do not use up buffer space if not going to draw as instanced
  549. if (geometryType_ != GEOM_INSTANCED)
  550. return;
  551. startIndex_ = freeIndex;
  552. Matrix3x4* dest = (Matrix3x4*)lockedData;
  553. dest += freeIndex;
  554. for (unsigned i = 0; i < instances_.Size(); ++i)
  555. *dest++ = *instances_[i].worldTransform_;
  556. freeIndex += instances_.Size();
  557. }
  558. void BatchGroup::Draw(View* view) const
  559. {
  560. Graphics* graphics = view->GetGraphics();
  561. Renderer* renderer = view->GetRenderer();
  562. if (instances_.Size() && !geometry_->IsEmpty())
  563. {
  564. // Draw as individual objects if instancing not supported
  565. VertexBuffer* instanceBuffer = renderer->GetInstancingBuffer();
  566. if (!instanceBuffer || geometryType_ != GEOM_INSTANCED)
  567. {
  568. Batch::Prepare(view, false);
  569. graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
  570. graphics->SetVertexBuffers(geometry_->GetVertexBuffers(), geometry_->GetVertexElementMasks());
  571. for (unsigned i = 0; i < instances_.Size(); ++i)
  572. {
  573. if (graphics->NeedParameterUpdate(SP_OBJECTTRANSFORM, instances_[i].worldTransform_))
  574. graphics->SetShaderParameter(VSP_MODEL, *instances_[i].worldTransform_);
  575. graphics->Draw(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(),
  576. geometry_->GetVertexStart(), geometry_->GetVertexCount());
  577. }
  578. }
  579. else
  580. {
  581. Batch::Prepare(view, false);
  582. // Get the geometry vertex buffers, then add the instancing stream buffer
  583. // Hack: use a const_cast to avoid dynamic allocation of new temp vectors
  584. Vector<SharedPtr<VertexBuffer> >& vertexBuffers = const_cast<Vector<SharedPtr<VertexBuffer> >&>
  585. (geometry_->GetVertexBuffers());
  586. PODVector<unsigned>& elementMasks = const_cast<PODVector<unsigned>&>(geometry_->GetVertexElementMasks());
  587. vertexBuffers.Push(SharedPtr<VertexBuffer>(instanceBuffer));
  588. elementMasks.Push(instanceBuffer->GetElementMask());
  589. // No stream offset support, instancing buffer not pre-filled with transforms: have to fill now
  590. if (startIndex_ == M_MAX_UNSIGNED)
  591. {
  592. unsigned startIndex = 0;
  593. while (startIndex < instances_.Size())
  594. {
  595. unsigned instances = instances_.Size() - startIndex;
  596. if (instances > instanceBuffer->GetVertexCount())
  597. instances = instanceBuffer->GetVertexCount();
  598. // Copy the transforms
  599. Matrix3x4* dest = (Matrix3x4*)instanceBuffer->Lock(0, instances, true);
  600. if (dest)
  601. {
  602. for (unsigned i = 0; i < instances; ++i)
  603. dest[i] = *instances_[i + startIndex].worldTransform_;
  604. instanceBuffer->Unlock();
  605. graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
  606. graphics->SetVertexBuffers(vertexBuffers, elementMasks);
  607. graphics->DrawInstanced(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(),
  608. geometry_->GetIndexCount(), geometry_->GetVertexStart(), geometry_->GetVertexCount(), instances);
  609. }
  610. startIndex += instances;
  611. }
  612. }
  613. // Stream offset supported and instancing buffer has been already filled, so just draw
  614. else
  615. {
  616. graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
  617. graphics->SetVertexBuffers(vertexBuffers, elementMasks, startIndex_);
  618. graphics->DrawInstanced(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(),
  619. geometry_->GetVertexStart(), geometry_->GetVertexCount(), instances_.Size());
  620. }
  621. // Remove the instancing buffer & element mask now
  622. vertexBuffers.Pop();
  623. elementMasks.Pop();
  624. }
  625. }
  626. }
  627. unsigned BatchGroupKey::ToHash() const
  628. {
  629. return ((unsigned)(size_t)zone_) / sizeof(Zone) +
  630. ((unsigned)(size_t)lightQueue_) / sizeof(LightBatchQueue) +
  631. ((unsigned)(size_t)pass_) / sizeof(Pass) +
  632. ((unsigned)(size_t)material_) / sizeof(Material) +
  633. ((unsigned)(size_t)geometry_) / sizeof(Geometry);
  634. }
  635. void BatchQueue::Clear(int maxSortedInstances)
  636. {
  637. batches_.Clear();
  638. sortedBaseBatches_.Clear();
  639. sortedBatches_.Clear();
  640. baseBatchGroups_.Clear();
  641. batchGroups_.Clear();
  642. maxSortedInstances_ = maxSortedInstances;
  643. }
  644. void BatchQueue::SortBackToFront()
  645. {
  646. sortedBaseBatches_.Clear();
  647. sortedBatches_.Resize(batches_.Size());
  648. for (unsigned i = 0; i < batches_.Size(); ++i)
  649. sortedBatches_[i] = &batches_[i];
  650. Sort(sortedBatches_.Begin(), sortedBatches_.End(), CompareBatchesBackToFront);
  651. // Do not actually sort batch groups, just list them
  652. sortedBaseBatchGroups_.Resize(baseBatchGroups_.Size());
  653. sortedBatchGroups_.Resize(batchGroups_.Size());
  654. unsigned index = 0;
  655. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  656. sortedBaseBatchGroups_[index++] = &i->second_;
  657. index = 0;
  658. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  659. sortedBatchGroups_[index++] = &i->second_;
  660. }
  661. void BatchQueue::SortFrontToBack()
  662. {
  663. sortedBaseBatches_.Clear();
  664. sortedBatches_.Clear();
  665. // Need to divide into base and non-base batches here to ensure proper order in relation to grouped batches
  666. for (unsigned i = 0; i < batches_.Size(); ++i)
  667. {
  668. if (batches_[i].isBase_)
  669. sortedBaseBatches_.Push(&batches_[i]);
  670. else
  671. sortedBatches_.Push(&batches_[i]);
  672. }
  673. SortFrontToBack2Pass(sortedBaseBatches_);
  674. SortFrontToBack2Pass(sortedBatches_);
  675. // Sort each group front to back
  676. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  677. {
  678. if (i->second_.instances_.Size() <= maxSortedInstances_)
  679. {
  680. Sort(i->second_.instances_.Begin(), i->second_.instances_.End(), CompareInstancesFrontToBack);
  681. if (i->second_.instances_.Size())
  682. i->second_.distance_ = i->second_.instances_[0].distance_;
  683. }
  684. else
  685. {
  686. float minDistance = M_INFINITY;
  687. for (PODVector<InstanceData>::ConstIterator j = i->second_.instances_.Begin(); j != i->second_.instances_.End(); ++j)
  688. minDistance = Min(minDistance, j->distance_);
  689. i->second_.distance_ = minDistance;
  690. }
  691. }
  692. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  693. {
  694. if (i->second_.instances_.Size() <= maxSortedInstances_)
  695. {
  696. Sort(i->second_.instances_.Begin(), i->second_.instances_.End(), CompareInstancesFrontToBack);
  697. if (i->second_.instances_.Size())
  698. i->second_.distance_ = i->second_.instances_[0].distance_;
  699. }
  700. else
  701. {
  702. float minDistance = M_INFINITY;
  703. for (PODVector<InstanceData>::ConstIterator j = i->second_.instances_.Begin(); j != i->second_.instances_.End(); ++j)
  704. minDistance = Min(minDistance, j->distance_);
  705. i->second_.distance_ = minDistance;
  706. }
  707. }
  708. sortedBaseBatchGroups_.Resize(baseBatchGroups_.Size());
  709. sortedBatchGroups_.Resize(batchGroups_.Size());
  710. unsigned index = 0;
  711. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  712. sortedBaseBatchGroups_[index++] = &i->second_;
  713. index = 0;
  714. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  715. sortedBatchGroups_[index++] = &i->second_;
  716. SortFrontToBack2Pass(reinterpret_cast<PODVector<Batch*>& >(sortedBaseBatchGroups_));
  717. SortFrontToBack2Pass(reinterpret_cast<PODVector<Batch*>& >(sortedBatchGroups_));
  718. }
  719. void BatchQueue::SortFrontToBack2Pass(PODVector<Batch*>& batches)
  720. {
  721. // Mobile devices likely use a tiled deferred approach, with which front-to-back sorting is irrelevant. The 2-pass
  722. // method is also time consuming, so just sort with state having priority
  723. #ifdef GL_ES_VERSION_2_0
  724. Sort(batches.Begin(), batches.End(), CompareBatchesState);
  725. #else
  726. // For desktop, first sort by distance and remap shader/material/geometry IDs in the sort key
  727. Sort(batches.Begin(), batches.End(), CompareBatchesFrontToBack);
  728. unsigned freeShaderID = 0;
  729. unsigned short freeMaterialID = 0;
  730. unsigned short freeGeometryID = 0;
  731. for (PODVector<Batch*>::Iterator i = batches.Begin(); i != batches.End(); ++i)
  732. {
  733. Batch* batch = *i;
  734. unsigned shaderID = (batch->sortKey_ >> 32);
  735. HashMap<unsigned, unsigned>::ConstIterator j = shaderRemapping_.Find(shaderID);
  736. if (j != shaderRemapping_.End())
  737. shaderID = j->second_;
  738. else
  739. {
  740. shaderID = shaderRemapping_[shaderID] = freeShaderID | (shaderID & 0xc0000000);
  741. ++freeShaderID;
  742. }
  743. unsigned short materialID = (unsigned short)(batch->sortKey_ & 0xffff0000);
  744. HashMap<unsigned short, unsigned short>::ConstIterator k = materialRemapping_.Find(materialID);
  745. if (k != materialRemapping_.End())
  746. materialID = k->second_;
  747. else
  748. {
  749. materialID = materialRemapping_[materialID] = freeMaterialID;
  750. ++freeMaterialID;
  751. }
  752. unsigned short geometryID = (unsigned short)(batch->sortKey_ & 0xffff);
  753. HashMap<unsigned short, unsigned short>::ConstIterator l = geometryRemapping_.Find(geometryID);
  754. if (l != geometryRemapping_.End())
  755. geometryID = l->second_;
  756. else
  757. {
  758. geometryID = geometryRemapping_[geometryID] = freeGeometryID;
  759. ++freeGeometryID;
  760. }
  761. batch->sortKey_ = (((unsigned long long)shaderID) << 32) || (((unsigned long long)materialID) << 16) | geometryID;
  762. }
  763. shaderRemapping_.Clear();
  764. materialRemapping_.Clear();
  765. geometryRemapping_.Clear();
  766. // Finally sort again with the rewritten ID's
  767. Sort(batches.Begin(), batches.End(), CompareBatchesState);
  768. #endif
  769. }
  770. void BatchQueue::SetTransforms(void* lockedData, unsigned& freeIndex)
  771. {
  772. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  773. i->second_.SetTransforms(lockedData, freeIndex);
  774. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  775. i->second_.SetTransforms(lockedData, freeIndex);
  776. }
  777. void BatchQueue::Draw(View* view, bool useScissor, bool markToStencil) const
  778. {
  779. Graphics* graphics = view->GetGraphics();
  780. Renderer* renderer = view->GetRenderer();
  781. graphics->SetScissorTest(false);
  782. // During G-buffer rendering, mark opaque pixels to stencil buffer
  783. if (!markToStencil)
  784. graphics->SetStencilTest(false);
  785. // Base instanced
  786. for (PODVector<BatchGroup*>::ConstIterator i = sortedBaseBatchGroups_.Begin(); i != sortedBaseBatchGroups_.End(); ++i)
  787. {
  788. BatchGroup* group = *i;
  789. if (markToStencil)
  790. graphics->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, group->lightMask_);
  791. group->Draw(view);
  792. }
  793. // Base non-instanced
  794. for (PODVector<Batch*>::ConstIterator i = sortedBaseBatches_.Begin(); i != sortedBaseBatches_.End(); ++i)
  795. {
  796. Batch* batch = *i;
  797. if (markToStencil)
  798. graphics->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, batch->lightMask_);
  799. batch->Draw(view);
  800. }
  801. // Non-base instanced
  802. for (PODVector<BatchGroup*>::ConstIterator i = sortedBatchGroups_.Begin(); i != sortedBatchGroups_.End(); ++i)
  803. {
  804. BatchGroup* group = *i;
  805. if (useScissor && group->lightQueue_)
  806. renderer->OptimizeLightByScissor(group->lightQueue_->light_, group->camera_);
  807. if (markToStencil)
  808. graphics->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, group->lightMask_);
  809. group->Draw(view);
  810. }
  811. // Non-base non-instanced
  812. for (PODVector<Batch*>::ConstIterator i = sortedBatches_.Begin(); i != sortedBatches_.End(); ++i)
  813. {
  814. Batch* batch = *i;
  815. if (useScissor)
  816. {
  817. if (!batch->isBase_ && batch->lightQueue_)
  818. renderer->OptimizeLightByScissor(batch->lightQueue_->light_, batch->camera_);
  819. else
  820. graphics->SetScissorTest(false);
  821. }
  822. if (markToStencil)
  823. graphics->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, batch->lightMask_);
  824. batch->Draw(view);
  825. }
  826. }
  827. void BatchQueue::Draw(Light* light, View* view) const
  828. {
  829. Graphics* graphics = view->GetGraphics();
  830. Renderer* renderer = view->GetRenderer();
  831. graphics->SetScissorTest(false);
  832. graphics->SetStencilTest(false);
  833. // Base instanced
  834. for (PODVector<BatchGroup*>::ConstIterator i = sortedBaseBatchGroups_.Begin(); i != sortedBaseBatchGroups_.End(); ++i)
  835. {
  836. BatchGroup* group = *i;
  837. group->Draw(view);
  838. }
  839. // Base non-instanced
  840. for (PODVector<Batch*>::ConstIterator i = sortedBaseBatches_.Begin(); i != sortedBaseBatches_.End(); ++i)
  841. {
  842. Batch* batch = *i;
  843. batch->Draw(view);
  844. }
  845. // All base passes have been drawn. Optimize at this point by both stencil volume and scissor
  846. bool optimized = false;
  847. // Non-base instanced
  848. for (PODVector<BatchGroup*>::ConstIterator i = sortedBatchGroups_.Begin(); i != sortedBatchGroups_.End(); ++i)
  849. {
  850. BatchGroup* group = *i;
  851. if (!optimized)
  852. {
  853. renderer->OptimizeLightByStencil(light, group->camera_);
  854. renderer->OptimizeLightByScissor(light, group->camera_);
  855. optimized = true;
  856. }
  857. group->Draw(view);
  858. }
  859. // Non-base non-instanced
  860. for (PODVector<Batch*>::ConstIterator i = sortedBatches_.Begin(); i != sortedBatches_.End(); ++i)
  861. {
  862. Batch* batch = *i;
  863. if (!optimized)
  864. {
  865. renderer->OptimizeLightByStencil(light, batch->camera_);
  866. renderer->OptimizeLightByScissor(light, batch->camera_);
  867. optimized = true;
  868. }
  869. batch->Draw(view);
  870. }
  871. }
  872. unsigned BatchQueue::GetNumInstances() const
  873. {
  874. unsigned total = 0;
  875. for (HashMap<BatchGroupKey, BatchGroup>::ConstIterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  876. {
  877. if (i->second_.geometryType_ == GEOM_INSTANCED)
  878. total += i->second_.instances_.Size();
  879. }
  880. for (HashMap<BatchGroupKey, BatchGroup>::ConstIterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  881. {
  882. if (i->second_.geometryType_ == GEOM_INSTANCED)
  883. total += i->second_.instances_.Size();
  884. }
  885. return total;
  886. }
  887. }