Device.cpp 63 KB

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