Device.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  1. /*
  2. * Copyright (c) 2021, Stephan Unverwerth <s.unverwerth@serenityos.org>
  3. * Copyright (c) 2021, Jesse Buhagiar <jooster669@gmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Function.h>
  8. #include <AK/SIMDExtras.h>
  9. #include <AK/SIMDMath.h>
  10. #include <LibCore/ElapsedTimer.h>
  11. #include <LibGfx/Painter.h>
  12. #include <LibGfx/Vector2.h>
  13. #include <LibGfx/Vector3.h>
  14. #include <LibSoftGPU/Config.h>
  15. #include <LibSoftGPU/Device.h>
  16. #include <LibSoftGPU/PixelQuad.h>
  17. #include <LibSoftGPU/SIMD.h>
  18. namespace SoftGPU {
  19. static long long g_num_rasterized_triangles;
  20. static long long g_num_pixels;
  21. static long long g_num_pixels_shaded;
  22. static long long g_num_pixels_blended;
  23. static long long g_num_sampler_calls;
  24. static long long g_num_quads;
  25. using IntVector2 = Gfx::Vector2<int>;
  26. using IntVector3 = Gfx::Vector3<int>;
  27. using AK::SIMD::exp;
  28. using AK::SIMD::expand4;
  29. using AK::SIMD::f32x4;
  30. using AK::SIMD::i32x4;
  31. using AK::SIMD::load4_masked;
  32. using AK::SIMD::maskbits;
  33. using AK::SIMD::maskcount;
  34. using AK::SIMD::none;
  35. using AK::SIMD::store4_masked;
  36. using AK::SIMD::to_f32x4;
  37. constexpr static int edge_function(const IntVector2& a, const IntVector2& b, const IntVector2& c)
  38. {
  39. return ((c.x() - a.x()) * (b.y() - a.y()) - (c.y() - a.y()) * (b.x() - a.x()));
  40. }
  41. constexpr static i32x4 edge_function4(const IntVector2& a, const IntVector2& b, const Vector2<i32x4>& c)
  42. {
  43. return ((c.x() - a.x()) * (b.y() - a.y()) - (c.y() - a.y()) * (b.x() - a.x()));
  44. }
  45. template<typename T, typename U>
  46. constexpr static auto interpolate(const T& v0, const T& v1, const T& v2, const Vector3<U>& barycentric_coords)
  47. {
  48. return v0 * barycentric_coords.x() + v1 * barycentric_coords.y() + v2 * barycentric_coords.z();
  49. }
  50. ALWAYS_INLINE constexpr static Gfx::RGBA32 to_rgba32(const FloatVector4& v)
  51. {
  52. auto clamped = v.clamped(0, 1);
  53. u8 r = clamped.x() * 255;
  54. u8 g = clamped.y() * 255;
  55. u8 b = clamped.z() * 255;
  56. u8 a = clamped.w() * 255;
  57. return a << 24 | r << 16 | g << 8 | b;
  58. }
  59. static FloatVector4 to_vec4(Gfx::RGBA32 rgba)
  60. {
  61. auto constexpr one_over_255 = 1.0f / 255;
  62. return {
  63. ((rgba >> 16) & 0xff) * one_over_255,
  64. ((rgba >> 8) & 0xff) * one_over_255,
  65. (rgba & 0xff) * one_over_255,
  66. ((rgba >> 24) & 0xff) * one_over_255,
  67. };
  68. }
  69. static Gfx::IntRect scissor_box_to_window_coordinates(Gfx::IntRect const& scissor_box, Gfx::IntRect const& window_rect)
  70. {
  71. return scissor_box.translated(0, window_rect.height() - 2 * scissor_box.y() - scissor_box.height());
  72. }
  73. static constexpr void setup_blend_factors(BlendFactor mode, FloatVector4& constant, float& src_alpha, float& dst_alpha, float& src_color, float& dst_color)
  74. {
  75. constant = { 0.0f, 0.0f, 0.0f, 0.0f };
  76. src_alpha = 0;
  77. dst_alpha = 0;
  78. src_color = 0;
  79. dst_color = 0;
  80. switch (mode) {
  81. case BlendFactor::Zero:
  82. break;
  83. case BlendFactor::One:
  84. constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  85. break;
  86. case BlendFactor::SrcColor:
  87. src_color = 1;
  88. break;
  89. case BlendFactor::OneMinusSrcColor:
  90. constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  91. src_color = -1;
  92. break;
  93. case BlendFactor::SrcAlpha:
  94. src_alpha = 1;
  95. break;
  96. case BlendFactor::OneMinusSrcAlpha:
  97. constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  98. src_alpha = -1;
  99. break;
  100. case BlendFactor::DstAlpha:
  101. dst_alpha = 1;
  102. break;
  103. case BlendFactor::OneMinusDstAlpha:
  104. constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  105. dst_alpha = -1;
  106. break;
  107. case BlendFactor::DstColor:
  108. dst_color = 1;
  109. break;
  110. case BlendFactor::OneMinusDstColor:
  111. constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  112. dst_color = -1;
  113. break;
  114. case BlendFactor::SrcAlphaSaturate:
  115. // FIXME: How do we implement this?
  116. break;
  117. default:
  118. VERIFY_NOT_REACHED();
  119. }
  120. }
  121. template<typename PS>
  122. static void rasterize_triangle(const RasterizerOptions& options, Gfx::Bitmap& render_target, DepthBuffer& depth_buffer, const Triangle& triangle, PS pixel_shader)
  123. {
  124. INCREASE_STATISTICS_COUNTER(g_num_rasterized_triangles, 1);
  125. // Since the algorithm is based on blocks of uniform size, we need
  126. // to ensure that our render_target size is actually a multiple of the block size
  127. VERIFY((render_target.width() % 2) == 0);
  128. VERIFY((render_target.height() % 2) == 0);
  129. // Return if alpha testing is a no-op
  130. if (options.enable_alpha_test && options.alpha_test_func == AlphaTestFunction::Never)
  131. return;
  132. // Vertices
  133. Vertex const vertex0 = triangle.vertices[0];
  134. Vertex const vertex1 = triangle.vertices[1];
  135. Vertex const vertex2 = triangle.vertices[2];
  136. constexpr int subpixel_factor = 1 << SUBPIXEL_BITS;
  137. // Calculate area of the triangle for later tests
  138. IntVector2 const v0 { static_cast<int>(vertex0.window_coordinates.x() * subpixel_factor), static_cast<int>(vertex0.window_coordinates.y() * subpixel_factor) };
  139. IntVector2 const v1 { static_cast<int>(vertex1.window_coordinates.x() * subpixel_factor), static_cast<int>(vertex1.window_coordinates.y() * subpixel_factor) };
  140. IntVector2 const v2 { static_cast<int>(vertex2.window_coordinates.x() * subpixel_factor), static_cast<int>(vertex2.window_coordinates.y() * subpixel_factor) };
  141. int area = edge_function(v0, v1, v2);
  142. if (area == 0)
  143. return;
  144. auto const one_over_area = 1.0f / area;
  145. FloatVector4 src_constant {};
  146. float src_factor_src_alpha = 0;
  147. float src_factor_dst_alpha = 0;
  148. float src_factor_src_color = 0;
  149. float src_factor_dst_color = 0;
  150. FloatVector4 dst_constant {};
  151. float dst_factor_src_alpha = 0;
  152. float dst_factor_dst_alpha = 0;
  153. float dst_factor_src_color = 0;
  154. float dst_factor_dst_color = 0;
  155. if (options.enable_blending) {
  156. setup_blend_factors(
  157. options.blend_source_factor,
  158. src_constant,
  159. src_factor_src_alpha,
  160. src_factor_dst_alpha,
  161. src_factor_src_color,
  162. src_factor_dst_color);
  163. setup_blend_factors(
  164. options.blend_destination_factor,
  165. dst_constant,
  166. dst_factor_src_alpha,
  167. dst_factor_dst_alpha,
  168. dst_factor_src_color,
  169. dst_factor_dst_color);
  170. }
  171. auto render_bounds = render_target.rect();
  172. auto window_scissor_rect = scissor_box_to_window_coordinates(options.scissor_box, render_target.rect());
  173. if (options.scissor_enabled)
  174. render_bounds.intersect(window_scissor_rect);
  175. // Obey top-left rule:
  176. // This sets up "zero" for later pixel coverage tests.
  177. // Depending on where on the triangle the edge is located
  178. // it is either tested against 0 or 1, effectively
  179. // turning "< 0" into "<= 0"
  180. IntVector3 zero { 1, 1, 1 };
  181. if (v1.y() > v0.y() || (v1.y() == v0.y() && v1.x() < v0.x()))
  182. zero.set_z(0);
  183. if (v2.y() > v1.y() || (v2.y() == v1.y() && v2.x() < v1.x()))
  184. zero.set_x(0);
  185. if (v0.y() > v2.y() || (v0.y() == v2.y() && v0.x() < v2.x()))
  186. zero.set_y(0);
  187. // This function calculates the 3 edge values for the pixel relative to the triangle.
  188. auto calculate_edge_values4 = [v0, v1, v2](const Vector2<i32x4>& p) -> Vector3<i32x4> {
  189. return {
  190. edge_function4(v1, v2, p),
  191. edge_function4(v2, v0, p),
  192. edge_function4(v0, v1, p),
  193. };
  194. };
  195. // This function tests whether a point as identified by its 3 edge values lies within the triangle
  196. auto test_point4 = [zero](const Vector3<i32x4>& edges) -> i32x4 {
  197. return edges.x() >= zero.x()
  198. && edges.y() >= zero.y()
  199. && edges.z() >= zero.z();
  200. };
  201. auto test_scissor4 = [window_scissor_rect](const Vector2<i32x4>& screen_coordinates) -> i32x4 {
  202. return screen_coordinates.x() >= window_scissor_rect.x()
  203. && screen_coordinates.x() < window_scissor_rect.x() + window_scissor_rect.width()
  204. && screen_coordinates.y() >= window_scissor_rect.y()
  205. && screen_coordinates.y() < window_scissor_rect.y() + window_scissor_rect.height();
  206. };
  207. // Calculate block-based bounds
  208. // clang-format off
  209. int const bx0 = max(render_bounds.left(), min(min(v0.x(), v1.x()), v2.x()) / subpixel_factor) & ~1;
  210. int const bx1 = (min(render_bounds.right(), max(max(v0.x(), v1.x()), v2.x()) / subpixel_factor) & ~1) + 2;
  211. int const by0 = max(render_bounds.top(), min(min(v0.y(), v1.y()), v2.y()) / subpixel_factor) & ~1;
  212. int const by1 = (min(render_bounds.bottom(), max(max(v0.y(), v1.y()), v2.y()) / subpixel_factor) & ~1) + 2;
  213. // clang-format on
  214. // Fog depths
  215. float const vertex0_eye_absz = fabs(vertex0.eye_coordinates.z());
  216. float const vertex1_eye_absz = fabs(vertex1.eye_coordinates.z());
  217. float const vertex2_eye_absz = fabs(vertex2.eye_coordinates.z());
  218. // FIXME: implement stencil testing
  219. // Iterate over all blocks within the bounds of the triangle
  220. for (int by = by0; by < by1; by += 2) {
  221. for (int bx = bx0; bx < bx1; bx += 2) {
  222. PixelQuad quad;
  223. quad.screen_coordinates = {
  224. i32x4 { bx, bx + 1, bx, bx + 1 },
  225. i32x4 { by, by, by + 1, by + 1 },
  226. };
  227. auto edge_values = calculate_edge_values4(quad.screen_coordinates * subpixel_factor);
  228. // Generate triangle coverage mask
  229. quad.mask = test_point4(edge_values);
  230. if (options.scissor_enabled) {
  231. quad.mask &= test_scissor4(quad.screen_coordinates);
  232. }
  233. if (none(quad.mask))
  234. continue;
  235. INCREASE_STATISTICS_COUNTER(g_num_quads, 1);
  236. INCREASE_STATISTICS_COUNTER(g_num_pixels, maskcount(quad.mask));
  237. // Calculate barycentric coordinates from previously calculated edge values
  238. quad.barycentrics = Vector3<f32x4> {
  239. to_f32x4(edge_values.x()),
  240. to_f32x4(edge_values.y()),
  241. to_f32x4(edge_values.z()),
  242. } * one_over_area;
  243. float* depth_ptrs[4] = {
  244. &depth_buffer.scanline(by)[bx],
  245. &depth_buffer.scanline(by)[bx + 1],
  246. &depth_buffer.scanline(by + 1)[bx],
  247. &depth_buffer.scanline(by + 1)[bx + 1],
  248. };
  249. // AND the depth mask onto the coverage mask
  250. if (options.enable_depth_test) {
  251. auto depth = load4_masked(depth_ptrs[0], depth_ptrs[1], depth_ptrs[2], depth_ptrs[3], quad.mask);
  252. quad.depth = interpolate(vertex0.window_coordinates.z(), vertex1.window_coordinates.z(), vertex2.window_coordinates.z(), quad.barycentrics);
  253. // FIXME: Also apply depth_offset_factor which depends on the depth gradient
  254. quad.depth += options.depth_offset_constant * NumericLimits<float>::epsilon();
  255. switch (options.depth_func) {
  256. case DepthTestFunction::Always:
  257. break;
  258. case DepthTestFunction::Never:
  259. quad.mask ^= quad.mask;
  260. break;
  261. case DepthTestFunction::Greater:
  262. quad.mask &= quad.depth > depth;
  263. break;
  264. case DepthTestFunction::GreaterOrEqual:
  265. quad.mask &= quad.depth >= depth;
  266. break;
  267. case DepthTestFunction::NotEqual:
  268. #ifdef __SSE__
  269. quad.mask &= quad.depth != depth;
  270. #else
  271. quad.mask[0] = bit_cast<u32>(quad.depth[0]) != bit_cast<u32>(depth[0]) ? -1 : 0;
  272. quad.mask[1] = bit_cast<u32>(quad.depth[1]) != bit_cast<u32>(depth[1]) ? -1 : 0;
  273. quad.mask[2] = bit_cast<u32>(quad.depth[2]) != bit_cast<u32>(depth[2]) ? -1 : 0;
  274. quad.mask[3] = bit_cast<u32>(quad.depth[3]) != bit_cast<u32>(depth[3]) ? -1 : 0;
  275. #endif
  276. break;
  277. case DepthTestFunction::Equal:
  278. #ifdef __SSE__
  279. quad.mask &= quad.depth == depth;
  280. #else
  281. //
  282. // This is an interesting quirk that occurs due to us using the x87 FPU when Serenity is
  283. // compiled for the i386 target. When we calculate our depth value to be stored in the buffer,
  284. // it is an 80-bit x87 floating point number, however, when stored into the DepthBuffer, this is
  285. // truncated to 32 bits. This 38 bit loss of precision means that when x87 `FCOMP` is eventually
  286. // used here the comparison fails.
  287. // This could be solved by using a `long double` for the depth buffer, however this would take
  288. // up significantly more space and is completely overkill for a depth buffer. As such, comparing
  289. // the first 32-bits of this depth value is "good enough" that if we get a hit on it being
  290. // equal, we can pretty much guarantee that it's actually equal.
  291. //
  292. quad.mask[0] = bit_cast<u32>(quad.depth[0]) == bit_cast<u32>(depth[0]) ? -1 : 0;
  293. quad.mask[1] = bit_cast<u32>(quad.depth[1]) == bit_cast<u32>(depth[1]) ? -1 : 0;
  294. quad.mask[2] = bit_cast<u32>(quad.depth[2]) == bit_cast<u32>(depth[2]) ? -1 : 0;
  295. quad.mask[3] = bit_cast<u32>(quad.depth[3]) == bit_cast<u32>(depth[3]) ? -1 : 0;
  296. #endif
  297. break;
  298. case DepthTestFunction::LessOrEqual:
  299. quad.mask &= quad.depth <= depth;
  300. break;
  301. case DepthTestFunction::Less:
  302. quad.mask &= quad.depth < depth;
  303. break;
  304. }
  305. // Nice, no pixels passed the depth test -> block rejected by early z
  306. if (none(quad.mask))
  307. continue;
  308. }
  309. INCREASE_STATISTICS_COUNTER(g_num_pixels_shaded, maskcount(quad.mask));
  310. // Draw the pixels according to the previously generated mask
  311. auto const w_coordinates = Vector3<f32x4> {
  312. expand4(vertex0.window_coordinates.w()),
  313. expand4(vertex1.window_coordinates.w()),
  314. expand4(vertex2.window_coordinates.w()),
  315. };
  316. auto const interpolated_reciprocal_w = interpolate(w_coordinates.x(), w_coordinates.y(), w_coordinates.z(), quad.barycentrics);
  317. auto const interpolated_w = 1.0f / interpolated_reciprocal_w;
  318. quad.barycentrics = quad.barycentrics * w_coordinates * interpolated_w;
  319. // FIXME: make this more generic. We want to interpolate more than just color and uv
  320. if (options.shade_smooth) {
  321. quad.vertex_color = interpolate(expand4(vertex0.color), expand4(vertex1.color), expand4(vertex2.color), quad.barycentrics);
  322. } else {
  323. quad.vertex_color = expand4(vertex0.color);
  324. }
  325. quad.uv = interpolate(expand4(vertex0.tex_coord), expand4(vertex1.tex_coord), expand4(vertex2.tex_coord), quad.barycentrics);
  326. if (options.fog_enabled) {
  327. // Calculate depth of fragment for fog
  328. //
  329. // OpenGL 1.5 spec chapter 3.10: "An implementation may choose to approximate the
  330. // eye-coordinate distance from the eye to each fragment center by |Ze|."
  331. quad.fog_depth = interpolate(expand4(vertex0_eye_absz), expand4(vertex1_eye_absz), expand4(vertex2_eye_absz), quad.barycentrics);
  332. }
  333. pixel_shader(quad);
  334. if (options.enable_alpha_test && options.alpha_test_func != AlphaTestFunction::Always) {
  335. switch (options.alpha_test_func) {
  336. case AlphaTestFunction::Less:
  337. quad.mask &= quad.out_color.w() < options.alpha_test_ref_value;
  338. break;
  339. case AlphaTestFunction::Equal:
  340. quad.mask &= quad.out_color.w() == options.alpha_test_ref_value;
  341. break;
  342. case AlphaTestFunction::LessOrEqual:
  343. quad.mask &= quad.out_color.w() <= options.alpha_test_ref_value;
  344. break;
  345. case AlphaTestFunction::Greater:
  346. quad.mask &= quad.out_color.w() > options.alpha_test_ref_value;
  347. break;
  348. case AlphaTestFunction::NotEqual:
  349. quad.mask &= quad.out_color.w() != options.alpha_test_ref_value;
  350. break;
  351. case AlphaTestFunction::GreaterOrEqual:
  352. quad.mask &= quad.out_color.w() >= options.alpha_test_ref_value;
  353. break;
  354. case AlphaTestFunction::Never:
  355. case AlphaTestFunction::Always:
  356. VERIFY_NOT_REACHED();
  357. }
  358. }
  359. // Write to depth buffer
  360. if (options.enable_depth_test && options.enable_depth_write) {
  361. store4_masked(quad.depth, depth_ptrs[0], depth_ptrs[1], depth_ptrs[2], depth_ptrs[3], quad.mask);
  362. }
  363. // We will not update the color buffer at all
  364. if (!options.color_mask || !options.enable_color_write)
  365. continue;
  366. Gfx::RGBA32* color_ptrs[4] = {
  367. &render_target.scanline(by)[bx],
  368. &render_target.scanline(by)[bx + 1],
  369. &render_target.scanline(by + 1)[bx],
  370. &render_target.scanline(by + 1)[bx + 1],
  371. };
  372. int bits = maskbits(quad.mask);
  373. if (options.enable_blending) {
  374. INCREASE_STATISTICS_COUNTER(g_num_pixels_blended, maskcount(quad.mask));
  375. // Blend color values from pixel_staging into render_target
  376. FloatVector4 dst_aos[4] {
  377. bits & 1 ? to_vec4(*color_ptrs[0]) : FloatVector4 { 0, 0, 0, 0 },
  378. bits & 2 ? to_vec4(*color_ptrs[1]) : FloatVector4 { 0, 0, 0, 0 },
  379. bits & 4 ? to_vec4(*color_ptrs[2]) : FloatVector4 { 0, 0, 0, 0 },
  380. bits & 8 ? to_vec4(*color_ptrs[3]) : FloatVector4 { 0, 0, 0, 0 },
  381. };
  382. auto dst = Vector4<f32x4> {
  383. f32x4 { dst_aos[0].x(), dst_aos[1].x(), dst_aos[2].x(), dst_aos[3].x() },
  384. f32x4 { dst_aos[0].y(), dst_aos[1].y(), dst_aos[2].y(), dst_aos[3].y() },
  385. f32x4 { dst_aos[0].z(), dst_aos[1].z(), dst_aos[2].z(), dst_aos[3].z() },
  386. f32x4 { dst_aos[0].w(), dst_aos[1].w(), dst_aos[2].w(), dst_aos[3].w() },
  387. };
  388. Vector4<f32x4> const& src = quad.out_color;
  389. auto src_factor = expand4(src_constant)
  390. + src * src_factor_src_color
  391. + Vector4<f32x4> { src.w(), src.w(), src.w(), src.w() } * src_factor_src_alpha
  392. + dst * src_factor_dst_color
  393. + Vector4<f32x4> { dst.w(), dst.w(), dst.w(), dst.w() } * src_factor_dst_alpha;
  394. auto dst_factor = expand4(dst_constant)
  395. + src * dst_factor_src_color
  396. + Vector4<f32x4> { src.w(), src.w(), src.w(), src.w() } * dst_factor_src_alpha
  397. + dst * dst_factor_dst_color
  398. + Vector4<f32x4> { dst.w(), dst.w(), dst.w(), dst.w() } * dst_factor_dst_alpha;
  399. quad.out_color = src * src_factor + dst * dst_factor;
  400. }
  401. if (bits & 1)
  402. *color_ptrs[0] = to_rgba32(FloatVector4 { quad.out_color.x()[0], quad.out_color.y()[0], quad.out_color.z()[0], quad.out_color.w()[0] });
  403. if (bits & 2)
  404. *color_ptrs[1] = to_rgba32(FloatVector4 { quad.out_color.x()[1], quad.out_color.y()[1], quad.out_color.z()[1], quad.out_color.w()[1] });
  405. if (bits & 4)
  406. *color_ptrs[2] = to_rgba32(FloatVector4 { quad.out_color.x()[2], quad.out_color.y()[2], quad.out_color.z()[2], quad.out_color.w()[2] });
  407. if (bits & 8)
  408. *color_ptrs[3] = to_rgba32(FloatVector4 { quad.out_color.x()[3], quad.out_color.y()[3], quad.out_color.z()[3], quad.out_color.w()[3] });
  409. }
  410. }
  411. }
  412. static Gfx::IntSize closest_multiple(const Gfx::IntSize& min_size, size_t step)
  413. {
  414. int width = ((min_size.width() + step - 1) / step) * step;
  415. int height = ((min_size.height() + step - 1) / step) * step;
  416. return { width, height };
  417. }
  418. Device::Device(const Gfx::IntSize& min_size)
  419. : m_render_target { Gfx::Bitmap::try_create(Gfx::BitmapFormat::BGRA8888, closest_multiple(min_size, 2)).release_value_but_fixme_should_propagate_errors() }
  420. , m_depth_buffer { adopt_own(*new DepthBuffer(closest_multiple(min_size, 2))) }
  421. {
  422. m_options.scissor_box = m_render_target->rect();
  423. }
  424. DeviceInfo Device::info() const
  425. {
  426. return {
  427. .vendor_name = "SerenityOS",
  428. .device_name = "SoftGPU",
  429. .num_texture_units = NUM_SAMPLERS
  430. };
  431. }
  432. static void generate_texture_coordinates(Vertex& vertex, RasterizerOptions const& options)
  433. {
  434. auto generate_coordinate = [&](size_t config_index) -> float {
  435. auto mode = options.texcoord_generation_config[config_index].mode;
  436. switch (mode) {
  437. case TexCoordGenerationMode::ObjectLinear: {
  438. auto coefficients = options.texcoord_generation_config[config_index].coefficients;
  439. return coefficients.dot(vertex.position);
  440. }
  441. case TexCoordGenerationMode::EyeLinear: {
  442. auto coefficients = options.texcoord_generation_config[config_index].coefficients;
  443. return coefficients.dot(vertex.eye_coordinates);
  444. }
  445. case TexCoordGenerationMode::SphereMap: {
  446. auto const eye_unit = vertex.eye_coordinates.normalized();
  447. FloatVector3 const eye_unit_xyz = { eye_unit.x(), eye_unit.y(), eye_unit.z() };
  448. auto const normal = vertex.normal;
  449. auto reflection = eye_unit_xyz - normal * 2 * normal.dot(eye_unit_xyz);
  450. reflection.set_z(reflection.z() + 1);
  451. auto const reflection_value = (config_index == 0) ? reflection.x() : reflection.y();
  452. return reflection_value / (2 * reflection.length()) + 0.5f;
  453. }
  454. case TexCoordGenerationMode::ReflectionMap: {
  455. auto const eye_unit = vertex.eye_coordinates.normalized();
  456. FloatVector3 const eye_unit_xyz = { eye_unit.x(), eye_unit.y(), eye_unit.z() };
  457. auto const normal = vertex.normal;
  458. auto reflection = eye_unit_xyz - normal * 2 * normal.dot(eye_unit_xyz);
  459. switch (config_index) {
  460. case 0:
  461. return reflection.x();
  462. case 1:
  463. return reflection.y();
  464. case 2:
  465. return reflection.z();
  466. default:
  467. VERIFY_NOT_REACHED();
  468. }
  469. }
  470. case TexCoordGenerationMode::NormalMap: {
  471. auto const normal = vertex.normal;
  472. switch (config_index) {
  473. case 0:
  474. return normal.x();
  475. case 1:
  476. return normal.y();
  477. case 2:
  478. return normal.z();
  479. default:
  480. VERIFY_NOT_REACHED();
  481. }
  482. }
  483. default:
  484. VERIFY_NOT_REACHED();
  485. }
  486. };
  487. auto const enabled_coords = options.texcoord_generation_enabled_coordinates;
  488. vertex.tex_coord = {
  489. ((enabled_coords & TexCoordGenerationCoordinate::S) > 0) ? generate_coordinate(0) : vertex.tex_coord.x(),
  490. ((enabled_coords & TexCoordGenerationCoordinate::T) > 0) ? generate_coordinate(1) : vertex.tex_coord.y(),
  491. ((enabled_coords & TexCoordGenerationCoordinate::R) > 0) ? generate_coordinate(2) : vertex.tex_coord.z(),
  492. ((enabled_coords & TexCoordGenerationCoordinate::Q) > 0) ? generate_coordinate(3) : vertex.tex_coord.w(),
  493. };
  494. }
  495. void Device::draw_primitives(PrimitiveType primitive_type, FloatMatrix4x4 const& model_view_transform, FloatMatrix3x3 const& normal_transform,
  496. FloatMatrix4x4 const& projection_transform, FloatMatrix4x4 const& texture_transform, Vector<Vertex> const& vertices,
  497. Vector<size_t> const& enabled_texture_units)
  498. {
  499. // At this point, the user has effectively specified that they are done with defining the geometry
  500. // of what they want to draw. We now need to do a few things (https://www.khronos.org/opengl/wiki/Rendering_Pipeline_Overview):
  501. //
  502. // 1. Transform all of the vertices in the current vertex list into eye space by multiplying the model-view matrix
  503. // 2. Transform all of the vertices from eye space into clip space by multiplying by the projection matrix
  504. // 3. If culling is enabled, we cull the desired faces (https://learnopengl.com/Advanced-OpenGL/Face-culling)
  505. // 4. Each element of the vertex is then divided by w to bring the positions into NDC (Normalized Device Coordinates)
  506. // 5. The vertices are sorted (for the rasterizer, how are we doing this? 3Dfx did this top to bottom in terms of vertex y coordinates)
  507. // 6. The vertices are then sent off to the rasterizer and drawn to the screen
  508. float scr_width = m_render_target->width();
  509. float scr_height = m_render_target->height();
  510. m_triangle_list.clear_with_capacity();
  511. m_processed_triangles.clear_with_capacity();
  512. // Let's construct some triangles
  513. if (primitive_type == PrimitiveType::Triangles) {
  514. Triangle triangle;
  515. for (size_t i = 0; i < vertices.size(); i += 3) {
  516. triangle.vertices[0] = vertices.at(i);
  517. triangle.vertices[1] = vertices.at(i + 1);
  518. triangle.vertices[2] = vertices.at(i + 2);
  519. m_triangle_list.append(triangle);
  520. }
  521. } else if (primitive_type == PrimitiveType::Quads) {
  522. // We need to construct two triangles to form the quad
  523. Triangle triangle;
  524. VERIFY(vertices.size() % 4 == 0);
  525. for (size_t i = 0; i < vertices.size(); i += 4) {
  526. // Triangle 1
  527. triangle.vertices[0] = vertices.at(i);
  528. triangle.vertices[1] = vertices.at(i + 1);
  529. triangle.vertices[2] = vertices.at(i + 2);
  530. m_triangle_list.append(triangle);
  531. // Triangle 2
  532. triangle.vertices[0] = vertices.at(i + 2);
  533. triangle.vertices[1] = vertices.at(i + 3);
  534. triangle.vertices[2] = vertices.at(i);
  535. m_triangle_list.append(triangle);
  536. }
  537. } else if (primitive_type == PrimitiveType::TriangleFan) {
  538. Triangle triangle;
  539. triangle.vertices[0] = vertices.at(0); // Root vertex is always the vertex defined first
  540. for (size_t i = 1; i < vertices.size() - 1; i++) // This is technically `n-2` triangles. We start at index 1
  541. {
  542. triangle.vertices[1] = vertices.at(i);
  543. triangle.vertices[2] = vertices.at(i + 1);
  544. m_triangle_list.append(triangle);
  545. }
  546. } else if (primitive_type == PrimitiveType::TriangleStrip) {
  547. Triangle triangle;
  548. for (size_t i = 0; i < vertices.size() - 2; i++) {
  549. if (i % 2 == 0) {
  550. triangle.vertices[0] = vertices.at(i);
  551. triangle.vertices[1] = vertices.at(i + 1);
  552. triangle.vertices[2] = vertices.at(i + 2);
  553. } else {
  554. triangle.vertices[0] = vertices.at(i + 1);
  555. triangle.vertices[1] = vertices.at(i);
  556. triangle.vertices[2] = vertices.at(i + 2);
  557. }
  558. m_triangle_list.append(triangle);
  559. }
  560. }
  561. // Now let's transform each triangle and send that to the GPU
  562. auto const depth_half_range = (m_options.depth_max - m_options.depth_min) / 2;
  563. auto const depth_halfway = (m_options.depth_min + m_options.depth_max) / 2;
  564. for (auto& triangle : m_triangle_list) {
  565. // Transform vertices into eye coordinates using the model-view transform
  566. triangle.vertices[0].eye_coordinates = model_view_transform * triangle.vertices[0].position;
  567. triangle.vertices[1].eye_coordinates = model_view_transform * triangle.vertices[1].position;
  568. triangle.vertices[2].eye_coordinates = model_view_transform * triangle.vertices[2].position;
  569. // Transform eye coordinates into clip coordinates using the projection transform
  570. triangle.vertices[0].clip_coordinates = projection_transform * triangle.vertices[0].eye_coordinates;
  571. triangle.vertices[1].clip_coordinates = projection_transform * triangle.vertices[1].eye_coordinates;
  572. triangle.vertices[2].clip_coordinates = projection_transform * triangle.vertices[2].eye_coordinates;
  573. // At this point, we're in clip space
  574. // Here's where we do the clipping. This is a really crude implementation of the
  575. // https://learnopengl.com/Getting-started/Coordinate-Systems
  576. // "Note that if only a part of a primitive e.g. a triangle is outside the clipping volume OpenGL
  577. // will reconstruct the triangle as one or more triangles to fit inside the clipping range. "
  578. //
  579. // ALL VERTICES ARE DEFINED IN A CLOCKWISE ORDER
  580. // Okay, let's do some face culling first
  581. m_clipped_vertices.clear_with_capacity();
  582. m_clipped_vertices.append(triangle.vertices[0]);
  583. m_clipped_vertices.append(triangle.vertices[1]);
  584. m_clipped_vertices.append(triangle.vertices[2]);
  585. m_clipper.clip_triangle_against_frustum(m_clipped_vertices);
  586. if (m_clipped_vertices.size() < 3)
  587. continue;
  588. for (auto& vec : m_clipped_vertices) {
  589. // To normalized device coordinates (NDC)
  590. auto const one_over_w = 1 / vec.clip_coordinates.w();
  591. auto const ndc_coordinates = FloatVector4 {
  592. vec.clip_coordinates.x() * one_over_w,
  593. vec.clip_coordinates.y() * one_over_w,
  594. vec.clip_coordinates.z() * one_over_w,
  595. one_over_w,
  596. };
  597. // To window coordinates
  598. // FIXME: implement viewport functionality
  599. vec.window_coordinates = {
  600. scr_width / 2 + ndc_coordinates.x() * scr_width / 2,
  601. scr_height / 2 - ndc_coordinates.y() * scr_height / 2,
  602. depth_half_range * ndc_coordinates.z() + depth_halfway,
  603. ndc_coordinates.w(),
  604. };
  605. }
  606. Triangle tri;
  607. tri.vertices[0] = m_clipped_vertices[0];
  608. for (size_t i = 1; i < m_clipped_vertices.size() - 1; i++) {
  609. tri.vertices[1] = m_clipped_vertices[i];
  610. tri.vertices[2] = m_clipped_vertices[i + 1];
  611. m_processed_triangles.append(tri);
  612. }
  613. }
  614. for (auto& triangle : m_processed_triangles) {
  615. // Let's calculate the (signed) area of the triangle
  616. // https://cp-algorithms.com/geometry/oriented-triangle-area.html
  617. float dxAB = triangle.vertices[0].window_coordinates.x() - triangle.vertices[1].window_coordinates.x(); // A.x - B.x
  618. float dxBC = triangle.vertices[1].window_coordinates.x() - triangle.vertices[2].window_coordinates.x(); // B.X - C.x
  619. float dyAB = triangle.vertices[0].window_coordinates.y() - triangle.vertices[1].window_coordinates.y();
  620. float dyBC = triangle.vertices[1].window_coordinates.y() - triangle.vertices[2].window_coordinates.y();
  621. float area = (dxAB * dyBC) - (dxBC * dyAB);
  622. if (area == 0.0f)
  623. continue;
  624. if (m_options.enable_culling) {
  625. bool is_front = (m_options.front_face == WindingOrder::CounterClockwise ? area < 0 : area > 0);
  626. if (!is_front && m_options.cull_back)
  627. continue;
  628. if (is_front && m_options.cull_front)
  629. continue;
  630. }
  631. if (area > 0)
  632. swap(triangle.vertices[0], triangle.vertices[1]);
  633. // Transform normals
  634. triangle.vertices[0].normal = normal_transform * triangle.vertices[0].normal;
  635. triangle.vertices[1].normal = normal_transform * triangle.vertices[1].normal;
  636. triangle.vertices[2].normal = normal_transform * triangle.vertices[2].normal;
  637. if (m_options.normalization_enabled) {
  638. triangle.vertices[0].normal.normalize();
  639. triangle.vertices[1].normal.normalize();
  640. triangle.vertices[2].normal.normalize();
  641. }
  642. // Generate texture coordinates if at least one coordinate is enabled
  643. if (m_options.texcoord_generation_enabled_coordinates != TexCoordGenerationCoordinate::None) {
  644. generate_texture_coordinates(triangle.vertices[0], m_options);
  645. generate_texture_coordinates(triangle.vertices[1], m_options);
  646. generate_texture_coordinates(triangle.vertices[2], m_options);
  647. }
  648. // Apply texture transformation
  649. // FIXME: implement multi-texturing: texcoords should be stored per texture unit
  650. triangle.vertices[0].tex_coord = texture_transform * triangle.vertices[0].tex_coord;
  651. triangle.vertices[1].tex_coord = texture_transform * triangle.vertices[1].tex_coord;
  652. triangle.vertices[2].tex_coord = texture_transform * triangle.vertices[2].tex_coord;
  653. submit_triangle(triangle, enabled_texture_units);
  654. }
  655. }
  656. void Device::submit_triangle(const Triangle& triangle, Vector<size_t> const& enabled_texture_units)
  657. {
  658. rasterize_triangle(m_options, *m_render_target, *m_depth_buffer, triangle, [this, &enabled_texture_units](PixelQuad& quad) {
  659. quad.out_color = quad.vertex_color;
  660. for (size_t i : enabled_texture_units) {
  661. // FIXME: implement GL_TEXTURE_1D, GL_TEXTURE_3D and GL_TEXTURE_CUBE_MAP
  662. auto const& sampler = m_samplers[i];
  663. auto texel = sampler.sample_2d({ quad.uv.x(), quad.uv.y() });
  664. INCREASE_STATISTICS_COUNTER(g_num_sampler_calls, 1);
  665. // FIXME: Implement more blend modes
  666. switch (sampler.config().fixed_function_texture_env_mode) {
  667. case TextureEnvMode::Modulate:
  668. quad.out_color = quad.out_color * texel;
  669. break;
  670. case TextureEnvMode::Replace:
  671. quad.out_color = texel;
  672. break;
  673. case TextureEnvMode::Decal: {
  674. auto src_alpha = quad.out_color.w();
  675. quad.out_color.set_x(mix(quad.out_color.x(), texel.x(), src_alpha));
  676. quad.out_color.set_y(mix(quad.out_color.y(), texel.y(), src_alpha));
  677. quad.out_color.set_z(mix(quad.out_color.z(), texel.z(), src_alpha));
  678. break;
  679. }
  680. default:
  681. VERIFY_NOT_REACHED();
  682. }
  683. }
  684. // Calculate fog
  685. // Math from here: https://opengl-notes.readthedocs.io/en/latest/topics/texturing/aliasing.html
  686. // FIXME: exponential fog is not vectorized, we should add a SIMD exp function that calculates an approximation.
  687. if (m_options.fog_enabled) {
  688. auto factor = expand4(0.0f);
  689. switch (m_options.fog_mode) {
  690. case FogMode::Linear:
  691. factor = (m_options.fog_end - quad.fog_depth) / (m_options.fog_end - m_options.fog_start);
  692. break;
  693. case FogMode::Exp: {
  694. auto argument = -m_options.fog_density * quad.fog_depth;
  695. factor = exp(argument);
  696. } break;
  697. case FogMode::Exp2: {
  698. auto argument = m_options.fog_density * quad.fog_depth;
  699. argument *= -argument;
  700. factor = exp(argument);
  701. } break;
  702. default:
  703. VERIFY_NOT_REACHED();
  704. }
  705. // Mix texel's RGB with fog's RBG - leave alpha alone
  706. auto fog_color = expand4(m_options.fog_color);
  707. quad.out_color.set_x(mix(fog_color.x(), quad.out_color.x(), factor));
  708. quad.out_color.set_y(mix(fog_color.y(), quad.out_color.y(), factor));
  709. quad.out_color.set_z(mix(fog_color.z(), quad.out_color.z(), factor));
  710. }
  711. });
  712. }
  713. void Device::resize(const Gfx::IntSize& min_size)
  714. {
  715. wait_for_all_threads();
  716. m_render_target = Gfx::Bitmap::try_create(Gfx::BitmapFormat::BGRA8888, closest_multiple(min_size, 2)).release_value_but_fixme_should_propagate_errors();
  717. m_depth_buffer = adopt_own(*new DepthBuffer(m_render_target->size()));
  718. }
  719. void Device::clear_color(const FloatVector4& color)
  720. {
  721. wait_for_all_threads();
  722. uint8_t r = static_cast<uint8_t>(clamp(color.x(), 0.0f, 1.0f) * 255);
  723. uint8_t g = static_cast<uint8_t>(clamp(color.y(), 0.0f, 1.0f) * 255);
  724. uint8_t b = static_cast<uint8_t>(clamp(color.z(), 0.0f, 1.0f) * 255);
  725. uint8_t a = static_cast<uint8_t>(clamp(color.w(), 0.0f, 1.0f) * 255);
  726. auto const fill_color = Gfx::Color(r, g, b, a);
  727. if (m_options.scissor_enabled) {
  728. auto fill_rect = m_render_target->rect();
  729. fill_rect.intersect(scissor_box_to_window_coordinates(m_options.scissor_box, fill_rect));
  730. Gfx::Painter painter { *m_render_target };
  731. painter.fill_rect(fill_rect, fill_color);
  732. return;
  733. }
  734. m_render_target->fill(fill_color);
  735. }
  736. void Device::clear_depth(float depth)
  737. {
  738. wait_for_all_threads();
  739. if (m_options.scissor_enabled) {
  740. m_depth_buffer->clear(scissor_box_to_window_coordinates(m_options.scissor_box, m_render_target->rect()), depth);
  741. return;
  742. }
  743. m_depth_buffer->clear(depth);
  744. }
  745. void Device::blit(Gfx::Bitmap const& source, int x, int y)
  746. {
  747. wait_for_all_threads();
  748. INCREASE_STATISTICS_COUNTER(g_num_pixels, source.width() * source.height());
  749. INCREASE_STATISTICS_COUNTER(g_num_pixels_shaded, source.width() * source.height());
  750. Gfx::Painter painter { *m_render_target };
  751. painter.blit({ x, y }, source, source.rect(), 1.0f, true);
  752. }
  753. void Device::blit_to(Gfx::Bitmap& target)
  754. {
  755. wait_for_all_threads();
  756. Gfx::Painter painter { target };
  757. painter.blit({ 0, 0 }, *m_render_target, m_render_target->rect(), 1.0f, false);
  758. if constexpr (ENABLE_STATISTICS_OVERLAY)
  759. draw_statistics_overlay(target);
  760. }
  761. void Device::draw_statistics_overlay(Gfx::Bitmap& target)
  762. {
  763. static Core::ElapsedTimer timer;
  764. static String debug_string;
  765. static int frame_counter;
  766. frame_counter++;
  767. int milliseconds = 0;
  768. if (timer.is_valid())
  769. milliseconds = timer.elapsed();
  770. else
  771. timer.start();
  772. Gfx::Painter painter { target };
  773. if (milliseconds > 500) {
  774. if (g_num_pixels == 0)
  775. g_num_pixels = 1;
  776. int num_rendertarget_pixels = m_render_target->width() * m_render_target->height();
  777. StringBuilder builder;
  778. builder.append(String::formatted("Timings : {:.1}ms {:.1}FPS\n",
  779. static_cast<double>(milliseconds) / frame_counter,
  780. (milliseconds > 0) ? 1000.0 * frame_counter / milliseconds : 9999.0));
  781. builder.append(String::formatted("Triangles : {}\n", g_num_rasterized_triangles));
  782. builder.append(String::formatted("SIMD usage : {}%\n", g_num_quads > 0 ? g_num_pixels_shaded * 25 / g_num_quads : 0));
  783. builder.append(String::formatted("Pixels : {}, Shaded: {}%, Blended: {}%, Overdraw: {}%\n",
  784. g_num_pixels,
  785. g_num_pixels_shaded * 100 / g_num_pixels,
  786. g_num_pixels_blended * 100 / g_num_pixels_shaded,
  787. g_num_pixels_shaded * 100 / num_rendertarget_pixels - 100));
  788. builder.append(String::formatted("Sampler calls: {}\n", g_num_sampler_calls));
  789. debug_string = builder.to_string();
  790. frame_counter = 0;
  791. timer.start();
  792. }
  793. g_num_rasterized_triangles = 0;
  794. g_num_pixels = 0;
  795. g_num_pixels_shaded = 0;
  796. g_num_pixels_blended = 0;
  797. g_num_sampler_calls = 0;
  798. g_num_quads = 0;
  799. auto& font = Gfx::FontDatabase::default_fixed_width_font();
  800. for (int y = -1; y < 2; y++)
  801. for (int x = -1; x < 2; x++)
  802. if (x != 0 && y != 0)
  803. painter.draw_text(target.rect().translated(x + 2, y + 2), debug_string, font, Gfx::TextAlignment::TopLeft, Gfx::Color::Black);
  804. painter.draw_text(target.rect().translated(2, 2), debug_string, font, Gfx::TextAlignment::TopLeft, Gfx::Color::White);
  805. }
  806. void Device::wait_for_all_threads() const
  807. {
  808. // FIXME: Wait for all render threads to finish when multithreading is being implemented
  809. }
  810. void Device::set_options(const RasterizerOptions& options)
  811. {
  812. wait_for_all_threads();
  813. m_options = options;
  814. // FIXME: Recreate or reinitialize render threads here when multithreading is being implemented
  815. }
  816. Gfx::RGBA32 Device::get_backbuffer_pixel(int x, int y)
  817. {
  818. // FIXME: Reading individual pixels is very slow, rewrite this to transfer whole blocks
  819. if (x < 0 || y < 0 || x >= m_render_target->width() || y >= m_render_target->height())
  820. return 0;
  821. return m_render_target->scanline(y)[x];
  822. }
  823. float Device::get_depthbuffer_value(int x, int y)
  824. {
  825. // FIXME: Reading individual pixels is very slow, rewrite this to transfer whole blocks
  826. if (x < 0 || y < 0 || x >= m_render_target->width() || y >= m_render_target->height())
  827. return 1.0f;
  828. return m_depth_buffer->scanline(y)[x];
  829. }
  830. NonnullRefPtr<Image> Device::create_image(ImageFormat format, unsigned width, unsigned height, unsigned depth, unsigned levels, unsigned layers)
  831. {
  832. VERIFY(width > 0);
  833. VERIFY(height > 0);
  834. VERIFY(depth > 0);
  835. VERIFY(levels > 0);
  836. VERIFY(layers > 0);
  837. return adopt_ref(*new Image(format, width, height, depth, levels, layers));
  838. }
  839. void Device::set_sampler_config(unsigned sampler, SamplerConfig const& config)
  840. {
  841. m_samplers[sampler].set_config(config);
  842. }
  843. }