Device.cpp 70 KB

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