Batch.cpp 38 KB

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