Device.cpp 40 KB

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