Batch.cpp 36 KB

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