Batch.cpp 41 KB

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