Batch.cpp 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Oorni
  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 fogStart = Min(zone_->GetFogStart(), farClip);
  270. float fogEnd = Min(zone_->GetFogEnd(), farClip);
  271. if (fogStart >= fogEnd * (1.0f - M_LARGE_EPSILON))
  272. fogStart = fogEnd * (1.0f - M_LARGE_EPSILON);
  273. float fogRange = Max(fogEnd - fogStart, M_EPSILON);
  274. Vector4 fogParams(fogEnd / farClip, farClip / fogRange, 0.0f, 0.0f);
  275. graphics->SetShaderParameter(PSP_FOGPARAMS, fogParams);
  276. }
  277. // Set light-related shader parameters
  278. Light* light = 0;
  279. Texture2D* shadowMap = 0;
  280. if (lightQueue_)
  281. {
  282. light = lightQueue_->light_;
  283. shadowMap = lightQueue_->shadowMap_;
  284. if (graphics->NeedParameterUpdate(SP_VERTEXLIGHTS, lightQueue_) && graphics->HasShaderParameter(VS, VSP_VERTEXLIGHTS))
  285. {
  286. Vector4 vertexLights[MAX_VERTEX_LIGHTS * 3];
  287. const PODVector<Light*>& lights = lightQueue_->vertexLights_;
  288. for (unsigned i = 0; i < lights.Size(); ++i)
  289. {
  290. Light* vertexLight = lights[i];
  291. Node* vertexLightNode = vertexLight->GetNode();
  292. LightType type = vertexLight->GetLightType();
  293. // Attenuation
  294. float invRange, cutoff, invCutoff;
  295. if (type == LIGHT_DIRECTIONAL)
  296. invRange = 0.0f;
  297. else
  298. invRange = 1.0f / Max(vertexLight->GetRange(), M_EPSILON);
  299. if (type == LIGHT_SPOT)
  300. {
  301. cutoff = cosf(vertexLight->GetFov() * 0.5f * M_DEGTORAD);
  302. invCutoff = 1.0f / (1.0f - cutoff);
  303. }
  304. else
  305. {
  306. cutoff = -1.0f;
  307. invCutoff = 1.0f;
  308. }
  309. // Color
  310. float fade = 1.0f;
  311. float fadeEnd = vertexLight->GetDrawDistance();
  312. float fadeStart = vertexLight->GetFadeDistance();
  313. // Do fade calculation for light if both fade & draw distance defined
  314. if (vertexLight->GetLightType() != LIGHT_DIRECTIONAL && fadeEnd > 0.0f && fadeStart > 0.0f && fadeStart < fadeEnd)
  315. fade = Min(1.0f - (vertexLight->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 1.0f);
  316. Color color = vertexLight->GetColor() * fade;
  317. vertexLights[i * 3] = Vector4(color.r_, color.g_, color.b_, invRange);
  318. // Direction
  319. vertexLights[i * 3 + 1] = Vector4(-(vertexLightNode->GetWorldDirection()), cutoff);
  320. // Position
  321. vertexLights[i * 3 + 2] = Vector4(vertexLightNode->GetWorldPosition(), invCutoff);
  322. }
  323. if (lights.Size())
  324. graphics->SetShaderParameter(VSP_VERTEXLIGHTS, vertexLights[0].Data(), lights.Size() * 3 * 4);
  325. }
  326. }
  327. if (light && graphics->NeedParameterUpdate(SP_LIGHT, light))
  328. {
  329. Node* lightNode = light->GetNode();
  330. Matrix3 lightWorldRotation = lightNode->GetWorldTransform().RotationMatrix();
  331. graphics->SetShaderParameter(VSP_LIGHTDIR, lightWorldRotation * Vector3::BACK);
  332. float atten = 1.0f / Max(light->GetRange(), M_EPSILON);
  333. graphics->SetShaderParameter(VSP_LIGHTPOS, Vector4(lightNode->GetWorldPosition(), atten));
  334. if (graphics->HasShaderParameter(VS, VSP_LIGHTMATRICES))
  335. {
  336. switch (light->GetLightType())
  337. {
  338. case LIGHT_DIRECTIONAL:
  339. {
  340. Matrix4 shadowMatrices[MAX_CASCADE_SPLITS];
  341. unsigned numSplits = lightQueue_->shadowSplits_.Size();
  342. for (unsigned i = 0; i < numSplits; ++i)
  343. CalculateShadowMatrix(shadowMatrices[i], lightQueue_, i, renderer, Vector3::ZERO);
  344. graphics->SetShaderParameter(VSP_LIGHTMATRICES, shadowMatrices[0].Data(), 16 * numSplits);
  345. }
  346. break;
  347. case LIGHT_SPOT:
  348. {
  349. Matrix4 shadowMatrices[2];
  350. CalculateSpotMatrix(shadowMatrices[0], light, Vector3::ZERO);
  351. bool isShadowed = shadowMap && graphics->HasTextureUnit(TU_SHADOWMAP);
  352. if (isShadowed)
  353. CalculateShadowMatrix(shadowMatrices[1], lightQueue_, 0, renderer, Vector3::ZERO);
  354. graphics->SetShaderParameter(VSP_LIGHTMATRICES, shadowMatrices[0].Data(), isShadowed ? 32 : 16);
  355. }
  356. break;
  357. case LIGHT_POINT:
  358. {
  359. Matrix4 lightVecRot(lightNode->GetWorldTransform().RotationMatrix());
  360. // HLSL compiler will pack the parameters as if the matrix is only 3x4, so must be careful to not overwrite
  361. // the next parameter
  362. #ifdef USE_OPENGL
  363. graphics->SetShaderParameter(VSP_LIGHTMATRICES, lightVecRot.Data(), 16);
  364. #else
  365. graphics->SetShaderParameter(VSP_LIGHTMATRICES, lightVecRot.Data(), 12);
  366. #endif
  367. }
  368. break;
  369. }
  370. }
  371. float fade = 1.0f;
  372. float fadeEnd = light->GetDrawDistance();
  373. float fadeStart = light->GetFadeDistance();
  374. // Do fade calculation for light if both fade & draw distance defined
  375. if (light->GetLightType() != LIGHT_DIRECTIONAL && fadeEnd > 0.0f && fadeStart > 0.0f && fadeStart < fadeEnd)
  376. fade = Min(1.0f - (light->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 1.0f);
  377. graphics->SetShaderParameter(PSP_LIGHTCOLOR, Vector4(light->GetColor().RGBValues(), light->GetSpecularIntensity()) * fade);
  378. graphics->SetShaderParameter(PSP_LIGHTDIR, lightWorldRotation * Vector3::BACK);
  379. graphics->SetShaderParameter(PSP_LIGHTPOS, Vector4(lightNode->GetWorldPosition() - cameraNode->GetWorldPosition(), atten));
  380. if (graphics->HasShaderParameter(PS, PSP_LIGHTMATRICES))
  381. {
  382. switch (light->GetLightType())
  383. {
  384. case LIGHT_DIRECTIONAL:
  385. {
  386. Matrix4 shadowMatrices[MAX_CASCADE_SPLITS];
  387. unsigned numSplits = lightQueue_->shadowSplits_.Size();
  388. for (unsigned i = 0; i < numSplits; ++i)
  389. CalculateShadowMatrix(shadowMatrices[i], lightQueue_, i, renderer, cameraNode->GetWorldPosition());
  390. graphics->SetShaderParameter(PSP_LIGHTMATRICES, shadowMatrices[0].Data(), 16 * numSplits);
  391. }
  392. break;
  393. case LIGHT_SPOT:
  394. {
  395. Matrix4 shadowMatrices[2];
  396. CalculateSpotMatrix(shadowMatrices[0], light, cameraNode->GetWorldPosition());
  397. bool isShadowed = lightQueue_->shadowMap_ != 0;
  398. if (isShadowed)
  399. CalculateShadowMatrix(shadowMatrices[1], lightQueue_, 0, renderer, cameraNode->GetWorldPosition());
  400. graphics->SetShaderParameter(PSP_LIGHTMATRICES, shadowMatrices[0].Data(), isShadowed ? 32 : 16);
  401. }
  402. break;
  403. case LIGHT_POINT:
  404. {
  405. Matrix4 lightVecRot(lightNode->GetWorldTransform().RotationMatrix());
  406. // HLSL compiler will pack the parameters as if the matrix is only 3x4, so must be careful to not overwrite
  407. // the next parameter
  408. #ifdef USE_OPENGL
  409. graphics->SetShaderParameter(PSP_LIGHTMATRICES, lightVecRot.Data(), 16);
  410. #else
  411. graphics->SetShaderParameter(PSP_LIGHTMATRICES, lightVecRot.Data(), 12);
  412. #endif
  413. }
  414. break;
  415. }
  416. }
  417. // Set shadow mapping shader parameters
  418. if (shadowMap)
  419. {
  420. {
  421. unsigned faceWidth = shadowMap->GetWidth() / 2;
  422. unsigned faceHeight = shadowMap->GetHeight() / 3;
  423. float width = (float)shadowMap->GetWidth();
  424. float height = (float)shadowMap->GetHeight();
  425. #ifdef USE_OPENGL
  426. float mulX = (float)(faceWidth - 3) / width;
  427. float mulY = (float)(faceHeight - 3) / height;
  428. float addX = 1.5f / width;
  429. float addY = 1.5f / height;
  430. #else
  431. float mulX = (float)(faceWidth - 4) / width;
  432. float mulY = (float)(faceHeight - 4) / height;
  433. float addX = 2.5f / width;
  434. float addY = 2.5f / height;
  435. #endif
  436. // If using 4 shadow samples, offset the position diagonally by half pixel
  437. if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT)
  438. {
  439. addX -= 0.5f / width;
  440. addY -= 0.5f / height;
  441. }
  442. graphics->SetShaderParameter(PSP_SHADOWCUBEADJUST, Vector4(mulX, mulY, addX, addY));
  443. }
  444. {
  445. Camera* shadowCamera = lightQueue_->shadowSplits_[0].shadowCamera_;
  446. float nearClip = shadowCamera->GetNearClip();
  447. float farClip = shadowCamera->GetFarClip();
  448. float q = farClip / (farClip - nearClip);
  449. float r = -q * nearClip;
  450. const CascadeParameters& parameters = light->GetShadowCascade();
  451. float viewFarClip = camera_->GetFarClip();
  452. float shadowRange = parameters.GetShadowRange();
  453. float fadeStart = parameters.fadeStart_ * shadowRange / viewFarClip;
  454. float fadeEnd = shadowRange / viewFarClip;
  455. float fadeRange = fadeEnd - fadeStart;
  456. graphics->SetShaderParameter(PSP_SHADOWDEPTHFADE, Vector4(q, r, fadeStart, 1.0f / fadeRange));
  457. }
  458. {
  459. float intensity = light->GetShadowIntensity();
  460. float fadeStart = light->GetShadowFadeDistance();
  461. float fadeEnd = light->GetShadowDistance();
  462. if (fadeStart > 0.0f && fadeEnd > 0.0f && fadeEnd > fadeStart)
  463. intensity = Lerp(intensity, 1.0f, Clamp((light->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 0.0f, 1.0f));
  464. float pcfValues = (1.0f - intensity);
  465. float samples = renderer->GetShadowQuality() >= SHADOWQUALITY_HIGH_16BIT ? 4.0f : 1.0f;
  466. graphics->SetShaderParameter(PSP_SHADOWINTENSITY, Vector4(pcfValues / samples, intensity, 0.0f, 0.0f));
  467. }
  468. float sizeX = 1.0f / (float)shadowMap->GetWidth();
  469. float sizeY = 1.0f / (float)shadowMap->GetHeight();
  470. graphics->SetShaderParameter(PSP_SHADOWMAPINVSIZE, Vector4(sizeX, sizeY, 0.0f, 0.0f));
  471. Vector4 lightSplits(M_LARGE_VALUE, M_LARGE_VALUE, M_LARGE_VALUE, M_LARGE_VALUE);
  472. if (lightQueue_->shadowSplits_.Size() > 1)
  473. lightSplits.x_ = lightQueue_->shadowSplits_[0].farSplit_ / camera_->GetFarClip();
  474. if (lightQueue_->shadowSplits_.Size() > 2)
  475. lightSplits.y_ = lightQueue_->shadowSplits_[1].farSplit_ / camera_->GetFarClip();
  476. if (lightQueue_->shadowSplits_.Size() > 3)
  477. lightSplits.z_ = lightQueue_->shadowSplits_[2].farSplit_ / camera_->GetFarClip();
  478. graphics->SetShaderParameter(PSP_SHADOWSPLITS, lightSplits);
  479. }
  480. }
  481. // Set material-specific shader parameters and textures
  482. if (material_)
  483. {
  484. if (graphics->NeedParameterUpdate(SP_MATERIAL, material_))
  485. {
  486. const HashMap<StringHash, MaterialShaderParameter>& parameters = material_->GetShaderParameters();
  487. for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = parameters.Begin(); i != parameters.End(); ++i)
  488. graphics->SetShaderParameter(i->first_, i->second_.value_);
  489. }
  490. const SharedPtr<Texture>* textures = material_->GetTextures();
  491. for (unsigned i = 0; i < MAX_MATERIAL_TEXTURE_UNITS; ++i)
  492. {
  493. TextureUnit unit = (TextureUnit)i;
  494. if (graphics->HasTextureUnit(unit))
  495. graphics->SetTexture(i, textures[i]);
  496. }
  497. }
  498. // Set light-related textures
  499. if (light)
  500. {
  501. if (shadowMap && graphics->HasTextureUnit(TU_SHADOWMAP))
  502. graphics->SetTexture(TU_SHADOWMAP, shadowMap);
  503. if (graphics->HasTextureUnit(TU_LIGHTRAMP))
  504. {
  505. Texture* rampTexture = light->GetRampTexture();
  506. if (!rampTexture)
  507. rampTexture = renderer->GetDefaultLightRamp();
  508. graphics->SetTexture(TU_LIGHTRAMP, rampTexture);
  509. }
  510. if (graphics->HasTextureUnit(TU_LIGHTSHAPE))
  511. {
  512. Texture* shapeTexture = light->GetShapeTexture();
  513. if (!shapeTexture && light->GetLightType() == LIGHT_SPOT)
  514. shapeTexture = renderer->GetDefaultLightSpot();
  515. graphics->SetTexture(TU_LIGHTSHAPE, shapeTexture);
  516. }
  517. }
  518. }
  519. void Batch::Draw(Graphics* graphics, Renderer* renderer) const
  520. {
  521. if (!geometry_->IsEmpty())
  522. {
  523. Prepare(graphics, renderer);
  524. geometry_->Draw(graphics);
  525. }
  526. }
  527. void BatchGroup::SetTransforms(Renderer* renderer, void* lockedData, unsigned& freeIndex)
  528. {
  529. // Do not use up buffer space if not going to draw as instanced
  530. if (geometry_->GetIndexCount() > (unsigned)renderer->GetMaxInstanceTriangles() * 3)
  531. return;
  532. startIndex_ = freeIndex;
  533. Matrix3x4* dest = (Matrix3x4*)lockedData;
  534. dest += freeIndex;
  535. for (unsigned i = 0; i < instances_.Size(); ++i)
  536. *dest++ = *instances_[i].worldTransform_;
  537. freeIndex += instances_.Size();
  538. }
  539. void BatchGroup::Draw(Graphics* graphics, Renderer* renderer) const
  540. {
  541. if (instances_.Size() && !geometry_->IsEmpty())
  542. {
  543. // Draw as individual objects if instancing not supported
  544. VertexBuffer* instanceBuffer = renderer->GetInstancingBuffer();
  545. if (!instanceBuffer || geometry_->GetIndexCount() > (unsigned)renderer->GetMaxInstanceTriangles() * 3)
  546. {
  547. Batch::Prepare(graphics, renderer, false);
  548. graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
  549. graphics->SetVertexBuffers(geometry_->GetVertexBuffers(), geometry_->GetVertexElementMasks());
  550. for (unsigned i = 0; i < instances_.Size(); ++i)
  551. {
  552. if (graphics->NeedParameterUpdate(SP_OBJECTTRANSFORM, instances_[i].worldTransform_))
  553. graphics->SetShaderParameter(VSP_MODEL, *instances_[i].worldTransform_);
  554. graphics->Draw(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(),
  555. geometry_->GetVertexStart(), geometry_->GetVertexCount());
  556. }
  557. }
  558. else
  559. {
  560. Batch::Prepare(graphics, renderer, false);
  561. // Get the geometry vertex buffers, then add the instancing stream buffer
  562. // Hack: use a const_cast to avoid dynamic allocation of new temp vectors
  563. Vector<SharedPtr<VertexBuffer> >& vertexBuffers = const_cast<Vector<SharedPtr<VertexBuffer> >&>
  564. (geometry_->GetVertexBuffers());
  565. PODVector<unsigned>& elementMasks = const_cast<PODVector<unsigned>&>(geometry_->GetVertexElementMasks());
  566. vertexBuffers.Push(SharedPtr<VertexBuffer>(instanceBuffer));
  567. elementMasks.Push(instanceBuffer->GetElementMask());
  568. // No stream offset support, instancing buffer not pre-filled with transforms: have to fill now
  569. if (startIndex_ == M_MAX_UNSIGNED)
  570. {
  571. unsigned startIndex = 0;
  572. while (startIndex < instances_.Size())
  573. {
  574. unsigned instances = instances_.Size() - startIndex;
  575. if (instances > instanceBuffer->GetVertexCount())
  576. instances = instanceBuffer->GetVertexCount();
  577. // Copy the transforms
  578. Matrix3x4* dest = (Matrix3x4*)instanceBuffer->Lock(0, instances, true);
  579. if (dest)
  580. {
  581. for (unsigned i = 0; i < instances; ++i)
  582. dest[i] = *instances_[i + startIndex].worldTransform_;
  583. instanceBuffer->Unlock();
  584. graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
  585. graphics->SetVertexBuffers(vertexBuffers, elementMasks);
  586. graphics->DrawInstanced(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(),
  587. geometry_->GetIndexCount(), geometry_->GetVertexStart(), geometry_->GetVertexCount(), instances);
  588. }
  589. startIndex += instances;
  590. }
  591. }
  592. // Stream offset supported, and instancing buffer has been already filled, so just draw
  593. else
  594. {
  595. graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
  596. graphics->SetVertexBuffers(vertexBuffers, elementMasks, startIndex_);
  597. graphics->DrawInstanced(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(),
  598. geometry_->GetVertexStart(), geometry_->GetVertexCount(), instances_.Size());
  599. }
  600. // Remove the instancing buffer & element mask now
  601. vertexBuffers.Pop();
  602. elementMasks.Pop();
  603. }
  604. }
  605. }
  606. unsigned BatchGroupKey::ToHash() const
  607. {
  608. return ((unsigned)zone_) / sizeof(Zone) + ((unsigned)lightQueue_) / sizeof(LightBatchQueue) + ((unsigned)pass_) / sizeof(Pass)
  609. + ((unsigned)material_) / sizeof(Material) + ((unsigned)geometry_) / sizeof(Geometry);
  610. }
  611. void BatchQueue::Clear(int maxSortedInstances)
  612. {
  613. batches_.Clear();
  614. sortedBaseBatches_.Clear();
  615. sortedBatches_.Clear();
  616. baseBatchGroups_.Clear();
  617. batchGroups_.Clear();
  618. maxSortedInstances_ = maxSortedInstances;
  619. }
  620. void BatchQueue::SortBackToFront()
  621. {
  622. sortedBaseBatches_.Clear();
  623. sortedBatches_.Resize(batches_.Size());
  624. for (unsigned i = 0; i < batches_.Size(); ++i)
  625. sortedBatches_[i] = &batches_[i];
  626. Sort(sortedBatches_.Begin(), sortedBatches_.End(), CompareBatchesBackToFront);
  627. // Do not actually sort batch groups, just list them
  628. sortedBaseBatchGroups_.Resize(baseBatchGroups_.Size());
  629. sortedBatchGroups_.Resize(batchGroups_.Size());
  630. unsigned index = 0;
  631. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  632. sortedBaseBatchGroups_[index++] = &i->second_;
  633. index = 0;
  634. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  635. sortedBatchGroups_[index++] = &i->second_;
  636. }
  637. void BatchQueue::SortFrontToBack()
  638. {
  639. sortedBaseBatches_.Clear();
  640. sortedBatches_.Clear();
  641. // Need to divide into base and non-base batches here to ensure proper order in relation to grouped batches
  642. for (unsigned i = 0; i < batches_.Size(); ++i)
  643. {
  644. if (batches_[i].isBase_)
  645. sortedBaseBatches_.Push(&batches_[i]);
  646. else
  647. sortedBatches_.Push(&batches_[i]);
  648. }
  649. SortFrontToBack2Pass(sortedBaseBatches_);
  650. SortFrontToBack2Pass(sortedBatches_);
  651. // Sort each group front to back
  652. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  653. {
  654. if (i->second_.instances_.Size() <= maxSortedInstances_)
  655. {
  656. Sort(i->second_.instances_.Begin(), i->second_.instances_.End(), CompareInstancesFrontToBack);
  657. if (i->second_.instances_.Size())
  658. i->second_.distance_ = i->second_.instances_[0].distance_;
  659. }
  660. else
  661. {
  662. float minDistance = M_INFINITY;
  663. for (PODVector<InstanceData>::ConstIterator j = i->second_.instances_.Begin(); j != i->second_.instances_.End(); ++j)
  664. minDistance = Min(minDistance, j->distance_);
  665. i->second_.distance_ = minDistance;
  666. }
  667. }
  668. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  669. {
  670. if (i->second_.instances_.Size() <= maxSortedInstances_)
  671. {
  672. Sort(i->second_.instances_.Begin(), i->second_.instances_.End(), CompareInstancesFrontToBack);
  673. if (i->second_.instances_.Size())
  674. i->second_.distance_ = i->second_.instances_[0].distance_;
  675. }
  676. else
  677. {
  678. float minDistance = M_INFINITY;
  679. for (PODVector<InstanceData>::ConstIterator j = i->second_.instances_.Begin(); j != i->second_.instances_.End(); ++j)
  680. minDistance = Min(minDistance, j->distance_);
  681. i->second_.distance_ = minDistance;
  682. }
  683. }
  684. sortedBaseBatchGroups_.Resize(baseBatchGroups_.Size());
  685. sortedBatchGroups_.Resize(batchGroups_.Size());
  686. unsigned index = 0;
  687. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  688. sortedBaseBatchGroups_[index++] = &i->second_;
  689. index = 0;
  690. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  691. sortedBatchGroups_[index++] = &i->second_;
  692. SortFrontToBack2Pass(reinterpret_cast<PODVector<Batch*>& >(sortedBaseBatchGroups_));
  693. SortFrontToBack2Pass(reinterpret_cast<PODVector<Batch*>& >(sortedBatchGroups_));
  694. }
  695. void BatchQueue::SortFrontToBack2Pass(PODVector<Batch*>& batches)
  696. {
  697. // Mobile devices likely use a tiled deferred approach, with which front-to-back sorting is irrelevant. The 2-pass
  698. // method is also time consuming, so just sort with state having priority
  699. #ifdef GL_ES_VERSION_2_0
  700. Sort(batches.Begin(), batches.End(), CompareBatchesState);
  701. #else
  702. // For desktop, first sort by distance and remap shader/material/geometry IDs in the sort key
  703. Sort(batches.Begin(), batches.End(), CompareBatchesFrontToBack);
  704. unsigned freeShaderID = 0;
  705. unsigned short freeMaterialID = 0;
  706. unsigned short freeGeometryID = 0;
  707. for (PODVector<Batch*>::Iterator i = batches.Begin(); i != batches.End(); ++i)
  708. {
  709. Batch* batch = *i;
  710. unsigned shaderID = (batch->sortKey_ >> 32);
  711. HashMap<unsigned, unsigned>::ConstIterator j = shaderRemapping_.Find(shaderID);
  712. if (j != shaderRemapping_.End())
  713. shaderID = j->second_;
  714. else
  715. {
  716. shaderID = shaderRemapping_[shaderID] = freeShaderID | (shaderID & 0xc0000000);
  717. ++freeShaderID;
  718. }
  719. unsigned short materialID = (unsigned short)(batch->sortKey_ & 0xffff0000);
  720. HashMap<unsigned short, unsigned short>::ConstIterator k = materialRemapping_.Find(materialID);
  721. if (k != materialRemapping_.End())
  722. materialID = k->second_;
  723. else
  724. {
  725. materialID = materialRemapping_[materialID] = freeMaterialID;
  726. ++freeMaterialID;
  727. }
  728. unsigned short geometryID = (unsigned short)(batch->sortKey_ & 0xffff);
  729. HashMap<unsigned short, unsigned short>::ConstIterator l = geometryRemapping_.Find(geometryID);
  730. if (l != geometryRemapping_.End())
  731. geometryID = l->second_;
  732. else
  733. {
  734. geometryID = geometryRemapping_[geometryID] = freeGeometryID;
  735. ++freeGeometryID;
  736. }
  737. batch->sortKey_ = (((unsigned long long)shaderID) << 32) || (((unsigned long long)materialID) << 16) | geometryID;
  738. }
  739. shaderRemapping_.Clear();
  740. materialRemapping_.Clear();
  741. geometryRemapping_.Clear();
  742. // Finally sort again with the rewritten ID's
  743. Sort(batches.Begin(), batches.End(), CompareBatchesState);
  744. #endif
  745. }
  746. void BatchQueue::SetTransforms(Renderer* renderer, void* lockedData, unsigned& freeIndex)
  747. {
  748. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  749. i->second_.SetTransforms(renderer, lockedData, freeIndex);
  750. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  751. i->second_.SetTransforms(renderer, lockedData, freeIndex);
  752. }
  753. void BatchQueue::Draw(Graphics* graphics, Renderer* renderer, bool useScissor, bool markToStencil) const
  754. {
  755. graphics->SetScissorTest(false);
  756. // During G-buffer rendering, mark opaque pixels to stencil buffer
  757. if (!markToStencil)
  758. graphics->SetStencilTest(false);
  759. // Base instanced
  760. for (PODVector<BatchGroup*>::ConstIterator i = sortedBaseBatchGroups_.Begin(); i != sortedBaseBatchGroups_.End(); ++i)
  761. {
  762. BatchGroup* group = *i;
  763. if (markToStencil)
  764. graphics->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, group->lightMask_);
  765. group->Draw(graphics, renderer);
  766. }
  767. // Base non-instanced
  768. for (PODVector<Batch*>::ConstIterator i = sortedBaseBatches_.Begin(); i != sortedBaseBatches_.End(); ++i)
  769. {
  770. Batch* batch = *i;
  771. if (markToStencil)
  772. graphics->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, batch->lightMask_);
  773. batch->Draw(graphics, renderer);
  774. }
  775. // Non-base instanced
  776. for (PODVector<BatchGroup*>::ConstIterator i = sortedBatchGroups_.Begin(); i != sortedBatchGroups_.End(); ++i)
  777. {
  778. BatchGroup* group = *i;
  779. if (useScissor && group->lightQueue_)
  780. renderer->OptimizeLightByScissor(group->lightQueue_->light_, group->camera_);
  781. if (markToStencil)
  782. graphics->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, group->lightMask_);
  783. group->Draw(graphics, renderer);
  784. }
  785. // Non-base non-instanced
  786. for (PODVector<Batch*>::ConstIterator i = sortedBatches_.Begin(); i != sortedBatches_.End(); ++i)
  787. {
  788. Batch* batch = *i;
  789. if (useScissor)
  790. {
  791. if (!batch->isBase_ && batch->lightQueue_)
  792. renderer->OptimizeLightByScissor(batch->lightQueue_->light_, batch->camera_);
  793. else
  794. graphics->SetScissorTest(false);
  795. }
  796. if (markToStencil)
  797. graphics->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, batch->lightMask_);
  798. batch->Draw(graphics, renderer);
  799. }
  800. }
  801. void BatchQueue::Draw(Light* light, Graphics* graphics, Renderer* renderer) const
  802. {
  803. graphics->SetScissorTest(false);
  804. graphics->SetStencilTest(false);
  805. // Base instanced
  806. for (PODVector<BatchGroup*>::ConstIterator i = sortedBaseBatchGroups_.Begin(); i != sortedBaseBatchGroups_.End(); ++i)
  807. {
  808. BatchGroup* group = *i;
  809. group->Draw(graphics, renderer);
  810. }
  811. // Base non-instanced
  812. for (PODVector<Batch*>::ConstIterator i = sortedBaseBatches_.Begin(); i != sortedBaseBatches_.End(); ++i)
  813. {
  814. Batch* batch = *i;
  815. batch->Draw(graphics, renderer);
  816. }
  817. // All base passes have been drawn. Optimize at this point by both stencil volume and scissor
  818. bool optimized = false;
  819. // Non-base instanced
  820. for (PODVector<BatchGroup*>::ConstIterator i = sortedBatchGroups_.Begin(); i != sortedBatchGroups_.End(); ++i)
  821. {
  822. BatchGroup* group = *i;
  823. if (!optimized)
  824. {
  825. renderer->OptimizeLightByStencil(light, group->camera_);
  826. renderer->OptimizeLightByScissor(light, group->camera_);
  827. optimized = true;
  828. }
  829. group->Draw(graphics, renderer);
  830. }
  831. // Non-base non-instanced
  832. for (PODVector<Batch*>::ConstIterator i = sortedBatches_.Begin(); i != sortedBatches_.End(); ++i)
  833. {
  834. Batch* batch = *i;
  835. if (!optimized)
  836. {
  837. renderer->OptimizeLightByStencil(light, batch->camera_);
  838. renderer->OptimizeLightByScissor(light, batch->camera_);
  839. optimized = true;
  840. }
  841. batch->Draw(graphics, renderer);
  842. }
  843. }
  844. unsigned BatchQueue::GetNumInstances(Renderer* renderer) const
  845. {
  846. unsigned total = 0;
  847. for (HashMap<BatchGroupKey, BatchGroup>::ConstIterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  848. {
  849. if (i->second_.geometryType_ == GEOM_INSTANCED)
  850. total += i->second_.instances_.Size();
  851. }
  852. for (HashMap<BatchGroupKey, BatchGroup>::ConstIterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  853. {
  854. if (i->second_.geometryType_ == GEOM_INSTANCED)
  855. total += i->second_.instances_.Size();
  856. }
  857. return total;
  858. }
  859. }