Device.cpp 59 KB

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