Batch.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  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(PSP_AMBIENTCOLOR, zone_))
  140. graphics->SetShaderParameter(PSP_AMBIENTCOLOR, zone_->GetAmbientColor().ToVector4());
  141. // If the pass is additive, override fog color to black so that shaders do not need a separate additive path
  142. BlendMode blend = pass_->GetBlendMode();
  143. Zone* fogColorZone = (blend == BLEND_ADD || blend == BLEND_ADDALPHA) ? renderer->GetDefaultZone() : zone_;
  144. if (graphics->NeedParameterUpdate(PSP_FOGCOLOR, fogColorZone))
  145. graphics->SetShaderParameter(PSP_FOGCOLOR, fogColorZone->GetFogColor().ToVector4());
  146. if (graphics->NeedParameterUpdate(PSP_FOGPARAMS, zone_))
  147. {
  148. float farClip = camera_->GetFarClip();
  149. float nearClip = camera_->GetNearClip();
  150. float fogStart = Min(zone_->GetFogStart(), farClip);
  151. float fogEnd = Min(zone_->GetFogEnd(), farClip);
  152. if (fogStart >= fogEnd * (1.0f - M_LARGE_EPSILON))
  153. fogStart = fogEnd * (1.0f - M_LARGE_EPSILON);
  154. float fogRange = Max(fogEnd - fogStart, M_EPSILON);
  155. Vector4 fogParams(fogStart / farClip, fogEnd / farClip, farClip / fogRange, 0.0f);
  156. graphics->SetShaderParameter(PSP_FOGPARAMS, fogParams);
  157. }
  158. }
  159. // Set light-related shader parameters
  160. Light* light = 0;
  161. Texture2D* shadowMap = 0;
  162. if (lightQueue_)
  163. {
  164. light = lightQueue_->light_;
  165. shadowMap = lightQueue_->shadowMap_;
  166. if (graphics->NeedParameterUpdate(VSP_LIGHTATTEN, light))
  167. {
  168. Vector4 lightAtten(1.0f / Max(light->GetRange(), M_EPSILON), 0.0f, 0.0f, 0.0f);
  169. graphics->SetShaderParameter(VSP_LIGHTATTEN, lightAtten);
  170. }
  171. if (graphics->NeedParameterUpdate(VSP_LIGHTDIR, light))
  172. graphics->SetShaderParameter(VSP_LIGHTDIR, light->GetWorldRotation() * Vector3::BACK);
  173. if (graphics->NeedParameterUpdate(VSP_LIGHTPOS, light))
  174. graphics->SetShaderParameter(VSP_LIGHTPOS, light->GetWorldPosition() - camera_->GetWorldPosition());
  175. if (graphics->NeedParameterUpdate(VSP_LIGHTVECROT, light))
  176. {
  177. Matrix3x4 lightVecRot(Vector3::ZERO, light->GetWorldRotation(), Vector3::ONE);
  178. graphics->SetShaderParameter(VSP_LIGHTVECROT, lightVecRot);
  179. }
  180. if (graphics->NeedParameterUpdate(VSP_SPOTPROJ, light))
  181. {
  182. Matrix3x4 spotView(light->GetWorldPosition(), light->GetWorldRotation(), 1.0f);
  183. Matrix4 spotProj(Matrix4::ZERO);
  184. Matrix4 texAdjust(Matrix4::IDENTITY);
  185. // Make the projected light slightly smaller than the shadow map to prevent light spill
  186. float h = 1.005f / tanf(light->GetFov() * M_DEGTORAD * 0.5f);
  187. float w = h / light->GetAspectRatio();
  188. spotProj.m00_ = w;
  189. spotProj.m11_ = h;
  190. spotProj.m22_ = 1.0f / Max(light->GetRange(), M_EPSILON);
  191. spotProj.m32_ = 1.0f;
  192. #ifdef USE_OPENGL
  193. texAdjust.SetTranslation(Vector3(0.5f, 0.5f, 0.5f));
  194. texAdjust.SetScale(Vector3(0.5f, -0.5f, 0.5f));
  195. #else
  196. texAdjust.SetTranslation(Vector3(0.5f, 0.5f, 0.0f));
  197. texAdjust.SetScale(Vector3(0.5f, -0.5f, 1.0f));
  198. #endif
  199. graphics->SetShaderParameter(VSP_SPOTPROJ, texAdjust * spotProj * spotView.Inverse());
  200. }
  201. if (graphics->NeedParameterUpdate(PSP_LIGHTCOLOR, light))
  202. {
  203. float fade = 1.0f;
  204. float fadeEnd = light->GetDrawDistance();
  205. float fadeStart = light->GetFadeDistance();
  206. // Do fade calculation for light if both fade & draw distance defined
  207. if (light->GetLightType() != LIGHT_DIRECTIONAL && fadeEnd > 0.0f && fadeStart > 0.0f && fadeStart < fadeEnd)
  208. fade = Min(1.0f - (light->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 1.0f);
  209. graphics->SetShaderParameter(PSP_LIGHTCOLOR, Vector4(light->GetColor().RGBValues(),
  210. light->GetSpecularIntensity()) * fade);
  211. }
  212. // Set shadow mapping shader parameters
  213. if (shadowMap)
  214. {
  215. if (graphics->NeedParameterUpdate(VSP_SHADOWPROJ, light))
  216. {
  217. Matrix4 shadowMatrices[MAX_CASCADE_SPLITS];
  218. unsigned numSplits = 1;
  219. if (light->GetLightType() == LIGHT_DIRECTIONAL)
  220. numSplits = lightQueue_->shadowSplits_.Size();
  221. for (unsigned i = 0; i < numSplits; ++i)
  222. {
  223. Camera* shadowCamera = lightQueue_->shadowSplits_[i].shadowCamera_;
  224. const IntRect& viewport = lightQueue_->shadowSplits_[i].shadowViewport_;
  225. Matrix3x4 shadowView(shadowCamera->GetInverseWorldTransform());
  226. Matrix4 shadowProj(shadowCamera->GetProjection());
  227. Matrix4 texAdjust(Matrix4::IDENTITY);
  228. float width = (float)shadowMap->GetWidth();
  229. float height = (float)shadowMap->GetHeight();
  230. Vector2 offset(
  231. (float)viewport.left_ / width,
  232. (float)viewport.top_ / height
  233. );
  234. Vector2 scale(
  235. 0.5f * (float)(viewport.right_ - viewport.left_) / width,
  236. 0.5f * (float)(viewport.bottom_ - viewport.top_) / height
  237. );
  238. #ifdef USE_OPENGL
  239. offset.x_ += scale.x_;
  240. offset.y_ += scale.y_;
  241. offset.y_ = 1.0f - offset.y_;
  242. // If using 4 shadow samples, offset the position diagonally by half pixel
  243. if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT)
  244. {
  245. offset.x_ -= 0.5f / width;
  246. offset.y_ -= 0.5f / height;
  247. }
  248. texAdjust.SetTranslation(Vector3(offset.x_, offset.y_, 0.5f));
  249. texAdjust.SetScale(Vector3(scale.x_, scale.y_, 0.5f));
  250. #else
  251. offset.x_ += scale.x_ + 0.5f / width;
  252. offset.y_ += scale.y_ + 0.5f / height;
  253. if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT)
  254. {
  255. offset.x_ -= 0.5f / width;
  256. offset.y_ -= 0.5f / height;
  257. }
  258. // If using 2 shadow samples (fallback mode), offset the position horizontally only
  259. if (graphics->GetFallback())
  260. offset.x_ -= 0.5f / width;
  261. scale.y_ = -scale.y_;
  262. texAdjust.SetTranslation(Vector3(offset.x_, offset.y_, 0.0f));
  263. texAdjust.SetScale(Vector3(scale.x_, scale.y_, 1.0f));
  264. #endif
  265. shadowMatrices[i] = texAdjust * shadowProj * shadowView;
  266. }
  267. graphics->SetShaderParameter(VSP_SHADOWPROJ, shadowMatrices[0].GetData(), 16 * numSplits);
  268. }
  269. if (graphics->NeedParameterUpdate(PSP_SAMPLEOFFSETS, shadowMap))
  270. {
  271. float addX = 1.0f / (float)shadowMap->GetWidth();
  272. float addY = 1.0f / (float)shadowMap->GetHeight();
  273. graphics->SetShaderParameter(PSP_SAMPLEOFFSETS, Vector4(addX, addY, 0.0f, 0.0f));
  274. }
  275. if (graphics->NeedParameterUpdate(PSP_SHADOWCUBEADJUST, light))
  276. {
  277. unsigned faceWidth = shadowMap->GetWidth() / 2;
  278. unsigned faceHeight = shadowMap->GetHeight() / 3;
  279. float width = (float)shadowMap->GetWidth();
  280. float height = (float)shadowMap->GetHeight();
  281. #ifdef USE_OPENGL
  282. float mulX = (float)(faceWidth - 3) / width;
  283. float mulY = (float)(faceHeight - 3) / height;
  284. float addX = 1.5f / width;
  285. float addY = 1.5f / height;
  286. #else
  287. float mulX = (float)(faceWidth - 4) / width;
  288. float mulY = (float)(faceHeight - 4) / height;
  289. float addX = 2.5f / width;
  290. float addY = 2.5f / height;
  291. #endif
  292. // If using 4 shadow samples, offset the position diagonally by half pixel
  293. if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT)
  294. {
  295. addX -= 0.5f / width;
  296. addY -= 0.5f / height;
  297. }
  298. // If using 2 shadow samples (fallback mode), offset the position horizontally only
  299. if (graphics->GetFallback())
  300. addX -= 0.5f / width;
  301. graphics->SetShaderParameter(PSP_SHADOWCUBEADJUST, Vector4(mulX, mulY, addX, addY));
  302. }
  303. if (graphics->NeedParameterUpdate(PSP_SHADOWCUBEPROJ, light))
  304. {
  305. // Note: we use the shadow camera of the first cube face. All are assumed to use the same projection
  306. Camera* shadowCamera = lightQueue_->shadowSplits_[0].shadowCamera_;
  307. float nearClip = shadowCamera->GetNearClip();
  308. float farClip = shadowCamera->GetFarClip();
  309. float q = farClip / (farClip - nearClip);
  310. float r = -q * nearClip;
  311. graphics->SetShaderParameter(PSP_SHADOWCUBEPROJ, Vector4(q, r, 0.0f, 0.0f));
  312. }
  313. if (graphics->NeedParameterUpdate(PSP_SHADOWFADE, light))
  314. {
  315. const CascadeParameters& parameters = light->GetShadowCascade();
  316. float farClip = camera_->GetFarClip();
  317. float shadowRange = parameters.GetShadowRange();
  318. float fadeStart = parameters.fadeStart_ * shadowRange / farClip;
  319. float fadeEnd = shadowRange / farClip;
  320. float fadeRange = fadeEnd - fadeStart;
  321. graphics->SetShaderParameter(PSP_SHADOWFADE, Vector4(fadeStart, 1.0f / fadeRange, 0.0f, 0.0f));
  322. }
  323. if (graphics->NeedParameterUpdate(PSP_SHADOWINTENSITY, light))
  324. {
  325. float intensity = light->GetShadowIntensity();
  326. float fadeStart = light->GetShadowFadeDistance();
  327. float fadeEnd = light->GetShadowDistance();
  328. if (fadeStart > 0.0f && fadeEnd > 0.0f && fadeEnd > fadeStart)
  329. intensity = Lerp(intensity, 1.0f, Clamp((light->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 0.0f, 1.0f));
  330. float pcfValues = (1.0f - intensity);
  331. float samples = 4.0f;
  332. float fallbackBias = 0.0f;
  333. // Fallback mode requires manual depth biasing. We do not do proper slope scale biasing,
  334. // instead just fudge the bias values together
  335. if (graphics->GetFallback())
  336. {
  337. samples = 2.0f;
  338. fallbackBias = graphics->GetDepthConstantBias() + 2.0f * graphics->GetDepthSlopeScaledBias() *
  339. graphics->GetDepthConstantBias();
  340. }
  341. graphics->SetShaderParameter(PSP_SHADOWINTENSITY, Vector4(pcfValues, pcfValues / samples, intensity, fallbackBias));
  342. }
  343. if (graphics->NeedParameterUpdate(PSP_SHADOWSPLITS, light))
  344. {
  345. Vector4 lightSplits(M_LARGE_VALUE, M_LARGE_VALUE, M_LARGE_VALUE, M_LARGE_VALUE);
  346. if (lightQueue_->shadowSplits_.Size() > 1)
  347. lightSplits.x_ = lightQueue_->shadowSplits_[0].farSplit_ / camera_->GetFarClip();
  348. if (lightQueue_->shadowSplits_.Size() > 2)
  349. lightSplits.y_ = lightQueue_->shadowSplits_[1].farSplit_ / camera_->GetFarClip();
  350. if (lightQueue_->shadowSplits_.Size() > 3)
  351. lightSplits.z_ = lightQueue_->shadowSplits_[2].farSplit_ / camera_->GetFarClip();
  352. graphics->SetShaderParameter(PSP_SHADOWSPLITS, lightSplits);
  353. }
  354. }
  355. }
  356. // Set material-specific shader parameters and textures
  357. if (material_)
  358. {
  359. const HashMap<StringHash, MaterialShaderParameter>& parameters = material_->GetShaderParameters();
  360. for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = parameters.Begin(); i != parameters.End(); ++i)
  361. {
  362. if (graphics->NeedParameterUpdate(i->first_, material_))
  363. graphics->SetShaderParameter(i->first_, i->second_.value_);
  364. }
  365. const Vector<SharedPtr<Texture> >& textures = material_->GetTextures();
  366. if (graphics->NeedTextureUnit(TU_DIFFUSE))
  367. graphics->SetTexture(TU_DIFFUSE, textures[TU_DIFFUSE]);
  368. if (graphics->NeedTextureUnit(TU_NORMAL))
  369. graphics->SetTexture(TU_NORMAL, textures[TU_NORMAL]);
  370. if (graphics->NeedTextureUnit(TU_SPECULAR))
  371. graphics->SetTexture(TU_NORMAL, textures[TU_SPECULAR]);
  372. if (graphics->NeedTextureUnit(TU_DETAIL))
  373. graphics->SetTexture(TU_DETAIL, textures[TU_DETAIL]);
  374. if (graphics->NeedTextureUnit(TU_ENVIRONMENT))
  375. graphics->SetTexture(TU_ENVIRONMENT, textures[TU_ENVIRONMENT]);
  376. }
  377. // Set light-related textures
  378. if (light)
  379. {
  380. if (shadowMap && graphics->NeedTextureUnit(TU_SHADOWMAP))
  381. graphics->SetTexture(TU_SHADOWMAP, shadowMap);
  382. if (graphics->NeedTextureUnit(TU_LIGHTRAMP))
  383. {
  384. Texture* rampTexture = light->GetRampTexture();
  385. if (!rampTexture)
  386. rampTexture = renderer->GetDefaultLightRamp();
  387. graphics->SetTexture(TU_LIGHTRAMP, rampTexture);
  388. }
  389. if (graphics->NeedTextureUnit(TU_LIGHTSHAPE))
  390. {
  391. Texture* shapeTexture = light->GetShapeTexture();
  392. if (!shapeTexture && light->GetLightType() == LIGHT_SPOT)
  393. shapeTexture = renderer->GetDefaultLightSpot();
  394. graphics->SetTexture(TU_LIGHTSHAPE, shapeTexture);
  395. }
  396. }
  397. }
  398. void Batch::Draw(Graphics* graphics, Renderer* renderer) const
  399. {
  400. Prepare(graphics, renderer);
  401. geometry_->Draw(graphics);
  402. }
  403. void BatchGroup::SetTransforms(Renderer* renderer, void* lockedData, unsigned& freeIndex)
  404. {
  405. // Do not use up buffer space if not going to draw as instanced
  406. if (geometry_->GetIndexCount() > (unsigned)renderer->GetMaxInstanceTriangles() * 3)
  407. return;
  408. startIndex_ = freeIndex;
  409. Matrix3x4* dest = (Matrix3x4*)lockedData;
  410. dest += freeIndex;
  411. for (unsigned i = 0; i < instances_.Size(); ++i)
  412. *dest++ = *instances_[i].worldTransform_;
  413. freeIndex += instances_.Size();
  414. }
  415. void BatchGroup::Draw(Graphics* graphics, Renderer* renderer) const
  416. {
  417. if (!instances_.Size())
  418. return;
  419. // Draw as individual objects if instancing not supported
  420. VertexBuffer* instanceBuffer = renderer->GetInstancingBuffer();
  421. if (!instanceBuffer || geometry_->GetIndexCount() > (unsigned)renderer->GetMaxInstanceTriangles() * 3)
  422. {
  423. Batch::Prepare(graphics, renderer, false);
  424. graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
  425. graphics->SetVertexBuffers(geometry_->GetVertexBuffers(), geometry_->GetVertexElementMasks());
  426. for (unsigned i = 0; i < instances_.Size(); ++i)
  427. {
  428. graphics->SetShaderParameter(VSP_MODEL, *instances_[i].worldTransform_);
  429. graphics->Draw(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(),
  430. geometry_->GetVertexStart(), geometry_->GetVertexCount());
  431. }
  432. graphics->ClearTransformSources();
  433. }
  434. else
  435. {
  436. Batch::Prepare(graphics, renderer, false);
  437. // Get the geometry vertex buffers, then add the instancing stream buffer
  438. // Hack: use a const_cast to avoid dynamic allocation of new temp vectors
  439. Vector<SharedPtr<VertexBuffer> >& vertexBuffers = const_cast<Vector<SharedPtr<VertexBuffer> >&>
  440. (geometry_->GetVertexBuffers());
  441. PODVector<unsigned>& elementMasks = const_cast<PODVector<unsigned>&>(geometry_->GetVertexElementMasks());
  442. vertexBuffers.Push(SharedPtr<VertexBuffer>(instanceBuffer));
  443. elementMasks.Push(instanceBuffer->GetElementMask());
  444. // No stream offset support, instancing buffer not pre-filled with transforms: have to lock and fill now
  445. if (startIndex_ == M_MAX_UNSIGNED)
  446. {
  447. unsigned startIndex = 0;
  448. while (startIndex < instances_.Size())
  449. {
  450. unsigned instances = instances_.Size() - startIndex;
  451. if (instances > instanceBuffer->GetVertexCount())
  452. instances = instanceBuffer->GetVertexCount();
  453. // Lock the instance stream buffer and copy the transforms
  454. void* data = instanceBuffer->Lock(0, instances, LOCK_DISCARD);
  455. if (!data)
  456. {
  457. // Remember to remove the instancing buffer and element mask
  458. vertexBuffers.Pop();
  459. elementMasks.Pop();
  460. return;
  461. }
  462. Matrix3x4* dest = (Matrix3x4*)data;
  463. for (unsigned i = 0; i < instances; ++i)
  464. dest[i] = *instances_[i + startIndex].worldTransform_;
  465. instanceBuffer->Unlock();
  466. graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
  467. graphics->SetVertexBuffers(vertexBuffers, elementMasks);
  468. graphics->DrawInstanced(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(),
  469. geometry_->GetVertexStart(), geometry_->GetVertexCount(), instances);
  470. startIndex += instances;
  471. }
  472. }
  473. // Stream offset supported, and instancing buffer has been already filled, so just draw
  474. else
  475. {
  476. graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
  477. graphics->SetVertexBuffers(vertexBuffers, elementMasks, startIndex_);
  478. graphics->DrawInstanced(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(),
  479. geometry_->GetVertexStart(), geometry_->GetVertexCount(), instances_.Size());
  480. }
  481. // Remove the instancing buffer & element mask now
  482. vertexBuffers.Pop();
  483. elementMasks.Pop();
  484. }
  485. }
  486. void BatchQueue::Clear()
  487. {
  488. batches_.Clear();
  489. sortedBaseBatches_.Clear();
  490. sortedBatches_.Clear();
  491. baseBatchGroups_.Clear();
  492. batchGroups_.Clear();
  493. }
  494. void BatchQueue::AddBatch(const Batch& batch)
  495. {
  496. // Important: this function does not check whether the batch can actually be instanced. It must have been checked before,
  497. // including setting the correct vertex shader (non-instanced or instanced)
  498. if (batch.geometryType_ != GEOM_INSTANCED)
  499. batches_.Push(batch);
  500. else
  501. {
  502. Map<BatchGroupKey, BatchGroup>* groups = batch.isBase_ ? &baseBatchGroups_ : &batchGroups_;
  503. BatchGroupKey key(batch);
  504. Map<BatchGroupKey, BatchGroup>::Iterator i = groups->Find(key);
  505. if (i == groups->End())
  506. {
  507. // Create a new group based on the batch
  508. BatchGroup newGroup(batch);
  509. newGroup.instances_.Push(InstanceData(batch.worldTransform_, batch.distance_));
  510. groups->Insert(MakePair(key, newGroup));
  511. }
  512. else
  513. i->second_.instances_.Push(InstanceData(batch.worldTransform_, batch.distance_));
  514. }
  515. }
  516. void BatchQueue::SortBackToFront()
  517. {
  518. sortedBaseBatches_.Clear();
  519. sortedBatches_.Resize(batches_.Size());
  520. for (unsigned i = 0; i < batches_.Size(); ++i)
  521. sortedBatches_[i] = &batches_[i];
  522. Sort(sortedBatches_.Begin(), sortedBatches_.End(), CompareBatchesBackToFront);
  523. // Do not actually sort batch groups, just list them
  524. sortedBaseBatchGroups_.Resize(baseBatchGroups_.Size());
  525. sortedBatchGroups_.Resize(batchGroups_.Size());
  526. unsigned index = 0;
  527. for (Map<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  528. sortedBaseBatchGroups_[index++] = &i->second_;
  529. index = 0;
  530. for (Map<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  531. sortedBatchGroups_[index++] = &i->second_;
  532. }
  533. void BatchQueue::SortFrontToBack()
  534. {
  535. sortedBaseBatches_.Clear();
  536. sortedBatches_.Clear();
  537. // Must explicitly divide into base and non-base batches, so that priorities do not get mixed up between
  538. // instanced and non-instanced batches
  539. for (unsigned i = 0; i < batches_.Size(); ++i)
  540. {
  541. if (batches_[i].isBase_)
  542. sortedBaseBatches_.Push(&batches_[i]);
  543. else
  544. sortedBatches_.Push(&batches_[i]);
  545. }
  546. Sort(sortedBaseBatches_.Begin(), sortedBaseBatches_.End(), CompareBatchesFrontToBack);
  547. Sort(sortedBatches_.Begin(), sortedBatches_.End(), CompareBatchesFrontToBack);
  548. // Sort each group front to back
  549. for (Map<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  550. Sort(i->second_.instances_.Begin(), i->second_.instances_.End(), CompareInstancesFrontToBack);
  551. for (Map<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  552. Sort(i->second_.instances_.Begin(), i->second_.instances_.End(), CompareInstancesFrontToBack);
  553. // Now sort batch groups by the distance of the first batch
  554. sortedBaseBatchGroups_.Resize(baseBatchGroups_.Size());
  555. sortedBatchGroups_.Resize(batchGroups_.Size());
  556. unsigned index = 0;
  557. for (Map<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  558. sortedBaseBatchGroups_[index++] = &i->second_;
  559. index = 0;
  560. for (Map<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  561. sortedBatchGroups_[index++] = &i->second_;
  562. Sort(sortedBaseBatchGroups_.Begin(), sortedBaseBatchGroups_.End(), CompareBatchGroupsFrontToBack);
  563. Sort(sortedBatchGroups_.Begin(), sortedBatchGroups_.End(), CompareBatchGroupsFrontToBack);
  564. }
  565. void BatchQueue::SetTransforms(Renderer* renderer, void* lockedData, unsigned& freeIndex)
  566. {
  567. for (Map<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  568. i->second_.SetTransforms(renderer, lockedData, freeIndex);
  569. for (Map<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  570. i->second_.SetTransforms(renderer, lockedData, freeIndex);
  571. }
  572. unsigned BatchQueue::GetNumInstances(Renderer* renderer) const
  573. {
  574. unsigned total = 0;
  575. unsigned maxIndexCount = renderer->GetMaxInstanceTriangles() * 3;
  576. // This is for the purpose of calculating how much space is needed in the instancing buffer. Do not add groups
  577. // that have too many triangles
  578. for (Map<BatchGroupKey, BatchGroup>::ConstIterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  579. {
  580. if (i->second_.geometry_->GetIndexCount() <= maxIndexCount)
  581. total += i->second_.instances_.Size();
  582. }
  583. for (Map<BatchGroupKey, BatchGroup>::ConstIterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  584. {
  585. if (i->second_.geometry_->GetIndexCount() <= maxIndexCount)
  586. total += i->second_.instances_.Size();
  587. }
  588. return total;
  589. }