rasterizer.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  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 "common/assert.h"
  8. #include "common/bit_field.h"
  9. #include "common/color.h"
  10. #include "common/common_types.h"
  11. #include "common/logging/log.h"
  12. #include "common/math_util.h"
  13. #include "common/microprofile.h"
  14. #include "common/vector_math.h"
  15. #include "core/hw/gpu.h"
  16. #include "core/memory.h"
  17. #include "video_core/debug_utils/debug_utils.h"
  18. #include "video_core/pica_state.h"
  19. #include "video_core/pica_types.h"
  20. #include "video_core/regs_framebuffer.h"
  21. #include "video_core/regs_rasterizer.h"
  22. #include "video_core/regs_texturing.h"
  23. #include "video_core/shader/shader.h"
  24. #include "video_core/swrasterizer/framebuffer.h"
  25. #include "video_core/swrasterizer/rasterizer.h"
  26. #include "video_core/swrasterizer/texturing.h"
  27. #include "video_core/texture/texture_decode.h"
  28. #include "video_core/utils.h"
  29. namespace Pica {
  30. namespace Rasterizer {
  31. // NOTE: Assuming that rasterizer coordinates are 12.4 fixed-point values
  32. struct Fix12P4 {
  33. Fix12P4() {}
  34. Fix12P4(u16 val) : val(val) {}
  35. static u16 FracMask() {
  36. return 0xF;
  37. }
  38. static u16 IntMask() {
  39. return (u16)~0xF;
  40. }
  41. operator u16() const {
  42. return val;
  43. }
  44. bool operator<(const Fix12P4& oth) const {
  45. return (u16) * this < (u16)oth;
  46. }
  47. private:
  48. u16 val;
  49. };
  50. /**
  51. * Calculate signed area of the triangle spanned by the three argument vertices.
  52. * The sign denotes an orientation.
  53. *
  54. * @todo define orientation concretely.
  55. */
  56. static int SignedArea(const Math::Vec2<Fix12P4>& vtx1, const Math::Vec2<Fix12P4>& vtx2,
  57. const Math::Vec2<Fix12P4>& vtx3) {
  58. const auto vec1 = Math::MakeVec(vtx2 - vtx1, 0);
  59. const auto vec2 = Math::MakeVec(vtx3 - vtx1, 0);
  60. // TODO: There is a very small chance this will overflow for sizeof(int) == 4
  61. return Math::Cross(vec1, vec2).z;
  62. };
  63. MICROPROFILE_DEFINE(GPU_Rasterization, "GPU", "Rasterization", MP_RGB(50, 50, 240));
  64. /**
  65. * Helper function for ProcessTriangle with the "reversed" flag to allow for implementing
  66. * culling via recursion.
  67. */
  68. static void ProcessTriangleInternal(const Vertex& v0, const Vertex& v1, const Vertex& v2,
  69. bool reversed = false) {
  70. const auto& regs = g_state.regs;
  71. MICROPROFILE_SCOPE(GPU_Rasterization);
  72. // vertex positions in rasterizer coordinates
  73. static auto FloatToFix = [](float24 flt) {
  74. // TODO: Rounding here is necessary to prevent garbage pixels at
  75. // triangle borders. Is it that the correct solution, though?
  76. return Fix12P4(static_cast<unsigned short>(round(flt.ToFloat32() * 16.0f)));
  77. };
  78. static auto ScreenToRasterizerCoordinates = [](const Math::Vec3<float24>& vec) {
  79. return Math::Vec3<Fix12P4>{FloatToFix(vec.x), FloatToFix(vec.y), FloatToFix(vec.z)};
  80. };
  81. Math::Vec3<Fix12P4> vtxpos[3]{ScreenToRasterizerCoordinates(v0.screenpos),
  82. ScreenToRasterizerCoordinates(v1.screenpos),
  83. ScreenToRasterizerCoordinates(v2.screenpos)};
  84. if (regs.rasterizer.cull_mode == RasterizerRegs::CullMode::KeepAll) {
  85. // Make sure we always end up with a triangle wound counter-clockwise
  86. if (!reversed && SignedArea(vtxpos[0].xy(), vtxpos[1].xy(), vtxpos[2].xy()) <= 0) {
  87. ProcessTriangleInternal(v0, v2, v1, true);
  88. return;
  89. }
  90. } else {
  91. if (!reversed && regs.rasterizer.cull_mode == RasterizerRegs::CullMode::KeepClockWise) {
  92. // Reverse vertex order and use the CCW code path.
  93. ProcessTriangleInternal(v0, v2, v1, true);
  94. return;
  95. }
  96. // Cull away triangles which are wound clockwise.
  97. if (SignedArea(vtxpos[0].xy(), vtxpos[1].xy(), vtxpos[2].xy()) <= 0)
  98. return;
  99. }
  100. u16 min_x = std::min({vtxpos[0].x, vtxpos[1].x, vtxpos[2].x});
  101. u16 min_y = std::min({vtxpos[0].y, vtxpos[1].y, vtxpos[2].y});
  102. u16 max_x = std::max({vtxpos[0].x, vtxpos[1].x, vtxpos[2].x});
  103. u16 max_y = std::max({vtxpos[0].y, vtxpos[1].y, vtxpos[2].y});
  104. // Convert the scissor box coordinates to 12.4 fixed point
  105. u16 scissor_x1 = (u16)(regs.rasterizer.scissor_test.x1 << 4);
  106. u16 scissor_y1 = (u16)(regs.rasterizer.scissor_test.y1 << 4);
  107. // x2,y2 have +1 added to cover the entire sub-pixel area
  108. u16 scissor_x2 = (u16)((regs.rasterizer.scissor_test.x2 + 1) << 4);
  109. u16 scissor_y2 = (u16)((regs.rasterizer.scissor_test.y2 + 1) << 4);
  110. if (regs.rasterizer.scissor_test.mode == RasterizerRegs::ScissorMode::Include) {
  111. // Calculate the new bounds
  112. min_x = std::max(min_x, scissor_x1);
  113. min_y = std::max(min_y, scissor_y1);
  114. max_x = std::min(max_x, scissor_x2);
  115. max_y = std::min(max_y, scissor_y2);
  116. }
  117. min_x &= Fix12P4::IntMask();
  118. min_y &= Fix12P4::IntMask();
  119. max_x = ((max_x + Fix12P4::FracMask()) & Fix12P4::IntMask());
  120. max_y = ((max_y + Fix12P4::FracMask()) & Fix12P4::IntMask());
  121. // Triangle filling rules: Pixels on the right-sided edge or on flat bottom edges are not
  122. // drawn. Pixels on any other triangle border are drawn. This is implemented with three bias
  123. // values which are added to the barycentric coordinates w0, w1 and w2, respectively.
  124. // NOTE: These are the PSP filling rules. Not sure if the 3DS uses the same ones...
  125. auto IsRightSideOrFlatBottomEdge = [](const Math::Vec2<Fix12P4>& vtx,
  126. const Math::Vec2<Fix12P4>& line1,
  127. const Math::Vec2<Fix12P4>& line2) {
  128. if (line1.y == line2.y) {
  129. // just check if vertex is above us => bottom line parallel to x-axis
  130. return vtx.y < line1.y;
  131. } else {
  132. // check if vertex is on our left => right side
  133. // TODO: Not sure how likely this is to overflow
  134. return (int)vtx.x < (int)line1.x +
  135. ((int)line2.x - (int)line1.x) * ((int)vtx.y - (int)line1.y) /
  136. ((int)line2.y - (int)line1.y);
  137. }
  138. };
  139. int bias0 =
  140. IsRightSideOrFlatBottomEdge(vtxpos[0].xy(), vtxpos[1].xy(), vtxpos[2].xy()) ? -1 : 0;
  141. int bias1 =
  142. IsRightSideOrFlatBottomEdge(vtxpos[1].xy(), vtxpos[2].xy(), vtxpos[0].xy()) ? -1 : 0;
  143. int bias2 =
  144. IsRightSideOrFlatBottomEdge(vtxpos[2].xy(), vtxpos[0].xy(), vtxpos[1].xy()) ? -1 : 0;
  145. auto w_inverse = Math::MakeVec(v0.pos.w, v1.pos.w, v2.pos.w);
  146. auto textures = regs.texturing.GetTextures();
  147. auto tev_stages = regs.texturing.GetTevStages();
  148. bool stencil_action_enable =
  149. g_state.regs.framebuffer.output_merger.stencil_test.enable &&
  150. g_state.regs.framebuffer.framebuffer.depth_format == FramebufferRegs::DepthFormat::D24S8;
  151. const auto stencil_test = g_state.regs.framebuffer.output_merger.stencil_test;
  152. // Enter rasterization loop, starting at the center of the topleft bounding box corner.
  153. // TODO: Not sure if looping through x first might be faster
  154. for (u16 y = min_y + 8; y < max_y; y += 0x10) {
  155. for (u16 x = min_x + 8; x < max_x; x += 0x10) {
  156. // Do not process the pixel if it's inside the scissor box and the scissor mode is set
  157. // to Exclude
  158. if (regs.rasterizer.scissor_test.mode == RasterizerRegs::ScissorMode::Exclude) {
  159. if (x >= scissor_x1 && x < scissor_x2 && y >= scissor_y1 && y < scissor_y2)
  160. continue;
  161. }
  162. // Calculate the barycentric coordinates w0, w1 and w2
  163. int w0 = bias0 + SignedArea(vtxpos[1].xy(), vtxpos[2].xy(), {x, y});
  164. int w1 = bias1 + SignedArea(vtxpos[2].xy(), vtxpos[0].xy(), {x, y});
  165. int w2 = bias2 + SignedArea(vtxpos[0].xy(), vtxpos[1].xy(), {x, y});
  166. int wsum = w0 + w1 + w2;
  167. // If current pixel is not covered by the current primitive
  168. if (w0 < 0 || w1 < 0 || w2 < 0)
  169. continue;
  170. auto baricentric_coordinates =
  171. Math::MakeVec(float24::FromFloat32(static_cast<float>(w0)),
  172. float24::FromFloat32(static_cast<float>(w1)),
  173. float24::FromFloat32(static_cast<float>(w2)));
  174. float24 interpolated_w_inverse =
  175. float24::FromFloat32(1.0f) / Math::Dot(w_inverse, baricentric_coordinates);
  176. // interpolated_z = z / w
  177. float interpolated_z_over_w =
  178. (v0.screenpos[2].ToFloat32() * w0 + v1.screenpos[2].ToFloat32() * w1 +
  179. v2.screenpos[2].ToFloat32() * w2) /
  180. wsum;
  181. // Not fully accurate. About 3 bits in precision are missing.
  182. // Z-Buffer (z / w * scale + offset)
  183. float depth_scale = float24::FromRaw(regs.rasterizer.viewport_depth_range).ToFloat32();
  184. float depth_offset =
  185. float24::FromRaw(regs.rasterizer.viewport_depth_near_plane).ToFloat32();
  186. float depth = interpolated_z_over_w * depth_scale + depth_offset;
  187. // Potentially switch to W-Buffer
  188. if (regs.rasterizer.depthmap_enable ==
  189. Pica::RasterizerRegs::DepthBuffering::WBuffering) {
  190. // W-Buffer (z * scale + w * offset = (z / w * scale + offset) * w)
  191. depth *= interpolated_w_inverse.ToFloat32() * wsum;
  192. }
  193. // Clamp the result
  194. depth = MathUtil::Clamp(depth, 0.0f, 1.0f);
  195. // Perspective correct attribute interpolation:
  196. // Attribute values cannot be calculated by simple linear interpolation since
  197. // they are not linear in screen space. For example, when interpolating a
  198. // texture coordinate across two vertices, something simple like
  199. // u = (u0*w0 + u1*w1)/(w0+w1)
  200. // will not work. However, the attribute value divided by the
  201. // clipspace w-coordinate (u/w) and and the inverse w-coordinate (1/w) are linear
  202. // in screenspace. Hence, we can linearly interpolate these two independently and
  203. // calculate the interpolated attribute by dividing the results.
  204. // I.e.
  205. // u_over_w = ((u0/v0.pos.w)*w0 + (u1/v1.pos.w)*w1)/(w0+w1)
  206. // one_over_w = (( 1/v0.pos.w)*w0 + ( 1/v1.pos.w)*w1)/(w0+w1)
  207. // u = u_over_w / one_over_w
  208. //
  209. // The generalization to three vertices is straightforward in baricentric coordinates.
  210. auto GetInterpolatedAttribute = [&](float24 attr0, float24 attr1, float24 attr2) {
  211. auto attr_over_w = Math::MakeVec(attr0, attr1, attr2);
  212. float24 interpolated_attr_over_w = Math::Dot(attr_over_w, baricentric_coordinates);
  213. return interpolated_attr_over_w * interpolated_w_inverse;
  214. };
  215. Math::Vec4<u8> primary_color{
  216. (u8)(
  217. GetInterpolatedAttribute(v0.color.r(), v1.color.r(), v2.color.r()).ToFloat32() *
  218. 255),
  219. (u8)(
  220. GetInterpolatedAttribute(v0.color.g(), v1.color.g(), v2.color.g()).ToFloat32() *
  221. 255),
  222. (u8)(
  223. GetInterpolatedAttribute(v0.color.b(), v1.color.b(), v2.color.b()).ToFloat32() *
  224. 255),
  225. (u8)(
  226. GetInterpolatedAttribute(v0.color.a(), v1.color.a(), v2.color.a()).ToFloat32() *
  227. 255),
  228. };
  229. Math::Vec2<float24> uv[3];
  230. uv[0].u() = GetInterpolatedAttribute(v0.tc0.u(), v1.tc0.u(), v2.tc0.u());
  231. uv[0].v() = GetInterpolatedAttribute(v0.tc0.v(), v1.tc0.v(), v2.tc0.v());
  232. uv[1].u() = GetInterpolatedAttribute(v0.tc1.u(), v1.tc1.u(), v2.tc1.u());
  233. uv[1].v() = GetInterpolatedAttribute(v0.tc1.v(), v1.tc1.v(), v2.tc1.v());
  234. uv[2].u() = GetInterpolatedAttribute(v0.tc2.u(), v1.tc2.u(), v2.tc2.u());
  235. uv[2].v() = GetInterpolatedAttribute(v0.tc2.v(), v1.tc2.v(), v2.tc2.v());
  236. Math::Vec4<u8> texture_color[3]{};
  237. for (int i = 0; i < 3; ++i) {
  238. const auto& texture = textures[i];
  239. if (!texture.enabled)
  240. continue;
  241. DEBUG_ASSERT(0 != texture.config.address);
  242. int coordinate_i =
  243. (i == 2 && regs.texturing.main_config.texture2_use_coord1) ? 1 : i;
  244. float24 u = uv[coordinate_i].u();
  245. float24 v = uv[coordinate_i].v();
  246. // Only unit 0 respects the texturing type (according to 3DBrew)
  247. // TODO: Refactor so cubemaps and shadowmaps can be handled
  248. if (i == 0) {
  249. switch (texture.config.type) {
  250. case TexturingRegs::TextureConfig::Texture2D:
  251. break;
  252. case TexturingRegs::TextureConfig::Projection2D: {
  253. auto tc0_w = GetInterpolatedAttribute(v0.tc0_w, v1.tc0_w, v2.tc0_w);
  254. u /= tc0_w;
  255. v /= tc0_w;
  256. break;
  257. }
  258. default:
  259. // TODO: Change to LOG_ERROR when more types are handled.
  260. LOG_DEBUG(HW_GPU, "Unhandled texture type %x", (int)texture.config.type);
  261. UNIMPLEMENTED();
  262. break;
  263. }
  264. }
  265. int s = (int)(u * float24::FromFloat32(static_cast<float>(texture.config.width)))
  266. .ToFloat32();
  267. int t = (int)(v * float24::FromFloat32(static_cast<float>(texture.config.height)))
  268. .ToFloat32();
  269. if ((texture.config.wrap_s == TexturingRegs::TextureConfig::ClampToBorder &&
  270. (s < 0 || static_cast<u32>(s) >= texture.config.width)) ||
  271. (texture.config.wrap_t == TexturingRegs::TextureConfig::ClampToBorder &&
  272. (t < 0 || static_cast<u32>(t) >= texture.config.height))) {
  273. auto border_color = texture.config.border_color;
  274. texture_color[i] = {border_color.r, border_color.g, border_color.b,
  275. border_color.a};
  276. } else {
  277. // Textures are laid out from bottom to top, hence we invert the t coordinate.
  278. // NOTE: This may not be the right place for the inversion.
  279. // TODO: Check if this applies to ETC textures, too.
  280. s = GetWrappedTexCoord(texture.config.wrap_s, s, texture.config.width);
  281. t = texture.config.height - 1 -
  282. GetWrappedTexCoord(texture.config.wrap_t, t, texture.config.height);
  283. u8* texture_data =
  284. Memory::GetPhysicalPointer(texture.config.GetPhysicalAddress());
  285. auto info =
  286. Texture::TextureInfo::FromPicaRegister(texture.config, texture.format);
  287. // TODO: Apply the min and mag filters to the texture
  288. texture_color[i] = Texture::LookupTexture(texture_data, s, t, info);
  289. #if PICA_DUMP_TEXTURES
  290. DebugUtils::DumpTexture(texture.config, texture_data);
  291. #endif
  292. }
  293. }
  294. // Texture environment - consists of 6 stages of color and alpha combining.
  295. //
  296. // Color combiners take three input color values from some source (e.g. interpolated
  297. // vertex color, texture color, previous stage, etc), perform some very simple
  298. // operations on each of them (e.g. inversion) and then calculate the output color
  299. // with some basic arithmetic. Alpha combiners can be configured separately but work
  300. // analogously.
  301. Math::Vec4<u8> combiner_output;
  302. Math::Vec4<u8> combiner_buffer = {0, 0, 0, 0};
  303. Math::Vec4<u8> next_combiner_buffer = {
  304. regs.texturing.tev_combiner_buffer_color.r,
  305. regs.texturing.tev_combiner_buffer_color.g,
  306. regs.texturing.tev_combiner_buffer_color.b,
  307. regs.texturing.tev_combiner_buffer_color.a,
  308. };
  309. for (unsigned tev_stage_index = 0; tev_stage_index < tev_stages.size();
  310. ++tev_stage_index) {
  311. const auto& tev_stage = tev_stages[tev_stage_index];
  312. using Source = TexturingRegs::TevStageConfig::Source;
  313. auto GetSource = [&](Source source) -> Math::Vec4<u8> {
  314. switch (source) {
  315. case Source::PrimaryColor:
  316. // HACK: Until we implement fragment lighting, use primary_color
  317. case Source::PrimaryFragmentColor:
  318. return primary_color;
  319. // HACK: Until we implement fragment lighting, use zero
  320. case Source::SecondaryFragmentColor:
  321. return {0, 0, 0, 0};
  322. case Source::Texture0:
  323. return texture_color[0];
  324. case Source::Texture1:
  325. return texture_color[1];
  326. case Source::Texture2:
  327. return texture_color[2];
  328. case Source::PreviousBuffer:
  329. return combiner_buffer;
  330. case Source::Constant:
  331. return {tev_stage.const_r, tev_stage.const_g, tev_stage.const_b,
  332. tev_stage.const_a};
  333. case Source::Previous:
  334. return combiner_output;
  335. default:
  336. LOG_ERROR(HW_GPU, "Unknown color combiner source %d", (int)source);
  337. UNIMPLEMENTED();
  338. return {0, 0, 0, 0};
  339. }
  340. };
  341. // color combiner
  342. // NOTE: Not sure if the alpha combiner might use the color output of the previous
  343. // stage as input. Hence, we currently don't directly write the result to
  344. // combiner_output.rgb(), but instead store it in a temporary variable until
  345. // alpha combining has been done.
  346. Math::Vec3<u8> color_result[3] = {
  347. GetColorModifier(tev_stage.color_modifier1, GetSource(tev_stage.color_source1)),
  348. GetColorModifier(tev_stage.color_modifier2, GetSource(tev_stage.color_source2)),
  349. GetColorModifier(tev_stage.color_modifier3, GetSource(tev_stage.color_source3)),
  350. };
  351. auto color_output = ColorCombine(tev_stage.color_op, color_result);
  352. u8 alpha_output;
  353. if (tev_stage.color_op == TexturingRegs::TevStageConfig::Operation::Dot3_RGBA) {
  354. // result of Dot3_RGBA operation is also placed to the alpha component
  355. alpha_output = color_output.x;
  356. } else {
  357. // alpha combiner
  358. std::array<u8, 3> alpha_result = {{
  359. GetAlphaModifier(tev_stage.alpha_modifier1,
  360. GetSource(tev_stage.alpha_source1)),
  361. GetAlphaModifier(tev_stage.alpha_modifier2,
  362. GetSource(tev_stage.alpha_source2)),
  363. GetAlphaModifier(tev_stage.alpha_modifier3,
  364. GetSource(tev_stage.alpha_source3)),
  365. }};
  366. alpha_output = AlphaCombine(tev_stage.alpha_op, alpha_result);
  367. }
  368. combiner_output[0] =
  369. std::min((unsigned)255, color_output.r() * tev_stage.GetColorMultiplier());
  370. combiner_output[1] =
  371. std::min((unsigned)255, color_output.g() * tev_stage.GetColorMultiplier());
  372. combiner_output[2] =
  373. std::min((unsigned)255, color_output.b() * tev_stage.GetColorMultiplier());
  374. combiner_output[3] =
  375. std::min((unsigned)255, alpha_output * tev_stage.GetAlphaMultiplier());
  376. combiner_buffer = next_combiner_buffer;
  377. if (regs.texturing.tev_combiner_buffer_input.TevStageUpdatesCombinerBufferColor(
  378. tev_stage_index)) {
  379. next_combiner_buffer.r() = combiner_output.r();
  380. next_combiner_buffer.g() = combiner_output.g();
  381. next_combiner_buffer.b() = combiner_output.b();
  382. }
  383. if (regs.texturing.tev_combiner_buffer_input.TevStageUpdatesCombinerBufferAlpha(
  384. tev_stage_index)) {
  385. next_combiner_buffer.a() = combiner_output.a();
  386. }
  387. }
  388. const auto& output_merger = regs.framebuffer.output_merger;
  389. // TODO: Does alpha testing happen before or after stencil?
  390. if (output_merger.alpha_test.enable) {
  391. bool pass = false;
  392. switch (output_merger.alpha_test.func) {
  393. case FramebufferRegs::CompareFunc::Never:
  394. pass = false;
  395. break;
  396. case FramebufferRegs::CompareFunc::Always:
  397. pass = true;
  398. break;
  399. case FramebufferRegs::CompareFunc::Equal:
  400. pass = combiner_output.a() == output_merger.alpha_test.ref;
  401. break;
  402. case FramebufferRegs::CompareFunc::NotEqual:
  403. pass = combiner_output.a() != output_merger.alpha_test.ref;
  404. break;
  405. case FramebufferRegs::CompareFunc::LessThan:
  406. pass = combiner_output.a() < output_merger.alpha_test.ref;
  407. break;
  408. case FramebufferRegs::CompareFunc::LessThanOrEqual:
  409. pass = combiner_output.a() <= output_merger.alpha_test.ref;
  410. break;
  411. case FramebufferRegs::CompareFunc::GreaterThan:
  412. pass = combiner_output.a() > output_merger.alpha_test.ref;
  413. break;
  414. case FramebufferRegs::CompareFunc::GreaterThanOrEqual:
  415. pass = combiner_output.a() >= output_merger.alpha_test.ref;
  416. break;
  417. }
  418. if (!pass)
  419. continue;
  420. }
  421. // Apply fog combiner
  422. // Not fully accurate. We'd have to know what data type is used to
  423. // store the depth etc. Using float for now until we know more
  424. // about Pica datatypes
  425. if (regs.texturing.fog_mode == TexturingRegs::FogMode::Fog) {
  426. const Math::Vec3<u8> fog_color = {
  427. static_cast<u8>(regs.texturing.fog_color.r.Value()),
  428. static_cast<u8>(regs.texturing.fog_color.g.Value()),
  429. static_cast<u8>(regs.texturing.fog_color.b.Value()),
  430. };
  431. // Get index into fog LUT
  432. float fog_index;
  433. if (g_state.regs.texturing.fog_flip) {
  434. fog_index = (1.0f - depth) * 128.0f;
  435. } else {
  436. fog_index = depth * 128.0f;
  437. }
  438. // Generate clamped fog factor from LUT for given fog index
  439. float fog_i = MathUtil::Clamp(floorf(fog_index), 0.0f, 127.0f);
  440. float fog_f = fog_index - fog_i;
  441. const auto& fog_lut_entry = g_state.fog.lut[static_cast<unsigned int>(fog_i)];
  442. float fog_factor = (fog_lut_entry.value + fog_lut_entry.difference * fog_f) /
  443. 2047.0f; // This is signed fixed point 1.11
  444. fog_factor = MathUtil::Clamp(fog_factor, 0.0f, 1.0f);
  445. // Blend the fog
  446. for (unsigned i = 0; i < 3; i++) {
  447. combiner_output[i] = static_cast<u8>(fog_factor * combiner_output[i] +
  448. (1.0f - fog_factor) * fog_color[i]);
  449. }
  450. }
  451. u8 old_stencil = 0;
  452. auto UpdateStencil = [stencil_test, x, y,
  453. &old_stencil](Pica::FramebufferRegs::StencilAction action) {
  454. u8 new_stencil =
  455. PerformStencilAction(action, old_stencil, stencil_test.reference_value);
  456. if (g_state.regs.framebuffer.framebuffer.allow_depth_stencil_write != 0)
  457. SetStencil(x >> 4, y >> 4, (new_stencil & stencil_test.write_mask) |
  458. (old_stencil & ~stencil_test.write_mask));
  459. };
  460. if (stencil_action_enable) {
  461. old_stencil = GetStencil(x >> 4, y >> 4);
  462. u8 dest = old_stencil & stencil_test.input_mask;
  463. u8 ref = stencil_test.reference_value & stencil_test.input_mask;
  464. bool pass = false;
  465. switch (stencil_test.func) {
  466. case FramebufferRegs::CompareFunc::Never:
  467. pass = false;
  468. break;
  469. case FramebufferRegs::CompareFunc::Always:
  470. pass = true;
  471. break;
  472. case FramebufferRegs::CompareFunc::Equal:
  473. pass = (ref == dest);
  474. break;
  475. case FramebufferRegs::CompareFunc::NotEqual:
  476. pass = (ref != dest);
  477. break;
  478. case FramebufferRegs::CompareFunc::LessThan:
  479. pass = (ref < dest);
  480. break;
  481. case FramebufferRegs::CompareFunc::LessThanOrEqual:
  482. pass = (ref <= dest);
  483. break;
  484. case FramebufferRegs::CompareFunc::GreaterThan:
  485. pass = (ref > dest);
  486. break;
  487. case FramebufferRegs::CompareFunc::GreaterThanOrEqual:
  488. pass = (ref >= dest);
  489. break;
  490. }
  491. if (!pass) {
  492. UpdateStencil(stencil_test.action_stencil_fail);
  493. continue;
  494. }
  495. }
  496. // Convert float to integer
  497. unsigned num_bits =
  498. FramebufferRegs::DepthBitsPerPixel(regs.framebuffer.framebuffer.depth_format);
  499. u32 z = (u32)(depth * ((1 << num_bits) - 1));
  500. if (output_merger.depth_test_enable) {
  501. u32 ref_z = GetDepth(x >> 4, y >> 4);
  502. bool pass = false;
  503. switch (output_merger.depth_test_func) {
  504. case FramebufferRegs::CompareFunc::Never:
  505. pass = false;
  506. break;
  507. case FramebufferRegs::CompareFunc::Always:
  508. pass = true;
  509. break;
  510. case FramebufferRegs::CompareFunc::Equal:
  511. pass = z == ref_z;
  512. break;
  513. case FramebufferRegs::CompareFunc::NotEqual:
  514. pass = z != ref_z;
  515. break;
  516. case FramebufferRegs::CompareFunc::LessThan:
  517. pass = z < ref_z;
  518. break;
  519. case FramebufferRegs::CompareFunc::LessThanOrEqual:
  520. pass = z <= ref_z;
  521. break;
  522. case FramebufferRegs::CompareFunc::GreaterThan:
  523. pass = z > ref_z;
  524. break;
  525. case FramebufferRegs::CompareFunc::GreaterThanOrEqual:
  526. pass = z >= ref_z;
  527. break;
  528. }
  529. if (!pass) {
  530. if (stencil_action_enable)
  531. UpdateStencil(stencil_test.action_depth_fail);
  532. continue;
  533. }
  534. }
  535. if (regs.framebuffer.framebuffer.allow_depth_stencil_write != 0 &&
  536. output_merger.depth_write_enable) {
  537. SetDepth(x >> 4, y >> 4, z);
  538. }
  539. // The stencil depth_pass action is executed even if depth testing is disabled
  540. if (stencil_action_enable)
  541. UpdateStencil(stencil_test.action_depth_pass);
  542. auto dest = GetPixel(x >> 4, y >> 4);
  543. Math::Vec4<u8> blend_output = combiner_output;
  544. if (output_merger.alphablend_enable) {
  545. auto params = output_merger.alpha_blending;
  546. auto LookupFactor = [&](unsigned channel,
  547. FramebufferRegs::BlendFactor factor) -> u8 {
  548. DEBUG_ASSERT(channel < 4);
  549. const Math::Vec4<u8> blend_const = {
  550. static_cast<u8>(output_merger.blend_const.r),
  551. static_cast<u8>(output_merger.blend_const.g),
  552. static_cast<u8>(output_merger.blend_const.b),
  553. static_cast<u8>(output_merger.blend_const.a),
  554. };
  555. switch (factor) {
  556. case FramebufferRegs::BlendFactor::Zero:
  557. return 0;
  558. case FramebufferRegs::BlendFactor::One:
  559. return 255;
  560. case FramebufferRegs::BlendFactor::SourceColor:
  561. return combiner_output[channel];
  562. case FramebufferRegs::BlendFactor::OneMinusSourceColor:
  563. return 255 - combiner_output[channel];
  564. case FramebufferRegs::BlendFactor::DestColor:
  565. return dest[channel];
  566. case FramebufferRegs::BlendFactor::OneMinusDestColor:
  567. return 255 - dest[channel];
  568. case FramebufferRegs::BlendFactor::SourceAlpha:
  569. return combiner_output.a();
  570. case FramebufferRegs::BlendFactor::OneMinusSourceAlpha:
  571. return 255 - combiner_output.a();
  572. case FramebufferRegs::BlendFactor::DestAlpha:
  573. return dest.a();
  574. case FramebufferRegs::BlendFactor::OneMinusDestAlpha:
  575. return 255 - dest.a();
  576. case FramebufferRegs::BlendFactor::ConstantColor:
  577. return blend_const[channel];
  578. case FramebufferRegs::BlendFactor::OneMinusConstantColor:
  579. return 255 - blend_const[channel];
  580. case FramebufferRegs::BlendFactor::ConstantAlpha:
  581. return blend_const.a();
  582. case FramebufferRegs::BlendFactor::OneMinusConstantAlpha:
  583. return 255 - blend_const.a();
  584. case FramebufferRegs::BlendFactor::SourceAlphaSaturate:
  585. // Returns 1.0 for the alpha channel
  586. if (channel == 3)
  587. return 255;
  588. return std::min(combiner_output.a(), static_cast<u8>(255 - dest.a()));
  589. default:
  590. LOG_CRITICAL(HW_GPU, "Unknown blend factor %x", factor);
  591. UNIMPLEMENTED();
  592. break;
  593. }
  594. return combiner_output[channel];
  595. };
  596. auto srcfactor = Math::MakeVec(LookupFactor(0, params.factor_source_rgb),
  597. LookupFactor(1, params.factor_source_rgb),
  598. LookupFactor(2, params.factor_source_rgb),
  599. LookupFactor(3, params.factor_source_a));
  600. auto dstfactor = Math::MakeVec(LookupFactor(0, params.factor_dest_rgb),
  601. LookupFactor(1, params.factor_dest_rgb),
  602. LookupFactor(2, params.factor_dest_rgb),
  603. LookupFactor(3, params.factor_dest_a));
  604. blend_output = EvaluateBlendEquation(combiner_output, srcfactor, dest, dstfactor,
  605. params.blend_equation_rgb);
  606. blend_output.a() = EvaluateBlendEquation(combiner_output, srcfactor, dest,
  607. dstfactor, params.blend_equation_a)
  608. .a();
  609. } else {
  610. blend_output =
  611. Math::MakeVec(LogicOp(combiner_output.r(), dest.r(), output_merger.logic_op),
  612. LogicOp(combiner_output.g(), dest.g(), output_merger.logic_op),
  613. LogicOp(combiner_output.b(), dest.b(), output_merger.logic_op),
  614. LogicOp(combiner_output.a(), dest.a(), output_merger.logic_op));
  615. }
  616. const Math::Vec4<u8> result = {
  617. output_merger.red_enable ? blend_output.r() : dest.r(),
  618. output_merger.green_enable ? blend_output.g() : dest.g(),
  619. output_merger.blue_enable ? blend_output.b() : dest.b(),
  620. output_merger.alpha_enable ? blend_output.a() : dest.a(),
  621. };
  622. if (regs.framebuffer.framebuffer.allow_color_write != 0)
  623. DrawPixel(x >> 4, y >> 4, result);
  624. }
  625. }
  626. }
  627. void ProcessTriangle(const Vertex& v0, const Vertex& v1, const Vertex& v2) {
  628. ProcessTriangleInternal(v0, v1, v2);
  629. }
  630. } // namespace Rasterizer
  631. } // namespace Pica