SoftwareRasterizer.cpp 20 KB

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