Device.cpp 71 KB

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