rasterizer.cpp 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114
  1. // Copyright 2014 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <array>
  6. #include <cmath>
  7. #include <tuple>
  8. #include "common/assert.h"
  9. #include "common/bit_field.h"
  10. #include "common/color.h"
  11. #include "common/common_types.h"
  12. #include "common/logging/log.h"
  13. #include "common/math_util.h"
  14. #include "common/microprofile.h"
  15. #include "common/quaternion.h"
  16. #include "common/vector_math.h"
  17. #include "core/hw/gpu.h"
  18. #include "core/memory.h"
  19. #include "video_core/debug_utils/debug_utils.h"
  20. #include "video_core/pica_state.h"
  21. #include "video_core/pica_types.h"
  22. #include "video_core/regs_framebuffer.h"
  23. #include "video_core/regs_rasterizer.h"
  24. #include "video_core/regs_texturing.h"
  25. #include "video_core/shader/shader.h"
  26. #include "video_core/swrasterizer/framebuffer.h"
  27. #include "video_core/swrasterizer/proctex.h"
  28. #include "video_core/swrasterizer/rasterizer.h"
  29. #include "video_core/swrasterizer/texturing.h"
  30. #include "video_core/texture/texture_decode.h"
  31. #include "video_core/utils.h"
  32. namespace Pica {
  33. namespace Rasterizer {
  34. // NOTE: Assuming that rasterizer coordinates are 12.4 fixed-point values
  35. struct Fix12P4 {
  36. Fix12P4() {}
  37. Fix12P4(u16 val) : val(val) {}
  38. static u16 FracMask() {
  39. return 0xF;
  40. }
  41. static u16 IntMask() {
  42. return (u16)~0xF;
  43. }
  44. operator u16() const {
  45. return val;
  46. }
  47. bool operator<(const Fix12P4& oth) const {
  48. return (u16) * this < (u16)oth;
  49. }
  50. private:
  51. u16 val;
  52. };
  53. /**
  54. * Calculate signed area of the triangle spanned by the three argument vertices.
  55. * The sign denotes an orientation.
  56. *
  57. * @todo define orientation concretely.
  58. */
  59. static int SignedArea(const Math::Vec2<Fix12P4>& vtx1, const Math::Vec2<Fix12P4>& vtx2,
  60. const Math::Vec2<Fix12P4>& vtx3) {
  61. const auto vec1 = Math::MakeVec(vtx2 - vtx1, 0);
  62. const auto vec2 = Math::MakeVec(vtx3 - vtx1, 0);
  63. // TODO: There is a very small chance this will overflow for sizeof(int) == 4
  64. return Math::Cross(vec1, vec2).z;
  65. };
  66. /// Convert a 3D vector for cube map coordinates to 2D texture coordinates along with the face name
  67. static std::tuple<float24, float24, PAddr> ConvertCubeCoord(float24 u, float24 v, float24 w,
  68. const TexturingRegs& regs) {
  69. const float abs_u = std::abs(u.ToFloat32());
  70. const float abs_v = std::abs(v.ToFloat32());
  71. const float abs_w = std::abs(w.ToFloat32());
  72. float24 x, y, z;
  73. PAddr addr;
  74. if (abs_u > abs_v && abs_u > abs_w) {
  75. if (u > float24::FromFloat32(0)) {
  76. addr = regs.GetCubePhysicalAddress(TexturingRegs::CubeFace::PositiveX);
  77. y = -v;
  78. } else {
  79. addr = regs.GetCubePhysicalAddress(TexturingRegs::CubeFace::NegativeX);
  80. y = v;
  81. }
  82. x = -w;
  83. z = u;
  84. } else if (abs_v > abs_w) {
  85. if (v > float24::FromFloat32(0)) {
  86. addr = regs.GetCubePhysicalAddress(TexturingRegs::CubeFace::PositiveY);
  87. x = u;
  88. } else {
  89. addr = regs.GetCubePhysicalAddress(TexturingRegs::CubeFace::NegativeY);
  90. x = -u;
  91. }
  92. y = w;
  93. z = v;
  94. } else {
  95. if (w > float24::FromFloat32(0)) {
  96. addr = regs.GetCubePhysicalAddress(TexturingRegs::CubeFace::PositiveZ);
  97. y = -v;
  98. } else {
  99. addr = regs.GetCubePhysicalAddress(TexturingRegs::CubeFace::NegativeZ);
  100. y = v;
  101. }
  102. x = u;
  103. z = w;
  104. }
  105. const float24 half = float24::FromFloat32(0.5f);
  106. return std::make_tuple(x / z * half + half, y / z * half + half, addr);
  107. }
  108. float LookupLightingLut(size_t lut_index, u8 index, float delta) {
  109. ASSERT_MSG(lut_index < g_state.lighting.luts.size(), "Out of range lut");
  110. ASSERT_MSG(index < g_state.lighting.luts[0].size(), "Out of range index");
  111. float lut_value = g_state.lighting.luts[lut_index][index].ToFloat();
  112. float lut_diff = g_state.lighting.luts[lut_index][index].DiffToFloat();
  113. return lut_value + lut_diff * delta;
  114. }
  115. std::tuple<Math::Vec4<u8>, Math::Vec4<u8>> ComputeFragmentsColors(const Math::Quaternion<float>& normquat, const Math::Vec3<float>& view) {
  116. const auto& lighting = g_state.regs.lighting;
  117. if (lighting.disable)
  118. return {{}, {}};
  119. // TODO(Subv): Bump mapping
  120. Math::Vec3<float> surface_normal = {0.0f, 0.0f, 1.0f};
  121. if (lighting.config0.bump_mode != LightingRegs::LightingBumpMode::None) {
  122. LOG_CRITICAL(HW_GPU, "unimplemented bump mapping");
  123. UNIMPLEMENTED();
  124. }
  125. // Use the normalized the quaternion when performing the rotation
  126. auto normal = Math::QuaternionRotate(normquat.Normalized(), surface_normal);
  127. Math::Vec3<float> light_vector = {};
  128. Math::Vec4<float> diffuse_sum = {0.f, 0.f, 0.f, 1.f};
  129. Math::Vec4<float> specular_sum = {0.f, 0.f, 0.f, 1.f};
  130. Math::Vec3<float> refl_value = {};
  131. for (unsigned light_index = 0; light_index <= lighting.max_light_index; ++light_index) {
  132. unsigned num = lighting.light_enable.GetNum(light_index);
  133. const auto& light_config = g_state.regs.lighting.light[num];
  134. Math::Vec3<float> position = {float16::FromRaw(light_config.x).ToFloat32(), float16::FromRaw(light_config.y).ToFloat32(), float16::FromRaw(light_config.z).ToFloat32()};
  135. if (light_config.config.directional)
  136. light_vector = position;
  137. else
  138. light_vector = position + view;
  139. light_vector.Normalize();
  140. auto LV_N = Math::Dot(light_vector, normal);
  141. auto dot_product = LV_N;
  142. if (light_config.config.two_sided_diffuse)
  143. dot_product = std::abs(dot_product);
  144. else
  145. dot_product = std::max(dot_product, 0.0f);
  146. float dist_atten = 1.0f;
  147. if (!lighting.IsDistAttenDisabled(num)) {
  148. auto distance = (-view - position).Length();
  149. float scale = Pica::float20::FromRaw(light_config.dist_atten_scale).ToFloat32();
  150. float bias = Pica::float20::FromRaw(light_config.dist_atten_scale).ToFloat32();
  151. size_t lut = static_cast<size_t>(LightingRegs::LightingSampler::DistanceAttenuation) + num;
  152. float sample_loc = scale * distance + bias;
  153. u8 lutindex = MathUtil::Clamp(floorf(sample_loc * 256.f), 0.0f, 255.0f);
  154. float delta = sample_loc * 256 - lutindex;
  155. dist_atten = LookupLightingLut(lut, lutindex, delta / 256.f);
  156. }
  157. float clamp_highlights = 1.0f;
  158. if (lighting.config0.clamp_highlights) {
  159. if (LV_N <= 0.f)
  160. clamp_highlights = 0.f;
  161. else
  162. clamp_highlights = 1.f;
  163. }
  164. auto GetLutIndex = [&](unsigned num, LightingRegs::LightingLutInput input,
  165. bool abs) -> std::tuple<u8, float> {
  166. Math::Vec3<float> norm_view = view.Normalized();
  167. Math::Vec3<float> half_angle = (norm_view + light_vector).Normalized();
  168. float result = 0.0f;
  169. switch (input) {
  170. case LightingRegs::LightingLutInput::NH:
  171. result = Math::Dot(normal, half_angle);
  172. break;
  173. case LightingRegs::LightingLutInput::VH:
  174. result = Math::Dot(norm_view, half_angle);
  175. break;
  176. case LightingRegs::LightingLutInput::NV:
  177. result = Math::Dot(normal, norm_view);
  178. break;
  179. case LightingRegs::LightingLutInput::LN:
  180. result = Math::Dot(light_vector, normal);
  181. break;
  182. default:
  183. LOG_CRITICAL(HW_GPU, "Unknown lighting LUT input %d\n", (int)input);
  184. UNIMPLEMENTED();
  185. result = 0.f;
  186. }
  187. if (abs) {
  188. if (light_config.config.two_sided_diffuse)
  189. result = std::abs(result);
  190. else
  191. result = std::max(result, 0.0f);
  192. u8 lutindex = MathUtil::Clamp(floorf(result * 256.f), 0.0f, 255.0f);
  193. float delta = result * 256 - lutindex;
  194. return { lutindex, delta / 256.f };
  195. } else {
  196. u8 tmpi = MathUtil::Clamp(floorf(result * 128.f), 0.0f, 127.0f);
  197. float delta = result * 128.f - tmpi;
  198. return { tmpi & 0xFF, delta / 128.f };
  199. }
  200. };
  201. // Specular 0 component
  202. float d0_lut_value = 1.0f;
  203. if (lighting.config1.disable_lut_d0 == 0 &&
  204. LightingRegs::IsLightingSamplerSupported(
  205. lighting.config0.config, LightingRegs::LightingSampler::Distribution0)) {
  206. // Lookup specular "distribution 0" LUT value
  207. u8 index;
  208. float delta;
  209. std::tie(index, delta) = GetLutIndex(num, lighting.lut_input.d0.Value(), lighting.abs_lut_input.disable_d0 == 0);
  210. float scale = lighting.lut_scale.GetScale(lighting.lut_scale.d0);
  211. d0_lut_value = scale * LookupLightingLut(static_cast<size_t>(LightingRegs::LightingSampler::Distribution0), index, delta);
  212. }
  213. Math::Vec3<float> specular_0 = d0_lut_value * light_config.specular_0.ToVec3f();
  214. // If enabled, lookup ReflectRed value, otherwise, 1.0 is used
  215. if (lighting.config1.disable_lut_rr == 0 &&
  216. LightingRegs::IsLightingSamplerSupported(lighting.config0.config,
  217. LightingRegs::LightingSampler::ReflectRed)) {
  218. u8 index;
  219. float delta;
  220. std::tie(index, delta) = GetLutIndex(num, lighting.lut_input.rr, lighting.abs_lut_input.disable_rr == 0);
  221. float scale = lighting.lut_scale.GetScale(lighting.lut_scale.rr);
  222. refl_value.x = scale * LookupLightingLut(static_cast<size_t>(LightingRegs::LightingSampler::ReflectRed), index, delta);
  223. } else {
  224. refl_value.x = 1.0f;
  225. }
  226. // If enabled, lookup ReflectGreen value, otherwise, ReflectRed value is used
  227. if (lighting.config1.disable_lut_rg == 0 &&
  228. LightingRegs::IsLightingSamplerSupported(lighting.config0.config,
  229. LightingRegs::LightingSampler::ReflectGreen)) {
  230. u8 index;
  231. float delta;
  232. std::tie(index, delta) = GetLutIndex(num, lighting.lut_input.rg, lighting.abs_lut_input.disable_rg == 0);
  233. float scale = lighting.lut_scale.GetScale(lighting.lut_scale.rg);
  234. refl_value.y = scale * LookupLightingLut(static_cast<size_t>(LightingRegs::LightingSampler::ReflectGreen), index, delta);
  235. } else {
  236. refl_value.y = refl_value.x;
  237. }
  238. // If enabled, lookup ReflectBlue value, otherwise, ReflectRed value is used
  239. if (lighting.config1.disable_lut_rb == 0 &&
  240. LightingRegs::IsLightingSamplerSupported(lighting.config0.config,
  241. LightingRegs::LightingSampler::ReflectBlue)) {
  242. u8 index;
  243. float delta;
  244. std::tie(index, delta) = GetLutIndex(num, lighting.lut_input.rb, lighting.abs_lut_input.disable_rb == 0);
  245. float scale = lighting.lut_scale.GetScale(lighting.lut_scale.rb);
  246. refl_value.z = scale * LookupLightingLut(static_cast<size_t>(LightingRegs::LightingSampler::ReflectBlue), index, delta);
  247. } else {
  248. refl_value.z = refl_value.x;
  249. }
  250. float d1_lut_value = 1.0f;
  251. if (lighting.config1.disable_lut_d1 == 0 &&
  252. LightingRegs::IsLightingSamplerSupported(
  253. lighting.config0.config, LightingRegs::LightingSampler::Distribution1)) {
  254. // Lookup specular "distribution 1" LUT value
  255. u8 index;
  256. float delta;
  257. std::tie(index, delta) = GetLutIndex(num, lighting.lut_input.d1.Value(), lighting.abs_lut_input.disable_d1 == 0);
  258. float scale = lighting.lut_scale.GetScale(lighting.lut_scale.d1);
  259. d1_lut_value = scale * LookupLightingLut(static_cast<size_t>(LightingRegs::LightingSampler::Distribution1), index, delta);
  260. }
  261. Math::Vec3<float> specular_1 = d1_lut_value * refl_value * light_config.specular_1.ToVec3f();
  262. if (lighting.config1.disable_lut_fr == 0 &&
  263. LightingRegs::IsLightingSamplerSupported(
  264. lighting.config0.config, LightingRegs::LightingSampler::Fresnel)) {
  265. // Lookup fresnel LUT value
  266. u8 index;
  267. float delta;
  268. std::tie(index, delta) = GetLutIndex(num, lighting.lut_input.fr.Value(), lighting.abs_lut_input.disable_fr == 0);
  269. float scale = lighting.lut_scale.GetScale(lighting.lut_scale.fr);
  270. float lut_value = scale * LookupLightingLut(static_cast<size_t>(LightingRegs::LightingSampler::Fresnel), index, delta);
  271. // Enabled for difffuse lighting alpha component
  272. if (lighting.config0.fresnel_selector == LightingRegs::LightingFresnelSelector::PrimaryAlpha ||
  273. lighting.config0.fresnel_selector == LightingRegs::LightingFresnelSelector::Both) {
  274. diffuse_sum.a() *= lut_value;
  275. }
  276. // Enabled for the specular lighting alpha component
  277. if (lighting.config0.fresnel_selector ==
  278. LightingRegs::LightingFresnelSelector::SecondaryAlpha ||
  279. lighting.config0.fresnel_selector == LightingRegs::LightingFresnelSelector::Both) {
  280. specular_sum.a() *= lut_value;
  281. }
  282. }
  283. auto diffuse = light_config.diffuse.ToVec3f() * dot_product + light_config.ambient.ToVec3f();
  284. diffuse_sum += Math::MakeVec(diffuse * dist_atten, 0.0f);
  285. specular_sum += Math::MakeVec((specular_0 + specular_1) * clamp_highlights * dist_atten, 0.f);
  286. }
  287. diffuse_sum += Math::MakeVec(lighting.global_ambient.ToVec3f(), 0.0f);
  288. return {
  289. Math::MakeVec<float>(MathUtil::Clamp(diffuse_sum.x, 0.0f, 1.0f) * 255, MathUtil::Clamp(diffuse_sum.y, 0.0f, 1.0f) * 255, MathUtil::Clamp(diffuse_sum.z, 0.0f, 1.0f) * 255, MathUtil::Clamp(diffuse_sum.w, 0.0f, 1.0f) * 255).Cast<u8>(),
  290. Math::MakeVec<float>(MathUtil::Clamp(specular_sum.x, 0.0f, 1.0f) * 255, MathUtil::Clamp(specular_sum.y, 0.0f, 1.0f) * 255, MathUtil::Clamp(specular_sum.z, 0.0f, 1.0f) * 255, MathUtil::Clamp(specular_sum.w, 0.0f, 1.0f) * 255).Cast<u8>()
  291. };
  292. }
  293. static bool AreQuaternionsOpposite(Math::Vec4<Pica::float24> qa, Math::Vec4<Pica::float24> qb) {
  294. Math::Vec4f a{ qa.x.ToFloat32(), qa.y.ToFloat32(), qa.z.ToFloat32(), qa.w.ToFloat32() };
  295. Math::Vec4f b{ qb.x.ToFloat32(), qb.y.ToFloat32(), qb.z.ToFloat32(), qb.w.ToFloat32() };
  296. return (Math::Dot(a, b) < 0.f);
  297. }
  298. MICROPROFILE_DEFINE(GPU_Rasterization, "GPU", "Rasterization", MP_RGB(50, 50, 240));
  299. /**
  300. * Helper function for ProcessTriangle with the "reversed" flag to allow for implementing
  301. * culling via recursion.
  302. */
  303. static void ProcessTriangleInternal(const Vertex& v0, const Vertex& v1, const Vertex& v2,
  304. bool reversed = false) {
  305. const auto& regs = g_state.regs;
  306. MICROPROFILE_SCOPE(GPU_Rasterization);
  307. // vertex positions in rasterizer coordinates
  308. static auto FloatToFix = [](float24 flt) {
  309. // TODO: Rounding here is necessary to prevent garbage pixels at
  310. // triangle borders. Is it that the correct solution, though?
  311. return Fix12P4(static_cast<unsigned short>(round(flt.ToFloat32() * 16.0f)));
  312. };
  313. static auto ScreenToRasterizerCoordinates = [](const Math::Vec3<float24>& vec) {
  314. return Math::Vec3<Fix12P4>{FloatToFix(vec.x), FloatToFix(vec.y), FloatToFix(vec.z)};
  315. };
  316. Math::Vec3<Fix12P4> vtxpos[3]{ScreenToRasterizerCoordinates(v0.screenpos),
  317. ScreenToRasterizerCoordinates(v1.screenpos),
  318. ScreenToRasterizerCoordinates(v2.screenpos)};
  319. if (regs.rasterizer.cull_mode == RasterizerRegs::CullMode::KeepAll) {
  320. // Make sure we always end up with a triangle wound counter-clockwise
  321. if (!reversed && SignedArea(vtxpos[0].xy(), vtxpos[1].xy(), vtxpos[2].xy()) <= 0) {
  322. ProcessTriangleInternal(v0, v2, v1, true);
  323. return;
  324. }
  325. } else {
  326. if (!reversed && regs.rasterizer.cull_mode == RasterizerRegs::CullMode::KeepClockWise) {
  327. // Reverse vertex order and use the CCW code path.
  328. ProcessTriangleInternal(v0, v2, v1, true);
  329. return;
  330. }
  331. // Cull away triangles which are wound clockwise.
  332. if (SignedArea(vtxpos[0].xy(), vtxpos[1].xy(), vtxpos[2].xy()) <= 0)
  333. return;
  334. }
  335. u16 min_x = std::min({vtxpos[0].x, vtxpos[1].x, vtxpos[2].x});
  336. u16 min_y = std::min({vtxpos[0].y, vtxpos[1].y, vtxpos[2].y});
  337. u16 max_x = std::max({vtxpos[0].x, vtxpos[1].x, vtxpos[2].x});
  338. u16 max_y = std::max({vtxpos[0].y, vtxpos[1].y, vtxpos[2].y});
  339. // Convert the scissor box coordinates to 12.4 fixed point
  340. u16 scissor_x1 = (u16)(regs.rasterizer.scissor_test.x1 << 4);
  341. u16 scissor_y1 = (u16)(regs.rasterizer.scissor_test.y1 << 4);
  342. // x2,y2 have +1 added to cover the entire sub-pixel area
  343. u16 scissor_x2 = (u16)((regs.rasterizer.scissor_test.x2 + 1) << 4);
  344. u16 scissor_y2 = (u16)((regs.rasterizer.scissor_test.y2 + 1) << 4);
  345. if (regs.rasterizer.scissor_test.mode == RasterizerRegs::ScissorMode::Include) {
  346. // Calculate the new bounds
  347. min_x = std::max(min_x, scissor_x1);
  348. min_y = std::max(min_y, scissor_y1);
  349. max_x = std::min(max_x, scissor_x2);
  350. max_y = std::min(max_y, scissor_y2);
  351. }
  352. min_x &= Fix12P4::IntMask();
  353. min_y &= Fix12P4::IntMask();
  354. max_x = ((max_x + Fix12P4::FracMask()) & Fix12P4::IntMask());
  355. max_y = ((max_y + Fix12P4::FracMask()) & Fix12P4::IntMask());
  356. // Triangle filling rules: Pixels on the right-sided edge or on flat bottom edges are not
  357. // drawn. Pixels on any other triangle border are drawn. This is implemented with three bias
  358. // values which are added to the barycentric coordinates w0, w1 and w2, respectively.
  359. // NOTE: These are the PSP filling rules. Not sure if the 3DS uses the same ones...
  360. auto IsRightSideOrFlatBottomEdge = [](const Math::Vec2<Fix12P4>& vtx,
  361. const Math::Vec2<Fix12P4>& line1,
  362. const Math::Vec2<Fix12P4>& line2) {
  363. if (line1.y == line2.y) {
  364. // just check if vertex is above us => bottom line parallel to x-axis
  365. return vtx.y < line1.y;
  366. } else {
  367. // check if vertex is on our left => right side
  368. // TODO: Not sure how likely this is to overflow
  369. return (int)vtx.x < (int)line1.x +
  370. ((int)line2.x - (int)line1.x) * ((int)vtx.y - (int)line1.y) /
  371. ((int)line2.y - (int)line1.y);
  372. }
  373. };
  374. int bias0 =
  375. IsRightSideOrFlatBottomEdge(vtxpos[0].xy(), vtxpos[1].xy(), vtxpos[2].xy()) ? -1 : 0;
  376. int bias1 =
  377. IsRightSideOrFlatBottomEdge(vtxpos[1].xy(), vtxpos[2].xy(), vtxpos[0].xy()) ? -1 : 0;
  378. int bias2 =
  379. IsRightSideOrFlatBottomEdge(vtxpos[2].xy(), vtxpos[0].xy(), vtxpos[1].xy()) ? -1 : 0;
  380. // Flip the quaternions if they are opposite to prevent interpolating them over the wrong direction.
  381. auto v1_quat = v1.quat;
  382. auto v2_quat = v2.quat;
  383. if (AreQuaternionsOpposite(v0.quat, v1.quat))
  384. v1_quat = v1_quat * float24::FromFloat32(-1.0f);
  385. if (AreQuaternionsOpposite(v0.quat, v2.quat))
  386. v2_quat = v2_quat * float24::FromFloat32(-1.0f);
  387. auto w_inverse = Math::MakeVec(v0.pos.w, v1.pos.w, v2.pos.w);
  388. auto textures = regs.texturing.GetTextures();
  389. auto tev_stages = regs.texturing.GetTevStages();
  390. bool stencil_action_enable =
  391. g_state.regs.framebuffer.output_merger.stencil_test.enable &&
  392. g_state.regs.framebuffer.framebuffer.depth_format == FramebufferRegs::DepthFormat::D24S8;
  393. const auto stencil_test = g_state.regs.framebuffer.output_merger.stencil_test;
  394. // Enter rasterization loop, starting at the center of the topleft bounding box corner.
  395. // TODO: Not sure if looping through x first might be faster
  396. for (u16 y = min_y + 8; y < max_y; y += 0x10) {
  397. for (u16 x = min_x + 8; x < max_x; x += 0x10) {
  398. // Do not process the pixel if it's inside the scissor box and the scissor mode is set
  399. // to Exclude
  400. if (regs.rasterizer.scissor_test.mode == RasterizerRegs::ScissorMode::Exclude) {
  401. if (x >= scissor_x1 && x < scissor_x2 && y >= scissor_y1 && y < scissor_y2)
  402. continue;
  403. }
  404. // Calculate the barycentric coordinates w0, w1 and w2
  405. int w0 = bias0 + SignedArea(vtxpos[1].xy(), vtxpos[2].xy(), {x, y});
  406. int w1 = bias1 + SignedArea(vtxpos[2].xy(), vtxpos[0].xy(), {x, y});
  407. int w2 = bias2 + SignedArea(vtxpos[0].xy(), vtxpos[1].xy(), {x, y});
  408. int wsum = w0 + w1 + w2;
  409. // If current pixel is not covered by the current primitive
  410. if (w0 < 0 || w1 < 0 || w2 < 0)
  411. continue;
  412. auto baricentric_coordinates =
  413. Math::MakeVec(float24::FromFloat32(static_cast<float>(w0)),
  414. float24::FromFloat32(static_cast<float>(w1)),
  415. float24::FromFloat32(static_cast<float>(w2)));
  416. float24 interpolated_w_inverse =
  417. float24::FromFloat32(1.0f) / Math::Dot(w_inverse, baricentric_coordinates);
  418. // interpolated_z = z / w
  419. float interpolated_z_over_w =
  420. (v0.screenpos[2].ToFloat32() * w0 + v1.screenpos[2].ToFloat32() * w1 +
  421. v2.screenpos[2].ToFloat32() * w2) /
  422. wsum;
  423. // Not fully accurate. About 3 bits in precision are missing.
  424. // Z-Buffer (z / w * scale + offset)
  425. float depth_scale = float24::FromRaw(regs.rasterizer.viewport_depth_range).ToFloat32();
  426. float depth_offset =
  427. float24::FromRaw(regs.rasterizer.viewport_depth_near_plane).ToFloat32();
  428. float depth = interpolated_z_over_w * depth_scale + depth_offset;
  429. // Potentially switch to W-Buffer
  430. if (regs.rasterizer.depthmap_enable ==
  431. Pica::RasterizerRegs::DepthBuffering::WBuffering) {
  432. // W-Buffer (z * scale + w * offset = (z / w * scale + offset) * w)
  433. depth *= interpolated_w_inverse.ToFloat32() * wsum;
  434. }
  435. // Clamp the result
  436. depth = MathUtil::Clamp(depth, 0.0f, 1.0f);
  437. // Perspective correct attribute interpolation:
  438. // Attribute values cannot be calculated by simple linear interpolation since
  439. // they are not linear in screen space. For example, when interpolating a
  440. // texture coordinate across two vertices, something simple like
  441. // u = (u0*w0 + u1*w1)/(w0+w1)
  442. // will not work. However, the attribute value divided by the
  443. // clipspace w-coordinate (u/w) and and the inverse w-coordinate (1/w) are linear
  444. // in screenspace. Hence, we can linearly interpolate these two independently and
  445. // calculate the interpolated attribute by dividing the results.
  446. // I.e.
  447. // u_over_w = ((u0/v0.pos.w)*w0 + (u1/v1.pos.w)*w1)/(w0+w1)
  448. // one_over_w = (( 1/v0.pos.w)*w0 + ( 1/v1.pos.w)*w1)/(w0+w1)
  449. // u = u_over_w / one_over_w
  450. //
  451. // The generalization to three vertices is straightforward in baricentric coordinates.
  452. auto GetInterpolatedAttribute = [&](float24 attr0, float24 attr1, float24 attr2) {
  453. auto attr_over_w = Math::MakeVec(attr0, attr1, attr2);
  454. float24 interpolated_attr_over_w = Math::Dot(attr_over_w, baricentric_coordinates);
  455. return interpolated_attr_over_w * interpolated_w_inverse;
  456. };
  457. Math::Vec4<u8> primary_color{
  458. (u8)(
  459. GetInterpolatedAttribute(v0.color.r(), v1.color.r(), v2.color.r()).ToFloat32() *
  460. 255),
  461. (u8)(
  462. GetInterpolatedAttribute(v0.color.g(), v1.color.g(), v2.color.g()).ToFloat32() *
  463. 255),
  464. (u8)(
  465. GetInterpolatedAttribute(v0.color.b(), v1.color.b(), v2.color.b()).ToFloat32() *
  466. 255),
  467. (u8)(
  468. GetInterpolatedAttribute(v0.color.a(), v1.color.a(), v2.color.a()).ToFloat32() *
  469. 255),
  470. };
  471. Math::Quaternion<float> normquat{
  472. {
  473. GetInterpolatedAttribute(v0.quat.x, v1_quat.x, v2_quat.x).ToFloat32(),
  474. GetInterpolatedAttribute(v0.quat.y, v1_quat.y, v2_quat.y).ToFloat32(),
  475. GetInterpolatedAttribute(v0.quat.z, v1_quat.z, v2_quat.z).ToFloat32()
  476. },
  477. GetInterpolatedAttribute(v0.quat.w, v1_quat.w, v2_quat.w).ToFloat32(),
  478. };
  479. Math::Vec3<float> fragment_position{
  480. GetInterpolatedAttribute(v0.view.x, v1.view.x, v2.view.x).ToFloat32(),
  481. GetInterpolatedAttribute(v0.view.y, v1.view.y, v2.view.y).ToFloat32(),
  482. GetInterpolatedAttribute(v0.view.z, v1.view.z, v2.view.z).ToFloat32()
  483. };
  484. Math::Vec2<float24> uv[3];
  485. uv[0].u() = GetInterpolatedAttribute(v0.tc0.u(), v1.tc0.u(), v2.tc0.u());
  486. uv[0].v() = GetInterpolatedAttribute(v0.tc0.v(), v1.tc0.v(), v2.tc0.v());
  487. uv[1].u() = GetInterpolatedAttribute(v0.tc1.u(), v1.tc1.u(), v2.tc1.u());
  488. uv[1].v() = GetInterpolatedAttribute(v0.tc1.v(), v1.tc1.v(), v2.tc1.v());
  489. uv[2].u() = GetInterpolatedAttribute(v0.tc2.u(), v1.tc2.u(), v2.tc2.u());
  490. uv[2].v() = GetInterpolatedAttribute(v0.tc2.v(), v1.tc2.v(), v2.tc2.v());
  491. Math::Vec4<u8> texture_color[4]{};
  492. for (int i = 0; i < 3; ++i) {
  493. const auto& texture = textures[i];
  494. if (!texture.enabled)
  495. continue;
  496. DEBUG_ASSERT(0 != texture.config.address);
  497. int coordinate_i =
  498. (i == 2 && regs.texturing.main_config.texture2_use_coord1) ? 1 : i;
  499. float24 u = uv[coordinate_i].u();
  500. float24 v = uv[coordinate_i].v();
  501. // Only unit 0 respects the texturing type (according to 3DBrew)
  502. // TODO: Refactor so cubemaps and shadowmaps can be handled
  503. PAddr texture_address = texture.config.GetPhysicalAddress();
  504. if (i == 0) {
  505. switch (texture.config.type) {
  506. case TexturingRegs::TextureConfig::Texture2D:
  507. break;
  508. case TexturingRegs::TextureConfig::TextureCube: {
  509. auto w = GetInterpolatedAttribute(v0.tc0_w, v1.tc0_w, v2.tc0_w);
  510. std::tie(u, v, texture_address) = ConvertCubeCoord(u, v, w, regs.texturing);
  511. break;
  512. }
  513. case TexturingRegs::TextureConfig::Projection2D: {
  514. auto tc0_w = GetInterpolatedAttribute(v0.tc0_w, v1.tc0_w, v2.tc0_w);
  515. u /= tc0_w;
  516. v /= tc0_w;
  517. break;
  518. }
  519. default:
  520. // TODO: Change to LOG_ERROR when more types are handled.
  521. LOG_DEBUG(HW_GPU, "Unhandled texture type %x", (int)texture.config.type);
  522. UNIMPLEMENTED();
  523. break;
  524. }
  525. }
  526. int s = (int)(u * float24::FromFloat32(static_cast<float>(texture.config.width)))
  527. .ToFloat32();
  528. int t = (int)(v * float24::FromFloat32(static_cast<float>(texture.config.height)))
  529. .ToFloat32();
  530. bool use_border_s = false;
  531. bool use_border_t = false;
  532. if (texture.config.wrap_s == TexturingRegs::TextureConfig::ClampToBorder) {
  533. use_border_s = s < 0 || s >= static_cast<int>(texture.config.width);
  534. } else if (texture.config.wrap_s == TexturingRegs::TextureConfig::ClampToBorder2) {
  535. use_border_s = s >= static_cast<int>(texture.config.width);
  536. }
  537. if (texture.config.wrap_t == TexturingRegs::TextureConfig::ClampToBorder) {
  538. use_border_t = t < 0 || t >= static_cast<int>(texture.config.height);
  539. } else if (texture.config.wrap_t == TexturingRegs::TextureConfig::ClampToBorder2) {
  540. use_border_t = t >= static_cast<int>(texture.config.height);
  541. }
  542. if (use_border_s || use_border_t) {
  543. auto border_color = texture.config.border_color;
  544. texture_color[i] = {border_color.r, border_color.g, border_color.b,
  545. border_color.a};
  546. } else {
  547. // Textures are laid out from bottom to top, hence we invert the t coordinate.
  548. // NOTE: This may not be the right place for the inversion.
  549. // TODO: Check if this applies to ETC textures, too.
  550. s = GetWrappedTexCoord(texture.config.wrap_s, s, texture.config.width);
  551. t = texture.config.height - 1 -
  552. GetWrappedTexCoord(texture.config.wrap_t, t, texture.config.height);
  553. const u8* texture_data = Memory::GetPhysicalPointer(texture_address);
  554. auto info =
  555. Texture::TextureInfo::FromPicaRegister(texture.config, texture.format);
  556. // TODO: Apply the min and mag filters to the texture
  557. texture_color[i] = Texture::LookupTexture(texture_data, s, t, info);
  558. #if PICA_DUMP_TEXTURES
  559. DebugUtils::DumpTexture(texture.config, texture_data);
  560. #endif
  561. }
  562. }
  563. // sample procedural texture
  564. if (regs.texturing.main_config.texture3_enable) {
  565. const auto& proctex_uv = uv[regs.texturing.main_config.texture3_coordinates];
  566. texture_color[3] = ProcTex(proctex_uv.u().ToFloat32(), proctex_uv.v().ToFloat32(),
  567. g_state.regs.texturing, g_state.proctex);
  568. }
  569. // Texture environment - consists of 6 stages of color and alpha combining.
  570. //
  571. // Color combiners take three input color values from some source (e.g. interpolated
  572. // vertex color, texture color, previous stage, etc), perform some very simple
  573. // operations on each of them (e.g. inversion) and then calculate the output color
  574. // with some basic arithmetic. Alpha combiners can be configured separately but work
  575. // analogously.
  576. Math::Vec4<u8> combiner_output;
  577. Math::Vec4<u8> combiner_buffer = {0, 0, 0, 0};
  578. Math::Vec4<u8> next_combiner_buffer = {
  579. regs.texturing.tev_combiner_buffer_color.r,
  580. regs.texturing.tev_combiner_buffer_color.g,
  581. regs.texturing.tev_combiner_buffer_color.b,
  582. regs.texturing.tev_combiner_buffer_color.a,
  583. };
  584. Math::Vec4<u8> primary_fragment_color;
  585. Math::Vec4<u8> secondary_fragment_color;
  586. std::tie(primary_fragment_color, secondary_fragment_color) = ComputeFragmentsColors(normquat, fragment_position);
  587. for (unsigned tev_stage_index = 0; tev_stage_index < tev_stages.size();
  588. ++tev_stage_index) {
  589. const auto& tev_stage = tev_stages[tev_stage_index];
  590. using Source = TexturingRegs::TevStageConfig::Source;
  591. auto GetSource = [&](Source source) -> Math::Vec4<u8> {
  592. switch (source) {
  593. case Source::PrimaryColor:
  594. return primary_color;
  595. case Source::PrimaryFragmentColor:
  596. return primary_fragment_color;
  597. case Source::SecondaryFragmentColor:
  598. return secondary_fragment_color;
  599. case Source::Texture0:
  600. return texture_color[0];
  601. case Source::Texture1:
  602. return texture_color[1];
  603. case Source::Texture2:
  604. return texture_color[2];
  605. case Source::Texture3:
  606. return texture_color[3];
  607. case Source::PreviousBuffer:
  608. return combiner_buffer;
  609. case Source::Constant:
  610. return {tev_stage.const_r, tev_stage.const_g, tev_stage.const_b,
  611. tev_stage.const_a};
  612. case Source::Previous:
  613. return combiner_output;
  614. default:
  615. LOG_ERROR(HW_GPU, "Unknown color combiner source %d", (int)source);
  616. UNIMPLEMENTED();
  617. return {0, 0, 0, 0};
  618. }
  619. };
  620. // color combiner
  621. // NOTE: Not sure if the alpha combiner might use the color output of the previous
  622. // stage as input. Hence, we currently don't directly write the result to
  623. // combiner_output.rgb(), but instead store it in a temporary variable until
  624. // alpha combining has been done.
  625. Math::Vec3<u8> color_result[3] = {
  626. GetColorModifier(tev_stage.color_modifier1, GetSource(tev_stage.color_source1)),
  627. GetColorModifier(tev_stage.color_modifier2, GetSource(tev_stage.color_source2)),
  628. GetColorModifier(tev_stage.color_modifier3, GetSource(tev_stage.color_source3)),
  629. };
  630. auto color_output = ColorCombine(tev_stage.color_op, color_result);
  631. u8 alpha_output;
  632. if (tev_stage.color_op == TexturingRegs::TevStageConfig::Operation::Dot3_RGBA) {
  633. // result of Dot3_RGBA operation is also placed to the alpha component
  634. alpha_output = color_output.x;
  635. } else {
  636. // alpha combiner
  637. std::array<u8, 3> alpha_result = {{
  638. GetAlphaModifier(tev_stage.alpha_modifier1,
  639. GetSource(tev_stage.alpha_source1)),
  640. GetAlphaModifier(tev_stage.alpha_modifier2,
  641. GetSource(tev_stage.alpha_source2)),
  642. GetAlphaModifier(tev_stage.alpha_modifier3,
  643. GetSource(tev_stage.alpha_source3)),
  644. }};
  645. alpha_output = AlphaCombine(tev_stage.alpha_op, alpha_result);
  646. }
  647. combiner_output[0] =
  648. std::min((unsigned)255, color_output.r() * tev_stage.GetColorMultiplier());
  649. combiner_output[1] =
  650. std::min((unsigned)255, color_output.g() * tev_stage.GetColorMultiplier());
  651. combiner_output[2] =
  652. std::min((unsigned)255, color_output.b() * tev_stage.GetColorMultiplier());
  653. combiner_output[3] =
  654. std::min((unsigned)255, alpha_output * tev_stage.GetAlphaMultiplier());
  655. combiner_buffer = next_combiner_buffer;
  656. if (regs.texturing.tev_combiner_buffer_input.TevStageUpdatesCombinerBufferColor(
  657. tev_stage_index)) {
  658. next_combiner_buffer.r() = combiner_output.r();
  659. next_combiner_buffer.g() = combiner_output.g();
  660. next_combiner_buffer.b() = combiner_output.b();
  661. }
  662. if (regs.texturing.tev_combiner_buffer_input.TevStageUpdatesCombinerBufferAlpha(
  663. tev_stage_index)) {
  664. next_combiner_buffer.a() = combiner_output.a();
  665. }
  666. }
  667. const auto& output_merger = regs.framebuffer.output_merger;
  668. // TODO: Does alpha testing happen before or after stencil?
  669. if (output_merger.alpha_test.enable) {
  670. bool pass = false;
  671. switch (output_merger.alpha_test.func) {
  672. case FramebufferRegs::CompareFunc::Never:
  673. pass = false;
  674. break;
  675. case FramebufferRegs::CompareFunc::Always:
  676. pass = true;
  677. break;
  678. case FramebufferRegs::CompareFunc::Equal:
  679. pass = combiner_output.a() == output_merger.alpha_test.ref;
  680. break;
  681. case FramebufferRegs::CompareFunc::NotEqual:
  682. pass = combiner_output.a() != output_merger.alpha_test.ref;
  683. break;
  684. case FramebufferRegs::CompareFunc::LessThan:
  685. pass = combiner_output.a() < output_merger.alpha_test.ref;
  686. break;
  687. case FramebufferRegs::CompareFunc::LessThanOrEqual:
  688. pass = combiner_output.a() <= output_merger.alpha_test.ref;
  689. break;
  690. case FramebufferRegs::CompareFunc::GreaterThan:
  691. pass = combiner_output.a() > output_merger.alpha_test.ref;
  692. break;
  693. case FramebufferRegs::CompareFunc::GreaterThanOrEqual:
  694. pass = combiner_output.a() >= output_merger.alpha_test.ref;
  695. break;
  696. }
  697. if (!pass)
  698. continue;
  699. }
  700. // Apply fog combiner
  701. // Not fully accurate. We'd have to know what data type is used to
  702. // store the depth etc. Using float for now until we know more
  703. // about Pica datatypes
  704. if (regs.texturing.fog_mode == TexturingRegs::FogMode::Fog) {
  705. const Math::Vec3<u8> fog_color = {
  706. static_cast<u8>(regs.texturing.fog_color.r.Value()),
  707. static_cast<u8>(regs.texturing.fog_color.g.Value()),
  708. static_cast<u8>(regs.texturing.fog_color.b.Value()),
  709. };
  710. // Get index into fog LUT
  711. float fog_index;
  712. if (g_state.regs.texturing.fog_flip) {
  713. fog_index = (1.0f - depth) * 128.0f;
  714. } else {
  715. fog_index = depth * 128.0f;
  716. }
  717. // Generate clamped fog factor from LUT for given fog index
  718. float fog_i = MathUtil::Clamp(floorf(fog_index), 0.0f, 127.0f);
  719. float fog_f = fog_index - fog_i;
  720. const auto& fog_lut_entry = g_state.fog.lut[static_cast<unsigned int>(fog_i)];
  721. float fog_factor = fog_lut_entry.ToFloat() + fog_lut_entry.DiffToFloat() * fog_f;
  722. fog_factor = MathUtil::Clamp(fog_factor, 0.0f, 1.0f);
  723. // Blend the fog
  724. for (unsigned i = 0; i < 3; i++) {
  725. combiner_output[i] = static_cast<u8>(fog_factor * combiner_output[i] +
  726. (1.0f - fog_factor) * fog_color[i]);
  727. }
  728. }
  729. u8 old_stencil = 0;
  730. auto UpdateStencil = [stencil_test, x, y,
  731. &old_stencil](Pica::FramebufferRegs::StencilAction action) {
  732. u8 new_stencil =
  733. PerformStencilAction(action, old_stencil, stencil_test.reference_value);
  734. if (g_state.regs.framebuffer.framebuffer.allow_depth_stencil_write != 0)
  735. SetStencil(x >> 4, y >> 4, (new_stencil & stencil_test.write_mask) |
  736. (old_stencil & ~stencil_test.write_mask));
  737. };
  738. if (stencil_action_enable) {
  739. old_stencil = GetStencil(x >> 4, y >> 4);
  740. u8 dest = old_stencil & stencil_test.input_mask;
  741. u8 ref = stencil_test.reference_value & stencil_test.input_mask;
  742. bool pass = false;
  743. switch (stencil_test.func) {
  744. case FramebufferRegs::CompareFunc::Never:
  745. pass = false;
  746. break;
  747. case FramebufferRegs::CompareFunc::Always:
  748. pass = true;
  749. break;
  750. case FramebufferRegs::CompareFunc::Equal:
  751. pass = (ref == dest);
  752. break;
  753. case FramebufferRegs::CompareFunc::NotEqual:
  754. pass = (ref != dest);
  755. break;
  756. case FramebufferRegs::CompareFunc::LessThan:
  757. pass = (ref < dest);
  758. break;
  759. case FramebufferRegs::CompareFunc::LessThanOrEqual:
  760. pass = (ref <= dest);
  761. break;
  762. case FramebufferRegs::CompareFunc::GreaterThan:
  763. pass = (ref > dest);
  764. break;
  765. case FramebufferRegs::CompareFunc::GreaterThanOrEqual:
  766. pass = (ref >= dest);
  767. break;
  768. }
  769. if (!pass) {
  770. UpdateStencil(stencil_test.action_stencil_fail);
  771. continue;
  772. }
  773. }
  774. // Convert float to integer
  775. unsigned num_bits =
  776. FramebufferRegs::DepthBitsPerPixel(regs.framebuffer.framebuffer.depth_format);
  777. u32 z = (u32)(depth * ((1 << num_bits) - 1));
  778. if (output_merger.depth_test_enable) {
  779. u32 ref_z = GetDepth(x >> 4, y >> 4);
  780. bool pass = false;
  781. switch (output_merger.depth_test_func) {
  782. case FramebufferRegs::CompareFunc::Never:
  783. pass = false;
  784. break;
  785. case FramebufferRegs::CompareFunc::Always:
  786. pass = true;
  787. break;
  788. case FramebufferRegs::CompareFunc::Equal:
  789. pass = z == ref_z;
  790. break;
  791. case FramebufferRegs::CompareFunc::NotEqual:
  792. pass = z != ref_z;
  793. break;
  794. case FramebufferRegs::CompareFunc::LessThan:
  795. pass = z < ref_z;
  796. break;
  797. case FramebufferRegs::CompareFunc::LessThanOrEqual:
  798. pass = z <= ref_z;
  799. break;
  800. case FramebufferRegs::CompareFunc::GreaterThan:
  801. pass = z > ref_z;
  802. break;
  803. case FramebufferRegs::CompareFunc::GreaterThanOrEqual:
  804. pass = z >= ref_z;
  805. break;
  806. }
  807. if (!pass) {
  808. if (stencil_action_enable)
  809. UpdateStencil(stencil_test.action_depth_fail);
  810. continue;
  811. }
  812. }
  813. if (regs.framebuffer.framebuffer.allow_depth_stencil_write != 0 &&
  814. output_merger.depth_write_enable) {
  815. SetDepth(x >> 4, y >> 4, z);
  816. }
  817. // The stencil depth_pass action is executed even if depth testing is disabled
  818. if (stencil_action_enable)
  819. UpdateStencil(stencil_test.action_depth_pass);
  820. auto dest = GetPixel(x >> 4, y >> 4);
  821. Math::Vec4<u8> blend_output = combiner_output;
  822. if (output_merger.alphablend_enable) {
  823. auto params = output_merger.alpha_blending;
  824. auto LookupFactor = [&](unsigned channel,
  825. FramebufferRegs::BlendFactor factor) -> u8 {
  826. DEBUG_ASSERT(channel < 4);
  827. const Math::Vec4<u8> blend_const = {
  828. static_cast<u8>(output_merger.blend_const.r),
  829. static_cast<u8>(output_merger.blend_const.g),
  830. static_cast<u8>(output_merger.blend_const.b),
  831. static_cast<u8>(output_merger.blend_const.a),
  832. };
  833. switch (factor) {
  834. case FramebufferRegs::BlendFactor::Zero:
  835. return 0;
  836. case FramebufferRegs::BlendFactor::One:
  837. return 255;
  838. case FramebufferRegs::BlendFactor::SourceColor:
  839. return combiner_output[channel];
  840. case FramebufferRegs::BlendFactor::OneMinusSourceColor:
  841. return 255 - combiner_output[channel];
  842. case FramebufferRegs::BlendFactor::DestColor:
  843. return dest[channel];
  844. case FramebufferRegs::BlendFactor::OneMinusDestColor:
  845. return 255 - dest[channel];
  846. case FramebufferRegs::BlendFactor::SourceAlpha:
  847. return combiner_output.a();
  848. case FramebufferRegs::BlendFactor::OneMinusSourceAlpha:
  849. return 255 - combiner_output.a();
  850. case FramebufferRegs::BlendFactor::DestAlpha:
  851. return dest.a();
  852. case FramebufferRegs::BlendFactor::OneMinusDestAlpha:
  853. return 255 - dest.a();
  854. case FramebufferRegs::BlendFactor::ConstantColor:
  855. return blend_const[channel];
  856. case FramebufferRegs::BlendFactor::OneMinusConstantColor:
  857. return 255 - blend_const[channel];
  858. case FramebufferRegs::BlendFactor::ConstantAlpha:
  859. return blend_const.a();
  860. case FramebufferRegs::BlendFactor::OneMinusConstantAlpha:
  861. return 255 - blend_const.a();
  862. case FramebufferRegs::BlendFactor::SourceAlphaSaturate:
  863. // Returns 1.0 for the alpha channel
  864. if (channel == 3)
  865. return 255;
  866. return std::min(combiner_output.a(), static_cast<u8>(255 - dest.a()));
  867. default:
  868. LOG_CRITICAL(HW_GPU, "Unknown blend factor %x", factor);
  869. UNIMPLEMENTED();
  870. break;
  871. }
  872. return combiner_output[channel];
  873. };
  874. auto srcfactor = Math::MakeVec(LookupFactor(0, params.factor_source_rgb),
  875. LookupFactor(1, params.factor_source_rgb),
  876. LookupFactor(2, params.factor_source_rgb),
  877. LookupFactor(3, params.factor_source_a));
  878. auto dstfactor = Math::MakeVec(LookupFactor(0, params.factor_dest_rgb),
  879. LookupFactor(1, params.factor_dest_rgb),
  880. LookupFactor(2, params.factor_dest_rgb),
  881. LookupFactor(3, params.factor_dest_a));
  882. blend_output = EvaluateBlendEquation(combiner_output, srcfactor, dest, dstfactor,
  883. params.blend_equation_rgb);
  884. blend_output.a() = EvaluateBlendEquation(combiner_output, srcfactor, dest,
  885. dstfactor, params.blend_equation_a)
  886. .a();
  887. } else {
  888. blend_output =
  889. Math::MakeVec(LogicOp(combiner_output.r(), dest.r(), output_merger.logic_op),
  890. LogicOp(combiner_output.g(), dest.g(), output_merger.logic_op),
  891. LogicOp(combiner_output.b(), dest.b(), output_merger.logic_op),
  892. LogicOp(combiner_output.a(), dest.a(), output_merger.logic_op));
  893. }
  894. const Math::Vec4<u8> result = {
  895. output_merger.red_enable ? blend_output.r() : dest.r(),
  896. output_merger.green_enable ? blend_output.g() : dest.g(),
  897. output_merger.blue_enable ? blend_output.b() : dest.b(),
  898. output_merger.alpha_enable ? blend_output.a() : dest.a(),
  899. };
  900. if (regs.framebuffer.framebuffer.allow_color_write != 0)
  901. DrawPixel(x >> 4, y >> 4, result);
  902. }
  903. }
  904. }
  905. void ProcessTriangle(const Vertex& v0, const Vertex& v1, const Vertex& v2) {
  906. ProcessTriangleInternal(v0, v1, v2);
  907. }
  908. } // namespace Rasterizer
  909. } // namespace Pica