rasterizer.cpp 48 KB

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