Device.cpp 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718
  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/AnyOf.h>
  9. #include <AK/Error.h>
  10. #include <AK/Math.h>
  11. #include <AK/NumericLimits.h>
  12. #include <AK/SIMDExtras.h>
  13. #include <AK/SIMDMath.h>
  14. #include <LibCore/ElapsedTimer.h>
  15. #include <LibGfx/Painter.h>
  16. #include <LibGfx/Vector2.h>
  17. #include <LibGfx/Vector3.h>
  18. #include <LibSoftGPU/Config.h>
  19. #include <LibSoftGPU/Device.h>
  20. #include <LibSoftGPU/Image.h>
  21. #include <LibSoftGPU/PixelConverter.h>
  22. #include <LibSoftGPU/PixelQuad.h>
  23. #include <LibSoftGPU/SIMD.h>
  24. #include <math.h>
  25. namespace SoftGPU {
  26. static i64 g_num_rasterized_triangles;
  27. static i64 g_num_pixels;
  28. static i64 g_num_pixels_shaded;
  29. static i64 g_num_pixels_blended;
  30. static i64 g_num_sampler_calls;
  31. static i64 g_num_stencil_writes;
  32. static i64 g_num_quads;
  33. using AK::abs;
  34. using AK::SIMD::any;
  35. using AK::SIMD::exp;
  36. using AK::SIMD::expand4;
  37. using AK::SIMD::f32x4;
  38. using AK::SIMD::i32x4;
  39. using AK::SIMD::load4_masked;
  40. using AK::SIMD::maskbits;
  41. using AK::SIMD::maskcount;
  42. using AK::SIMD::store4_masked;
  43. using AK::SIMD::to_f32x4;
  44. using AK::SIMD::to_u32x4;
  45. using AK::SIMD::u32x4;
  46. static constexpr int subpixel_factor = 1 << SUBPIXEL_BITS;
  47. // Returns positive values for counter-clockwise rotation of vertices. Note that it returns the
  48. // area of a parallelogram with sides {a, b} and {b, c}, so _double_ the area of the triangle {a, b, c}.
  49. constexpr static i32 edge_function(IntVector2 const& a, IntVector2 const& b, IntVector2 const& c)
  50. {
  51. return (c.y() - a.y()) * (b.x() - a.x()) - (c.x() - a.x()) * (b.y() - a.y());
  52. }
  53. constexpr static i32x4 edge_function4(IntVector2 const& a, IntVector2 const& b, Vector2<i32x4> const& c)
  54. {
  55. return (c.y() - a.y()) * (b.x() - a.x()) - (c.x() - a.x()) * (b.y() - a.y());
  56. }
  57. template<typename T, typename U>
  58. constexpr static auto interpolate(T const& v0, T const& v1, T const& v2, Vector3<U> const& barycentric_coords)
  59. {
  60. return v0 * barycentric_coords.x() + v1 * barycentric_coords.y() + v2 * barycentric_coords.z();
  61. }
  62. static GPU::ColorType to_argb32(FloatVector4 const& color)
  63. {
  64. auto clamped = color.clamped(0.0f, 1.0f);
  65. auto r = static_cast<u8>(clamped.x() * 255);
  66. auto g = static_cast<u8>(clamped.y() * 255);
  67. auto b = static_cast<u8>(clamped.z() * 255);
  68. auto a = static_cast<u8>(clamped.w() * 255);
  69. return a << 24 | r << 16 | g << 8 | b;
  70. }
  71. ALWAYS_INLINE static u32x4 to_argb32(Vector4<f32x4> const& color)
  72. {
  73. auto clamped = color.clamped(expand4(0.0f), expand4(1.0f));
  74. auto r = to_u32x4(clamped.x() * 255);
  75. auto g = to_u32x4(clamped.y() * 255);
  76. auto b = to_u32x4(clamped.z() * 255);
  77. auto a = to_u32x4(clamped.w() * 255);
  78. return a << 24 | r << 16 | g << 8 | b;
  79. }
  80. static Vector4<f32x4> to_vec4(u32x4 bgra)
  81. {
  82. auto constexpr one_over_255 = expand4(1.0f / 255);
  83. return {
  84. to_f32x4((bgra >> 16) & 0xff) * one_over_255,
  85. to_f32x4((bgra >> 8) & 0xff) * one_over_255,
  86. to_f32x4(bgra & 0xff) * one_over_255,
  87. to_f32x4((bgra >> 24) & 0xff) * one_over_255,
  88. };
  89. }
  90. void Device::setup_blend_factors()
  91. {
  92. m_alpha_blend_factors = {};
  93. switch (m_options.blend_source_factor) {
  94. case GPU::BlendFactor::Zero:
  95. break;
  96. case GPU::BlendFactor::One:
  97. m_alpha_blend_factors.src_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  98. break;
  99. case GPU::BlendFactor::SrcColor:
  100. m_alpha_blend_factors.src_factor_src_color = 1;
  101. break;
  102. case GPU::BlendFactor::OneMinusSrcColor:
  103. m_alpha_blend_factors.src_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  104. m_alpha_blend_factors.src_factor_src_color = -1;
  105. break;
  106. case GPU::BlendFactor::SrcAlpha:
  107. m_alpha_blend_factors.src_factor_src_alpha = 1;
  108. break;
  109. case GPU::BlendFactor::OneMinusSrcAlpha:
  110. m_alpha_blend_factors.src_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  111. m_alpha_blend_factors.src_factor_src_alpha = -1;
  112. break;
  113. case GPU::BlendFactor::DstAlpha:
  114. m_alpha_blend_factors.src_factor_dst_alpha = 1;
  115. break;
  116. case GPU::BlendFactor::OneMinusDstAlpha:
  117. m_alpha_blend_factors.src_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  118. m_alpha_blend_factors.src_factor_dst_alpha = -1;
  119. break;
  120. case GPU::BlendFactor::DstColor:
  121. m_alpha_blend_factors.src_factor_dst_color = 1;
  122. break;
  123. case GPU::BlendFactor::OneMinusDstColor:
  124. m_alpha_blend_factors.src_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  125. m_alpha_blend_factors.src_factor_dst_color = -1;
  126. break;
  127. case GPU::BlendFactor::SrcAlphaSaturate:
  128. default:
  129. VERIFY_NOT_REACHED();
  130. }
  131. switch (m_options.blend_destination_factor) {
  132. case GPU::BlendFactor::Zero:
  133. break;
  134. case GPU::BlendFactor::One:
  135. m_alpha_blend_factors.dst_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  136. break;
  137. case GPU::BlendFactor::SrcColor:
  138. m_alpha_blend_factors.dst_factor_src_color = 1;
  139. break;
  140. case GPU::BlendFactor::OneMinusSrcColor:
  141. m_alpha_blend_factors.dst_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  142. m_alpha_blend_factors.dst_factor_src_color = -1;
  143. break;
  144. case GPU::BlendFactor::SrcAlpha:
  145. m_alpha_blend_factors.dst_factor_src_alpha = 1;
  146. break;
  147. case GPU::BlendFactor::OneMinusSrcAlpha:
  148. m_alpha_blend_factors.dst_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  149. m_alpha_blend_factors.dst_factor_src_alpha = -1;
  150. break;
  151. case GPU::BlendFactor::DstAlpha:
  152. m_alpha_blend_factors.dst_factor_dst_alpha = 1;
  153. break;
  154. case GPU::BlendFactor::OneMinusDstAlpha:
  155. m_alpha_blend_factors.dst_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  156. m_alpha_blend_factors.dst_factor_dst_alpha = -1;
  157. break;
  158. case GPU::BlendFactor::DstColor:
  159. m_alpha_blend_factors.dst_factor_dst_color = 1;
  160. break;
  161. case GPU::BlendFactor::OneMinusDstColor:
  162. m_alpha_blend_factors.dst_constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  163. m_alpha_blend_factors.dst_factor_dst_color = -1;
  164. break;
  165. case GPU::BlendFactor::SrcAlphaSaturate:
  166. default:
  167. VERIFY_NOT_REACHED();
  168. }
  169. }
  170. ALWAYS_INLINE static void test_alpha(PixelQuad& quad, GPU::AlphaTestFunction alpha_test_function, f32x4 const& reference_value)
  171. {
  172. auto const alpha = quad.out_color.w();
  173. switch (alpha_test_function) {
  174. case GPU::AlphaTestFunction::Always:
  175. quad.mask &= expand4(~0);
  176. break;
  177. case GPU::AlphaTestFunction::Equal:
  178. quad.mask &= alpha == reference_value;
  179. break;
  180. case GPU::AlphaTestFunction::Greater:
  181. quad.mask &= alpha > reference_value;
  182. break;
  183. case GPU::AlphaTestFunction::GreaterOrEqual:
  184. quad.mask &= alpha >= reference_value;
  185. break;
  186. case GPU::AlphaTestFunction::Less:
  187. quad.mask &= alpha < reference_value;
  188. break;
  189. case GPU::AlphaTestFunction::LessOrEqual:
  190. quad.mask &= alpha <= reference_value;
  191. break;
  192. case GPU::AlphaTestFunction::NotEqual:
  193. quad.mask &= alpha != reference_value;
  194. break;
  195. case GPU::AlphaTestFunction::Never:
  196. default:
  197. VERIFY_NOT_REACHED();
  198. }
  199. }
  200. template<typename CB1, typename CB2, typename CB3>
  201. ALWAYS_INLINE void Device::rasterize(Gfx::IntRect& render_bounds, CB1 set_coverage_mask, CB2 set_quad_depth, CB3 set_quad_attributes)
  202. {
  203. // Return if alpha testing is a no-op
  204. if (m_options.enable_alpha_test && m_options.alpha_test_func == GPU::AlphaTestFunction::Never)
  205. return;
  206. auto const alpha_test_ref_value = expand4(m_options.alpha_test_ref_value);
  207. // Buffers
  208. auto color_buffer = m_frame_buffer->color_buffer();
  209. auto depth_buffer = m_frame_buffer->depth_buffer();
  210. auto stencil_buffer = m_frame_buffer->stencil_buffer();
  211. // Stencil configuration and writing
  212. auto const& stencil_configuration = m_stencil_configuration[GPU::Face::Front];
  213. auto const stencil_reference_value = stencil_configuration.reference_value & stencil_configuration.test_mask;
  214. 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) {
  215. if (write_mask == 0 || op == GPU::StencilOperation::Keep)
  216. return;
  217. switch (op) {
  218. case GPU::StencilOperation::Decrement:
  219. stencil_value = (stencil_value & ~write_mask) | (max(stencil_value - 1, expand4(0)) & write_mask);
  220. break;
  221. case GPU::StencilOperation::DecrementWrap:
  222. stencil_value = (stencil_value & ~write_mask) | (((stencil_value - 1) & 0xFF) & write_mask);
  223. break;
  224. case GPU::StencilOperation::Increment:
  225. stencil_value = (stencil_value & ~write_mask) | (min(stencil_value + 1, expand4(0xFF)) & write_mask);
  226. break;
  227. case GPU::StencilOperation::IncrementWrap:
  228. stencil_value = (stencil_value & ~write_mask) | (((stencil_value + 1) & 0xFF) & write_mask);
  229. break;
  230. case GPU::StencilOperation::Invert:
  231. stencil_value ^= write_mask;
  232. break;
  233. case GPU::StencilOperation::Replace:
  234. stencil_value = (stencil_value & ~write_mask) | (reference_value & write_mask);
  235. break;
  236. case GPU::StencilOperation::Zero:
  237. stencil_value &= ~write_mask;
  238. break;
  239. default:
  240. VERIFY_NOT_REACHED();
  241. }
  242. INCREASE_STATISTICS_COUNTER(g_num_stencil_writes, maskcount(pixel_mask));
  243. store4_masked(stencil_value, stencil_ptrs[0], stencil_ptrs[1], stencil_ptrs[2], stencil_ptrs[3], pixel_mask);
  244. };
  245. // Limit rendering to framebuffer and scissor rects
  246. render_bounds.intersect(m_frame_buffer->rect());
  247. if (m_options.scissor_enabled)
  248. render_bounds.intersect(m_options.scissor_box);
  249. // Quad bounds
  250. auto const render_bounds_left = render_bounds.left();
  251. auto const render_bounds_right = render_bounds.right();
  252. auto const render_bounds_top = render_bounds.top();
  253. auto const render_bounds_bottom = render_bounds.bottom();
  254. auto const qx0 = render_bounds_left & ~1;
  255. auto const qx1 = render_bounds_right & ~1;
  256. auto const qy0 = render_bounds_top & ~1;
  257. auto const qy1 = render_bounds_bottom & ~1;
  258. // Rasterize all quads
  259. // FIXME: this could be embarrassingly parallel
  260. for (int qy = qy0; qy <= qy1; qy += 2) {
  261. for (int qx = qx0; qx <= qx1; qx += 2) {
  262. PixelQuad quad;
  263. quad.screen_coordinates = {
  264. i32x4 { qx, qx + 1, qx, qx + 1 },
  265. i32x4 { qy, qy, qy + 1, qy + 1 },
  266. };
  267. // Set coverage mask and test against render bounds
  268. set_coverage_mask(quad);
  269. quad.mask &= quad.screen_coordinates.x() >= render_bounds_left
  270. && quad.screen_coordinates.x() <= render_bounds_right
  271. && quad.screen_coordinates.y() >= render_bounds_top
  272. && quad.screen_coordinates.y() <= render_bounds_bottom;
  273. auto coverage_bits = maskbits(quad.mask);
  274. if (coverage_bits == 0)
  275. continue;
  276. INCREASE_STATISTICS_COUNTER(g_num_quads, 1);
  277. INCREASE_STATISTICS_COUNTER(g_num_pixels, maskcount(quad.mask));
  278. // Stencil testing
  279. GPU::StencilType* stencil_ptrs[4];
  280. i32x4 stencil_value;
  281. if (m_options.enable_stencil_test) {
  282. stencil_ptrs[0] = coverage_bits & 1 ? &stencil_buffer->scanline(qy)[qx] : nullptr;
  283. stencil_ptrs[1] = coverage_bits & 2 ? &stencil_buffer->scanline(qy)[qx + 1] : nullptr;
  284. stencil_ptrs[2] = coverage_bits & 4 ? &stencil_buffer->scanline(qy + 1)[qx] : nullptr;
  285. stencil_ptrs[3] = coverage_bits & 8 ? &stencil_buffer->scanline(qy + 1)[qx + 1] : nullptr;
  286. stencil_value = load4_masked(stencil_ptrs[0], stencil_ptrs[1], stencil_ptrs[2], stencil_ptrs[3], quad.mask);
  287. stencil_value &= stencil_configuration.test_mask;
  288. i32x4 stencil_test_passed;
  289. switch (stencil_configuration.test_function) {
  290. case GPU::StencilTestFunction::Always:
  291. stencil_test_passed = expand4(~0);
  292. break;
  293. case GPU::StencilTestFunction::Equal:
  294. stencil_test_passed = stencil_value == stencil_reference_value;
  295. break;
  296. case GPU::StencilTestFunction::Greater:
  297. stencil_test_passed = stencil_value > stencil_reference_value;
  298. break;
  299. case GPU::StencilTestFunction::GreaterOrEqual:
  300. stencil_test_passed = stencil_value >= stencil_reference_value;
  301. break;
  302. case GPU::StencilTestFunction::Less:
  303. stencil_test_passed = stencil_value < stencil_reference_value;
  304. break;
  305. case GPU::StencilTestFunction::LessOrEqual:
  306. stencil_test_passed = stencil_value <= stencil_reference_value;
  307. break;
  308. case GPU::StencilTestFunction::Never:
  309. stencil_test_passed = expand4(0);
  310. break;
  311. case GPU::StencilTestFunction::NotEqual:
  312. stencil_test_passed = stencil_value != stencil_reference_value;
  313. break;
  314. default:
  315. VERIFY_NOT_REACHED();
  316. }
  317. // Update stencil buffer for pixels that failed the stencil test
  318. write_to_stencil(
  319. stencil_ptrs,
  320. stencil_value,
  321. stencil_configuration.on_stencil_test_fail,
  322. stencil_reference_value,
  323. stencil_configuration.write_mask,
  324. quad.mask & ~stencil_test_passed);
  325. // Update coverage mask + early quad rejection
  326. quad.mask &= stencil_test_passed;
  327. coverage_bits = maskbits(quad.mask);
  328. if (coverage_bits == 0)
  329. continue;
  330. }
  331. // Depth testing
  332. GPU::DepthType* depth_ptrs[4] = {
  333. coverage_bits & 1 ? &depth_buffer->scanline(qy)[qx] : nullptr,
  334. coverage_bits & 2 ? &depth_buffer->scanline(qy)[qx + 1] : nullptr,
  335. coverage_bits & 4 ? &depth_buffer->scanline(qy + 1)[qx] : nullptr,
  336. coverage_bits & 8 ? &depth_buffer->scanline(qy + 1)[qx + 1] : nullptr,
  337. };
  338. if (m_options.enable_depth_test) {
  339. set_quad_depth(quad);
  340. auto depth = load4_masked(depth_ptrs[0], depth_ptrs[1], depth_ptrs[2], depth_ptrs[3], quad.mask);
  341. i32x4 depth_test_passed;
  342. switch (m_options.depth_func) {
  343. case GPU::DepthTestFunction::Always:
  344. depth_test_passed = expand4(~0);
  345. break;
  346. case GPU::DepthTestFunction::Never:
  347. depth_test_passed = expand4(0);
  348. break;
  349. case GPU::DepthTestFunction::Greater:
  350. depth_test_passed = quad.depth > depth;
  351. break;
  352. case GPU::DepthTestFunction::GreaterOrEqual:
  353. depth_test_passed = quad.depth >= depth;
  354. break;
  355. case GPU::DepthTestFunction::NotEqual:
  356. #ifdef __SSE__
  357. depth_test_passed = quad.depth != depth;
  358. #else
  359. depth_test_passed = i32x4 {
  360. bit_cast<u32>(quad.depth[0]) != bit_cast<u32>(depth[0]) ? -1 : 0,
  361. bit_cast<u32>(quad.depth[1]) != bit_cast<u32>(depth[1]) ? -1 : 0,
  362. bit_cast<u32>(quad.depth[2]) != bit_cast<u32>(depth[2]) ? -1 : 0,
  363. bit_cast<u32>(quad.depth[3]) != bit_cast<u32>(depth[3]) ? -1 : 0,
  364. };
  365. #endif
  366. break;
  367. case GPU::DepthTestFunction::Equal:
  368. #ifdef __SSE__
  369. depth_test_passed = quad.depth == depth;
  370. #else
  371. //
  372. // This is an interesting quirk that occurs due to us using the x87 FPU when Serenity is
  373. // compiled for the i686 target. When we calculate our depth value to be stored in the buffer,
  374. // it is an 80-bit x87 floating point number, however, when stored into the depth buffer, this is
  375. // truncated to 32 bits. This 38 bit loss of precision means that when x87 `FCOMP` is eventually
  376. // used here the comparison fails.
  377. // This could be solved by using a `long double` for the depth buffer, however this would take
  378. // up significantly more space and is completely overkill for a depth buffer. As such, comparing
  379. // the first 32-bits of this depth value is "good enough" that if we get a hit on it being
  380. // equal, we can pretty much guarantee that it's actually equal.
  381. //
  382. depth_test_passed = i32x4 {
  383. bit_cast<u32>(quad.depth[0]) == bit_cast<u32>(depth[0]) ? -1 : 0,
  384. bit_cast<u32>(quad.depth[1]) == bit_cast<u32>(depth[1]) ? -1 : 0,
  385. bit_cast<u32>(quad.depth[2]) == bit_cast<u32>(depth[2]) ? -1 : 0,
  386. bit_cast<u32>(quad.depth[3]) == bit_cast<u32>(depth[3]) ? -1 : 0,
  387. };
  388. #endif
  389. break;
  390. case GPU::DepthTestFunction::LessOrEqual:
  391. depth_test_passed = quad.depth <= depth;
  392. break;
  393. case GPU::DepthTestFunction::Less:
  394. depth_test_passed = quad.depth < depth;
  395. break;
  396. default:
  397. VERIFY_NOT_REACHED();
  398. }
  399. // Update stencil buffer for pixels that failed the depth test
  400. if (m_options.enable_stencil_test) {
  401. write_to_stencil(
  402. stencil_ptrs,
  403. stencil_value,
  404. stencil_configuration.on_depth_test_fail,
  405. stencil_reference_value,
  406. stencil_configuration.write_mask,
  407. quad.mask & ~depth_test_passed);
  408. }
  409. // Update coverage mask + early quad rejection
  410. quad.mask &= depth_test_passed;
  411. coverage_bits = maskbits(quad.mask);
  412. if (coverage_bits == 0)
  413. continue;
  414. }
  415. // Update stencil buffer for passed pixels
  416. if (m_options.enable_stencil_test) {
  417. write_to_stencil(
  418. stencil_ptrs,
  419. stencil_value,
  420. stencil_configuration.on_pass,
  421. stencil_reference_value,
  422. stencil_configuration.write_mask,
  423. quad.mask);
  424. }
  425. INCREASE_STATISTICS_COUNTER(g_num_pixels_shaded, maskcount(quad.mask));
  426. set_quad_attributes(quad);
  427. shade_fragments(quad);
  428. // Alpha testing
  429. if (m_options.enable_alpha_test) {
  430. test_alpha(quad, m_options.alpha_test_func, alpha_test_ref_value);
  431. coverage_bits = maskbits(quad.mask);
  432. if (coverage_bits == 0)
  433. continue;
  434. }
  435. // Write to depth buffer
  436. if (m_options.enable_depth_test && m_options.enable_depth_write)
  437. store4_masked(quad.depth, depth_ptrs[0], depth_ptrs[1], depth_ptrs[2], depth_ptrs[3], quad.mask);
  438. // We will not update the color buffer at all
  439. if ((m_options.color_mask == 0) || !m_options.enable_color_write)
  440. continue;
  441. GPU::ColorType* color_ptrs[4] = {
  442. coverage_bits & 1 ? &color_buffer->scanline(qy)[qx] : nullptr,
  443. coverage_bits & 2 ? &color_buffer->scanline(qy)[qx + 1] : nullptr,
  444. coverage_bits & 4 ? &color_buffer->scanline(qy + 1)[qx] : nullptr,
  445. coverage_bits & 8 ? &color_buffer->scanline(qy + 1)[qx + 1] : nullptr,
  446. };
  447. u32x4 dst_u32;
  448. if (m_options.enable_blending || m_options.color_mask != 0xffffffff)
  449. dst_u32 = load4_masked(color_ptrs[0], color_ptrs[1], color_ptrs[2], color_ptrs[3], quad.mask);
  450. if (m_options.enable_blending) {
  451. INCREASE_STATISTICS_COUNTER(g_num_pixels_blended, maskcount(quad.mask));
  452. // Blend color values from pixel_staging into color_buffer
  453. auto const& src = quad.out_color;
  454. auto dst = to_vec4(dst_u32);
  455. auto src_factor = expand4(m_alpha_blend_factors.src_constant)
  456. + src * m_alpha_blend_factors.src_factor_src_color
  457. + Vector4<f32x4> { src.w(), src.w(), src.w(), src.w() } * m_alpha_blend_factors.src_factor_src_alpha
  458. + dst * m_alpha_blend_factors.src_factor_dst_color
  459. + Vector4<f32x4> { dst.w(), dst.w(), dst.w(), dst.w() } * m_alpha_blend_factors.src_factor_dst_alpha;
  460. auto dst_factor = expand4(m_alpha_blend_factors.dst_constant)
  461. + src * m_alpha_blend_factors.dst_factor_src_color
  462. + Vector4<f32x4> { src.w(), src.w(), src.w(), src.w() } * m_alpha_blend_factors.dst_factor_src_alpha
  463. + dst * m_alpha_blend_factors.dst_factor_dst_color
  464. + Vector4<f32x4> { dst.w(), dst.w(), dst.w(), dst.w() } * m_alpha_blend_factors.dst_factor_dst_alpha;
  465. quad.out_color = src * src_factor + dst * dst_factor;
  466. }
  467. auto const argb32_color = to_argb32(quad.out_color);
  468. if (m_options.color_mask == 0xffffffff)
  469. store4_masked(argb32_color, color_ptrs[0], color_ptrs[1], color_ptrs[2], color_ptrs[3], quad.mask);
  470. else
  471. store4_masked((argb32_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);
  472. }
  473. }
  474. }
  475. void Device::rasterize_line_aliased(GPU::Vertex& from, GPU::Vertex& to)
  476. {
  477. // FIXME: implement aliased lines; for now we fall back to anti-aliased logic
  478. rasterize_line_antialiased(from, to);
  479. }
  480. void Device::rasterize_line_antialiased(GPU::Vertex& from, GPU::Vertex& to)
  481. {
  482. auto const from_coords = from.window_coordinates.xy();
  483. auto const to_coords = to.window_coordinates.xy();
  484. auto const line_width = ceilf(m_options.line_width);
  485. auto const line_radius = line_width / 2;
  486. auto render_bounds = Gfx::IntRect {
  487. min(from_coords.x(), to_coords.x()),
  488. min(from_coords.y(), to_coords.y()),
  489. abs(from_coords.x() - to_coords.x()) + 1,
  490. abs(from_coords.y() - to_coords.y()) + 1,
  491. };
  492. render_bounds.inflate(line_width, line_width);
  493. auto const from_coords4 = expand4(from_coords);
  494. auto const line_vector = to_coords - from_coords;
  495. auto const line_vector4 = expand4(line_vector);
  496. auto const line_dot4 = expand4(line_vector.dot(line_vector));
  497. auto const from_depth4 = expand4(from.window_coordinates.z());
  498. auto const to_depth4 = expand4(to.window_coordinates.z());
  499. auto const from_color4 = expand4(from.color);
  500. auto const from_fog_depth4 = expand4(abs(from.eye_coordinates.z()));
  501. // Rasterize using a 2D signed distance field for a line segment
  502. // FIXME: performance-wise, this might be the absolute worst way to draw an anti-aliased line
  503. f32x4 distance_along_line;
  504. rasterize(
  505. render_bounds,
  506. [&from_coords4, &distance_along_line, &line_vector4, &line_dot4, &line_radius](auto& quad) {
  507. auto const screen_coordinates4 = to_vec2_f32x4(quad.screen_coordinates);
  508. auto const pixel_vector = screen_coordinates4 - from_coords4;
  509. distance_along_line = AK::SIMD::clamp(pixel_vector.dot(line_vector4) / line_dot4, 0.f, 1.f);
  510. auto distance_to_line = length(pixel_vector - line_vector4 * distance_along_line) - line_radius;
  511. // Add .5f to the distance so coverage transitions half a pixel before the actual border
  512. quad.coverage = 1.f - AK::SIMD::clamp(distance_to_line + 0.5f, 0.f, 1.f);
  513. quad.mask = quad.coverage > 0.f;
  514. },
  515. [&from_depth4, &to_depth4, &distance_along_line](auto& quad) {
  516. quad.depth = mix(from_depth4, to_depth4, distance_along_line);
  517. },
  518. [&from_color4, &from, &from_fog_depth4](auto& quad) {
  519. // FIXME: interpolate color, tex coords and fog depth along the distance of the line
  520. // in clip space (i.e. NOT distance_from_line)
  521. quad.vertex_color = from_color4;
  522. for (size_t i = 0; i < GPU::NUM_TEXTURE_UNITS; ++i)
  523. quad.texture_coordinates[i] = expand4(from.tex_coords[i]);
  524. quad.fog_depth = from_fog_depth4;
  525. });
  526. }
  527. void Device::rasterize_line(GPU::Vertex& from, GPU::Vertex& to)
  528. {
  529. if (m_options.line_smooth)
  530. rasterize_line_antialiased(from, to);
  531. else
  532. rasterize_line_aliased(from, to);
  533. }
  534. void Device::rasterize_point_aliased(GPU::Vertex& point)
  535. {
  536. // Determine aliased point width
  537. constexpr size_t maximum_aliased_point_size = 64;
  538. auto point_width = clamp(round_to<int>(m_options.point_size), 1, maximum_aliased_point_size);
  539. // Determine aliased center coordinates
  540. IntVector2 point_center;
  541. if (point_width % 2 == 1)
  542. point_center = point.window_coordinates.xy().to_type<int>();
  543. else
  544. point_center = (point.window_coordinates.xy() + FloatVector2 { .5f, .5f }).to_type<int>();
  545. // Aliased points are rects; calculate boundaries around center
  546. auto point_rect = Gfx::IntRect {
  547. point_center.x() - point_width / 2,
  548. point_center.y() - point_width / 2,
  549. point_width,
  550. point_width,
  551. };
  552. // Rasterize the point as a rect
  553. rasterize(
  554. point_rect,
  555. [](auto& quad) {
  556. // We already passed in point_rect, so this doesn't matter
  557. quad.mask = expand4(~0);
  558. },
  559. [&point](auto& quad) {
  560. quad.depth = expand4(point.window_coordinates.z());
  561. },
  562. [&point](auto& quad) {
  563. quad.vertex_color = expand4(point.color);
  564. for (size_t i = 0; i < GPU::NUM_TEXTURE_UNITS; ++i)
  565. quad.texture_coordinates[i] = expand4(point.tex_coords[i]);
  566. quad.fog_depth = expand4(abs(point.eye_coordinates.z()));
  567. });
  568. }
  569. void Device::rasterize_point_antialiased(GPU::Vertex& point)
  570. {
  571. auto const center = point.window_coordinates.xy();
  572. auto const center4 = expand4(center);
  573. auto const radius = m_options.point_size / 2;
  574. auto render_bounds = Gfx::IntRect {
  575. center.x() - radius,
  576. center.y() - radius,
  577. radius * 2 + 1,
  578. radius * 2 + 1,
  579. };
  580. // Rasterize using a 2D signed distance field for a circle
  581. rasterize(
  582. render_bounds,
  583. [&center4, &radius](auto& quad) {
  584. auto screen_coords = to_vec2_f32x4(quad.screen_coordinates);
  585. auto distance_to_point = length(center4 - screen_coords) - radius;
  586. // Add .5f to the distance so coverage transitions half a pixel before the actual border
  587. quad.coverage = 1.f - AK::SIMD::clamp(distance_to_point + .5f, 0.f, 1.f);
  588. quad.mask = quad.coverage > 0.f;
  589. },
  590. [&point](auto& quad) {
  591. quad.depth = expand4(point.window_coordinates.z());
  592. },
  593. [&point](auto& quad) {
  594. quad.vertex_color = expand4(point.color);
  595. for (size_t i = 0; i < GPU::NUM_TEXTURE_UNITS; ++i)
  596. quad.texture_coordinates[i] = expand4(point.tex_coords[i]);
  597. quad.fog_depth = expand4(abs(point.eye_coordinates.z()));
  598. });
  599. }
  600. void Device::rasterize_point(GPU::Vertex& point)
  601. {
  602. if (m_options.point_smooth)
  603. rasterize_point_antialiased(point);
  604. else
  605. rasterize_point_aliased(point);
  606. }
  607. void Device::rasterize_triangle(Triangle& triangle)
  608. {
  609. INCREASE_STATISTICS_COUNTER(g_num_rasterized_triangles, 1);
  610. auto v0 = (triangle.vertices[0].window_coordinates.xy() * subpixel_factor).to_rounded<int>();
  611. auto v1 = (triangle.vertices[1].window_coordinates.xy() * subpixel_factor).to_rounded<int>();
  612. auto v2 = (triangle.vertices[2].window_coordinates.xy() * subpixel_factor).to_rounded<int>();
  613. auto triangle_area = edge_function(v0, v1, v2);
  614. if (triangle_area == 0)
  615. return;
  616. // Perform face culling
  617. if (m_options.enable_culling) {
  618. bool is_front = (m_options.front_face == GPU::WindingOrder::CounterClockwise ? triangle_area > 0 : triangle_area < 0);
  619. if (!is_front && m_options.cull_back)
  620. return;
  621. if (is_front && m_options.cull_front)
  622. return;
  623. }
  624. // Force counter-clockwise ordering of vertices
  625. if (triangle_area < 0) {
  626. swap(triangle.vertices[0], triangle.vertices[1]);
  627. swap(v0, v1);
  628. triangle_area *= -1;
  629. }
  630. auto const& vertex0 = triangle.vertices[0];
  631. auto const& vertex1 = triangle.vertices[1];
  632. auto const& vertex2 = triangle.vertices[2];
  633. auto const one_over_area = 1.0f / triangle_area;
  634. // This function calculates the 3 edge values for the pixel relative to the triangle.
  635. auto calculate_edge_values4 = [v0, v1, v2](Vector2<i32x4> const& p) -> Vector3<i32x4> {
  636. return {
  637. edge_function4(v1, v2, p),
  638. edge_function4(v2, v0, p),
  639. edge_function4(v0, v1, p),
  640. };
  641. };
  642. // Zero is used in testing against edge values below, applying the "top-left rule". If a pixel
  643. // lies exactly on an edge shared by two triangles, we only render that pixel if the edge in
  644. // question is a "top" or "left" edge. By setting either a 1 or 0, we effectively change the
  645. // comparisons against the edge values below from "> 0" into ">= 0".
  646. IntVector3 const zero {
  647. (v2.y() < v1.y() || (v2.y() == v1.y() && v2.x() < v1.x())) ? 0 : 1,
  648. (v0.y() < v2.y() || (v0.y() == v2.y() && v0.x() < v2.x())) ? 0 : 1,
  649. (v1.y() < v0.y() || (v1.y() == v0.y() && v1.x() < v0.x())) ? 0 : 1,
  650. };
  651. // This function tests whether a point as identified by its 3 edge values lies within the triangle
  652. auto test_point4 = [zero](Vector3<i32x4> const& edges) -> i32x4 {
  653. return edges.x() >= zero.x()
  654. && edges.y() >= zero.y()
  655. && edges.z() >= zero.z();
  656. };
  657. // Calculate render bounds based on the triangle's vertices
  658. Gfx::IntRect render_bounds;
  659. render_bounds.set_left(min(min(v0.x(), v1.x()), v2.x()) / subpixel_factor);
  660. render_bounds.set_right(max(max(v0.x(), v1.x()), v2.x()) / subpixel_factor);
  661. render_bounds.set_top(min(min(v0.y(), v1.y()), v2.y()) / subpixel_factor);
  662. render_bounds.set_bottom(max(max(v0.y(), v1.y()), v2.y()) / subpixel_factor);
  663. // Calculate depth of fragment for fog;
  664. // OpenGL 1.5 chapter 3.10: "An implementation may choose to approximate the
  665. // eye-coordinate distance from the eye to each fragment center by |Ze|."
  666. Vector3<f32x4> fog_depth;
  667. if (m_options.fog_enabled) {
  668. fog_depth = {
  669. expand4(abs(vertex0.eye_coordinates.z())),
  670. expand4(abs(vertex1.eye_coordinates.z())),
  671. expand4(abs(vertex2.eye_coordinates.z())),
  672. };
  673. }
  674. auto const half_pixel_offset = Vector2<i32x4> { expand4(subpixel_factor / 2), expand4(subpixel_factor / 2) };
  675. auto const window_w_coordinates = Vector3<f32x4> {
  676. expand4(vertex0.window_coordinates.w()),
  677. expand4(vertex1.window_coordinates.w()),
  678. expand4(vertex2.window_coordinates.w()),
  679. };
  680. // Calculate depth offset to apply
  681. float depth_offset = 0.f;
  682. if (m_options.depth_offset_enabled) {
  683. // OpenGL 2.0 § 3.5.5 allows us to approximate the maximum slope
  684. auto delta_z = max(
  685. max(
  686. abs(vertex0.window_coordinates.z() - vertex1.window_coordinates.z()),
  687. abs(vertex1.window_coordinates.z() - vertex2.window_coordinates.z())),
  688. abs(vertex2.window_coordinates.z() - vertex0.window_coordinates.z()));
  689. auto depth_max_slope = max(delta_z / render_bounds.width(), delta_z / render_bounds.height());
  690. // Calculate total depth offset
  691. depth_offset = depth_max_slope * m_options.depth_offset_factor + NumericLimits<float>::epsilon() * m_options.depth_offset_constant;
  692. }
  693. auto const window_z_coordinates = Vector3<f32x4> {
  694. expand4(vertex0.window_coordinates.z() + depth_offset),
  695. expand4(vertex1.window_coordinates.z() + depth_offset),
  696. expand4(vertex2.window_coordinates.z() + depth_offset),
  697. };
  698. rasterize(
  699. render_bounds,
  700. [&](auto& quad) {
  701. auto edge_values = calculate_edge_values4(quad.screen_coordinates * subpixel_factor + half_pixel_offset);
  702. quad.mask = test_point4(edge_values);
  703. quad.barycentrics = {
  704. to_f32x4(edge_values.x()),
  705. to_f32x4(edge_values.y()),
  706. to_f32x4(edge_values.z()),
  707. };
  708. },
  709. [&](auto& quad) {
  710. // Determine each edge's ratio to the total area
  711. quad.barycentrics = quad.barycentrics * one_over_area;
  712. // Because the Z coordinates were divided by W, we can interpolate between them
  713. quad.depth = AK::SIMD::clamp(window_z_coordinates.dot(quad.barycentrics), 0.f, 1.f);
  714. },
  715. [&](auto& quad) {
  716. auto const interpolated_reciprocal_w = window_w_coordinates.dot(quad.barycentrics);
  717. quad.barycentrics = quad.barycentrics * window_w_coordinates / interpolated_reciprocal_w;
  718. // FIXME: make this more generic. We want to interpolate more than just color and uv
  719. if (m_options.shade_smooth)
  720. quad.vertex_color = interpolate(expand4(vertex0.color), expand4(vertex1.color), expand4(vertex2.color), quad.barycentrics);
  721. else
  722. quad.vertex_color = expand4(vertex0.color);
  723. for (GPU::TextureUnitIndex i = 0; i < GPU::NUM_TEXTURE_UNITS; ++i)
  724. quad.texture_coordinates[i] = interpolate(expand4(vertex0.tex_coords[i]), expand4(vertex1.tex_coords[i]), expand4(vertex2.tex_coords[i]), quad.barycentrics);
  725. if (m_options.fog_enabled)
  726. quad.fog_depth = fog_depth.dot(quad.barycentrics);
  727. });
  728. }
  729. Device::Device(Gfx::IntSize size)
  730. : m_frame_buffer(FrameBuffer<GPU::ColorType, GPU::DepthType, GPU::StencilType>::try_create(size).release_value_but_fixme_should_propagate_errors())
  731. {
  732. m_options.scissor_box = m_frame_buffer->rect();
  733. m_options.viewport = m_frame_buffer->rect();
  734. }
  735. GPU::DeviceInfo Device::info() const
  736. {
  737. return {
  738. .vendor_name = "SerenityOS",
  739. .device_name = "SoftGPU",
  740. .num_texture_units = GPU::NUM_TEXTURE_UNITS,
  741. .num_lights = NUM_LIGHTS,
  742. .max_clip_planes = MAX_CLIP_PLANES,
  743. .max_texture_size = MAX_TEXTURE_SIZE,
  744. .max_texture_lod_bias = MAX_TEXTURE_LOD_BIAS,
  745. .stencil_bits = sizeof(GPU::StencilType) * 8,
  746. .supports_npot_textures = true,
  747. .supports_texture_clamp_to_edge = true,
  748. .supports_texture_env_add = true,
  749. };
  750. }
  751. static void generate_texture_coordinates(GPU::Vertex const& vertex, FloatVector4& tex_coord, GPU::TextureUnitConfiguration const& texture_unit_configuration)
  752. {
  753. auto generate_coordinate = [&](size_t config_index) -> float {
  754. auto const& tex_coord_generation = texture_unit_configuration.tex_coord_generation[config_index];
  755. switch (tex_coord_generation.mode) {
  756. case GPU::TexCoordGenerationMode::ObjectLinear: {
  757. auto coefficients = tex_coord_generation.coefficients;
  758. return coefficients.dot(vertex.position);
  759. }
  760. case GPU::TexCoordGenerationMode::EyeLinear: {
  761. auto coefficients = tex_coord_generation.coefficients;
  762. return coefficients.dot(vertex.eye_coordinates);
  763. }
  764. case GPU::TexCoordGenerationMode::SphereMap: {
  765. auto const eye_unit = vertex.eye_coordinates.normalized();
  766. FloatVector3 const eye_unit_xyz = eye_unit.xyz();
  767. auto const normal = vertex.normal;
  768. auto reflection = eye_unit_xyz - normal * 2 * normal.dot(eye_unit_xyz);
  769. reflection.set_z(reflection.z() + 1);
  770. auto const reflection_value = reflection[config_index];
  771. return reflection_value / (2 * reflection.length()) + 0.5f;
  772. }
  773. case GPU::TexCoordGenerationMode::ReflectionMap: {
  774. auto const eye_unit = vertex.eye_coordinates.normalized();
  775. FloatVector3 const eye_unit_xyz = eye_unit.xyz();
  776. auto const normal = vertex.normal;
  777. auto reflection = eye_unit_xyz - normal * 2 * normal.dot(eye_unit_xyz);
  778. return reflection[config_index];
  779. }
  780. case GPU::TexCoordGenerationMode::NormalMap: {
  781. return vertex.normal[config_index];
  782. }
  783. }
  784. VERIFY_NOT_REACHED();
  785. };
  786. auto const enabled_coords = texture_unit_configuration.tex_coord_generation_enabled;
  787. if (enabled_coords == GPU::TexCoordGenerationCoordinate::None)
  788. return;
  789. tex_coord = {
  790. ((enabled_coords & GPU::TexCoordGenerationCoordinate::S) > 0) ? generate_coordinate(0) : tex_coord.x(),
  791. ((enabled_coords & GPU::TexCoordGenerationCoordinate::T) > 0) ? generate_coordinate(1) : tex_coord.y(),
  792. ((enabled_coords & GPU::TexCoordGenerationCoordinate::R) > 0) ? generate_coordinate(2) : tex_coord.z(),
  793. ((enabled_coords & GPU::TexCoordGenerationCoordinate::Q) > 0) ? generate_coordinate(3) : tex_coord.w(),
  794. };
  795. }
  796. void Device::calculate_vertex_lighting(GPU::Vertex& vertex) const
  797. {
  798. if (!m_options.lighting_enabled)
  799. return;
  800. auto const& material = m_materials.at(0);
  801. auto ambient = material.ambient;
  802. auto diffuse = material.diffuse;
  803. auto emissive = material.emissive;
  804. auto specular = material.specular;
  805. if (m_options.color_material_enabled
  806. && (m_options.color_material_face == GPU::ColorMaterialFace::Front || m_options.color_material_face == GPU::ColorMaterialFace::FrontAndBack)) {
  807. switch (m_options.color_material_mode) {
  808. case GPU::ColorMaterialMode::Ambient:
  809. ambient = vertex.color;
  810. break;
  811. case GPU::ColorMaterialMode::AmbientAndDiffuse:
  812. ambient = vertex.color;
  813. diffuse = vertex.color;
  814. break;
  815. case GPU::ColorMaterialMode::Diffuse:
  816. diffuse = vertex.color;
  817. break;
  818. case GPU::ColorMaterialMode::Emissive:
  819. emissive = vertex.color;
  820. break;
  821. case GPU::ColorMaterialMode::Specular:
  822. specular = vertex.color;
  823. break;
  824. }
  825. }
  826. FloatVector4 result_color = emissive + ambient * m_lighting_model.scene_ambient_color;
  827. for (auto const& light : m_lights) {
  828. if (!light.is_enabled)
  829. continue;
  830. // We need to save the length here because the attenuation factor requires a non-normalized vector!
  831. auto sgi_arrow_operator = [](FloatVector4 const& p1, FloatVector4 const& p2, float& output_length) {
  832. FloatVector3 light_vector;
  833. if ((p1.w() != 0.f) && (p2.w() == 0.f))
  834. light_vector = p2.xyz();
  835. else if ((p1.w() == 0.f) && (p2.w() != 0.f))
  836. light_vector = -p1.xyz();
  837. else
  838. light_vector = p2.xyz() - p1.xyz();
  839. output_length = light_vector.length();
  840. if (output_length == 0.f)
  841. return light_vector;
  842. return light_vector / output_length;
  843. };
  844. auto sgi_dot_operator = [](FloatVector3 const& d1, FloatVector3 const& d2) {
  845. return AK::max(d1.dot(d2), 0.0f);
  846. };
  847. float vertex_to_light_length = 0.f;
  848. FloatVector3 vertex_to_light = sgi_arrow_operator(vertex.eye_coordinates, light.position, vertex_to_light_length);
  849. // Light attenuation value.
  850. float light_attenuation_factor = 1.0f;
  851. if (light.position.w() != 0.0f)
  852. 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));
  853. // Spotlight factor
  854. float spotlight_factor = 1.0f;
  855. if (light.spotlight_cutoff_angle != 180.0f) {
  856. auto const vertex_to_light_dot_spotlight_direction = sgi_dot_operator(vertex_to_light, light.spotlight_direction.normalized());
  857. auto const cos_spotlight_cutoff = AK::cos<float>(light.spotlight_cutoff_angle * AK::Pi<float> / 180.f);
  858. if (vertex_to_light_dot_spotlight_direction >= cos_spotlight_cutoff)
  859. spotlight_factor = AK::pow<float>(vertex_to_light_dot_spotlight_direction, light.spotlight_exponent);
  860. else
  861. spotlight_factor = 0.0f;
  862. }
  863. // FIXME: The spec allows for splitting the colors calculated here into multiple different colors (primary/secondary color). Investigate what this means.
  864. (void)m_lighting_model.color_control;
  865. // 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)
  866. (void)m_lighting_model.two_sided_lighting;
  867. // Ambient
  868. auto const ambient_component = ambient * light.ambient_intensity;
  869. // Diffuse
  870. auto const normal_dot_vertex_to_light = sgi_dot_operator(vertex.normal, vertex_to_light);
  871. auto const diffuse_component = diffuse * light.diffuse_intensity * normal_dot_vertex_to_light;
  872. // Specular
  873. FloatVector4 specular_component = { 0.0f, 0.0f, 0.0f, 0.0f };
  874. if (normal_dot_vertex_to_light > 0.0f) {
  875. FloatVector3 half_vector_normalized;
  876. if (!m_lighting_model.viewer_at_infinity) {
  877. half_vector_normalized = vertex_to_light + FloatVector3(0.0f, 0.0f, 1.0f);
  878. } else {
  879. auto const vertex_to_eye_point = sgi_arrow_operator(vertex.eye_coordinates, { 0.f, 0.f, 0.f, 1.f }, vertex_to_light_length);
  880. half_vector_normalized = vertex_to_light + vertex_to_eye_point;
  881. }
  882. half_vector_normalized.normalize();
  883. auto const normal_dot_half_vector = sgi_dot_operator(vertex.normal, half_vector_normalized);
  884. auto const specular_coefficient = AK::pow(normal_dot_half_vector, material.shininess);
  885. specular_component = specular * light.specular_intensity * specular_coefficient;
  886. }
  887. auto color = ambient_component + diffuse_component + specular_component;
  888. color = color * light_attenuation_factor * spotlight_factor;
  889. result_color += color;
  890. }
  891. vertex.color = result_color;
  892. 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"
  893. vertex.color.clamp(0.0f, 1.0f);
  894. }
  895. void Device::draw_primitives(GPU::PrimitiveType primitive_type, FloatMatrix4x4 const& model_view_transform, FloatMatrix4x4 const& projection_transform, Vector<GPU::Vertex>& vertices)
  896. {
  897. // At this point, the user has effectively specified that they are done with defining the geometry
  898. // of what they want to draw. We now need to do a few things (https://www.khronos.org/opengl/wiki/Rendering_Pipeline_Overview):
  899. //
  900. // 1. Transform all of the vertices in the current vertex list into eye space by multiplying the model-view matrix
  901. // 2. Transform all of the vertices from eye space into clip space by multiplying by the projection matrix
  902. // 3. If culling is enabled, we cull the desired faces (https://learnopengl.com/Advanced-OpenGL/Face-culling)
  903. // 4. Each element of the vertex is then divided by w to bring the positions into NDC (Normalized Device Coordinates)
  904. // 5. The triangle's vertices are sorted in a counter-clockwise orientation
  905. // 6. The triangles are then sent off to the rasterizer and drawn to the screen
  906. if (vertices.is_empty())
  907. return;
  908. // Set up normals transform by taking the upper left 3x3 elements from the model view matrix
  909. // See section 2.11.3 of the OpenGL 1.5 spec
  910. auto const normal_transform = model_view_transform.submatrix_from_topleft<3>().transpose().inverse();
  911. // First, transform all vertices
  912. for (auto& vertex : vertices) {
  913. vertex.eye_coordinates = model_view_transform * vertex.position;
  914. vertex.normal = normal_transform * vertex.normal;
  915. if (m_options.normalization_enabled)
  916. vertex.normal.normalize();
  917. calculate_vertex_lighting(vertex);
  918. vertex.clip_coordinates = projection_transform * vertex.eye_coordinates;
  919. for (GPU::TextureUnitIndex i = 0; i < GPU::NUM_TEXTURE_UNITS; ++i) {
  920. auto const& texture_unit_configuration = m_texture_unit_configuration[i];
  921. if (!texture_unit_configuration.enabled)
  922. continue;
  923. generate_texture_coordinates(vertex, vertex.tex_coords[i], texture_unit_configuration);
  924. vertex.tex_coords[i] = texture_unit_configuration.transformation_matrix * vertex.tex_coords[i];
  925. }
  926. }
  927. // Window coordinate calculation
  928. auto const viewport = m_options.viewport;
  929. auto const viewport_half_width = viewport.width() / 2.f;
  930. auto const viewport_half_height = viewport.height() / 2.f;
  931. auto const viewport_center_x = viewport.x() + viewport_half_width;
  932. auto const viewport_center_y = viewport.y() + viewport_half_height;
  933. auto const depth_half_range = (m_options.depth_max - m_options.depth_min) / 2;
  934. auto const depth_halfway = (m_options.depth_min + m_options.depth_max) / 2;
  935. auto calculate_vertex_window_coordinates = [&](GPU::Vertex& vertex) {
  936. auto const one_over_w = 1 / vertex.clip_coordinates.w();
  937. auto const ndc_coordinates = vertex.clip_coordinates.xyz() * one_over_w;
  938. vertex.window_coordinates = {
  939. viewport_center_x + ndc_coordinates.x() * viewport_half_width,
  940. viewport_center_y + ndc_coordinates.y() * viewport_half_height,
  941. depth_halfway + ndc_coordinates.z() * depth_half_range,
  942. one_over_w,
  943. };
  944. };
  945. // Process points
  946. if (primitive_type == GPU::PrimitiveType::Points) {
  947. m_clipper.clip_points_against_frustum(vertices);
  948. for (auto& vertex : vertices) {
  949. calculate_vertex_window_coordinates(vertex);
  950. rasterize_point(vertex);
  951. }
  952. return;
  953. }
  954. // Process lines, line loop and line strips
  955. auto rasterize_line_segment = [&](GPU::Vertex& from, GPU::Vertex& to) {
  956. if (!m_clipper.clip_line_against_frustum(from, to))
  957. return;
  958. calculate_vertex_window_coordinates(from);
  959. calculate_vertex_window_coordinates(to);
  960. rasterize_line(from, to);
  961. };
  962. if (primitive_type == GPU::PrimitiveType::Lines) {
  963. if (vertices.size() < 2)
  964. return;
  965. for (size_t i = 0; i < vertices.size() - 1; i += 2)
  966. rasterize_line_segment(vertices[i], vertices[i + 1]);
  967. return;
  968. } else if (primitive_type == GPU::PrimitiveType::LineLoop) {
  969. if (vertices.size() < 2)
  970. return;
  971. for (size_t i = 0; i < vertices.size(); ++i)
  972. rasterize_line_segment(vertices[i], vertices[(i + 1) % vertices.size()]);
  973. return;
  974. } else if (primitive_type == GPU::PrimitiveType::LineStrip) {
  975. if (vertices.size() < 2)
  976. return;
  977. for (size_t i = 0; i < vertices.size() - 1; ++i)
  978. rasterize_line_segment(vertices[i], vertices[i + 1]);
  979. return;
  980. }
  981. // Let's construct some triangles
  982. m_triangle_list.clear_with_capacity();
  983. m_processed_triangles.clear_with_capacity();
  984. if (primitive_type == GPU::PrimitiveType::Triangles) {
  985. Triangle triangle;
  986. if (vertices.size() < 3)
  987. return;
  988. for (size_t i = 0; i < vertices.size() - 2; i += 3) {
  989. triangle.vertices[0] = vertices.at(i);
  990. triangle.vertices[1] = vertices.at(i + 1);
  991. triangle.vertices[2] = vertices.at(i + 2);
  992. m_triangle_list.append(triangle);
  993. }
  994. } else if (primitive_type == GPU::PrimitiveType::Quads) {
  995. // We need to construct two triangles to form the quad
  996. Triangle triangle;
  997. if (vertices.size() < 4)
  998. return;
  999. for (size_t i = 0; i < vertices.size() - 3; i += 4) {
  1000. // Triangle 1
  1001. triangle.vertices[0] = vertices.at(i);
  1002. triangle.vertices[1] = vertices.at(i + 1);
  1003. triangle.vertices[2] = vertices.at(i + 2);
  1004. m_triangle_list.append(triangle);
  1005. // Triangle 2
  1006. triangle.vertices[0] = vertices.at(i + 2);
  1007. triangle.vertices[1] = vertices.at(i + 3);
  1008. triangle.vertices[2] = vertices.at(i);
  1009. m_triangle_list.append(triangle);
  1010. }
  1011. } else if (primitive_type == GPU::PrimitiveType::TriangleFan) {
  1012. Triangle triangle;
  1013. triangle.vertices[0] = vertices.at(0); // Root vertex is always the vertex defined first
  1014. // This is technically `n-2` triangles. We start at index 1
  1015. for (size_t i = 1; i < vertices.size() - 1; i++) {
  1016. triangle.vertices[1] = vertices.at(i);
  1017. triangle.vertices[2] = vertices.at(i + 1);
  1018. m_triangle_list.append(triangle);
  1019. }
  1020. } else if (primitive_type == GPU::PrimitiveType::TriangleStrip) {
  1021. Triangle triangle;
  1022. if (vertices.size() < 3)
  1023. return;
  1024. for (size_t i = 0; i < vertices.size() - 2; i++) {
  1025. if (i % 2 == 0) {
  1026. triangle.vertices[0] = vertices.at(i);
  1027. triangle.vertices[1] = vertices.at(i + 1);
  1028. triangle.vertices[2] = vertices.at(i + 2);
  1029. } else {
  1030. triangle.vertices[0] = vertices.at(i + 1);
  1031. triangle.vertices[1] = vertices.at(i);
  1032. triangle.vertices[2] = vertices.at(i + 2);
  1033. }
  1034. m_triangle_list.append(triangle);
  1035. }
  1036. }
  1037. // Clip triangles
  1038. for (auto& triangle : m_triangle_list) {
  1039. m_clipped_vertices.clear_with_capacity();
  1040. m_clipped_vertices.append(triangle.vertices[0]);
  1041. m_clipped_vertices.append(triangle.vertices[1]);
  1042. m_clipped_vertices.append(triangle.vertices[2]);
  1043. m_clipper.clip_triangle_against_frustum(m_clipped_vertices);
  1044. if (m_clip_planes.size() > 0)
  1045. m_clipper.clip_triangle_against_user_defined(m_clipped_vertices, m_clip_planes);
  1046. if (m_clipped_vertices.size() < 3)
  1047. continue;
  1048. for (auto& vertex : m_clipped_vertices)
  1049. calculate_vertex_window_coordinates(vertex);
  1050. Triangle tri;
  1051. tri.vertices[0] = m_clipped_vertices[0];
  1052. for (size_t i = 1; i < m_clipped_vertices.size() - 1; i++) {
  1053. tri.vertices[1] = m_clipped_vertices[i];
  1054. tri.vertices[2] = m_clipped_vertices[i + 1];
  1055. m_processed_triangles.append(tri);
  1056. }
  1057. }
  1058. for (auto& triangle : m_processed_triangles)
  1059. rasterize_triangle(triangle);
  1060. }
  1061. ALWAYS_INLINE void Device::shade_fragments(PixelQuad& quad)
  1062. {
  1063. Array<Vector4<f32x4>, GPU::NUM_TEXTURE_UNITS> texture_stage_texel;
  1064. auto current_color = quad.vertex_color;
  1065. for (GPU::TextureUnitIndex i = 0; i < GPU::NUM_TEXTURE_UNITS; ++i) {
  1066. if (!m_texture_unit_configuration[i].enabled)
  1067. continue;
  1068. auto const& sampler = m_samplers[i];
  1069. // OpenGL 2.0 ¶ 3.5.1 states (in a roundabout way) that texture coordinates must be divided by Q
  1070. auto texel = sampler.sample_2d(quad.texture_coordinates[i].xy() / quad.texture_coordinates[i].w());
  1071. texture_stage_texel[i] = texel;
  1072. INCREASE_STATISTICS_COUNTER(g_num_sampler_calls, 1);
  1073. // FIXME: implement support for GL_ALPHA, GL_LUMINANCE, GL_LUMINANCE_ALPHA, GL_INTENSITY and GL_RGB internal formats
  1074. auto& fixed_function_env = sampler.config().fixed_function_texture_environment;
  1075. switch (fixed_function_env.env_mode) {
  1076. case GPU::TextureEnvMode::Add:
  1077. current_color.set_x(current_color.x() + texel.x());
  1078. current_color.set_y(current_color.y() + texel.y());
  1079. current_color.set_z(current_color.z() + texel.z());
  1080. current_color.set_w(current_color.w() * texel.w());
  1081. break;
  1082. case GPU::TextureEnvMode::Blend: {
  1083. auto blend_color = expand4(fixed_function_env.color);
  1084. current_color.set_x(mix(current_color.x(), blend_color.x(), texel.x()));
  1085. current_color.set_y(mix(current_color.y(), blend_color.y(), texel.y()));
  1086. current_color.set_z(mix(current_color.z(), blend_color.z(), texel.z()));
  1087. current_color.set_w(current_color.w() * texel.w());
  1088. break;
  1089. }
  1090. case GPU::TextureEnvMode::Combine: {
  1091. auto get_source_color = [&](GPU::TextureSource source, u8 texture_stage) {
  1092. switch (source) {
  1093. case GPU::TextureSource::Constant:
  1094. return expand4(fixed_function_env.color);
  1095. case GPU::TextureSource::Previous:
  1096. return current_color;
  1097. case GPU::TextureSource::PrimaryColor:
  1098. return quad.vertex_color;
  1099. case GPU::TextureSource::Texture:
  1100. return texel;
  1101. case GPU::TextureSource::TextureStage:
  1102. return texture_stage_texel[texture_stage];
  1103. }
  1104. VERIFY_NOT_REACHED();
  1105. };
  1106. auto get_argument_value = [](GPU::TextureOperand operand, auto value) {
  1107. switch (operand) {
  1108. case GPU::TextureOperand::OneMinusSourceAlpha:
  1109. case GPU::TextureOperand::OneMinusSourceColor:
  1110. return expand4(FloatVector4 { 1.f, 1.f, 1.f, 1.f }) - value;
  1111. case GPU::TextureOperand::SourceAlpha:
  1112. case GPU::TextureOperand::SourceColor:
  1113. return value;
  1114. }
  1115. VERIFY_NOT_REACHED();
  1116. };
  1117. auto calculate_combinator = [](GPU::TextureCombinator combinator, auto arg0, auto arg1, auto arg2) {
  1118. switch (combinator) {
  1119. case GPU::TextureCombinator::Add:
  1120. return arg0 + arg1;
  1121. case GPU::TextureCombinator::AddSigned:
  1122. return arg0 + arg1 - expand4(FloatVector4 { .5f, .5f, .5f, .5f });
  1123. case GPU::TextureCombinator::Dot3RGB:
  1124. case GPU::TextureCombinator::Dot3RGBA: {
  1125. auto scalar = 4.f * ((arg0.x() - .5f) * (arg1.x() - .5f) + (arg0.y() - 0.5f) * (arg1.y() - 0.5f) + (arg0.z() - 0.5f) * (arg1.z() - 0.5f));
  1126. return Vector4<f32x4> { scalar, scalar, scalar, scalar };
  1127. }
  1128. case GPU::TextureCombinator::Interpolate:
  1129. return mix(arg0, arg1, arg2);
  1130. case GPU::TextureCombinator::Modulate:
  1131. return arg0 * arg1;
  1132. case GPU::TextureCombinator::Replace:
  1133. return arg0;
  1134. case GPU::TextureCombinator::Subtract:
  1135. return arg0 - arg1;
  1136. }
  1137. VERIFY_NOT_REACHED();
  1138. };
  1139. auto calculate_color = [&](GPU::TextureCombinator combinator, auto& operands, auto& sources, u8 texture_stage) {
  1140. auto arg0 = get_argument_value(operands[0], get_source_color(sources[0], texture_stage));
  1141. auto arg1 = get_argument_value(operands[1], get_source_color(sources[1], texture_stage));
  1142. auto arg2 = get_argument_value(operands[2], get_source_color(sources[2], texture_stage));
  1143. return calculate_combinator(combinator, arg0, arg1, arg2);
  1144. };
  1145. auto rgb_color = calculate_color(
  1146. fixed_function_env.rgb_combinator,
  1147. fixed_function_env.rgb_operand,
  1148. fixed_function_env.rgb_source,
  1149. fixed_function_env.rgb_source_texture_stage);
  1150. auto alpha_color = calculate_color(
  1151. fixed_function_env.alpha_combinator,
  1152. fixed_function_env.alpha_operand,
  1153. fixed_function_env.alpha_source,
  1154. fixed_function_env.alpha_source_texture_stage);
  1155. current_color.set_x(rgb_color.x() * fixed_function_env.rgb_scale);
  1156. current_color.set_y(rgb_color.y() * fixed_function_env.rgb_scale);
  1157. current_color.set_z(rgb_color.z() * fixed_function_env.rgb_scale);
  1158. current_color.set_w(alpha_color.w() * fixed_function_env.alpha_scale);
  1159. current_color.clamp(expand4(0.f), expand4(1.f));
  1160. break;
  1161. }
  1162. case GPU::TextureEnvMode::Decal: {
  1163. auto dst_alpha = texel.w();
  1164. current_color.set_x(mix(current_color.x(), texel.x(), dst_alpha));
  1165. current_color.set_y(mix(current_color.y(), texel.y(), dst_alpha));
  1166. current_color.set_z(mix(current_color.z(), texel.z(), dst_alpha));
  1167. break;
  1168. }
  1169. case GPU::TextureEnvMode::Modulate:
  1170. current_color = current_color * texel;
  1171. break;
  1172. case GPU::TextureEnvMode::Replace:
  1173. current_color = texel;
  1174. break;
  1175. }
  1176. }
  1177. quad.out_color = current_color;
  1178. // Calculate fog
  1179. // Math from here: https://opengl-notes.readthedocs.io/en/latest/topics/texturing/aliasing.html
  1180. // FIXME: exponential fog is not vectorized, we should add a SIMD exp function that calculates an approximation.
  1181. if (m_options.fog_enabled) {
  1182. f32x4 factor;
  1183. switch (m_options.fog_mode) {
  1184. case GPU::FogMode::Linear:
  1185. factor = (m_options.fog_end - quad.fog_depth) / (m_options.fog_end - m_options.fog_start);
  1186. break;
  1187. case GPU::FogMode::Exp: {
  1188. auto argument = -m_options.fog_density * quad.fog_depth;
  1189. factor = exp(argument);
  1190. } break;
  1191. case GPU::FogMode::Exp2: {
  1192. auto argument = m_options.fog_density * quad.fog_depth;
  1193. argument *= -argument;
  1194. factor = exp(argument);
  1195. } break;
  1196. default:
  1197. VERIFY_NOT_REACHED();
  1198. }
  1199. // Mix texel's RGB with fog's RBG - leave alpha alone
  1200. auto fog_color = expand4(m_options.fog_color);
  1201. quad.out_color.set_x(mix(fog_color.x(), quad.out_color.x(), factor));
  1202. quad.out_color.set_y(mix(fog_color.y(), quad.out_color.y(), factor));
  1203. quad.out_color.set_z(mix(fog_color.z(), quad.out_color.z(), factor));
  1204. }
  1205. // Multiply coverage with the fragment's alpha to obtain the final alpha value
  1206. quad.out_color.set_w(quad.out_color.w() * quad.coverage);
  1207. }
  1208. void Device::resize(Gfx::IntSize size)
  1209. {
  1210. auto frame_buffer_or_error = FrameBuffer<GPU::ColorType, GPU::DepthType, GPU::StencilType>::try_create(size);
  1211. m_frame_buffer = MUST(frame_buffer_or_error);
  1212. }
  1213. void Device::clear_color(FloatVector4 const& color)
  1214. {
  1215. auto const fill_color = to_argb32(color);
  1216. auto clear_rect = m_frame_buffer->rect();
  1217. if (m_options.scissor_enabled)
  1218. clear_rect.intersect(m_options.scissor_box);
  1219. m_frame_buffer->color_buffer()->fill(fill_color, clear_rect);
  1220. }
  1221. void Device::clear_depth(GPU::DepthType depth)
  1222. {
  1223. auto clear_rect = m_frame_buffer->rect();
  1224. if (m_options.scissor_enabled)
  1225. clear_rect.intersect(m_options.scissor_box);
  1226. m_frame_buffer->depth_buffer()->fill(depth, clear_rect);
  1227. }
  1228. void Device::clear_stencil(GPU::StencilType value)
  1229. {
  1230. auto clear_rect = m_frame_buffer->rect();
  1231. if (m_options.scissor_enabled)
  1232. clear_rect.intersect(m_options.scissor_box);
  1233. m_frame_buffer->stencil_buffer()->fill(value, clear_rect);
  1234. }
  1235. GPU::ImageDataLayout Device::color_buffer_data_layout(Vector2<u32> size, Vector2<i32> offset)
  1236. {
  1237. return {
  1238. .pixel_type = {
  1239. .format = GPU::PixelFormat::BGRA,
  1240. .bits = GPU::PixelComponentBits::B8_8_8_8,
  1241. .data_type = GPU::PixelDataType::UnsignedInt,
  1242. .components_order = GPU::ComponentsOrder::Reversed,
  1243. },
  1244. .dimensions = {
  1245. .width = static_cast<u32>(m_frame_buffer->rect().width()),
  1246. .height = static_cast<u32>(m_frame_buffer->rect().height()),
  1247. .depth = 1,
  1248. },
  1249. .selection = {
  1250. .offset_x = offset.x(),
  1251. .offset_y = offset.y(),
  1252. .offset_z = 0,
  1253. .width = size.x(),
  1254. .height = size.y(),
  1255. .depth = 1,
  1256. },
  1257. };
  1258. }
  1259. GPU::ImageDataLayout Device::depth_buffer_data_layout(Vector2<u32> size, Vector2<i32> offset)
  1260. {
  1261. return {
  1262. .pixel_type = {
  1263. .format = GPU::PixelFormat::DepthComponent,
  1264. .bits = GPU::PixelComponentBits::AllBits,
  1265. .data_type = GPU::PixelDataType::Float,
  1266. },
  1267. .dimensions = {
  1268. .width = static_cast<u32>(m_frame_buffer->rect().width()),
  1269. .height = static_cast<u32>(m_frame_buffer->rect().height()),
  1270. .depth = 1,
  1271. },
  1272. .selection = {
  1273. .offset_x = offset.x(),
  1274. .offset_y = offset.y(),
  1275. .offset_z = 0,
  1276. .width = size.x(),
  1277. .height = size.y(),
  1278. .depth = 1,
  1279. },
  1280. };
  1281. }
  1282. void Device::blit_from_color_buffer(Gfx::Bitmap& target)
  1283. {
  1284. m_frame_buffer->color_buffer()->blit_flipped_to_bitmap(target, m_frame_buffer->rect());
  1285. if constexpr (ENABLE_STATISTICS_OVERLAY)
  1286. draw_statistics_overlay(target);
  1287. }
  1288. void Device::blit_from_color_buffer(NonnullRefPtr<GPU::Image> image, u32 level, Vector2<u32> input_size, Vector2<i32> input_offset, Vector3<i32> output_offset)
  1289. {
  1290. auto input_layout = color_buffer_data_layout(input_size, input_offset);
  1291. auto const* input_data = m_frame_buffer->color_buffer()->scanline(0);
  1292. auto const& softgpu_image = reinterpret_cast<Image*>(image.ptr());
  1293. auto output_layout = softgpu_image->image_data_layout(level, output_offset);
  1294. auto* output_data = softgpu_image->texel_pointer(level, 0, 0, 0);
  1295. PixelConverter converter { input_layout, output_layout };
  1296. auto conversion_result = converter.convert(input_data, output_data, {});
  1297. if (conversion_result.is_error())
  1298. dbgln("Pixel conversion failed: {}", conversion_result.error().string_literal());
  1299. }
  1300. void Device::blit_from_color_buffer(void* output_data, Vector2<i32> input_offset, GPU::ImageDataLayout const& output_layout)
  1301. {
  1302. auto const& output_selection = output_layout.selection;
  1303. auto input_layout = color_buffer_data_layout({ output_selection.width, output_selection.height }, input_offset);
  1304. PixelConverter converter { input_layout, output_layout };
  1305. auto const* input_data = m_frame_buffer->color_buffer()->scanline(0);
  1306. auto conversion_result = converter.convert(input_data, output_data, {});
  1307. if (conversion_result.is_error())
  1308. dbgln("Pixel conversion failed: {}", conversion_result.error().string_literal());
  1309. }
  1310. void Device::blit_from_depth_buffer(void* output_data, Vector2<i32> input_offset, GPU::ImageDataLayout const& output_layout)
  1311. {
  1312. auto const& output_selection = output_layout.selection;
  1313. auto input_layout = depth_buffer_data_layout({ output_selection.width, output_selection.height }, input_offset);
  1314. PixelConverter converter { input_layout, output_layout };
  1315. auto const* input_data = m_frame_buffer->depth_buffer()->scanline(0);
  1316. auto conversion_result = converter.convert(input_data, output_data, {});
  1317. if (conversion_result.is_error())
  1318. dbgln("Pixel conversion failed: {}", conversion_result.error().string_literal());
  1319. }
  1320. void Device::blit_from_depth_buffer(NonnullRefPtr<GPU::Image> image, u32 level, Vector2<u32> input_size, Vector2<i32> input_offset, Vector3<i32> output_offset)
  1321. {
  1322. auto input_layout = depth_buffer_data_layout(input_size, input_offset);
  1323. auto const* input_data = m_frame_buffer->depth_buffer()->scanline(0);
  1324. auto const& softgpu_image = reinterpret_cast<Image*>(image.ptr());
  1325. auto output_layout = softgpu_image->image_data_layout(level, output_offset);
  1326. auto* output_data = softgpu_image->texel_pointer(level, 0, 0, 0);
  1327. PixelConverter converter { input_layout, output_layout };
  1328. auto conversion_result = converter.convert(input_data, output_data, {});
  1329. if (conversion_result.is_error())
  1330. dbgln("Pixel conversion failed: {}", conversion_result.error().string_literal());
  1331. }
  1332. void Device::blit_to_color_buffer_at_raster_position(void const* input_data, GPU::ImageDataLayout const& input_layout)
  1333. {
  1334. if (!m_raster_position.valid)
  1335. return;
  1336. auto input_selection = input_layout.selection;
  1337. INCREASE_STATISTICS_COUNTER(g_num_pixels, input_selection.width * input_selection.height);
  1338. INCREASE_STATISTICS_COUNTER(g_num_pixels_shaded, input_selection.width * input_selection.height);
  1339. auto const rasterization_rect = get_rasterization_rect_of_size({ input_selection.width, input_selection.height });
  1340. auto output_layout = color_buffer_data_layout(
  1341. { static_cast<u32>(rasterization_rect.width()), static_cast<u32>(rasterization_rect.height()) },
  1342. { rasterization_rect.x(), rasterization_rect.y() });
  1343. PixelConverter converter { input_layout, output_layout };
  1344. auto* output_data = m_frame_buffer->color_buffer()->scanline(0);
  1345. auto conversion_result = converter.convert(input_data, output_data, {});
  1346. if (conversion_result.is_error())
  1347. dbgln("Pixel conversion failed: {}", conversion_result.error().string_literal());
  1348. }
  1349. void Device::blit_to_depth_buffer_at_raster_position(void const* input_data, GPU::ImageDataLayout const& input_layout)
  1350. {
  1351. if (!m_raster_position.valid)
  1352. return;
  1353. auto input_selection = input_layout.selection;
  1354. auto const rasterization_rect = get_rasterization_rect_of_size({ input_selection.width, input_selection.height });
  1355. auto output_layout = depth_buffer_data_layout(
  1356. { static_cast<u32>(rasterization_rect.width()), static_cast<u32>(rasterization_rect.height()) },
  1357. { rasterization_rect.x(), rasterization_rect.y() });
  1358. PixelConverter converter { input_layout, output_layout };
  1359. auto* output_data = m_frame_buffer->depth_buffer()->scanline(0);
  1360. auto conversion_result = converter.convert(input_data, output_data, {});
  1361. if (conversion_result.is_error())
  1362. dbgln("Pixel conversion failed: {}", conversion_result.error().string_literal());
  1363. }
  1364. void Device::draw_statistics_overlay(Gfx::Bitmap& target)
  1365. {
  1366. static Core::ElapsedTimer timer;
  1367. static DeprecatedString debug_string;
  1368. static int frame_counter;
  1369. frame_counter++;
  1370. int milliseconds = 0;
  1371. if (timer.is_valid())
  1372. milliseconds = timer.elapsed();
  1373. else
  1374. timer.start();
  1375. Gfx::Painter painter { target };
  1376. if (milliseconds > MILLISECONDS_PER_STATISTICS_PERIOD) {
  1377. int num_rendertarget_pixels = m_frame_buffer->rect().size().area();
  1378. StringBuilder builder;
  1379. builder.append(DeprecatedString::formatted("Timings : {:.1}ms {:.1}FPS\n",
  1380. static_cast<double>(milliseconds) / frame_counter,
  1381. (milliseconds > 0) ? 1000.0 * frame_counter / milliseconds : 9999.0));
  1382. builder.append(DeprecatedString::formatted("Triangles : {}\n", g_num_rasterized_triangles));
  1383. builder.append(DeprecatedString::formatted("SIMD usage : {}%\n", g_num_quads > 0 ? g_num_pixels_shaded * 25 / g_num_quads : 0));
  1384. builder.append(DeprecatedString::formatted("Pixels : {}, Stencil: {}%, Shaded: {}%, Blended: {}%, Overdraw: {}%\n",
  1385. g_num_pixels,
  1386. g_num_pixels > 0 ? g_num_stencil_writes * 100 / g_num_pixels : 0,
  1387. g_num_pixels > 0 ? g_num_pixels_shaded * 100 / g_num_pixels : 0,
  1388. g_num_pixels_shaded > 0 ? g_num_pixels_blended * 100 / g_num_pixels_shaded : 0,
  1389. num_rendertarget_pixels > 0 ? g_num_pixels_shaded * 100 / num_rendertarget_pixels - 100 : 0));
  1390. builder.append(DeprecatedString::formatted("Sampler calls: {}\n", g_num_sampler_calls));
  1391. debug_string = builder.to_deprecated_string();
  1392. frame_counter = 0;
  1393. timer.start();
  1394. }
  1395. g_num_rasterized_triangles = 0;
  1396. g_num_pixels = 0;
  1397. g_num_pixels_shaded = 0;
  1398. g_num_pixels_blended = 0;
  1399. g_num_sampler_calls = 0;
  1400. g_num_stencil_writes = 0;
  1401. g_num_quads = 0;
  1402. auto& font = Gfx::FontDatabase::default_fixed_width_font();
  1403. for (int y = -1; y < 2; y++)
  1404. for (int x = -1; x < 2; x++)
  1405. if (x != 0 && y != 0)
  1406. painter.draw_text(target.rect().translated(x + 2, y + 2), debug_string, font, Gfx::TextAlignment::TopLeft, Gfx::Color::Black);
  1407. painter.draw_text(target.rect().translated(2, 2), debug_string, font, Gfx::TextAlignment::TopLeft, Gfx::Color::White);
  1408. }
  1409. void Device::set_options(GPU::RasterizerOptions const& options)
  1410. {
  1411. m_options = options;
  1412. if (m_options.enable_blending)
  1413. setup_blend_factors();
  1414. }
  1415. void Device::set_light_model_params(GPU::LightModelParameters const& lighting_model)
  1416. {
  1417. m_lighting_model = lighting_model;
  1418. }
  1419. NonnullRefPtr<GPU::Image> Device::create_image(GPU::PixelFormat const& pixel_format, u32 width, u32 height, u32 depth, u32 max_levels)
  1420. {
  1421. VERIFY(width > 0);
  1422. VERIFY(height > 0);
  1423. VERIFY(depth > 0);
  1424. VERIFY(max_levels > 0);
  1425. return adopt_ref(*new Image(this, pixel_format, width, height, depth, max_levels));
  1426. }
  1427. void Device::set_sampler_config(unsigned sampler, GPU::SamplerConfig const& config)
  1428. {
  1429. VERIFY(config.bound_image.is_null() || config.bound_image->ownership_token() == this);
  1430. m_samplers[sampler].set_config(config);
  1431. }
  1432. void Device::set_light_state(unsigned int light_id, GPU::Light const& light)
  1433. {
  1434. m_lights.at(light_id) = light;
  1435. }
  1436. void Device::set_material_state(GPU::Face face, GPU::Material const& material)
  1437. {
  1438. m_materials[face] = material;
  1439. }
  1440. void Device::set_stencil_configuration(GPU::Face face, GPU::StencilConfiguration const& stencil_configuration)
  1441. {
  1442. m_stencil_configuration[face] = stencil_configuration;
  1443. }
  1444. void Device::set_texture_unit_configuration(GPU::TextureUnitIndex index, GPU::TextureUnitConfiguration const& configuration)
  1445. {
  1446. m_texture_unit_configuration[index] = configuration;
  1447. }
  1448. void Device::set_raster_position(GPU::RasterPosition const& raster_position)
  1449. {
  1450. m_raster_position = raster_position;
  1451. }
  1452. void Device::set_clip_planes(Vector<FloatVector4> const& clip_planes)
  1453. {
  1454. m_clip_planes = clip_planes;
  1455. }
  1456. void Device::set_raster_position(FloatVector4 const& position, FloatMatrix4x4 const& model_view_transform, FloatMatrix4x4 const& projection_transform)
  1457. {
  1458. auto const eye_coordinates = model_view_transform * position;
  1459. auto const clip_coordinates = projection_transform * eye_coordinates;
  1460. // FIXME: implement clipping
  1461. m_raster_position.valid = true;
  1462. auto ndc_coordinates = clip_coordinates / clip_coordinates.w();
  1463. ndc_coordinates.set_w(clip_coordinates.w());
  1464. auto const viewport = m_options.viewport;
  1465. auto const viewport_half_width = viewport.width() / 2.0f;
  1466. auto const viewport_half_height = viewport.height() / 2.0f;
  1467. auto const viewport_center_x = viewport.x() + viewport_half_width;
  1468. auto const viewport_center_y = viewport.y() + viewport_half_height;
  1469. auto const depth_half_range = (m_options.depth_max - m_options.depth_min) / 2;
  1470. auto const depth_halfway = (m_options.depth_min + m_options.depth_max) / 2;
  1471. // FIXME: implement other raster position properties such as color and texcoords
  1472. m_raster_position.window_coordinates = {
  1473. viewport_center_x + ndc_coordinates.x() * viewport_half_width,
  1474. viewport_center_y + ndc_coordinates.y() * viewport_half_height,
  1475. depth_halfway + ndc_coordinates.z() * depth_half_range,
  1476. ndc_coordinates.w(),
  1477. };
  1478. m_raster_position.eye_coordinate_distance = eye_coordinates.length();
  1479. }
  1480. Gfx::IntRect Device::get_rasterization_rect_of_size(Gfx::IntSize size) const
  1481. {
  1482. // Round the X and Y floating point coordinates to the nearest integer; OpenGL 1.5 spec:
  1483. // "Any fragments whose centers lie inside of this rectangle (or on its bottom or left
  1484. // boundaries) are produced in correspondence with this particular group of elements."
  1485. return {
  1486. round_to<int>(m_raster_position.window_coordinates.x()),
  1487. round_to<int>(m_raster_position.window_coordinates.y()),
  1488. size.width(),
  1489. size.height(),
  1490. };
  1491. }
  1492. }
  1493. extern "C" {
  1494. GPU::Device* serenity_gpu_create_device(Gfx::IntSize size)
  1495. {
  1496. return make<SoftGPU::Device>(size).leak_ptr();
  1497. }
  1498. }