VertexShaderManager.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. // Copyright 2008 Dolphin Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include "VideoCommon/VertexShaderManager.h"
  4. #include <array>
  5. #include <cmath>
  6. #include <cstring>
  7. #include <iterator>
  8. #include "Common/BitSet.h"
  9. #include "Common/ChunkFile.h"
  10. #include "Common/CommonTypes.h"
  11. #include "Common/Config/Config.h"
  12. #include "Common/Logging/Log.h"
  13. #include "Common/Matrix.h"
  14. #include "Core/Config/GraphicsSettings.h"
  15. #include "Core/ConfigManager.h"
  16. #include "Core/Core.h"
  17. #include "VideoCommon/BPFunctions.h"
  18. #include "VideoCommon/BPMemory.h"
  19. #include "VideoCommon/CPMemory.h"
  20. #include "VideoCommon/FramebufferManager.h"
  21. #include "VideoCommon/FreeLookCamera.h"
  22. #include "VideoCommon/GraphicsModSystem/Runtime/GraphicsModActionData.h"
  23. #include "VideoCommon/GraphicsModSystem/Runtime/GraphicsModManager.h"
  24. #include "VideoCommon/Statistics.h"
  25. #include "VideoCommon/VertexLoaderManager.h"
  26. #include "VideoCommon/VertexManagerBase.h"
  27. #include "VideoCommon/VideoCommon.h"
  28. #include "VideoCommon/VideoConfig.h"
  29. #include "VideoCommon/XFMemory.h"
  30. #include "VideoCommon/XFStateManager.h"
  31. void VertexShaderManager::Init()
  32. {
  33. // Initialize state tracking variables
  34. m_projection_graphics_mod_change = false;
  35. constants = {};
  36. // TODO: should these go inside ResetView()?
  37. m_viewport_correction = Common::Matrix44::Identity();
  38. m_projection_matrix = Common::Matrix44::Identity().data;
  39. dirty = true;
  40. }
  41. Common::Matrix44 VertexShaderManager::LoadProjectionMatrix()
  42. {
  43. const auto& rawProjection = xfmem.projection.rawProjection;
  44. switch (xfmem.projection.type)
  45. {
  46. case ProjectionType::Perspective:
  47. {
  48. const Common::Vec2 fov_multiplier = g_freelook_camera.IsActive() ?
  49. g_freelook_camera.GetFieldOfViewMultiplier() :
  50. Common::Vec2{1, 1};
  51. m_projection_matrix[0] = rawProjection[0] * g_ActiveConfig.fAspectRatioHackW * fov_multiplier.x;
  52. m_projection_matrix[1] = 0.0f;
  53. m_projection_matrix[2] = rawProjection[1] * g_ActiveConfig.fAspectRatioHackW * fov_multiplier.x;
  54. m_projection_matrix[3] = 0.0f;
  55. m_projection_matrix[4] = 0.0f;
  56. m_projection_matrix[5] = rawProjection[2] * g_ActiveConfig.fAspectRatioHackH * fov_multiplier.y;
  57. m_projection_matrix[6] = rawProjection[3] * g_ActiveConfig.fAspectRatioHackH * fov_multiplier.y;
  58. m_projection_matrix[7] = 0.0f;
  59. m_projection_matrix[8] = 0.0f;
  60. m_projection_matrix[9] = 0.0f;
  61. m_projection_matrix[10] = rawProjection[4];
  62. m_projection_matrix[11] = rawProjection[5];
  63. m_projection_matrix[12] = 0.0f;
  64. m_projection_matrix[13] = 0.0f;
  65. m_projection_matrix[14] = -1.0f;
  66. m_projection_matrix[15] = 0.0f;
  67. g_stats.gproj = m_projection_matrix;
  68. }
  69. break;
  70. case ProjectionType::Orthographic:
  71. {
  72. m_projection_matrix[0] = rawProjection[0];
  73. m_projection_matrix[1] = 0.0f;
  74. m_projection_matrix[2] = 0.0f;
  75. m_projection_matrix[3] = rawProjection[1];
  76. m_projection_matrix[4] = 0.0f;
  77. m_projection_matrix[5] = rawProjection[2];
  78. m_projection_matrix[6] = 0.0f;
  79. m_projection_matrix[7] = rawProjection[3];
  80. m_projection_matrix[8] = 0.0f;
  81. m_projection_matrix[9] = 0.0f;
  82. m_projection_matrix[10] = rawProjection[4];
  83. m_projection_matrix[11] = rawProjection[5];
  84. m_projection_matrix[12] = 0.0f;
  85. m_projection_matrix[13] = 0.0f;
  86. m_projection_matrix[14] = 0.0f;
  87. m_projection_matrix[15] = 1.0f;
  88. g_stats.g2proj = m_projection_matrix;
  89. g_stats.proj = rawProjection;
  90. }
  91. break;
  92. default:
  93. ERROR_LOG_FMT(VIDEO, "Unknown projection type: {}", xfmem.projection.type);
  94. }
  95. PRIM_LOG("Projection: {} {} {} {} {} {}", rawProjection[0], rawProjection[1], rawProjection[2],
  96. rawProjection[3], rawProjection[4], rawProjection[5]);
  97. auto corrected_matrix = m_viewport_correction * Common::Matrix44::FromArray(m_projection_matrix);
  98. if (g_freelook_camera.IsActive() && xfmem.projection.type == ProjectionType::Perspective)
  99. corrected_matrix *= g_freelook_camera.GetView();
  100. g_freelook_camera.GetController()->SetClean();
  101. return corrected_matrix;
  102. }
  103. void VertexShaderManager::SetProjectionMatrix(XFStateManager& xf_state_manager)
  104. {
  105. if (xf_state_manager.DidProjectionChange() || g_freelook_camera.GetController()->IsDirty())
  106. {
  107. xf_state_manager.ResetProjection();
  108. auto corrected_matrix = LoadProjectionMatrix();
  109. memcpy(constants.projection.data(), corrected_matrix.data.data(), 4 * sizeof(float4));
  110. }
  111. }
  112. bool VertexShaderManager::UseVertexDepthRange()
  113. {
  114. // We can't compute the depth range in the vertex shader if we don't support depth clamp.
  115. if (!g_ActiveConfig.backend_info.bSupportsDepthClamp)
  116. return false;
  117. // We need a full depth range if a ztexture is used.
  118. if (bpmem.ztex2.op != ZTexOp::Disabled && !bpmem.zcontrol.early_ztest)
  119. return true;
  120. // If an inverted depth range is unsupported, we also need to check if the range is inverted.
  121. if (!g_ActiveConfig.backend_info.bSupportsReversedDepthRange)
  122. {
  123. if (xfmem.viewport.zRange < 0.0f)
  124. return true;
  125. if (xfmem.viewport.zRange > xfmem.viewport.farZ)
  126. return true;
  127. }
  128. // If an oversized depth range or a ztexture is used, we need to calculate the depth range
  129. // in the vertex shader.
  130. return fabs(xfmem.viewport.zRange) > 16777215.0f || fabs(xfmem.viewport.farZ) > 16777215.0f;
  131. }
  132. // Syncs the shader constant buffers with xfmem
  133. // TODO: A cleaner way to control the matrices without making a mess in the parameters field
  134. void VertexShaderManager::SetConstants(const std::vector<std::string>& textures,
  135. XFStateManager& xf_state_manager)
  136. {
  137. if (constants.missing_color_hex != g_ActiveConfig.iMissingColorValue)
  138. {
  139. const float a = (g_ActiveConfig.iMissingColorValue) & 0xFF;
  140. const float b = (g_ActiveConfig.iMissingColorValue >> 8) & 0xFF;
  141. const float g = (g_ActiveConfig.iMissingColorValue >> 16) & 0xFF;
  142. const float r = (g_ActiveConfig.iMissingColorValue >> 24) & 0xFF;
  143. constants.missing_color_hex = g_ActiveConfig.iMissingColorValue;
  144. constants.missing_color_value = {r / 255, g / 255, b / 255, a / 255};
  145. dirty = true;
  146. }
  147. const auto per_vertex_transform_matrix_changes =
  148. xf_state_manager.GetPerVertexTransformMatrixChanges();
  149. if (per_vertex_transform_matrix_changes[0] >= 0)
  150. {
  151. int startn = per_vertex_transform_matrix_changes[0] / 4;
  152. int endn = (per_vertex_transform_matrix_changes[1] + 3) / 4;
  153. memcpy(constants.transformmatrices[startn].data(), &xfmem.posMatrices[startn * 4],
  154. (endn - startn) * sizeof(float4));
  155. dirty = true;
  156. xf_state_manager.ResetPerVertexTransformMatrixChanges();
  157. }
  158. const auto per_vertex_normal_matrices_changed =
  159. xf_state_manager.GetPerVertexNormalMatrixChanges();
  160. if (per_vertex_normal_matrices_changed[0] >= 0)
  161. {
  162. int startn = per_vertex_normal_matrices_changed[0] / 3;
  163. int endn = (per_vertex_normal_matrices_changed[1] + 2) / 3;
  164. for (int i = startn; i < endn; i++)
  165. {
  166. memcpy(constants.normalmatrices[i].data(), &xfmem.normalMatrices[3 * i], 12);
  167. }
  168. dirty = true;
  169. xf_state_manager.ResetPerVertexNormalMatrixChanges();
  170. }
  171. const auto post_transform_matrices_changed = xf_state_manager.GetPostTransformMatrixChanges();
  172. if (post_transform_matrices_changed[0] >= 0)
  173. {
  174. int startn = post_transform_matrices_changed[0] / 4;
  175. int endn = (post_transform_matrices_changed[1] + 3) / 4;
  176. memcpy(constants.posttransformmatrices[startn].data(), &xfmem.postMatrices[startn * 4],
  177. (endn - startn) * sizeof(float4));
  178. dirty = true;
  179. xf_state_manager.ResetPostTransformMatrixChanges();
  180. }
  181. const auto light_changes = xf_state_manager.GetLightsChanged();
  182. if (light_changes[0] >= 0)
  183. {
  184. // TODO: Outdated comment
  185. // lights don't have a 1 to 1 mapping, the color component needs to be converted to 4 floats
  186. const int istart = light_changes[0] / 0x10;
  187. const int iend = (light_changes[1] + 15) / 0x10;
  188. for (int i = istart; i < iend; ++i)
  189. {
  190. const Light& light = xfmem.lights[i];
  191. VertexShaderConstants::Light& dstlight = constants.lights[i];
  192. // xfmem.light.color is packed as abgr in u8[4], so we have to swap the order
  193. dstlight.color[0] = light.color[3];
  194. dstlight.color[1] = light.color[2];
  195. dstlight.color[2] = light.color[1];
  196. dstlight.color[3] = light.color[0];
  197. dstlight.cosatt[0] = light.cosatt[0];
  198. dstlight.cosatt[1] = light.cosatt[1];
  199. dstlight.cosatt[2] = light.cosatt[2];
  200. if (fabs(light.distatt[0]) < 0.00001f && fabs(light.distatt[1]) < 0.00001f &&
  201. fabs(light.distatt[2]) < 0.00001f)
  202. {
  203. // dist attenuation, make sure not equal to 0!!!
  204. dstlight.distatt[0] = .00001f;
  205. }
  206. else
  207. {
  208. dstlight.distatt[0] = light.distatt[0];
  209. }
  210. dstlight.distatt[1] = light.distatt[1];
  211. dstlight.distatt[2] = light.distatt[2];
  212. dstlight.pos[0] = light.dpos[0];
  213. dstlight.pos[1] = light.dpos[1];
  214. dstlight.pos[2] = light.dpos[2];
  215. // TODO: Hardware testing is needed to confirm that this normalization is correct
  216. auto sanitize = [](float f) {
  217. if (std::isnan(f))
  218. return 0.0f;
  219. else if (std::isinf(f))
  220. return f > 0.0f ? 1.0f : -1.0f;
  221. else
  222. return f;
  223. };
  224. double norm = double(light.ddir[0]) * double(light.ddir[0]) +
  225. double(light.ddir[1]) * double(light.ddir[1]) +
  226. double(light.ddir[2]) * double(light.ddir[2]);
  227. norm = 1.0 / sqrt(norm);
  228. dstlight.dir[0] = sanitize(static_cast<float>(light.ddir[0] * norm));
  229. dstlight.dir[1] = sanitize(static_cast<float>(light.ddir[1] * norm));
  230. dstlight.dir[2] = sanitize(static_cast<float>(light.ddir[2] * norm));
  231. }
  232. dirty = true;
  233. xf_state_manager.ResetLightsChanged();
  234. }
  235. for (int i : xf_state_manager.GetMaterialChanges())
  236. {
  237. u32 data = i >= 2 ? xfmem.matColor[i - 2] : xfmem.ambColor[i];
  238. constants.materials[i][0] = (data >> 24) & 0xFF;
  239. constants.materials[i][1] = (data >> 16) & 0xFF;
  240. constants.materials[i][2] = (data >> 8) & 0xFF;
  241. constants.materials[i][3] = data & 0xFF;
  242. dirty = true;
  243. }
  244. xf_state_manager.ResetMaterialChanges();
  245. if (xf_state_manager.DidPosNormalChange())
  246. {
  247. xf_state_manager.ResetPosNormalChange();
  248. const float* pos = &xfmem.posMatrices[g_main_cp_state.matrix_index_a.PosNormalMtxIdx * 4];
  249. const float* norm =
  250. &xfmem.normalMatrices[3 * (g_main_cp_state.matrix_index_a.PosNormalMtxIdx & 31)];
  251. memcpy(constants.posnormalmatrix.data(), pos, 3 * sizeof(float4));
  252. memcpy(constants.posnormalmatrix[3].data(), norm, 3 * sizeof(float));
  253. memcpy(constants.posnormalmatrix[4].data(), norm + 3, 3 * sizeof(float));
  254. memcpy(constants.posnormalmatrix[5].data(), norm + 6, 3 * sizeof(float));
  255. dirty = true;
  256. }
  257. if (xf_state_manager.DidTexMatrixAChange())
  258. {
  259. xf_state_manager.ResetTexMatrixAChange();
  260. const std::array<const float*, 4> pos_matrix_ptrs{
  261. &xfmem.posMatrices[g_main_cp_state.matrix_index_a.Tex0MtxIdx * 4],
  262. &xfmem.posMatrices[g_main_cp_state.matrix_index_a.Tex1MtxIdx * 4],
  263. &xfmem.posMatrices[g_main_cp_state.matrix_index_a.Tex2MtxIdx * 4],
  264. &xfmem.posMatrices[g_main_cp_state.matrix_index_a.Tex3MtxIdx * 4],
  265. };
  266. for (size_t i = 0; i < pos_matrix_ptrs.size(); ++i)
  267. {
  268. memcpy(constants.texmatrices[3 * i].data(), pos_matrix_ptrs[i], 3 * sizeof(float4));
  269. }
  270. dirty = true;
  271. }
  272. if (xf_state_manager.DidTexMatrixBChange())
  273. {
  274. xf_state_manager.ResetTexMatrixBChange();
  275. const std::array<const float*, 4> pos_matrix_ptrs{
  276. &xfmem.posMatrices[g_main_cp_state.matrix_index_b.Tex4MtxIdx * 4],
  277. &xfmem.posMatrices[g_main_cp_state.matrix_index_b.Tex5MtxIdx * 4],
  278. &xfmem.posMatrices[g_main_cp_state.matrix_index_b.Tex6MtxIdx * 4],
  279. &xfmem.posMatrices[g_main_cp_state.matrix_index_b.Tex7MtxIdx * 4],
  280. };
  281. for (size_t i = 0; i < pos_matrix_ptrs.size(); ++i)
  282. {
  283. memcpy(constants.texmatrices[3 * i + 12].data(), pos_matrix_ptrs[i], 3 * sizeof(float4));
  284. }
  285. dirty = true;
  286. }
  287. if (xf_state_manager.DidViewportChange())
  288. {
  289. xf_state_manager.ResetViewportChange();
  290. // The console GPU places the pixel center at 7/12 unless antialiasing
  291. // is enabled, while D3D and OpenGL place it at 0.5. See the comment
  292. // in VertexShaderGen.cpp for details.
  293. // NOTE: If we ever emulate antialiasing, the sample locations set by
  294. // BP registers 0x01-0x04 need to be considered here.
  295. const float pixel_center_correction = 7.0f / 12.0f - 0.5f;
  296. const bool bUseVertexRounding = g_ActiveConfig.UseVertexRounding();
  297. const float viewport_width = bUseVertexRounding ?
  298. (2.f * xfmem.viewport.wd) :
  299. g_framebuffer_manager->EFBToScaledXf(2.f * xfmem.viewport.wd);
  300. const float viewport_height = bUseVertexRounding ?
  301. (2.f * xfmem.viewport.ht) :
  302. g_framebuffer_manager->EFBToScaledXf(2.f * xfmem.viewport.ht);
  303. const float pixel_size_x = 2.f / viewport_width;
  304. const float pixel_size_y = 2.f / viewport_height;
  305. constants.pixelcentercorrection[0] = pixel_center_correction * pixel_size_x;
  306. constants.pixelcentercorrection[1] = pixel_center_correction * pixel_size_y;
  307. // By default we don't change the depth value at all in the vertex shader.
  308. constants.pixelcentercorrection[2] = 1.0f;
  309. constants.pixelcentercorrection[3] = 0.0f;
  310. constants.viewport[0] = (2.f * xfmem.viewport.wd);
  311. constants.viewport[1] = (2.f * xfmem.viewport.ht);
  312. if (UseVertexDepthRange())
  313. {
  314. // Oversized depth ranges are handled in the vertex shader. We need to reverse
  315. // the far value to use the reversed-Z trick.
  316. if (g_ActiveConfig.backend_info.bSupportsReversedDepthRange)
  317. {
  318. // Sometimes the console also tries to use the reversed-Z trick. We can only do
  319. // that with the expected accuracy if the backend can reverse the depth range.
  320. constants.pixelcentercorrection[2] = fabs(xfmem.viewport.zRange) / 16777215.0f;
  321. if (xfmem.viewport.zRange < 0.0f)
  322. constants.pixelcentercorrection[3] = xfmem.viewport.farZ / 16777215.0f;
  323. else
  324. constants.pixelcentercorrection[3] = 1.0f - xfmem.viewport.farZ / 16777215.0f;
  325. }
  326. else
  327. {
  328. // For backends that don't support reversing the depth range we can still render
  329. // cases where the console uses the reversed-Z trick. But we simply can't provide
  330. // the expected accuracy, which might result in z-fighting.
  331. constants.pixelcentercorrection[2] = xfmem.viewport.zRange / 16777215.0f;
  332. constants.pixelcentercorrection[3] = 1.0f - xfmem.viewport.farZ / 16777215.0f;
  333. }
  334. }
  335. dirty = true;
  336. BPFunctions::SetScissorAndViewport();
  337. g_stats.AddScissorRect();
  338. }
  339. std::vector<GraphicsModAction*> projection_actions;
  340. if (g_ActiveConfig.bGraphicMods)
  341. {
  342. for (const auto& action : g_graphics_mod_manager->GetProjectionActions(xfmem.projection.type))
  343. {
  344. projection_actions.push_back(action);
  345. }
  346. for (const auto& texture : textures)
  347. {
  348. for (const auto& action :
  349. g_graphics_mod_manager->GetProjectionTextureActions(xfmem.projection.type, texture))
  350. {
  351. projection_actions.push_back(action);
  352. }
  353. }
  354. }
  355. if (xf_state_manager.DidProjectionChange() || g_freelook_camera.GetController()->IsDirty() ||
  356. !projection_actions.empty() || m_projection_graphics_mod_change)
  357. {
  358. xf_state_manager.ResetProjection();
  359. m_projection_graphics_mod_change = !projection_actions.empty();
  360. auto corrected_matrix = LoadProjectionMatrix();
  361. GraphicsModActionData::Projection projection{&corrected_matrix};
  362. for (const auto& action : projection_actions)
  363. {
  364. action->OnProjection(&projection);
  365. }
  366. memcpy(constants.projection.data(), corrected_matrix.data.data(), 4 * sizeof(float4));
  367. dirty = true;
  368. }
  369. if (xf_state_manager.DidTexMatrixInfoChange())
  370. {
  371. xf_state_manager.ResetTexMatrixInfoChange();
  372. constants.xfmem_dualTexInfo = xfmem.dualTexTrans.enabled;
  373. for (size_t i = 0; i < std::size(xfmem.texMtxInfo); i++)
  374. constants.xfmem_pack1[i][0] = xfmem.texMtxInfo[i].hex;
  375. for (size_t i = 0; i < std::size(xfmem.postMtxInfo); i++)
  376. constants.xfmem_pack1[i][1] = xfmem.postMtxInfo[i].hex;
  377. dirty = true;
  378. }
  379. if (xf_state_manager.DidLightingConfigChange())
  380. {
  381. xf_state_manager.ResetLightingConfigChange();
  382. for (size_t i = 0; i < 2; i++)
  383. {
  384. constants.xfmem_pack1[i][2] = xfmem.color[i].hex;
  385. constants.xfmem_pack1[i][3] = xfmem.alpha[i].hex;
  386. }
  387. constants.xfmem_numColorChans = xfmem.numChan.numColorChans;
  388. dirty = true;
  389. }
  390. }
  391. void VertexShaderManager::TransformToClipSpace(const float* data, float* out, u32 MtxIdx)
  392. {
  393. const float* world_matrix = &xfmem.posMatrices[(MtxIdx & 0x3f) * 4];
  394. // We use the projection matrix calculated by VertexShaderManager, because it
  395. // includes any free look transformations.
  396. // Make sure VertexShaderManager::SetConstants() has been called first.
  397. const float* proj_matrix = &m_projection_matrix[0];
  398. const float t[3] = {data[0] * world_matrix[0] + data[1] * world_matrix[1] +
  399. data[2] * world_matrix[2] + world_matrix[3],
  400. data[0] * world_matrix[4] + data[1] * world_matrix[5] +
  401. data[2] * world_matrix[6] + world_matrix[7],
  402. data[0] * world_matrix[8] + data[1] * world_matrix[9] +
  403. data[2] * world_matrix[10] + world_matrix[11]};
  404. out[0] = t[0] * proj_matrix[0] + t[1] * proj_matrix[1] + t[2] * proj_matrix[2] + proj_matrix[3];
  405. out[1] = t[0] * proj_matrix[4] + t[1] * proj_matrix[5] + t[2] * proj_matrix[6] + proj_matrix[7];
  406. out[2] = t[0] * proj_matrix[8] + t[1] * proj_matrix[9] + t[2] * proj_matrix[10] + proj_matrix[11];
  407. out[3] =
  408. t[0] * proj_matrix[12] + t[1] * proj_matrix[13] + t[2] * proj_matrix[14] + proj_matrix[15];
  409. }
  410. void VertexShaderManager::DoState(PointerWrap& p)
  411. {
  412. p.DoArray(m_projection_matrix);
  413. p.Do(m_viewport_correction);
  414. g_freelook_camera.DoState(p);
  415. p.Do(constants);
  416. if (p.IsReadMode())
  417. {
  418. dirty = true;
  419. }
  420. }