Device.cpp 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335
  1. /*
  2. * Copyright (c) 2021, Stephan Unverwerth <s.unverwerth@serenityos.org>
  3. * Copyright (c) 2021, Jesse Buhagiar <jooster669@gmail.com>
  4. * Copyright (c) 2022, Jelle Raaijmakers <jelle@gmta.nl>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/Math.h>
  9. #include <AK/NumericLimits.h>
  10. #include <AK/SIMDExtras.h>
  11. #include <AK/SIMDMath.h>
  12. #include <LibCore/ElapsedTimer.h>
  13. #include <LibGfx/Painter.h>
  14. #include <LibGfx/Vector2.h>
  15. #include <LibGfx/Vector3.h>
  16. #include <LibSoftGPU/Config.h>
  17. #include <LibSoftGPU/Device.h>
  18. #include <LibSoftGPU/PixelQuad.h>
  19. #include <LibSoftGPU/SIMD.h>
  20. #include <math.h>
  21. namespace SoftGPU {
  22. static long long g_num_rasterized_triangles;
  23. static long long g_num_pixels;
  24. static long long g_num_pixels_shaded;
  25. static long long g_num_pixels_blended;
  26. static long long g_num_sampler_calls;
  27. static long long g_num_stencil_writes;
  28. static long long g_num_quads;
  29. using IntVector2 = Gfx::Vector2<int>;
  30. using IntVector3 = Gfx::Vector3<int>;
  31. using AK::SIMD::any;
  32. using AK::SIMD::exp;
  33. using AK::SIMD::expand4;
  34. using AK::SIMD::f32x4;
  35. using AK::SIMD::i32x4;
  36. using AK::SIMD::load4_masked;
  37. using AK::SIMD::maskbits;
  38. using AK::SIMD::maskcount;
  39. using AK::SIMD::none;
  40. using AK::SIMD::store4_masked;
  41. using AK::SIMD::to_f32x4;
  42. using AK::SIMD::to_u32x4;
  43. using AK::SIMD::u32x4;
  44. constexpr static int edge_function(const IntVector2& a, const IntVector2& b, const IntVector2& c)
  45. {
  46. return ((c.x() - a.x()) * (b.y() - a.y()) - (c.y() - a.y()) * (b.x() - a.x()));
  47. }
  48. constexpr static i32x4 edge_function4(const IntVector2& a, const IntVector2& b, const Vector2<i32x4>& c)
  49. {
  50. return ((c.x() - a.x()) * (b.y() - a.y()) - (c.y() - a.y()) * (b.x() - a.x()));
  51. }
  52. template<typename T, typename U>
  53. constexpr static auto interpolate(const T& v0, const T& v1, const T& v2, const Vector3<U>& barycentric_coords)
  54. {
  55. return v0 * barycentric_coords.x() + v1 * barycentric_coords.y() + v2 * barycentric_coords.z();
  56. }
  57. static ColorType to_bgra32(FloatVector4 const& color)
  58. {
  59. auto clamped = color.clamped(0.0f, 1.0f);
  60. auto r = static_cast<u8>(clamped.x() * 255);
  61. auto g = static_cast<u8>(clamped.y() * 255);
  62. auto b = static_cast<u8>(clamped.z() * 255);
  63. auto a = static_cast<u8>(clamped.w() * 255);
  64. return a << 24 | r << 16 | g << 8 | b;
  65. }
  66. ALWAYS_INLINE static u32x4 to_bgra32(Vector4<f32x4> const& v)
  67. {
  68. auto clamped = v.clamped(expand4(0.0f), expand4(1.0f));
  69. auto r = to_u32x4(clamped.x() * 255);
  70. auto g = to_u32x4(clamped.y() * 255);
  71. auto b = to_u32x4(clamped.z() * 255);
  72. auto a = to_u32x4(clamped.w() * 255);
  73. return a << 24 | r << 16 | g << 8 | b;
  74. }
  75. static Vector4<f32x4> to_vec4(u32x4 bgra)
  76. {
  77. auto constexpr one_over_255 = expand4(1.0f / 255);
  78. return {
  79. to_f32x4((bgra >> 16) & 0xff) * one_over_255,
  80. to_f32x4((bgra >> 8) & 0xff) * one_over_255,
  81. to_f32x4(bgra & 0xff) * one_over_255,
  82. to_f32x4((bgra >> 24) & 0xff) * one_over_255,
  83. };
  84. }
  85. void Device::setup_blend_factors()
  86. {
  87. m_alpha_blend_factors = {};
  88. switch (m_options.blend_source_factor) {
  89. case BlendFactor::Zero:
  90. break;
  91. case BlendFactor::One:
  92. m_alpha_blend_factors.src_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  93. break;
  94. case BlendFactor::SrcColor:
  95. m_alpha_blend_factors.src_factor_src_color = 1;
  96. break;
  97. case BlendFactor::OneMinusSrcColor:
  98. m_alpha_blend_factors.src_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  99. m_alpha_blend_factors.src_factor_src_color = -1;
  100. break;
  101. case BlendFactor::SrcAlpha:
  102. m_alpha_blend_factors.src_factor_src_alpha = 1;
  103. break;
  104. case BlendFactor::OneMinusSrcAlpha:
  105. m_alpha_blend_factors.src_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  106. m_alpha_blend_factors.src_factor_src_alpha = -1;
  107. break;
  108. case BlendFactor::DstAlpha:
  109. m_alpha_blend_factors.src_factor_dst_alpha = 1;
  110. break;
  111. case BlendFactor::OneMinusDstAlpha:
  112. m_alpha_blend_factors.src_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  113. m_alpha_blend_factors.src_factor_dst_alpha = -1;
  114. break;
  115. case BlendFactor::DstColor:
  116. m_alpha_blend_factors.src_factor_dst_color = 1;
  117. break;
  118. case BlendFactor::OneMinusDstColor:
  119. m_alpha_blend_factors.src_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  120. m_alpha_blend_factors.src_factor_dst_color = -1;
  121. break;
  122. case BlendFactor::SrcAlphaSaturate:
  123. default:
  124. VERIFY_NOT_REACHED();
  125. }
  126. switch (m_options.blend_destination_factor) {
  127. case BlendFactor::Zero:
  128. break;
  129. case BlendFactor::One:
  130. m_alpha_blend_factors.dst_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  131. break;
  132. case BlendFactor::SrcColor:
  133. m_alpha_blend_factors.dst_factor_src_color = 1;
  134. break;
  135. case BlendFactor::OneMinusSrcColor:
  136. m_alpha_blend_factors.dst_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  137. m_alpha_blend_factors.dst_factor_src_color = -1;
  138. break;
  139. case BlendFactor::SrcAlpha:
  140. m_alpha_blend_factors.dst_factor_src_alpha = 1;
  141. break;
  142. case BlendFactor::OneMinusSrcAlpha:
  143. m_alpha_blend_factors.dst_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  144. m_alpha_blend_factors.dst_factor_src_alpha = -1;
  145. break;
  146. case BlendFactor::DstAlpha:
  147. m_alpha_blend_factors.dst_factor_dst_alpha = 1;
  148. break;
  149. case BlendFactor::OneMinusDstAlpha:
  150. m_alpha_blend_factors.dst_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  151. m_alpha_blend_factors.dst_factor_dst_alpha = -1;
  152. break;
  153. case BlendFactor::DstColor:
  154. m_alpha_blend_factors.dst_factor_dst_color = 1;
  155. break;
  156. case BlendFactor::OneMinusDstColor:
  157. m_alpha_blend_factors.dst_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  158. m_alpha_blend_factors.dst_factor_dst_color = -1;
  159. break;
  160. case BlendFactor::SrcAlphaSaturate:
  161. default:
  162. VERIFY_NOT_REACHED();
  163. }
  164. }
  165. void Device::rasterize_triangle(const Triangle& triangle)
  166. {
  167. INCREASE_STATISTICS_COUNTER(g_num_rasterized_triangles, 1);
  168. // Return if alpha testing is a no-op
  169. if (m_options.enable_alpha_test && m_options.alpha_test_func == AlphaTestFunction::Never)
  170. return;
  171. // Vertices
  172. Vertex const vertex0 = triangle.vertices[0];
  173. Vertex const vertex1 = triangle.vertices[1];
  174. Vertex const vertex2 = triangle.vertices[2];
  175. constexpr int subpixel_factor = 1 << SUBPIXEL_BITS;
  176. // Calculate area of the triangle for later tests
  177. IntVector2 const v0 { static_cast<int>(vertex0.window_coordinates.x() * subpixel_factor), static_cast<int>(vertex0.window_coordinates.y() * subpixel_factor) };
  178. IntVector2 const v1 { static_cast<int>(vertex1.window_coordinates.x() * subpixel_factor), static_cast<int>(vertex1.window_coordinates.y() * subpixel_factor) };
  179. IntVector2 const v2 { static_cast<int>(vertex2.window_coordinates.x() * subpixel_factor), static_cast<int>(vertex2.window_coordinates.y() * subpixel_factor) };
  180. int area = edge_function(v0, v1, v2);
  181. if (area == 0)
  182. return;
  183. auto const one_over_area = 1.0f / area;
  184. auto render_bounds = m_frame_buffer->rect();
  185. if (m_options.scissor_enabled)
  186. render_bounds.intersect(m_options.scissor_box);
  187. // Obey top-left rule:
  188. // This sets up "zero" for later pixel coverage tests.
  189. // Depending on where on the triangle the edge is located
  190. // it is either tested against 0 or 1, effectively
  191. // turning "< 0" into "<= 0"
  192. IntVector3 zero { 1, 1, 1 };
  193. if (v1.y() > v0.y() || (v1.y() == v0.y() && v1.x() < v0.x()))
  194. zero.set_z(0);
  195. if (v2.y() > v1.y() || (v2.y() == v1.y() && v2.x() < v1.x()))
  196. zero.set_x(0);
  197. if (v0.y() > v2.y() || (v0.y() == v2.y() && v0.x() < v2.x()))
  198. zero.set_y(0);
  199. // This function calculates the 3 edge values for the pixel relative to the triangle.
  200. auto calculate_edge_values4 = [v0, v1, v2](Vector2<i32x4> const& p) -> Vector3<i32x4> {
  201. return {
  202. edge_function4(v1, v2, p),
  203. edge_function4(v2, v0, p),
  204. edge_function4(v0, v1, p),
  205. };
  206. };
  207. // This function tests whether a point as identified by its 3 edge values lies within the triangle
  208. auto test_point4 = [zero](Vector3<i32x4> const& edges) -> i32x4 {
  209. return edges.x() >= zero.x()
  210. && edges.y() >= zero.y()
  211. && edges.z() >= zero.z();
  212. };
  213. // Calculate block-based bounds
  214. // clang-format off
  215. int const bx0 = max(render_bounds.left(), min(min(v0.x(), v1.x()), v2.x()) / subpixel_factor) & ~1;
  216. int const bx1 = (min(render_bounds.right(), max(max(v0.x(), v1.x()), v2.x()) / subpixel_factor) & ~1) + 2;
  217. int const by0 = max(render_bounds.top(), min(min(v0.y(), v1.y()), v2.y()) / subpixel_factor) & ~1;
  218. int const by1 = (min(render_bounds.bottom(), max(max(v0.y(), v1.y()), v2.y()) / subpixel_factor) & ~1) + 2;
  219. // clang-format on
  220. // Fog depths
  221. float const vertex0_eye_absz = fabsf(vertex0.eye_coordinates.z());
  222. float const vertex1_eye_absz = fabsf(vertex1.eye_coordinates.z());
  223. float const vertex2_eye_absz = fabsf(vertex2.eye_coordinates.z());
  224. int const render_bounds_left = render_bounds.x();
  225. int const render_bounds_right = render_bounds.x() + render_bounds.width();
  226. int const render_bounds_top = render_bounds.y();
  227. int const render_bounds_bottom = render_bounds.y() + render_bounds.height();
  228. auto const half_pixel_offset = Vector2<i32x4> {
  229. expand4(subpixel_factor / 2),
  230. expand4(subpixel_factor / 2),
  231. };
  232. auto color_buffer = m_frame_buffer->color_buffer();
  233. auto depth_buffer = m_frame_buffer->depth_buffer();
  234. auto stencil_buffer = m_frame_buffer->stencil_buffer();
  235. // Stencil configuration and writing
  236. auto const stencil_configuration = m_stencil_configuration[Face::Front];
  237. auto const stencil_reference_value = stencil_configuration.reference_value & stencil_configuration.test_mask;
  238. auto write_to_stencil = [](StencilType* stencil_ptrs[4], i32x4 stencil_value, StencilOperation op, StencilType reference_value, StencilType write_mask, i32x4 pixel_mask) {
  239. if (write_mask == 0 || op == StencilOperation::Keep)
  240. return;
  241. switch (op) {
  242. case StencilOperation::Decrement:
  243. stencil_value = (stencil_value & ~write_mask) | (max(stencil_value - 1, expand4(0)) & write_mask);
  244. break;
  245. case StencilOperation::DecrementWrap:
  246. stencil_value = (stencil_value & ~write_mask) | (((stencil_value - 1) & 0xFF) & write_mask);
  247. break;
  248. case StencilOperation::Increment:
  249. stencil_value = (stencil_value & ~write_mask) | (min(stencil_value + 1, expand4(0xFF)) & write_mask);
  250. break;
  251. case StencilOperation::IncrementWrap:
  252. stencil_value = (stencil_value & ~write_mask) | (((stencil_value + 1) & 0xFF) & write_mask);
  253. break;
  254. case StencilOperation::Invert:
  255. stencil_value ^= write_mask;
  256. break;
  257. case StencilOperation::Replace:
  258. stencil_value = (stencil_value & ~write_mask) | (reference_value & write_mask);
  259. break;
  260. case StencilOperation::Zero:
  261. stencil_value &= ~write_mask;
  262. break;
  263. default:
  264. VERIFY_NOT_REACHED();
  265. }
  266. INCREASE_STATISTICS_COUNTER(g_num_stencil_writes, maskcount(pixel_mask));
  267. store4_masked(stencil_value, stencil_ptrs[0], stencil_ptrs[1], stencil_ptrs[2], stencil_ptrs[3], pixel_mask);
  268. };
  269. // Iterate over all blocks within the bounds of the triangle
  270. for (int by = by0; by < by1; by += 2) {
  271. for (int bx = bx0; bx < bx1; bx += 2) {
  272. PixelQuad quad;
  273. quad.screen_coordinates = {
  274. i32x4 { bx, bx + 1, bx, bx + 1 },
  275. i32x4 { by, by, by + 1, by + 1 },
  276. };
  277. auto edge_values = calculate_edge_values4(quad.screen_coordinates * subpixel_factor + half_pixel_offset);
  278. // Generate triangle coverage mask
  279. quad.mask = test_point4(edge_values);
  280. // Test quad against intersection of render target size and scissor rect
  281. quad.mask &= quad.screen_coordinates.x() >= render_bounds_left
  282. && quad.screen_coordinates.x() < render_bounds_right
  283. && quad.screen_coordinates.y() >= render_bounds_top
  284. && quad.screen_coordinates.y() < render_bounds_bottom;
  285. if (none(quad.mask))
  286. continue;
  287. INCREASE_STATISTICS_COUNTER(g_num_quads, 1);
  288. INCREASE_STATISTICS_COUNTER(g_num_pixels, maskcount(quad.mask));
  289. // Calculate barycentric coordinates from previously calculated edge values
  290. quad.barycentrics = Vector3<f32x4> {
  291. to_f32x4(edge_values.x()),
  292. to_f32x4(edge_values.y()),
  293. to_f32x4(edge_values.z()),
  294. } * one_over_area;
  295. int coverage_bits = maskbits(quad.mask);
  296. // Stencil testing
  297. StencilType* stencil_ptrs[4];
  298. i32x4 stencil_value;
  299. if (m_options.enable_stencil_test) {
  300. stencil_ptrs[0] = coverage_bits & 1 ? &stencil_buffer->scanline(by)[bx] : nullptr;
  301. stencil_ptrs[1] = coverage_bits & 2 ? &stencil_buffer->scanline(by)[bx + 1] : nullptr;
  302. stencil_ptrs[2] = coverage_bits & 4 ? &stencil_buffer->scanline(by + 1)[bx] : nullptr;
  303. stencil_ptrs[3] = coverage_bits & 8 ? &stencil_buffer->scanline(by + 1)[bx + 1] : nullptr;
  304. stencil_value = load4_masked(stencil_ptrs[0], stencil_ptrs[1], stencil_ptrs[2], stencil_ptrs[3], quad.mask);
  305. stencil_value &= stencil_configuration.test_mask;
  306. i32x4 stencil_test_passed;
  307. switch (stencil_configuration.test_function) {
  308. case StencilTestFunction::Always:
  309. stencil_test_passed = expand4(~0);
  310. break;
  311. case StencilTestFunction::Equal:
  312. stencil_test_passed = stencil_value == stencil_reference_value;
  313. break;
  314. case StencilTestFunction::Greater:
  315. stencil_test_passed = stencil_value > stencil_reference_value;
  316. break;
  317. case StencilTestFunction::GreaterOrEqual:
  318. stencil_test_passed = stencil_value >= stencil_reference_value;
  319. break;
  320. case StencilTestFunction::Less:
  321. stencil_test_passed = stencil_value < stencil_reference_value;
  322. break;
  323. case StencilTestFunction::LessOrEqual:
  324. stencil_test_passed = stencil_value <= stencil_reference_value;
  325. break;
  326. case StencilTestFunction::Never:
  327. stencil_test_passed = expand4(0);
  328. break;
  329. case StencilTestFunction::NotEqual:
  330. stencil_test_passed = stencil_value != stencil_reference_value;
  331. break;
  332. default:
  333. VERIFY_NOT_REACHED();
  334. }
  335. // Update stencil buffer for pixels that failed the stencil test
  336. write_to_stencil(
  337. stencil_ptrs,
  338. stencil_value,
  339. stencil_configuration.on_stencil_test_fail,
  340. stencil_reference_value,
  341. stencil_configuration.write_mask,
  342. quad.mask & ~stencil_test_passed);
  343. // Update coverage mask + early quad rejection
  344. quad.mask &= stencil_test_passed;
  345. if (none(quad.mask))
  346. continue;
  347. }
  348. // Depth testing
  349. DepthType* depth_ptrs[4] = {
  350. coverage_bits & 1 ? &depth_buffer->scanline(by)[bx] : nullptr,
  351. coverage_bits & 2 ? &depth_buffer->scanline(by)[bx + 1] : nullptr,
  352. coverage_bits & 4 ? &depth_buffer->scanline(by + 1)[bx] : nullptr,
  353. coverage_bits & 8 ? &depth_buffer->scanline(by + 1)[bx + 1] : nullptr,
  354. };
  355. if (m_options.enable_depth_test) {
  356. auto depth = load4_masked(depth_ptrs[0], depth_ptrs[1], depth_ptrs[2], depth_ptrs[3], quad.mask);
  357. quad.depth = interpolate(vertex0.window_coordinates.z(), vertex1.window_coordinates.z(), vertex2.window_coordinates.z(), quad.barycentrics);
  358. // FIXME: Also apply depth_offset_factor which depends on the depth gradient
  359. if (m_options.depth_offset_enabled)
  360. quad.depth += m_options.depth_offset_constant * NumericLimits<float>::epsilon();
  361. i32x4 depth_test_passed;
  362. switch (m_options.depth_func) {
  363. case DepthTestFunction::Always:
  364. depth_test_passed = expand4(~0);
  365. break;
  366. case DepthTestFunction::Never:
  367. depth_test_passed = expand4(0);
  368. break;
  369. case DepthTestFunction::Greater:
  370. depth_test_passed = quad.depth > depth;
  371. break;
  372. case DepthTestFunction::GreaterOrEqual:
  373. depth_test_passed = quad.depth >= depth;
  374. break;
  375. case DepthTestFunction::NotEqual:
  376. #ifdef __SSE__
  377. depth_test_passed = quad.depth != depth;
  378. #else
  379. depth_test_passed = i32x4 {
  380. bit_cast<u32>(quad.depth[0]) != bit_cast<u32>(depth[0]) ? -1 : 0,
  381. bit_cast<u32>(quad.depth[1]) != bit_cast<u32>(depth[1]) ? -1 : 0,
  382. bit_cast<u32>(quad.depth[2]) != bit_cast<u32>(depth[2]) ? -1 : 0,
  383. bit_cast<u32>(quad.depth[3]) != bit_cast<u32>(depth[3]) ? -1 : 0,
  384. };
  385. #endif
  386. break;
  387. case DepthTestFunction::Equal:
  388. #ifdef __SSE__
  389. depth_test_passed = quad.depth == depth;
  390. #else
  391. //
  392. // This is an interesting quirk that occurs due to us using the x87 FPU when Serenity is
  393. // compiled for the i386 target. When we calculate our depth value to be stored in the buffer,
  394. // it is an 80-bit x87 floating point number, however, when stored into the depth buffer, this is
  395. // truncated to 32 bits. This 38 bit loss of precision means that when x87 `FCOMP` is eventually
  396. // used here the comparison fails.
  397. // This could be solved by using a `long double` for the depth buffer, however this would take
  398. // up significantly more space and is completely overkill for a depth buffer. As such, comparing
  399. // the first 32-bits of this depth value is "good enough" that if we get a hit on it being
  400. // equal, we can pretty much guarantee that it's actually equal.
  401. //
  402. depth_test_passed = i32x4 {
  403. bit_cast<u32>(quad.depth[0]) == bit_cast<u32>(depth[0]) ? -1 : 0,
  404. bit_cast<u32>(quad.depth[1]) == bit_cast<u32>(depth[1]) ? -1 : 0,
  405. bit_cast<u32>(quad.depth[2]) == bit_cast<u32>(depth[2]) ? -1 : 0,
  406. bit_cast<u32>(quad.depth[3]) == bit_cast<u32>(depth[3]) ? -1 : 0,
  407. };
  408. #endif
  409. break;
  410. case DepthTestFunction::LessOrEqual:
  411. depth_test_passed = quad.depth <= depth;
  412. break;
  413. case DepthTestFunction::Less:
  414. depth_test_passed = quad.depth < depth;
  415. break;
  416. default:
  417. VERIFY_NOT_REACHED();
  418. }
  419. // Update stencil buffer for pixels that failed the depth test
  420. if (m_options.enable_stencil_test) {
  421. write_to_stencil(
  422. stencil_ptrs,
  423. stencil_value,
  424. stencil_configuration.on_depth_test_fail,
  425. stencil_reference_value,
  426. stencil_configuration.write_mask,
  427. quad.mask & ~depth_test_passed);
  428. }
  429. // Update coverage mask + early quad rejection
  430. quad.mask &= depth_test_passed;
  431. if (none(quad.mask))
  432. continue;
  433. }
  434. // Update stencil buffer for passed pixels
  435. if (m_options.enable_stencil_test) {
  436. write_to_stencil(
  437. stencil_ptrs,
  438. stencil_value,
  439. stencil_configuration.on_pass,
  440. stencil_reference_value,
  441. stencil_configuration.write_mask,
  442. quad.mask);
  443. }
  444. INCREASE_STATISTICS_COUNTER(g_num_pixels_shaded, maskcount(quad.mask));
  445. // Draw the pixels according to the previously generated mask
  446. auto const w_coordinates = Vector3<f32x4> {
  447. expand4(vertex0.window_coordinates.w()),
  448. expand4(vertex1.window_coordinates.w()),
  449. expand4(vertex2.window_coordinates.w()),
  450. };
  451. auto const interpolated_reciprocal_w = interpolate(w_coordinates.x(), w_coordinates.y(), w_coordinates.z(), quad.barycentrics);
  452. auto const interpolated_w = 1.0f / interpolated_reciprocal_w;
  453. quad.barycentrics = quad.barycentrics * w_coordinates * interpolated_w;
  454. // FIXME: make this more generic. We want to interpolate more than just color and uv
  455. if (m_options.shade_smooth)
  456. quad.vertex_color = interpolate(expand4(vertex0.color), expand4(vertex1.color), expand4(vertex2.color), quad.barycentrics);
  457. else
  458. quad.vertex_color = expand4(vertex0.color);
  459. for (size_t i = 0; i < NUM_SAMPLERS; ++i)
  460. quad.texture_coordinates[i] = interpolate(expand4(vertex0.tex_coords[i]), expand4(vertex1.tex_coords[i]), expand4(vertex2.tex_coords[i]), quad.barycentrics);
  461. if (m_options.fog_enabled) {
  462. // Calculate depth of fragment for fog
  463. //
  464. // OpenGL 1.5 spec chapter 3.10: "An implementation may choose to approximate the
  465. // eye-coordinate distance from the eye to each fragment center by |Ze|."
  466. quad.fog_depth = interpolate(expand4(vertex0_eye_absz), expand4(vertex1_eye_absz), expand4(vertex2_eye_absz), quad.barycentrics);
  467. }
  468. shade_fragments(quad);
  469. if (m_options.enable_alpha_test && m_options.alpha_test_func != AlphaTestFunction::Always && !test_alpha(quad))
  470. continue;
  471. // Write to depth buffer
  472. if (m_options.enable_depth_test && m_options.enable_depth_write)
  473. store4_masked(quad.depth, depth_ptrs[0], depth_ptrs[1], depth_ptrs[2], depth_ptrs[3], quad.mask);
  474. // We will not update the color buffer at all
  475. if ((m_options.color_mask == 0) || !m_options.enable_color_write)
  476. continue;
  477. ColorType* color_ptrs[4] = {
  478. coverage_bits & 1 ? &color_buffer->scanline(by)[bx] : nullptr,
  479. coverage_bits & 2 ? &color_buffer->scanline(by)[bx + 1] : nullptr,
  480. coverage_bits & 4 ? &color_buffer->scanline(by + 1)[bx] : nullptr,
  481. coverage_bits & 8 ? &color_buffer->scanline(by + 1)[bx + 1] : nullptr,
  482. };
  483. u32x4 dst_u32;
  484. if (m_options.enable_blending || m_options.color_mask != 0xffffffff)
  485. dst_u32 = load4_masked(color_ptrs[0], color_ptrs[1], color_ptrs[2], color_ptrs[3], quad.mask);
  486. if (m_options.enable_blending) {
  487. INCREASE_STATISTICS_COUNTER(g_num_pixels_blended, maskcount(quad.mask));
  488. // Blend color values from pixel_staging into color_buffer
  489. Vector4<f32x4> const& src = quad.out_color;
  490. auto dst = to_vec4(dst_u32);
  491. auto src_factor = expand4(m_alpha_blend_factors.src_constant)
  492. + src * m_alpha_blend_factors.src_factor_src_color
  493. + Vector4<f32x4> { src.w(), src.w(), src.w(), src.w() } * m_alpha_blend_factors.src_factor_src_alpha
  494. + dst * m_alpha_blend_factors.src_factor_dst_color
  495. + Vector4<f32x4> { dst.w(), dst.w(), dst.w(), dst.w() } * m_alpha_blend_factors.src_factor_dst_alpha;
  496. auto dst_factor = expand4(m_alpha_blend_factors.dst_constant)
  497. + src * m_alpha_blend_factors.dst_factor_src_color
  498. + Vector4<f32x4> { src.w(), src.w(), src.w(), src.w() } * m_alpha_blend_factors.dst_factor_src_alpha
  499. + dst * m_alpha_blend_factors.dst_factor_dst_color
  500. + Vector4<f32x4> { dst.w(), dst.w(), dst.w(), dst.w() } * m_alpha_blend_factors.dst_factor_dst_alpha;
  501. quad.out_color = src * src_factor + dst * dst_factor;
  502. }
  503. if (m_options.color_mask == 0xffffffff)
  504. store4_masked(to_bgra32(quad.out_color), color_ptrs[0], color_ptrs[1], color_ptrs[2], color_ptrs[3], quad.mask);
  505. else
  506. store4_masked((to_bgra32(quad.out_color) & m_options.color_mask) | (dst_u32 & ~m_options.color_mask), color_ptrs[0], color_ptrs[1], color_ptrs[2], color_ptrs[3], quad.mask);
  507. }
  508. }
  509. }
  510. Device::Device(Gfx::IntSize const& size)
  511. : m_frame_buffer(FrameBuffer<ColorType, DepthType, StencilType>::try_create(size).release_value_but_fixme_should_propagate_errors())
  512. {
  513. m_options.scissor_box = m_frame_buffer->rect();
  514. m_options.viewport = m_frame_buffer->rect();
  515. }
  516. DeviceInfo Device::info() const
  517. {
  518. return {
  519. .vendor_name = "SerenityOS",
  520. .device_name = "SoftGPU",
  521. .num_texture_units = NUM_SAMPLERS,
  522. .num_lights = NUM_LIGHTS,
  523. .stencil_bits = sizeof(StencilType) * 8,
  524. .supports_npot_textures = true,
  525. };
  526. }
  527. static void generate_texture_coordinates(Vertex& vertex, RasterizerOptions const& options)
  528. {
  529. auto generate_coordinate = [&](size_t texcoord_index, size_t config_index) -> float {
  530. auto mode = options.texcoord_generation_config[texcoord_index][config_index].mode;
  531. switch (mode) {
  532. case TexCoordGenerationMode::ObjectLinear: {
  533. auto coefficients = options.texcoord_generation_config[texcoord_index][config_index].coefficients;
  534. return coefficients.dot(vertex.position);
  535. }
  536. case TexCoordGenerationMode::EyeLinear: {
  537. auto coefficients = options.texcoord_generation_config[texcoord_index][config_index].coefficients;
  538. return coefficients.dot(vertex.eye_coordinates);
  539. }
  540. case TexCoordGenerationMode::SphereMap: {
  541. auto const eye_unit = vertex.eye_coordinates.normalized();
  542. FloatVector3 const eye_unit_xyz = { eye_unit.x(), eye_unit.y(), eye_unit.z() };
  543. auto const normal = vertex.normal;
  544. auto reflection = eye_unit_xyz - normal * 2 * normal.dot(eye_unit_xyz);
  545. reflection.set_z(reflection.z() + 1);
  546. auto const reflection_value = (config_index == 0) ? reflection.x() : reflection.y();
  547. return reflection_value / (2 * reflection.length()) + 0.5f;
  548. }
  549. case TexCoordGenerationMode::ReflectionMap: {
  550. auto const eye_unit = vertex.eye_coordinates.normalized();
  551. FloatVector3 const eye_unit_xyz = { eye_unit.x(), eye_unit.y(), eye_unit.z() };
  552. auto const normal = vertex.normal;
  553. auto reflection = eye_unit_xyz - normal * 2 * normal.dot(eye_unit_xyz);
  554. switch (config_index) {
  555. case 0:
  556. return reflection.x();
  557. case 1:
  558. return reflection.y();
  559. case 2:
  560. return reflection.z();
  561. default:
  562. VERIFY_NOT_REACHED();
  563. }
  564. }
  565. case TexCoordGenerationMode::NormalMap: {
  566. auto const normal = vertex.normal;
  567. switch (config_index) {
  568. case 0:
  569. return normal.x();
  570. case 1:
  571. return normal.y();
  572. case 2:
  573. return normal.z();
  574. default:
  575. VERIFY_NOT_REACHED();
  576. }
  577. }
  578. default:
  579. VERIFY_NOT_REACHED();
  580. }
  581. };
  582. for (size_t i = 0; i < vertex.tex_coords.size(); ++i) {
  583. auto& tex_coord = vertex.tex_coords[i];
  584. auto const enabled_coords = options.texcoord_generation_enabled_coordinates[i];
  585. tex_coord = {
  586. ((enabled_coords & TexCoordGenerationCoordinate::S) > 0) ? generate_coordinate(i, 0) : tex_coord.x(),
  587. ((enabled_coords & TexCoordGenerationCoordinate::T) > 0) ? generate_coordinate(i, 1) : tex_coord.y(),
  588. ((enabled_coords & TexCoordGenerationCoordinate::R) > 0) ? generate_coordinate(i, 2) : tex_coord.z(),
  589. ((enabled_coords & TexCoordGenerationCoordinate::Q) > 0) ? generate_coordinate(i, 3) : tex_coord.w(),
  590. };
  591. }
  592. }
  593. void Device::draw_primitives(PrimitiveType primitive_type, FloatMatrix4x4 const& model_view_transform, FloatMatrix3x3 const& normal_transform,
  594. FloatMatrix4x4 const& projection_transform, FloatMatrix4x4 const& texture_transform, Vector<Vertex> const& vertices,
  595. Vector<size_t> const& enabled_texture_units)
  596. {
  597. // At this point, the user has effectively specified that they are done with defining the geometry
  598. // of what they want to draw. We now need to do a few things (https://www.khronos.org/opengl/wiki/Rendering_Pipeline_Overview):
  599. //
  600. // 1. Transform all of the vertices in the current vertex list into eye space by multiplying the model-view matrix
  601. // 2. Transform all of the vertices from eye space into clip space by multiplying by the projection matrix
  602. // 3. If culling is enabled, we cull the desired faces (https://learnopengl.com/Advanced-OpenGL/Face-culling)
  603. // 4. Each element of the vertex is then divided by w to bring the positions into NDC (Normalized Device Coordinates)
  604. // 5. The vertices are sorted (for the rasterizer, how are we doing this? 3Dfx did this top to bottom in terms of vertex y coordinates)
  605. // 6. The vertices are then sent off to the rasterizer and drawn to the screen
  606. m_enabled_texture_units = enabled_texture_units;
  607. m_triangle_list.clear_with_capacity();
  608. m_processed_triangles.clear_with_capacity();
  609. // Let's construct some triangles
  610. if (primitive_type == PrimitiveType::Triangles) {
  611. Triangle triangle;
  612. if (vertices.size() < 3)
  613. return;
  614. for (size_t i = 0; i < vertices.size() - 2; i += 3) {
  615. triangle.vertices[0] = vertices.at(i);
  616. triangle.vertices[1] = vertices.at(i + 1);
  617. triangle.vertices[2] = vertices.at(i + 2);
  618. m_triangle_list.append(triangle);
  619. }
  620. } else if (primitive_type == PrimitiveType::Quads) {
  621. // We need to construct two triangles to form the quad
  622. Triangle triangle;
  623. if (vertices.size() < 4)
  624. return;
  625. for (size_t i = 0; i < vertices.size() - 3; i += 4) {
  626. // Triangle 1
  627. triangle.vertices[0] = vertices.at(i);
  628. triangle.vertices[1] = vertices.at(i + 1);
  629. triangle.vertices[2] = vertices.at(i + 2);
  630. m_triangle_list.append(triangle);
  631. // Triangle 2
  632. triangle.vertices[0] = vertices.at(i + 2);
  633. triangle.vertices[1] = vertices.at(i + 3);
  634. triangle.vertices[2] = vertices.at(i);
  635. m_triangle_list.append(triangle);
  636. }
  637. } else if (primitive_type == PrimitiveType::TriangleFan) {
  638. Triangle triangle;
  639. triangle.vertices[0] = vertices.at(0); // Root vertex is always the vertex defined first
  640. // This is technically `n-2` triangles. We start at index 1
  641. for (size_t i = 1; i < vertices.size() - 1; i++) {
  642. triangle.vertices[1] = vertices.at(i);
  643. triangle.vertices[2] = vertices.at(i + 1);
  644. m_triangle_list.append(triangle);
  645. }
  646. } else if (primitive_type == PrimitiveType::TriangleStrip) {
  647. Triangle triangle;
  648. if (vertices.size() < 3)
  649. return;
  650. for (size_t i = 0; i < vertices.size() - 2; i++) {
  651. if (i % 2 == 0) {
  652. triangle.vertices[0] = vertices.at(i);
  653. triangle.vertices[1] = vertices.at(i + 1);
  654. triangle.vertices[2] = vertices.at(i + 2);
  655. } else {
  656. triangle.vertices[0] = vertices.at(i + 1);
  657. triangle.vertices[1] = vertices.at(i);
  658. triangle.vertices[2] = vertices.at(i + 2);
  659. }
  660. m_triangle_list.append(triangle);
  661. }
  662. }
  663. // Now let's transform each triangle and send that to the GPU
  664. auto const viewport = m_options.viewport;
  665. auto const viewport_half_width = viewport.width() / 2.0f;
  666. auto const viewport_half_height = viewport.height() / 2.0f;
  667. auto const viewport_center_x = viewport.x() + viewport_half_width;
  668. auto const viewport_center_y = viewport.y() + viewport_half_height;
  669. auto const depth_half_range = (m_options.depth_max - m_options.depth_min) / 2;
  670. auto const depth_halfway = (m_options.depth_min + m_options.depth_max) / 2;
  671. for (auto& triangle : m_triangle_list) {
  672. // Transform vertices into eye coordinates using the model-view transform
  673. triangle.vertices[0].eye_coordinates = model_view_transform * triangle.vertices[0].position;
  674. triangle.vertices[1].eye_coordinates = model_view_transform * triangle.vertices[1].position;
  675. triangle.vertices[2].eye_coordinates = model_view_transform * triangle.vertices[2].position;
  676. // Transform the vertex normals into eye-space
  677. triangle.vertices[0].normal = transform_direction(model_view_transform, triangle.vertices[0].normal);
  678. triangle.vertices[1].normal = transform_direction(model_view_transform, triangle.vertices[1].normal);
  679. triangle.vertices[2].normal = transform_direction(model_view_transform, triangle.vertices[2].normal);
  680. // Calculate per-vertex lighting
  681. if (m_options.lighting_enabled) {
  682. auto const& material = m_materials.at(0);
  683. for (auto& vertex : triangle.vertices) {
  684. auto ambient = material.ambient;
  685. auto diffuse = material.diffuse;
  686. auto emissive = material.emissive;
  687. auto specular = material.specular;
  688. if (m_options.color_material_enabled
  689. && (m_options.color_material_face == ColorMaterialFace::Front || m_options.color_material_face == ColorMaterialFace::FrontAndBack)) {
  690. switch (m_options.color_material_mode) {
  691. case ColorMaterialMode::Ambient:
  692. ambient = vertex.color;
  693. break;
  694. case ColorMaterialMode::AmbientAndDiffuse:
  695. ambient = vertex.color;
  696. diffuse = vertex.color;
  697. break;
  698. case ColorMaterialMode::Diffuse:
  699. diffuse = vertex.color;
  700. break;
  701. case ColorMaterialMode::Emissive:
  702. emissive = vertex.color;
  703. break;
  704. case ColorMaterialMode::Specular:
  705. specular = vertex.color;
  706. break;
  707. }
  708. }
  709. FloatVector4 result_color = emissive + (ambient * m_lighting_model.scene_ambient_color);
  710. for (auto const& light : m_lights) {
  711. if (!light.is_enabled)
  712. continue;
  713. // We need to save the length here because the attenuation factor requires a non-normalized vector!
  714. auto sgi_arrow_operator = [](FloatVector4 const& p1, FloatVector4 const& p2, float& output_length) {
  715. FloatVector3 light_vector;
  716. if ((p1.w() != 0.f) && (p2.w() == 0.f))
  717. light_vector = p2.xyz();
  718. else if ((p1.w() == 0.f) && (p2.w() != 0.f))
  719. light_vector = -p1.xyz();
  720. else
  721. light_vector = p2.xyz() - p1.xyz();
  722. output_length = light_vector.length();
  723. if (output_length == 0.f)
  724. return light_vector;
  725. return light_vector / output_length;
  726. };
  727. auto sgi_dot_operator = [](FloatVector3 const& d1, FloatVector3 const& d2) {
  728. return AK::max(d1.dot(d2), 0.0f);
  729. };
  730. float vertex_to_light_length = 0.f;
  731. FloatVector3 vertex_to_light = sgi_arrow_operator(vertex.eye_coordinates, light.position, vertex_to_light_length);
  732. // Light attenuation value.
  733. float light_attenuation_factor = 1.0f;
  734. if (light.position.w() != 0.0f)
  735. light_attenuation_factor = 1.0f / (light.constant_attenuation + (light.linear_attenuation * vertex_to_light_length) + (light.quadratic_attenuation * vertex_to_light_length * vertex_to_light_length));
  736. // Spotlight factor
  737. float spotlight_factor = 1.0f;
  738. if (light.spotlight_cutoff_angle != 180.0f) {
  739. auto const vertex_to_light_dot_spotlight_direction = sgi_dot_operator(vertex_to_light, light.spotlight_direction.normalized());
  740. auto const cos_spotlight_cutoff = AK::cos<float>(light.spotlight_cutoff_angle * AK::Pi<float> / 180.f);
  741. if (vertex_to_light_dot_spotlight_direction >= cos_spotlight_cutoff)
  742. spotlight_factor = AK::pow<float>(vertex_to_light_dot_spotlight_direction, light.spotlight_exponent);
  743. else
  744. spotlight_factor = 0.0f;
  745. }
  746. // FIXME: The spec allows for splitting the colors calculated here into multiple different colors (primary/secondary color). Investigate what this means.
  747. (void)m_lighting_model.single_color;
  748. // FIXME: Two sided lighting should be implemented eventually (I believe this is where the normals are -ve and then lighting is calculated with the BACK material)
  749. (void)m_lighting_model.two_sided_lighting;
  750. // Ambient
  751. auto const ambient_component = ambient * light.ambient_intensity;
  752. // Diffuse
  753. auto const normal_dot_vertex_to_light = sgi_dot_operator(vertex.normal, vertex_to_light);
  754. auto const diffuse_component = ((diffuse * light.diffuse_intensity) * normal_dot_vertex_to_light);
  755. // Specular
  756. FloatVector4 specular_component = { 0.0f, 0.0f, 0.0f, 0.0f };
  757. if (normal_dot_vertex_to_light > 0.0f) {
  758. FloatVector3 half_vector_normalized;
  759. if (!m_lighting_model.viewer_at_infinity) {
  760. half_vector_normalized = (vertex_to_light + FloatVector3(0.0f, 0.0f, 1.0f)).normalized();
  761. } else {
  762. auto const vertex_to_eye_point = sgi_arrow_operator(vertex.eye_coordinates.normalized(), { 0.f, 0.f, 0.f, 1.f }, vertex_to_light_length);
  763. half_vector_normalized = vertex_to_light + vertex_to_eye_point;
  764. }
  765. auto const normal_dot_half_vector = sgi_dot_operator(vertex.normal.normalized(), half_vector_normalized);
  766. auto const specular_coefficient = AK::pow(normal_dot_half_vector, material.shininess);
  767. specular_component = (specular * light.specular_intensity) * specular_coefficient;
  768. }
  769. auto color = ambient_component + diffuse_component + specular_component;
  770. color = color * light_attenuation_factor * spotlight_factor;
  771. result_color += color;
  772. }
  773. vertex.color = result_color;
  774. vertex.color.set_w(diffuse.w()); // OpenGL 1.5 spec, page 59: "The A produced by lighting is the alpha value associated with diffuse color material"
  775. vertex.color.clamp(0.0f, 1.0f);
  776. }
  777. }
  778. // Transform eye coordinates into clip coordinates using the projection transform
  779. triangle.vertices[0].clip_coordinates = projection_transform * triangle.vertices[0].eye_coordinates;
  780. triangle.vertices[1].clip_coordinates = projection_transform * triangle.vertices[1].eye_coordinates;
  781. triangle.vertices[2].clip_coordinates = projection_transform * triangle.vertices[2].eye_coordinates;
  782. // At this point, we're in clip space
  783. // Here's where we do the clipping. This is a really crude implementation of the
  784. // https://learnopengl.com/Getting-started/Coordinate-Systems
  785. // "Note that if only a part of a primitive e.g. a triangle is outside the clipping volume OpenGL
  786. // will reconstruct the triangle as one or more triangles to fit inside the clipping range. "
  787. //
  788. // ALL VERTICES ARE DEFINED IN A CLOCKWISE ORDER
  789. // Okay, let's do some face culling first
  790. m_clipped_vertices.clear_with_capacity();
  791. m_clipped_vertices.append(triangle.vertices[0]);
  792. m_clipped_vertices.append(triangle.vertices[1]);
  793. m_clipped_vertices.append(triangle.vertices[2]);
  794. m_clipper.clip_triangle_against_frustum(m_clipped_vertices);
  795. if (m_clipped_vertices.size() < 3)
  796. continue;
  797. for (auto& vec : m_clipped_vertices) {
  798. // To normalized device coordinates (NDC)
  799. auto const one_over_w = 1 / vec.clip_coordinates.w();
  800. auto const ndc_coordinates = FloatVector4 {
  801. vec.clip_coordinates.x() * one_over_w,
  802. vec.clip_coordinates.y() * one_over_w,
  803. vec.clip_coordinates.z() * one_over_w,
  804. one_over_w,
  805. };
  806. // To window coordinates
  807. vec.window_coordinates = {
  808. viewport_center_x + ndc_coordinates.x() * viewport_half_width,
  809. viewport_center_y + ndc_coordinates.y() * viewport_half_height,
  810. depth_halfway + ndc_coordinates.z() * depth_half_range,
  811. ndc_coordinates.w(),
  812. };
  813. }
  814. Triangle tri;
  815. tri.vertices[0] = m_clipped_vertices[0];
  816. for (size_t i = 1; i < m_clipped_vertices.size() - 1; i++) {
  817. tri.vertices[1] = m_clipped_vertices[i];
  818. tri.vertices[2] = m_clipped_vertices[i + 1];
  819. m_processed_triangles.append(tri);
  820. }
  821. }
  822. // Generate texture coordinates if at least one coordinate is enabled
  823. bool texture_coordinate_generation_enabled = false;
  824. for (auto const coordinates_enabled : m_options.texcoord_generation_enabled_coordinates) {
  825. if (coordinates_enabled != TexCoordGenerationCoordinate::None) {
  826. texture_coordinate_generation_enabled = true;
  827. break;
  828. }
  829. }
  830. for (auto& triangle : m_processed_triangles) {
  831. // Let's calculate the (signed) area of the triangle
  832. // https://cp-algorithms.com/geometry/oriented-triangle-area.html
  833. float dxAB = triangle.vertices[0].window_coordinates.x() - triangle.vertices[1].window_coordinates.x(); // A.x - B.x
  834. float dxBC = triangle.vertices[1].window_coordinates.x() - triangle.vertices[2].window_coordinates.x(); // B.X - C.x
  835. float dyAB = triangle.vertices[0].window_coordinates.y() - triangle.vertices[1].window_coordinates.y();
  836. float dyBC = triangle.vertices[1].window_coordinates.y() - triangle.vertices[2].window_coordinates.y();
  837. float area = (dxAB * dyBC) - (dxBC * dyAB);
  838. if (area == 0.0f)
  839. continue;
  840. if (m_options.enable_culling) {
  841. bool is_front = (m_options.front_face == WindingOrder::CounterClockwise ? area > 0 : area < 0);
  842. if (!is_front && m_options.cull_back)
  843. continue;
  844. if (is_front && m_options.cull_front)
  845. continue;
  846. }
  847. if (area > 0)
  848. swap(triangle.vertices[0], triangle.vertices[1]);
  849. // Transform normals
  850. triangle.vertices[0].normal = normal_transform * triangle.vertices[0].normal;
  851. triangle.vertices[1].normal = normal_transform * triangle.vertices[1].normal;
  852. triangle.vertices[2].normal = normal_transform * triangle.vertices[2].normal;
  853. if (m_options.normalization_enabled) {
  854. triangle.vertices[0].normal.normalize();
  855. triangle.vertices[1].normal.normalize();
  856. triangle.vertices[2].normal.normalize();
  857. }
  858. if (texture_coordinate_generation_enabled) {
  859. generate_texture_coordinates(triangle.vertices[0], m_options);
  860. generate_texture_coordinates(triangle.vertices[1], m_options);
  861. generate_texture_coordinates(triangle.vertices[2], m_options);
  862. }
  863. // Apply texture transformation
  864. for (size_t i = 0; i < NUM_SAMPLERS; ++i) {
  865. triangle.vertices[0].tex_coords[i] = texture_transform * triangle.vertices[0].tex_coords[i];
  866. triangle.vertices[1].tex_coords[i] = texture_transform * triangle.vertices[1].tex_coords[i];
  867. triangle.vertices[2].tex_coords[i] = texture_transform * triangle.vertices[2].tex_coords[i];
  868. }
  869. rasterize_triangle(triangle);
  870. }
  871. }
  872. ALWAYS_INLINE void Device::shade_fragments(PixelQuad& quad)
  873. {
  874. quad.out_color = quad.vertex_color;
  875. for (size_t i : m_enabled_texture_units) {
  876. // FIXME: implement GL_TEXTURE_1D, GL_TEXTURE_3D and GL_TEXTURE_CUBE_MAP
  877. auto const& sampler = m_samplers[i];
  878. auto texel = sampler.sample_2d({ quad.texture_coordinates[i].x(), quad.texture_coordinates[i].y() });
  879. INCREASE_STATISTICS_COUNTER(g_num_sampler_calls, 1);
  880. // FIXME: Implement more blend modes
  881. switch (sampler.config().fixed_function_texture_env_mode) {
  882. case TextureEnvMode::Modulate:
  883. quad.out_color = quad.out_color * texel;
  884. break;
  885. case TextureEnvMode::Replace:
  886. quad.out_color = texel;
  887. break;
  888. case TextureEnvMode::Decal: {
  889. auto dst_alpha = texel.w();
  890. quad.out_color.set_x(mix(quad.out_color.x(), texel.x(), dst_alpha));
  891. quad.out_color.set_y(mix(quad.out_color.y(), texel.y(), dst_alpha));
  892. quad.out_color.set_z(mix(quad.out_color.z(), texel.z(), dst_alpha));
  893. break;
  894. }
  895. default:
  896. VERIFY_NOT_REACHED();
  897. }
  898. }
  899. // Calculate fog
  900. // Math from here: https://opengl-notes.readthedocs.io/en/latest/topics/texturing/aliasing.html
  901. // FIXME: exponential fog is not vectorized, we should add a SIMD exp function that calculates an approximation.
  902. if (m_options.fog_enabled) {
  903. auto factor = expand4(0.0f);
  904. switch (m_options.fog_mode) {
  905. case FogMode::Linear:
  906. factor = (m_options.fog_end - quad.fog_depth) / (m_options.fog_end - m_options.fog_start);
  907. break;
  908. case FogMode::Exp: {
  909. auto argument = -m_options.fog_density * quad.fog_depth;
  910. factor = exp(argument);
  911. } break;
  912. case FogMode::Exp2: {
  913. auto argument = m_options.fog_density * quad.fog_depth;
  914. argument *= -argument;
  915. factor = exp(argument);
  916. } break;
  917. default:
  918. VERIFY_NOT_REACHED();
  919. }
  920. // Mix texel's RGB with fog's RBG - leave alpha alone
  921. auto fog_color = expand4(m_options.fog_color);
  922. quad.out_color.set_x(mix(fog_color.x(), quad.out_color.x(), factor));
  923. quad.out_color.set_y(mix(fog_color.y(), quad.out_color.y(), factor));
  924. quad.out_color.set_z(mix(fog_color.z(), quad.out_color.z(), factor));
  925. }
  926. }
  927. ALWAYS_INLINE bool Device::test_alpha(PixelQuad& quad)
  928. {
  929. auto const alpha = quad.out_color.w();
  930. auto const ref_value = expand4(m_options.alpha_test_ref_value);
  931. switch (m_options.alpha_test_func) {
  932. case AlphaTestFunction::Less:
  933. quad.mask &= alpha < ref_value;
  934. break;
  935. case AlphaTestFunction::Equal:
  936. quad.mask &= alpha == ref_value;
  937. break;
  938. case AlphaTestFunction::LessOrEqual:
  939. quad.mask &= alpha <= ref_value;
  940. break;
  941. case AlphaTestFunction::Greater:
  942. quad.mask &= alpha > ref_value;
  943. break;
  944. case AlphaTestFunction::NotEqual:
  945. quad.mask &= alpha != ref_value;
  946. break;
  947. case AlphaTestFunction::GreaterOrEqual:
  948. quad.mask &= alpha >= ref_value;
  949. break;
  950. case AlphaTestFunction::Never:
  951. case AlphaTestFunction::Always:
  952. default:
  953. VERIFY_NOT_REACHED();
  954. }
  955. return any(quad.mask);
  956. }
  957. void Device::resize(Gfx::IntSize const& size)
  958. {
  959. auto frame_buffer_or_error = FrameBuffer<ColorType, DepthType, StencilType>::try_create(size);
  960. m_frame_buffer = MUST(frame_buffer_or_error);
  961. }
  962. void Device::clear_color(FloatVector4 const& color)
  963. {
  964. auto const fill_color = to_bgra32(color);
  965. auto clear_rect = m_frame_buffer->rect();
  966. if (m_options.scissor_enabled)
  967. clear_rect.intersect(m_options.scissor_box);
  968. m_frame_buffer->color_buffer()->fill(fill_color, clear_rect);
  969. }
  970. void Device::clear_depth(DepthType depth)
  971. {
  972. auto clear_rect = m_frame_buffer->rect();
  973. if (m_options.scissor_enabled)
  974. clear_rect.intersect(m_options.scissor_box);
  975. m_frame_buffer->depth_buffer()->fill(depth, clear_rect);
  976. }
  977. void Device::clear_stencil(StencilType value)
  978. {
  979. auto clear_rect = m_frame_buffer->rect();
  980. if (m_options.scissor_enabled)
  981. clear_rect.intersect(m_options.scissor_box);
  982. m_frame_buffer->stencil_buffer()->fill(value, clear_rect);
  983. }
  984. void Device::blit_to_color_buffer_at_raster_position(Gfx::Bitmap const& source)
  985. {
  986. if (!m_raster_position.valid)
  987. return;
  988. INCREASE_STATISTICS_COUNTER(g_num_pixels, source.width() * source.height());
  989. INCREASE_STATISTICS_COUNTER(g_num_pixels_shaded, source.width() * source.height());
  990. auto const blit_rect = get_rasterization_rect_of_size({ source.width(), source.height() });
  991. m_frame_buffer->color_buffer()->blit_from_bitmap(source, blit_rect);
  992. }
  993. void Device::blit_to_depth_buffer_at_raster_position(Vector<DepthType> const& depth_values, int width, int height)
  994. {
  995. if (!m_raster_position.valid)
  996. return;
  997. auto const raster_rect = get_rasterization_rect_of_size({ width, height });
  998. auto const y1 = raster_rect.y();
  999. auto const y2 = y1 + height;
  1000. auto const x1 = raster_rect.x();
  1001. auto const x2 = x1 + width;
  1002. auto index = 0;
  1003. for (auto y = y1; y < y2; ++y) {
  1004. auto depth_line = m_frame_buffer->depth_buffer()->scanline(y);
  1005. for (auto x = x1; x < x2; ++x)
  1006. depth_line[x] = depth_values[index++];
  1007. }
  1008. }
  1009. void Device::blit_color_buffer_to(Gfx::Bitmap& target)
  1010. {
  1011. m_frame_buffer->color_buffer()->blit_flipped_to_bitmap(target, m_frame_buffer->rect());
  1012. if constexpr (ENABLE_STATISTICS_OVERLAY)
  1013. draw_statistics_overlay(target);
  1014. }
  1015. void Device::draw_statistics_overlay(Gfx::Bitmap& target)
  1016. {
  1017. static Core::ElapsedTimer timer;
  1018. static String debug_string;
  1019. static int frame_counter;
  1020. frame_counter++;
  1021. int milliseconds = 0;
  1022. if (timer.is_valid())
  1023. milliseconds = timer.elapsed();
  1024. else
  1025. timer.start();
  1026. Gfx::Painter painter { target };
  1027. if (milliseconds > MILLISECONDS_PER_STATISTICS_PERIOD) {
  1028. int num_rendertarget_pixels = m_frame_buffer->rect().size().area();
  1029. StringBuilder builder;
  1030. builder.append(String::formatted("Timings : {:.1}ms {:.1}FPS\n",
  1031. static_cast<double>(milliseconds) / frame_counter,
  1032. (milliseconds > 0) ? 1000.0 * frame_counter / milliseconds : 9999.0));
  1033. builder.append(String::formatted("Triangles : {}\n", g_num_rasterized_triangles));
  1034. builder.append(String::formatted("SIMD usage : {}%\n", g_num_quads > 0 ? g_num_pixels_shaded * 25 / g_num_quads : 0));
  1035. builder.append(String::formatted("Pixels : {}, Stencil: {}%, Shaded: {}%, Blended: {}%, Overdraw: {}%\n",
  1036. g_num_pixels,
  1037. g_num_pixels > 0 ? g_num_stencil_writes * 100 / g_num_pixels : 0,
  1038. g_num_pixels > 0 ? g_num_pixels_shaded * 100 / g_num_pixels : 0,
  1039. g_num_pixels_shaded > 0 ? g_num_pixels_blended * 100 / g_num_pixels_shaded : 0,
  1040. num_rendertarget_pixels > 0 ? g_num_pixels_shaded * 100 / num_rendertarget_pixels - 100 : 0));
  1041. builder.append(String::formatted("Sampler calls: {}\n", g_num_sampler_calls));
  1042. debug_string = builder.to_string();
  1043. frame_counter = 0;
  1044. timer.start();
  1045. }
  1046. g_num_rasterized_triangles = 0;
  1047. g_num_pixels = 0;
  1048. g_num_pixels_shaded = 0;
  1049. g_num_pixels_blended = 0;
  1050. g_num_sampler_calls = 0;
  1051. g_num_stencil_writes = 0;
  1052. g_num_quads = 0;
  1053. auto& font = Gfx::FontDatabase::default_fixed_width_font();
  1054. for (int y = -1; y < 2; y++)
  1055. for (int x = -1; x < 2; x++)
  1056. if (x != 0 && y != 0)
  1057. painter.draw_text(target.rect().translated(x + 2, y + 2), debug_string, font, Gfx::TextAlignment::TopLeft, Gfx::Color::Black);
  1058. painter.draw_text(target.rect().translated(2, 2), debug_string, font, Gfx::TextAlignment::TopLeft, Gfx::Color::White);
  1059. }
  1060. void Device::set_options(const RasterizerOptions& options)
  1061. {
  1062. m_options = options;
  1063. if (m_options.enable_blending)
  1064. setup_blend_factors();
  1065. }
  1066. void Device::set_light_model_params(const LightModelParameters& lighting_model)
  1067. {
  1068. m_lighting_model = lighting_model;
  1069. }
  1070. ColorType Device::get_color_buffer_pixel(int x, int y)
  1071. {
  1072. // FIXME: Reading individual pixels is very slow, rewrite this to transfer whole blocks
  1073. if (!m_frame_buffer->rect().contains(x, y))
  1074. return 0;
  1075. return m_frame_buffer->color_buffer()->scanline(y)[x];
  1076. }
  1077. DepthType Device::get_depthbuffer_value(int x, int y)
  1078. {
  1079. // FIXME: Reading individual pixels is very slow, rewrite this to transfer whole blocks
  1080. if (!m_frame_buffer->rect().contains(x, y))
  1081. return 1.0f;
  1082. return m_frame_buffer->depth_buffer()->scanline(y)[x];
  1083. }
  1084. NonnullRefPtr<Image> Device::create_image(ImageFormat format, unsigned width, unsigned height, unsigned depth, unsigned levels, unsigned layers)
  1085. {
  1086. VERIFY(format == ImageFormat::BGRA8888);
  1087. VERIFY(width > 0);
  1088. VERIFY(height > 0);
  1089. VERIFY(depth > 0);
  1090. VERIFY(levels > 0);
  1091. VERIFY(layers > 0);
  1092. return adopt_ref(*new Image(width, height, depth, levels, layers));
  1093. }
  1094. void Device::set_sampler_config(unsigned sampler, SamplerConfig const& config)
  1095. {
  1096. m_samplers[sampler].set_config(config);
  1097. }
  1098. void Device::set_light_state(unsigned int light_id, Light const& light)
  1099. {
  1100. m_lights.at(light_id) = light;
  1101. }
  1102. void Device::set_material_state(Face face, Material const& material)
  1103. {
  1104. m_materials[face] = material;
  1105. }
  1106. void Device::set_stencil_configuration(Face face, StencilConfiguration const& stencil_configuration)
  1107. {
  1108. m_stencil_configuration[face] = stencil_configuration;
  1109. }
  1110. void Device::set_raster_position(RasterPosition const& raster_position)
  1111. {
  1112. m_raster_position = raster_position;
  1113. }
  1114. void Device::set_raster_position(FloatVector4 const& position, FloatMatrix4x4 const& model_view_transform, FloatMatrix4x4 const& projection_transform)
  1115. {
  1116. auto const eye_coordinates = model_view_transform * position;
  1117. auto const clip_coordinates = projection_transform * eye_coordinates;
  1118. // FIXME: implement clipping
  1119. m_raster_position.valid = true;
  1120. auto ndc_coordinates = clip_coordinates / clip_coordinates.w();
  1121. ndc_coordinates.set_w(clip_coordinates.w());
  1122. auto const viewport = m_options.viewport;
  1123. auto const viewport_half_width = viewport.width() / 2.0f;
  1124. auto const viewport_half_height = viewport.height() / 2.0f;
  1125. auto const viewport_center_x = viewport.x() + viewport_half_width;
  1126. auto const viewport_center_y = viewport.y() + viewport_half_height;
  1127. auto const depth_half_range = (m_options.depth_max - m_options.depth_min) / 2;
  1128. auto const depth_halfway = (m_options.depth_min + m_options.depth_max) / 2;
  1129. // FIXME: implement other raster position properties such as color and texcoords
  1130. m_raster_position.window_coordinates = {
  1131. viewport_center_x + ndc_coordinates.x() * viewport_half_width,
  1132. viewport_center_y + ndc_coordinates.y() * viewport_half_height,
  1133. depth_halfway + ndc_coordinates.z() * depth_half_range,
  1134. ndc_coordinates.w(),
  1135. };
  1136. m_raster_position.eye_coordinate_distance = eye_coordinates.length();
  1137. }
  1138. Gfx::IntRect Device::get_rasterization_rect_of_size(Gfx::IntSize size)
  1139. {
  1140. // Round the X and Y floating point coordinates to the nearest integer; OpenGL 1.5 spec:
  1141. // "Any fragments whose centers lie inside of this rectangle (or on its bottom or left
  1142. // boundaries) are produced in correspondence with this particular group of elements."
  1143. return {
  1144. static_cast<int>(roundf(m_raster_position.window_coordinates.x())),
  1145. static_cast<int>(roundf(m_raster_position.window_coordinates.y())),
  1146. size.width(),
  1147. size.height(),
  1148. };
  1149. }
  1150. }