Device.cpp 56 KB

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