Batch.cpp 42 KB

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