Device.cpp 56 KB

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