Batch.cpp 39 KB

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