SoftwareRasterizer.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  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 | r << 16 | g << 8 | b;
  32. }
  33. static FloatVector4 to_vec4(Gfx::RGBA32 rgba)
  34. {
  35. return {
  36. ((rgba >> 16) & 0xff) / 255.0f,
  37. ((rgba >> 8) & 0xff) / 255.0f,
  38. (rgba & 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_destination_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. z = options.depth_min + (options.depth_max - options.depth_min) * (z + 1) / 2;
  227. if (z >= *depth) {
  228. pixel_mask[y] ^= 1 << x;
  229. continue;
  230. }
  231. if (options.enable_depth_write)
  232. *depth = z;
  233. z_pass_count++;
  234. }
  235. }
  236. // Nice, no pixels passed the depth test -> block rejected by early z
  237. if (z_pass_count == 0)
  238. continue;
  239. }
  240. // Draw the pixels according to the previously generated mask
  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* pixel = pixel_buffer[y];
  248. for (int x = 0; x < RASTERIZER_BLOCK_SIZE; x++, coords += dbdx, pixel++) {
  249. if (~pixel_mask[y] & (1 << x))
  250. continue;
  251. // Perspective correct barycentric coordinates
  252. auto barycentric = FloatVector3(coords.x(), coords.y(), coords.z()) * one_over_area;
  253. float interpolated_reciprocal_w = interpolate(triangle.vertices[0].w, triangle.vertices[1].w, triangle.vertices[2].w, barycentric);
  254. float interpolated_w = 1 / interpolated_reciprocal_w;
  255. barycentric = barycentric * FloatVector3(triangle.vertices[0].w, triangle.vertices[1].w, triangle.vertices[2].w) * interpolated_w;
  256. // FIXME: make this more generic. We want to interpolate more than just color and uv
  257. FloatVector4 vertex_color;
  258. if (options.shade_smooth) {
  259. vertex_color = interpolate(
  260. FloatVector4(triangle.vertices[0].r, triangle.vertices[0].g, triangle.vertices[0].b, triangle.vertices[0].a),
  261. FloatVector4(triangle.vertices[1].r, triangle.vertices[1].g, triangle.vertices[1].b, triangle.vertices[1].a),
  262. FloatVector4(triangle.vertices[2].r, triangle.vertices[2].g, triangle.vertices[2].b, triangle.vertices[2].a),
  263. barycentric);
  264. } else {
  265. vertex_color = { triangle.vertices[0].r, triangle.vertices[0].g, triangle.vertices[0].b, triangle.vertices[0].a };
  266. }
  267. auto uv = interpolate(
  268. FloatVector2(triangle.vertices[0].u, triangle.vertices[0].v),
  269. FloatVector2(triangle.vertices[1].u, triangle.vertices[1].v),
  270. FloatVector2(triangle.vertices[2].u, triangle.vertices[2].v),
  271. barycentric);
  272. *pixel = pixel_shader(uv, vertex_color);
  273. }
  274. }
  275. if (options.enable_alpha_test && options.alpha_test_func != GL_ALWAYS) {
  276. // FIXME: I'm not sure if this is the right place to test this.
  277. // If we tested this right at the beginning of our rasterizer routine
  278. // we could skip a lot of work but the GL spec might disagree.
  279. if (options.alpha_test_func == GL_NEVER)
  280. continue;
  281. for (int y = 0; y < RASTERIZER_BLOCK_SIZE; y++) {
  282. auto src = pixel_buffer[y];
  283. for (int x = 0; x < RASTERIZER_BLOCK_SIZE; x++, src++) {
  284. if (~pixel_mask[y] & (1 << x))
  285. continue;
  286. bool passed = true;
  287. switch (options.alpha_test_func) {
  288. case GL_LESS:
  289. passed = src->w() < options.alpha_test_ref_value;
  290. break;
  291. case GL_EQUAL:
  292. passed = src->w() == options.alpha_test_ref_value;
  293. break;
  294. case GL_LEQUAL:
  295. passed = src->w() <= options.alpha_test_ref_value;
  296. break;
  297. case GL_GREATER:
  298. passed = src->w() > options.alpha_test_ref_value;
  299. break;
  300. case GL_NOTEQUAL:
  301. passed = src->w() != options.alpha_test_ref_value;
  302. break;
  303. case GL_GEQUAL:
  304. passed = src->w() >= options.alpha_test_ref_value;
  305. break;
  306. }
  307. if (!passed)
  308. pixel_mask[y] ^= (1 << x);
  309. }
  310. }
  311. }
  312. if (options.enable_blending) {
  313. // Blend color values from pixel_buffer into render_target
  314. for (int y = 0; y < RASTERIZER_BLOCK_SIZE; y++) {
  315. auto src = pixel_buffer[y];
  316. auto dst = &render_target.scanline(y + y0)[x0];
  317. for (int x = 0; x < RASTERIZER_BLOCK_SIZE; x++, src++, dst++) {
  318. if (~pixel_mask[y] & (1 << x))
  319. continue;
  320. auto float_dst = to_vec4(*dst);
  321. auto src_factor = src_constant
  322. + *src * src_factor_src_color
  323. + FloatVector4(src->w(), src->w(), src->w(), src->w()) * src_factor_src_alpha
  324. + float_dst * src_factor_dst_color
  325. + FloatVector4(float_dst.w(), float_dst.w(), float_dst.w(), float_dst.w()) * src_factor_dst_alpha;
  326. auto dst_factor = dst_constant
  327. + *src * dst_factor_src_color
  328. + FloatVector4(src->w(), src->w(), src->w(), src->w()) * dst_factor_src_alpha
  329. + float_dst * dst_factor_dst_color
  330. + FloatVector4(float_dst.w(), float_dst.w(), float_dst.w(), float_dst.w()) * dst_factor_dst_alpha;
  331. *dst = (*dst & ~options.color_mask) | (to_rgba32(*src * src_factor + float_dst * dst_factor) & options.color_mask);
  332. }
  333. }
  334. } else {
  335. // Copy color values from pixel_buffer into render_target
  336. for (int y = 0; y < RASTERIZER_BLOCK_SIZE; y++) {
  337. auto src = pixel_buffer[y];
  338. auto dst = &render_target.scanline(y + y0)[x0];
  339. for (int x = 0; x < RASTERIZER_BLOCK_SIZE; x++, src++, dst++) {
  340. if (~pixel_mask[y] & (1 << x))
  341. continue;
  342. *dst = (*dst & ~options.color_mask) | (to_rgba32(*src) & options.color_mask);
  343. }
  344. }
  345. }
  346. }
  347. }
  348. }
  349. static Gfx::IntSize closest_multiple(const Gfx::IntSize& min_size, size_t step)
  350. {
  351. int width = ((min_size.width() + step - 1) / step) * step;
  352. int height = ((min_size.height() + step - 1) / step) * step;
  353. return { width, height };
  354. }
  355. SoftwareRasterizer::SoftwareRasterizer(const Gfx::IntSize& min_size)
  356. : m_render_target { Gfx::Bitmap::try_create(Gfx::BitmapFormat::BGRA8888, closest_multiple(min_size, RASTERIZER_BLOCK_SIZE)) }
  357. , m_depth_buffer { adopt_own(*new DepthBuffer(closest_multiple(min_size, RASTERIZER_BLOCK_SIZE))) }
  358. {
  359. }
  360. void SoftwareRasterizer::submit_triangle(const GLTriangle& triangle)
  361. {
  362. rasterize_triangle(m_options, *m_render_target, *m_depth_buffer, triangle, [](const FloatVector2&, const FloatVector4& color) -> FloatVector4 {
  363. return color;
  364. });
  365. }
  366. void SoftwareRasterizer::submit_triangle(const GLTriangle& triangle, const Array<TextureUnit, 32>& texture_units)
  367. {
  368. rasterize_triangle(m_options, *m_render_target, *m_depth_buffer, triangle, [&texture_units](const FloatVector2& uv, const FloatVector4& color) -> FloatVector4 {
  369. // TODO: We'd do some kind of multitexturing/blending here
  370. // Construct a vector for the texel we want to sample
  371. FloatVector4 texel = color;
  372. for (const auto& texture_unit : texture_units) {
  373. // No texture is bound to this texture unit
  374. if (!texture_unit.is_bound())
  375. continue;
  376. // FIXME: Don't assume Texture2D, _and_ work out how we blend/do multitexturing properly.....
  377. texel = texel * static_ptr_cast<Texture2D>(texture_unit.bound_texture())->sampler().sample(uv);
  378. }
  379. return texel;
  380. });
  381. }
  382. void SoftwareRasterizer::resize(const Gfx::IntSize& min_size)
  383. {
  384. wait_for_all_threads();
  385. m_render_target = Gfx::Bitmap::try_create(Gfx::BitmapFormat::BGRA8888, closest_multiple(min_size, RASTERIZER_BLOCK_SIZE));
  386. m_depth_buffer = adopt_own(*new DepthBuffer(m_render_target->size()));
  387. }
  388. void SoftwareRasterizer::clear_color(const FloatVector4& color)
  389. {
  390. wait_for_all_threads();
  391. uint8_t r = static_cast<uint8_t>(clamp(color.x(), 0.0f, 1.0f) * 255);
  392. uint8_t g = static_cast<uint8_t>(clamp(color.y(), 0.0f, 1.0f) * 255);
  393. uint8_t b = static_cast<uint8_t>(clamp(color.z(), 0.0f, 1.0f) * 255);
  394. uint8_t a = static_cast<uint8_t>(clamp(color.w(), 0.0f, 1.0f) * 255);
  395. m_render_target->fill(Gfx::Color(r, g, b, a));
  396. }
  397. void SoftwareRasterizer::clear_depth(float depth)
  398. {
  399. wait_for_all_threads();
  400. m_depth_buffer->clear(depth);
  401. }
  402. void SoftwareRasterizer::blit_to(Gfx::Bitmap& target)
  403. {
  404. wait_for_all_threads();
  405. Gfx::Painter painter { target };
  406. painter.blit({ 0, 0 }, *m_render_target, m_render_target->rect(), 1.0f, false);
  407. }
  408. void SoftwareRasterizer::wait_for_all_threads() const
  409. {
  410. // FIXME: Wait for all render threads to finish when multithreading is being implemented
  411. }
  412. void SoftwareRasterizer::set_options(const RasterizerOptions& options)
  413. {
  414. wait_for_all_threads();
  415. m_options = options;
  416. // FIXME: Recreate or reinitialize render threads here when multithreading is being implemented
  417. }
  418. Gfx::RGBA32 SoftwareRasterizer::get_backbuffer_pixel(int x, int y)
  419. {
  420. // FIXME: Reading individual pixels is very slow, rewrite this to transfer whole blocks
  421. if (x < 0 || y < 0 || x >= m_render_target->width() || y >= m_render_target->height())
  422. return 0;
  423. return m_render_target->scanline(y)[x];
  424. }
  425. float SoftwareRasterizer::get_depthbuffer_value(int x, int y)
  426. {
  427. // FIXME: Reading individual pixels is very slow, rewrite this to transfer whole blocks
  428. if (x < 0 || y < 0 || x >= m_render_target->width() || y >= m_render_target->height())
  429. return 1.0f;
  430. return m_depth_buffer->scanline(y)[x];
  431. }
  432. }