Device.cpp 57 KB

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