Device.cpp 72 KB

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