Device.cpp 59 KB

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