Batch.cpp 44 KB

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