Device.cpp 57 KB

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