Device.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  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 <LibGfx/Painter.h>
  9. #include <LibGfx/Vector2.h>
  10. #include <LibGfx/Vector3.h>
  11. #include <LibSoftGPU/Device.h>
  12. namespace SoftGPU {
  13. using IntVector2 = Gfx::Vector2<int>;
  14. using IntVector3 = Gfx::Vector3<int>;
  15. static constexpr int RASTERIZER_BLOCK_SIZE = 8;
  16. constexpr static int edge_function(const IntVector2& a, const IntVector2& b, const IntVector2& c)
  17. {
  18. return ((c.x() - a.x()) * (b.y() - a.y()) - (c.y() - a.y()) * (b.x() - a.x()));
  19. }
  20. template<typename T>
  21. constexpr static T interpolate(const T& v0, const T& v1, const T& v2, const FloatVector3& barycentric_coords)
  22. {
  23. return v0 * barycentric_coords.x() + v1 * barycentric_coords.y() + v2 * barycentric_coords.z();
  24. }
  25. template<typename T>
  26. constexpr static T mix(const T& x, const T& y, float interp)
  27. {
  28. return x * (1 - interp) + y * interp;
  29. }
  30. ALWAYS_INLINE constexpr static Gfx::RGBA32 to_rgba32(const FloatVector4& v)
  31. {
  32. auto clamped = v.clamped(0, 1);
  33. u8 r = clamped.x() * 255;
  34. u8 g = clamped.y() * 255;
  35. u8 b = clamped.z() * 255;
  36. u8 a = clamped.w() * 255;
  37. return a << 24 | r << 16 | g << 8 | b;
  38. }
  39. static FloatVector4 to_vec4(Gfx::RGBA32 rgba)
  40. {
  41. return {
  42. ((rgba >> 16) & 0xff) / 255.0f,
  43. ((rgba >> 8) & 0xff) / 255.0f,
  44. (rgba & 0xff) / 255.0f,
  45. ((rgba >> 24) & 0xff) / 255.0f
  46. };
  47. }
  48. static Gfx::IntRect scissor_box_to_window_coordinates(Gfx::IntRect const& scissor_box, Gfx::IntRect const& window_rect)
  49. {
  50. return scissor_box.translated(0, window_rect.height() - 2 * scissor_box.y() - scissor_box.height());
  51. }
  52. static constexpr void setup_blend_factors(BlendFactor mode, FloatVector4& constant, float& src_alpha, float& dst_alpha, float& src_color, float& dst_color)
  53. {
  54. constant = { 0.0f, 0.0f, 0.0f, 0.0f };
  55. src_alpha = 0;
  56. dst_alpha = 0;
  57. src_color = 0;
  58. dst_color = 0;
  59. switch (mode) {
  60. case BlendFactor::Zero:
  61. break;
  62. case BlendFactor::One:
  63. constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  64. break;
  65. case BlendFactor::SrcColor:
  66. src_color = 1;
  67. break;
  68. case BlendFactor::OneMinusSrcColor:
  69. constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  70. src_color = -1;
  71. break;
  72. case BlendFactor::SrcAlpha:
  73. src_alpha = 1;
  74. break;
  75. case BlendFactor::OneMinusSrcAlpha:
  76. constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  77. src_alpha = -1;
  78. break;
  79. case BlendFactor::DstAlpha:
  80. dst_alpha = 1;
  81. break;
  82. case BlendFactor::OneMinusDstAlpha:
  83. constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  84. dst_alpha = -1;
  85. break;
  86. case BlendFactor::DstColor:
  87. dst_color = 1;
  88. break;
  89. case BlendFactor::OneMinusDstColor:
  90. constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  91. dst_color = -1;
  92. break;
  93. case BlendFactor::SrcAlphaSaturate:
  94. // FIXME: How do we implement this?
  95. break;
  96. default:
  97. VERIFY_NOT_REACHED();
  98. }
  99. }
  100. template<typename PS>
  101. static void rasterize_triangle(const RasterizerOptions& options, Gfx::Bitmap& render_target, DepthBuffer& depth_buffer, const Triangle& triangle, PS pixel_shader)
  102. {
  103. // Since the algorithm is based on blocks of uniform size, we need
  104. // to ensure that our render_target size is actually a multiple of the block size
  105. VERIFY((render_target.width() % RASTERIZER_BLOCK_SIZE) == 0);
  106. VERIFY((render_target.height() % RASTERIZER_BLOCK_SIZE) == 0);
  107. // Return if alpha testing is a no-op
  108. if (options.enable_alpha_test && options.alpha_test_func == AlphaTestFunction::Never)
  109. return;
  110. // Calculate area of the triangle for later tests
  111. IntVector2 v0 { (int)triangle.vertices[0].position.x(), (int)triangle.vertices[0].position.y() };
  112. IntVector2 v1 { (int)triangle.vertices[1].position.x(), (int)triangle.vertices[1].position.y() };
  113. IntVector2 v2 { (int)triangle.vertices[2].position.x(), (int)triangle.vertices[2].position.y() };
  114. int area = edge_function(v0, v1, v2);
  115. if (area == 0)
  116. return;
  117. float one_over_area = 1.0f / area;
  118. FloatVector4 src_constant {};
  119. float src_factor_src_alpha = 0;
  120. float src_factor_dst_alpha = 0;
  121. float src_factor_src_color = 0;
  122. float src_factor_dst_color = 0;
  123. FloatVector4 dst_constant {};
  124. float dst_factor_src_alpha = 0;
  125. float dst_factor_dst_alpha = 0;
  126. float dst_factor_src_color = 0;
  127. float dst_factor_dst_color = 0;
  128. if (options.enable_blending) {
  129. setup_blend_factors(
  130. options.blend_source_factor,
  131. src_constant,
  132. src_factor_src_alpha,
  133. src_factor_dst_alpha,
  134. src_factor_src_color,
  135. src_factor_dst_color);
  136. setup_blend_factors(
  137. options.blend_destination_factor,
  138. dst_constant,
  139. dst_factor_src_alpha,
  140. dst_factor_dst_alpha,
  141. dst_factor_src_color,
  142. dst_factor_dst_color);
  143. }
  144. // Obey top-left rule:
  145. // This sets up "zero" for later pixel coverage tests.
  146. // Depending on where on the triangle the edge is located
  147. // it is either tested against 0 or 1, effectively
  148. // turning "< 0" into "<= 0"
  149. IntVector3 zero { 1, 1, 1 };
  150. if (v1.y() > v0.y() || (v1.y() == v0.y() && v1.x() < v0.x()))
  151. zero.set_z(0);
  152. if (v2.y() > v1.y() || (v2.y() == v1.y() && v2.x() < v1.x()))
  153. zero.set_x(0);
  154. if (v0.y() > v2.y() || (v0.y() == v2.y() && v0.x() < v2.x()))
  155. zero.set_y(0);
  156. // This function calculates the 3 edge values for the pixel relative to the triangle.
  157. auto calculate_edge_values = [v0, v1, v2](const IntVector2& p) -> IntVector3 {
  158. return {
  159. edge_function(v1, v2, p),
  160. edge_function(v2, v0, p),
  161. edge_function(v0, v1, p),
  162. };
  163. };
  164. // This function tests whether a point as identified by its 3 edge values lies within the triangle
  165. auto test_point = [zero](const IntVector3& edges) -> bool {
  166. return edges.x() >= zero.x()
  167. && edges.y() >= zero.y()
  168. && edges.z() >= zero.z();
  169. };
  170. // Calculate block-based bounds
  171. auto render_bounds = render_target.rect();
  172. if (options.scissor_enabled)
  173. render_bounds.intersect(scissor_box_to_window_coordinates(options.scissor_box, render_target.rect()));
  174. int const block_padding = RASTERIZER_BLOCK_SIZE - 1;
  175. // clang-format off
  176. int const bx0 = max(render_bounds.left(), min(min(v0.x(), v1.x()), v2.x())) / RASTERIZER_BLOCK_SIZE;
  177. int const bx1 = (min(render_bounds.right(), max(max(v0.x(), v1.x()), v2.x())) + block_padding) / RASTERIZER_BLOCK_SIZE;
  178. int const by0 = max(render_bounds.top(), min(min(v0.y(), v1.y()), v2.y())) / RASTERIZER_BLOCK_SIZE;
  179. int const by1 = (min(render_bounds.bottom(), max(max(v0.y(), v1.y()), v2.y())) + block_padding) / RASTERIZER_BLOCK_SIZE;
  180. // clang-format on
  181. u8 pixel_mask[RASTERIZER_BLOCK_SIZE];
  182. static_assert(RASTERIZER_BLOCK_SIZE <= sizeof(decltype(*pixel_mask)) * 8, "RASTERIZER_BLOCK_SIZE must be smaller than the pixel_mask's width in bits");
  183. FloatVector4 pixel_staging[RASTERIZER_BLOCK_SIZE][RASTERIZER_BLOCK_SIZE];
  184. float depth_staging[RASTERIZER_BLOCK_SIZE][RASTERIZER_BLOCK_SIZE];
  185. // FIXME: implement stencil testing
  186. // Iterate over all blocks within the bounds of the triangle
  187. for (int by = by0; by < by1; by++) {
  188. for (int bx = bx0; bx < bx1; bx++) {
  189. // Edge values of the 4 block corners
  190. // clang-format off
  191. auto b0 = calculate_edge_values({ bx * RASTERIZER_BLOCK_SIZE, by * RASTERIZER_BLOCK_SIZE });
  192. auto b1 = calculate_edge_values({ bx * RASTERIZER_BLOCK_SIZE + RASTERIZER_BLOCK_SIZE, by * RASTERIZER_BLOCK_SIZE });
  193. auto b2 = calculate_edge_values({ bx * RASTERIZER_BLOCK_SIZE, by * RASTERIZER_BLOCK_SIZE + RASTERIZER_BLOCK_SIZE });
  194. auto b3 = calculate_edge_values({ bx * RASTERIZER_BLOCK_SIZE + RASTERIZER_BLOCK_SIZE, by * RASTERIZER_BLOCK_SIZE + RASTERIZER_BLOCK_SIZE });
  195. // clang-format on
  196. // If the whole block is outside any of the triangle edges we can discard it completely
  197. // We test this by and'ing the relevant edge function values together for all block corners
  198. // and checking if the negative sign bit is set for all of them
  199. if ((b0.x() & b1.x() & b2.x() & b3.x()) & 0x80000000)
  200. continue;
  201. if ((b0.y() & b1.y() & b2.y() & b3.y()) & 0x80000000)
  202. continue;
  203. if ((b0.z() & b1.z() & b2.z() & b3.z()) & 0x80000000)
  204. continue;
  205. // edge value derivatives
  206. auto dbdx = (b1 - b0) / RASTERIZER_BLOCK_SIZE;
  207. auto dbdy = (b2 - b0) / RASTERIZER_BLOCK_SIZE;
  208. // step edge value after each horizontal span: 1 down, BLOCK_SIZE left
  209. auto step_y = dbdy - dbdx * RASTERIZER_BLOCK_SIZE;
  210. int x0 = bx * RASTERIZER_BLOCK_SIZE;
  211. int y0 = by * RASTERIZER_BLOCK_SIZE;
  212. // Generate the coverage mask
  213. if (!options.scissor_enabled && test_point(b0) && test_point(b1) && test_point(b2) && test_point(b3)) {
  214. // The block is fully contained within the triangle. Fill the mask with all 1s
  215. for (int y = 0; y < RASTERIZER_BLOCK_SIZE; y++)
  216. pixel_mask[y] = -1;
  217. } else {
  218. // The block overlaps at least one triangle edge.
  219. // We need to test coverage of every pixel within the block.
  220. auto coords = b0;
  221. for (int y = 0; y < RASTERIZER_BLOCK_SIZE; y++, coords += step_y) {
  222. pixel_mask[y] = 0;
  223. for (int x = 0; x < RASTERIZER_BLOCK_SIZE; x++, coords += dbdx) {
  224. if (test_point(coords) && (!options.scissor_enabled || render_bounds.contains(x0 + x, y0 + y)))
  225. pixel_mask[y] |= 1 << x;
  226. }
  227. }
  228. }
  229. // AND the depth mask onto the coverage mask
  230. if (options.enable_depth_test) {
  231. int z_pass_count = 0;
  232. auto coords = b0;
  233. for (int y = 0; y < RASTERIZER_BLOCK_SIZE; y++, coords += step_y) {
  234. if (pixel_mask[y] == 0) {
  235. coords += dbdx * RASTERIZER_BLOCK_SIZE;
  236. continue;
  237. }
  238. auto* depth = &depth_buffer.scanline(y0 + y)[x0];
  239. for (int x = 0; x < RASTERIZER_BLOCK_SIZE; x++, coords += dbdx, depth++) {
  240. if (~pixel_mask[y] & (1 << x))
  241. continue;
  242. auto barycentric = FloatVector3(coords.x(), coords.y(), coords.z()) * one_over_area;
  243. float z = interpolate(triangle.vertices[0].position.z(), triangle.vertices[1].position.z(), triangle.vertices[2].position.z(), barycentric);
  244. z = options.depth_min + (options.depth_max - options.depth_min) * (z + 1) / 2;
  245. // FIXME: Also apply depth_offset_factor which depends on the depth gradient
  246. z += options.depth_offset_constant * NumericLimits<float>::epsilon();
  247. bool pass = false;
  248. switch (options.depth_func) {
  249. case DepthTestFunction::Always:
  250. pass = true;
  251. break;
  252. case DepthTestFunction::Never:
  253. pass = false;
  254. break;
  255. case DepthTestFunction::Greater:
  256. pass = z > *depth;
  257. break;
  258. case DepthTestFunction::GreaterOrEqual:
  259. pass = z >= *depth;
  260. break;
  261. case DepthTestFunction::NotEqual:
  262. #ifdef __SSE__
  263. pass = z != *depth;
  264. #else
  265. pass = bit_cast<u32>(z) != bit_cast<u32>(*depth);
  266. #endif
  267. break;
  268. case DepthTestFunction::Equal:
  269. #ifdef __SSE__
  270. pass = z == *depth;
  271. #else
  272. //
  273. // This is an interesting quirk that occurs due to us using the x87 FPU when Serenity is
  274. // compiled for the i386 target. When we calculate our depth value to be stored in the buffer,
  275. // it is an 80-bit x87 floating point number, however, when stored into the DepthBuffer, this is
  276. // truncated to 32 bits. This 38 bit loss of precision means that when x87 `FCOMP` is eventually
  277. // used here the comparison fails.
  278. // This could be solved by using a `long double` for the depth buffer, however this would take
  279. // up significantly more space and is completely overkill for a depth buffer. As such, comparing
  280. // the first 32-bits of this depth value is "good enough" that if we get a hit on it being
  281. // equal, we can pretty much guarantee that it's actually equal.
  282. //
  283. pass = bit_cast<u32>(z) == bit_cast<u32>(*depth);
  284. #endif
  285. break;
  286. case DepthTestFunction::LessOrEqual:
  287. pass = z <= *depth;
  288. break;
  289. case DepthTestFunction::Less:
  290. pass = z < *depth;
  291. break;
  292. }
  293. if (!pass) {
  294. pixel_mask[y] ^= 1 << x;
  295. continue;
  296. }
  297. depth_staging[y][x] = z;
  298. z_pass_count++;
  299. }
  300. }
  301. // Nice, no pixels passed the depth test -> block rejected by early z
  302. if (z_pass_count == 0)
  303. continue;
  304. }
  305. // Draw the pixels according to the previously generated mask
  306. auto coords = b0;
  307. for (int y = 0; y < RASTERIZER_BLOCK_SIZE; y++, coords += step_y) {
  308. if (pixel_mask[y] == 0) {
  309. coords += dbdx * RASTERIZER_BLOCK_SIZE;
  310. continue;
  311. }
  312. auto* pixel = pixel_staging[y];
  313. for (int x = 0; x < RASTERIZER_BLOCK_SIZE; x++, coords += dbdx, pixel++) {
  314. if (~pixel_mask[y] & (1 << x))
  315. continue;
  316. // Perspective correct barycentric coordinates
  317. auto barycentric = FloatVector3(coords.x(), coords.y(), coords.z()) * one_over_area;
  318. float interpolated_reciprocal_w = interpolate(triangle.vertices[0].position.w(), triangle.vertices[1].position.w(), triangle.vertices[2].position.w(), barycentric);
  319. float interpolated_w = 1 / interpolated_reciprocal_w;
  320. barycentric = barycentric * FloatVector3(triangle.vertices[0].position.w(), triangle.vertices[1].position.w(), triangle.vertices[2].position.w()) * interpolated_w;
  321. // FIXME: make this more generic. We want to interpolate more than just color and uv
  322. FloatVector4 vertex_color;
  323. if (options.shade_smooth) {
  324. vertex_color = interpolate(
  325. triangle.vertices[0].color,
  326. triangle.vertices[1].color,
  327. triangle.vertices[2].color,
  328. barycentric);
  329. } else {
  330. vertex_color = triangle.vertices[0].color;
  331. }
  332. auto uv = interpolate(
  333. triangle.vertices[0].tex_coord,
  334. triangle.vertices[1].tex_coord,
  335. triangle.vertices[2].tex_coord,
  336. barycentric);
  337. // Calculate depth of fragment for fog
  338. float z = interpolate(triangle.vertices[0].position.z(), triangle.vertices[1].position.z(), triangle.vertices[2].position.z(), barycentric);
  339. z = options.depth_min + (options.depth_max - options.depth_min) * (z + 1) / 2;
  340. *pixel = pixel_shader(uv, vertex_color, z);
  341. }
  342. }
  343. if (options.enable_alpha_test && options.alpha_test_func != AlphaTestFunction::Always) {
  344. for (int y = 0; y < RASTERIZER_BLOCK_SIZE; y++) {
  345. if (pixel_mask[y] == 0)
  346. continue;
  347. auto src = pixel_staging[y];
  348. for (int x = 0; x < RASTERIZER_BLOCK_SIZE; x++, src++) {
  349. if (~pixel_mask[y] & (1 << x))
  350. continue;
  351. bool passed = true;
  352. switch (options.alpha_test_func) {
  353. case AlphaTestFunction::Less:
  354. passed = src->w() < options.alpha_test_ref_value;
  355. break;
  356. case AlphaTestFunction::Equal:
  357. passed = src->w() == options.alpha_test_ref_value;
  358. break;
  359. case AlphaTestFunction::LessOrEqual:
  360. passed = src->w() <= options.alpha_test_ref_value;
  361. break;
  362. case AlphaTestFunction::Greater:
  363. passed = src->w() > options.alpha_test_ref_value;
  364. break;
  365. case AlphaTestFunction::NotEqual:
  366. passed = src->w() != options.alpha_test_ref_value;
  367. break;
  368. case AlphaTestFunction::GreaterOrEqual:
  369. passed = src->w() >= options.alpha_test_ref_value;
  370. break;
  371. case AlphaTestFunction::Never:
  372. case AlphaTestFunction::Always:
  373. VERIFY_NOT_REACHED();
  374. }
  375. if (!passed)
  376. pixel_mask[y] ^= (1 << x);
  377. }
  378. }
  379. }
  380. // Write to depth buffer
  381. if (options.enable_depth_test && options.enable_depth_write) {
  382. for (int y = 0; y < RASTERIZER_BLOCK_SIZE; y++) {
  383. if (pixel_mask[y] == 0)
  384. continue;
  385. auto* depth = &depth_buffer.scanline(y0 + y)[x0];
  386. for (int x = 0; x < RASTERIZER_BLOCK_SIZE; x++, depth++) {
  387. if (~pixel_mask[y] & (1 << x))
  388. continue;
  389. *depth = depth_staging[y][x];
  390. }
  391. }
  392. }
  393. // We will not update the color buffer at all
  394. if (!options.color_mask || !options.enable_color_write)
  395. continue;
  396. if (options.enable_blending) {
  397. // Blend color values from pixel_staging into render_target
  398. for (int y = 0; y < RASTERIZER_BLOCK_SIZE; y++) {
  399. auto src = pixel_staging[y];
  400. auto dst = &render_target.scanline(y0 + y)[x0];
  401. for (int x = 0; x < RASTERIZER_BLOCK_SIZE; x++, src++, dst++) {
  402. if (~pixel_mask[y] & (1 << x))
  403. continue;
  404. auto float_dst = to_vec4(*dst);
  405. auto src_factor = src_constant
  406. + *src * src_factor_src_color
  407. + FloatVector4(src->w(), src->w(), src->w(), src->w()) * src_factor_src_alpha
  408. + float_dst * src_factor_dst_color
  409. + FloatVector4(float_dst.w(), float_dst.w(), float_dst.w(), float_dst.w()) * src_factor_dst_alpha;
  410. auto dst_factor = dst_constant
  411. + *src * dst_factor_src_color
  412. + FloatVector4(src->w(), src->w(), src->w(), src->w()) * dst_factor_src_alpha
  413. + float_dst * dst_factor_dst_color
  414. + FloatVector4(float_dst.w(), float_dst.w(), float_dst.w(), float_dst.w()) * dst_factor_dst_alpha;
  415. *dst = (*dst & ~options.color_mask) | (to_rgba32(*src * src_factor + float_dst * dst_factor) & options.color_mask);
  416. }
  417. }
  418. } else {
  419. // Copy color values from pixel_staging into render_target
  420. for (int y = 0; y < RASTERIZER_BLOCK_SIZE; y++) {
  421. auto src = pixel_staging[y];
  422. auto dst = &render_target.scanline(y + y0)[x0];
  423. for (int x = 0; x < RASTERIZER_BLOCK_SIZE; x++, src++, dst++) {
  424. if (~pixel_mask[y] & (1 << x))
  425. continue;
  426. *dst = (*dst & ~options.color_mask) | (to_rgba32(*src) & options.color_mask);
  427. }
  428. }
  429. }
  430. }
  431. }
  432. }
  433. static Gfx::IntSize closest_multiple(const Gfx::IntSize& min_size, size_t step)
  434. {
  435. int width = ((min_size.width() + step - 1) / step) * step;
  436. int height = ((min_size.height() + step - 1) / step) * step;
  437. return { width, height };
  438. }
  439. Device::Device(const Gfx::IntSize& min_size)
  440. : m_render_target { Gfx::Bitmap::try_create(Gfx::BitmapFormat::BGRA8888, closest_multiple(min_size, RASTERIZER_BLOCK_SIZE)).release_value_but_fixme_should_propagate_errors() }
  441. , m_depth_buffer { adopt_own(*new DepthBuffer(closest_multiple(min_size, RASTERIZER_BLOCK_SIZE))) }
  442. {
  443. m_options.scissor_box = m_render_target->rect();
  444. }
  445. DeviceInfo Device::info() const
  446. {
  447. return {
  448. .vendor_name = "SerenityOS",
  449. .device_name = "SoftGPU",
  450. .num_texture_units = num_samplers
  451. };
  452. }
  453. void Device::draw_primitives(PrimitiveType primitive_type, FloatMatrix4x4 const& transform, FloatMatrix3x3 const& normal_transform,
  454. FloatMatrix4x4 const& texture_transform, Vector<Vertex> const& vertices, Vector<size_t> const& enabled_texture_units)
  455. {
  456. // At this point, the user has effectively specified that they are done with defining the geometry
  457. // of what they want to draw. We now need to do a few things (https://www.khronos.org/opengl/wiki/Rendering_Pipeline_Overview):
  458. //
  459. // 1. Transform all of the vertices in the current vertex list into eye space by mulitplying the model-view matrix
  460. // 2. Transform all of the vertices from eye space into clip space by multiplying by the projection matrix
  461. // 3. If culling is enabled, we cull the desired faces (https://learnopengl.com/Advanced-OpenGL/Face-culling)
  462. // 4. Each element of the vertex is then divided by w to bring the positions into NDC (Normalized Device Coordinates)
  463. // 5. The vertices are sorted (for the rasteriser, how are we doing this? 3Dfx did this top to bottom in terms of vertex y coordinates)
  464. // 6. The vertices are then sent off to the rasteriser and drawn to the screen
  465. float scr_width = m_render_target->width();
  466. float scr_height = m_render_target->height();
  467. m_triangle_list.clear_with_capacity();
  468. m_processed_triangles.clear_with_capacity();
  469. // Let's construct some triangles
  470. if (primitive_type == PrimitiveType::Triangles) {
  471. Triangle triangle;
  472. for (size_t i = 0; i < vertices.size(); i += 3) {
  473. triangle.vertices[0] = vertices.at(i);
  474. triangle.vertices[1] = vertices.at(i + 1);
  475. triangle.vertices[2] = vertices.at(i + 2);
  476. m_triangle_list.append(triangle);
  477. }
  478. } else if (primitive_type == PrimitiveType::Quads) {
  479. // We need to construct two triangles to form the quad
  480. Triangle triangle;
  481. VERIFY(vertices.size() % 4 == 0);
  482. for (size_t i = 0; i < vertices.size(); i += 4) {
  483. // Triangle 1
  484. triangle.vertices[0] = vertices.at(i);
  485. triangle.vertices[1] = vertices.at(i + 1);
  486. triangle.vertices[2] = vertices.at(i + 2);
  487. m_triangle_list.append(triangle);
  488. // Triangle 2
  489. triangle.vertices[0] = vertices.at(i + 2);
  490. triangle.vertices[1] = vertices.at(i + 3);
  491. triangle.vertices[2] = vertices.at(i);
  492. m_triangle_list.append(triangle);
  493. }
  494. } else if (primitive_type == PrimitiveType::TriangleFan) {
  495. Triangle triangle;
  496. triangle.vertices[0] = vertices.at(0); // Root vertex is always the vertex defined first
  497. for (size_t i = 1; i < vertices.size() - 1; i++) // This is technically `n-2` triangles. We start at index 1
  498. {
  499. triangle.vertices[1] = vertices.at(i);
  500. triangle.vertices[2] = vertices.at(i + 1);
  501. m_triangle_list.append(triangle);
  502. }
  503. } else if (primitive_type == PrimitiveType::TriangleStrip) {
  504. Triangle triangle;
  505. for (size_t i = 0; i < vertices.size() - 2; i++) {
  506. if (i % 2 == 0) {
  507. triangle.vertices[0] = vertices.at(i);
  508. triangle.vertices[1] = vertices.at(i + 1);
  509. triangle.vertices[2] = vertices.at(i + 2);
  510. } else {
  511. triangle.vertices[0] = vertices.at(i + 1);
  512. triangle.vertices[1] = vertices.at(i);
  513. triangle.vertices[2] = vertices.at(i + 2);
  514. }
  515. m_triangle_list.append(triangle);
  516. }
  517. }
  518. // Now let's transform each triangle and send that to the GPU
  519. for (size_t i = 0; i < m_triangle_list.size(); i++) {
  520. Triangle& triangle = m_triangle_list.at(i);
  521. // First multiply the vertex by the MODELVIEW matrix and then the PROJECTION matrix
  522. triangle.vertices[0].position = transform * triangle.vertices[0].position;
  523. triangle.vertices[1].position = transform * triangle.vertices[1].position;
  524. triangle.vertices[2].position = transform * triangle.vertices[2].position;
  525. // Apply texture transformation
  526. // FIXME: implement multi-texturing: texcoords should be stored per texture unit
  527. triangle.vertices[0].tex_coord = texture_matrix * triangle.vertices[0].tex_coord;
  528. triangle.vertices[1].tex_coord = texture_matrix * triangle.vertices[1].tex_coord;
  529. triangle.vertices[2].tex_coord = texture_matrix * triangle.vertices[2].tex_coord;
  530. // At this point, we're in clip space
  531. // Here's where we do the clipping. This is a really crude implementation of the
  532. // https://learnopengl.com/Getting-started/Coordinate-Systems
  533. // "Note that if only a part of a primitive e.g. a triangle is outside the clipping volume OpenGL
  534. // will reconstruct the triangle as one or more triangles to fit inside the clipping range. "
  535. //
  536. // ALL VERTICES ARE DEFINED IN A CLOCKWISE ORDER
  537. // Okay, let's do some face culling first
  538. m_clipped_vertices.clear_with_capacity();
  539. m_clipped_vertices.append(triangle.vertices[0]);
  540. m_clipped_vertices.append(triangle.vertices[1]);
  541. m_clipped_vertices.append(triangle.vertices[2]);
  542. m_clipper.clip_triangle_against_frustum(m_clipped_vertices);
  543. if (m_clipped_vertices.size() < 3)
  544. continue;
  545. for (auto& vec : m_clipped_vertices) {
  546. // perspective divide
  547. float w = vec.position.w();
  548. vec.position.set_x(vec.position.x() / w);
  549. vec.position.set_y(vec.position.y() / w);
  550. vec.position.set_z(vec.position.z() / w);
  551. vec.position.set_w(1 / w);
  552. // to screen space
  553. vec.position.set_x(scr_width / 2 + vec.position.x() * scr_width / 2);
  554. vec.position.set_y(scr_height / 2 - vec.position.y() * scr_height / 2);
  555. }
  556. Triangle tri;
  557. tri.vertices[0] = m_clipped_vertices[0];
  558. for (size_t i = 1; i < m_clipped_vertices.size() - 1; i++) {
  559. tri.vertices[1] = m_clipped_vertices[i];
  560. tri.vertices[2] = m_clipped_vertices[i + 1];
  561. m_processed_triangles.append(tri);
  562. }
  563. }
  564. for (size_t i = 0; i < m_processed_triangles.size(); i++) {
  565. Triangle& triangle = m_processed_triangles.at(i);
  566. // Let's calculate the (signed) area of the triangle
  567. // https://cp-algorithms.com/geometry/oriented-triangle-area.html
  568. float dxAB = triangle.vertices[0].position.x() - triangle.vertices[1].position.x(); // A.x - B.x
  569. float dxBC = triangle.vertices[1].position.x() - triangle.vertices[2].position.x(); // B.X - C.x
  570. float dyAB = triangle.vertices[0].position.y() - triangle.vertices[1].position.y();
  571. float dyBC = triangle.vertices[1].position.y() - triangle.vertices[2].position.y();
  572. float area = (dxAB * dyBC) - (dxBC * dyAB);
  573. if (area == 0.0f)
  574. continue;
  575. if (m_options.enable_culling) {
  576. bool is_front = (m_options.front_face == WindingOrder::CounterClockwise ? area < 0 : area > 0);
  577. if (!is_front && m_options.cull_back)
  578. continue;
  579. if (is_front && m_options.cull_front)
  580. continue;
  581. }
  582. if (area > 0)
  583. swap(triangle.vertices[0], triangle.vertices[1]);
  584. // Transform normals
  585. triangle.vertices[0].normal = normal_transform * triangle.vertices[0].normal;
  586. triangle.vertices[1].normal = normal_transform * triangle.vertices[1].normal;
  587. triangle.vertices[2].normal = normal_transform * triangle.vertices[2].normal;
  588. if (m_options.normalization_enabled) {
  589. triangle.vertices[0].normal.normalize();
  590. triangle.vertices[1].normal.normalize();
  591. triangle.vertices[2].normal.normalize();
  592. }
  593. submit_triangle(triangle, enabled_texture_units);
  594. }
  595. }
  596. void Device::submit_triangle(const Triangle& triangle, Vector<size_t> const& enabled_texture_units)
  597. {
  598. rasterize_triangle(m_options, *m_render_target, *m_depth_buffer, triangle, [this, &enabled_texture_units](FloatVector4 const& uv, FloatVector4 const& color, float z) -> FloatVector4 {
  599. FloatVector4 fragment = color;
  600. for (size_t i : enabled_texture_units) {
  601. // FIXME: implement GL_TEXTURE_1D, GL_TEXTURE_3D and GL_TEXTURE_CUBE_MAP
  602. auto const& sampler = m_samplers[i];
  603. FloatVector4 texel = sampler.sample_2d({ uv.x(), uv.y() });
  604. // FIXME: Implement more blend modes
  605. switch (sampler.config().fixed_function_texture_env_mode) {
  606. case TextureEnvMode::Modulate:
  607. fragment = fragment * texel;
  608. break;
  609. case TextureEnvMode::Replace:
  610. fragment = texel;
  611. break;
  612. case TextureEnvMode::Decal: {
  613. float src_alpha = fragment.w();
  614. float one_minus_src_alpha = 1 - src_alpha;
  615. fragment.set_x(texel.x() * src_alpha + fragment.x() * one_minus_src_alpha);
  616. fragment.set_y(texel.y() * src_alpha + fragment.y() * one_minus_src_alpha);
  617. fragment.set_z(texel.z() * src_alpha + fragment.z() * one_minus_src_alpha);
  618. break;
  619. }
  620. default:
  621. VERIFY_NOT_REACHED();
  622. }
  623. }
  624. // Calculate fog
  625. // Math from here: https://opengl-notes.readthedocs.io/en/latest/topics/texturing/aliasing.html
  626. if (m_options.fog_enabled) {
  627. float factor = 0.0f;
  628. switch (m_options.fog_mode) {
  629. case FogMode::Linear:
  630. factor = (m_options.fog_end - z) / (m_options.fog_end - m_options.fog_start);
  631. break;
  632. case FogMode::Exp:
  633. factor = exp(-((m_options.fog_density * z)));
  634. break;
  635. case FogMode::Exp2:
  636. factor = exp(-((m_options.fog_density * z) * (m_options.fog_density * z)));
  637. break;
  638. default:
  639. VERIFY_NOT_REACHED();
  640. }
  641. // Mix texel's RGB with fog's RBG - leave alpha alone
  642. fragment.set_x(mix(m_options.fog_color.x(), fragment.x(), factor));
  643. fragment.set_y(mix(m_options.fog_color.y(), fragment.y(), factor));
  644. fragment.set_z(mix(m_options.fog_color.z(), fragment.z(), factor));
  645. }
  646. return fragment;
  647. });
  648. }
  649. void Device::resize(const Gfx::IntSize& min_size)
  650. {
  651. wait_for_all_threads();
  652. m_render_target = Gfx::Bitmap::try_create(Gfx::BitmapFormat::BGRA8888, closest_multiple(min_size, RASTERIZER_BLOCK_SIZE)).release_value_but_fixme_should_propagate_errors();
  653. m_depth_buffer = adopt_own(*new DepthBuffer(m_render_target->size()));
  654. }
  655. void Device::clear_color(const FloatVector4& color)
  656. {
  657. wait_for_all_threads();
  658. uint8_t r = static_cast<uint8_t>(clamp(color.x(), 0.0f, 1.0f) * 255);
  659. uint8_t g = static_cast<uint8_t>(clamp(color.y(), 0.0f, 1.0f) * 255);
  660. uint8_t b = static_cast<uint8_t>(clamp(color.z(), 0.0f, 1.0f) * 255);
  661. uint8_t a = static_cast<uint8_t>(clamp(color.w(), 0.0f, 1.0f) * 255);
  662. auto const fill_color = Gfx::Color(r, g, b, a);
  663. if (m_options.scissor_enabled) {
  664. auto fill_rect = m_render_target->rect();
  665. fill_rect.intersect(scissor_box_to_window_coordinates(m_options.scissor_box, fill_rect));
  666. Gfx::Painter painter { *m_render_target };
  667. painter.fill_rect(fill_rect, fill_color);
  668. return;
  669. }
  670. m_render_target->fill(fill_color);
  671. }
  672. void Device::clear_depth(float depth)
  673. {
  674. wait_for_all_threads();
  675. if (m_options.scissor_enabled) {
  676. m_depth_buffer->clear(scissor_box_to_window_coordinates(m_options.scissor_box, m_render_target->rect()), depth);
  677. return;
  678. }
  679. m_depth_buffer->clear(depth);
  680. }
  681. void Device::blit(Gfx::Bitmap const& source, int x, int y)
  682. {
  683. wait_for_all_threads();
  684. Gfx::Painter painter { *m_render_target };
  685. painter.blit({ x, y }, source, source.rect(), 1.0f, true);
  686. }
  687. void Device::blit_to(Gfx::Bitmap& target)
  688. {
  689. wait_for_all_threads();
  690. Gfx::Painter painter { target };
  691. painter.blit({ 0, 0 }, *m_render_target, m_render_target->rect(), 1.0f, false);
  692. }
  693. void Device::wait_for_all_threads() const
  694. {
  695. // FIXME: Wait for all render threads to finish when multithreading is being implemented
  696. }
  697. void Device::set_options(const RasterizerOptions& options)
  698. {
  699. wait_for_all_threads();
  700. m_options = options;
  701. // FIXME: Recreate or reinitialize render threads here when multithreading is being implemented
  702. }
  703. Gfx::RGBA32 Device::get_backbuffer_pixel(int x, int y)
  704. {
  705. // FIXME: Reading individual pixels is very slow, rewrite this to transfer whole blocks
  706. if (x < 0 || y < 0 || x >= m_render_target->width() || y >= m_render_target->height())
  707. return 0;
  708. return m_render_target->scanline(y)[x];
  709. }
  710. float Device::get_depthbuffer_value(int x, int y)
  711. {
  712. // FIXME: Reading individual pixels is very slow, rewrite this to transfer whole blocks
  713. if (x < 0 || y < 0 || x >= m_render_target->width() || y >= m_render_target->height())
  714. return 1.0f;
  715. return m_depth_buffer->scanline(y)[x];
  716. }
  717. NonnullRefPtr<Image> Device::create_image(ImageFormat format, unsigned width, unsigned height, unsigned depth, unsigned levels, unsigned layers)
  718. {
  719. VERIFY(width > 0);
  720. VERIFY(height > 0);
  721. VERIFY(depth > 0);
  722. VERIFY(levels > 0);
  723. VERIFY(layers > 0);
  724. return adopt_ref(*new Image(format, width, height, depth, levels, layers));
  725. }
  726. void Device::set_sampler_config(unsigned sampler, SamplerConfig const& config)
  727. {
  728. m_samplers[sampler].set_config(config);
  729. }
  730. }