Device.cpp 57 KB

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