SoftwareRasterizer.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. /*
  2. * Copyright (c) 2021, Stephan Unverwerth <s.unverwerth@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "SoftwareRasterizer.h"
  7. #include <AK/Function.h>
  8. #include <LibGfx/Painter.h>
  9. #include <LibGfx/Vector2.h>
  10. #include <LibGfx/Vector3.h>
  11. namespace GL {
  12. using IntVector2 = Gfx::Vector2<int>;
  13. using IntVector3 = Gfx::Vector3<int>;
  14. static constexpr int RASTERIZER_BLOCK_SIZE = 16;
  15. constexpr static int edge_function(const IntVector2& a, const IntVector2& b, const IntVector2& c)
  16. {
  17. return ((c.x() - a.x()) * (b.y() - a.y()) - (c.y() - a.y()) * (b.x() - a.x()));
  18. }
  19. template<typename T>
  20. constexpr static T interpolate(const T& v0, const T& v1, const T& v2, const FloatVector3& barycentric_coords)
  21. {
  22. return v0 * barycentric_coords.x() + v1 * barycentric_coords.y() + v2 * barycentric_coords.z();
  23. }
  24. static Gfx::RGBA32 to_rgba32(const FloatVector4& v)
  25. {
  26. auto clamped = v.clamped(0, 1);
  27. u8 r = clamped.x() * 255;
  28. u8 g = clamped.y() * 255;
  29. u8 b = clamped.z() * 255;
  30. u8 a = clamped.w() * 255;
  31. return a << 24 | b << 16 | g << 8 | r;
  32. }
  33. static FloatVector4 to_vec4(Gfx::RGBA32 rgba)
  34. {
  35. return {
  36. (rgba & 0xff) / 255.0f,
  37. ((rgba >> 8) & 0xff) / 255.0f,
  38. ((rgba >> 16) & 0xff) / 255.0f,
  39. ((rgba >> 24) & 0xff) / 255.0f
  40. };
  41. }
  42. static constexpr void setup_blend_factors(GLenum mode, FloatVector4& constant, float& src_alpha, float& dst_alpha, float& src_color, float& dst_color)
  43. {
  44. constant = { 0.0f, 0.0f, 0.0f, 0.0f };
  45. src_alpha = 0;
  46. dst_alpha = 0;
  47. src_color = 0;
  48. dst_color = 0;
  49. switch (mode) {
  50. case GL_ZERO:
  51. break;
  52. case GL_ONE:
  53. constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  54. break;
  55. case GL_SRC_COLOR:
  56. src_color = 1;
  57. break;
  58. case GL_ONE_MINUS_SRC_COLOR:
  59. constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  60. src_color = -1;
  61. break;
  62. case GL_SRC_ALPHA:
  63. src_alpha = 1;
  64. break;
  65. case GL_ONE_MINUS_SRC_ALPHA:
  66. constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  67. src_alpha = -1;
  68. break;
  69. case GL_DST_ALPHA:
  70. dst_alpha = -1;
  71. break;
  72. case GL_ONE_MINUS_DST_ALPHA:
  73. constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  74. dst_alpha = -1;
  75. break;
  76. case GL_DST_COLOR:
  77. dst_color = 1;
  78. break;
  79. case GL_ONE_MINUS_DST_COLOR:
  80. constant = { 1.0f, 1.0f, 1.0f, 1.0f };
  81. dst_color = -1;
  82. break;
  83. case GL_SRC_ALPHA_SATURATE:
  84. // FIXME: How do we implement this?
  85. break;
  86. default:
  87. VERIFY_NOT_REACHED();
  88. }
  89. }
  90. template<typename PS>
  91. static void rasterize_triangle(const RasterizerOptions& options, Gfx::Bitmap& render_target, DepthBuffer& depth_buffer, const GLTriangle& triangle, PS pixel_shader)
  92. {
  93. // Since the algorithm is based on blocks of uniform size, we need
  94. // to ensure that our render_target size is actually a multiple of the block size
  95. VERIFY((render_target.width() % RASTERIZER_BLOCK_SIZE) == 0);
  96. VERIFY((render_target.height() % RASTERIZER_BLOCK_SIZE) == 0);
  97. // Calculate area of the triangle for later tests
  98. IntVector2 v0 { (int)triangle.vertices[0].x, (int)triangle.vertices[0].y };
  99. IntVector2 v1 { (int)triangle.vertices[1].x, (int)triangle.vertices[1].y };
  100. IntVector2 v2 { (int)triangle.vertices[2].x, (int)triangle.vertices[2].y };
  101. int area = edge_function(v0, v1, v2);
  102. if (area == 0)
  103. return;
  104. float one_over_area = 1.0f / area;
  105. FloatVector4 src_constant {};
  106. float src_factor_src_alpha = 0;
  107. float src_factor_dst_alpha = 0;
  108. float src_factor_src_color = 0;
  109. float src_factor_dst_color = 0;
  110. FloatVector4 dst_constant {};
  111. float dst_factor_src_alpha = 0;
  112. float dst_factor_dst_alpha = 0;
  113. float dst_factor_src_color = 0;
  114. float dst_factor_dst_color = 0;
  115. if (options.enable_blending) {
  116. setup_blend_factors(
  117. options.blend_source_factor,
  118. src_constant,
  119. src_factor_src_alpha,
  120. src_factor_dst_alpha,
  121. src_factor_src_color,
  122. src_factor_dst_color);
  123. setup_blend_factors(
  124. options.blend_source_factor,
  125. dst_constant,
  126. dst_factor_src_alpha,
  127. dst_factor_dst_alpha,
  128. dst_factor_src_color,
  129. dst_factor_dst_color);
  130. }
  131. // Obey top-left rule:
  132. // This sets up "zero" for later pixel coverage tests.
  133. // Depending on where on the triangle the edge is located
  134. // it is either tested against 0 or 1, effectively
  135. // turning "< 0" into "<= 0"
  136. IntVector3 zero { 1, 1, 1 };
  137. if (v1.y() > v0.y() || (v1.y() == v0.y() && v1.x() < v0.x()))
  138. zero.set_z(0);
  139. if (v2.y() > v1.y() || (v2.y() == v1.y() && v2.x() < v1.x()))
  140. zero.set_x(0);
  141. if (v0.y() > v2.y() || (v0.y() == v2.y() && v0.x() < v2.x()))
  142. zero.set_y(0);
  143. // This function calculates the 3 edge values for the pixel relative to the triangle.
  144. auto calculate_edge_values = [v0, v1, v2](const IntVector2& p) -> IntVector3 {
  145. return {
  146. edge_function(v1, v2, p),
  147. edge_function(v2, v0, p),
  148. edge_function(v0, v1, p),
  149. };
  150. };
  151. // This function tests whether a point as identified by its 3 edge values lies within the triangle
  152. auto test_point = [zero](const IntVector3& edges) -> bool {
  153. return edges.x() >= zero.x()
  154. && edges.y() >= zero.y()
  155. && edges.z() >= zero.z();
  156. };
  157. // Calculate block-based bounds
  158. // clang-format off
  159. const int bx0 = max(0, min(min(v0.x(), v1.x()), v2.x()) ) / RASTERIZER_BLOCK_SIZE;
  160. const int bx1 = min(render_target.width(), max(max(v0.x(), v1.x()), v2.x()) + RASTERIZER_BLOCK_SIZE - 1) / RASTERIZER_BLOCK_SIZE;
  161. const int by0 = max(0, min(min(v0.y(), v1.y()), v2.y()) ) / RASTERIZER_BLOCK_SIZE;
  162. const int by1 = min(render_target.height(), max(max(v0.y(), v1.y()), v2.y()) + RASTERIZER_BLOCK_SIZE - 1) / RASTERIZER_BLOCK_SIZE;
  163. // clang-format on
  164. static_assert(RASTERIZER_BLOCK_SIZE < sizeof(int) * 8, "RASTERIZER_BLOCK_SIZE must be smaller than the pixel_mask's width in bits");
  165. int pixel_mask[RASTERIZER_BLOCK_SIZE];
  166. FloatVector4 pixel_buffer[RASTERIZER_BLOCK_SIZE][RASTERIZER_BLOCK_SIZE];
  167. // Iterate over all blocks within the bounds of the triangle
  168. for (int by = by0; by < by1; by++) {
  169. for (int bx = bx0; bx < bx1; bx++) {
  170. // Edge values of the 4 block corners
  171. // clang-format off
  172. auto b0 = calculate_edge_values({ bx * RASTERIZER_BLOCK_SIZE, by * RASTERIZER_BLOCK_SIZE });
  173. auto b1 = calculate_edge_values({ bx * RASTERIZER_BLOCK_SIZE + RASTERIZER_BLOCK_SIZE, by * RASTERIZER_BLOCK_SIZE });
  174. auto b2 = calculate_edge_values({ bx * RASTERIZER_BLOCK_SIZE, by * RASTERIZER_BLOCK_SIZE + RASTERIZER_BLOCK_SIZE });
  175. auto b3 = calculate_edge_values({ bx * RASTERIZER_BLOCK_SIZE + RASTERIZER_BLOCK_SIZE, by * RASTERIZER_BLOCK_SIZE + RASTERIZER_BLOCK_SIZE });
  176. // clang-format on
  177. // If the whole block is outside any of the triangle edges we can discard it completely
  178. // We test this by and'ing the relevant edge function values together for all block corners
  179. // and checking if the negative sign bit is set for all of them
  180. if ((b0.x() & b1.x() & b2.x() & b3.x()) & 0x80000000)
  181. continue;
  182. if ((b0.y() & b1.y() & b2.y() & b3.y()) & 0x80000000)
  183. continue;
  184. if ((b0.z() & b1.z() & b2.z() & b3.z()) & 0x80000000)
  185. continue;
  186. // edge value derivatives
  187. auto dbdx = (b1 - b0) / RASTERIZER_BLOCK_SIZE;
  188. auto dbdy = (b2 - b0) / RASTERIZER_BLOCK_SIZE;
  189. // step edge value after each horizontal span: 1 down, BLOCK_SIZE left
  190. auto step_y = dbdy - dbdx * RASTERIZER_BLOCK_SIZE;
  191. int x0 = bx * RASTERIZER_BLOCK_SIZE;
  192. int y0 = by * RASTERIZER_BLOCK_SIZE;
  193. // Generate the coverage mask
  194. if (test_point(b0) && test_point(b1) && test_point(b2) && test_point(b3)) {
  195. // The block is fully contained within the triangle. Fill the mask with all 1s
  196. for (int y = 0; y < RASTERIZER_BLOCK_SIZE; y++) {
  197. pixel_mask[y] = -1;
  198. }
  199. } else {
  200. // The block overlaps at least one triangle edge.
  201. // We need to test coverage of every pixel within the block.
  202. auto coords = b0;
  203. for (int y = 0; y < RASTERIZER_BLOCK_SIZE; y++, coords += step_y) {
  204. pixel_mask[y] = 0;
  205. for (int x = 0; x < RASTERIZER_BLOCK_SIZE; x++, coords += dbdx) {
  206. if (test_point(coords))
  207. pixel_mask[y] |= 1 << x;
  208. }
  209. }
  210. }
  211. // AND the depth mask onto the coverage mask
  212. if (options.enable_depth_test) {
  213. int z_pass_count = 0;
  214. auto coords = b0;
  215. for (int y = 0; y < RASTERIZER_BLOCK_SIZE; y++, coords += step_y) {
  216. if (pixel_mask[y] == 0) {
  217. coords += dbdx * RASTERIZER_BLOCK_SIZE;
  218. continue;
  219. }
  220. auto* depth = &depth_buffer.scanline(y0 + y)[x0];
  221. for (int x = 0; x < RASTERIZER_BLOCK_SIZE; x++, coords += dbdx, depth++) {
  222. if (~pixel_mask[y] & (1 << x))
  223. continue;
  224. auto barycentric = FloatVector3(coords.x(), coords.y(), coords.z()) * one_over_area;
  225. float z = interpolate(triangle.vertices[0].z, triangle.vertices[1].z, triangle.vertices[2].z, barycentric);
  226. if (z >= *depth) {
  227. pixel_mask[y] ^= 1 << x;
  228. continue;
  229. }
  230. *depth = z;
  231. z_pass_count++;
  232. }
  233. }
  234. // Nice, no pixels passed the depth test -> block rejected by early z
  235. if (z_pass_count == 0)
  236. continue;
  237. }
  238. // Draw the pixels according to the previously generated mask
  239. auto coords = b0;
  240. for (int y = 0; y < RASTERIZER_BLOCK_SIZE; y++, coords += step_y) {
  241. if (pixel_mask[y] == 0) {
  242. coords += dbdx * RASTERIZER_BLOCK_SIZE;
  243. continue;
  244. }
  245. auto* pixel = pixel_buffer[y];
  246. for (int x = 0; x < RASTERIZER_BLOCK_SIZE; x++, coords += dbdx, pixel++) {
  247. if (~pixel_mask[y] & (1 << x))
  248. continue;
  249. // Perspective correct barycentric coordinates
  250. auto barycentric = FloatVector3(coords.x(), coords.y(), coords.z()) * one_over_area;
  251. float interpolated_reciprocal_w = interpolate(triangle.vertices[0].w, triangle.vertices[1].w, triangle.vertices[2].w, barycentric);
  252. float interpolated_w = 1 / interpolated_reciprocal_w;
  253. barycentric = barycentric * FloatVector3(triangle.vertices[0].w, triangle.vertices[1].w, triangle.vertices[2].w) * interpolated_w;
  254. // FIXME: make this more generic. We want to interpolate more than just color and uv
  255. FloatVector4 vertex_color;
  256. if (options.shade_smooth) {
  257. vertex_color = interpolate(
  258. FloatVector4(triangle.vertices[0].r, triangle.vertices[0].g, triangle.vertices[0].b, triangle.vertices[0].a),
  259. FloatVector4(triangle.vertices[1].r, triangle.vertices[1].g, triangle.vertices[1].b, triangle.vertices[1].a),
  260. FloatVector4(triangle.vertices[2].r, triangle.vertices[2].g, triangle.vertices[2].b, triangle.vertices[2].a),
  261. barycentric);
  262. } else {
  263. vertex_color = { triangle.vertices[0].r, triangle.vertices[0].g, triangle.vertices[0].b, triangle.vertices[0].a };
  264. }
  265. auto uv = interpolate(
  266. FloatVector2(triangle.vertices[0].u, triangle.vertices[0].v),
  267. FloatVector2(triangle.vertices[1].u, triangle.vertices[1].v),
  268. FloatVector2(triangle.vertices[2].u, triangle.vertices[2].v),
  269. barycentric);
  270. *pixel = pixel_shader(uv, vertex_color);
  271. }
  272. }
  273. if (options.enable_alpha_test && options.alpha_test_func != GL_ALWAYS) {
  274. // FIXME: I'm not sure if this is the right place to test this.
  275. // If we tested this right at the beginning of our rasterizer routine
  276. // we could skip a lot of work but the GL spec might disagree.
  277. if (options.alpha_test_func == GL_NEVER)
  278. continue;
  279. for (int y = 0; y < RASTERIZER_BLOCK_SIZE; y++) {
  280. auto src = pixel_buffer[y];
  281. for (int x = 0; x < RASTERIZER_BLOCK_SIZE; x++, src++) {
  282. if (~pixel_mask[y] & (1 << x))
  283. continue;
  284. bool passed = true;
  285. switch (options.alpha_test_func) {
  286. case GL_LESS:
  287. passed = src->w() < options.alpha_test_ref_value;
  288. break;
  289. case GL_EQUAL:
  290. passed = src->w() == options.alpha_test_ref_value;
  291. break;
  292. case GL_LEQUAL:
  293. passed = src->w() <= options.alpha_test_ref_value;
  294. break;
  295. case GL_GREATER:
  296. passed = src->w() > options.alpha_test_ref_value;
  297. break;
  298. case GL_NOTEQUAL:
  299. passed = src->w() != options.alpha_test_ref_value;
  300. break;
  301. case GL_GEQUAL:
  302. passed = src->w() >= options.alpha_test_ref_value;
  303. break;
  304. }
  305. if (!passed)
  306. pixel_mask[y] ^= (1 << x);
  307. }
  308. }
  309. }
  310. if (options.enable_blending) {
  311. // Blend color values from pixel_buffer into render_target
  312. for (int y = 0; y < RASTERIZER_BLOCK_SIZE; y++) {
  313. auto src = pixel_buffer[y];
  314. auto dst = &render_target.scanline(y + y0)[x0];
  315. for (int x = 0; x < RASTERIZER_BLOCK_SIZE; x++, src++, dst++) {
  316. if (~pixel_mask[y] & (1 << x))
  317. continue;
  318. auto float_dst = to_vec4(*dst);
  319. auto src_factor = src_constant
  320. + *src * src_factor_src_color
  321. + FloatVector4(src->w(), src->w(), src->w(), src->w()) * src_factor_src_alpha
  322. + float_dst * src_factor_dst_color
  323. + FloatVector4(float_dst.w(), float_dst.w(), float_dst.w(), float_dst.w()) * src_factor_dst_alpha;
  324. auto dst_factor = dst_constant
  325. + *src * dst_factor_src_color
  326. + FloatVector4(src->w(), src->w(), src->w(), src->w()) * dst_factor_src_alpha
  327. + float_dst * dst_factor_dst_color
  328. + FloatVector4(float_dst.w(), float_dst.w(), float_dst.w(), float_dst.w()) * dst_factor_dst_alpha;
  329. *dst = to_rgba32(*src * src_factor + float_dst * dst_factor);
  330. }
  331. }
  332. } else {
  333. // Copy color values from pixel_buffer into render_target
  334. for (int y = 0; y < RASTERIZER_BLOCK_SIZE; y++) {
  335. auto src = pixel_buffer[y];
  336. auto dst = &render_target.scanline(y + y0)[x0];
  337. for (int x = 0; x < RASTERIZER_BLOCK_SIZE; x++, src++, dst++) {
  338. if (~pixel_mask[y] & (1 << x))
  339. continue;
  340. *dst = to_rgba32(*src);
  341. }
  342. }
  343. }
  344. }
  345. }
  346. }
  347. static Gfx::IntSize closest_multiple(const Gfx::IntSize& min_size, size_t step)
  348. {
  349. int width = ((min_size.width() + step - 1) / step) * step;
  350. int height = ((min_size.height() + step - 1) / step) * step;
  351. return { width, height };
  352. }
  353. SoftwareRasterizer::SoftwareRasterizer(const Gfx::IntSize& min_size)
  354. : m_render_target { Gfx::Bitmap::create(Gfx::BitmapFormat::BGRA8888, closest_multiple(min_size, RASTERIZER_BLOCK_SIZE)) }
  355. , m_depth_buffer { adopt_own(*new DepthBuffer(closest_multiple(min_size, RASTERIZER_BLOCK_SIZE))) }
  356. {
  357. }
  358. void SoftwareRasterizer::submit_triangle(const GLTriangle& triangle, const Texture& texture)
  359. {
  360. rasterize_triangle(m_options, *m_render_target, *m_depth_buffer, triangle, [&texture](const FloatVector2& uv, const FloatVector4& color) -> FloatVector4 {
  361. // TODO: We'd do some kind of multitexturing/blending here
  362. // Construct a vector for the texel we want to sample
  363. FloatVector4 texel = texture.sample_texel(uv);
  364. return texel * color;
  365. });
  366. }
  367. void SoftwareRasterizer::resize(const Gfx::IntSize& min_size)
  368. {
  369. wait_for_all_threads();
  370. m_render_target = Gfx::Bitmap::create(Gfx::BitmapFormat::BGRA8888, closest_multiple(min_size, RASTERIZER_BLOCK_SIZE));
  371. m_depth_buffer = adopt_own(*new DepthBuffer(m_render_target->size()));
  372. }
  373. void SoftwareRasterizer::clear_color(const FloatVector4& color)
  374. {
  375. wait_for_all_threads();
  376. uint8_t r = static_cast<uint8_t>(clamp(color.x(), 0.0f, 1.0f) * 255);
  377. uint8_t g = static_cast<uint8_t>(clamp(color.y(), 0.0f, 1.0f) * 255);
  378. uint8_t b = static_cast<uint8_t>(clamp(color.z(), 0.0f, 1.0f) * 255);
  379. uint8_t a = static_cast<uint8_t>(clamp(color.w(), 0.0f, 1.0f) * 255);
  380. m_render_target->fill(Gfx::Color(r, g, b, a));
  381. }
  382. void SoftwareRasterizer::clear_depth(float depth)
  383. {
  384. wait_for_all_threads();
  385. m_depth_buffer->clear(depth);
  386. }
  387. void SoftwareRasterizer::blit_to(Gfx::Bitmap& target)
  388. {
  389. wait_for_all_threads();
  390. Gfx::Painter painter { target };
  391. painter.blit({ 0, 0 }, *m_render_target, m_render_target->rect(), 1.0f, false);
  392. }
  393. void SoftwareRasterizer::wait_for_all_threads() const
  394. {
  395. // FIXME: Wait for all render threads to finish when multithreading is being implemented
  396. }
  397. void SoftwareRasterizer::set_options(const RasterizerOptions& options)
  398. {
  399. wait_for_all_threads();
  400. m_options = options;
  401. // FIXME: Recreate or reinitialize render threads here when multithreading is being implemented
  402. }
  403. Gfx::RGBA32 SoftwareRasterizer::get_backbuffer_pixel(int x, int y)
  404. {
  405. // FIXME: Reading individual pixels is very slow, rewrite this to transfer whole blocks
  406. if (x < 0 || y < 0 || x >= m_render_target->width() || y >= m_render_target->height())
  407. return 0;
  408. return m_render_target->scanline(y)[x];
  409. }
  410. float SoftwareRasterizer::get_depthbuffer_value(int x, int y)
  411. {
  412. // FIXME: Reading individual pixels is very slow, rewrite this to transfer whole blocks
  413. if (x < 0 || y < 0 || x >= m_render_target->width() || y >= m_render_target->height())
  414. return 1.0f;
  415. return m_depth_buffer->scanline(y)[x];
  416. }
  417. }