Batch.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 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 "Node.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 "View.h"
  38. #include "Zone.h"
  39. #include "DebugNew.h"
  40. inline bool CompareBatchesFrontToBack(Batch* lhs, Batch* rhs)
  41. {
  42. if (lhs->sortKey_ == rhs->sortKey_)
  43. return lhs->distance_ < rhs->distance_;
  44. else
  45. return lhs->sortKey_ > rhs->sortKey_;
  46. }
  47. inline bool CompareBatchesBackToFront(Batch* lhs, Batch* rhs)
  48. {
  49. if (lhs->distance_ == rhs->distance_)
  50. return lhs->sortKey_ > rhs->sortKey_;
  51. else
  52. return lhs->distance_ > rhs->distance_;
  53. }
  54. inline bool CompareInstancesFrontToBack(const InstanceData& lhs, const InstanceData& rhs)
  55. {
  56. return lhs.distance_ < rhs.distance_;
  57. }
  58. inline bool CompareBatchGroupsFrontToBack(BatchGroup* lhs, BatchGroup* rhs)
  59. {
  60. if (lhs->sortKey_ == rhs->sortKey_)
  61. return lhs->distance_ < rhs->distance_;
  62. else
  63. return lhs->sortKey_ > rhs->sortKey_;
  64. }
  65. void CalculateShadowMatrix(Matrix4& dest, LightBatchQueue* queue, unsigned split, Renderer* renderer, const Vector3& translation)
  66. {
  67. Camera* shadowCamera = queue->shadowSplits_[split].shadowCamera_;
  68. const IntRect& viewport = queue->shadowSplits_[split].shadowViewport_;
  69. Matrix3x4 posAdjust(translation, Quaternion::IDENTITY, 1.0f);
  70. Matrix3x4 shadowView(shadowCamera->GetInverseWorldTransform());
  71. Matrix4 shadowProj(shadowCamera->GetProjection());
  72. Matrix4 texAdjust(Matrix4::IDENTITY);
  73. Texture2D* shadowMap = queue->shadowMap_;
  74. if (!shadowMap)
  75. return;
  76. float width = (float)shadowMap->GetWidth();
  77. float height = (float)shadowMap->GetHeight();
  78. Vector2 offset(
  79. (float)viewport.left_ / width,
  80. (float)viewport.top_ / height
  81. );
  82. Vector2 scale(
  83. 0.5f * (float)(viewport.right_ - viewport.left_) / width,
  84. 0.5f * (float)(viewport.bottom_ - viewport.top_) / height
  85. );
  86. #ifdef USE_OPENGL
  87. offset.x_ += scale.x_;
  88. offset.y_ += scale.y_;
  89. offset.y_ = 1.0f - offset.y_;
  90. // If using 4 shadow samples, offset the position diagonally by half pixel
  91. if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT)
  92. {
  93. offset.x_ -= 0.5f / width;
  94. offset.y_ -= 0.5f / height;
  95. }
  96. texAdjust.SetTranslation(Vector3(offset.x_, offset.y_, 0.5f));
  97. texAdjust.SetScale(Vector3(scale.x_, scale.y_, 0.5f));
  98. #else
  99. offset.x_ += scale.x_ + 0.5f / width;
  100. offset.y_ += scale.y_ + 0.5f / height;
  101. if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT)
  102. {
  103. offset.x_ -= 0.5f / width;
  104. offset.y_ -= 0.5f / height;
  105. }
  106. scale.y_ = -scale.y_;
  107. texAdjust.SetTranslation(Vector3(offset.x_, offset.y_, 0.0f));
  108. texAdjust.SetScale(Vector3(scale.x_, scale.y_, 1.0f));
  109. #endif
  110. dest = texAdjust * shadowProj * shadowView * posAdjust;
  111. }
  112. void CalculateSpotMatrix(Matrix4& dest, Light* light, const Vector3& translation)
  113. {
  114. Node* lightNode = light->GetNode();
  115. Matrix3x4 posAdjust(translation, Quaternion::IDENTITY, 1.0f);
  116. Matrix3x4 spotView = lightNode->GetWorldTransform();
  117. // Remove any scaling
  118. spotView.SetRotation(spotView.RotationMatrix());
  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.Inverse() * posAdjust;
  136. }
  137. void Batch::CalculateSortKey()
  138. {
  139. unsigned lightQueue = (*((unsigned*)&lightQueue_) / sizeof(LightBatchQueue)) & 0x3fff;
  140. unsigned pass = (*((unsigned*)&pass_) / sizeof(Pass)) & 0xffff;
  141. unsigned material = (*((unsigned*)&material_) / sizeof(Material)) & 0xffff;
  142. unsigned geometry = (*((unsigned*)&geometry_) / sizeof(Geometry)) & 0xffff;
  143. if (isBase_)
  144. lightQueue |= 0x8000;
  145. if (pass_ && !pass_->GetAlphaMask())
  146. lightQueue |= 0x4000;
  147. sortKey_ = (((unsigned long long)lightQueue) << 48) | (((unsigned long long)pass) << 32) |
  148. (((unsigned long long)material) << 16) | geometry;
  149. }
  150. void Batch::Prepare(Graphics* graphics, Renderer* renderer, bool setModelTransform) const
  151. {
  152. if (!vertexShader_ || !pixelShader_)
  153. return;
  154. Node* cameraNode = camera_ ? camera_->GetNode() : 0;
  155. // Set pass / material-specific renderstates
  156. if (pass_ && material_)
  157. {
  158. graphics->SetBlendMode(pass_->GetBlendMode());
  159. renderer->SetCullMode(pass_->GetType() != PASS_SHADOW ? material_->GetCullMode() : material_->GetShadowCullMode(),
  160. camera_);
  161. graphics->SetDepthTest(pass_->GetDepthTestMode());
  162. graphics->SetDepthWrite(pass_->GetDepthWrite());
  163. }
  164. // Set shaders
  165. graphics->SetShaders(vertexShader_, pixelShader_);
  166. // Set camera shader parameters
  167. unsigned cameraHash = overrideView_ ? (unsigned)camera_ + 4 : (unsigned)camera_;
  168. if (graphics->NeedParameterUpdate(SP_CAMERA, (void*)cameraHash))
  169. {
  170. // Calculate camera rotation just once
  171. Matrix3 cameraWorldRotation = cameraNode->GetWorldTransform().RotationMatrix();
  172. graphics->SetShaderParameter(VSP_CAMERAPOS, cameraNode->GetWorldPosition());
  173. graphics->SetShaderParameter(VSP_CAMERAROT, cameraWorldRotation);
  174. Vector4 depthMode = Vector4::ZERO;
  175. if (camera_->IsOrthographic())
  176. {
  177. depthMode.x_ = 1.0f;
  178. #ifdef USE_OPENGL
  179. depthMode.z_ = 0.5f;
  180. depthMode.w_ = 0.5f;
  181. #else
  182. depthMode.z_ = 1.0f;
  183. #endif
  184. }
  185. else
  186. depthMode.w_ = 1.0f / camera_->GetFarClip();
  187. graphics->SetShaderParameter(VSP_DEPTHMODE, depthMode);
  188. Vector3 nearVector, farVector;
  189. camera_->GetFrustumSize(nearVector, farVector);
  190. Vector4 viewportParams(farVector.x_, farVector.y_, farVector.z_, 0.0f);
  191. graphics->SetShaderParameter(VSP_FRUSTUMSIZE, viewportParams);
  192. if (overrideView_)
  193. graphics->SetShaderParameter(VSP_VIEWPROJ, camera_->GetProjection());
  194. else
  195. graphics->SetShaderParameter(VSP_VIEWPROJ, camera_->GetProjection() * camera_->GetInverseWorldTransform());
  196. graphics->SetShaderParameter(VSP_VIEWRIGHTVECTOR, cameraWorldRotation * Vector3::RIGHT);
  197. graphics->SetShaderParameter(VSP_VIEWUPVECTOR, cameraWorldRotation * Vector3::UP);
  198. float farClip = camera_->GetFarClip();
  199. float nearClip = camera_->GetNearClip();
  200. Vector4 depthReconstruct(farClip / (farClip - nearClip), -nearClip / (farClip - nearClip), 0.0f, 0.0f);
  201. graphics->SetShaderParameter(PSP_DEPTHRECONSTRUCT, depthReconstruct);
  202. }
  203. // Set viewport shader parameters
  204. IntVector2 rtSize = graphics->GetRenderTargetDimensions();
  205. IntRect viewport = graphics->GetViewport();
  206. unsigned viewportHash = (viewport.left_) | (viewport.top_ << 8) | (viewport.right_ << 16) | (viewport.bottom_ << 24);
  207. if (graphics->NeedParameterUpdate(SP_VIEWPORT, (void*)viewportHash))
  208. {
  209. float rtWidth = (float)rtSize.x_;
  210. float rtHeight = (float)rtSize.y_;
  211. float widthRange = 0.5f * (viewport.right_ - viewport.left_) / rtWidth;
  212. float heightRange = 0.5f * (viewport.bottom_ - viewport.top_) / rtHeight;
  213. #ifdef USE_OPENGL
  214. Vector4 bufferUVOffset(((float)viewport.left_) / rtWidth + widthRange,
  215. 1.0f - (((float)viewport.top_) / rtHeight + heightRange), widthRange, heightRange);
  216. #else
  217. Vector4 bufferUVOffset((0.5f + (float)viewport.left_) / rtWidth + widthRange,
  218. (0.5f + (float)viewport.top_) / rtHeight + heightRange, widthRange, heightRange);
  219. #endif
  220. graphics->SetShaderParameter(VSP_GBUFFEROFFSETS, bufferUVOffset);
  221. float sizeX = 1.0f / rtWidth;
  222. float sizeY = 1.0f / rtHeight;
  223. graphics->SetShaderParameter(PSP_GBUFFERINVSIZE, Vector4(sizeX, sizeY, 0.0f, 0.0f));
  224. }
  225. // Set model transform
  226. if (setModelTransform && graphics->NeedParameterUpdate(SP_OBJECTTRANSFORM, worldTransform_))
  227. graphics->SetShaderParameter(VSP_MODEL, *worldTransform_);
  228. // Set skinning transforms
  229. if (shaderData_ && shaderDataSize_ && graphics->NeedParameterUpdate(SP_OBJECTDATA, shaderData_))
  230. graphics->SetShaderParameter(VSP_SKINMATRICES, shaderData_, shaderDataSize_);
  231. // Set zone-related shader parameters
  232. BlendMode blend = graphics->GetBlendMode();
  233. Zone* fogColorZone = (blend == BLEND_ADD || blend == BLEND_ADDALPHA) ? renderer->GetDefaultZone() : zone_;
  234. unsigned zoneHash = (unsigned)zone_ + (unsigned)fogColorZone;
  235. if (zone_ && graphics->NeedParameterUpdate(SP_ZONE, (void*)zoneHash))
  236. {
  237. graphics->SetShaderParameter(VSP_AMBIENTSTARTCOLOR, zone_->GetAmbientStartColor());
  238. graphics->SetShaderParameter(VSP_AMBIENTENDCOLOR, zone_->GetAmbientEndColor().ToVector4() - zone_->GetAmbientStartColor().ToVector4());
  239. const BoundingBox& box = zone_->GetBoundingBox();
  240. Vector3 boxSize = box.Size();
  241. Matrix3x4 adjust(Matrix3x4::IDENTITY);
  242. adjust.SetScale(Vector3(1.0f / boxSize.x_, 1.0f / boxSize.y_, 1.0f / boxSize.z_));
  243. adjust.SetTranslation(Vector3(0.5f, 0.5f, 0.5f));
  244. Matrix3x4 zoneTransform = adjust * zone_->GetInverseWorldTransform();
  245. graphics->SetShaderParameter(VSP_ZONE, zoneTransform);
  246. graphics->SetShaderParameter(PSP_AMBIENTCOLOR, zone_->GetAmbientColor());
  247. // If the pass is additive, override fog color to black so that shaders do not need a separate additive path
  248. graphics->SetShaderParameter(PSP_FOGCOLOR, fogColorZone->GetFogColor());
  249. float farClip = camera_->GetFarClip();
  250. float nearClip = camera_->GetNearClip();
  251. float fogStart = Min(zone_->GetFogStart(), farClip);
  252. float fogEnd = Min(zone_->GetFogEnd(), farClip);
  253. if (fogStart >= fogEnd * (1.0f - M_LARGE_EPSILON))
  254. fogStart = fogEnd * (1.0f - M_LARGE_EPSILON);
  255. float fogRange = Max(fogEnd - fogStart, M_EPSILON);
  256. Vector4 fogParams(fogEnd / farClip, farClip / fogRange, 0.0f, 0.0f);
  257. graphics->SetShaderParameter(PSP_FOGPARAMS, fogParams);
  258. }
  259. // Set light-related shader parameters
  260. Light* light = 0;
  261. Texture2D* shadowMap = 0;
  262. if (lightQueue_)
  263. {
  264. light = lightQueue_->light_;
  265. shadowMap = lightQueue_->shadowMap_;
  266. if (graphics->NeedParameterUpdate(SP_VERTEXLIGHTS, lightQueue_) && graphics->HasShaderParameter(VS, VSP_VERTEXLIGHTS))
  267. {
  268. Vector4 vertexLights[MAX_VERTEX_LIGHTS * 3];
  269. const PODVector<Light*>& lights = lightQueue_->vertexLights_;
  270. for (unsigned i = 0; i < lights.Size(); ++i)
  271. {
  272. Light* vertexLight = lights[i];
  273. Node* vertexLightNode = vertexLight->GetNode();
  274. LightType type = vertexLight->GetLightType();
  275. // Attenuation
  276. float invRange, cutoff, invCutoff;
  277. if (type == LIGHT_DIRECTIONAL)
  278. invRange = 0.0f;
  279. else
  280. invRange = 1.0f / Max(vertexLight->GetRange(), M_EPSILON);
  281. if (type == LIGHT_SPOT)
  282. {
  283. cutoff = cosf(vertexLight->GetFov() * 0.5f * M_DEGTORAD);
  284. invCutoff = 1.0f / (1.0f - cutoff);
  285. }
  286. else
  287. {
  288. cutoff = -1.0f;
  289. invCutoff = 1.0f;
  290. }
  291. // Color
  292. float fade = 1.0f;
  293. float fadeEnd = vertexLight->GetDrawDistance();
  294. float fadeStart = vertexLight->GetFadeDistance();
  295. // Do fade calculation for light if both fade & draw distance defined
  296. if (vertexLight->GetLightType() != LIGHT_DIRECTIONAL && fadeEnd > 0.0f && fadeStart > 0.0f && fadeStart < fadeEnd)
  297. fade = Min(1.0f - (vertexLight->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 1.0f);
  298. Color color = vertexLight->GetColor() * fade;
  299. vertexLights[i * 3] = Vector4(color.r_, color.g_, color.b_, invRange);
  300. // Direction
  301. vertexLights[i * 3 + 1] = Vector4(-(vertexLightNode->GetWorldDirection()), cutoff);
  302. // Position
  303. vertexLights[i * 3 + 2] = Vector4(vertexLightNode->GetWorldPosition(), invCutoff);
  304. }
  305. if (lights.Size())
  306. graphics->SetShaderParameter(VSP_VERTEXLIGHTS, vertexLights[0].Data(), lights.Size() * 3 * 4);
  307. }
  308. }
  309. if (light && graphics->NeedParameterUpdate(SP_LIGHT, light))
  310. {
  311. Node* lightNode = light->GetNode();
  312. Matrix3 lightWorldRotation = lightNode->GetWorldTransform().RotationMatrix();
  313. graphics->SetShaderParameter(VSP_LIGHTDIR, lightWorldRotation * Vector3::BACK);
  314. float atten = 1.0f / Max(light->GetRange(), M_EPSILON);
  315. graphics->SetShaderParameter(VSP_LIGHTPOS, Vector4(lightNode->GetWorldPosition(), atten));
  316. if (graphics->HasShaderParameter(VS, VSP_LIGHTMATRICES))
  317. {
  318. switch (light->GetLightType())
  319. {
  320. case LIGHT_DIRECTIONAL:
  321. {
  322. Matrix4 shadowMatrices[MAX_CASCADE_SPLITS];
  323. unsigned numSplits = lightQueue_->shadowSplits_.Size();
  324. for (unsigned i = 0; i < numSplits; ++i)
  325. CalculateShadowMatrix(shadowMatrices[i], lightQueue_, i, renderer, Vector3::ZERO);
  326. graphics->SetShaderParameter(VSP_LIGHTMATRICES, shadowMatrices[0].Data(), 16 * numSplits);
  327. }
  328. break;
  329. case LIGHT_SPOT:
  330. {
  331. Matrix4 shadowMatrices[2];
  332. CalculateSpotMatrix(shadowMatrices[0], light, Vector3::ZERO);
  333. bool isShadowed = shadowMap && graphics->HasTextureUnit(TU_SHADOWMAP);
  334. if (isShadowed)
  335. CalculateShadowMatrix(shadowMatrices[1], lightQueue_, 0, renderer, Vector3::ZERO);
  336. graphics->SetShaderParameter(VSP_LIGHTMATRICES, shadowMatrices[0].Data(), isShadowed ? 32 : 16);
  337. }
  338. break;
  339. case LIGHT_POINT:
  340. {
  341. Matrix4 lightVecRot(lightNode->GetWorldTransform().RotationMatrix());
  342. // HLSL compiler will pack the parameters as if the matrix is only 3x4, so must be careful to not overwrite
  343. // the next parameter
  344. #ifdef USE_OPENGL
  345. graphics->SetShaderParameter(VSP_LIGHTMATRICES, lightVecRot.Data(), 16);
  346. #else
  347. graphics->SetShaderParameter(VSP_LIGHTMATRICES, lightVecRot.Data(), 12);
  348. #endif
  349. }
  350. break;
  351. }
  352. }
  353. float fade = 1.0f;
  354. float fadeEnd = light->GetDrawDistance();
  355. float fadeStart = light->GetFadeDistance();
  356. // Do fade calculation for light if both fade & draw distance defined
  357. if (light->GetLightType() != LIGHT_DIRECTIONAL && fadeEnd > 0.0f && fadeStart > 0.0f && fadeStart < fadeEnd)
  358. fade = Min(1.0f - (light->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 1.0f);
  359. graphics->SetShaderParameter(PSP_LIGHTCOLOR, Vector4(light->GetColor().RGBValues(), light->GetSpecularIntensity()) * fade);
  360. graphics->SetShaderParameter(PSP_LIGHTDIR, lightWorldRotation * Vector3::BACK);
  361. graphics->SetShaderParameter(PSP_LIGHTPOS, Vector4(lightNode->GetWorldPosition() - cameraNode->GetWorldPosition(), atten));
  362. if (graphics->HasShaderParameter(PS, PSP_LIGHTMATRICES))
  363. {
  364. switch (light->GetLightType())
  365. {
  366. case LIGHT_DIRECTIONAL:
  367. {
  368. Matrix4 shadowMatrices[MAX_CASCADE_SPLITS];
  369. unsigned numSplits = lightQueue_->shadowSplits_.Size();
  370. for (unsigned i = 0; i < numSplits; ++i)
  371. CalculateShadowMatrix(shadowMatrices[i], lightQueue_, i, renderer, cameraNode->GetWorldPosition());
  372. graphics->SetShaderParameter(PSP_LIGHTMATRICES, shadowMatrices[0].Data(), 16 * numSplits);
  373. }
  374. break;
  375. case LIGHT_SPOT:
  376. {
  377. Matrix4 shadowMatrices[2];
  378. CalculateSpotMatrix(shadowMatrices[0], light, cameraNode->GetWorldPosition());
  379. bool isShadowed = lightQueue_->shadowMap_ != 0;
  380. if (isShadowed)
  381. CalculateShadowMatrix(shadowMatrices[1], lightQueue_, 0, renderer, cameraNode->GetWorldPosition());
  382. graphics->SetShaderParameter(PSP_LIGHTMATRICES, shadowMatrices[0].Data(), isShadowed ? 32 : 16);
  383. }
  384. break;
  385. case LIGHT_POINT:
  386. {
  387. Matrix4 lightVecRot(lightNode->GetWorldTransform().RotationMatrix());
  388. // HLSL compiler will pack the parameters as if the matrix is only 3x4, so must be careful to not overwrite
  389. // the next parameter
  390. #ifdef USE_OPENGL
  391. graphics->SetShaderParameter(PSP_LIGHTMATRICES, lightVecRot.Data(), 16);
  392. #else
  393. graphics->SetShaderParameter(PSP_LIGHTMATRICES, lightVecRot.Data(), 12);
  394. #endif
  395. }
  396. break;
  397. }
  398. }
  399. // Set shadow mapping shader parameters
  400. if (shadowMap)
  401. {
  402. {
  403. unsigned faceWidth = shadowMap->GetWidth() / 2;
  404. unsigned faceHeight = shadowMap->GetHeight() / 3;
  405. float width = (float)shadowMap->GetWidth();
  406. float height = (float)shadowMap->GetHeight();
  407. #ifdef USE_OPENGL
  408. float mulX = (float)(faceWidth - 3) / width;
  409. float mulY = (float)(faceHeight - 3) / height;
  410. float addX = 1.5f / width;
  411. float addY = 1.5f / height;
  412. #else
  413. float mulX = (float)(faceWidth - 4) / width;
  414. float mulY = (float)(faceHeight - 4) / height;
  415. float addX = 2.5f / width;
  416. float addY = 2.5f / height;
  417. #endif
  418. // If using 4 shadow samples, offset the position diagonally by half pixel
  419. if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT)
  420. {
  421. addX -= 0.5f / width;
  422. addY -= 0.5f / height;
  423. }
  424. graphics->SetShaderParameter(PSP_SHADOWCUBEADJUST, Vector4(mulX, mulY, addX, addY));
  425. }
  426. {
  427. Camera* shadowCamera = lightQueue_->shadowSplits_[0].shadowCamera_;
  428. float nearClip = shadowCamera->GetNearClip();
  429. float farClip = shadowCamera->GetFarClip();
  430. float q = farClip / (farClip - nearClip);
  431. float r = -q * nearClip;
  432. const CascadeParameters& parameters = light->GetShadowCascade();
  433. float viewFarClip = camera_->GetFarClip();
  434. float shadowRange = parameters.GetShadowRange();
  435. float fadeStart = parameters.fadeStart_ * shadowRange / viewFarClip;
  436. float fadeEnd = shadowRange / viewFarClip;
  437. float fadeRange = fadeEnd - fadeStart;
  438. graphics->SetShaderParameter(PSP_SHADOWDEPTHFADE, Vector4(q, r, fadeStart, 1.0f / fadeRange));
  439. }
  440. {
  441. float intensity = light->GetShadowIntensity();
  442. float fadeStart = light->GetShadowFadeDistance();
  443. float fadeEnd = light->GetShadowDistance();
  444. if (fadeStart > 0.0f && fadeEnd > 0.0f && fadeEnd > fadeStart)
  445. intensity = Lerp(intensity, 1.0f, Clamp((light->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 0.0f, 1.0f));
  446. float pcfValues = (1.0f - intensity);
  447. float samples = renderer->GetShadowQuality() >= SHADOWQUALITY_HIGH_16BIT ? 4.0f : 1.0f;
  448. graphics->SetShaderParameter(PSP_SHADOWINTENSITY, Vector4(pcfValues / samples, intensity, 0.0f, 0.0f));
  449. }
  450. float sizeX = 1.0f / (float)shadowMap->GetWidth();
  451. float sizeY = 1.0f / (float)shadowMap->GetHeight();
  452. graphics->SetShaderParameter(PSP_SHADOWMAPINVSIZE, Vector4(sizeX, sizeY, 0.0f, 0.0f));
  453. Vector4 lightSplits(M_LARGE_VALUE, M_LARGE_VALUE, M_LARGE_VALUE, M_LARGE_VALUE);
  454. if (lightQueue_->shadowSplits_.Size() > 1)
  455. lightSplits.x_ = lightQueue_->shadowSplits_[0].farSplit_ / camera_->GetFarClip();
  456. if (lightQueue_->shadowSplits_.Size() > 2)
  457. lightSplits.y_ = lightQueue_->shadowSplits_[1].farSplit_ / camera_->GetFarClip();
  458. if (lightQueue_->shadowSplits_.Size() > 3)
  459. lightSplits.z_ = lightQueue_->shadowSplits_[2].farSplit_ / camera_->GetFarClip();
  460. graphics->SetShaderParameter(PSP_SHADOWSPLITS, lightSplits);
  461. }
  462. }
  463. // Set material-specific shader parameters and textures
  464. if (material_)
  465. {
  466. if (graphics->NeedParameterUpdate(SP_MATERIAL, material_))
  467. {
  468. const HashMap<StringHash, MaterialShaderParameter>& parameters = material_->GetShaderParameters();
  469. for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = parameters.Begin(); i != parameters.End(); ++i)
  470. graphics->SetShaderParameter(i->first_, i->second_.value_);
  471. }
  472. const SharedPtr<Texture>* textures = material_->GetTextures();
  473. if (graphics->HasTextureUnit(TU_DIFFUSE))
  474. graphics->SetTexture(TU_DIFFUSE, textures[TU_DIFFUSE]);
  475. if (graphics->HasTextureUnit(TU_NORMAL))
  476. graphics->SetTexture(TU_NORMAL, textures[TU_NORMAL]);
  477. if (graphics->HasTextureUnit(TU_SPECULAR))
  478. graphics->SetTexture(TU_NORMAL, textures[TU_SPECULAR]);
  479. if (graphics->HasTextureUnit(TU_ENVIRONMENT))
  480. graphics->SetTexture(TU_ENVIRONMENT, textures[TU_ENVIRONMENT]);
  481. }
  482. // Set light-related textures
  483. if (light)
  484. {
  485. if (shadowMap && graphics->HasTextureUnit(TU_SHADOWMAP))
  486. graphics->SetTexture(TU_SHADOWMAP, shadowMap);
  487. if (graphics->HasTextureUnit(TU_LIGHTRAMP))
  488. {
  489. Texture* rampTexture = light->GetRampTexture();
  490. if (!rampTexture)
  491. rampTexture = renderer->GetDefaultLightRamp();
  492. graphics->SetTexture(TU_LIGHTRAMP, rampTexture);
  493. }
  494. if (graphics->HasTextureUnit(TU_LIGHTSHAPE))
  495. {
  496. Texture* shapeTexture = light->GetShapeTexture();
  497. if (!shapeTexture && light->GetLightType() == LIGHT_SPOT)
  498. shapeTexture = renderer->GetDefaultLightSpot();
  499. graphics->SetTexture(TU_LIGHTSHAPE, shapeTexture);
  500. }
  501. }
  502. }
  503. void Batch::Draw(Graphics* graphics, Renderer* renderer) const
  504. {
  505. Prepare(graphics, renderer);
  506. geometry_->Draw(graphics);
  507. }
  508. void BatchGroup::SetTransforms(Renderer* renderer, void* lockedData, unsigned& freeIndex)
  509. {
  510. // Do not use up buffer space if not going to draw as instanced
  511. if (geometry_->GetIndexCount() > (unsigned)renderer->GetMaxInstanceTriangles() * 3)
  512. return;
  513. startIndex_ = freeIndex;
  514. Matrix3x4* dest = (Matrix3x4*)lockedData;
  515. dest += freeIndex;
  516. for (unsigned i = 0; i < instances_.Size(); ++i)
  517. *dest++ = *instances_[i].worldTransform_;
  518. freeIndex += instances_.Size();
  519. }
  520. void BatchGroup::Draw(Graphics* graphics, Renderer* renderer) const
  521. {
  522. if (!instances_.Size())
  523. return;
  524. // Draw as individual objects if instancing not supported
  525. VertexBuffer* instanceBuffer = renderer->GetInstancingBuffer();
  526. if (!instanceBuffer || geometry_->GetIndexCount() > (unsigned)renderer->GetMaxInstanceTriangles() * 3)
  527. {
  528. Batch::Prepare(graphics, renderer, false);
  529. graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
  530. graphics->SetVertexBuffers(geometry_->GetVertexBuffers(), geometry_->GetVertexElementMasks());
  531. for (unsigned i = 0; i < instances_.Size(); ++i)
  532. {
  533. graphics->SetShaderParameter(VSP_MODEL, *instances_[i].worldTransform_);
  534. graphics->Draw(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(),
  535. geometry_->GetVertexStart(), geometry_->GetVertexCount());
  536. }
  537. graphics->ClearTransformSources();
  538. }
  539. else
  540. {
  541. Batch::Prepare(graphics, renderer, false);
  542. // Get the geometry vertex buffers, then add the instancing stream buffer
  543. // Hack: use a const_cast to avoid dynamic allocation of new temp vectors
  544. Vector<SharedPtr<VertexBuffer> >& vertexBuffers = const_cast<Vector<SharedPtr<VertexBuffer> >&>
  545. (geometry_->GetVertexBuffers());
  546. PODVector<unsigned>& elementMasks = const_cast<PODVector<unsigned>&>(geometry_->GetVertexElementMasks());
  547. vertexBuffers.Push(SharedPtr<VertexBuffer>(instanceBuffer));
  548. elementMasks.Push(instanceBuffer->GetElementMask());
  549. // No stream offset support, instancing buffer not pre-filled with transforms: have to fill now
  550. if (startIndex_ == M_MAX_UNSIGNED)
  551. {
  552. unsigned startIndex = 0;
  553. while (startIndex < instances_.Size())
  554. {
  555. unsigned instances = instances_.Size() - startIndex;
  556. if (instances > instanceBuffer->GetVertexCount())
  557. instances = instanceBuffer->GetVertexCount();
  558. // Copy the transforms
  559. Matrix3x4* dest = (Matrix3x4*)instanceBuffer->Lock(0, instances, true);
  560. if (dest)
  561. {
  562. for (unsigned i = 0; i < instances; ++i)
  563. dest[i] = *instances_[i + startIndex].worldTransform_;
  564. instanceBuffer->Unlock();
  565. graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
  566. graphics->SetVertexBuffers(vertexBuffers, elementMasks);
  567. graphics->DrawInstanced(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(),
  568. geometry_->GetVertexStart(), geometry_->GetVertexCount(), instances);
  569. }
  570. startIndex += instances;
  571. }
  572. }
  573. // Stream offset supported, and instancing buffer has been already filled, so just draw
  574. else
  575. {
  576. graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
  577. graphics->SetVertexBuffers(vertexBuffers, elementMasks, startIndex_);
  578. graphics->DrawInstanced(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(),
  579. geometry_->GetVertexStart(), geometry_->GetVertexCount(), instances_.Size());
  580. }
  581. // Remove the instancing buffer & element mask now
  582. vertexBuffers.Pop();
  583. elementMasks.Pop();
  584. }
  585. }
  586. unsigned BatchGroupKey::ToHash() const
  587. {
  588. return ((unsigned)zone_) / sizeof(Zone) + ((unsigned)lightQueue_) / sizeof(LightBatchQueue) + ((unsigned)pass_) / sizeof(Pass)
  589. + ((unsigned)material_) / sizeof(Material) + ((unsigned)geometry_) / sizeof(Geometry);
  590. }
  591. void BatchQueue::Clear(int maxSortedInstances)
  592. {
  593. batches_.Clear();
  594. sortedBaseBatches_.Clear();
  595. sortedBatches_.Clear();
  596. baseBatchGroups_.Clear();
  597. batchGroups_.Clear();
  598. maxSortedInstances_ = maxSortedInstances;
  599. }
  600. void BatchQueue::SortBackToFront()
  601. {
  602. sortedBaseBatches_.Clear();
  603. sortedBatches_.Resize(batches_.Size());
  604. for (unsigned i = 0; i < batches_.Size(); ++i)
  605. sortedBatches_[i] = &batches_[i];
  606. Sort(sortedBatches_.Begin(), sortedBatches_.End(), CompareBatchesBackToFront);
  607. // Do not actually sort batch groups, just list them
  608. sortedBaseBatchGroups_.Resize(baseBatchGroups_.Size());
  609. sortedBatchGroups_.Resize(batchGroups_.Size());
  610. unsigned index = 0;
  611. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  612. sortedBaseBatchGroups_[index++] = &i->second_;
  613. index = 0;
  614. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  615. sortedBatchGroups_[index++] = &i->second_;
  616. }
  617. void BatchQueue::SortFrontToBack()
  618. {
  619. sortedBaseBatches_.Clear();
  620. sortedBatches_.Clear();
  621. // Need to divide into base and non-base batches here to ensure proper order in relation to grouped batches
  622. for (unsigned i = 0; i < batches_.Size(); ++i)
  623. {
  624. if (batches_[i].isBase_)
  625. sortedBaseBatches_.Push(&batches_[i]);
  626. else
  627. sortedBatches_.Push(&batches_[i]);
  628. }
  629. Sort(sortedBaseBatches_.Begin(), sortedBaseBatches_.End(), CompareBatchesFrontToBack);
  630. Sort(sortedBatches_.Begin(), sortedBatches_.End(), CompareBatchesFrontToBack);
  631. // Sort each group front to back
  632. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  633. {
  634. if (i->second_.instances_.Size() <= maxSortedInstances_)
  635. {
  636. Sort(i->second_.instances_.Begin(), i->second_.instances_.End(), CompareInstancesFrontToBack);
  637. if (i->second_.instances_.Size())
  638. i->second_.distance_ = i->second_.instances_[0].distance_;
  639. }
  640. else
  641. {
  642. float minDistance = M_INFINITY;
  643. for (PODVector<InstanceData>::ConstIterator j = i->second_.instances_.Begin(); j != i->second_.instances_.End(); ++j)
  644. minDistance = Min(minDistance, j->distance_);
  645. i->second_.distance_ = minDistance;
  646. }
  647. }
  648. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  649. {
  650. if (i->second_.instances_.Size() <= maxSortedInstances_)
  651. {
  652. Sort(i->second_.instances_.Begin(), i->second_.instances_.End(), CompareInstancesFrontToBack);
  653. if (i->second_.instances_.Size())
  654. i->second_.distance_ = i->second_.instances_[0].distance_;
  655. }
  656. else
  657. {
  658. float minDistance = M_INFINITY;
  659. for (PODVector<InstanceData>::ConstIterator j = i->second_.instances_.Begin(); j != i->second_.instances_.End(); ++j)
  660. minDistance = Min(minDistance, j->distance_);
  661. i->second_.distance_ = minDistance;
  662. }
  663. }
  664. // Now sort batch groups by the distance of the first batch
  665. sortedBaseBatchGroups_.Resize(baseBatchGroups_.Size());
  666. sortedBatchGroups_.Resize(batchGroups_.Size());
  667. unsigned index = 0;
  668. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  669. sortedBaseBatchGroups_[index++] = &i->second_;
  670. index = 0;
  671. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  672. sortedBatchGroups_[index++] = &i->second_;
  673. Sort(sortedBaseBatchGroups_.Begin(), sortedBaseBatchGroups_.End(), CompareBatchGroupsFrontToBack);
  674. Sort(sortedBatchGroups_.Begin(), sortedBatchGroups_.End(), CompareBatchGroupsFrontToBack);
  675. }
  676. void BatchQueue::SetTransforms(Renderer* renderer, void* lockedData, unsigned& freeIndex)
  677. {
  678. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  679. i->second_.SetTransforms(renderer, lockedData, freeIndex);
  680. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  681. i->second_.SetTransforms(renderer, lockedData, freeIndex);
  682. }
  683. void BatchQueue::Draw(Graphics* graphics, Renderer* renderer, bool useScissor, bool markToStencil) const
  684. {
  685. graphics->SetScissorTest(false);
  686. // During G-buffer rendering, mark opaque pixels to stencil buffer
  687. if (!markToStencil)
  688. graphics->SetStencilTest(false);
  689. // Base instanced
  690. for (PODVector<BatchGroup*>::ConstIterator i = sortedBaseBatchGroups_.Begin(); i != sortedBaseBatchGroups_.End(); ++i)
  691. {
  692. BatchGroup* group = *i;
  693. if (markToStencil)
  694. graphics->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, group->lightMask_);
  695. group->Draw(graphics, renderer);
  696. }
  697. // Base non-instanced
  698. for (PODVector<Batch*>::ConstIterator i = sortedBaseBatches_.Begin(); i != sortedBaseBatches_.End(); ++i)
  699. {
  700. Batch* batch = *i;
  701. if (markToStencil)
  702. graphics->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, batch->lightMask_);
  703. batch->Draw(graphics, renderer);
  704. }
  705. // Non-base instanced
  706. for (PODVector<BatchGroup*>::ConstIterator i = sortedBatchGroups_.Begin(); i != sortedBatchGroups_.End(); ++i)
  707. {
  708. BatchGroup* group = *i;
  709. if (useScissor && group->lightQueue_)
  710. renderer->OptimizeLightByScissor(group->lightQueue_->light_, group->camera_);
  711. if (markToStencil)
  712. graphics->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, group->lightMask_);
  713. group->Draw(graphics, renderer);
  714. }
  715. // Non-base non-instanced
  716. for (PODVector<Batch*>::ConstIterator i = sortedBatches_.Begin(); i != sortedBatches_.End(); ++i)
  717. {
  718. Batch* batch = *i;
  719. if (useScissor)
  720. {
  721. if (!batch->isBase_ && batch->lightQueue_)
  722. renderer->OptimizeLightByScissor(batch->lightQueue_->light_, batch->camera_);
  723. else
  724. graphics->SetScissorTest(false);
  725. }
  726. if (markToStencil)
  727. graphics->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, batch->lightMask_);
  728. batch->Draw(graphics, renderer);
  729. }
  730. }
  731. void BatchQueue::Draw(Light* light, Graphics* graphics, Renderer* renderer) const
  732. {
  733. graphics->SetScissorTest(false);
  734. graphics->SetStencilTest(false);
  735. // Base instanced
  736. for (PODVector<BatchGroup*>::ConstIterator i = sortedBaseBatchGroups_.Begin(); i != sortedBaseBatchGroups_.End(); ++i)
  737. {
  738. BatchGroup* group = *i;
  739. group->Draw(graphics, renderer);
  740. }
  741. // Base non-instanced
  742. for (PODVector<Batch*>::ConstIterator i = sortedBaseBatches_.Begin(); i != sortedBaseBatches_.End(); ++i)
  743. {
  744. Batch* batch = *i;
  745. batch->Draw(graphics, renderer);
  746. }
  747. // All base passes have been drawn. Optimize at this point by both stencil volume and scissor
  748. bool optimized = false;
  749. // Non-base instanced
  750. for (PODVector<BatchGroup*>::ConstIterator i = sortedBatchGroups_.Begin(); i != sortedBatchGroups_.End(); ++i)
  751. {
  752. BatchGroup* group = *i;
  753. if (!optimized)
  754. {
  755. renderer->OptimizeLightByStencil(light, group->camera_);
  756. renderer->OptimizeLightByScissor(light, group->camera_);
  757. optimized = true;
  758. }
  759. group->Draw(graphics, renderer);
  760. }
  761. // Non-base non-instanced
  762. for (PODVector<Batch*>::ConstIterator i = sortedBatches_.Begin(); i != sortedBatches_.End(); ++i)
  763. {
  764. Batch* batch = *i;
  765. if (!optimized)
  766. {
  767. renderer->OptimizeLightByStencil(light, batch->camera_);
  768. renderer->OptimizeLightByScissor(light, batch->camera_);
  769. optimized = true;
  770. }
  771. batch->Draw(graphics, renderer);
  772. }
  773. }
  774. unsigned BatchQueue::GetNumInstances(Renderer* renderer) const
  775. {
  776. unsigned total = 0;
  777. unsigned maxIndexCount = renderer->GetMaxInstanceTriangles() * 3;
  778. // As this function is for the purpose of calculating how much space is needed in the instancing buffer, do not add groups
  779. // that have too many triangles to be instanced
  780. for (HashMap<BatchGroupKey, BatchGroup>::ConstIterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  781. {
  782. if (i->second_.geometry_->GetIndexCount() <= maxIndexCount)
  783. total += i->second_.instances_.Size();
  784. }
  785. for (HashMap<BatchGroupKey, BatchGroup>::ConstIterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  786. {
  787. if (i->second_.geometry_->GetIndexCount() <= maxIndexCount)
  788. total += i->second_.instances_.Size();
  789. }
  790. return total;
  791. }