Batch.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Camera.h"
  25. #include "Geometry.h"
  26. #include "Graphics.h"
  27. #include "GraphicsImpl.h"
  28. #include "Light.h"
  29. #include "Material.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 "Zone.h"
  38. #include "DebugNew.h"
  39. inline bool CompareBatchesFrontToBack(Batch* lhs, Batch* rhs)
  40. {
  41. if (lhs->sortKey_ == rhs->sortKey_)
  42. return lhs->distance_ < rhs->distance_;
  43. else
  44. return lhs->sortKey_ > rhs->sortKey_;
  45. }
  46. inline bool CompareBatchesBackToFront(Batch* lhs, Batch* rhs)
  47. {
  48. if (lhs->distance_ == rhs->distance_)
  49. return lhs->sortKey_ > rhs->sortKey_;
  50. else
  51. return lhs->distance_ > rhs->distance_;
  52. }
  53. inline bool CompareInstancesFrontToBack(const InstanceData& lhs, const InstanceData& rhs)
  54. {
  55. return lhs.distance_ < rhs.distance_;
  56. }
  57. inline bool CompareBatchGroupsFrontToBack(BatchGroup* lhs, BatchGroup* rhs)
  58. {
  59. return lhs->instances_[0].distance_ < rhs->instances_[0].distance_;
  60. }
  61. void Batch::CalculateSortKey()
  62. {
  63. unsigned lightQueue = (*((unsigned*)&lightQueue_) / sizeof(LightBatchQueue)) & 0x7fff;
  64. unsigned pass = (*((unsigned*)&pass_) / sizeof(Pass)) & 0xffff;
  65. unsigned material = (*((unsigned*)&material_) / sizeof(Material)) & 0xffff;
  66. unsigned geometry = (*((unsigned*)&geometry_) / sizeof(Geometry)) & 0xffff;
  67. if (isBase_)
  68. lightQueue |= 0x8000;
  69. sortKey_ = (((unsigned long long)lightQueue) << 48) | (((unsigned long long)pass) << 32) |
  70. (((unsigned long long)material) << 16) | geometry;
  71. }
  72. void Batch::Prepare(Graphics* graphics, Renderer* renderer, bool setModelTransform) const
  73. {
  74. if (!vertexShader_ || !pixelShader_)
  75. return;
  76. // Set pass / material-specific renderstates
  77. if (pass_ && material_)
  78. {
  79. if (pass_->GetAlphaTest())
  80. graphics->SetAlphaTest(true, CMP_GREATEREQUAL, 0.5f);
  81. else
  82. graphics->SetAlphaTest(false);
  83. graphics->SetBlendMode(pass_->GetBlendMode());
  84. graphics->SetCullMode(pass_->GetType() != PASS_SHADOW ? material_->GetCullMode() : material_->GetShadowCullMode());
  85. graphics->SetDepthTest(pass_->GetDepthTestMode());
  86. graphics->SetDepthWrite(pass_->GetDepthWrite());
  87. }
  88. // Set shaders
  89. graphics->SetShaders(vertexShader_, pixelShader_);
  90. // Set viewport and camera shader parameters
  91. if (graphics->NeedParameterUpdate(VSP_CAMERAPOS, camera_))
  92. graphics->SetShaderParameter(VSP_CAMERAPOS, camera_->GetWorldPosition());
  93. if (graphics->NeedParameterUpdate(VSP_CAMERAROT, camera_))
  94. graphics->SetShaderParameter(VSP_CAMERAROT, camera_->GetWorldTransform().RotationMatrix());
  95. if (graphics->NeedParameterUpdate(VSP_DEPTHMODE, camera_))
  96. {
  97. Vector4 depthMode = Vector4::ZERO;
  98. if (camera_->IsOrthographic())
  99. {
  100. depthMode.x_ = 1.0f;
  101. #ifdef USE_OPENGL
  102. depthMode.z_ = 0.5f;
  103. depthMode.w_ = 0.5f;
  104. #else
  105. depthMode.z_ = 1.0f;
  106. #endif
  107. }
  108. else
  109. depthMode.w_ = 1.0f / camera_->GetFarClip();
  110. graphics->SetShaderParameter(VSP_DEPTHMODE, depthMode);
  111. }
  112. if (overrideView_)
  113. {
  114. if (graphics->NeedParameterUpdate(VSP_VIEWPROJ, ((unsigned char*)camera_) + 4))
  115. graphics->SetShaderParameter(VSP_VIEWPROJ, camera_->GetProjection());
  116. }
  117. else
  118. {
  119. if (graphics->NeedParameterUpdate(VSP_VIEWPROJ, camera_))
  120. graphics->SetShaderParameter(VSP_VIEWPROJ, camera_->GetProjection() *
  121. camera_->GetInverseWorldTransform());
  122. }
  123. if (graphics->NeedParameterUpdate(VSP_VIEWRIGHTVECTOR, camera_))
  124. graphics->SetShaderParameter(VSP_VIEWRIGHTVECTOR, camera_->GetRightVector());
  125. if (graphics->NeedParameterUpdate(VSP_VIEWUPVECTOR, camera_))
  126. graphics->SetShaderParameter(VSP_VIEWUPVECTOR, camera_->GetUpVector());
  127. // Set model transform
  128. if (setModelTransform && graphics->NeedParameterUpdate(VSP_MODEL, worldTransform_))
  129. graphics->SetShaderParameter(VSP_MODEL, *worldTransform_);
  130. // Set skinning transforms
  131. if (shaderData_ && shaderDataSize_)
  132. {
  133. if (graphics->NeedParameterUpdate(VSP_SKINMATRICES, shaderData_))
  134. graphics->SetShaderParameter(VSP_SKINMATRICES, shaderData_, shaderDataSize_);
  135. }
  136. // Set zone-related shader parameters
  137. if (zone_)
  138. {
  139. if (graphics->NeedParameterUpdate(VSP_ZONE, zone_))
  140. {
  141. const BoundingBox& box = zone_->GetBoundingBox();
  142. Vector3 boxSize = box.Size();
  143. Matrix3x4 adjust(Matrix3x4::IDENTITY);
  144. adjust.SetScale(Vector3(1.0f / boxSize.x_, 1.0f / boxSize.y_, 1.0f / boxSize.z_));
  145. adjust.SetTranslation(Vector3(0.5f, 0.5f, 0.5f));
  146. Matrix3x4 zoneTransform = adjust * zone_->GetWorldTransform().Inverse();
  147. graphics->SetShaderParameter(VSP_ZONE, zoneTransform);
  148. }
  149. if (graphics->NeedParameterUpdate(PSP_AMBIENTSTARTCOLOR, zone_))
  150. graphics->SetShaderParameter(PSP_AMBIENTSTARTCOLOR, zone_->GetAmbientStartColor().ToVector4());
  151. if (graphics->NeedParameterUpdate(PSP_AMBIENTENDCOLOR, zone_))
  152. graphics->SetShaderParameter(PSP_AMBIENTENDCOLOR, zone_->GetAmbientEndColor().ToVector4() - zone_->GetAmbientStartColor().ToVector4());
  153. // If the pass is additive, override fog color to black so that shaders do not need a separate additive path
  154. BlendMode blend = pass_->GetBlendMode();
  155. Zone* fogColorZone = (blend == BLEND_ADD || blend == BLEND_ADDALPHA) ? renderer->GetDefaultZone() : zone_;
  156. if (graphics->NeedParameterUpdate(PSP_FOGCOLOR, fogColorZone))
  157. graphics->SetShaderParameter(PSP_FOGCOLOR, fogColorZone->GetFogColor().ToVector4());
  158. if (graphics->NeedParameterUpdate(PSP_FOGPARAMS, zone_))
  159. {
  160. float farClip = camera_->GetFarClip();
  161. float nearClip = camera_->GetNearClip();
  162. float fogStart = Min(zone_->GetFogStart(), farClip);
  163. float fogEnd = Min(zone_->GetFogEnd(), farClip);
  164. if (fogStart >= fogEnd * (1.0f - M_LARGE_EPSILON))
  165. fogStart = fogEnd * (1.0f - M_LARGE_EPSILON);
  166. float fogRange = Max(fogEnd - fogStart, M_EPSILON);
  167. Vector4 fogParams(fogStart / farClip, fogEnd / farClip, farClip / fogRange, 0.0f);
  168. graphics->SetShaderParameter(PSP_FOGPARAMS, fogParams);
  169. }
  170. }
  171. // Set light-related shader parameters
  172. Light* light = 0;
  173. Texture2D* shadowMap = 0;
  174. if (lightQueue_)
  175. {
  176. light = lightQueue_->light_;
  177. shadowMap = lightQueue_->shadowMap_;
  178. if (graphics->NeedParameterUpdate(VSP_LIGHTDIR, light))
  179. graphics->SetShaderParameter(VSP_LIGHTDIR, light->GetWorldRotation() * Vector3::BACK);
  180. if (graphics->NeedParameterUpdate(VSP_LIGHTPOS, light))
  181. {
  182. float atten = 1.0f / Max(light->GetRange(), M_EPSILON);
  183. graphics->SetShaderParameter(VSP_LIGHTPOS, Vector4(light->GetWorldPosition(), atten));
  184. }
  185. if (graphics->NeedParameterUpdate(VSP_LIGHTVECROT, light))
  186. {
  187. Matrix3x4 lightVecRot(Vector3::ZERO, light->GetWorldRotation(), Vector3::ONE);
  188. graphics->SetShaderParameter(VSP_LIGHTVECROT, lightVecRot);
  189. }
  190. if (graphics->NeedParameterUpdate(VSP_SPOTPROJ, light))
  191. {
  192. Matrix3x4 spotView(light->GetWorldPosition(), light->GetWorldRotation(), 1.0f);
  193. Matrix4 spotProj(Matrix4::ZERO);
  194. Matrix4 texAdjust(Matrix4::IDENTITY);
  195. // Make the projected light slightly smaller than the shadow map to prevent light spill
  196. float h = 1.005f / tanf(light->GetFov() * M_DEGTORAD * 0.5f);
  197. float w = h / light->GetAspectRatio();
  198. spotProj.m00_ = w;
  199. spotProj.m11_ = h;
  200. spotProj.m22_ = 1.0f / Max(light->GetRange(), M_EPSILON);
  201. spotProj.m32_ = 1.0f;
  202. #ifdef USE_OPENGL
  203. texAdjust.SetTranslation(Vector3(0.5f, 0.5f, 0.5f));
  204. texAdjust.SetScale(Vector3(0.5f, -0.5f, 0.5f));
  205. #else
  206. texAdjust.SetTranslation(Vector3(0.5f, 0.5f, 0.0f));
  207. texAdjust.SetScale(Vector3(0.5f, -0.5f, 1.0f));
  208. #endif
  209. graphics->SetShaderParameter(VSP_SPOTPROJ, texAdjust * spotProj * spotView.Inverse());
  210. }
  211. if (graphics->NeedParameterUpdate(VSP_VERTEXLIGHTS, lightQueue_))
  212. {
  213. Vector4 vertexLights[MAX_VERTEX_LIGHTS * 3];
  214. const PODVector<Light*>& lights = lightQueue_->vertexLights_;
  215. for (unsigned i = 0; i < lights.Size(); ++i)
  216. {
  217. Light* vertexLight = lights[i];
  218. LightType type = vertexLight->GetLightType();
  219. // Attenuation
  220. float invRange, cutoff, invCutoff;
  221. if (type == LIGHT_DIRECTIONAL)
  222. invRange = 0.0f;
  223. else
  224. invRange = 1.0f / Max(vertexLight->GetRange(), M_EPSILON);
  225. if (type == LIGHT_SPOT)
  226. {
  227. cutoff = cosf(vertexLight->GetFov() * 0.5f * M_DEGTORAD);
  228. invCutoff = 1.0f / (1.0f - cutoff);
  229. }
  230. else
  231. {
  232. cutoff = -1.0f;
  233. invCutoff = 1.0f;
  234. }
  235. // Color
  236. float fade = 1.0f;
  237. float fadeEnd = vertexLight->GetDrawDistance();
  238. float fadeStart = vertexLight->GetFadeDistance();
  239. // Do fade calculation for light if both fade & draw distance defined
  240. if (vertexLight->GetLightType() != LIGHT_DIRECTIONAL && fadeEnd > 0.0f && fadeStart > 0.0f && fadeStart < fadeEnd)
  241. fade = Min(1.0f - (vertexLight->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 1.0f);
  242. Color color = vertexLight->GetColor() * fade;
  243. vertexLights[i * 3] = Vector4(color.r_, color.g_, color.b_, invRange);
  244. // Direction
  245. vertexLights[i * 3 + 1] = Vector4(-(vertexLight->GetNode()->GetWorldDirection()), cutoff);
  246. // Position
  247. vertexLights[i * 3 + 2] = Vector4(vertexLight->GetWorldPosition(), invCutoff);
  248. }
  249. if (lights.Size())
  250. graphics->SetShaderParameter(VSP_VERTEXLIGHTS, vertexLights[0].GetData(), lights.Size() * 3 * 4);
  251. }
  252. if (graphics->NeedParameterUpdate(PSP_LIGHTCOLOR, light))
  253. {
  254. float fade = 1.0f;
  255. float fadeEnd = light->GetDrawDistance();
  256. float fadeStart = light->GetFadeDistance();
  257. // Do fade calculation for light if both fade & draw distance defined
  258. if (light->GetLightType() != LIGHT_DIRECTIONAL && fadeEnd > 0.0f && fadeStart > 0.0f && fadeStart < fadeEnd)
  259. fade = Min(1.0f - (light->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 1.0f);
  260. graphics->SetShaderParameter(PSP_LIGHTCOLOR, Vector4(light->GetColor().RGBValues(),
  261. light->GetSpecularIntensity()) * fade);
  262. }
  263. // Set shadow mapping shader parameters
  264. if (shadowMap)
  265. {
  266. if (graphics->NeedParameterUpdate(VSP_SHADOWPROJ, light))
  267. {
  268. Matrix4 shadowMatrices[MAX_CASCADE_SPLITS];
  269. unsigned numSplits = 1;
  270. if (light->GetLightType() == LIGHT_DIRECTIONAL)
  271. numSplits = lightQueue_->shadowSplits_.Size();
  272. for (unsigned i = 0; i < numSplits; ++i)
  273. {
  274. Camera* shadowCamera = lightQueue_->shadowSplits_[i].shadowCamera_;
  275. const IntRect& viewport = lightQueue_->shadowSplits_[i].shadowViewport_;
  276. Matrix3x4 shadowView(shadowCamera->GetInverseWorldTransform());
  277. Matrix4 shadowProj(shadowCamera->GetProjection());
  278. Matrix4 texAdjust(Matrix4::IDENTITY);
  279. float width = (float)shadowMap->GetWidth();
  280. float height = (float)shadowMap->GetHeight();
  281. Vector2 offset(
  282. (float)viewport.left_ / width,
  283. (float)viewport.top_ / height
  284. );
  285. Vector2 scale(
  286. 0.5f * (float)(viewport.right_ - viewport.left_) / width,
  287. 0.5f * (float)(viewport.bottom_ - viewport.top_) / height
  288. );
  289. #ifdef USE_OPENGL
  290. offset.x_ += scale.x_;
  291. offset.y_ += scale.y_;
  292. offset.y_ = 1.0f - offset.y_;
  293. // If using 4 shadow samples, offset the position diagonally by half pixel
  294. if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT)
  295. {
  296. offset.x_ -= 0.5f / width;
  297. offset.y_ -= 0.5f / height;
  298. }
  299. texAdjust.SetTranslation(Vector3(offset.x_, offset.y_, 0.5f));
  300. texAdjust.SetScale(Vector3(scale.x_, scale.y_, 0.5f));
  301. #else
  302. offset.x_ += scale.x_ + 0.5f / width;
  303. offset.y_ += scale.y_ + 0.5f / height;
  304. if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT)
  305. {
  306. offset.x_ -= 0.5f / width;
  307. offset.y_ -= 0.5f / height;
  308. }
  309. // If using 2 shadow samples (fallback mode), offset the position horizontally only
  310. if (graphics->GetFallback())
  311. offset.x_ -= 0.5f / width;
  312. scale.y_ = -scale.y_;
  313. texAdjust.SetTranslation(Vector3(offset.x_, offset.y_, 0.0f));
  314. texAdjust.SetScale(Vector3(scale.x_, scale.y_, 1.0f));
  315. #endif
  316. shadowMatrices[i] = texAdjust * shadowProj * shadowView;
  317. }
  318. graphics->SetShaderParameter(VSP_SHADOWPROJ, shadowMatrices[0].GetData(), 16 * numSplits);
  319. }
  320. if (graphics->NeedParameterUpdate(PSP_SAMPLEOFFSETS, shadowMap))
  321. {
  322. float addX = 1.0f / (float)shadowMap->GetWidth();
  323. float addY = 1.0f / (float)shadowMap->GetHeight();
  324. graphics->SetShaderParameter(PSP_SAMPLEOFFSETS, Vector4(addX, addY, 0.0f, 0.0f));
  325. }
  326. if (graphics->NeedParameterUpdate(PSP_SHADOWCUBEADJUST, light))
  327. {
  328. unsigned faceWidth = shadowMap->GetWidth() / 2;
  329. unsigned faceHeight = shadowMap->GetHeight() / 3;
  330. float width = (float)shadowMap->GetWidth();
  331. float height = (float)shadowMap->GetHeight();
  332. #ifdef USE_OPENGL
  333. float mulX = (float)(faceWidth - 3) / width;
  334. float mulY = (float)(faceHeight - 3) / height;
  335. float addX = 1.5f / width;
  336. float addY = 1.5f / height;
  337. #else
  338. float mulX = (float)(faceWidth - 4) / width;
  339. float mulY = (float)(faceHeight - 4) / height;
  340. float addX = 2.5f / width;
  341. float addY = 2.5f / height;
  342. #endif
  343. // If using 4 shadow samples, offset the position diagonally by half pixel
  344. if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT)
  345. {
  346. addX -= 0.5f / width;
  347. addY -= 0.5f / height;
  348. }
  349. // If using 2 shadow samples (fallback mode), offset the position horizontally only
  350. if (graphics->GetFallback())
  351. addX -= 0.5f / width;
  352. graphics->SetShaderParameter(PSP_SHADOWCUBEADJUST, Vector4(mulX, mulY, addX, addY));
  353. }
  354. if (graphics->NeedParameterUpdate(PSP_SHADOWDEPTHFADE, light))
  355. {
  356. // Note: we use the shadow camera of the first cube face. All are assumed to use the same projection
  357. Camera* shadowCamera = lightQueue_->shadowSplits_[0].shadowCamera_;
  358. float nearClip = shadowCamera->GetNearClip();
  359. float farClip = shadowCamera->GetFarClip();
  360. float q = farClip / (farClip - nearClip);
  361. float r = -q * nearClip;
  362. const CascadeParameters& parameters = light->GetShadowCascade();
  363. float viewFarClip = camera_->GetFarClip();
  364. float shadowRange = parameters.GetShadowRange();
  365. float fadeStart = parameters.fadeStart_ * shadowRange / viewFarClip;
  366. float fadeEnd = shadowRange / viewFarClip;
  367. float fadeRange = fadeEnd - fadeStart;
  368. graphics->SetShaderParameter(PSP_SHADOWDEPTHFADE, Vector4(q, r, fadeStart, 1.0f / fadeRange));
  369. }
  370. if (graphics->NeedParameterUpdate(PSP_SHADOWINTENSITY, light))
  371. {
  372. float intensity = light->GetShadowIntensity();
  373. float fadeStart = light->GetShadowFadeDistance();
  374. float fadeEnd = light->GetShadowDistance();
  375. if (fadeStart > 0.0f && fadeEnd > 0.0f && fadeEnd > fadeStart)
  376. intensity = Lerp(intensity, 1.0f, Clamp((light->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 0.0f, 1.0f));
  377. float pcfValues = (1.0f - intensity);
  378. float samples = 4.0f;
  379. float fallbackBias = 0.0f;
  380. // Fallback mode requires manual depth biasing. We do not do proper slope scale biasing,
  381. // instead just fudge the bias values together
  382. if (graphics->GetFallback())
  383. {
  384. samples = 2.0f;
  385. fallbackBias = graphics->GetDepthConstantBias() + 2.0f * graphics->GetDepthSlopeScaledBias() *
  386. graphics->GetDepthConstantBias();
  387. }
  388. graphics->SetShaderParameter(PSP_SHADOWINTENSITY, Vector4(pcfValues, pcfValues / samples, intensity, fallbackBias));
  389. }
  390. if (graphics->NeedParameterUpdate(PSP_SHADOWSPLITS, light))
  391. {
  392. Vector4 lightSplits(M_LARGE_VALUE, M_LARGE_VALUE, M_LARGE_VALUE, M_LARGE_VALUE);
  393. if (lightQueue_->shadowSplits_.Size() > 1)
  394. lightSplits.x_ = lightQueue_->shadowSplits_[0].farSplit_ / camera_->GetFarClip();
  395. if (lightQueue_->shadowSplits_.Size() > 2)
  396. lightSplits.y_ = lightQueue_->shadowSplits_[1].farSplit_ / camera_->GetFarClip();
  397. if (lightQueue_->shadowSplits_.Size() > 3)
  398. lightSplits.z_ = lightQueue_->shadowSplits_[2].farSplit_ / camera_->GetFarClip();
  399. graphics->SetShaderParameter(PSP_SHADOWSPLITS, lightSplits);
  400. }
  401. }
  402. }
  403. // Set material-specific shader parameters and textures
  404. if (material_)
  405. {
  406. const HashMap<StringHash, MaterialShaderParameter>& parameters = material_->GetShaderParameters();
  407. for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = parameters.Begin(); i != parameters.End(); ++i)
  408. {
  409. if (graphics->NeedParameterUpdate(i->first_, material_))
  410. graphics->SetShaderParameter(i->first_, i->second_.value_);
  411. }
  412. const Vector<SharedPtr<Texture> >& textures = material_->GetTextures();
  413. if (graphics->NeedTextureUnit(TU_DIFFUSE))
  414. graphics->SetTexture(TU_DIFFUSE, textures[TU_DIFFUSE]);
  415. if (graphics->NeedTextureUnit(TU_NORMAL))
  416. graphics->SetTexture(TU_NORMAL, textures[TU_NORMAL]);
  417. if (graphics->NeedTextureUnit(TU_SPECULAR))
  418. graphics->SetTexture(TU_NORMAL, textures[TU_SPECULAR]);
  419. if (graphics->NeedTextureUnit(TU_DETAIL))
  420. graphics->SetTexture(TU_DETAIL, textures[TU_DETAIL]);
  421. if (graphics->NeedTextureUnit(TU_ENVIRONMENT))
  422. graphics->SetTexture(TU_ENVIRONMENT, textures[TU_ENVIRONMENT]);
  423. }
  424. // Set light-related textures
  425. if (light)
  426. {
  427. if (shadowMap && graphics->NeedTextureUnit(TU_SHADOWMAP))
  428. graphics->SetTexture(TU_SHADOWMAP, shadowMap);
  429. if (graphics->NeedTextureUnit(TU_LIGHTRAMP))
  430. {
  431. Texture* rampTexture = light->GetRampTexture();
  432. if (!rampTexture)
  433. rampTexture = renderer->GetDefaultLightRamp();
  434. graphics->SetTexture(TU_LIGHTRAMP, rampTexture);
  435. }
  436. if (graphics->NeedTextureUnit(TU_LIGHTSHAPE))
  437. {
  438. Texture* shapeTexture = light->GetShapeTexture();
  439. if (!shapeTexture && light->GetLightType() == LIGHT_SPOT)
  440. shapeTexture = renderer->GetDefaultLightSpot();
  441. graphics->SetTexture(TU_LIGHTSHAPE, shapeTexture);
  442. }
  443. }
  444. }
  445. void Batch::Draw(Graphics* graphics, Renderer* renderer) const
  446. {
  447. Prepare(graphics, renderer);
  448. geometry_->Draw(graphics);
  449. }
  450. void BatchGroup::SetTransforms(Renderer* renderer, void* lockedData, unsigned& freeIndex)
  451. {
  452. // Do not use up buffer space if not going to draw as instanced
  453. if (geometry_->GetIndexCount() > (unsigned)renderer->GetMaxInstanceTriangles() * 3)
  454. return;
  455. startIndex_ = freeIndex;
  456. Matrix3x4* dest = (Matrix3x4*)lockedData;
  457. dest += freeIndex;
  458. for (unsigned i = 0; i < instances_.Size(); ++i)
  459. *dest++ = *instances_[i].worldTransform_;
  460. freeIndex += instances_.Size();
  461. }
  462. void BatchGroup::Draw(Graphics* graphics, Renderer* renderer) const
  463. {
  464. if (!instances_.Size())
  465. return;
  466. // Draw as individual objects if instancing not supported
  467. VertexBuffer* instanceBuffer = renderer->GetInstancingBuffer();
  468. if (!instanceBuffer || geometry_->GetIndexCount() > (unsigned)renderer->GetMaxInstanceTriangles() * 3)
  469. {
  470. Batch::Prepare(graphics, renderer, false);
  471. graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
  472. graphics->SetVertexBuffers(geometry_->GetVertexBuffers(), geometry_->GetVertexElementMasks());
  473. for (unsigned i = 0; i < instances_.Size(); ++i)
  474. {
  475. graphics->SetShaderParameter(VSP_MODEL, *instances_[i].worldTransform_);
  476. graphics->Draw(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(),
  477. geometry_->GetVertexStart(), geometry_->GetVertexCount());
  478. }
  479. graphics->ClearTransformSources();
  480. }
  481. else
  482. {
  483. Batch::Prepare(graphics, renderer, false);
  484. // Get the geometry vertex buffers, then add the instancing stream buffer
  485. // Hack: use a const_cast to avoid dynamic allocation of new temp vectors
  486. Vector<SharedPtr<VertexBuffer> >& vertexBuffers = const_cast<Vector<SharedPtr<VertexBuffer> >&>
  487. (geometry_->GetVertexBuffers());
  488. PODVector<unsigned>& elementMasks = const_cast<PODVector<unsigned>&>(geometry_->GetVertexElementMasks());
  489. vertexBuffers.Push(SharedPtr<VertexBuffer>(instanceBuffer));
  490. elementMasks.Push(instanceBuffer->GetElementMask());
  491. // No stream offset support, instancing buffer not pre-filled with transforms: have to lock and fill now
  492. if (startIndex_ == M_MAX_UNSIGNED)
  493. {
  494. unsigned startIndex = 0;
  495. while (startIndex < instances_.Size())
  496. {
  497. unsigned instances = instances_.Size() - startIndex;
  498. if (instances > instanceBuffer->GetVertexCount())
  499. instances = instanceBuffer->GetVertexCount();
  500. // Lock the instance stream buffer and copy the transforms
  501. void* data = instanceBuffer->Lock(0, instances, LOCK_DISCARD);
  502. if (!data)
  503. {
  504. // Remember to remove the instancing buffer and element mask
  505. vertexBuffers.Pop();
  506. elementMasks.Pop();
  507. return;
  508. }
  509. Matrix3x4* dest = (Matrix3x4*)data;
  510. for (unsigned i = 0; i < instances; ++i)
  511. dest[i] = *instances_[i + startIndex].worldTransform_;
  512. instanceBuffer->Unlock();
  513. graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
  514. graphics->SetVertexBuffers(vertexBuffers, elementMasks);
  515. graphics->DrawInstanced(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(),
  516. geometry_->GetVertexStart(), geometry_->GetVertexCount(), instances);
  517. startIndex += instances;
  518. }
  519. }
  520. // Stream offset supported, and instancing buffer has been already filled, so just draw
  521. else
  522. {
  523. graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
  524. graphics->SetVertexBuffers(vertexBuffers, elementMasks, startIndex_);
  525. graphics->DrawInstanced(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(),
  526. geometry_->GetVertexStart(), geometry_->GetVertexCount(), instances_.Size());
  527. }
  528. // Remove the instancing buffer & element mask now
  529. vertexBuffers.Pop();
  530. elementMasks.Pop();
  531. }
  532. }
  533. void BatchQueue::Clear()
  534. {
  535. batches_.Clear();
  536. sortedBaseBatches_.Clear();
  537. sortedBatches_.Clear();
  538. baseBatchGroups_.Clear();
  539. batchGroups_.Clear();
  540. }
  541. void BatchQueue::AddBatch(const Batch& batch)
  542. {
  543. // Important: this function does not check whether the batch can actually be instanced. It must have been checked before,
  544. // including setting the correct vertex shader (non-instanced or instanced)
  545. if (batch.geometryType_ != GEOM_INSTANCED)
  546. batches_.Push(batch);
  547. else
  548. {
  549. Map<BatchGroupKey, BatchGroup>* groups = batch.isBase_ ? &baseBatchGroups_ : &batchGroups_;
  550. BatchGroupKey key(batch);
  551. Map<BatchGroupKey, BatchGroup>::Iterator i = groups->Find(key);
  552. if (i == groups->End())
  553. {
  554. // Create a new group based on the batch
  555. BatchGroup newGroup(batch);
  556. newGroup.instances_.Push(InstanceData(batch.worldTransform_, batch.distance_));
  557. groups->Insert(MakePair(key, newGroup));
  558. }
  559. else
  560. i->second_.instances_.Push(InstanceData(batch.worldTransform_, batch.distance_));
  561. }
  562. }
  563. void BatchQueue::SortBackToFront()
  564. {
  565. sortedBaseBatches_.Clear();
  566. sortedBatches_.Resize(batches_.Size());
  567. for (unsigned i = 0; i < batches_.Size(); ++i)
  568. sortedBatches_[i] = &batches_[i];
  569. Sort(sortedBatches_.Begin(), sortedBatches_.End(), CompareBatchesBackToFront);
  570. // Do not actually sort batch groups, just list them
  571. sortedBaseBatchGroups_.Resize(baseBatchGroups_.Size());
  572. sortedBatchGroups_.Resize(batchGroups_.Size());
  573. unsigned index = 0;
  574. for (Map<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  575. sortedBaseBatchGroups_[index++] = &i->second_;
  576. index = 0;
  577. for (Map<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  578. sortedBatchGroups_[index++] = &i->second_;
  579. }
  580. void BatchQueue::SortFrontToBack()
  581. {
  582. sortedBaseBatches_.Clear();
  583. sortedBatches_.Clear();
  584. // Must explicitly divide into base and non-base batches, so that priorities do not get mixed up between
  585. // instanced and non-instanced batches
  586. for (unsigned i = 0; i < batches_.Size(); ++i)
  587. {
  588. if (batches_[i].isBase_)
  589. sortedBaseBatches_.Push(&batches_[i]);
  590. else
  591. sortedBatches_.Push(&batches_[i]);
  592. }
  593. Sort(sortedBaseBatches_.Begin(), sortedBaseBatches_.End(), CompareBatchesFrontToBack);
  594. Sort(sortedBatches_.Begin(), sortedBatches_.End(), CompareBatchesFrontToBack);
  595. // Sort each group front to back
  596. for (Map<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  597. Sort(i->second_.instances_.Begin(), i->second_.instances_.End(), CompareInstancesFrontToBack);
  598. for (Map<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  599. Sort(i->second_.instances_.Begin(), i->second_.instances_.End(), CompareInstancesFrontToBack);
  600. // Now sort batch groups by the distance of the first batch
  601. sortedBaseBatchGroups_.Resize(baseBatchGroups_.Size());
  602. sortedBatchGroups_.Resize(batchGroups_.Size());
  603. unsigned index = 0;
  604. for (Map<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  605. sortedBaseBatchGroups_[index++] = &i->second_;
  606. index = 0;
  607. for (Map<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  608. sortedBatchGroups_[index++] = &i->second_;
  609. Sort(sortedBaseBatchGroups_.Begin(), sortedBaseBatchGroups_.End(), CompareBatchGroupsFrontToBack);
  610. Sort(sortedBatchGroups_.Begin(), sortedBatchGroups_.End(), CompareBatchGroupsFrontToBack);
  611. }
  612. void BatchQueue::SetTransforms(Renderer* renderer, void* lockedData, unsigned& freeIndex)
  613. {
  614. for (Map<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  615. i->second_.SetTransforms(renderer, lockedData, freeIndex);
  616. for (Map<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  617. i->second_.SetTransforms(renderer, lockedData, freeIndex);
  618. }
  619. unsigned BatchQueue::GetNumInstances(Renderer* renderer) const
  620. {
  621. unsigned total = 0;
  622. unsigned maxIndexCount = renderer->GetMaxInstanceTriangles() * 3;
  623. // This is for the purpose of calculating how much space is needed in the instancing buffer. Do not add groups
  624. // that have too many triangles
  625. for (Map<BatchGroupKey, BatchGroup>::ConstIterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  626. {
  627. if (i->second_.geometry_->GetIndexCount() <= maxIndexCount)
  628. total += i->second_.instances_.Size();
  629. }
  630. for (Map<BatchGroupKey, BatchGroup>::ConstIterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  631. {
  632. if (i->second_.geometry_->GetIndexCount() <= maxIndexCount)
  633. total += i->second_.instances_.Size();
  634. }
  635. return total;
  636. }