Batch.cpp 39 KB

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