rasterizer.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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 "common/common_types.h"
  6. #include "math.h"
  7. #include "pica.h"
  8. #include "rasterizer.h"
  9. #include "vertex_shader.h"
  10. #include "debug_utils/debug_utils.h"
  11. namespace Pica {
  12. namespace Rasterizer {
  13. static void DrawPixel(int x, int y, const Math::Vec4<u8>& color) {
  14. u32* color_buffer = reinterpret_cast<u32*>(Memory::GetPointer(PAddrToVAddr(registers.framebuffer.GetColorBufferPhysicalAddress())));
  15. u32 value = (color.a() << 24) | (color.r() << 16) | (color.g() << 8) | color.b();
  16. // Assuming RGBA8 format until actual framebuffer format handling is implemented
  17. *(color_buffer + x + y * registers.framebuffer.GetWidth()) = value;
  18. }
  19. static const Math::Vec4<u8> GetPixel(int x, int y) {
  20. u32* color_buffer_u32 = reinterpret_cast<u32*>(Memory::GetPointer(PAddrToVAddr(registers.framebuffer.GetColorBufferPhysicalAddress())));
  21. u32 value = *(color_buffer_u32 + x + y * registers.framebuffer.GetWidth());
  22. Math::Vec4<u8> ret;
  23. ret.a() = value >> 24;
  24. ret.r() = (value >> 16) & 0xFF;
  25. ret.g() = (value >> 8) & 0xFF;
  26. ret.b() = value & 0xFF;
  27. return ret;
  28. }
  29. static u32 GetDepth(int x, int y) {
  30. u16* depth_buffer = reinterpret_cast<u16*>(Memory::GetPointer(PAddrToVAddr(registers.framebuffer.GetDepthBufferPhysicalAddress())));
  31. // Assuming 16-bit depth buffer format until actual format handling is implemented
  32. return *(depth_buffer + x + y * registers.framebuffer.GetWidth());
  33. }
  34. static void SetDepth(int x, int y, u16 value) {
  35. u16* depth_buffer = reinterpret_cast<u16*>(Memory::GetPointer(PAddrToVAddr(registers.framebuffer.GetDepthBufferPhysicalAddress())));
  36. // Assuming 16-bit depth buffer format until actual format handling is implemented
  37. *(depth_buffer + x + y * registers.framebuffer.GetWidth()) = value;
  38. }
  39. void ProcessTriangle(const VertexShader::OutputVertex& v0,
  40. const VertexShader::OutputVertex& v1,
  41. const VertexShader::OutputVertex& v2)
  42. {
  43. // NOTE: Assuming that rasterizer coordinates are 12.4 fixed-point values
  44. struct Fix12P4 {
  45. Fix12P4() {}
  46. Fix12P4(u16 val) : val(val) {}
  47. static u16 FracMask() { return 0xF; }
  48. static u16 IntMask() { return (u16)~0xF; }
  49. operator u16() const {
  50. return val;
  51. }
  52. bool operator < (const Fix12P4& oth) const {
  53. return (u16)*this < (u16)oth;
  54. }
  55. private:
  56. u16 val;
  57. };
  58. // vertex positions in rasterizer coordinates
  59. auto FloatToFix = [](float24 flt) {
  60. return Fix12P4(static_cast<unsigned short>(flt.ToFloat32() * 16.0f));
  61. };
  62. auto ScreenToRasterizerCoordinates = [FloatToFix](const Math::Vec3<float24> vec) {
  63. return Math::Vec3<Fix12P4>{FloatToFix(vec.x), FloatToFix(vec.y), FloatToFix(vec.z)};
  64. };
  65. Math::Vec3<Fix12P4> vtxpos[3]{ ScreenToRasterizerCoordinates(v0.screenpos),
  66. ScreenToRasterizerCoordinates(v1.screenpos),
  67. ScreenToRasterizerCoordinates(v2.screenpos) };
  68. // TODO: Proper scissor rect test!
  69. u16 min_x = std::min({vtxpos[0].x, vtxpos[1].x, vtxpos[2].x});
  70. u16 min_y = std::min({vtxpos[0].y, vtxpos[1].y, vtxpos[2].y});
  71. u16 max_x = std::max({vtxpos[0].x, vtxpos[1].x, vtxpos[2].x});
  72. u16 max_y = std::max({vtxpos[0].y, vtxpos[1].y, vtxpos[2].y});
  73. min_x &= Fix12P4::IntMask();
  74. min_y &= Fix12P4::IntMask();
  75. max_x = ((max_x + Fix12P4::FracMask()) & Fix12P4::IntMask());
  76. max_y = ((max_y + Fix12P4::FracMask()) & Fix12P4::IntMask());
  77. // Triangle filling rules: Pixels on the right-sided edge or on flat bottom edges are not
  78. // drawn. Pixels on any other triangle border are drawn. This is implemented with three bias
  79. // values which are added to the barycentric coordinates w0, w1 and w2, respectively.
  80. // NOTE: These are the PSP filling rules. Not sure if the 3DS uses the same ones...
  81. auto IsRightSideOrFlatBottomEdge = [](const Math::Vec2<Fix12P4>& vtx,
  82. const Math::Vec2<Fix12P4>& line1,
  83. const Math::Vec2<Fix12P4>& line2)
  84. {
  85. if (line1.y == line2.y) {
  86. // just check if vertex is above us => bottom line parallel to x-axis
  87. return vtx.y < line1.y;
  88. } else {
  89. // check if vertex is on our left => right side
  90. // TODO: Not sure how likely this is to overflow
  91. return (int)vtx.x < (int)line1.x + ((int)line2.x - (int)line1.x) * ((int)vtx.y - (int)line1.y) / ((int)line2.y - (int)line1.y);
  92. }
  93. };
  94. int bias0 = IsRightSideOrFlatBottomEdge(vtxpos[0].xy(), vtxpos[1].xy(), vtxpos[2].xy()) ? -1 : 0;
  95. int bias1 = IsRightSideOrFlatBottomEdge(vtxpos[1].xy(), vtxpos[2].xy(), vtxpos[0].xy()) ? -1 : 0;
  96. int bias2 = IsRightSideOrFlatBottomEdge(vtxpos[2].xy(), vtxpos[0].xy(), vtxpos[1].xy()) ? -1 : 0;
  97. auto w_inverse = Math::MakeVec(v0.pos.w, v1.pos.w, v2.pos.w);
  98. auto textures = registers.GetTextures();
  99. auto tev_stages = registers.GetTevStages();
  100. // TODO: Not sure if looping through x first might be faster
  101. for (u16 y = min_y; y < max_y; y += 0x10) {
  102. for (u16 x = min_x; x < max_x; x += 0x10) {
  103. // Calculate the barycentric coordinates w0, w1 and w2
  104. auto orient2d = [](const Math::Vec2<Fix12P4>& vtx1,
  105. const Math::Vec2<Fix12P4>& vtx2,
  106. const Math::Vec2<Fix12P4>& vtx3) {
  107. const auto vec1 = Math::MakeVec(vtx2 - vtx1, 0);
  108. const auto vec2 = Math::MakeVec(vtx3 - vtx1, 0);
  109. // TODO: There is a very small chance this will overflow for sizeof(int) == 4
  110. return Math::Cross(vec1, vec2).z;
  111. };
  112. int w0 = bias0 + orient2d(vtxpos[1].xy(), vtxpos[2].xy(), {x, y});
  113. int w1 = bias1 + orient2d(vtxpos[2].xy(), vtxpos[0].xy(), {x, y});
  114. int w2 = bias2 + orient2d(vtxpos[0].xy(), vtxpos[1].xy(), {x, y});
  115. int wsum = w0 + w1 + w2;
  116. // If current pixel is not covered by the current primitive
  117. if (w0 < 0 || w1 < 0 || w2 < 0)
  118. continue;
  119. auto baricentric_coordinates = Math::MakeVec(float24::FromFloat32(static_cast<float>(w0)),
  120. float24::FromFloat32(static_cast<float>(w1)),
  121. float24::FromFloat32(static_cast<float>(w2)));
  122. float24 interpolated_w_inverse = float24::FromFloat32(1.0f) / Math::Dot(w_inverse, baricentric_coordinates);
  123. // Perspective correct attribute interpolation:
  124. // Attribute values cannot be calculated by simple linear interpolation since
  125. // they are not linear in screen space. For example, when interpolating a
  126. // texture coordinate across two vertices, something simple like
  127. // u = (u0*w0 + u1*w1)/(w0+w1)
  128. // will not work. However, the attribute value divided by the
  129. // clipspace w-coordinate (u/w) and and the inverse w-coordinate (1/w) are linear
  130. // in screenspace. Hence, we can linearly interpolate these two independently and
  131. // calculate the interpolated attribute by dividing the results.
  132. // I.e.
  133. // u_over_w = ((u0/v0.pos.w)*w0 + (u1/v1.pos.w)*w1)/(w0+w1)
  134. // one_over_w = (( 1/v0.pos.w)*w0 + ( 1/v1.pos.w)*w1)/(w0+w1)
  135. // u = u_over_w / one_over_w
  136. //
  137. // The generalization to three vertices is straightforward in baricentric coordinates.
  138. auto GetInterpolatedAttribute = [&](float24 attr0, float24 attr1, float24 attr2) {
  139. auto attr_over_w = Math::MakeVec(attr0, attr1, attr2);
  140. float24 interpolated_attr_over_w = Math::Dot(attr_over_w, baricentric_coordinates);
  141. return interpolated_attr_over_w * interpolated_w_inverse;
  142. };
  143. Math::Vec4<u8> primary_color{
  144. (u8)(GetInterpolatedAttribute(v0.color.r(), v1.color.r(), v2.color.r()).ToFloat32() * 255),
  145. (u8)(GetInterpolatedAttribute(v0.color.g(), v1.color.g(), v2.color.g()).ToFloat32() * 255),
  146. (u8)(GetInterpolatedAttribute(v0.color.b(), v1.color.b(), v2.color.b()).ToFloat32() * 255),
  147. (u8)(GetInterpolatedAttribute(v0.color.a(), v1.color.a(), v2.color.a()).ToFloat32() * 255)
  148. };
  149. Math::Vec2<float24> uv[3];
  150. uv[0].u() = GetInterpolatedAttribute(v0.tc0.u(), v1.tc0.u(), v2.tc0.u());
  151. uv[0].v() = GetInterpolatedAttribute(v0.tc0.v(), v1.tc0.v(), v2.tc0.v());
  152. uv[1].u() = GetInterpolatedAttribute(v0.tc1.u(), v1.tc1.u(), v2.tc1.u());
  153. uv[1].v() = GetInterpolatedAttribute(v0.tc1.v(), v1.tc1.v(), v2.tc1.v());
  154. uv[2].u() = GetInterpolatedAttribute(v0.tc2.u(), v1.tc2.u(), v2.tc2.u());
  155. uv[2].v() = GetInterpolatedAttribute(v0.tc2.v(), v1.tc2.v(), v2.tc2.v());
  156. Math::Vec4<u8> texture_color[3]{};
  157. for (int i = 0; i < 3; ++i) {
  158. const auto& texture = textures[i];
  159. if (!texture.enabled)
  160. continue;
  161. _dbg_assert_(HW_GPU, 0 != texture.config.address);
  162. int s = (int)(uv[i].u() * float24::FromFloat32(static_cast<float>(texture.config.width))).ToFloat32();
  163. int t = (int)(uv[i].v() * float24::FromFloat32(static_cast<float>(texture.config.height))).ToFloat32();
  164. auto GetWrappedTexCoord = [](Regs::TextureConfig::WrapMode mode, int val, unsigned size) {
  165. switch (mode) {
  166. case Regs::TextureConfig::ClampToEdge:
  167. val = std::max(val, 0);
  168. val = std::min(val, (int)size - 1);
  169. return val;
  170. case Regs::TextureConfig::Repeat:
  171. return (int)(((unsigned)val) % size);
  172. default:
  173. LOG_ERROR(HW_GPU, "Unknown texture coordinate wrapping mode %x\n", (int)mode);
  174. _dbg_assert_(HW_GPU, 0);
  175. return 0;
  176. }
  177. };
  178. s = GetWrappedTexCoord(registers.texture0.wrap_s, s, registers.texture0.width);
  179. t = registers.texture0.height - 1 - GetWrappedTexCoord(registers.texture0.wrap_t, t, registers.texture0.height);
  180. u8* texture_data = Memory::GetPointer(PAddrToVAddr(texture.config.GetPhysicalAddress()));
  181. auto info = DebugUtils::TextureInfo::FromPicaRegister(texture.config, texture.format);
  182. texture_color[i] = DebugUtils::LookupTexture(texture_data, s, t, info);
  183. DebugUtils::DumpTexture(texture.config, texture_data);
  184. }
  185. // Texture environment - consists of 6 stages of color and alpha combining.
  186. //
  187. // Color combiners take three input color values from some source (e.g. interpolated
  188. // vertex color, texture color, previous stage, etc), perform some very simple
  189. // operations on each of them (e.g. inversion) and then calculate the output color
  190. // with some basic arithmetic. Alpha combiners can be configured separately but work
  191. // analogously.
  192. Math::Vec4<u8> combiner_output;
  193. for (const auto& tev_stage : tev_stages) {
  194. using Source = Regs::TevStageConfig::Source;
  195. using ColorModifier = Regs::TevStageConfig::ColorModifier;
  196. using AlphaModifier = Regs::TevStageConfig::AlphaModifier;
  197. using Operation = Regs::TevStageConfig::Operation;
  198. auto GetColorSource = [&](Source source) -> Math::Vec4<u8> {
  199. switch (source) {
  200. case Source::PrimaryColor:
  201. return primary_color;
  202. case Source::Texture0:
  203. return texture_color[0];
  204. case Source::Texture1:
  205. return texture_color[1];
  206. case Source::Texture2:
  207. return texture_color[2];
  208. case Source::Constant:
  209. return {tev_stage.const_r, tev_stage.const_g, tev_stage.const_b, tev_stage.const_a};
  210. case Source::Previous:
  211. return combiner_output;
  212. default:
  213. LOG_ERROR(HW_GPU, "Unknown color combiner source %d\n", (int)source);
  214. _dbg_assert_(HW_GPU, 0);
  215. return {};
  216. }
  217. };
  218. auto GetAlphaSource = [&](Source source) -> u8 {
  219. switch (source) {
  220. case Source::PrimaryColor:
  221. return primary_color.a();
  222. case Source::Texture0:
  223. return texture_color[0].a();
  224. case Source::Texture1:
  225. return texture_color[1].a();
  226. case Source::Texture2:
  227. return texture_color[2].a();
  228. case Source::Constant:
  229. return tev_stage.const_a;
  230. case Source::Previous:
  231. return combiner_output.a();
  232. default:
  233. LOG_ERROR(HW_GPU, "Unknown alpha combiner source %d\n", (int)source);
  234. _dbg_assert_(HW_GPU, 0);
  235. return 0;
  236. }
  237. };
  238. static auto GetColorModifier = [](ColorModifier factor, const Math::Vec4<u8>& values) -> Math::Vec3<u8> {
  239. switch (factor)
  240. {
  241. case ColorModifier::SourceColor:
  242. return values.rgb();
  243. case ColorModifier::OneMinusSourceColor:
  244. return (Math::Vec3<u8>(255, 255, 255) - values.rgb()).Cast<u8>();
  245. case ColorModifier::SourceAlpha:
  246. return { values.a(), values.a(), values.a() };
  247. default:
  248. LOG_ERROR(HW_GPU, "Unknown color factor %d\n", (int)factor);
  249. _dbg_assert_(HW_GPU, 0);
  250. return {};
  251. }
  252. };
  253. static auto GetAlphaModifier = [](AlphaModifier factor, u8 value) -> u8 {
  254. switch (factor) {
  255. case AlphaModifier::SourceAlpha:
  256. return value;
  257. case AlphaModifier::OneMinusSourceAlpha:
  258. return 255 - value;
  259. default:
  260. LOG_ERROR(HW_GPU, "Unknown alpha factor %d\n", (int)factor);
  261. _dbg_assert_(HW_GPU, 0);
  262. return 0;
  263. }
  264. };
  265. static auto ColorCombine = [](Operation op, const Math::Vec3<u8> input[3]) -> Math::Vec3<u8> {
  266. switch (op) {
  267. case Operation::Replace:
  268. return input[0];
  269. case Operation::Modulate:
  270. return ((input[0] * input[1]) / 255).Cast<u8>();
  271. case Operation::Add:
  272. {
  273. auto result = input[0] + input[1];
  274. result.r() = std::min(255, result.r());
  275. result.g() = std::min(255, result.g());
  276. result.b() = std::min(255, result.b());
  277. return result.Cast<u8>();
  278. }
  279. case Operation::Lerp:
  280. return ((input[0] * input[2] + input[1] * (Math::MakeVec<u8>(255, 255, 255) - input[2]).Cast<u8>()) / 255).Cast<u8>();
  281. case Operation::Subtract:
  282. {
  283. auto result = input[0].Cast<int>() - input[1].Cast<int>();
  284. result.r() = std::max(0, result.r());
  285. result.g() = std::max(0, result.g());
  286. result.b() = std::max(0, result.b());
  287. return result.Cast<u8>();
  288. }
  289. default:
  290. LOG_ERROR(HW_GPU, "Unknown color combiner operation %d\n", (int)op);
  291. _dbg_assert_(HW_GPU, 0);
  292. return {};
  293. }
  294. };
  295. static auto AlphaCombine = [](Operation op, const std::array<u8,3>& input) -> u8 {
  296. switch (op) {
  297. case Operation::Replace:
  298. return input[0];
  299. case Operation::Modulate:
  300. return input[0] * input[1] / 255;
  301. case Operation::Add:
  302. return std::min(255, input[0] + input[1]);
  303. case Operation::Lerp:
  304. return (input[0] * input[2] + input[1] * (255 - input[2])) / 255;
  305. case Operation::Subtract:
  306. return std::max(0, (int)input[0] - (int)input[1]);
  307. default:
  308. LOG_ERROR(HW_GPU, "Unknown alpha combiner operation %d\n", (int)op);
  309. _dbg_assert_(HW_GPU, 0);
  310. return 0;
  311. }
  312. };
  313. // color combiner
  314. // NOTE: Not sure if the alpha combiner might use the color output of the previous
  315. // stage as input. Hence, we currently don't directly write the result to
  316. // combiner_output.rgb(), but instead store it in a temporary variable until
  317. // alpha combining has been done.
  318. Math::Vec3<u8> color_result[3] = {
  319. GetColorModifier(tev_stage.color_modifier1, GetColorSource(tev_stage.color_source1)),
  320. GetColorModifier(tev_stage.color_modifier2, GetColorSource(tev_stage.color_source2)),
  321. GetColorModifier(tev_stage.color_modifier3, GetColorSource(tev_stage.color_source3))
  322. };
  323. auto color_output = ColorCombine(tev_stage.color_op, color_result);
  324. // alpha combiner
  325. std::array<u8,3> alpha_result = {
  326. GetAlphaModifier(tev_stage.alpha_modifier1, GetAlphaSource(tev_stage.alpha_source1)),
  327. GetAlphaModifier(tev_stage.alpha_modifier2, GetAlphaSource(tev_stage.alpha_source2)),
  328. GetAlphaModifier(tev_stage.alpha_modifier3, GetAlphaSource(tev_stage.alpha_source3))
  329. };
  330. auto alpha_output = AlphaCombine(tev_stage.alpha_op, alpha_result);
  331. combiner_output = Math::MakeVec(color_output, alpha_output);
  332. }
  333. // TODO: Does depth indeed only get written even if depth testing is enabled?
  334. if (registers.output_merger.depth_test_enable) {
  335. u16 z = (u16)(-((float)v0.screenpos[2].ToFloat32() * w0 +
  336. (float)v1.screenpos[2].ToFloat32() * w1 +
  337. (float)v2.screenpos[2].ToFloat32() * w2) * 65535.f / wsum);
  338. u16 ref_z = GetDepth(x >> 4, y >> 4);
  339. bool pass = false;
  340. switch (registers.output_merger.depth_test_func) {
  341. case registers.output_merger.Always:
  342. pass = true;
  343. break;
  344. case registers.output_merger.LessThan:
  345. pass = z < ref_z;
  346. break;
  347. case registers.output_merger.GreaterThan:
  348. pass = z > ref_z;
  349. break;
  350. default:
  351. LOG_ERROR(HW_GPU, "Unknown depth test function %x", registers.output_merger.depth_test_func.Value());
  352. break;
  353. }
  354. if (!pass)
  355. continue;
  356. if (registers.output_merger.depth_write_enable)
  357. SetDepth(x >> 4, y >> 4, z);
  358. }
  359. auto dest = GetPixel(x >> 4, y >> 4);
  360. if (registers.output_merger.alphablend_enable) {
  361. auto params = registers.output_merger.alpha_blending;
  362. auto LookupFactorRGB = [&](decltype(params)::BlendFactor factor) -> Math::Vec3<u8> {
  363. switch(factor) {
  364. case params.Zero:
  365. return Math::Vec3<u8>(0, 0, 0);
  366. case params.One:
  367. return Math::Vec3<u8>(255, 255, 255);
  368. case params.SourceAlpha:
  369. return Math::MakeVec(combiner_output.a(), combiner_output.a(), combiner_output.a());
  370. case params.OneMinusSourceAlpha:
  371. return Math::Vec3<u8>(255-combiner_output.a(), 255-combiner_output.a(), 255-combiner_output.a());
  372. default:
  373. LOG_CRITICAL(HW_GPU, "Unknown color blend factor %x", factor);
  374. exit(0);
  375. break;
  376. }
  377. };
  378. auto LookupFactorA = [&](decltype(params)::BlendFactor factor) -> u8 {
  379. switch(factor) {
  380. case params.Zero:
  381. return 0;
  382. case params.One:
  383. return 255;
  384. case params.SourceAlpha:
  385. return combiner_output.a();
  386. case params.OneMinusSourceAlpha:
  387. return 255 - combiner_output.a();
  388. default:
  389. LOG_CRITICAL(HW_GPU, "Unknown alpha blend factor %x", factor);
  390. exit(0);
  391. break;
  392. }
  393. };
  394. auto srcfactor = Math::MakeVec(LookupFactorRGB(params.factor_source_rgb),
  395. LookupFactorA(params.factor_source_a));
  396. auto dstfactor = Math::MakeVec(LookupFactorRGB(params.factor_dest_rgb),
  397. LookupFactorA(params.factor_dest_a));
  398. switch (params.blend_equation_rgb) {
  399. case params.Add:
  400. {
  401. auto result = (combiner_output * srcfactor + dest * dstfactor) / 255;
  402. result.r() = std::min(255, result.r());
  403. result.g() = std::min(255, result.g());
  404. result.b() = std::min(255, result.b());
  405. combiner_output = result.Cast<u8>();
  406. break;
  407. }
  408. default:
  409. LOG_CRITICAL(HW_GPU, "Unknown RGB blend equation %x", params.blend_equation_rgb.Value());
  410. exit(0);
  411. }
  412. } else {
  413. LOG_CRITICAL(HW_GPU, "logic op: %x", registers.output_merger.logic_op);
  414. exit(0);
  415. }
  416. DrawPixel(x >> 4, y >> 4, combiner_output);
  417. }
  418. }
  419. }
  420. } // namespace Rasterizer
  421. } // namespace Pica